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