User.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.IO;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Model.Configuration;
  5. using System;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Model.Serialization;
  12. namespace MediaBrowser.Controller.Entities
  13. {
  14. /// <summary>
  15. /// Class User
  16. /// </summary>
  17. public class User : BaseItem
  18. {
  19. internal static IUserManager UserManager { get; set; }
  20. /// <summary>
  21. /// The _root folder path
  22. /// </summary>
  23. private string _rootFolderPath;
  24. /// <summary>
  25. /// Gets the root folder path.
  26. /// </summary>
  27. /// <value>The root folder path.</value>
  28. [IgnoreDataMember]
  29. public string RootFolderPath
  30. {
  31. get
  32. {
  33. if (_rootFolderPath == null)
  34. {
  35. if (Configuration.UseCustomLibrary)
  36. {
  37. _rootFolderPath = GetRootFolderPath(Name);
  38. if (!Directory.Exists(_rootFolderPath))
  39. {
  40. Directory.CreateDirectory(_rootFolderPath);
  41. }
  42. }
  43. else
  44. {
  45. _rootFolderPath = Kernel.Instance.ApplicationPaths.DefaultUserViewsPath;
  46. }
  47. }
  48. return _rootFolderPath;
  49. }
  50. }
  51. /// <summary>
  52. /// Gets the root folder path based on a given username
  53. /// </summary>
  54. /// <param name="username">The username.</param>
  55. /// <returns>System.String.</returns>
  56. private string GetRootFolderPath(string username)
  57. {
  58. var safeFolderName = FileSystem.GetValidFilename(username);
  59. return System.IO.Path.Combine(Kernel.Instance.ApplicationPaths.RootFolderPath, safeFolderName);
  60. }
  61. /// <summary>
  62. /// Gets or sets the password.
  63. /// </summary>
  64. /// <value>The password.</value>
  65. public string Password { get; set; }
  66. /// <summary>
  67. /// Gets or sets the path.
  68. /// </summary>
  69. /// <value>The path.</value>
  70. public override string Path
  71. {
  72. get
  73. {
  74. // Return this so that metadata providers will look in here
  75. return ConfigurationDirectoryPath;
  76. }
  77. set
  78. {
  79. base.Path = value;
  80. }
  81. }
  82. /// <summary>
  83. /// Ensure this has a value
  84. /// </summary>
  85. /// <value>The display type of the media.</value>
  86. public override string DisplayMediaType
  87. {
  88. get
  89. {
  90. return base.DisplayMediaType ?? GetType().Name;
  91. }
  92. set
  93. {
  94. base.DisplayMediaType = value;
  95. }
  96. }
  97. /// <summary>
  98. /// The _root folder
  99. /// </summary>
  100. private UserRootFolder _rootFolder;
  101. /// <summary>
  102. /// The _user root folder initialized
  103. /// </summary>
  104. private bool _userRootFolderInitialized;
  105. /// <summary>
  106. /// The _user root folder sync lock
  107. /// </summary>
  108. private object _userRootFolderSyncLock = new object();
  109. /// <summary>
  110. /// Gets the root folder.
  111. /// </summary>
  112. /// <value>The root folder.</value>
  113. [IgnoreDataMember]
  114. public UserRootFolder RootFolder
  115. {
  116. get
  117. {
  118. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _userRootFolderInitialized, ref _userRootFolderSyncLock, () => (UserRootFolder)Kernel.Instance.LibraryManager.GetItem(RootFolderPath));
  119. return _rootFolder;
  120. }
  121. private set
  122. {
  123. _rootFolder = value;
  124. if (_rootFolder == null)
  125. {
  126. _userRootFolderInitialized = false;
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Gets or sets the last login date.
  132. /// </summary>
  133. /// <value>The last login date.</value>
  134. public DateTime? LastLoginDate { get; set; }
  135. /// <summary>
  136. /// Gets or sets the last activity date.
  137. /// </summary>
  138. /// <value>The last activity date.</value>
  139. public DateTime? LastActivityDate { get; set; }
  140. /// <summary>
  141. /// The _configuration
  142. /// </summary>
  143. private UserConfiguration _configuration;
  144. /// <summary>
  145. /// The _configuration initialized
  146. /// </summary>
  147. private bool _configurationInitialized;
  148. /// <summary>
  149. /// The _configuration sync lock
  150. /// </summary>
  151. private object _configurationSyncLock = new object();
  152. /// <summary>
  153. /// Gets the user's configuration
  154. /// </summary>
  155. /// <value>The configuration.</value>
  156. [IgnoreDataMember]
  157. public UserConfiguration Configuration
  158. {
  159. get
  160. {
  161. // Lazy load
  162. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationInitialized, ref _configurationSyncLock, () => (UserConfiguration)Kernel.Instance.GetXmlConfiguration(typeof(UserConfiguration), ConfigurationFilePath));
  163. return _configuration;
  164. }
  165. private set
  166. {
  167. _configuration = value;
  168. if (value == null)
  169. {
  170. _configurationInitialized = false;
  171. }
  172. }
  173. }
  174. /// <summary>
  175. /// Gets the last date modified of the configuration
  176. /// </summary>
  177. /// <value>The configuration date last modified.</value>
  178. [IgnoreDataMember]
  179. public DateTime ConfigurationDateLastModified
  180. {
  181. get
  182. {
  183. // Ensure it's been lazy loaded
  184. var config = Configuration;
  185. return File.GetLastWriteTimeUtc(ConfigurationFilePath);
  186. }
  187. }
  188. /// <summary>
  189. /// Reloads the root media folder
  190. /// </summary>
  191. /// <param name="cancellationToken">The cancellation token.</param>
  192. /// <param name="progress">The progress.</param>
  193. /// <returns>Task.</returns>
  194. public async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  195. {
  196. Logger.Info("Validating media library for {0}", Name);
  197. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  198. cancellationToken.ThrowIfCancellationRequested();
  199. await RootFolder.ValidateChildren(progress, cancellationToken).ConfigureAwait(false);
  200. }
  201. /// <summary>
  202. /// Validates only the collection folders for a User and goes no further
  203. /// </summary>
  204. /// <param name="cancellationToken">The cancellation token.</param>
  205. /// <param name="progress">The progress.</param>
  206. /// <returns>Task.</returns>
  207. public async Task ValidateCollectionFolders(IProgress<double> progress, CancellationToken cancellationToken)
  208. {
  209. Logger.Info("Validating collection folders for {0}", Name);
  210. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  211. cancellationToken.ThrowIfCancellationRequested();
  212. await RootFolder.ValidateChildren(progress, cancellationToken, recursive: false).ConfigureAwait(false);
  213. }
  214. /// <summary>
  215. /// Renames the user.
  216. /// </summary>
  217. /// <param name="newName">The new name.</param>
  218. /// <returns>Task.</returns>
  219. /// <exception cref="System.ArgumentNullException"></exception>
  220. public Task Rename(string newName)
  221. {
  222. if (string.IsNullOrEmpty(newName))
  223. {
  224. throw new ArgumentNullException();
  225. }
  226. // If only the casing is changing, leave the file system alone
  227. if (!newName.Equals(Name, StringComparison.OrdinalIgnoreCase))
  228. {
  229. // Move configuration
  230. var newConfigDirectory = GetConfigurationDirectoryPath(newName);
  231. // Exceptions will be thrown if these paths already exist
  232. if (Directory.Exists(newConfigDirectory))
  233. {
  234. Directory.Delete(newConfigDirectory, true);
  235. }
  236. Directory.Move(ConfigurationDirectoryPath, newConfigDirectory);
  237. var customLibraryPath = GetRootFolderPath(Name);
  238. // Move the root folder path if using a custom library
  239. if (Directory.Exists(customLibraryPath))
  240. {
  241. var newRootFolderPath = GetRootFolderPath(newName);
  242. if (Directory.Exists(newRootFolderPath))
  243. {
  244. Directory.Delete(newRootFolderPath, true);
  245. }
  246. Directory.Move(customLibraryPath, newRootFolderPath);
  247. }
  248. }
  249. Name = newName;
  250. // Force these to be lazy loaded again
  251. _configurationDirectoryPath = null;
  252. _rootFolderPath = null;
  253. RootFolder = null;
  254. // Kick off a task to validate the media library
  255. Task.Run(() => ValidateMediaLibrary(new Progress<double> { }, CancellationToken.None));
  256. return RefreshMetadata(CancellationToken.None, forceSave: true, forceRefresh: true);
  257. }
  258. /// <summary>
  259. /// The _configuration directory path
  260. /// </summary>
  261. private string _configurationDirectoryPath;
  262. /// <summary>
  263. /// Gets the path to the user's configuration directory
  264. /// </summary>
  265. /// <value>The configuration directory path.</value>
  266. private string ConfigurationDirectoryPath
  267. {
  268. get
  269. {
  270. if (_configurationDirectoryPath == null)
  271. {
  272. _configurationDirectoryPath = GetConfigurationDirectoryPath(Name);
  273. if (!Directory.Exists(_configurationDirectoryPath))
  274. {
  275. Directory.CreateDirectory(_configurationDirectoryPath);
  276. }
  277. }
  278. return _configurationDirectoryPath;
  279. }
  280. }
  281. /// <summary>
  282. /// Gets the configuration directory path.
  283. /// </summary>
  284. /// <param name="username">The username.</param>
  285. /// <returns>System.String.</returns>
  286. private string GetConfigurationDirectoryPath(string username)
  287. {
  288. var safeFolderName = FileSystem.GetValidFilename(username);
  289. return System.IO.Path.Combine(Kernel.Instance.ApplicationPaths.UserConfigurationDirectoryPath, safeFolderName);
  290. }
  291. /// <summary>
  292. /// Gets the path to the user's configuration file
  293. /// </summary>
  294. /// <value>The configuration file path.</value>
  295. private string ConfigurationFilePath
  296. {
  297. get
  298. {
  299. return System.IO.Path.Combine(ConfigurationDirectoryPath, "config.xml");
  300. }
  301. }
  302. /// <summary>
  303. /// Saves the current configuration to the file system
  304. /// </summary>
  305. public void SaveConfiguration(IXmlSerializer serializer)
  306. {
  307. serializer.SerializeToFile(Configuration, ConfigurationFilePath);
  308. }
  309. /// <summary>
  310. /// Refresh metadata on us by execution our provider chain
  311. /// The item will be persisted if a change is made by a provider, or if it's new or changed.
  312. /// </summary>
  313. /// <param name="cancellationToken">The cancellation token.</param>
  314. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  315. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  316. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  317. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  318. /// <returns>true if a provider reports we changed</returns>
  319. public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  320. {
  321. if (resetResolveArgs)
  322. {
  323. ResolveArgs = null;
  324. }
  325. var changed = await Kernel.Instance.ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  326. if (changed || forceSave)
  327. {
  328. cancellationToken.ThrowIfCancellationRequested();
  329. await UserManager.UpdateUser(this).ConfigureAwait(false);
  330. }
  331. return changed;
  332. }
  333. /// <summary>
  334. /// Updates the configuration.
  335. /// </summary>
  336. /// <param name="config">The config.</param>
  337. /// <param name="serializer">The serializer.</param>
  338. /// <exception cref="System.ArgumentNullException">config</exception>
  339. public void UpdateConfiguration(UserConfiguration config, IXmlSerializer serializer)
  340. {
  341. if (config == null)
  342. {
  343. throw new ArgumentNullException("config");
  344. }
  345. var customLibraryChanged = config.UseCustomLibrary != Configuration.UseCustomLibrary;
  346. Configuration = config;
  347. SaveConfiguration(serializer);
  348. // Force these to be lazy loaded again
  349. if (customLibraryChanged)
  350. {
  351. _rootFolderPath = null;
  352. RootFolder = null;
  353. if (config.UseCustomLibrary)
  354. {
  355. CopyDefaultLibraryPathsIfNeeded();
  356. }
  357. }
  358. }
  359. /// <summary>
  360. /// Copies the default library paths if needed.
  361. /// </summary>
  362. private void CopyDefaultLibraryPathsIfNeeded()
  363. {
  364. var userPath = RootFolderPath;
  365. var defaultPath = Kernel.Instance.ApplicationPaths.DefaultUserViewsPath;
  366. if (userPath.Equals(defaultPath, StringComparison.OrdinalIgnoreCase))
  367. {
  368. return;
  369. }
  370. if (!Directory.EnumerateFileSystemEntries(userPath, "*.lnk", SearchOption.AllDirectories).Any())
  371. {
  372. FileSystem.CopyAll(defaultPath, userPath);
  373. }
  374. }
  375. /// <summary>
  376. /// Resets the password by clearing it.
  377. /// </summary>
  378. /// <returns>Task.</returns>
  379. public Task ResetPassword(IUserManager userManager)
  380. {
  381. return ChangePassword(string.Empty, userManager);
  382. }
  383. /// <summary>
  384. /// Changes the password.
  385. /// </summary>
  386. /// <param name="newPassword">The new password.</param>
  387. /// <returns>Task.</returns>
  388. public Task ChangePassword(string newPassword, IUserManager userManager)
  389. {
  390. Password = string.IsNullOrEmpty(newPassword) ? string.Empty : newPassword.GetMD5().ToString();
  391. return userManager.UpdateUser(this);
  392. }
  393. }
  394. }