LibraryController.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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.Helpers;
  15. using Jellyfin.Api.Models.LibraryDtos;
  16. using Jellyfin.Data.Entities;
  17. using MediaBrowser.Common.Progress;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Dto;
  20. using MediaBrowser.Controller.Entities;
  21. using MediaBrowser.Controller.Entities.Audio;
  22. using MediaBrowser.Controller.Entities.Movies;
  23. using MediaBrowser.Controller.Entities.TV;
  24. using MediaBrowser.Controller.Library;
  25. using MediaBrowser.Controller.LiveTv;
  26. using MediaBrowser.Controller.Net;
  27. using MediaBrowser.Controller.Providers;
  28. using MediaBrowser.Model.Activity;
  29. using MediaBrowser.Model.Configuration;
  30. using MediaBrowser.Model.Dto;
  31. using MediaBrowser.Model.Entities;
  32. using MediaBrowser.Model.Globalization;
  33. using MediaBrowser.Model.Net;
  34. using MediaBrowser.Model.Querying;
  35. using Microsoft.AspNetCore.Authorization;
  36. using Microsoft.AspNetCore.Http;
  37. using Microsoft.AspNetCore.Mvc;
  38. using Microsoft.Extensions.Logging;
  39. using Book = MediaBrowser.Controller.Entities.Book;
  40. namespace Jellyfin.Api.Controllers
  41. {
  42. /// <summary>
  43. /// Library Controller.
  44. /// </summary>
  45. [Route("")]
  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. [ProducesFile("video/*", "audio/*")]
  106. public ActionResult GetFile([FromRoute, Required] Guid itemId)
  107. {
  108. var item = _libraryManager.GetItemById(itemId);
  109. if (item == null)
  110. {
  111. return NotFound();
  112. }
  113. return PhysicalFile(item.Path, 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, Required] Guid itemId,
  143. [FromQuery] Guid? userId,
  144. [FromQuery] bool inheritFromParent = false)
  145. {
  146. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  147. ? _userManager.GetUserById(userId.Value)
  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, Required] Guid itemId,
  199. [FromQuery] Guid? userId,
  200. [FromQuery] bool inheritFromParent = false)
  201. {
  202. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  203. ? _userManager.GetUserById(userId.Value)
  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, Required] Guid itemId,
  254. [FromQuery] Guid? userId,
  255. [FromQuery] bool inheritFromParent = false)
  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. if (string.IsNullOrEmpty(ids))
  332. {
  333. return NoContent();
  334. }
  335. var itemIds = RequestHelpers.Split(ids, ',', true);
  336. foreach (var i in itemIds)
  337. {
  338. var item = _libraryManager.GetItemById(i);
  339. var auth = _authContext.GetAuthorizationInfo(Request);
  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(typeof(MusicAlbum), user, isFavorite),
  376. EpisodeCount = GetCount(typeof(Episode), user, isFavorite),
  377. MovieCount = GetCount(typeof(Movie), user, isFavorite),
  378. SeriesCount = GetCount(typeof(Series), user, isFavorite),
  379. SongCount = GetCount(typeof(Audio), user, isFavorite),
  380. MusicVideoCount = GetCount(typeof(MusicVideo), user, isFavorite),
  381. BoxSetCount = GetCount(typeof(BoxSet), user, isFavorite),
  382. BookCount = GetCount(typeof(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[] { nameof(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[] { nameof(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="updates">A list of updated media 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[] updates)
  535. {
  536. foreach (var item in updates)
  537. {
  538. _libraryMonitor.ReportFileSystemChanged(item.Path);
  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 = _authContext.GetAuthorizationInfo(Request);
  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));
  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 = "GetSimilarArtists2")]
  608. [HttpGet("Items/{itemId}/Similar")]
  609. [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums2")]
  610. [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows2")]
  611. [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies2")]
  612. [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers2")]
  613. [Authorize(Policy = Policies.DefaultAuthorization)]
  614. [ProducesResponseType(StatusCodes.Status200OK)]
  615. public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems(
  616. [FromRoute, Required] Guid itemId,
  617. [FromQuery] string? excludeArtistIds,
  618. [FromQuery] Guid? userId,
  619. [FromQuery] int? limit,
  620. [FromQuery] string? 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. var program = item as IHasProgramAttributes;
  628. var isMovie = item is MediaBrowser.Controller.Entities.Movies.Movie || (program != null && program.IsMovie) || item is Trailer;
  629. if (program != null && program.IsSeries)
  630. {
  631. return GetSimilarItemsResult(
  632. item,
  633. excludeArtistIds,
  634. userId,
  635. limit,
  636. fields,
  637. new[] { nameof(Series) },
  638. false);
  639. }
  640. if (item is MediaBrowser.Controller.Entities.TV.Episode || (item is IItemByName && !(item is MusicArtist)))
  641. {
  642. return new QueryResult<BaseItemDto>();
  643. }
  644. return GetSimilarItemsResult(
  645. item,
  646. excludeArtistIds,
  647. userId,
  648. limit,
  649. fields,
  650. new[] { item.GetType().Name },
  651. isMovie);
  652. }
  653. /// <summary>
  654. /// Gets the library options info.
  655. /// </summary>
  656. /// <param name="libraryContentType">Library content type.</param>
  657. /// <param name="isNewLibrary">Whether this is a new library.</param>
  658. /// <response code="200">Library options info returned.</response>
  659. /// <returns>Library options info.</returns>
  660. [HttpGet("Libraries/AvailableOptions")]
  661. [Authorize(Policy = Policies.FirstTimeSetupOrDefault)]
  662. [ProducesResponseType(StatusCodes.Status200OK)]
  663. public ActionResult<LibraryOptionsResultDto> GetLibraryOptionsInfo(
  664. [FromQuery] string? libraryContentType,
  665. [FromQuery] bool isNewLibrary)
  666. {
  667. var result = new LibraryOptionsResultDto();
  668. var types = GetRepresentativeItemTypes(libraryContentType);
  669. var typesList = types.ToList();
  670. var plugins = _providerManager.GetAllMetadataPlugins()
  671. .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
  672. .OrderBy(i => typesList.IndexOf(i.ItemType))
  673. .ToList();
  674. result.MetadataSavers = plugins
  675. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
  676. .Select(i => new LibraryOptionInfoDto
  677. {
  678. Name = i.Name,
  679. DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
  680. })
  681. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  682. .Select(x => x.First())
  683. .ToArray();
  684. result.MetadataReaders = plugins
  685. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
  686. .Select(i => new LibraryOptionInfoDto
  687. {
  688. Name = i.Name,
  689. DefaultEnabled = true
  690. })
  691. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  692. .Select(x => x.First())
  693. .ToArray();
  694. result.SubtitleFetchers = plugins
  695. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
  696. .Select(i => new LibraryOptionInfoDto
  697. {
  698. Name = i.Name,
  699. DefaultEnabled = true
  700. })
  701. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  702. .Select(x => x.First())
  703. .ToArray();
  704. var typeOptions = new List<LibraryTypeOptionsDto>();
  705. foreach (var type in types)
  706. {
  707. TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions);
  708. typeOptions.Add(new LibraryTypeOptionsDto
  709. {
  710. Type = type,
  711. MetadataFetchers = plugins
  712. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  713. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
  714. .Select(i => new LibraryOptionInfoDto
  715. {
  716. Name = i.Name,
  717. DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
  718. })
  719. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  720. .Select(x => x.First())
  721. .ToArray(),
  722. ImageFetchers = plugins
  723. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  724. .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
  725. .Select(i => new LibraryOptionInfoDto
  726. {
  727. Name = i.Name,
  728. DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
  729. })
  730. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  731. .Select(x => x.First())
  732. .ToArray(),
  733. SupportedImageTypes = plugins
  734. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  735. .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
  736. .Distinct()
  737. .ToArray(),
  738. DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
  739. });
  740. }
  741. result.TypeOptions = typeOptions.ToArray();
  742. return result;
  743. }
  744. private int GetCount(Type type, User? user, bool? isFavorite)
  745. {
  746. var query = new InternalItemsQuery(user)
  747. {
  748. IncludeItemTypes = new[] { type.Name },
  749. Limit = 0,
  750. Recursive = true,
  751. IsVirtualItem = false,
  752. IsFavorite = isFavorite,
  753. DtoOptions = new DtoOptions(false)
  754. {
  755. EnableImages = false
  756. }
  757. };
  758. return _libraryManager.GetItemsResult(query).TotalRecordCount;
  759. }
  760. private BaseItem TranslateParentItem(BaseItem item, User user)
  761. {
  762. return item.GetParent() is AggregateFolder
  763. ? _libraryManager.GetUserRootFolder().GetChildren(user, true)
  764. .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
  765. : item;
  766. }
  767. private async Task LogDownloadAsync(BaseItem item, User user, AuthorizationInfo auth)
  768. {
  769. try
  770. {
  771. await _activityManager.CreateAsync(new ActivityLog(
  772. string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Username, item.Name),
  773. "UserDownloadingContent",
  774. auth.UserId)
  775. {
  776. ShortOverview = string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
  777. }).ConfigureAwait(false);
  778. }
  779. catch
  780. {
  781. // Logged at lower levels
  782. }
  783. }
  784. private QueryResult<BaseItemDto> GetSimilarItemsResult(
  785. BaseItem item,
  786. string? excludeArtistIds,
  787. Guid? userId,
  788. int? limit,
  789. string? fields,
  790. string[] includeItemTypes,
  791. bool isMovie)
  792. {
  793. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  794. ? _userManager.GetUserById(userId.Value)
  795. : null;
  796. var dtoOptions = new DtoOptions()
  797. .AddItemFields(fields)
  798. .AddClientFields(Request);
  799. var query = new InternalItemsQuery(user)
  800. {
  801. Limit = limit,
  802. IncludeItemTypes = includeItemTypes,
  803. IsMovie = isMovie,
  804. SimilarTo = item,
  805. DtoOptions = dtoOptions,
  806. EnableTotalRecordCount = !isMovie,
  807. EnableGroupByMetadataKey = isMovie
  808. };
  809. // ExcludeArtistIds
  810. if (!string.IsNullOrEmpty(excludeArtistIds))
  811. {
  812. query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
  813. }
  814. List<BaseItem> itemsResult;
  815. if (isMovie)
  816. {
  817. var itemTypes = new List<string> { nameof(MediaBrowser.Controller.Entities.Movies.Movie) };
  818. if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
  819. {
  820. itemTypes.Add(nameof(Trailer));
  821. itemTypes.Add(nameof(LiveTvProgram));
  822. }
  823. query.IncludeItemTypes = itemTypes.ToArray();
  824. itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
  825. }
  826. else if (item is MusicArtist)
  827. {
  828. query.IncludeItemTypes = Array.Empty<string>();
  829. itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
  830. }
  831. else
  832. {
  833. itemsResult = _libraryManager.GetItemList(query);
  834. }
  835. var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
  836. var result = new QueryResult<BaseItemDto>
  837. {
  838. Items = returnList,
  839. TotalRecordCount = itemsResult.Count
  840. };
  841. return result;
  842. }
  843. private static string[] GetRepresentativeItemTypes(string? contentType)
  844. {
  845. return contentType switch
  846. {
  847. CollectionType.BoxSets => new[] { "BoxSet" },
  848. CollectionType.Playlists => new[] { "Playlist" },
  849. CollectionType.Movies => new[] { "Movie" },
  850. CollectionType.TvShows => new[] { "Series", "Season", "Episode" },
  851. CollectionType.Books => new[] { "Book" },
  852. CollectionType.Music => new[] { "MusicArtist", "MusicAlbum", "Audio", "MusicVideo" },
  853. CollectionType.HomeVideos => new[] { "Video", "Photo" },
  854. CollectionType.Photos => new[] { "Video", "Photo" },
  855. CollectionType.MusicVideos => new[] { "MusicVideo" },
  856. _ => new[] { "Series", "Season", "Episode", "Movie" }
  857. };
  858. }
  859. private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
  860. {
  861. if (isNewLibrary)
  862. {
  863. return false;
  864. }
  865. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  866. .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  867. .ToArray();
  868. return metadataOptions.Length == 0 || metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
  869. }
  870. private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
  871. {
  872. if (isNewLibrary)
  873. {
  874. if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
  875. {
  876. return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
  877. || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
  878. || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase));
  879. }
  880. return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
  881. || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
  882. || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase);
  883. }
  884. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  885. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  886. .ToArray();
  887. return metadataOptions.Length == 0
  888. || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
  889. }
  890. private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
  891. {
  892. if (isNewLibrary)
  893. {
  894. if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
  895. {
  896. return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)
  897. && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
  898. && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
  899. && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase);
  900. }
  901. return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
  902. || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)
  903. || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
  904. || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase);
  905. }
  906. var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
  907. .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
  908. .ToArray();
  909. if (metadataOptions.Length == 0)
  910. {
  911. return true;
  912. }
  913. return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
  914. }
  915. }
  916. }