User.cs 19 KB

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