LibraryStructureController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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.ModelBinders;
  10. using Jellyfin.Api.Models.LibraryStructureDto;
  11. using MediaBrowser.Common.Api;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Mvc;
  21. namespace Jellyfin.Api.Controllers;
  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. /// <response code="200">Virtual folders retrieved.</response>
  51. /// <returns>An <see cref="IEnumerable{VirtualFolderInfo}"/> with the virtual folders.</returns>
  52. [HttpGet]
  53. [ProducesResponseType(StatusCodes.Status200OK)]
  54. public ActionResult<IEnumerable<VirtualFolderInfo>> GetVirtualFolders()
  55. {
  56. return _libraryManager.GetVirtualFolders(true);
  57. }
  58. /// <summary>
  59. /// Adds a virtual folder.
  60. /// </summary>
  61. /// <param name="name">The name of the virtual folder.</param>
  62. /// <param name="collectionType">The type of the collection.</param>
  63. /// <param name="paths">The paths of the virtual folder.</param>
  64. /// <param name="libraryOptionsDto">The library options.</param>
  65. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  66. /// <response code="204">Folder added.</response>
  67. /// <returns>A <see cref="NoContentResult"/>.</returns>
  68. [HttpPost]
  69. [ProducesResponseType(StatusCodes.Status204NoContent)]
  70. public async Task<ActionResult> AddVirtualFolder(
  71. [FromQuery] string? name,
  72. [FromQuery] CollectionTypeOptions? collectionType,
  73. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths,
  74. [FromBody] AddVirtualFolderDto? libraryOptionsDto,
  75. [FromQuery] bool refreshLibrary = false)
  76. {
  77. var libraryOptions = libraryOptionsDto?.LibraryOptions ?? new LibraryOptions();
  78. if (paths is not null && paths.Length > 0)
  79. {
  80. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo(i)).ToArray();
  81. }
  82. await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false);
  83. return NoContent();
  84. }
  85. /// <summary>
  86. /// Removes a virtual folder.
  87. /// </summary>
  88. /// <param name="name">The name of the folder.</param>
  89. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  90. /// <response code="204">Folder removed.</response>
  91. /// <returns>A <see cref="NoContentResult"/>.</returns>
  92. [HttpDelete]
  93. [ProducesResponseType(StatusCodes.Status204NoContent)]
  94. public async Task<ActionResult> RemoveVirtualFolder(
  95. [FromQuery] string? name,
  96. [FromQuery] bool refreshLibrary = false)
  97. {
  98. await _libraryManager.RemoveVirtualFolder(name, refreshLibrary).ConfigureAwait(false);
  99. return NoContent();
  100. }
  101. /// <summary>
  102. /// Renames a virtual folder.
  103. /// </summary>
  104. /// <param name="name">The name of the virtual folder.</param>
  105. /// <param name="newName">The new name.</param>
  106. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  107. /// <response code="204">Folder renamed.</response>
  108. /// <response code="404">Library doesn't exist.</response>
  109. /// <response code="409">Library already exists.</response>
  110. /// <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>
  111. /// <exception cref="ArgumentNullException">The new name may not be null.</exception>
  112. [HttpPost("Name")]
  113. [ProducesResponseType(StatusCodes.Status204NoContent)]
  114. [ProducesResponseType(StatusCodes.Status404NotFound)]
  115. [ProducesResponseType(StatusCodes.Status409Conflict)]
  116. public ActionResult RenameVirtualFolder(
  117. [FromQuery] string? name,
  118. [FromQuery] string? newName,
  119. [FromQuery] bool refreshLibrary = false)
  120. {
  121. if (string.IsNullOrWhiteSpace(name))
  122. {
  123. throw new ArgumentNullException(nameof(name));
  124. }
  125. if (string.IsNullOrWhiteSpace(newName))
  126. {
  127. throw new ArgumentNullException(nameof(newName));
  128. }
  129. var rootFolderPath = _appPaths.DefaultUserViewsPath;
  130. var currentPath = Path.Combine(rootFolderPath, name);
  131. var newPath = Path.Combine(rootFolderPath, newName);
  132. if (!Directory.Exists(currentPath))
  133. {
  134. return NotFound("The media collection does not exist.");
  135. }
  136. if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
  137. {
  138. return Conflict($"The media library already exists at {newPath}.");
  139. }
  140. _libraryMonitor.Stop();
  141. try
  142. {
  143. // Changing capitalization. Handle windows case insensitivity
  144. if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
  145. {
  146. var tempPath = Path.Combine(
  147. rootFolderPath,
  148. Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
  149. Directory.Move(currentPath, tempPath);
  150. currentPath = tempPath;
  151. }
  152. Directory.Move(currentPath, newPath);
  153. }
  154. finally
  155. {
  156. CollectionFolder.OnCollectionFolderChange();
  157. Task.Run(async () =>
  158. {
  159. // No need to start if scanning the library because it will handle it
  160. if (refreshLibrary)
  161. {
  162. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  163. }
  164. else
  165. {
  166. // Need to add a delay here or directory watchers may still pick up the changes
  167. // Have to block here to allow exceptions to bubble
  168. await Task.Delay(1000).ConfigureAwait(false);
  169. _libraryMonitor.Start();
  170. }
  171. });
  172. }
  173. return NoContent();
  174. }
  175. /// <summary>
  176. /// Add a media path to a library.
  177. /// </summary>
  178. /// <param name="mediaPathDto">The media path dto.</param>
  179. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  180. /// <returns>A <see cref="NoContentResult"/>.</returns>
  181. /// <response code="204">Media path added.</response>
  182. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  183. [HttpPost("Paths")]
  184. [ProducesResponseType(StatusCodes.Status204NoContent)]
  185. public ActionResult AddMediaPath(
  186. [FromBody, Required] MediaPathDto mediaPathDto,
  187. [FromQuery] bool refreshLibrary = false)
  188. {
  189. _libraryMonitor.Stop();
  190. try
  191. {
  192. var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));
  193. _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
  194. }
  195. finally
  196. {
  197. Task.Run(async () =>
  198. {
  199. // No need to start if scanning the library because it will handle it
  200. if (refreshLibrary)
  201. {
  202. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  203. }
  204. else
  205. {
  206. // Need to add a delay here or directory watchers may still pick up the changes
  207. // Have to block here to allow exceptions to bubble
  208. await Task.Delay(1000).ConfigureAwait(false);
  209. _libraryMonitor.Start();
  210. }
  211. });
  212. }
  213. return NoContent();
  214. }
  215. /// <summary>
  216. /// Updates a media path.
  217. /// </summary>
  218. /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
  219. /// <returns>A <see cref="NoContentResult"/>.</returns>
  220. /// <response code="204">Media path updated.</response>
  221. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  222. [HttpPost("Paths/Update")]
  223. [ProducesResponseType(StatusCodes.Status204NoContent)]
  224. public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
  225. {
  226. if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
  227. {
  228. throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
  229. }
  230. _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
  231. return NoContent();
  232. }
  233. /// <summary>
  234. /// Remove a media path.
  235. /// </summary>
  236. /// <param name="name">The name of the library.</param>
  237. /// <param name="path">The path to remove.</param>
  238. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  239. /// <returns>A <see cref="NoContentResult"/>.</returns>
  240. /// <response code="204">Media path removed.</response>
  241. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  242. [HttpDelete("Paths")]
  243. [ProducesResponseType(StatusCodes.Status204NoContent)]
  244. public ActionResult RemoveMediaPath(
  245. [FromQuery] string? name,
  246. [FromQuery] string? path,
  247. [FromQuery] bool refreshLibrary = false)
  248. {
  249. if (string.IsNullOrWhiteSpace(name))
  250. {
  251. throw new ArgumentNullException(nameof(name));
  252. }
  253. _libraryMonitor.Stop();
  254. try
  255. {
  256. _libraryManager.RemoveMediaPath(name, path);
  257. }
  258. finally
  259. {
  260. Task.Run(async () =>
  261. {
  262. // No need to start if scanning the library because it will handle it
  263. if (refreshLibrary)
  264. {
  265. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
  266. }
  267. else
  268. {
  269. // Need to add a delay here or directory watchers may still pick up the changes
  270. // Have to block here to allow exceptions to bubble
  271. await Task.Delay(1000).ConfigureAwait(false);
  272. _libraryMonitor.Start();
  273. }
  274. });
  275. }
  276. return NoContent();
  277. }
  278. /// <summary>
  279. /// Update library options.
  280. /// </summary>
  281. /// <param name="request">The library name and options.</param>
  282. /// <response code="204">Library updated.</response>
  283. /// <returns>A <see cref="NoContentResult"/>.</returns>
  284. [HttpPost("LibraryOptions")]
  285. [ProducesResponseType(StatusCodes.Status204NoContent)]
  286. public ActionResult UpdateLibraryOptions(
  287. [FromBody] UpdateLibraryOptionsDto request)
  288. {
  289. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(request.Id);
  290. collectionFolder.UpdateLibraryOptions(request.LibraryOptions);
  291. return NoContent();
  292. }
  293. }