ItemLookupController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Text.Json;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Attributes;
  9. using Jellyfin.Api.Constants;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Entities.Audio;
  15. using MediaBrowser.Controller.Entities.Movies;
  16. using MediaBrowser.Controller.Entities.TV;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.Providers;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.Net;
  21. using MediaBrowser.Model.Providers;
  22. using Microsoft.AspNetCore.Authorization;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Mvc;
  25. using Microsoft.Extensions.Logging;
  26. namespace Jellyfin.Api.Controllers
  27. {
  28. /// <summary>
  29. /// Item lookup controller.
  30. /// </summary>
  31. [Route("")]
  32. [Authorize(Policy = Policies.DefaultAuthorization)]
  33. public class ItemLookupController : BaseJellyfinApiController
  34. {
  35. private readonly IProviderManager _providerManager;
  36. private readonly IServerApplicationPaths _appPaths;
  37. private readonly IFileSystem _fileSystem;
  38. private readonly ILibraryManager _libraryManager;
  39. private readonly ILogger<ItemLookupController> _logger;
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="ItemLookupController"/> class.
  42. /// </summary>
  43. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  44. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  45. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  46. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  47. /// <param name="logger">Instance of the <see cref="ILogger{ItemLookupController}"/> interface.</param>
  48. public ItemLookupController(
  49. IProviderManager providerManager,
  50. IServerConfigurationManager serverConfigurationManager,
  51. IFileSystem fileSystem,
  52. ILibraryManager libraryManager,
  53. ILogger<ItemLookupController> logger)
  54. {
  55. _providerManager = providerManager;
  56. _appPaths = serverConfigurationManager.ApplicationPaths;
  57. _fileSystem = fileSystem;
  58. _libraryManager = libraryManager;
  59. _logger = logger;
  60. }
  61. /// <summary>
  62. /// Get the item's external id info.
  63. /// </summary>
  64. /// <param name="itemId">Item id.</param>
  65. /// <response code="200">External id info retrieved.</response>
  66. /// <response code="404">Item not found.</response>
  67. /// <returns>List of external id info.</returns>
  68. [HttpGet("Items/{itemId}/ExternalIdInfos")]
  69. [Authorize(Policy = Policies.RequiresElevation)]
  70. [ProducesResponseType(StatusCodes.Status200OK)]
  71. [ProducesResponseType(StatusCodes.Status404NotFound)]
  72. public ActionResult<IEnumerable<ExternalIdInfo>> GetExternalIdInfos([FromRoute, Required] Guid itemId)
  73. {
  74. var item = _libraryManager.GetItemById(itemId);
  75. if (item == null)
  76. {
  77. return NotFound();
  78. }
  79. return Ok(_providerManager.GetExternalIdInfos(item));
  80. }
  81. /// <summary>
  82. /// Get movie remote search.
  83. /// </summary>
  84. /// <param name="query">Remote search query.</param>
  85. /// <response code="200">Movie remote search executed.</response>
  86. /// <returns>
  87. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  88. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  89. /// </returns>
  90. [HttpPost("Items/RemoteSearch/Movie")]
  91. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMovieRemoteSearchResults([FromBody, Required] RemoteSearchQuery<MovieInfo> query)
  92. {
  93. var results = await _providerManager.GetRemoteSearchResults<Movie, MovieInfo>(query, CancellationToken.None)
  94. .ConfigureAwait(false);
  95. return Ok(results);
  96. }
  97. /// <summary>
  98. /// Get trailer remote search.
  99. /// </summary>
  100. /// <param name="query">Remote search query.</param>
  101. /// <response code="200">Trailer remote search executed.</response>
  102. /// <returns>
  103. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  104. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  105. /// </returns>
  106. [HttpPost("Items/RemoteSearch/Trailer")]
  107. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetTrailerRemoteSearchResults([FromBody, Required] RemoteSearchQuery<TrailerInfo> query)
  108. {
  109. var results = await _providerManager.GetRemoteSearchResults<Trailer, TrailerInfo>(query, CancellationToken.None)
  110. .ConfigureAwait(false);
  111. return Ok(results);
  112. }
  113. /// <summary>
  114. /// Get music video remote search.
  115. /// </summary>
  116. /// <param name="query">Remote search query.</param>
  117. /// <response code="200">Music video remote search executed.</response>
  118. /// <returns>
  119. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  120. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  121. /// </returns>
  122. [HttpPost("Items/RemoteSearch/MusicVideo")]
  123. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicVideoRemoteSearchResults([FromBody, Required] RemoteSearchQuery<MusicVideoInfo> query)
  124. {
  125. var results = await _providerManager.GetRemoteSearchResults<MusicVideo, MusicVideoInfo>(query, CancellationToken.None)
  126. .ConfigureAwait(false);
  127. return Ok(results);
  128. }
  129. /// <summary>
  130. /// Get series remote search.
  131. /// </summary>
  132. /// <param name="query">Remote search query.</param>
  133. /// <response code="200">Series remote search executed.</response>
  134. /// <returns>
  135. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  136. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  137. /// </returns>
  138. [HttpPost("Items/RemoteSearch/Series")]
  139. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetSeriesRemoteSearchResults([FromBody, Required] RemoteSearchQuery<SeriesInfo> query)
  140. {
  141. var results = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(query, CancellationToken.None)
  142. .ConfigureAwait(false);
  143. return Ok(results);
  144. }
  145. /// <summary>
  146. /// Get box set remote search.
  147. /// </summary>
  148. /// <param name="query">Remote search query.</param>
  149. /// <response code="200">Box set remote search executed.</response>
  150. /// <returns>
  151. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  152. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  153. /// </returns>
  154. [HttpPost("Items/RemoteSearch/BoxSet")]
  155. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBoxSetRemoteSearchResults([FromBody, Required] RemoteSearchQuery<BoxSetInfo> query)
  156. {
  157. var results = await _providerManager.GetRemoteSearchResults<BoxSet, BoxSetInfo>(query, CancellationToken.None)
  158. .ConfigureAwait(false);
  159. return Ok(results);
  160. }
  161. /// <summary>
  162. /// Get music artist remote search.
  163. /// </summary>
  164. /// <param name="query">Remote search query.</param>
  165. /// <response code="200">Music artist remote search executed.</response>
  166. /// <returns>
  167. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  168. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  169. /// </returns>
  170. [HttpPost("Items/RemoteSearch/MusicArtist")]
  171. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicArtistRemoteSearchResults([FromBody, Required] RemoteSearchQuery<ArtistInfo> query)
  172. {
  173. var results = await _providerManager.GetRemoteSearchResults<MusicArtist, ArtistInfo>(query, CancellationToken.None)
  174. .ConfigureAwait(false);
  175. return Ok(results);
  176. }
  177. /// <summary>
  178. /// Get music album remote search.
  179. /// </summary>
  180. /// <param name="query">Remote search query.</param>
  181. /// <response code="200">Music album remote search executed.</response>
  182. /// <returns>
  183. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  184. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  185. /// </returns>
  186. [HttpPost("Items/RemoteSearch/MusicAlbum")]
  187. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicAlbumRemoteSearchResults([FromBody, Required] RemoteSearchQuery<AlbumInfo> query)
  188. {
  189. var results = await _providerManager.GetRemoteSearchResults<MusicAlbum, AlbumInfo>(query, CancellationToken.None)
  190. .ConfigureAwait(false);
  191. return Ok(results);
  192. }
  193. /// <summary>
  194. /// Get person remote search.
  195. /// </summary>
  196. /// <param name="query">Remote search query.</param>
  197. /// <response code="200">Person remote search executed.</response>
  198. /// <returns>
  199. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  200. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  201. /// </returns>
  202. [HttpPost("Items/RemoteSearch/Person")]
  203. [Authorize(Policy = Policies.RequiresElevation)]
  204. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetPersonRemoteSearchResults([FromBody, Required] RemoteSearchQuery<PersonLookupInfo> query)
  205. {
  206. var results = await _providerManager.GetRemoteSearchResults<Person, PersonLookupInfo>(query, CancellationToken.None)
  207. .ConfigureAwait(false);
  208. return Ok(results);
  209. }
  210. /// <summary>
  211. /// Get book remote search.
  212. /// </summary>
  213. /// <param name="query">Remote search query.</param>
  214. /// <response code="200">Book remote search executed.</response>
  215. /// <returns>
  216. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  217. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  218. /// </returns>
  219. [HttpPost("Items/RemoteSearch/Book")]
  220. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBookRemoteSearchResults([FromBody, Required] RemoteSearchQuery<BookInfo> query)
  221. {
  222. var results = await _providerManager.GetRemoteSearchResults<Book, BookInfo>(query, CancellationToken.None)
  223. .ConfigureAwait(false);
  224. return Ok(results);
  225. }
  226. /// <summary>
  227. /// Gets a remote image.
  228. /// </summary>
  229. /// <param name="imageUrl">The image url.</param>
  230. /// <param name="providerName">The provider name.</param>
  231. /// <response code="200">Remote image retrieved.</response>
  232. /// <returns>
  233. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  234. /// The task result contains an <see cref="FileStreamResult"/> containing the images file stream.
  235. /// </returns>
  236. [HttpGet("Items/RemoteSearch/Image")]
  237. [ProducesResponseType(StatusCodes.Status200OK)]
  238. [ProducesImageFile]
  239. public async Task<ActionResult> GetRemoteSearchImage(
  240. [FromQuery, Required] string imageUrl,
  241. [FromQuery, Required] string providerName)
  242. {
  243. var urlHash = imageUrl.GetMD5();
  244. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  245. try
  246. {
  247. var contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  248. if (System.IO.File.Exists(contentPath))
  249. {
  250. return PhysicalFile(contentPath, MimeTypes.GetMimeType(contentPath));
  251. }
  252. }
  253. catch (FileNotFoundException)
  254. {
  255. // Means the file isn't cached yet
  256. }
  257. catch (IOException)
  258. {
  259. // Means the file isn't cached yet
  260. }
  261. await DownloadImage(providerName, imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  262. var updatedContentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  263. return PhysicalFile(updatedContentPath, MimeTypes.GetMimeType(updatedContentPath));
  264. }
  265. /// <summary>
  266. /// Applies search criteria to an item and refreshes metadata.
  267. /// </summary>
  268. /// <param name="itemId">Item id.</param>
  269. /// <param name="searchResult">The remote search result.</param>
  270. /// <param name="replaceAllImages">Optional. Whether or not to replace all images. Default: True.</param>
  271. /// <response code="204">Item metadata refreshed.</response>
  272. /// <returns>
  273. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  274. /// The task result contains an <see cref="NoContentResult"/>.
  275. /// </returns>
  276. [HttpPost("Items/RemoteSearch/Apply/{itemId}")]
  277. [Authorize(Policy = Policies.RequiresElevation)]
  278. [ProducesResponseType(StatusCodes.Status204NoContent)]
  279. public async Task<ActionResult> ApplySearchCriteria(
  280. [FromRoute, Required] Guid itemId,
  281. [FromBody, Required] RemoteSearchResult searchResult,
  282. [FromQuery] bool replaceAllImages = true)
  283. {
  284. var item = _libraryManager.GetItemById(itemId);
  285. _logger.LogInformation(
  286. "Setting provider id's to item {0}-{1}: {2}",
  287. item.Id,
  288. item.Name,
  289. JsonSerializer.Serialize(searchResult.ProviderIds));
  290. // Since the refresh process won't erase provider Ids, we need to set this explicitly now.
  291. item.ProviderIds = searchResult.ProviderIds;
  292. await _providerManager.RefreshFullItem(
  293. item,
  294. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  295. {
  296. MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
  297. ImageRefreshMode = MetadataRefreshMode.FullRefresh,
  298. ReplaceAllMetadata = true,
  299. ReplaceAllImages = replaceAllImages,
  300. SearchResult = searchResult
  301. }, CancellationToken.None).ConfigureAwait(false);
  302. return NoContent();
  303. }
  304. /// <summary>
  305. /// Downloads the image.
  306. /// </summary>
  307. /// <param name="providerName">Name of the provider.</param>
  308. /// <param name="url">The URL.</param>
  309. /// <param name="urlHash">The URL hash.</param>
  310. /// <param name="pointerCachePath">The pointer cache path.</param>
  311. /// <returns>Task.</returns>
  312. private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath)
  313. {
  314. using var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);
  315. if (result.Content.Headers.ContentType?.MediaType == null)
  316. {
  317. throw new ResourceNotFoundException(nameof(result.Content.Headers.ContentType));
  318. }
  319. var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1];
  320. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  321. var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid.");
  322. Directory.CreateDirectory(directory);
  323. using (var stream = result.Content)
  324. {
  325. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  326. await using var fileStream = new FileStream(
  327. fullCachePath,
  328. FileMode.Create,
  329. FileAccess.Write,
  330. FileShare.None,
  331. IODefaults.FileStreamBufferSize,
  332. true);
  333. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  334. }
  335. var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath));
  336. Directory.CreateDirectory(pointerCacheDirectory);
  337. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false);
  338. }
  339. /// <summary>
  340. /// Gets the full cache path.
  341. /// </summary>
  342. /// <param name="filename">The filename.</param>
  343. /// <returns>System.String.</returns>
  344. private string GetFullCachePath(string filename)
  345. => Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  346. }
  347. }