User.cs 20 KB

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