User.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. /// <inheritdoc />
  256. [ConcurrencyCheck]
  257. public uint RowVersion { get; private set; }
  258. /// <summary>
  259. /// Gets the list of access schedules this user has.
  260. /// </summary>
  261. public virtual ICollection<AccessSchedule> AccessSchedules { get; private set; }
  262. /// <summary>
  263. /// Gets the list of item display preferences.
  264. /// </summary>
  265. public virtual ICollection<ItemDisplayPreferences> ItemDisplayPreferences { get; private set; }
  266. /*
  267. /// <summary>
  268. /// Gets the list of groups this user is a member of.
  269. /// </summary>
  270. public virtual ICollection<Group> Groups { get; private set; }
  271. */
  272. /// <summary>
  273. /// Gets the list of permissions this user has.
  274. /// </summary>
  275. [ForeignKey("Permission_Permissions_Guid")]
  276. public virtual ICollection<Permission> Permissions { get; private set; }
  277. /*
  278. /// <summary>
  279. /// Gets the list of provider mappings this user has.
  280. /// </summary>
  281. public virtual ICollection<ProviderMapping> ProviderMappings { get; private set; }
  282. */
  283. /// <summary>
  284. /// Gets the list of preferences this user has.
  285. /// </summary>
  286. [ForeignKey("Preference_Preferences_Guid")]
  287. public virtual ICollection<Preference> Preferences { get; private set; }
  288. /// <inheritdoc/>
  289. public void OnSavingChanges()
  290. {
  291. RowVersion++;
  292. }
  293. /// <summary>
  294. /// Checks whether the user has the specified permission.
  295. /// </summary>
  296. /// <param name="kind">The permission kind.</param>
  297. /// <returns><c>True</c> if the user has the specified permission.</returns>
  298. public bool HasPermission(PermissionKind kind)
  299. {
  300. return Permissions.FirstOrDefault(p => p.Kind == kind)?.Value ?? false;
  301. }
  302. /// <summary>
  303. /// Sets the given permission kind to the provided value.
  304. /// </summary>
  305. /// <param name="kind">The permission kind.</param>
  306. /// <param name="value">The value to set.</param>
  307. public void SetPermission(PermissionKind kind, bool value)
  308. {
  309. var currentPermission = Permissions.FirstOrDefault(p => p.Kind == kind);
  310. if (currentPermission is null)
  311. {
  312. Permissions.Add(new Permission(kind, value));
  313. }
  314. else
  315. {
  316. currentPermission.Value = value;
  317. }
  318. }
  319. /// <summary>
  320. /// Gets the user's preferences for the given preference kind.
  321. /// </summary>
  322. /// <param name="preference">The preference kind.</param>
  323. /// <returns>A string array containing the user's preferences.</returns>
  324. public string[] GetPreference(PreferenceKind preference)
  325. {
  326. var val = Preferences.FirstOrDefault(p => p.Kind == preference)?.Value;
  327. return string.IsNullOrEmpty(val) ? Array.Empty<string>() : val.Split(Delimiter);
  328. }
  329. /// <summary>
  330. /// Gets the user's preferences for the given preference kind.
  331. /// </summary>
  332. /// <param name="preference">The preference kind.</param>
  333. /// <typeparam name="T">Type of preference.</typeparam>
  334. /// <returns>A {T} array containing the user's preference.</returns>
  335. public T[] GetPreferenceValues<T>(PreferenceKind preference)
  336. {
  337. var val = Preferences.FirstOrDefault(p => p.Kind == preference)?.Value;
  338. if (string.IsNullOrEmpty(val))
  339. {
  340. return Array.Empty<T>();
  341. }
  342. // Convert array of {string} to array of {T}
  343. var converter = TypeDescriptor.GetConverter(typeof(T));
  344. var stringValues = val.Split(Delimiter);
  345. var convertedCount = 0;
  346. var parsedValues = new T[stringValues.Length];
  347. for (var i = 0; i < stringValues.Length; i++)
  348. {
  349. try
  350. {
  351. var parsedValue = converter.ConvertFromString(stringValues[i].Trim());
  352. if (parsedValue is not null)
  353. {
  354. parsedValues[convertedCount++] = (T)parsedValue;
  355. }
  356. }
  357. catch (FormatException)
  358. {
  359. // Unable to convert value
  360. }
  361. }
  362. return parsedValues[..convertedCount];
  363. }
  364. /// <summary>
  365. /// Sets the specified preference to the given value.
  366. /// </summary>
  367. /// <param name="preference">The preference kind.</param>
  368. /// <param name="values">The values.</param>
  369. public void SetPreference(PreferenceKind preference, string[] values)
  370. {
  371. var value = string.Join(Delimiter, values);
  372. var currentPreference = Preferences.FirstOrDefault(p => p.Kind == preference);
  373. if (currentPreference is null)
  374. {
  375. Preferences.Add(new Preference(preference, value));
  376. }
  377. else
  378. {
  379. currentPreference.Value = value;
  380. }
  381. }
  382. /// <summary>
  383. /// Sets the specified preference to the given value.
  384. /// </summary>
  385. /// <param name="preference">The preference kind.</param>
  386. /// <param name="values">The values.</param>
  387. /// <typeparam name="T">The type of value.</typeparam>
  388. public void SetPreference<T>(PreferenceKind preference, T[] values)
  389. {
  390. var value = string.Join(Delimiter, values);
  391. var currentPreference = Preferences.FirstOrDefault(p => p.Kind == preference);
  392. if (currentPreference is null)
  393. {
  394. Preferences.Add(new Preference(preference, value));
  395. }
  396. else
  397. {
  398. currentPreference.Value = value;
  399. }
  400. }
  401. /// <summary>
  402. /// Checks whether this user is currently allowed to use the server.
  403. /// </summary>
  404. /// <returns><c>True</c> if the current time is within an access schedule, or there are no access schedules.</returns>
  405. public bool IsParentalScheduleAllowed()
  406. {
  407. return AccessSchedules.Count == 0
  408. || AccessSchedules.Any(i => IsParentalScheduleAllowed(i, DateTime.UtcNow));
  409. }
  410. /// <summary>
  411. /// Checks whether the provided folder is in this user's grouped folders.
  412. /// </summary>
  413. /// <param name="id">The Guid of the folder.</param>
  414. /// <returns><c>True</c> if the folder is in the user's grouped folders.</returns>
  415. public bool IsFolderGrouped(Guid id)
  416. {
  417. return Array.IndexOf(GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders), id) != -1;
  418. }
  419. /// <summary>
  420. /// Initializes the default permissions for a user. Should only be called on user creation.
  421. /// </summary>
  422. // TODO: make these user configurable?
  423. public void AddDefaultPermissions()
  424. {
  425. Permissions.Add(new Permission(PermissionKind.IsAdministrator, false));
  426. Permissions.Add(new Permission(PermissionKind.IsDisabled, false));
  427. Permissions.Add(new Permission(PermissionKind.IsHidden, true));
  428. Permissions.Add(new Permission(PermissionKind.EnableAllChannels, true));
  429. Permissions.Add(new Permission(PermissionKind.EnableAllDevices, true));
  430. Permissions.Add(new Permission(PermissionKind.EnableAllFolders, true));
  431. Permissions.Add(new Permission(PermissionKind.EnableContentDeletion, false));
  432. Permissions.Add(new Permission(PermissionKind.EnableContentDownloading, true));
  433. Permissions.Add(new Permission(PermissionKind.EnableMediaConversion, true));
  434. Permissions.Add(new Permission(PermissionKind.EnableMediaPlayback, true));
  435. Permissions.Add(new Permission(PermissionKind.EnablePlaybackRemuxing, true));
  436. Permissions.Add(new Permission(PermissionKind.EnablePublicSharing, true));
  437. Permissions.Add(new Permission(PermissionKind.EnableRemoteAccess, true));
  438. Permissions.Add(new Permission(PermissionKind.EnableSyncTranscoding, true));
  439. Permissions.Add(new Permission(PermissionKind.EnableAudioPlaybackTranscoding, true));
  440. Permissions.Add(new Permission(PermissionKind.EnableLiveTvAccess, true));
  441. Permissions.Add(new Permission(PermissionKind.EnableLiveTvManagement, true));
  442. Permissions.Add(new Permission(PermissionKind.EnableSharedDeviceControl, true));
  443. Permissions.Add(new Permission(PermissionKind.EnableVideoPlaybackTranscoding, true));
  444. Permissions.Add(new Permission(PermissionKind.ForceRemoteSourceTranscoding, false));
  445. Permissions.Add(new Permission(PermissionKind.EnableRemoteControlOfOtherUsers, false));
  446. Permissions.Add(new Permission(PermissionKind.EnableCollectionManagement, false));
  447. }
  448. /// <summary>
  449. /// Initializes the default preferences. Should only be called on user creation.
  450. /// </summary>
  451. public void AddDefaultPreferences()
  452. {
  453. foreach (var val in Enum.GetValues(typeof(PreferenceKind)).Cast<PreferenceKind>())
  454. {
  455. Preferences.Add(new Preference(val, string.Empty));
  456. }
  457. }
  458. private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date)
  459. {
  460. var localTime = date.ToLocalTime();
  461. var hour = localTime.TimeOfDay.TotalHours;
  462. var currentDayOfWeek = localTime.DayOfWeek;
  463. return schedule.DayOfWeek.Contains(currentDayOfWeek)
  464. && hour >= schedule.StartHour
  465. && hour <= schedule.EndHour;
  466. }
  467. }
  468. }