2
0

LibraryController.cs 41 KB

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