LibraryStructureController.cs 14 KB

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