LibraryStructureController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  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 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. namespace Jellyfin.Api.Controllers
  21. {
  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="libraryOptions">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] string? collectionType,
  73. [FromQuery] string[] paths,
  74. [FromQuery] LibraryOptions? libraryOptions,
  75. [FromQuery] bool refreshLibrary = false)
  76. {
  77. libraryOptions ??= new LibraryOptions();
  78. if (paths != null && paths.Length > 0)
  79. {
  80. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo { Path = 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 SimpleProgress<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="name">The name of the library.</param>
  179. /// <param name="path">The path to add.</param>
  180. /// <param name="pathInfo">The path info.</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. [FromQuery] string? name,
  189. [FromQuery] string? path,
  190. [FromQuery] MediaPathInfo? pathInfo,
  191. [FromQuery] bool refreshLibrary = false)
  192. {
  193. if (string.IsNullOrWhiteSpace(name))
  194. {
  195. throw new ArgumentNullException(nameof(name));
  196. }
  197. _libraryMonitor.Stop();
  198. try
  199. {
  200. var mediaPath = pathInfo ?? new MediaPathInfo { Path = path };
  201. _libraryManager.AddMediaPath(name, mediaPath);
  202. }
  203. finally
  204. {
  205. Task.Run(async () =>
  206. {
  207. // No need to start if scanning the library because it will handle it
  208. if (refreshLibrary)
  209. {
  210. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  211. }
  212. else
  213. {
  214. // Need to add a delay here or directory watchers may still pick up the changes
  215. // Have to block here to allow exceptions to bubble
  216. await Task.Delay(1000).ConfigureAwait(false);
  217. _libraryMonitor.Start();
  218. }
  219. });
  220. }
  221. return NoContent();
  222. }
  223. /// <summary>
  224. /// Updates a media path.
  225. /// </summary>
  226. /// <param name="name">The name of the library.</param>
  227. /// <param name="pathInfo">The path info.</param>
  228. /// <returns>A <see cref="NoContentResult"/>.</returns>
  229. /// <response code="204">Media path updated.</response>
  230. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  231. [HttpPost("Paths/Update")]
  232. [ProducesResponseType(StatusCodes.Status204NoContent)]
  233. public ActionResult UpdateMediaPath(
  234. [FromQuery] string? name,
  235. [FromQuery] MediaPathInfo? pathInfo)
  236. {
  237. if (string.IsNullOrWhiteSpace(name))
  238. {
  239. throw new ArgumentNullException(nameof(name));
  240. }
  241. _libraryManager.UpdateMediaPath(name, pathInfo);
  242. return NoContent();
  243. }
  244. /// <summary>
  245. /// Remove a media path.
  246. /// </summary>
  247. /// <param name="name">The name of the library.</param>
  248. /// <param name="path">The path to remove.</param>
  249. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  250. /// <returns>A <see cref="NoContentResult"/>.</returns>
  251. /// <response code="204">Media path removed.</response>
  252. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  253. [HttpDelete("Paths")]
  254. [ProducesResponseType(StatusCodes.Status204NoContent)]
  255. public ActionResult RemoveMediaPath(
  256. [FromQuery] string? name,
  257. [FromQuery] string? path,
  258. [FromQuery] bool refreshLibrary = false)
  259. {
  260. if (string.IsNullOrWhiteSpace(name))
  261. {
  262. throw new ArgumentNullException(nameof(name));
  263. }
  264. _libraryMonitor.Stop();
  265. try
  266. {
  267. _libraryManager.RemoveMediaPath(name, path);
  268. }
  269. finally
  270. {
  271. Task.Run(async () =>
  272. {
  273. // No need to start if scanning the library because it will handle it
  274. if (refreshLibrary)
  275. {
  276. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  277. }
  278. else
  279. {
  280. // Need to add a delay here or directory watchers may still pick up the changes
  281. // Have to block here to allow exceptions to bubble
  282. await Task.Delay(1000).ConfigureAwait(false);
  283. _libraryMonitor.Start();
  284. }
  285. });
  286. }
  287. return NoContent();
  288. }
  289. /// <summary>
  290. /// Update library options.
  291. /// </summary>
  292. /// <param name="id">The library name.</param>
  293. /// <param name="libraryOptions">The library options.</param>
  294. /// <response code="204">Library updated.</response>
  295. /// <returns>A <see cref="NoContentResult"/>.</returns>
  296. [HttpPost("LibraryOptions")]
  297. [ProducesResponseType(StatusCodes.Status204NoContent)]
  298. public ActionResult UpdateLibraryOptions(
  299. [FromQuery] string? id,
  300. [FromQuery] LibraryOptions? libraryOptions)
  301. {
  302. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(id);
  303. collectionFolder.UpdateLibraryOptions(libraryOptions);
  304. return NoContent();
  305. }
  306. }
  307. }