LibraryStructureController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Constants;
  9. using Jellyfin.Api.Models.LibraryStructureDto;
  10. using MediaBrowser.Common.Progress;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Entities;
  17. using Microsoft.AspNetCore.Authorization;
  18. using Microsoft.AspNetCore.Http;
  19. using Microsoft.AspNetCore.Mvc;
  20. using Microsoft.AspNetCore.Mvc.ModelBinding;
  21. namespace Jellyfin.Api.Controllers
  22. {
  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] string? collectionType,
  74. [FromQuery] string[] paths,
  75. [FromBody] LibraryOptionsDto? libraryOptionsDto,
  76. [FromQuery] bool refreshLibrary = false)
  77. {
  78. var libraryOptions = libraryOptionsDto?.LibraryOptions ?? new LibraryOptions();
  79. if (paths != null && paths.Length > 0)
  80. {
  81. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo { Path = 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, BindRequired] MediaPathDto mediaPathDto,
  188. [FromQuery] bool refreshLibrary = false)
  189. {
  190. _libraryMonitor.Stop();
  191. try
  192. {
  193. var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo { Path = mediaPathDto.Path };
  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="name">The name of the library.</param>
  220. /// <param name="pathInfo">The path info.</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(
  227. [FromQuery] string? name,
  228. [FromBody] MediaPathInfo? pathInfo)
  229. {
  230. if (string.IsNullOrWhiteSpace(name))
  231. {
  232. throw new ArgumentNullException(nameof(name));
  233. }
  234. _libraryManager.UpdateMediaPath(name, pathInfo);
  235. return NoContent();
  236. }
  237. /// <summary>
  238. /// Remove a media path.
  239. /// </summary>
  240. /// <param name="name">The name of the library.</param>
  241. /// <param name="path">The path to remove.</param>
  242. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  243. /// <returns>A <see cref="NoContentResult"/>.</returns>
  244. /// <response code="204">Media path removed.</response>
  245. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  246. [HttpDelete("Paths")]
  247. [ProducesResponseType(StatusCodes.Status204NoContent)]
  248. public ActionResult RemoveMediaPath(
  249. [FromQuery] string? name,
  250. [FromQuery] string? path,
  251. [FromQuery] bool refreshLibrary = false)
  252. {
  253. if (string.IsNullOrWhiteSpace(name))
  254. {
  255. throw new ArgumentNullException(nameof(name));
  256. }
  257. _libraryMonitor.Stop();
  258. try
  259. {
  260. _libraryManager.RemoveMediaPath(name, path);
  261. }
  262. finally
  263. {
  264. Task.Run(async () =>
  265. {
  266. // No need to start if scanning the library because it will handle it
  267. if (refreshLibrary)
  268. {
  269. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  270. }
  271. else
  272. {
  273. // Need to add a delay here or directory watchers may still pick up the changes
  274. // Have to block here to allow exceptions to bubble
  275. await Task.Delay(1000).ConfigureAwait(false);
  276. _libraryMonitor.Start();
  277. }
  278. });
  279. }
  280. return NoContent();
  281. }
  282. /// <summary>
  283. /// Update library options.
  284. /// </summary>
  285. /// <param name="id">The library name.</param>
  286. /// <param name="libraryOptions">The library options.</param>
  287. /// <response code="204">Library updated.</response>
  288. /// <returns>A <see cref="NoContentResult"/>.</returns>
  289. [HttpPost("LibraryOptions")]
  290. [ProducesResponseType(StatusCodes.Status204NoContent)]
  291. public ActionResult UpdateLibraryOptions(
  292. [FromQuery] string? id,
  293. [FromBody] LibraryOptions? libraryOptions)
  294. {
  295. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(id);
  296. collectionFolder.UpdateLibraryOptions(libraryOptions);
  297. return NoContent();
  298. }
  299. }
  300. }