LibraryStructureController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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(CommaDelimitedArrayModelBinder))] 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. /// <returns>A <see cref="NoContentResult"/>.</returns>
  94. [HttpDelete]
  95. [ProducesResponseType(StatusCodes.Status204NoContent)]
  96. public async Task<ActionResult> RemoveVirtualFolder(
  97. [FromQuery] string name,
  98. [FromQuery] bool refreshLibrary = false)
  99. {
  100. await _libraryManager.RemoveVirtualFolder(name, refreshLibrary).ConfigureAwait(false);
  101. return NoContent();
  102. }
  103. /// <summary>
  104. /// Renames a virtual folder.
  105. /// </summary>
  106. /// <param name="name">The name of the virtual folder.</param>
  107. /// <param name="newName">The new name.</param>
  108. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  109. /// <response code="204">Folder renamed.</response>
  110. /// <response code="404">Library doesn't exist.</response>
  111. /// <response code="409">Library already exists.</response>
  112. /// <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>
  113. /// <exception cref="ArgumentNullException">The new name may not be null.</exception>
  114. [HttpPost("Name")]
  115. [ProducesResponseType(StatusCodes.Status204NoContent)]
  116. [ProducesResponseType(StatusCodes.Status404NotFound)]
  117. [ProducesResponseType(StatusCodes.Status409Conflict)]
  118. public ActionResult RenameVirtualFolder(
  119. [FromQuery] string? name,
  120. [FromQuery] string? newName,
  121. [FromQuery] bool refreshLibrary = false)
  122. {
  123. if (string.IsNullOrWhiteSpace(name))
  124. {
  125. throw new ArgumentNullException(nameof(name));
  126. }
  127. if (string.IsNullOrWhiteSpace(newName))
  128. {
  129. throw new ArgumentNullException(nameof(newName));
  130. }
  131. var rootFolderPath = _appPaths.DefaultUserViewsPath;
  132. var currentPath = Path.Combine(rootFolderPath, name);
  133. var newPath = Path.Combine(rootFolderPath, newName);
  134. if (!Directory.Exists(currentPath))
  135. {
  136. return NotFound("The media collection does not exist.");
  137. }
  138. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  139. {
  140. return Conflict($"The media library already exists at {newPath}.");
  141. }
  142. _libraryMonitor.Stop();
  143. try
  144. {
  145. // Changing capitalization. Handle windows case insensitivity
  146. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  147. {
  148. var tempPath = Path.Combine(
  149. rootFolderPath,
  150. Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
  151. Directory.Move(currentPath, tempPath);
  152. currentPath = tempPath;
  153. }
  154. Directory.Move(currentPath, newPath);
  155. }
  156. finally
  157. {
  158. CollectionFolder.OnCollectionFolderChange();
  159. Task.Run(async () =>
  160. {
  161. // No need to start if scanning the library because it will handle it
  162. if (refreshLibrary)
  163. {
  164. await _libraryManager.ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
  165. var newLib = _libraryManager.GetUserRootFolder().Children.FirstOrDefault(f => f.Path.Equals(newPath, StringComparison.OrdinalIgnoreCase));
  166. if (newLib is CollectionFolder folder)
  167. {
  168. foreach (var child in folder.GetPhysicalFolders())
  169. {
  170. await child.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  171. await child.ValidateChildren(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  172. }
  173. }
  174. else
  175. {
  176. // We don't know if this one can be validated individually, trigger a new validation
  177. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  178. }
  179. }
  180. else
  181. {
  182. // Need to add a delay here or directory watchers may still pick up the changes
  183. // Have to block here to allow exceptions to bubble
  184. await Task.Delay(1000).ConfigureAwait(false);
  185. _libraryMonitor.Start();
  186. }
  187. });
  188. }
  189. return NoContent();
  190. }
  191. /// <summary>
  192. /// Add a media path to a library.
  193. /// </summary>
  194. /// <param name="mediaPathDto">The media path dto.</param>
  195. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  196. /// <returns>A <see cref="NoContentResult"/>.</returns>
  197. /// <response code="204">Media path added.</response>
  198. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  199. [HttpPost("Paths")]
  200. [ProducesResponseType(StatusCodes.Status204NoContent)]
  201. public ActionResult AddMediaPath(
  202. [FromBody, Required] MediaPathDto mediaPathDto,
  203. [FromQuery] bool refreshLibrary = false)
  204. {
  205. _libraryMonitor.Stop();
  206. try
  207. {
  208. var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));
  209. _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
  210. }
  211. finally
  212. {
  213. Task.Run(async () =>
  214. {
  215. // No need to start if scanning the library because it will handle it
  216. if (refreshLibrary)
  217. {
  218. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  219. }
  220. else
  221. {
  222. // Need to add a delay here or directory watchers may still pick up the changes
  223. // Have to block here to allow exceptions to bubble
  224. await Task.Delay(1000).ConfigureAwait(false);
  225. _libraryMonitor.Start();
  226. }
  227. });
  228. }
  229. return NoContent();
  230. }
  231. /// <summary>
  232. /// Updates a media path.
  233. /// </summary>
  234. /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
  235. /// <returns>A <see cref="NoContentResult"/>.</returns>
  236. /// <response code="204">Media path updated.</response>
  237. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  238. [HttpPost("Paths/Update")]
  239. [ProducesResponseType(StatusCodes.Status204NoContent)]
  240. public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
  241. {
  242. if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
  243. {
  244. throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
  245. }
  246. _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
  247. return NoContent();
  248. }
  249. /// <summary>
  250. /// Remove a media path.
  251. /// </summary>
  252. /// <param name="name">The name of the library.</param>
  253. /// <param name="path">The path to remove.</param>
  254. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  255. /// <returns>A <see cref="NoContentResult"/>.</returns>
  256. /// <response code="204">Media path removed.</response>
  257. /// <exception cref="ArgumentException">The name of the library and path may not be empty.</exception>
  258. [HttpDelete("Paths")]
  259. [ProducesResponseType(StatusCodes.Status204NoContent)]
  260. public ActionResult RemoveMediaPath(
  261. [FromQuery] string name,
  262. [FromQuery] string path,
  263. [FromQuery] bool refreshLibrary = false)
  264. {
  265. ArgumentException.ThrowIfNullOrWhiteSpace(name);
  266. ArgumentException.ThrowIfNullOrWhiteSpace(path);
  267. _libraryMonitor.Stop();
  268. try
  269. {
  270. _libraryManager.RemoveMediaPath(name, path);
  271. }
  272. finally
  273. {
  274. Task.Run(async () =>
  275. {
  276. // No need to start if scanning the library because it will handle it
  277. if (refreshLibrary)
  278. {
  279. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  280. }
  281. else
  282. {
  283. // Need to add a delay here or directory watchers may still pick up the changes
  284. // Have to block here to allow exceptions to bubble
  285. await Task.Delay(1000).ConfigureAwait(false);
  286. _libraryMonitor.Start();
  287. }
  288. });
  289. }
  290. return NoContent();
  291. }
  292. /// <summary>
  293. /// Update library options.
  294. /// </summary>
  295. /// <param name="request">The library name and options.</param>
  296. /// <response code="204">Library updated.</response>
  297. /// <response code="404">Item not found.</response>
  298. /// <returns>A <see cref="NoContentResult"/>.</returns>
  299. [HttpPost("LibraryOptions")]
  300. [ProducesResponseType(StatusCodes.Status204NoContent)]
  301. [ProducesResponseType(StatusCodes.Status404NotFound)]
  302. public ActionResult UpdateLibraryOptions(
  303. [FromBody] UpdateLibraryOptionsDto request)
  304. {
  305. var item = _libraryManager.GetItemById<CollectionFolder>(request.Id);
  306. if (item is null)
  307. {
  308. return NotFound();
  309. }
  310. item.UpdateLibraryOptions(request.LibraryOptions);
  311. return NoContent();
  312. }
  313. }