LibraryController.cs 41 KB

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