User.cs 15 KB

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