LibraryStructureService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.ServiceHost;
  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. _directoryWatchers.Start();
  248. _directoryWatchers.RemoveTempIgnore(virtualFolderPath);
  249. }
  250. if (request.RefreshLibrary)
  251. {
  252. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  253. }
  254. }
  255. /// <summary>
  256. /// Posts the specified request.
  257. /// </summary>
  258. /// <param name="request">The request.</param>
  259. public void Post(RenameVirtualFolder request)
  260. {
  261. string rootFolderPath;
  262. if (string.IsNullOrEmpty(request.UserId))
  263. {
  264. rootFolderPath = _appPaths.DefaultUserViewsPath;
  265. }
  266. else
  267. {
  268. var user = _userManager.GetUserById(new Guid(request.UserId));
  269. rootFolderPath = user.RootFolderPath;
  270. }
  271. var currentPath = Path.Combine(rootFolderPath, request.Name);
  272. var newPath = Path.Combine(rootFolderPath, request.NewName);
  273. if (!Directory.Exists(currentPath))
  274. {
  275. throw new DirectoryNotFoundException("The media collection does not exist");
  276. }
  277. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  278. {
  279. throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
  280. }
  281. _directoryWatchers.Stop();
  282. _directoryWatchers.TemporarilyIgnore(currentPath);
  283. _directoryWatchers.TemporarilyIgnore(newPath);
  284. try
  285. {
  286. // Only make a two-phase move when changing capitalization
  287. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  288. {
  289. //Create an unique name
  290. var temporaryName = Guid.NewGuid().ToString();
  291. var temporaryPath = Path.Combine(rootFolderPath, temporaryName);
  292. Directory.Move(currentPath, temporaryPath);
  293. currentPath = temporaryPath;
  294. }
  295. Directory.Move(currentPath, newPath);
  296. // Need to add a delay here or directory watchers may still pick up the changes
  297. var task = Task.Delay(1000);
  298. // Have to block here to allow exceptions to bubble
  299. Task.WaitAll(task);
  300. }
  301. finally
  302. {
  303. _directoryWatchers.Start();
  304. _directoryWatchers.RemoveTempIgnore(currentPath);
  305. _directoryWatchers.RemoveTempIgnore(newPath);
  306. }
  307. if (request.RefreshLibrary)
  308. {
  309. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  310. }
  311. }
  312. /// <summary>
  313. /// Deletes the specified request.
  314. /// </summary>
  315. /// <param name="request">The request.</param>
  316. public void Delete(RemoveVirtualFolder request)
  317. {
  318. string rootFolderPath;
  319. if (string.IsNullOrEmpty(request.UserId))
  320. {
  321. rootFolderPath = _appPaths.DefaultUserViewsPath;
  322. }
  323. else
  324. {
  325. var user = _userManager.GetUserById(new Guid(request.UserId));
  326. rootFolderPath = user.RootFolderPath;
  327. }
  328. var path = Path.Combine(rootFolderPath, request.Name);
  329. if (!Directory.Exists(path))
  330. {
  331. throw new DirectoryNotFoundException("The media folder does not exist");
  332. }
  333. _directoryWatchers.Stop();
  334. _directoryWatchers.TemporarilyIgnore(path);
  335. try
  336. {
  337. Directory.Delete(path, true);
  338. // Need to add a delay here or directory watchers may still pick up the changes
  339. var delayTask = Task.Delay(1000);
  340. // Have to block here to allow exceptions to bubble
  341. Task.WaitAll(delayTask);
  342. }
  343. finally
  344. {
  345. _directoryWatchers.Start();
  346. _directoryWatchers.RemoveTempIgnore(path);
  347. }
  348. if (request.RefreshLibrary)
  349. {
  350. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  351. }
  352. }
  353. /// <summary>
  354. /// Posts the specified request.
  355. /// </summary>
  356. /// <param name="request">The request.</param>
  357. public void Post(AddMediaPath request)
  358. {
  359. _directoryWatchers.Stop();
  360. try
  361. {
  362. if (string.IsNullOrEmpty(request.UserId))
  363. {
  364. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  365. }
  366. else
  367. {
  368. var user = _userManager.GetUserById(new Guid(request.UserId));
  369. LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, user, _appPaths);
  370. }
  371. // Need to add a delay here or directory watchers may still pick up the changes
  372. var task = Task.Delay(1000);
  373. // Have to block here to allow exceptions to bubble
  374. Task.WaitAll(task);
  375. }
  376. finally
  377. {
  378. _directoryWatchers.Start();
  379. }
  380. if (request.RefreshLibrary)
  381. {
  382. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  383. }
  384. }
  385. /// <summary>
  386. /// Deletes the specified request.
  387. /// </summary>
  388. /// <param name="request">The request.</param>
  389. public void Delete(RemoveMediaPath request)
  390. {
  391. _directoryWatchers.Stop();
  392. try
  393. {
  394. if (string.IsNullOrEmpty(request.UserId))
  395. {
  396. LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, null, _appPaths);
  397. }
  398. else
  399. {
  400. var user = _userManager.GetUserById(new Guid(request.UserId));
  401. LibraryHelpers.RemoveMediaPath(_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. _directoryWatchers.Start();
  411. }
  412. if (request.RefreshLibrary)
  413. {
  414. _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  415. }
  416. }
  417. }
  418. }