LibraryStructureController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. {
  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 = paths.Select(i => new MediaPathInfo(i)).ToArray();
  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.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  165. }
  166. else
  167. {
  168. // Need to add a delay here or directory watchers may still pick up the changes
  169. // Have to block here to allow exceptions to bubble
  170. await Task.Delay(1000).ConfigureAwait(false);
  171. _libraryMonitor.Start();
  172. }
  173. });
  174. }
  175. return NoContent();
  176. }
  177. /// <summary>
  178. /// Add a media path to a library.
  179. /// </summary>
  180. /// <param name="mediaPathDto">The media path dto.</param>
  181. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  182. /// <returns>A <see cref="NoContentResult"/>.</returns>
  183. /// <response code="204">Media path added.</response>
  184. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  185. [HttpPost("Paths")]
  186. [ProducesResponseType(StatusCodes.Status204NoContent)]
  187. public ActionResult AddMediaPath(
  188. [FromBody, Required] MediaPathDto mediaPathDto,
  189. [FromQuery] bool refreshLibrary = false)
  190. {
  191. _libraryMonitor.Stop();
  192. try
  193. {
  194. var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));
  195. _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
  196. }
  197. finally
  198. {
  199. Task.Run(async () =>
  200. {
  201. // No need to start if scanning the library because it will handle it
  202. if (refreshLibrary)
  203. {
  204. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  205. }
  206. else
  207. {
  208. // Need to add a delay here or directory watchers may still pick up the changes
  209. // Have to block here to allow exceptions to bubble
  210. await Task.Delay(1000).ConfigureAwait(false);
  211. _libraryMonitor.Start();
  212. }
  213. });
  214. }
  215. return NoContent();
  216. }
  217. /// <summary>
  218. /// Updates a media path.
  219. /// </summary>
  220. /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
  221. /// <returns>A <see cref="NoContentResult"/>.</returns>
  222. /// <response code="204">Media path updated.</response>
  223. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  224. [HttpPost("Paths/Update")]
  225. [ProducesResponseType(StatusCodes.Status204NoContent)]
  226. public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
  227. {
  228. if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
  229. {
  230. throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
  231. }
  232. _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
  233. return NoContent();
  234. }
  235. /// <summary>
  236. /// Remove a media path.
  237. /// </summary>
  238. /// <param name="name">The name of the library.</param>
  239. /// <param name="path">The path to remove.</param>
  240. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  241. /// <returns>A <see cref="NoContentResult"/>.</returns>
  242. /// <response code="204">Media path removed.</response>
  243. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  244. [HttpDelete("Paths")]
  245. [ProducesResponseType(StatusCodes.Status204NoContent)]
  246. public ActionResult RemoveMediaPath(
  247. [FromQuery] string? name,
  248. [FromQuery] string? path,
  249. [FromQuery] bool refreshLibrary = false)
  250. {
  251. if (string.IsNullOrWhiteSpace(name))
  252. {
  253. throw new ArgumentNullException(nameof(name));
  254. }
  255. _libraryMonitor.Stop();
  256. try
  257. {
  258. _libraryManager.RemoveMediaPath(name, path);
  259. }
  260. finally
  261. {
  262. Task.Run(async () =>
  263. {
  264. // No need to start if scanning the library because it will handle it
  265. if (refreshLibrary)
  266. {
  267. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  268. }
  269. else
  270. {
  271. // Need to add a delay here or directory watchers may still pick up the changes
  272. // Have to block here to allow exceptions to bubble
  273. await Task.Delay(1000).ConfigureAwait(false);
  274. _libraryMonitor.Start();
  275. }
  276. });
  277. }
  278. return NoContent();
  279. }
  280. /// <summary>
  281. /// Update library options.
  282. /// </summary>
  283. /// <param name="request">The library name and options.</param>
  284. /// <response code="204">Library updated.</response>
  285. /// <returns>A <see cref="NoContentResult"/>.</returns>
  286. [HttpPost("LibraryOptions")]
  287. [ProducesResponseType(StatusCodes.Status204NoContent)]
  288. public ActionResult UpdateLibraryOptions(
  289. [FromBody] UpdateLibraryOptionsDto request)
  290. {
  291. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(request.Id);
  292. collectionFolder.UpdateLibraryOptions(request.LibraryOptions);
  293. return NoContent();
  294. }
  295. }
  296. }