LibraryStructureController.cs 14 KB

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