User.cs 15 KB

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