LibraryStructureService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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", "POST")]
  30. [Route("/Users/{UserId}/VirtualFolders", "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", "DELETE")]
  55. [Route("/Users/{UserId}/VirtualFolders", "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", "POST")]
  75. [Route("/Users/{UserId}/VirtualFolders/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/Paths", "POST")]
  100. [Route("/Users/{UserId}/VirtualFolders/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/Paths", "DELETE")]
  125. [Route("/Users/{UserId}/VirtualFolders/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. if (string.IsNullOrWhiteSpace(request.Name))
  215. {
  216. throw new ArgumentNullException("request");
  217. }
  218. var name = _fileSystem.GetValidFilename(request.Name);
  219. string rootFolderPath;
  220. if (string.IsNullOrEmpty(request.UserId))
  221. {
  222. rootFolderPath = _appPaths.DefaultUserViewsPath;
  223. }
  224. else
  225. {
  226. var user = _userManager.GetUserById(new Guid(request.UserId));
  227. rootFolderPath = user.RootFolderPath;
  228. }
  229. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  230. if (Directory.Exists(virtualFolderPath))
  231. {
  232. throw new ArgumentException("There is already a media collection with the name " + name + ".");
  233. }
  234. _directoryWatchers.Stop();
  235. _directoryWatchers.TemporarilyIgnore(virtualFolderPath);
  236. try
  237. {
  238. Directory.CreateDirectory(virtualFolderPath);
  239. if (!string.IsNullOrEmpty(request.CollectionType))
  240. {
  241. var path = Path.Combine(virtualFolderPath, request.CollectionType + ".collection");
  242. File.Create(path);
  243. }
  244. // Need to add a delay here or directory watchers may still pick up the changes
  245. var task = Task.Delay(1000);
  246. // Have to block here to allow exceptions to bubble
  247. Task.WaitAll(task);
  248. }
  249. finally
  250. {
  251. // No need to start if scanning the library because it will handle it
  252. if (!request.RefreshLibrary)
  253. {
  254. _directoryWatchers.Start();
  255. }
  256. _directoryWatchers.RemoveTempIgnore(virtualFolderPath);
  257. }
  258. if (request.RefreshLibrary)
  259. {
  260. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  261. }
  262. }
  263. /// <summary>
  264. /// Posts the specified request.
  265. /// </summary>
  266. /// <param name="request">The request.</param>
  267. public void Post(RenameVirtualFolder request)
  268. {
  269. if (string.IsNullOrWhiteSpace(request.Name))
  270. {
  271. throw new ArgumentNullException("request");
  272. }
  273. if (string.IsNullOrWhiteSpace(request.NewName))
  274. {
  275. throw new ArgumentNullException("request");
  276. }
  277. string rootFolderPath;
  278. if (string.IsNullOrEmpty(request.UserId))
  279. {
  280. rootFolderPath = _appPaths.DefaultUserViewsPath;
  281. }
  282. else
  283. {
  284. var user = _userManager.GetUserById(new Guid(request.UserId));
  285. rootFolderPath = user.RootFolderPath;
  286. }
  287. var currentPath = Path.Combine(rootFolderPath, request.Name);
  288. var newPath = Path.Combine(rootFolderPath, request.NewName);
  289. if (!Directory.Exists(currentPath))
  290. {
  291. throw new DirectoryNotFoundException("The media collection does not exist");
  292. }
  293. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  294. {
  295. throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
  296. }
  297. _directoryWatchers.Stop();
  298. _directoryWatchers.TemporarilyIgnore(currentPath);
  299. _directoryWatchers.TemporarilyIgnore(newPath);
  300. try
  301. {
  302. // Only make a two-phase move when changing capitalization
  303. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  304. {
  305. //Create an unique name
  306. var temporaryName = Guid.NewGuid().ToString();
  307. var temporaryPath = Path.Combine(rootFolderPath, temporaryName);
  308. Directory.Move(currentPath, temporaryPath);
  309. currentPath = temporaryPath;
  310. }
  311. Directory.Move(currentPath, newPath);
  312. // Need to add a delay here or directory watchers may still pick up the changes
  313. var task = Task.Delay(1000);
  314. // Have to block here to allow exceptions to bubble
  315. Task.WaitAll(task);
  316. }
  317. finally
  318. {
  319. // No need to start if scanning the library because it will handle it
  320. if (!request.RefreshLibrary)
  321. {
  322. _directoryWatchers.Start();
  323. }
  324. _directoryWatchers.RemoveTempIgnore(currentPath);
  325. _directoryWatchers.RemoveTempIgnore(newPath);
  326. }
  327. if (request.RefreshLibrary)
  328. {
  329. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  330. }
  331. }
  332. /// <summary>
  333. /// Deletes the specified request.
  334. /// </summary>
  335. /// <param name="request">The request.</param>
  336. public void Delete(RemoveVirtualFolder request)
  337. {
  338. if (string.IsNullOrWhiteSpace(request.Name))
  339. {
  340. throw new ArgumentNullException("request");
  341. }
  342. string rootFolderPath;
  343. if (string.IsNullOrEmpty(request.UserId))
  344. {
  345. rootFolderPath = _appPaths.DefaultUserViewsPath;
  346. }
  347. else
  348. {
  349. var user = _userManager.GetUserById(new Guid(request.UserId));
  350. rootFolderPath = user.RootFolderPath;
  351. }
  352. var path = Path.Combine(rootFolderPath, request.Name);
  353. if (!Directory.Exists(path))
  354. {
  355. throw new DirectoryNotFoundException("The media folder does not exist");
  356. }
  357. _directoryWatchers.Stop();
  358. _directoryWatchers.TemporarilyIgnore(path);
  359. try
  360. {
  361. Directory.Delete(path, true);
  362. // Need to add a delay here or directory watchers may still pick up the changes
  363. var delayTask = Task.Delay(1000);
  364. // Have to block here to allow exceptions to bubble
  365. Task.WaitAll(delayTask);
  366. }
  367. finally
  368. {
  369. // No need to start if scanning the library because it will handle it
  370. if (!request.RefreshLibrary)
  371. {
  372. _directoryWatchers.Start();
  373. }
  374. _directoryWatchers.RemoveTempIgnore(path);
  375. }
  376. if (request.RefreshLibrary)
  377. {
  378. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  379. }
  380. }
  381. /// <summary>
  382. /// Posts the specified request.
  383. /// </summary>
  384. /// <param name="request">The request.</param>
  385. public void Post(AddMediaPath request)
  386. {
  387. if (string.IsNullOrWhiteSpace(request.Name))
  388. {
  389. throw new ArgumentNullException("request");
  390. }
  391. _directoryWatchers.Stop();
  392. try
  393. {
  394. if (string.IsNullOrEmpty(request.UserId))
  395. {
  396. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  397. }
  398. else
  399. {
  400. var user = _userManager.GetUserById(new Guid(request.UserId));
  401. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, user, _appPaths);
  402. }
  403. // Need to add a delay here or directory watchers may still pick up the changes
  404. var task = Task.Delay(1000);
  405. // Have to block here to allow exceptions to bubble
  406. Task.WaitAll(task);
  407. }
  408. finally
  409. {
  410. // No need to start if scanning the library because it will handle it
  411. if (!request.RefreshLibrary)
  412. {
  413. _directoryWatchers.Start();
  414. }
  415. }
  416. if (request.RefreshLibrary)
  417. {
  418. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  419. }
  420. }
  421. /// <summary>
  422. /// Deletes the specified request.
  423. /// </summary>
  424. /// <param name="request">The request.</param>
  425. public void Delete(RemoveMediaPath request)
  426. {
  427. if (string.IsNullOrWhiteSpace(request.Name))
  428. {
  429. throw new ArgumentNullException("request");
  430. }
  431. _directoryWatchers.Stop();
  432. try
  433. {
  434. if (string.IsNullOrEmpty(request.UserId))
  435. {
  436. LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  437. }
  438. else
  439. {
  440. var user = _userManager.GetUserById(new Guid(request.UserId));
  441. LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, user, _appPaths);
  442. }
  443. // Need to add a delay here or directory watchers may still pick up the changes
  444. var task = Task.Delay(1000);
  445. // Have to block here to allow exceptions to bubble
  446. Task.WaitAll(task);
  447. }
  448. finally
  449. {
  450. // No need to start if scanning the library because it will handle it
  451. if (!request.RefreshLibrary)
  452. {
  453. _directoryWatchers.Start();
  454. }
  455. }
  456. if (request.RefreshLibrary)
  457. {
  458. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  459. }
  460. }
  461. }
  462. }