LibraryStructureService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.IO;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Api.Library
  15. {
  16. /// <summary>
  17. /// Class GetDefaultVirtualFolders
  18. /// </summary>
  19. [Route("/Library/VirtualFolders", "GET")]
  20. [Route("/Users/{UserId}/VirtualFolders", "GET")]
  21. public class GetVirtualFolders : IReturn<List<VirtualFolderInfo>>
  22. {
  23. /// <summary>
  24. /// Gets or sets the user id.
  25. /// </summary>
  26. /// <value>The user id.</value>
  27. public string UserId { get; set; }
  28. }
  29. [Route("/Library/VirtualFolders/{Name}", "POST")]
  30. [Route("/Users/{UserId}/VirtualFolders/{Name}", "POST")]
  31. public class AddVirtualFolder : IReturnVoid
  32. {
  33. /// <summary>
  34. /// Gets or sets the user id.
  35. /// </summary>
  36. /// <value>The user id.</value>
  37. public string UserId { get; set; }
  38. /// <summary>
  39. /// Gets or sets the name.
  40. /// </summary>
  41. /// <value>The name.</value>
  42. public string Name { get; set; }
  43. /// <summary>
  44. /// Gets or sets the type of the collection.
  45. /// </summary>
  46. /// <value>The type of the collection.</value>
  47. public string CollectionType { get; set; }
  48. /// <summary>
  49. /// Gets or sets a value indicating whether [refresh library].
  50. /// </summary>
  51. /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
  52. public bool RefreshLibrary { get; set; }
  53. }
  54. [Route("/Library/VirtualFolders/{Name}", "DELETE")]
  55. [Route("/Users/{UserId}/VirtualFolders/{Name}", "DELETE")]
  56. public class RemoveVirtualFolder : IReturnVoid
  57. {
  58. /// <summary>
  59. /// Gets or sets the user id.
  60. /// </summary>
  61. /// <value>The user id.</value>
  62. public string UserId { get; set; }
  63. /// <summary>
  64. /// Gets or sets the name.
  65. /// </summary>
  66. /// <value>The name.</value>
  67. public string Name { get; set; }
  68. /// <summary>
  69. /// Gets or sets a value indicating whether [refresh library].
  70. /// </summary>
  71. /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
  72. public bool RefreshLibrary { get; set; }
  73. }
  74. [Route("/Library/VirtualFolders/{Name}/Name", "POST")]
  75. [Route("/Users/{UserId}/VirtualFolders/{Name}/Name", "POST")]
  76. public class RenameVirtualFolder : IReturnVoid
  77. {
  78. /// <summary>
  79. /// Gets or sets the user id.
  80. /// </summary>
  81. /// <value>The user id.</value>
  82. public string UserId { get; set; }
  83. /// <summary>
  84. /// Gets or sets the name.
  85. /// </summary>
  86. /// <value>The name.</value>
  87. public string Name { get; set; }
  88. /// <summary>
  89. /// Gets or sets the name.
  90. /// </summary>
  91. /// <value>The name.</value>
  92. public string NewName { get; set; }
  93. /// <summary>
  94. /// Gets or sets a value indicating whether [refresh library].
  95. /// </summary>
  96. /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
  97. public bool RefreshLibrary { get; set; }
  98. }
  99. [Route("/Library/VirtualFolders/{Name}/Paths", "POST")]
  100. [Route("/Users/{UserId}/VirtualFolders/{Name}/Paths", "POST")]
  101. public class AddMediaPath : IReturnVoid
  102. {
  103. /// <summary>
  104. /// Gets or sets the user id.
  105. /// </summary>
  106. /// <value>The user id.</value>
  107. public string UserId { get; set; }
  108. /// <summary>
  109. /// Gets or sets the name.
  110. /// </summary>
  111. /// <value>The name.</value>
  112. public string Name { get; set; }
  113. /// <summary>
  114. /// Gets or sets the name.
  115. /// </summary>
  116. /// <value>The name.</value>
  117. public string Path { get; set; }
  118. /// <summary>
  119. /// Gets or sets a value indicating whether [refresh library].
  120. /// </summary>
  121. /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
  122. public bool RefreshLibrary { get; set; }
  123. }
  124. [Route("/Library/VirtualFolders/{Name}/Paths", "DELETE")]
  125. [Route("/Users/{UserId}/VirtualFolders/{Name}/Paths", "DELETE")]
  126. public class RemoveMediaPath : IReturnVoid
  127. {
  128. /// <summary>
  129. /// Gets or sets the user id.
  130. /// </summary>
  131. /// <value>The user id.</value>
  132. public string UserId { get; set; }
  133. /// <summary>
  134. /// Gets or sets the name.
  135. /// </summary>
  136. /// <value>The name.</value>
  137. public string Name { get; set; }
  138. /// <summary>
  139. /// Gets or sets the name.
  140. /// </summary>
  141. /// <value>The name.</value>
  142. public string Path { get; set; }
  143. /// <summary>
  144. /// Gets or sets a value indicating whether [refresh library].
  145. /// </summary>
  146. /// <value><c>true</c> if [refresh library]; otherwise, <c>false</c>.</value>
  147. public bool RefreshLibrary { get; set; }
  148. }
  149. /// <summary>
  150. /// Class LibraryStructureService
  151. /// </summary>
  152. public class LibraryStructureService : BaseApiService
  153. {
  154. /// <summary>
  155. /// The _app paths
  156. /// </summary>
  157. private readonly IServerApplicationPaths _appPaths;
  158. /// <summary>
  159. /// The _user manager
  160. /// </summary>
  161. private readonly IUserManager _userManager;
  162. /// <summary>
  163. /// The _library manager
  164. /// </summary>
  165. private readonly ILibraryManager _libraryManager;
  166. private readonly IDirectoryWatchers _directoryWatchers;
  167. private readonly IFileSystem _fileSystem;
  168. private readonly ILogger _logger;
  169. /// <summary>
  170. /// Initializes a new instance of the <see cref="LibraryStructureService"/> class.
  171. /// </summary>
  172. /// <param name="appPaths">The app paths.</param>
  173. /// <param name="userManager">The user manager.</param>
  174. /// <param name="libraryManager">The library manager.</param>
  175. /// <exception cref="System.ArgumentNullException">appPaths</exception>
  176. public LibraryStructureService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IDirectoryWatchers directoryWatchers, IFileSystem fileSystem, ILogger logger)
  177. {
  178. if (appPaths == null)
  179. {
  180. throw new ArgumentNullException("appPaths");
  181. }
  182. _userManager = userManager;
  183. _appPaths = appPaths;
  184. _libraryManager = libraryManager;
  185. _directoryWatchers = directoryWatchers;
  186. _fileSystem = fileSystem;
  187. _logger = logger;
  188. }
  189. /// <summary>
  190. /// Gets the specified request.
  191. /// </summary>
  192. /// <param name="request">The request.</param>
  193. /// <returns>System.Object.</returns>
  194. public object Get(GetVirtualFolders request)
  195. {
  196. if (string.IsNullOrEmpty(request.UserId))
  197. {
  198. var result = _libraryManager.GetDefaultVirtualFolders().OrderBy(i => i.Name).ToList();
  199. return ToOptimizedResult(result);
  200. }
  201. else
  202. {
  203. var user = _userManager.GetUserById(new Guid(request.UserId));
  204. var result = _libraryManager.GetVirtualFolders(user).OrderBy(i => i.Name).ToList();
  205. return ToOptimizedResult(result);
  206. }
  207. }
  208. /// <summary>
  209. /// Posts the specified request.
  210. /// </summary>
  211. /// <param name="request">The request.</param>
  212. public void Post(AddVirtualFolder request)
  213. {
  214. var name = _fileSystem.GetValidFilename(request.Name);
  215. string rootFolderPath;
  216. if (string.IsNullOrEmpty(request.UserId))
  217. {
  218. rootFolderPath = _appPaths.DefaultUserViewsPath;
  219. }
  220. else
  221. {
  222. var user = _userManager.GetUserById(new Guid(request.UserId));
  223. rootFolderPath = user.RootFolderPath;
  224. }
  225. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  226. if (Directory.Exists(virtualFolderPath))
  227. {
  228. throw new ArgumentException("There is already a media collection with the name " + name + ".");
  229. }
  230. _directoryWatchers.Stop();
  231. _directoryWatchers.TemporarilyIgnore(virtualFolderPath);
  232. try
  233. {
  234. Directory.CreateDirectory(virtualFolderPath);
  235. if (!string.IsNullOrEmpty(request.CollectionType))
  236. {
  237. var path = Path.Combine(virtualFolderPath, request.CollectionType + ".collection");
  238. File.Create(path);
  239. }
  240. // Need to add a delay here or directory watchers may still pick up the changes
  241. var task = Task.Delay(1000);
  242. // Have to block here to allow exceptions to bubble
  243. Task.WaitAll(task);
  244. }
  245. finally
  246. {
  247. // No need to start if scanning the library because it will handle it
  248. if (!request.RefreshLibrary)
  249. {
  250. _directoryWatchers.Start();
  251. }
  252. _directoryWatchers.RemoveTempIgnore(virtualFolderPath);
  253. }
  254. if (request.RefreshLibrary)
  255. {
  256. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  257. }
  258. }
  259. /// <summary>
  260. /// Posts the specified request.
  261. /// </summary>
  262. /// <param name="request">The request.</param>
  263. public void Post(RenameVirtualFolder request)
  264. {
  265. string rootFolderPath;
  266. if (string.IsNullOrEmpty(request.UserId))
  267. {
  268. rootFolderPath = _appPaths.DefaultUserViewsPath;
  269. }
  270. else
  271. {
  272. var user = _userManager.GetUserById(new Guid(request.UserId));
  273. rootFolderPath = user.RootFolderPath;
  274. }
  275. var currentPath = Path.Combine(rootFolderPath, request.Name);
  276. var newPath = Path.Combine(rootFolderPath, request.NewName);
  277. if (!Directory.Exists(currentPath))
  278. {
  279. throw new DirectoryNotFoundException("The media collection does not exist");
  280. }
  281. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  282. {
  283. throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
  284. }
  285. _directoryWatchers.Stop();
  286. _directoryWatchers.TemporarilyIgnore(currentPath);
  287. _directoryWatchers.TemporarilyIgnore(newPath);
  288. try
  289. {
  290. // Only make a two-phase move when changing capitalization
  291. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  292. {
  293. //Create an unique name
  294. var temporaryName = Guid.NewGuid().ToString();
  295. var temporaryPath = Path.Combine(rootFolderPath, temporaryName);
  296. Directory.Move(currentPath, temporaryPath);
  297. currentPath = temporaryPath;
  298. }
  299. Directory.Move(currentPath, newPath);
  300. // Need to add a delay here or directory watchers may still pick up the changes
  301. var task = Task.Delay(1000);
  302. // Have to block here to allow exceptions to bubble
  303. Task.WaitAll(task);
  304. }
  305. finally
  306. {
  307. // No need to start if scanning the library because it will handle it
  308. if (!request.RefreshLibrary)
  309. {
  310. _directoryWatchers.Start();
  311. }
  312. _directoryWatchers.RemoveTempIgnore(currentPath);
  313. _directoryWatchers.RemoveTempIgnore(newPath);
  314. }
  315. if (request.RefreshLibrary)
  316. {
  317. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  318. }
  319. }
  320. /// <summary>
  321. /// Deletes the specified request.
  322. /// </summary>
  323. /// <param name="request">The request.</param>
  324. public void Delete(RemoveVirtualFolder request)
  325. {
  326. string rootFolderPath;
  327. if (string.IsNullOrEmpty(request.UserId))
  328. {
  329. rootFolderPath = _appPaths.DefaultUserViewsPath;
  330. }
  331. else
  332. {
  333. var user = _userManager.GetUserById(new Guid(request.UserId));
  334. rootFolderPath = user.RootFolderPath;
  335. }
  336. var path = Path.Combine(rootFolderPath, request.Name);
  337. if (!Directory.Exists(path))
  338. {
  339. throw new DirectoryNotFoundException("The media folder does not exist");
  340. }
  341. _directoryWatchers.Stop();
  342. _directoryWatchers.TemporarilyIgnore(path);
  343. try
  344. {
  345. Directory.Delete(path, true);
  346. // Need to add a delay here or directory watchers may still pick up the changes
  347. var delayTask = Task.Delay(1000);
  348. // Have to block here to allow exceptions to bubble
  349. Task.WaitAll(delayTask);
  350. }
  351. finally
  352. {
  353. // No need to start if scanning the library because it will handle it
  354. if (!request.RefreshLibrary)
  355. {
  356. _directoryWatchers.Start();
  357. }
  358. _directoryWatchers.RemoveTempIgnore(path);
  359. }
  360. if (request.RefreshLibrary)
  361. {
  362. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  363. }
  364. }
  365. /// <summary>
  366. /// Posts the specified request.
  367. /// </summary>
  368. /// <param name="request">The request.</param>
  369. public void Post(AddMediaPath request)
  370. {
  371. _directoryWatchers.Stop();
  372. try
  373. {
  374. if (string.IsNullOrEmpty(request.UserId))
  375. {
  376. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  377. }
  378. else
  379. {
  380. var user = _userManager.GetUserById(new Guid(request.UserId));
  381. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, user, _appPaths);
  382. }
  383. // Need to add a delay here or directory watchers may still pick up the changes
  384. var task = Task.Delay(1000);
  385. // Have to block here to allow exceptions to bubble
  386. Task.WaitAll(task);
  387. }
  388. finally
  389. {
  390. // No need to start if scanning the library because it will handle it
  391. if (!request.RefreshLibrary)
  392. {
  393. _directoryWatchers.Start();
  394. }
  395. }
  396. if (request.RefreshLibrary)
  397. {
  398. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  399. }
  400. }
  401. /// <summary>
  402. /// Deletes the specified request.
  403. /// </summary>
  404. /// <param name="request">The request.</param>
  405. public void Delete(RemoveMediaPath request)
  406. {
  407. _directoryWatchers.Stop();
  408. try
  409. {
  410. if (string.IsNullOrEmpty(request.UserId))
  411. {
  412. LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  413. }
  414. else
  415. {
  416. var user = _userManager.GetUserById(new Guid(request.UserId));
  417. LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, user, _appPaths);
  418. }
  419. // Need to add a delay here or directory watchers may still pick up the changes
  420. var task = Task.Delay(1000);
  421. // Have to block here to allow exceptions to bubble
  422. Task.WaitAll(task);
  423. }
  424. finally
  425. {
  426. // No need to start if scanning the library because it will handle it
  427. if (!request.RefreshLibrary)
  428. {
  429. _directoryWatchers.Start();
  430. }
  431. }
  432. if (request.RefreshLibrary)
  433. {
  434. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  435. }
  436. }
  437. }
  438. }