User.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. using System.Linq;
  7. using System.Text.Json.Serialization;
  8. using Jellyfin.Data.Enums;
  9. using Jellyfin.Data.Interfaces;
  10. namespace Jellyfin.Data.Entities
  11. {
  12. /// <summary>
  13. /// An entity representing a user.
  14. /// </summary>
  15. public class User : IHasPermissions, IHasConcurrencyToken
  16. {
  17. /// <summary>
  18. /// The values being delimited here are Guids, so commas work as they do not appear in Guids.
  19. /// </summary>
  20. private const char Delimiter = ',';
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="User"/> class.
  23. /// Public constructor with required data.
  24. /// </summary>
  25. /// <param name="username">The username for the new user.</param>
  26. /// <param name="authenticationProviderId">The Id of the user's authentication provider.</param>
  27. /// <param name="passwordResetProviderId">The Id of the user's password reset provider.</param>
  28. public User(string username, string authenticationProviderId, string passwordResetProviderId)
  29. {
  30. ArgumentException.ThrowIfNullOrEmpty(username);
  31. ArgumentException.ThrowIfNullOrEmpty(authenticationProviderId);
  32. ArgumentException.ThrowIfNullOrEmpty(passwordResetProviderId);
  33. Username = username;
  34. AuthenticationProviderId = authenticationProviderId;
  35. PasswordResetProviderId = passwordResetProviderId;
  36. AccessSchedules = new HashSet<AccessSchedule>();
  37. DisplayPreferences = new HashSet<DisplayPreferences>();
  38. ItemDisplayPreferences = new HashSet<ItemDisplayPreferences>();
  39. // Groups = new HashSet<Group>();
  40. Permissions = new HashSet<Permission>();
  41. Preferences = new HashSet<Preference>();
  42. // ProviderMappings = new HashSet<ProviderMapping>();
  43. // Set default values
  44. Id = Guid.NewGuid();
  45. InvalidLoginAttemptCount = 0;
  46. EnableUserPreferenceAccess = true;
  47. MustUpdatePassword = false;
  48. DisplayMissingEpisodes = false;
  49. DisplayCollectionsView = false;
  50. HidePlayedInLatest = true;
  51. RememberAudioSelections = true;
  52. RememberSubtitleSelections = true;
  53. EnableNextEpisodeAutoPlay = true;
  54. EnableAutoLogin = false;
  55. PlayDefaultAudioTrack = true;
  56. SubtitleMode = SubtitlePlaybackMode.Default;
  57. SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups;
  58. }
  59. /// <summary>
  60. /// Gets or sets the Id of the user.
  61. /// </summary>
  62. /// <remarks>
  63. /// Identity, Indexed, Required.
  64. /// </remarks>
  65. [JsonIgnore]
  66. public Guid Id { get; set; }
  67. /// <summary>
  68. /// Gets or sets the user's name.
  69. /// </summary>
  70. /// <remarks>
  71. /// Required, Max length = 255.
  72. /// </remarks>
  73. [MaxLength(255)]
  74. [StringLength(255)]
  75. public string Username { get; set; }
  76. /// <summary>
  77. /// Gets or sets the user's password, or <c>null</c> if none is set.
  78. /// </summary>
  79. /// <remarks>
  80. /// Max length = 65535.
  81. /// </remarks>
  82. [MaxLength(65535)]
  83. [StringLength(65535)]
  84. public string? Password { get; set; }
  85. /// <summary>
  86. /// Gets or sets a value indicating whether the user must update their password.
  87. /// </summary>
  88. /// <remarks>
  89. /// Required.
  90. /// </remarks>
  91. public bool MustUpdatePassword { get; set; }
  92. /// <summary>
  93. /// Gets or sets the audio language preference.
  94. /// </summary>
  95. /// <remarks>
  96. /// Max length = 255.
  97. /// </remarks>
  98. [MaxLength(255)]
  99. [StringLength(255)]
  100. public string? AudioLanguagePreference { get; set; }
  101. /// <summary>
  102. /// Gets or sets the authentication provider id.
  103. /// </summary>
  104. /// <remarks>
  105. /// Required, Max length = 255.
  106. /// </remarks>
  107. [MaxLength(255)]
  108. [StringLength(255)]
  109. public string AuthenticationProviderId { get; set; }
  110. /// <summary>
  111. /// Gets or sets the password reset provider id.
  112. /// </summary>
  113. /// <remarks>
  114. /// Required, Max length = 255.
  115. /// </remarks>
  116. [MaxLength(255)]
  117. [StringLength(255)]
  118. public string PasswordResetProviderId { get; set; }
  119. /// <summary>
  120. /// Gets or sets the invalid login attempt count.
  121. /// </summary>
  122. /// <remarks>
  123. /// Required.
  124. /// </remarks>
  125. public int InvalidLoginAttemptCount { get; set; }
  126. /// <summary>
  127. /// Gets or sets the last activity date.
  128. /// </summary>
  129. public DateTime? LastActivityDate { get; set; }
  130. /// <summary>
  131. /// Gets or sets the last login date.
  132. /// </summary>
  133. public DateTime? LastLoginDate { get; set; }
  134. /// <summary>
  135. /// Gets or sets the number of login attempts the user can make before they are locked out.
  136. /// </summary>
  137. public int? LoginAttemptsBeforeLockout { get; set; }
  138. /// <summary>
  139. /// Gets or sets the maximum number of active sessions the user can have at once.
  140. /// </summary>
  141. public int MaxActiveSessions { get; set; }
  142. /// <summary>
  143. /// Gets or sets the subtitle mode.
  144. /// </summary>
  145. /// <remarks>
  146. /// Required.
  147. /// </remarks>
  148. public SubtitlePlaybackMode SubtitleMode { get; set; }
  149. /// <summary>
  150. /// Gets or sets a value indicating whether the default audio track should be played.
  151. /// </summary>
  152. /// <remarks>
  153. /// Required.
  154. /// </remarks>
  155. public bool PlayDefaultAudioTrack { get; set; }
  156. /// <summary>
  157. /// Gets or sets the subtitle language preference.
  158. /// </summary>
  159. /// <remarks>
  160. /// Max length = 255.
  161. /// </remarks>
  162. [MaxLength(255)]
  163. [StringLength(255)]
  164. public string? SubtitleLanguagePreference { get; set; }
  165. /// <summary>
  166. /// Gets or sets a value indicating whether missing episodes should be displayed.
  167. /// </summary>
  168. /// <remarks>
  169. /// Required.
  170. /// </remarks>
  171. public bool DisplayMissingEpisodes { get; set; }
  172. /// <summary>
  173. /// Gets or sets a value indicating whether to display the collections view.
  174. /// </summary>
  175. /// <remarks>
  176. /// Required.
  177. /// </remarks>
  178. public bool DisplayCollectionsView { get; set; }
  179. /// <summary>
  180. /// Gets or sets a value indicating whether the user has a local password.
  181. /// </summary>
  182. /// <remarks>
  183. /// Required.
  184. /// </remarks>
  185. public bool EnableLocalPassword { get; set; }
  186. /// <summary>
  187. /// Gets or sets a value indicating whether the server should hide played content in "Latest".
  188. /// </summary>
  189. /// <remarks>
  190. /// Required.
  191. /// </remarks>
  192. public bool HidePlayedInLatest { get; set; }
  193. /// <summary>
  194. /// Gets or sets a value indicating whether to remember audio selections on played content.
  195. /// </summary>
  196. /// <remarks>
  197. /// Required.
  198. /// </remarks>
  199. public bool RememberAudioSelections { get; set; }
  200. /// <summary>
  201. /// Gets or sets a value indicating whether to remember subtitle selections on played content.
  202. /// </summary>
  203. /// <remarks>
  204. /// Required.
  205. /// </remarks>
  206. public bool RememberSubtitleSelections { get; set; }
  207. /// <summary>
  208. /// Gets or sets a value indicating whether to enable auto-play for the next episode.
  209. /// </summary>
  210. /// <remarks>
  211. /// Required.
  212. /// </remarks>
  213. public bool EnableNextEpisodeAutoPlay { get; set; }
  214. /// <summary>
  215. /// Gets or sets a value indicating whether the user should auto-login.
  216. /// </summary>
  217. /// <remarks>
  218. /// Required.
  219. /// </remarks>
  220. public bool EnableAutoLogin { get; set; }
  221. /// <summary>
  222. /// Gets or sets a value indicating whether the user can change their preferences.
  223. /// </summary>
  224. /// <remarks>
  225. /// Required.
  226. /// </remarks>
  227. public bool EnableUserPreferenceAccess { get; set; }
  228. /// <summary>
  229. /// Gets or sets the maximum parental age rating.
  230. /// </summary>
  231. public int? MaxParentalAgeRating { get; set; }
  232. /// <summary>
  233. /// Gets or sets the remote client bitrate limit.
  234. /// </summary>
  235. public int? RemoteClientBitrateLimit { get; set; }
  236. /// <summary>
  237. /// Gets or sets the internal id.
  238. /// This is a temporary stopgap for until the library db is migrated.
  239. /// This corresponds to the value of the index of this user in the library db.
  240. /// </summary>
  241. public long InternalId { get; set; }
  242. /// <summary>
  243. /// Gets or sets the user's profile image. Can be <c>null</c>.
  244. /// </summary>
  245. // [ForeignKey("UserId")]
  246. public virtual ImageInfo? ProfileImage { get; set; }
  247. /// <summary>
  248. /// Gets the user's display preferences.
  249. /// </summary>
  250. public virtual ICollection<DisplayPreferences> DisplayPreferences { get; private set; }
  251. /// <summary>
  252. /// Gets or sets the level of sync play permissions this user has.
  253. /// </summary>
  254. public SyncPlayUserAccessType SyncPlayAccess { get; set; }
  255. /// <summary>
  256. /// Gets or sets the cast receiver id.
  257. /// </summary>
  258. [StringLength(32)]
  259. public string? CastReceiverId { get; set; }
  260. /// <inheritdoc />
  261. [ConcurrencyCheck]
  262. public uint RowVersion { get; private set; }
  263. /// <summary>
  264. /// Gets the list of access schedules this user has.
  265. /// </summary>
  266. public virtual ICollection<AccessSchedule> AccessSchedules { get; private set; }
  267. /// <summary>
  268. /// Gets the list of item display preferences.
  269. /// </summary>
  270. public virtual ICollection<ItemDisplayPreferences> ItemDisplayPreferences { get; private set; }
  271. /*
  272. /// <summary>
  273. /// Gets the list of groups this user is a member of.
  274. /// </summary>
  275. public virtual ICollection<Group> Groups { get; private set; }
  276. */
  277. /// <summary>
  278. /// Gets the list of permissions this user has.
  279. /// </summary>
  280. [ForeignKey("Permission_Permissions_Guid")]
  281. public virtual ICollection<Permission> Permissions { get; private set; }
  282. /*
  283. /// <summary>
  284. /// Gets the list of provider mappings this user has.
  285. /// </summary>
  286. public virtual ICollection<ProviderMapping> ProviderMappings { get; private set; }
  287. */
  288. /// <summary>
  289. /// Gets the list of preferences this user has.
  290. /// </summary>
  291. [ForeignKey("Preference_Preferences_Guid")]
  292. public virtual ICollection<Preference> Preferences { get; private set; }
  293. /// <inheritdoc/>
  294. public void OnSavingChanges()
  295. {
  296. RowVersion++;
  297. }
  298. /// <summary>
  299. /// Checks whether the user has the specified permission.
  300. /// </summary>
  301. /// <param name="kind">The permission kind.</param>
  302. /// <returns><c>True</c> if the user has the specified permission.</returns>
  303. public bool HasPermission(PermissionKind kind)
  304. {
  305. return Permissions.FirstOrDefault(p => p.Kind == kind)?.Value ?? false;
  306. }
  307. /// <summary>
  308. /// Sets the given permission kind to the provided value.
  309. /// </summary>
  310. /// <param name="kind">The permission kind.</param>
  311. /// <param name="value">The value to set.</param>
  312. public void SetPermission(PermissionKind kind, bool value)
  313. {
  314. var currentPermission = Permissions.FirstOrDefault(p => p.Kind == kind);
  315. if (currentPermission is null)
  316. {
  317. Permissions.Add(new Permission(kind, value));
  318. }
  319. else
  320. {
  321. currentPermission.Value = value;
  322. }
  323. }
  324. /// <summary>
  325. /// Gets the user's preferences for the given preference kind.
  326. /// </summary>
  327. /// <param name="preference">The preference kind.</param>
  328. /// <returns>A string array containing the user's preferences.</returns>
  329. public string[] GetPreference(PreferenceKind preference)
  330. {
  331. var val = Preferences.FirstOrDefault(p => p.Kind == preference)?.Value;
  332. return string.IsNullOrEmpty(val) ? Array.Empty<string>() : val.Split(Delimiter);
  333. }
  334. /// <summary>
  335. /// Gets the user's preferences for the given preference kind.
  336. /// </summary>
  337. /// <param name="preference">The preference kind.</param>
  338. /// <typeparam name="T">Type of preference.</typeparam>
  339. /// <returns>A {T} array containing the user's preference.</returns>
  340. public T[] GetPreferenceValues<T>(PreferenceKind preference)
  341. {
  342. var val = Preferences.FirstOrDefault(p => p.Kind == preference)?.Value;
  343. if (string.IsNullOrEmpty(val))
  344. {
  345. return Array.Empty<T>();
  346. }
  347. // Convert array of {string} to array of {T}
  348. var converter = TypeDescriptor.GetConverter(typeof(T));
  349. var stringValues = val.Split(Delimiter);
  350. var convertedCount = 0;
  351. var parsedValues = new T[stringValues.Length];
  352. for (var i = 0; i < stringValues.Length; i++)
  353. {
  354. try
  355. {
  356. var parsedValue = converter.ConvertFromString(stringValues[i].Trim());
  357. if (parsedValue is not null)
  358. {
  359. parsedValues[convertedCount++] = (T)parsedValue;
  360. }
  361. }
  362. catch (FormatException)
  363. {
  364. // Unable to convert value
  365. }
  366. }
  367. return parsedValues[..convertedCount];
  368. }
  369. /// <summary>
  370. /// Sets the specified preference to the given value.
  371. /// </summary>
  372. /// <param name="preference">The preference kind.</param>
  373. /// <param name="values">The values.</param>
  374. public void SetPreference(PreferenceKind preference, string[] values)
  375. {
  376. var value = string.Join(Delimiter, values);
  377. var currentPreference = Preferences.FirstOrDefault(p => p.Kind == preference);
  378. if (currentPreference is null)
  379. {
  380. Preferences.Add(new Preference(preference, value));
  381. }
  382. else
  383. {
  384. currentPreference.Value = value;
  385. }
  386. }
  387. /// <summary>
  388. /// Sets the specified preference to the given value.
  389. /// </summary>
  390. /// <param name="preference">The preference kind.</param>
  391. /// <param name="values">The values.</param>
  392. /// <typeparam name="T">The type of value.</typeparam>
  393. public void SetPreference<T>(PreferenceKind preference, T[] values)
  394. {
  395. var value = string.Join(Delimiter, values);
  396. var currentPreference = Preferences.FirstOrDefault(p => p.Kind == preference);
  397. if (currentPreference is null)
  398. {
  399. Preferences.Add(new Preference(preference, value));
  400. }
  401. else
  402. {
  403. currentPreference.Value = value;
  404. }
  405. }
  406. /// <summary>
  407. /// Checks whether this user is currently allowed to use the server.
  408. /// </summary>
  409. /// <returns><c>True</c> if the current time is within an access schedule, or there are no access schedules.</returns>
  410. public bool IsParentalScheduleAllowed()
  411. {
  412. return AccessSchedules.Count == 0
  413. || AccessSchedules.Any(i => IsParentalScheduleAllowed(i, DateTime.UtcNow));
  414. }
  415. /// <summary>
  416. /// Checks whether the provided folder is in this user's grouped folders.
  417. /// </summary>
  418. /// <param name="id">The Guid of the folder.</param>
  419. /// <returns><c>True</c> if the folder is in the user's grouped folders.</returns>
  420. public bool IsFolderGrouped(Guid id)
  421. {
  422. return Array.IndexOf(GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders), id) != -1;
  423. }
  424. /// <summary>
  425. /// Initializes the default permissions for a user. Should only be called on user creation.
  426. /// </summary>
  427. // TODO: make these user configurable?
  428. public void AddDefaultPermissions()
  429. {
  430. Permissions.Add(new Permission(PermissionKind.IsAdministrator, false));
  431. Permissions.Add(new Permission(PermissionKind.IsDisabled, false));
  432. Permissions.Add(new Permission(PermissionKind.IsHidden, true));
  433. Permissions.Add(new Permission(PermissionKind.EnableAllChannels, true));
  434. Permissions.Add(new Permission(PermissionKind.EnableAllDevices, true));
  435. Permissions.Add(new Permission(PermissionKind.EnableAllFolders, true));
  436. Permissions.Add(new Permission(PermissionKind.EnableContentDeletion, false));
  437. Permissions.Add(new Permission(PermissionKind.EnableContentDownloading, true));
  438. Permissions.Add(new Permission(PermissionKind.EnableMediaConversion, true));
  439. Permissions.Add(new Permission(PermissionKind.EnableMediaPlayback, true));
  440. Permissions.Add(new Permission(PermissionKind.EnablePlaybackRemuxing, true));
  441. Permissions.Add(new Permission(PermissionKind.EnablePublicSharing, true));
  442. Permissions.Add(new Permission(PermissionKind.EnableRemoteAccess, true));
  443. Permissions.Add(new Permission(PermissionKind.EnableSyncTranscoding, true));
  444. Permissions.Add(new Permission(PermissionKind.EnableAudioPlaybackTranscoding, true));
  445. Permissions.Add(new Permission(PermissionKind.EnableLiveTvAccess, true));
  446. Permissions.Add(new Permission(PermissionKind.EnableLiveTvManagement, true));
  447. Permissions.Add(new Permission(PermissionKind.EnableSharedDeviceControl, true));
  448. Permissions.Add(new Permission(PermissionKind.EnableVideoPlaybackTranscoding, true));
  449. Permissions.Add(new Permission(PermissionKind.ForceRemoteSourceTranscoding, false));
  450. Permissions.Add(new Permission(PermissionKind.EnableRemoteControlOfOtherUsers, false));
  451. Permissions.Add(new Permission(PermissionKind.EnableCollectionManagement, false));
  452. Permissions.Add(new Permission(PermissionKind.EnableSubtitleManagement, false));
  453. Permissions.Add(new Permission(PermissionKind.EnableLyricManagement, false));
  454. }
  455. /// <summary>
  456. /// Initializes the default preferences. Should only be called on user creation.
  457. /// </summary>
  458. public void AddDefaultPreferences()
  459. {
  460. foreach (var val in Enum.GetValues<PreferenceKind>())
  461. {
  462. Preferences.Add(new Preference(val, string.Empty));
  463. }
  464. }
  465. private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date)
  466. {
  467. var localTime = date.ToLocalTime();
  468. var hour = localTime.TimeOfDay.TotalHours;
  469. var currentDayOfWeek = localTime.DayOfWeek;
  470. return schedule.DayOfWeek.Contains(currentDayOfWeek)
  471. && hour >= schedule.StartHour
  472. && hour <= schedule.EndHour;
  473. }
  474. }
  475. }