LibraryController.cs 42 KB

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