User.cs 15 KB

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