LibraryController.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Api.Attributes;
  12. using Jellyfin.Api.Constants;
  13. using Jellyfin.Api.Extensions;
  14. using Jellyfin.Api.ModelBinders;
  15. using Jellyfin.Api.Models.LibraryDtos;
  16. using Jellyfin.Data.Entities;
  17. using Jellyfin.Data.Enums;
  18. using MediaBrowser.Common.Progress;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Controller.Dto;
  21. using MediaBrowser.Controller.Entities;
  22. using MediaBrowser.Controller.Entities.Audio;
  23. using MediaBrowser.Controller.Entities.Movies;
  24. using MediaBrowser.Controller.Entities.TV;
  25. using MediaBrowser.Controller.Library;
  26. using MediaBrowser.Controller.LiveTv;
  27. using MediaBrowser.Controller.Net;
  28. using MediaBrowser.Controller.Providers;
  29. using MediaBrowser.Model.Activity;
  30. using MediaBrowser.Model.Configuration;
  31. using MediaBrowser.Model.Dto;
  32. using MediaBrowser.Model.Entities;
  33. using MediaBrowser.Model.Globalization;
  34. using MediaBrowser.Model.Net;
  35. using MediaBrowser.Model.Querying;
  36. using Microsoft.AspNetCore.Authorization;
  37. using Microsoft.AspNetCore.Http;
  38. using Microsoft.AspNetCore.Mvc;
  39. using Microsoft.Extensions.Logging;
  40. using Book = MediaBrowser.Controller.Entities.Book;
  41. namespace Jellyfin.Api.Controllers
  42. {
  43. /// <summary>
  44. /// Library Controller.
  45. /// </summary>
  46. [Route("")]
  47. public class LibraryController : BaseJellyfinApiController
  48. {
  49. private readonly IProviderManager _providerManager;
  50. private readonly ILibraryManager _libraryManager;
  51. private readonly IUserManager _userManager;
  52. private readonly IDtoService _dtoService;
  53. private readonly IAuthorizationContext _authContext;
  54. private readonly IActivityManager _activityManager;
  55. private readonly ILocalizationManager _localization;
  56. private readonly ILibraryMonitor _libraryMonitor;
  57. private readonly ILogger<LibraryController> _logger;
  58. private readonly IServerConfigurationManager _serverConfigurationManager;
  59. /// <summary>
  60. /// Initializes a new instance of the <see cref="LibraryController"/> class.
  61. /// </summary>
  62. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  63. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  64. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  65. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  66. /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
  67. /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
  68. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  69. /// <param name="libraryMonitor">Instance of the <see cref="ILibraryMonitor"/> interface.</param>
  70. /// <param name="logger">Instance of the <see cref="ILogger{LibraryController}"/> interface.</param>
  71. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  72. public LibraryController(
  73. IProviderManager providerManager,
  74. ILibraryManager libraryManager,
  75. IUserManager userManager,
  76. IDtoService dtoService,
  77. IAuthorizationContext authContext,
  78. IActivityManager activityManager,
  79. ILocalizationManager localization,
  80. ILibraryMonitor libraryMonitor,
  81. ILogger<LibraryController> logger,
  82. IServerConfigurationManager serverConfigurationManager)
  83. {
  84. _providerManager = providerManager;
  85. _libraryManager = libraryManager;
  86. _userManager = userManager;
  87. _dtoService = dtoService;
  88. _authContext = authContext;
  89. _activityManager = activityManager;
  90. _localization = localization;
  91. _libraryMonitor = libraryMonitor;
  92. _logger = logger;
  93. _serverConfigurationManager = serverConfigurationManager;
  94. }
  95. /// <summary>
  96. /// Get the original file of an item.
  97. /// </summary>
  98. /// <param name="itemId">The item id.</param>
  99. /// <response code="200">File stream returned.</response>
  100. /// <response code="404">Item not found.</response>
  101. /// <returns>A <see cref="FileStreamResult"/> with the original file.</returns>
  102. [HttpGet("Items/{itemId}/File")]
  103. [Authorize(Policy = Policies.DefaultAuthorization)]
  104. [ProducesResponseType(StatusCodes.Status200OK)]
  105. [ProducesResponseType(StatusCodes.Status404NotFound)]
  106. [ProducesFile("video/*", "audio/*")]
  107. public ActionResult GetFile([FromRoute, Required] Guid itemId)
  108. {
  109. var item = _libraryManager.GetItemById(itemId);
  110. if (item == null)
  111. {
  112. return NotFound();
  113. }
  114. return PhysicalFile(item.Path, MimeTypes.GetMimeType(item.Path), true);
  115. }
  116. /// <summary>
  117. /// Gets critic review for an item.
  118. /// </summary>
  119. /// <response code="200">Critic reviews returned.</response>
  120. /// <returns>The list of critic reviews.</returns>
  121. [HttpGet("Items/{itemId}/CriticReviews")]
  122. [Authorize(Policy = Policies.DefaultAuthorization)]
  123. [Obsolete("This endpoint is obsolete.")]
  124. [ProducesResponseType(StatusCodes.Status200OK)]
  125. public ActionResult<QueryResult<BaseItemDto>> GetCriticReviews()
  126. {
  127. return new QueryResult<BaseItemDto>();
  128. }
  129. /// <summary>
  130. /// Get theme songs for an item.
  131. /// </summary>
  132. /// <param name="itemId">The item id.</param>
  133. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  134. /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
  135. /// <response code="200">Theme songs returned.</response>
  136. /// <response code="404">Item not found.</response>
  137. /// <returns>The item theme songs.</returns>
  138. [HttpGet("Items/{itemId}/ThemeSongs")]
  139. [Authorize(Policy = Policies.DefaultAuthorization)]
  140. [ProducesResponseType(StatusCodes.Status200OK)]
  141. [ProducesResponseType(StatusCodes.Status404NotFound)]
  142. public ActionResult<ThemeMediaResult> GetThemeSongs(
  143. [FromRoute, Required] Guid itemId,
  144. [FromQuery] Guid? userId,
  145. [FromQuery] bool inheritFromParent = false)
  146. {
  147. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  148. ? _userManager.GetUserById(userId.Value)
  149. : null;
  150. var item = itemId.Equals(Guid.Empty)
  151. ? (!userId.Equals(Guid.Empty)
  152. ? _libraryManager.GetUserRootFolder()
  153. : _libraryManager.RootFolder)
  154. : _libraryManager.GetItemById(itemId);
  155. if (item == null)
  156. {
  157. return NotFound("Item not found.");
  158. }
  159. IEnumerable<BaseItem> themeItems;
  160. while (true)
  161. {
  162. themeItems = item.GetThemeSongs();
  163. if (themeItems.Any() || !inheritFromParent)
  164. {
  165. break;
  166. }
  167. var parent = item.GetParent();
  168. if (parent == null)
  169. {
  170. break;
  171. }
  172. item = parent;
  173. }
  174. var dtoOptions = new DtoOptions().AddClientFields(Request);
  175. var items = themeItems
  176. .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
  177. .ToArray();
  178. return new ThemeMediaResult
  179. {
  180. Items = items,
  181. TotalRecordCount = items.Length,
  182. OwnerId = item.Id
  183. };
  184. }
  185. /// <summary>
  186. /// Get theme videos for an item.
  187. /// </summary>
  188. /// <param name="itemId">The item id.</param>
  189. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  190. /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
  191. /// <response code="200">Theme videos returned.</response>
  192. /// <response code="404">Item not found.</response>
  193. /// <returns>The item theme videos.</returns>
  194. [HttpGet("Items/{itemId}/ThemeVideos")]
  195. [Authorize(Policy = Policies.DefaultAuthorization)]
  196. [ProducesResponseType(StatusCodes.Status200OK)]
  197. [ProducesResponseType(StatusCodes.Status404NotFound)]
  198. public ActionResult<ThemeMediaResult> GetThemeVideos(
  199. [FromRoute, Required] Guid itemId,
  200. [FromQuery] Guid? userId,
  201. [FromQuery] bool inheritFromParent = false)
  202. {
  203. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  204. ? _userManager.GetUserById(userId.Value)
  205. : null;
  206. var item = itemId.Equals(Guid.Empty)
  207. ? (!userId.Equals(Guid.Empty)
  208. ? _libraryManager.GetUserRootFolder()
  209. : _libraryManager.RootFolder)
  210. : _libraryManager.GetItemById(itemId);
  211. if (item == null)
  212. {
  213. return NotFound("Item not found.");
  214. }
  215. IEnumerable<BaseItem> themeItems;
  216. while (true)
  217. {
  218. themeItems = item.GetThemeVideos();
  219. if (themeItems.Any() || !inheritFromParent)
  220. {
  221. break;
  222. }
  223. var parent = item.GetParent();
  224. if (parent == null)
  225. {
  226. break;
  227. }
  228. item = parent;
  229. }
  230. var dtoOptions = new DtoOptions().AddClientFields(Request);
  231. var items = themeItems
  232. .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
  233. .ToArray();
  234. return new ThemeMediaResult
  235. {
  236. Items = items,
  237. TotalRecordCount = items.Length,
  238. OwnerId = item.Id
  239. };
  240. }
  241. /// <summary>
  242. /// Get theme songs and videos for an item.
  243. /// </summary>
  244. /// <param name="itemId">The item id.</param>
  245. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  246. /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
  247. /// <response code="200">Theme songs and videos returned.</response>
  248. /// <response code="404">Item not found.</response>
  249. /// <returns>The item theme videos.</returns>
  250. [HttpGet("Items/{itemId}/ThemeMedia")]
  251. [Authorize(Policy = Policies.DefaultAuthorization)]
  252. [ProducesResponseType(StatusCodes.Status200OK)]
  253. public ActionResult<AllThemeMediaResult> GetThemeMedia(
  254. [FromRoute, Required] Guid itemId,
  255. [FromQuery] Guid? userId,
  256. [FromQuery] bool inheritFromParent = false)
  257. {
  258. var themeSongs = GetThemeSongs(
  259. itemId,
  260. userId,
  261. inheritFromParent);
  262. var themeVideos = GetThemeVideos(
  263. itemId,
  264. userId,
  265. inheritFromParent);
  266. return new AllThemeMediaResult
  267. {
  268. ThemeSongsResult = themeSongs?.Value,
  269. ThemeVideosResult = themeVideos?.Value,
  270. SoundtrackSongsResult = new ThemeMediaResult()
  271. };
  272. }
  273. /// <summary>
  274. /// Starts a library scan.
  275. /// </summary>
  276. /// <response code="204">Library scan started.</response>
  277. /// <returns>A <see cref="NoContentResult"/>.</returns>
  278. [HttpPost("Library/Refresh")]
  279. [Authorize(Policy = Policies.RequiresElevation)]
  280. [ProducesResponseType(StatusCodes.Status204NoContent)]
  281. public async Task<ActionResult> RefreshLibrary()
  282. {
  283. try
  284. {
  285. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  286. }
  287. catch (Exception ex)
  288. {
  289. _logger.LogError(ex, "Error refreshing library");
  290. }
  291. return NoContent();
  292. }
  293. /// <summary>
  294. /// Deletes an item from the library and filesystem.
  295. /// </summary>
  296. /// <param name="itemId">The item id.</param>
  297. /// <response code="204">Item deleted.</response>
  298. /// <response code="401">Unauthorized access.</response>
  299. /// <returns>A <see cref="NoContentResult"/>.</returns>
  300. [HttpDelete("Items/{itemId}")]
  301. [Authorize(Policy = Policies.DefaultAuthorization)]
  302. [ProducesResponseType(StatusCodes.Status204NoContent)]
  303. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  304. public async Task<ActionResult> DeleteItem(Guid itemId)
  305. {
  306. var item = _libraryManager.GetItemById(itemId);
  307. var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
  308. var user = auth.User;
  309. if (!item.CanDelete(user))
  310. {
  311. return Unauthorized("Unauthorized access");
  312. }
  313. _libraryManager.DeleteItem(
  314. item,
  315. new DeleteOptions { DeleteFileLocation = true },
  316. true);
  317. return NoContent();
  318. }
  319. /// <summary>
  320. /// Deletes items from the library and filesystem.
  321. /// </summary>
  322. /// <param name="ids">The item ids.</param>
  323. /// <response code="204">Items deleted.</response>
  324. /// <response code="401">Unauthorized access.</response>
  325. /// <returns>A <see cref="NoContentResult"/>.</returns>
  326. [HttpDelete("Items")]
  327. [Authorize(Policy = Policies.DefaultAuthorization)]
  328. [ProducesResponseType(StatusCodes.Status204NoContent)]
  329. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  330. public async Task<ActionResult> DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
  331. {
  332. if (ids.Length == 0)
  333. {
  334. return NoContent();
  335. }
  336. foreach (var i in ids)
  337. {
  338. var item = _libraryManager.GetItemById(i);
  339. var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
  340. var user = auth.User;
  341. if (!item.CanDelete(user))
  342. {
  343. if (ids.Length > 1)
  344. {
  345. return Unauthorized("Unauthorized access");
  346. }
  347. continue;
  348. }
  349. _libraryManager.DeleteItem(
  350. item,
  351. new DeleteOptions { DeleteFileLocation = true },
  352. true);
  353. }
  354. return NoContent();
  355. }
  356. /// <summary>
  357. /// Get item counts.
  358. /// </summary>
  359. /// <param name="userId">Optional. Get counts from a specific user's library.</param>
  360. /// <param name="isFavorite">Optional. Get counts of favorite items.</param>
  361. /// <response code="200">Item counts returned.</response>
  362. /// <returns>Item counts.</returns>
  363. [HttpGet("Items/Counts")]
  364. [Authorize(Policy = Policies.DefaultAuthorization)]
  365. [ProducesResponseType(StatusCodes.Status200OK)]
  366. public ActionResult<ItemCounts> GetItemCounts(
  367. [FromQuery] Guid? userId,
  368. [FromQuery] bool? isFavorite)
  369. {
  370. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  371. ? _userManager.GetUserById(userId.Value)
  372. : null;
  373. var counts = new ItemCounts
  374. {
  375. AlbumCount = GetCount(BaseItemKind.MusicAlbum, user, isFavorite),
  376. EpisodeCount = GetCount(BaseItemKind.Episode, user, isFavorite),
  377. MovieCount = GetCount(BaseItemKind.Movie, user, isFavorite),
  378. SeriesCount = GetCount(BaseItemKind.Series, user, isFavorite),
  379. SongCount = GetCount(BaseItemKind.Audio, user, isFavorite),
  380. MusicVideoCount = GetCount(BaseItemKind.MusicVideo, user, isFavorite),
  381. BoxSetCount = GetCount(BaseItemKind.BoxSet, user, isFavorite),
  382. BookCount = GetCount(BaseItemKind.Book, user, isFavorite)
  383. };
  384. return counts;
  385. }
  386. /// <summary>
  387. /// Gets all parents of an item.
  388. /// </summary>
  389. /// <param name="itemId">The item id.</param>
  390. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  391. /// <response code="200">Item parents returned.</response>
  392. /// <response code="404">Item not found.</response>
  393. /// <returns>Item parents.</returns>
  394. [HttpGet("Items/{itemId}/Ancestors")]
  395. [Authorize(Policy = Policies.DefaultAuthorization)]
  396. [ProducesResponseType(StatusCodes.Status200OK)]
  397. [ProducesResponseType(StatusCodes.Status404NotFound)]
  398. public ActionResult<IEnumerable<BaseItemDto>> GetAncestors([FromRoute, Required] Guid itemId, [FromQuery] Guid? userId)
  399. {
  400. var item = _libraryManager.GetItemById(itemId);
  401. if (item == null)
  402. {
  403. return NotFound("Item not found");
  404. }
  405. var baseItemDtos = new List<BaseItemDto>();
  406. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  407. ? _userManager.GetUserById(userId.Value)
  408. : null;
  409. var dtoOptions = new DtoOptions().AddClientFields(Request);
  410. BaseItem? parent = item.GetParent();
  411. while (parent != null)
  412. {
  413. if (user != null)
  414. {
  415. parent = TranslateParentItem(parent, user);
  416. }
  417. baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
  418. parent = parent?.GetParent();
  419. }
  420. return baseItemDtos;
  421. }
  422. /// <summary>
  423. /// Gets a list of physical paths from virtual folders.
  424. /// </summary>
  425. /// <response code="200">Physical paths returned.</response>
  426. /// <returns>List of physical paths.</returns>
  427. [HttpGet("Library/PhysicalPaths")]
  428. [Authorize(Policy = Policies.RequiresElevation)]
  429. [ProducesResponseType(StatusCodes.Status200OK)]
  430. public ActionResult<IEnumerable<string>> GetPhysicalPaths()
  431. {
  432. return Ok(_libraryManager.RootFolder.Children
  433. .SelectMany(c => c.PhysicalLocations));
  434. }
  435. /// <summary>
  436. /// Gets all user media folders.
  437. /// </summary>
  438. /// <param name="isHidden">Optional. Filter by folders that are marked hidden, or not.</param>
  439. /// <response code="200">Media folders returned.</response>
  440. /// <returns>List of user media folders.</returns>
  441. [HttpGet("Library/MediaFolders")]
  442. [Authorize(Policy = Policies.DefaultAuthorization)]
  443. [ProducesResponseType(StatusCodes.Status200OK)]
  444. public ActionResult<QueryResult<BaseItemDto>> GetMediaFolders([FromQuery] bool? isHidden)
  445. {
  446. var items = _libraryManager.GetUserRootFolder().Children.Concat(_libraryManager.RootFolder.VirtualChildren).OrderBy(i => i.SortName).ToList();
  447. if (isHidden.HasValue)
  448. {
  449. var val = isHidden.Value;
  450. items = items.Where(i => i.IsHidden == val).ToList();
  451. }
  452. var dtoOptions = new DtoOptions().AddClientFields(Request);
  453. var result = new QueryResult<BaseItemDto>
  454. {
  455. TotalRecordCount = items.Count,
  456. Items = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions)).ToArray()
  457. };
  458. return result;
  459. }
  460. /// <summary>
  461. /// Reports that new episodes of a series have been added by an external source.
  462. /// </summary>
  463. /// <param name="tvdbId">The tvdbId.</param>
  464. /// <response code="204">Report success.</response>
  465. /// <returns>A <see cref="NoContentResult"/>.</returns>
  466. [HttpPost("Library/Series/Added", Name = "PostAddedSeries")]
  467. [HttpPost("Library/Series/Updated")]
  468. [Authorize(Policy = Policies.DefaultAuthorization)]
  469. [ProducesResponseType(StatusCodes.Status204NoContent)]
  470. public ActionResult PostUpdatedSeries([FromQuery] string? tvdbId)
  471. {
  472. var series = _libraryManager.GetItemList(new InternalItemsQuery
  473. {
  474. IncludeItemTypes = new[] { BaseItemKind.Series },
  475. DtoOptions = new DtoOptions(false)
  476. {
  477. EnableImages = false
  478. }
  479. }).Where(i => string.Equals(tvdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tvdb), StringComparison.OrdinalIgnoreCase)).ToArray();
  480. foreach (var item in series)
  481. {
  482. _libraryMonitor.ReportFileSystemChanged(item.Path);
  483. }
  484. return NoContent();
  485. }
  486. /// <summary>
  487. /// Reports that new movies have been added by an external source.
  488. /// </summary>
  489. /// <param name="tmdbId">The tmdbId.</param>
  490. /// <param name="imdbId">The imdbId.</param>
  491. /// <response code="204">Report success.</response>
  492. /// <returns>A <see cref="NoContentResult"/>.</returns>
  493. [HttpPost("Library/Movies/Added", Name = "PostAddedMovies")]
  494. [HttpPost("Library/Movies/Updated")]
  495. [Authorize(Policy = Policies.DefaultAuthorization)]
  496. [ProducesResponseType(StatusCodes.Status204NoContent)]
  497. public ActionResult PostUpdatedMovies([FromQuery] string? tmdbId, [FromQuery] string? imdbId)
  498. {
  499. var movies = _libraryManager.GetItemList(new InternalItemsQuery
  500. {
  501. IncludeItemTypes = new[] { BaseItemKind.Movie },
  502. DtoOptions = new DtoOptions(false)
  503. {
  504. EnableImages = false
  505. }
  506. });
  507. if (!string.IsNullOrWhiteSpace(imdbId))
  508. {
  509. movies = movies.Where(i => string.Equals(imdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Imdb), StringComparison.OrdinalIgnoreCase)).ToList();
  510. }
  511. else if (!string.IsNullOrWhiteSpace(tmdbId))
  512. {
  513. movies = movies.Where(i => string.Equals(tmdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tmdb), StringComparison.OrdinalIgnoreCase)).ToList();
  514. }
  515. else
  516. {
  517. movies = new List<BaseItem>();
  518. }
  519. foreach (var item in movies)
  520. {
  521. _libraryMonitor.ReportFileSystemChanged(item.Path);
  522. }
  523. return NoContent();
  524. }
  525. /// <summary>
  526. /// Reports that new movies have been added by an external source.
  527. /// </summary>
  528. /// <param name="dto">The update paths.</param>
  529. /// <response code="204">Report success.</response>
  530. /// <returns>A <see cref="NoContentResult"/>.</returns>
  531. [HttpPost("Library/Media/Updated")]
  532. [Authorize(Policy = Policies.DefaultAuthorization)]
  533. [ProducesResponseType(StatusCodes.Status204NoContent)]
  534. public ActionResult PostUpdatedMedia([FromBody, Required] MediaUpdateInfoDto dto)
  535. {
  536. foreach (var item in dto.Updates)
  537. {
  538. _libraryMonitor.ReportFileSystemChanged(item.Path ?? throw new ArgumentException("Item path can't be null."));
  539. }
  540. return NoContent();
  541. }
  542. /// <summary>
  543. /// Downloads item media.
  544. /// </summary>
  545. /// <param name="itemId">The item id.</param>
  546. /// <response code="200">Media downloaded.</response>
  547. /// <response code="404">Item not found.</response>
  548. /// <returns>A <see cref="FileResult"/> containing the media stream.</returns>
  549. /// <exception cref="ArgumentException">User can't download or item can't be downloaded.</exception>
  550. [HttpGet("Items/{itemId}/Download")]
  551. [Authorize(Policy = Policies.Download)]
  552. [ProducesResponseType(StatusCodes.Status200OK)]
  553. [ProducesResponseType(StatusCodes.Status404NotFound)]
  554. [ProducesFile("video/*", "audio/*")]
  555. public async Task<ActionResult> GetDownload([FromRoute, Required] Guid itemId)
  556. {
  557. var item = _libraryManager.GetItemById(itemId);
  558. if (item == null)
  559. {
  560. return NotFound();
  561. }
  562. var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
  563. var user = auth.User;
  564. if (user != null)
  565. {
  566. if (!item.CanDownload(user))
  567. {
  568. throw new ArgumentException("Item does not support downloading");
  569. }
  570. }
  571. else
  572. {
  573. if (!item.CanDownload())
  574. {
  575. throw new ArgumentException("Item does not support downloading");
  576. }
  577. }
  578. if (user != null)
  579. {
  580. await LogDownloadAsync(item, user, auth).ConfigureAwait(false);
  581. }
  582. var path = item.Path;
  583. // Quotes are valid in linux. They'll possibly cause issues here
  584. var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty, StringComparison.Ordinal);
  585. if (!string.IsNullOrWhiteSpace(filename))
  586. {
  587. // Kestrel doesn't support non-ASCII characters in headers
  588. if (Regex.IsMatch(filename, @"[^\p{IsBasicLatin}]"))
  589. {
  590. // Manually encoding non-ASCII characters, following https://tools.ietf.org/html/rfc5987#section-3.2.2
  591. filename = WebUtility.UrlEncode(filename);
  592. }
  593. }
  594. // TODO determine non-ASCII validity.
  595. return PhysicalFile(path, MimeTypes.GetMimeType(path), filename, true);
  596. }
  597. /// <summary>
  598. /// Gets similar items.
  599. /// </summary>
  600. /// <param name="itemId">The item id.</param>
  601. /// <param name="excludeArtistIds">Exclude artist ids.</param>
  602. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  603. /// <param name="limit">Optional. The maximum number of records to return.</param>
  604. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param>
  605. /// <response code="200">Similar items returned.</response>
  606. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns>
  607. [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists")]
  608. [HttpGet("Items/{itemId}/Similar")]
  609. [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums")]
  610. [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows")]
  611. [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies")]
  612. [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers")]
  613. [Authorize(Policy = Policies.DefaultAuthorization)]
  614. [ProducesResponseType(StatusCodes.Status200OK)]
  615. public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems(
  616. [FromRoute, Required] Guid itemId,
  617. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
  618. [FromQuery] Guid? userId,
  619. [FromQuery] int? limit,
  620. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
  621. {
  622. var item = itemId.Equals(Guid.Empty)
  623. ? (!userId.Equals(Guid.Empty)
  624. ? _libraryManager.GetUserRootFolder()
  625. : _libraryManager.RootFolder)
  626. : _libraryManager.GetItemById(itemId);
  627. if (item is Episode || (item is IItemByName && item is not MusicArtist))
  628. {
  629. return new QueryResult<BaseItemDto>();
  630. }
  631. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  632. ? _userManager.GetUserById(userId.Value)
  633. : null;
  634. var dtoOptions = new DtoOptions { Fields = fields }
  635. .AddClientFields(Request);
  636. var program = item as IHasProgramAttributes;
  637. bool? isMovie = item is Movie || (program != null && program.IsMovie) || item is Trailer;
  638. bool? isSeries = item is Series || (program != null && program.IsSeries);
  639. var includeItemTypes = new List<BaseItemKind>();
  640. if (isMovie.Value)
  641. {
  642. includeItemTypes.Add(BaseItemKind.Movie);
  643. if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
  644. {
  645. includeItemTypes.Add(BaseItemKind.Trailer);
  646. includeItemTypes.Add(BaseItemKind.LiveTvProgram);
  647. }
  648. }
  649. else if (isSeries.Value)
  650. {
  651. includeItemTypes.Add(BaseItemKind.Series);
  652. }
  653. else
  654. {
  655. // For non series and movie types these columns are typically null
  656. isSeries = null;
  657. isMovie = null;
  658. includeItemTypes.Add(item.GetBaseItemKind());
  659. }
  660. var query = new InternalItemsQuery(user)
  661. {
  662. Genres = item.Genres,
  663. Limit = limit,
  664. IncludeItemTypes = includeItemTypes.ToArray(),
  665. SimilarTo = item,
  666. DtoOptions = dtoOptions,
  667. EnableTotalRecordCount = !isMovie ?? true,
  668. EnableGroupByMetadataKey = isMovie ?? false,
  669. MinSimilarityScore = 2 // A remnant from album/artist scoring
  670. };
  671. // ExcludeArtistIds
  672. if (excludeArtistIds.Length != 0)
  673. {
  674. query.ExcludeArtistIds = excludeArtistIds;
  675. }
  676. List<BaseItem> itemsResult = _libraryManager.GetItemList(query);
  677. var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
  678. return new QueryResult<BaseItemDto>
  679. {
  680. Items = returnList,
  681. TotalRecordCount = itemsResult.Count
  682. };
  683. }
  684. /// <summary>
  685. /// Gets the library options info.
  686. /// </summary>
  687. /// <param name="libraryContentType">Library content type.</param>
  688. /// <param name="isNewLibrary">Whether this is a new library.</param>
  689. /// <response code="200">Library options info returned.</response>
  690. /// <returns>Library options info.</returns>
  691. [HttpGet("Libraries/AvailableOptions")]
  692. [Authorize(Policy = Policies.FirstTimeSetupOrDefault)]
  693. [ProducesResponseType(StatusCodes.Status200OK)]
  694. public ActionResult<LibraryOptionsResultDto> GetLibraryOptionsInfo(
  695. [FromQuery] string? libraryContentType,
  696. [FromQuery] bool isNewLibrary = false)
  697. {
  698. var result = new LibraryOptionsResultDto();
  699. var types = GetRepresentativeItemTypes(libraryContentType);
  700. var typesList = types.ToList();
  701. var plugins = _providerManager.GetAllMetadataPlugins()
  702. .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
  703. .OrderBy(i => typesList.IndexOf(i.ItemType))
  704. .ToList();
  705. result.MetadataSavers = plugins
  706. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
  707. .Select(i => new LibraryOptionInfoDto
  708. {
  709. Name = i.Name,
  710. DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
  711. })
  712. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  713. .Select(x => x.First())
  714. .ToArray();
  715. result.MetadataReaders = plugins
  716. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
  717. .Select(i => new LibraryOptionInfoDto
  718. {
  719. Name = i.Name,
  720. DefaultEnabled = true
  721. })
  722. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  723. .Select(x => x.First())
  724. .ToArray();
  725. result.SubtitleFetchers = plugins
  726. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
  727. .Select(i => new LibraryOptionInfoDto
  728. {
  729. Name = i.Name,
  730. DefaultEnabled = true
  731. })
  732. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  733. .Select(x => x.First())
  734. .ToArray();
  735. var typeOptions = new List<LibraryTypeOptionsDto>();
  736. foreach (var type in types)
  737. {
  738. TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions);
  739. typeOptions.Add(new LibraryTypeOptionsDto
  740. {
  741. Type = type,
  742. MetadataFetchers = plugins
  743. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  744. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
  745. .Select(i => new LibraryOptionInfoDto
  746. {
  747. Name = i.Name,
  748. DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
  749. })
  750. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  751. .Select(x => x.First())
  752. .ToArray(),
  753. ImageFetchers = plugins
  754. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  755. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
  756. .Select(i => new LibraryOptionInfoDto
  757. {
  758. Name = i.Name,
  759. DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
  760. })
  761. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  762. .Select(x => x.First())
  763. .ToArray(),
  764. SupportedImageTypes = plugins
  765. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  766. .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
  767. .Distinct()
  768. .ToArray(),
  769. DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
  770. });
  771. }
  772. result.TypeOptions = typeOptions.ToArray();
  773. return result;
  774. }
  775. private int GetCount(BaseItemKind itemKind, User? user, bool? isFavorite)
  776. {
  777. var query = new InternalItemsQuery(user)
  778. {
  779. IncludeItemTypes = new[] { itemKind },
  780. Limit = 0,
  781. Recursive = true,
  782. IsVirtualItem = false,
  783. IsFavorite = isFavorite,
  784. DtoOptions = new DtoOptions(false)
  785. {
  786. EnableImages = false
  787. }
  788. };
  789. return _libraryManager.GetItemsResult(query).TotalRecordCount;
  790. }
  791. private BaseItem? TranslateParentItem(BaseItem item, User user)
  792. {
  793. return item.GetParent() is AggregateFolder
  794. ? _libraryManager.GetUserRootFolder().GetChildren(user, true)
  795. .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
  796. : item;
  797. }
  798. private async Task LogDownloadAsync(BaseItem item, User user, AuthorizationInfo auth)
  799. {
  800. try
  801. {
  802. await _activityManager.CreateAsync(new ActivityLog(
  803. string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Username, item.Name),
  804. "UserDownloadingContent",
  805. auth.UserId)
  806. {
  807. ShortOverview = string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
  808. }).ConfigureAwait(false);
  809. }
  810. catch
  811. {
  812. // Logged at lower levels
  813. }
  814. }
  815. private static string[] GetRepresentativeItemTypes(string? contentType)
  816. {
  817. return contentType switch
  818. {
  819. CollectionType.BoxSets => new[] { "BoxSet" },
  820. CollectionType.Playlists => new[] { "Playlist" },
  821. CollectionType.Movies => new[] { "Movie" },
  822. CollectionType.TvShows => new[] { "Series", "Season", "Episode" },
  823. CollectionType.Books => new[] { "Book" },
  824. CollectionType.Music => new[] { "MusicArtist", "MusicAlbum", "Audio", "MusicVideo" },
  825. CollectionType.HomeVideos => new[] { "Video", "Photo" },
  826. CollectionType.Photos => new[] { "Video", "Photo" },
  827. CollectionType.MusicVideos => new[] { "MusicVideo" },
  828. _ => new[] { "Series", "Season", "Episode", "Movie" }
  829. };
  830. }
  831. private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
  832. {
  833. if (isNewLibrary)
  834. {
  835. return false;
  836. }
  837. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  838. .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  839. .ToArray();
  840. return metadataOptions.Length == 0 || metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
  841. }
  842. private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
  843. {
  844. if (isNewLibrary)
  845. {
  846. if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
  847. {
  848. return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
  849. || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
  850. || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase));
  851. }
  852. return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
  853. || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
  854. || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase);
  855. }
  856. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  857. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  858. .ToArray();
  859. return metadataOptions.Length == 0
  860. || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
  861. }
  862. private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
  863. {
  864. if (isNewLibrary)
  865. {
  866. if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
  867. {
  868. return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)
  869. && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
  870. && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
  871. && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase);
  872. }
  873. return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
  874. || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)
  875. || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
  876. || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase);
  877. }
  878. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  879. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  880. .ToArray();
  881. if (metadataOptions.Length == 0)
  882. {
  883. return true;
  884. }
  885. return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
  886. }
  887. }
  888. }