ItemLookupController.cs 18 KB

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