LibraryStructureController.cs 14 KB

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