LibraryStructureController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #pragma warning disable CA1801
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Api.Constants;
  10. using MediaBrowser.Common.Progress;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Entities;
  17. using Microsoft.AspNetCore.Authorization;
  18. using Microsoft.AspNetCore.Http;
  19. using Microsoft.AspNetCore.Mvc;
  20. namespace Jellyfin.Api.Controllers
  21. {
  22. /// <summary>
  23. /// The library structure controller.
  24. /// </summary>
  25. [Route("/Library/VirtualFolders")]
  26. [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
  27. public class LibraryStructureController : BaseJellyfinApiController
  28. {
  29. private readonly IServerApplicationPaths _appPaths;
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly ILibraryMonitor _libraryMonitor;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="LibraryStructureController"/> class.
  34. /// </summary>
  35. /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
  36. /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
  37. /// <param name="libraryMonitor">Instance of <see cref="ILibraryMonitor"/> interface.</param>
  38. public LibraryStructureController(
  39. IServerConfigurationManager serverConfigurationManager,
  40. ILibraryManager libraryManager,
  41. ILibraryMonitor libraryMonitor)
  42. {
  43. _appPaths = serverConfigurationManager.ApplicationPaths;
  44. _libraryManager = libraryManager;
  45. _libraryMonitor = libraryMonitor;
  46. }
  47. /// <summary>
  48. /// Gets all virtual folders.
  49. /// </summary>
  50. /// <param name="userId">The user id.</param>
  51. /// <response code="200">Virtual folders retrieved.</response>
  52. /// <returns>An <see cref="IEnumerable{VirtualFolderInfo}"/> with the virtual folders.</returns>
  53. [HttpGet]
  54. [ProducesResponseType(StatusCodes.Status200OK)]
  55. public ActionResult<IEnumerable<VirtualFolderInfo>> GetVirtualFolders([FromQuery] string userId)
  56. {
  57. return _libraryManager.GetVirtualFolders(true);
  58. }
  59. /// <summary>
  60. /// Adds a virtual folder.
  61. /// </summary>
  62. /// <param name="name">The name of the virtual folder.</param>
  63. /// <param name="collectionType">The type of the collection.</param>
  64. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  65. /// <param name="paths">The paths of the virtual folder.</param>
  66. /// <param name="libraryOptions">The library options.</param>
  67. /// <response code="204">Folder added.</response>
  68. /// <returns>A <see cref="NoContentResult"/>.</returns>
  69. [HttpPost]
  70. [ProducesResponseType(StatusCodes.Status204NoContent)]
  71. public async Task<ActionResult> AddVirtualFolder(
  72. [FromQuery] string name,
  73. [FromQuery] string collectionType,
  74. [FromQuery] bool refreshLibrary,
  75. [FromQuery] string[] paths,
  76. [FromQuery] LibraryOptions libraryOptions)
  77. {
  78. libraryOptions ??= new LibraryOptions();
  79. if (paths != null && paths.Length > 0)
  80. {
  81. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo { Path = i }).ToArray();
  82. }
  83. await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false);
  84. return NoContent();
  85. }
  86. /// <summary>
  87. /// Removes a virtual folder.
  88. /// </summary>
  89. /// <param name="name">The name of the folder.</param>
  90. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  91. /// <response code="204">Folder removed.</response>
  92. /// <returns>A <see cref="NoContentResult"/>.</returns>
  93. [HttpDelete]
  94. [ProducesResponseType(StatusCodes.Status204NoContent)]
  95. public async Task<ActionResult> RemoveVirtualFolder(
  96. [FromQuery] string name,
  97. [FromQuery] bool refreshLibrary)
  98. {
  99. await _libraryManager.RemoveVirtualFolder(name, refreshLibrary).ConfigureAwait(false);
  100. return NoContent();
  101. }
  102. /// <summary>
  103. /// Renames a virtual folder.
  104. /// </summary>
  105. /// <param name="name">The name of the virtual folder.</param>
  106. /// <param name="newName">The new name.</param>
  107. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  108. /// <response code="204">Folder renamed.</response>
  109. /// <response code="404">Library doesn't exist.</response>
  110. /// <response code="409">Library already exists.</response>
  111. /// <returns>A <see cref="NoContentResult"/> on success, a <see cref="NotFoundResult"/> if the library doesn't exist, a <see cref="ConflictResult"/> if the new name is already taken.</returns>
  112. /// <exception cref="ArgumentNullException">The new name may not be null.</exception>
  113. [HttpPost("Name")]
  114. [ProducesResponseType(StatusCodes.Status204NoContent)]
  115. [ProducesResponseType(StatusCodes.Status404NotFound)]
  116. [ProducesResponseType(StatusCodes.Status409Conflict)]
  117. public ActionResult RenameVirtualFolder(
  118. [FromQuery] string name,
  119. [FromQuery] string newName,
  120. [FromQuery] bool refreshLibrary)
  121. {
  122. if (string.IsNullOrWhiteSpace(name))
  123. {
  124. throw new ArgumentNullException(nameof(name));
  125. }
  126. if (string.IsNullOrWhiteSpace(newName))
  127. {
  128. throw new ArgumentNullException(nameof(newName));
  129. }
  130. var rootFolderPath = _appPaths.DefaultUserViewsPath;
  131. var currentPath = Path.Combine(rootFolderPath, name);
  132. var newPath = Path.Combine(rootFolderPath, newName);
  133. if (!Directory.Exists(currentPath))
  134. {
  135. return NotFound("The media collection does not exist.");
  136. }
  137. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  138. {
  139. return Conflict($"The media library already exists at {newPath}.");
  140. }
  141. _libraryMonitor.Stop();
  142. try
  143. {
  144. // Changing capitalization. Handle windows case insensitivity
  145. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  146. {
  147. var tempPath = Path.Combine(
  148. rootFolderPath,
  149. Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
  150. Directory.Move(currentPath, tempPath);
  151. currentPath = tempPath;
  152. }
  153. Directory.Move(currentPath, newPath);
  154. }
  155. finally
  156. {
  157. CollectionFolder.OnCollectionFolderChange();
  158. Task.Run(async () =>
  159. {
  160. // No need to start if scanning the library because it will handle it
  161. if (refreshLibrary)
  162. {
  163. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  164. }
  165. else
  166. {
  167. // Need to add a delay here or directory watchers may still pick up the changes
  168. // Have to block here to allow exceptions to bubble
  169. await Task.Delay(1000).ConfigureAwait(false);
  170. _libraryMonitor.Start();
  171. }
  172. });
  173. }
  174. return NoContent();
  175. }
  176. /// <summary>
  177. /// Add a media path to a library.
  178. /// </summary>
  179. /// <param name="name">The name of the library.</param>
  180. /// <param name="path">The path to add.</param>
  181. /// <param name="pathInfo">The path info.</param>
  182. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  183. /// <returns>A <see cref="NoContentResult"/>.</returns>
  184. /// <response code="204">Media path added.</response>
  185. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  186. [HttpPost("Paths")]
  187. [ProducesResponseType(StatusCodes.Status204NoContent)]
  188. public ActionResult AddMediaPath(
  189. [FromQuery] string name,
  190. [FromQuery] string path,
  191. [FromQuery] MediaPathInfo pathInfo,
  192. [FromQuery] bool refreshLibrary)
  193. {
  194. if (string.IsNullOrWhiteSpace(name))
  195. {
  196. throw new ArgumentNullException(nameof(name));
  197. }
  198. _libraryMonitor.Stop();
  199. try
  200. {
  201. var mediaPath = pathInfo ?? new MediaPathInfo { Path = path };
  202. _libraryManager.AddMediaPath(name, mediaPath);
  203. }
  204. finally
  205. {
  206. Task.Run(async () =>
  207. {
  208. // No need to start if scanning the library because it will handle it
  209. if (refreshLibrary)
  210. {
  211. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  212. }
  213. else
  214. {
  215. // Need to add a delay here or directory watchers may still pick up the changes
  216. // Have to block here to allow exceptions to bubble
  217. await Task.Delay(1000).ConfigureAwait(false);
  218. _libraryMonitor.Start();
  219. }
  220. });
  221. }
  222. return NoContent();
  223. }
  224. /// <summary>
  225. /// Updates a media path.
  226. /// </summary>
  227. /// <param name="name">The name of the library.</param>
  228. /// <param name="pathInfo">The path info.</param>
  229. /// <returns>A <see cref="NoContentResult"/>.</returns>
  230. /// <response code="204">Media path updated.</response>
  231. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  232. [HttpPost("Paths/Update")]
  233. [ProducesResponseType(StatusCodes.Status204NoContent)]
  234. public ActionResult UpdateMediaPath(
  235. [FromQuery] string name,
  236. [FromQuery] MediaPathInfo pathInfo)
  237. {
  238. if (string.IsNullOrWhiteSpace(name))
  239. {
  240. throw new ArgumentNullException(nameof(name));
  241. }
  242. _libraryManager.UpdateMediaPath(name, pathInfo);
  243. return NoContent();
  244. }
  245. /// <summary>
  246. /// Remove a media path.
  247. /// </summary>
  248. /// <param name="name">The name of the library.</param>
  249. /// <param name="path">The path to remove.</param>
  250. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  251. /// <returns>A <see cref="NoContentResult"/>.</returns>
  252. /// <response code="204">Media path removed.</response>
  253. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  254. [HttpDelete("Paths")]
  255. [ProducesResponseType(StatusCodes.Status204NoContent)]
  256. public ActionResult RemoveMediaPath(
  257. [FromQuery] string name,
  258. [FromQuery] string path,
  259. [FromQuery] bool refreshLibrary)
  260. {
  261. if (string.IsNullOrWhiteSpace(name))
  262. {
  263. throw new ArgumentNullException(nameof(name));
  264. }
  265. _libraryMonitor.Stop();
  266. try
  267. {
  268. _libraryManager.RemoveMediaPath(name, path);
  269. }
  270. finally
  271. {
  272. Task.Run(async () =>
  273. {
  274. // No need to start if scanning the library because it will handle it
  275. if (refreshLibrary)
  276. {
  277. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  278. }
  279. else
  280. {
  281. // Need to add a delay here or directory watchers may still pick up the changes
  282. // Have to block here to allow exceptions to bubble
  283. await Task.Delay(1000).ConfigureAwait(false);
  284. _libraryMonitor.Start();
  285. }
  286. });
  287. }
  288. return NoContent();
  289. }
  290. /// <summary>
  291. /// Update library options.
  292. /// </summary>
  293. /// <param name="id">The library name.</param>
  294. /// <param name="libraryOptions">The library options.</param>
  295. /// <response code="204">Library updated.</response>
  296. /// <returns>A <see cref="NoContentResult"/>.</returns>
  297. [HttpPost("LibraryOptions")]
  298. [ProducesResponseType(StatusCodes.Status204NoContent)]
  299. public ActionResult UpdateLibraryOptions(
  300. [FromQuery] string id,
  301. [FromQuery] LibraryOptions libraryOptions)
  302. {
  303. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(id);
  304. collectionFolder.UpdateLibraryOptions(libraryOptions);
  305. return NoContent();
  306. }
  307. }
  308. }