LibraryStructureController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. #nullable enable
  2. #pragma warning disable CA1801
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Api.Constants;
  11. using MediaBrowser.Common.Progress;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Mvc;
  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. /// <param name="userId">The user id.</param>
  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([FromQuery] string userId)
  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="refreshLibrary">Whether to refresh the library.</param>
  66. /// <param name="paths">The paths of the virtual folder.</param>
  67. /// <param name="libraryOptions">The library options.</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] string collectionType,
  75. [FromQuery] bool refreshLibrary,
  76. [FromQuery] string[] paths,
  77. [FromQuery] LibraryOptions libraryOptions)
  78. {
  79. libraryOptions ??= new LibraryOptions();
  80. if (paths != null && paths.Length > 0)
  81. {
  82. libraryOptions.PathInfos = paths.Select(i => new MediaPathInfo { Path = 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)
  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)
  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(() =>
  160. {
  161. // No need to start if scanning the library because it will handle it
  162. if (refreshLibrary)
  163. {
  164. _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
  165. }
  166. else
  167. {
  168. // Need to add a delay here or directory watchers may still pick up the changes
  169. var task = Task.Delay(1000);
  170. // Have to block here to allow exceptions to bubble
  171. Task.WaitAll(task);
  172. _libraryMonitor.Start();
  173. }
  174. });
  175. }
  176. return NoContent();
  177. }
  178. /// <summary>
  179. /// Add a media path to a library.
  180. /// </summary>
  181. /// <param name="name">The name of the library.</param>
  182. /// <param name="path">The path to add.</param>
  183. /// <param name="pathInfo">The path info.</param>
  184. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  185. /// <returns>A <see cref="NoContentResult"/>.</returns>
  186. /// <response code="204">Media path added.</response>
  187. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  188. [HttpPost("Paths")]
  189. [ProducesResponseType(StatusCodes.Status204NoContent)]
  190. public ActionResult AddMediaPath(
  191. [FromQuery] string name,
  192. [FromQuery] string path,
  193. [FromQuery] MediaPathInfo pathInfo,
  194. [FromQuery] bool refreshLibrary)
  195. {
  196. if (string.IsNullOrWhiteSpace(name))
  197. {
  198. throw new ArgumentNullException(nameof(name));
  199. }
  200. _libraryMonitor.Stop();
  201. try
  202. {
  203. var mediaPath = pathInfo ?? new MediaPathInfo { Path = path };
  204. _libraryManager.AddMediaPath(name, mediaPath);
  205. }
  206. finally
  207. {
  208. Task.Run(() =>
  209. {
  210. // No need to start if scanning the library because it will handle it
  211. if (refreshLibrary)
  212. {
  213. _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
  214. }
  215. else
  216. {
  217. // Need to add a delay here or directory watchers may still pick up the changes
  218. var task = Task.Delay(1000);
  219. // Have to block here to allow exceptions to bubble
  220. Task.WaitAll(task);
  221. _libraryMonitor.Start();
  222. }
  223. });
  224. }
  225. return NoContent();
  226. }
  227. /// <summary>
  228. /// Updates a media path.
  229. /// </summary>
  230. /// <param name="name">The name of the library.</param>
  231. /// <param name="pathInfo">The path info.</param>
  232. /// <returns>A <see cref="NoContentResult"/>.</returns>
  233. /// <response code="204">Media path updated.</response>
  234. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  235. [HttpPost("Paths/Update")]
  236. [ProducesResponseType(StatusCodes.Status204NoContent)]
  237. public ActionResult UpdateMediaPath(
  238. [FromQuery] string name,
  239. [FromQuery] MediaPathInfo pathInfo)
  240. {
  241. if (string.IsNullOrWhiteSpace(name))
  242. {
  243. throw new ArgumentNullException(nameof(name));
  244. }
  245. _libraryManager.UpdateMediaPath(name, pathInfo);
  246. return NoContent();
  247. }
  248. /// <summary>
  249. /// Remove a media path.
  250. /// </summary>
  251. /// <param name="name">The name of the library.</param>
  252. /// <param name="path">The path to remove.</param>
  253. /// <param name="refreshLibrary">Whether to refresh the library.</param>
  254. /// <returns>A <see cref="NoContentResult"/>.</returns>
  255. /// <response code="204">Media path removed.</response>
  256. /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
  257. [HttpDelete("Paths")]
  258. [ProducesResponseType(StatusCodes.Status204NoContent)]
  259. public ActionResult RemoveMediaPath(
  260. [FromQuery] string name,
  261. [FromQuery] string path,
  262. [FromQuery] bool refreshLibrary)
  263. {
  264. if (string.IsNullOrWhiteSpace(name))
  265. {
  266. throw new ArgumentNullException(nameof(name));
  267. }
  268. _libraryMonitor.Stop();
  269. try
  270. {
  271. _libraryManager.RemoveMediaPath(name, path);
  272. }
  273. finally
  274. {
  275. Task.Run(() =>
  276. {
  277. // No need to start if scanning the library because it will handle it
  278. if (refreshLibrary)
  279. {
  280. _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
  281. }
  282. else
  283. {
  284. // Need to add a delay here or directory watchers may still pick up the changes
  285. var task = Task.Delay(1000);
  286. // Have to block here to allow exceptions to bubble
  287. Task.WaitAll(task);
  288. _libraryMonitor.Start();
  289. }
  290. });
  291. }
  292. return NoContent();
  293. }
  294. /// <summary>
  295. /// Update library options.
  296. /// </summary>
  297. /// <param name="id">The library name.</param>
  298. /// <param name="libraryOptions">The library options.</param>
  299. /// <response code="204">Library updated.</response>
  300. /// <returns>A <see cref="NoContentResult"/>.</returns>
  301. [HttpPost("LibraryOptions")]
  302. [ProducesResponseType(StatusCodes.Status204NoContent)]
  303. public ActionResult UpdateLibraryOptions(
  304. [FromQuery] string id,
  305. [FromQuery] LibraryOptions libraryOptions)
  306. {
  307. var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(id);
  308. collectionFolder.UpdateLibraryOptions(libraryOptions);
  309. return NoContent();
  310. }
  311. }
  312. }