User.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. DisplayPreferences = new HashSet<DisplayPreferences>();
  48. ItemDisplayPreferences = new HashSet<ItemDisplayPreferences>();
  49. // Groups = new HashSet<Group>();
  50. Permissions = new HashSet<Permission>();
  51. Preferences = new HashSet<Preference>();
  52. // ProviderMappings = new HashSet<ProviderMapping>();
  53. // Set default values
  54. Id = Guid.NewGuid();
  55. InvalidLoginAttemptCount = 0;
  56. EnableUserPreferenceAccess = true;
  57. MustUpdatePassword = false;
  58. DisplayMissingEpisodes = false;
  59. DisplayCollectionsView = false;
  60. HidePlayedInLatest = true;
  61. RememberAudioSelections = true;
  62. RememberSubtitleSelections = true;
  63. EnableNextEpisodeAutoPlay = true;
  64. EnableAutoLogin = false;
  65. PlayDefaultAudioTrack = true;
  66. SubtitleMode = SubtitlePlaybackMode.Default;
  67. SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups;
  68. }
  69. /// <summary>
  70. /// Gets or sets the Id of the user.
  71. /// </summary>
  72. /// <remarks>
  73. /// Identity, Indexed, Required.
  74. /// </remarks>
  75. [JsonIgnore]
  76. public Guid Id { get; set; }
  77. /// <summary>
  78. /// Gets or sets the user's name.
  79. /// </summary>
  80. /// <remarks>
  81. /// Required, Max length = 255.
  82. /// </remarks>
  83. [MaxLength(255)]
  84. [StringLength(255)]
  85. public string Username { get; set; }
  86. /// <summary>
  87. /// Gets or sets the user's password, or <c>null</c> if none is set.
  88. /// </summary>
  89. /// <remarks>
  90. /// Max length = 65535.
  91. /// </remarks>
  92. [MaxLength(65535)]
  93. [StringLength(65535)]
  94. public string? Password { get; set; }
  95. /// <summary>
  96. /// Gets or sets the user's easy 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? EasyPassword { get; set; }
  104. /// <summary>
  105. /// Gets or sets a value indicating whether the user must update their password.
  106. /// </summary>
  107. /// <remarks>
  108. /// Required.
  109. /// </remarks>
  110. public bool MustUpdatePassword { get; set; }
  111. /// <summary>
  112. /// Gets or sets the audio language preference.
  113. /// </summary>
  114. /// <remarks>
  115. /// Max length = 255.
  116. /// </remarks>
  117. [MaxLength(255)]
  118. [StringLength(255)]
  119. public string? AudioLanguagePreference { get; set; }
  120. /// <summary>
  121. /// Gets or sets the authentication provider id.
  122. /// </summary>
  123. /// <remarks>
  124. /// Required, Max length = 255.
  125. /// </remarks>
  126. [MaxLength(255)]
  127. [StringLength(255)]
  128. public string AuthenticationProviderId { get; set; }
  129. /// <summary>
  130. /// Gets or sets the password reset provider id.
  131. /// </summary>
  132. /// <remarks>
  133. /// Required, Max length = 255.
  134. /// </remarks>
  135. [MaxLength(255)]
  136. [StringLength(255)]
  137. public string PasswordResetProviderId { get; set; }
  138. /// <summary>
  139. /// Gets or sets the invalid login attempt count.
  140. /// </summary>
  141. /// <remarks>
  142. /// Required.
  143. /// </remarks>
  144. public int InvalidLoginAttemptCount { get; set; }
  145. /// <summary>
  146. /// Gets or sets the last activity date.
  147. /// </summary>
  148. public DateTime? LastActivityDate { get; set; }
  149. /// <summary>
  150. /// Gets or sets the last login date.
  151. /// </summary>
  152. public DateTime? LastLoginDate { get; set; }
  153. /// <summary>
  154. /// Gets or sets the number of login attempts the user can make before they are locked out.
  155. /// </summary>
  156. public int? LoginAttemptsBeforeLockout { get; set; }
  157. /// <summary>
  158. /// Gets or sets the maximum number of active sessions the user can have at once.
  159. /// </summary>
  160. public int MaxActiveSessions { get; set; }
  161. /// <summary>
  162. /// Gets or sets the subtitle mode.
  163. /// </summary>
  164. /// <remarks>
  165. /// Required.
  166. /// </remarks>
  167. public SubtitlePlaybackMode SubtitleMode { get; set; }
  168. /// <summary>
  169. /// Gets or sets a value indicating whether the default audio track should be played.
  170. /// </summary>
  171. /// <remarks>
  172. /// Required.
  173. /// </remarks>
  174. public bool PlayDefaultAudioTrack { get; set; }
  175. /// <summary>
  176. /// Gets or sets the subtitle language preference.
  177. /// </summary>
  178. /// <remarks>
  179. /// Max length = 255.
  180. /// </remarks>
  181. [MaxLength(255)]
  182. [StringLength(255)]
  183. public string? SubtitleLanguagePreference { get; set; }
  184. /// <summary>
  185. /// Gets or sets a value indicating whether missing episodes should be displayed.
  186. /// </summary>
  187. /// <remarks>
  188. /// Required.
  189. /// </remarks>
  190. public bool DisplayMissingEpisodes { get; set; }
  191. /// <summary>
  192. /// Gets or sets a value indicating whether to display the collections view.
  193. /// </summary>
  194. /// <remarks>
  195. /// Required.
  196. /// </remarks>
  197. public bool DisplayCollectionsView { get; set; }
  198. /// <summary>
  199. /// Gets or sets a value indicating whether the user has a local password.
  200. /// </summary>
  201. /// <remarks>
  202. /// Required.
  203. /// </remarks>
  204. public bool EnableLocalPassword { get; set; }
  205. /// <summary>
  206. /// Gets or sets a value indicating whether the server should hide played content in "Latest".
  207. /// </summary>
  208. /// <remarks>
  209. /// Required.
  210. /// </remarks>
  211. public bool HidePlayedInLatest { get; set; }
  212. /// <summary>
  213. /// Gets or sets a value indicating whether to remember audio selections on played content.
  214. /// </summary>
  215. /// <remarks>
  216. /// Required.
  217. /// </remarks>
  218. public bool RememberAudioSelections { get; set; }
  219. /// <summary>
  220. /// Gets or sets a value indicating whether to remember subtitle selections on played content.
  221. /// </summary>
  222. /// <remarks>
  223. /// Required.
  224. /// </remarks>
  225. public bool RememberSubtitleSelections { get; set; }
  226. /// <summary>
  227. /// Gets or sets a value indicating whether to enable auto-play for the next episode.
  228. /// </summary>
  229. /// <remarks>
  230. /// Required.
  231. /// </remarks>
  232. public bool EnableNextEpisodeAutoPlay { get; set; }
  233. /// <summary>
  234. /// Gets or sets a value indicating whether the user should auto-login.
  235. /// </summary>
  236. /// <remarks>
  237. /// Required.
  238. /// </remarks>
  239. public bool EnableAutoLogin { get; set; }
  240. /// <summary>
  241. /// Gets or sets a value indicating whether the user can change their preferences.
  242. /// </summary>
  243. /// <remarks>
  244. /// Required.
  245. /// </remarks>
  246. public bool EnableUserPreferenceAccess { get; set; }
  247. /// <summary>
  248. /// Gets or sets the maximum parental age rating.
  249. /// </summary>
  250. public int? MaxParentalAgeRating { get; set; }
  251. /// <summary>
  252. /// Gets or sets the remote client bitrate limit.
  253. /// </summary>
  254. public int? RemoteClientBitrateLimit { get; set; }
  255. /// <summary>
  256. /// Gets or sets the internal id.
  257. /// This is a temporary stopgap for until the library db is migrated.
  258. /// This corresponds to the value of the index of this user in the library db.
  259. /// </summary>
  260. public long InternalId { get; set; }
  261. /// <summary>
  262. /// Gets or sets the user's profile image. Can be <c>null</c>.
  263. /// </summary>
  264. // [ForeignKey("UserId")]
  265. public virtual ImageInfo? ProfileImage { get; set; }
  266. /// <summary>
  267. /// Gets or sets the user's display preferences.
  268. /// </summary>
  269. /// <remarks>
  270. /// Required.
  271. /// </remarks>
  272. public virtual ICollection<DisplayPreferences> DisplayPreferences { get; set; }
  273. /// <summary>
  274. /// Gets or sets the level of sync play permissions this user has.
  275. /// </summary>
  276. public SyncPlayUserAccessType SyncPlayAccess { get; set; }
  277. /// <summary>
  278. /// Gets or sets the row version.
  279. /// </summary>
  280. /// <remarks>
  281. /// Required, Concurrency Token.
  282. /// </remarks>
  283. [ConcurrencyCheck]
  284. public uint RowVersion { get; set; }
  285. /// <summary>
  286. /// Gets or sets the list of access schedules this user has.
  287. /// </summary>
  288. public virtual ICollection<AccessSchedule> AccessSchedules { get; protected set; }
  289. /// <summary>
  290. /// Gets or sets the list of item display preferences.
  291. /// </summary>
  292. public virtual ICollection<ItemDisplayPreferences> ItemDisplayPreferences { get; protected set; }
  293. /*
  294. /// <summary>
  295. /// Gets or sets the list of groups this user is a member of.
  296. /// </summary>
  297. [ForeignKey("Group_Groups_Guid")]
  298. public virtual ICollection<Group> Groups { get; protected set; }
  299. */
  300. /// <summary>
  301. /// Gets or sets the list of permissions this user has.
  302. /// </summary>
  303. [ForeignKey("Permission_Permissions_Guid")]
  304. public virtual ICollection<Permission> Permissions { get; protected set; }
  305. /*
  306. /// <summary>
  307. /// Gets or sets the list of provider mappings this user has.
  308. /// </summary>
  309. [ForeignKey("ProviderMapping_ProviderMappings_Id")]
  310. public virtual ICollection<ProviderMapping> ProviderMappings { get; protected set; }
  311. */
  312. /// <summary>
  313. /// Gets or sets the list of preferences this user has.
  314. /// </summary>
  315. [ForeignKey("Preference_Preferences_Guid")]
  316. public virtual ICollection<Preference> Preferences { get; protected set; }
  317. /// <inheritdoc/>
  318. public void OnSavingChanges()
  319. {
  320. RowVersion++;
  321. }
  322. /// <summary>
  323. /// Checks whether the user has the specified permission.
  324. /// </summary>
  325. /// <param name="kind">The permission kind.</param>
  326. /// <returns><c>True</c> if the user has the specified permission.</returns>
  327. public bool HasPermission(PermissionKind kind)
  328. {
  329. return Permissions.First(p => p.Kind == kind).Value;
  330. }
  331. /// <summary>
  332. /// Sets the given permission kind to the provided value.
  333. /// </summary>
  334. /// <param name="kind">The permission kind.</param>
  335. /// <param name="value">The value to set.</param>
  336. public void SetPermission(PermissionKind kind, bool value)
  337. {
  338. Permissions.First(p => p.Kind == kind).Value = value;
  339. }
  340. /// <summary>
  341. /// Gets the user's preferences for the given preference kind.
  342. /// </summary>
  343. /// <param name="preference">The preference kind.</param>
  344. /// <returns>A string array containing the user's preferences.</returns>
  345. public string[] GetPreference(PreferenceKind preference)
  346. {
  347. var val = Preferences.First(p => p.Kind == preference).Value;
  348. return Equals(val, string.Empty) ? Array.Empty<string>() : val.Split(Delimiter);
  349. }
  350. /// <summary>
  351. /// Gets the user's preferences for the given preference kind.
  352. /// </summary>
  353. /// <param name="preference">The preference kind.</param>
  354. /// <typeparam name="T">Type of preference.</typeparam>
  355. /// <returns>A {T} array containing the user's preference.</returns>
  356. public T[] GetPreferenceValues<T>(PreferenceKind preference)
  357. {
  358. var val = Preferences.First(p => p.Kind == preference).Value;
  359. if (string.IsNullOrEmpty(val))
  360. {
  361. return Array.Empty<T>();
  362. }
  363. // Convert array of {string} to array of {T}
  364. var converter = TypeDescriptor.GetConverter(typeof(T));
  365. var stringValues = val.Split(Delimiter);
  366. var convertedCount = 0;
  367. var parsedValues = new T[stringValues.Length];
  368. for (var i = 0; i < stringValues.Length; i++)
  369. {
  370. try
  371. {
  372. var parsedValue = converter.ConvertFromString(stringValues[i].Trim());
  373. if (parsedValue != null)
  374. {
  375. parsedValues[convertedCount++] = (T)parsedValue;
  376. }
  377. }
  378. catch (FormatException)
  379. {
  380. // Unable to convert value
  381. }
  382. }
  383. return parsedValues[..convertedCount];
  384. }
  385. /// <summary>
  386. /// Sets the specified preference to the given value.
  387. /// </summary>
  388. /// <param name="preference">The preference kind.</param>
  389. /// <param name="values">The values.</param>
  390. public void SetPreference(PreferenceKind preference, string[] values)
  391. {
  392. Preferences.First(p => p.Kind == preference).Value
  393. = string.Join(Delimiter, values);
  394. }
  395. /// <summary>
  396. /// Sets the specified preference to the given value.
  397. /// </summary>
  398. /// <param name="preference">The preference kind.</param>
  399. /// <param name="values">The values.</param>
  400. /// <typeparam name="T">The type of value.</typeparam>
  401. public void SetPreference<T>(PreferenceKind preference, T[] values)
  402. {
  403. Preferences.First(p => p.Kind == preference).Value
  404. = string.Join(Delimiter, values);
  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. }
  452. /// <summary>
  453. /// Initializes the default preferences. Should only be called on user creation.
  454. /// </summary>
  455. public void AddDefaultPreferences()
  456. {
  457. foreach (var val in Enum.GetValues(typeof(PreferenceKind)).Cast<PreferenceKind>())
  458. {
  459. Preferences.Add(new Preference(val, string.Empty));
  460. }
  461. }
  462. private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date)
  463. {
  464. var localTime = date.ToLocalTime();
  465. var hour = localTime.TimeOfDay.TotalHours;
  466. return DayOfWeekHelper.GetDaysOfWeek(schedule.DayOfWeek).Contains(localTime.DayOfWeek)
  467. && hour >= schedule.StartHour
  468. && hour <= schedule.EndHour;
  469. }
  470. }
  471. }