LibraryStructureController.cs 14 KB

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