LibraryStructureController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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.Constants;
  10. using Jellyfin.Api.ModelBinders;
  11. using Jellyfin.Api.Models.LibraryStructureDto;
  12. using MediaBrowser.Common.Progress;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Entities;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Http;
  21. using Microsoft.AspNetCore.Mvc;
  22. namespace Jellyfin.Api.Controllers;
  23. /// <summary>
  24. /// The library structure controller.
  25. /// </summary>
  26. [Route("Library/VirtualFolders")]
  27. [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
  28. public class LibraryStructureController : BaseJellyfinApiController
  29. {
  30. private readonly IServerApplicationPaths _appPaths;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly ILibraryMonitor _libraryMonitor;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="LibraryStructureController"/> class.
  35. /// </summary>
  36. /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
  37. /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
  38. /// <param name="libraryMonitor">Instance of <see cref="ILibraryMonitor"/> interface.</param>
  39. public LibraryStructureController(
  40. IServerConfigurationManager serverConfigurationManager,
  41. ILibraryManager libraryManager,
  42. ILibraryMonitor libraryMonitor)
  43. {
  44. _appPaths = serverConfigurationManager.ApplicationPaths;
  45. _libraryManager = libraryManager;
  46. _libraryMonitor = libraryMonitor;
  47. }
  48. /// <summary>
  49. /// Gets all virtual folders.
  50. /// </summary>
  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()
  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="paths">The paths of the virtual folder.</param>
  65. /// <param name="libraryOptionsDto">The library options.</param>
  66. /// <param name="refreshLibrary">Whether to refresh the library.</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] CollectionTypeOptions? collectionType,
  74. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths,
  75. [FromBody] AddVirtualFolderDto? libraryOptionsDto,
  76. [FromQuery] bool refreshLibrary = false)
  77. {
  78. var libraryOptions = libraryOptionsDto?.LibraryOptions ?? new LibraryOptions();
  79. if (paths is not null && paths.Length > 0)
  80. {
  81. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo(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 = false)
  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 = false)
  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="mediaPathDto">The media path dto.</param>
  180. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  181. /// <returns>A <see cref="NoContentResult"/>.</returns>
  182. /// <response code="204">Media path added.</response>
  183. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  184. [HttpPost("Paths")]
  185. [ProducesResponseType(StatusCodes.Status204NoContent)]
  186. public ActionResult AddMediaPath(
  187. [FromBody, Required] MediaPathDto mediaPathDto,
  188. [FromQuery] bool refreshLibrary = false)
  189. {
  190. _libraryMonitor.Stop();
  191. try
  192. {
  193. var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));
  194. _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
  195. }
  196. finally
  197. {
  198. Task.Run(async () =>
  199. {
  200. // No need to start if scanning the library because it will handle it
  201. if (refreshLibrary)
  202. {
  203. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  204. }
  205. else
  206. {
  207. // Need to add a delay here or directory watchers may still pick up the changes
  208. // Have to block here to allow exceptions to bubble
  209. await Task.Delay(1000).ConfigureAwait(false);
  210. _libraryMonitor.Start();
  211. }
  212. });
  213. }
  214. return NoContent();
  215. }
  216. /// <summary>
  217. /// Updates a media path.
  218. /// </summary>
  219. /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
  220. /// <returns>A <see cref="NoContentResult"/>.</returns>
  221. /// <response code="204">Media path updated.</response>
  222. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  223. [HttpPost("Paths/Update")]
  224. [ProducesResponseType(StatusCodes.Status204NoContent)]
  225. public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
  226. {
  227. if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
  228. {
  229. throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
  230. }
  231. _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
  232. return NoContent();
  233. }
  234. /// <summary>
  235. /// Remove a media path.
  236. /// </summary>
  237. /// <param name="name">The name of the library.</param>
  238. /// <param name="path">The path to remove.</param>
  239. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  240. /// <returns>A <see cref="NoContentResult"/>.</returns>
  241. /// <response code="204">Media path removed.</response>
  242. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  243. [HttpDelete("Paths")]
  244. [ProducesResponseType(StatusCodes.Status204NoContent)]
  245. public ActionResult RemoveMediaPath(
  246. [FromQuery] string? name,
  247. [FromQuery] string? path,
  248. [FromQuery] bool refreshLibrary = false)
  249. {
  250. if (string.IsNullOrWhiteSpace(name))
  251. {
  252. throw new ArgumentNullException(nameof(name));
  253. }
  254. _libraryMonitor.Stop();
  255. try
  256. {
  257. _libraryManager.RemoveMediaPath(name, path);
  258. }
  259. finally
  260. {
  261. Task.Run(async () =>
  262. {
  263. // No need to start if scanning the library because it will handle it
  264. if (refreshLibrary)
  265. {
  266. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  267. }
  268. else
  269. {
  270. // Need to add a delay here or directory watchers may still pick up the changes
  271. // Have to block here to allow exceptions to bubble
  272. await Task.Delay(1000).ConfigureAwait(false);
  273. _libraryMonitor.Start();
  274. }
  275. });
  276. }
  277. return NoContent();
  278. }
  279. /// <summary>
  280. /// Update library options.
  281. /// </summary>
  282. /// <param name="request">The library name and options.</param>
  283. /// <response code="204">Library updated.</response>
  284. /// <returns>A <see cref="NoContentResult"/>.</returns>
  285. [HttpPost("LibraryOptions")]
  286. [ProducesResponseType(StatusCodes.Status204NoContent)]
  287. public ActionResult UpdateLibraryOptions(
  288. [FromBody] UpdateLibraryOptionsDto request)
  289. {
  290. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(request.Id);
  291. collectionFolder.UpdateLibraryOptions(request.LibraryOptions);
  292. return NoContent();
  293. }
  294. }