ItemLookupController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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.Constants;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Entities.Audio;
  16. using MediaBrowser.Controller.Entities.Movies;
  17. using MediaBrowser.Controller.Entities.TV;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.Providers;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Providers;
  22. using Microsoft.AspNetCore.Authorization;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Mvc;
  25. using Microsoft.AspNetCore.Mvc.ModelBinding;
  26. using Microsoft.Extensions.Logging;
  27. namespace Jellyfin.Api.Controllers
  28. {
  29. /// <summary>
  30. /// Item lookup controller.
  31. /// </summary>
  32. [Route("")]
  33. [Authorize(Policy = Policies.DefaultAuthorization)]
  34. public class ItemLookupController : BaseJellyfinApiController
  35. {
  36. private readonly IProviderManager _providerManager;
  37. private readonly IServerApplicationPaths _appPaths;
  38. private readonly IFileSystem _fileSystem;
  39. private readonly ILibraryManager _libraryManager;
  40. private readonly ILogger<ItemLookupController> _logger;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="ItemLookupController"/> class.
  43. /// </summary>
  44. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  45. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  46. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  47. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  48. /// <param name="logger">Instance of the <see cref="ILogger{ItemLookupController}"/> interface.</param>
  49. public ItemLookupController(
  50. IProviderManager providerManager,
  51. IServerConfigurationManager serverConfigurationManager,
  52. IFileSystem fileSystem,
  53. ILibraryManager libraryManager,
  54. ILogger<ItemLookupController> logger)
  55. {
  56. _providerManager = providerManager;
  57. _appPaths = serverConfigurationManager.ApplicationPaths;
  58. _fileSystem = fileSystem;
  59. _libraryManager = libraryManager;
  60. _logger = logger;
  61. }
  62. /// <summary>
  63. /// Get the item's external id info.
  64. /// </summary>
  65. /// <param name="itemId">Item id.</param>
  66. /// <response code="200">External id info retrieved.</response>
  67. /// <response code="404">Item not found.</response>
  68. /// <returns>List of external id info.</returns>
  69. [HttpGet("Items/{itemId}/ExternalIdInfos")]
  70. [Authorize(Policy = Policies.RequiresElevation)]
  71. [ProducesResponseType(StatusCodes.Status200OK)]
  72. [ProducesResponseType(StatusCodes.Status404NotFound)]
  73. public ActionResult<IEnumerable<ExternalIdInfo>> GetExternalIdInfos([FromRoute] Guid itemId)
  74. {
  75. var item = _libraryManager.GetItemById(itemId);
  76. if (item == null)
  77. {
  78. return NotFound();
  79. }
  80. return Ok(_providerManager.GetExternalIdInfos(item));
  81. }
  82. /// <summary>
  83. /// Get movie remote search.
  84. /// </summary>
  85. /// <param name="query">Remote search query.</param>
  86. /// <response code="200">Movie remote search executed.</response>
  87. /// <returns>
  88. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  89. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  90. /// </returns>
  91. [HttpPost("Items/RemoteSearch/Movie")]
  92. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMovieRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<MovieInfo> query)
  93. {
  94. var results = await _providerManager.GetRemoteSearchResults<Movie, MovieInfo>(query, CancellationToken.None)
  95. .ConfigureAwait(false);
  96. return Ok(results);
  97. }
  98. /// <summary>
  99. /// Get trailer remote search.
  100. /// </summary>
  101. /// <param name="query">Remote search query.</param>
  102. /// <response code="200">Trailer remote search executed.</response>
  103. /// <returns>
  104. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  105. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  106. /// </returns>
  107. [HttpPost("Items/RemoteSearch/Trailer")]
  108. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetTrailerRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<TrailerInfo> query)
  109. {
  110. var results = await _providerManager.GetRemoteSearchResults<Trailer, TrailerInfo>(query, CancellationToken.None)
  111. .ConfigureAwait(false);
  112. return Ok(results);
  113. }
  114. /// <summary>
  115. /// Get music video remote search.
  116. /// </summary>
  117. /// <param name="query">Remote search query.</param>
  118. /// <response code="200">Music video remote search executed.</response>
  119. /// <returns>
  120. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  121. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  122. /// </returns>
  123. [HttpPost("Items/RemoteSearch/MusicVideo")]
  124. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicVideoRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<MusicVideoInfo> query)
  125. {
  126. var results = await _providerManager.GetRemoteSearchResults<MusicVideo, MusicVideoInfo>(query, CancellationToken.None)
  127. .ConfigureAwait(false);
  128. return Ok(results);
  129. }
  130. /// <summary>
  131. /// Get series remote search.
  132. /// </summary>
  133. /// <param name="query">Remote search query.</param>
  134. /// <response code="200">Series remote search executed.</response>
  135. /// <returns>
  136. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  137. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  138. /// </returns>
  139. [HttpPost("Items/RemoteSearch/Series")]
  140. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetSeriesRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<SeriesInfo> query)
  141. {
  142. var results = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(query, CancellationToken.None)
  143. .ConfigureAwait(false);
  144. return Ok(results);
  145. }
  146. /// <summary>
  147. /// Get box set remote search.
  148. /// </summary>
  149. /// <param name="query">Remote search query.</param>
  150. /// <response code="200">Box set remote search executed.</response>
  151. /// <returns>
  152. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  153. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  154. /// </returns>
  155. [HttpPost("Items/RemoteSearch/BoxSet")]
  156. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBoxSetRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<BoxSetInfo> query)
  157. {
  158. var results = await _providerManager.GetRemoteSearchResults<BoxSet, BoxSetInfo>(query, CancellationToken.None)
  159. .ConfigureAwait(false);
  160. return Ok(results);
  161. }
  162. /// <summary>
  163. /// Get music artist remote search.
  164. /// </summary>
  165. /// <param name="query">Remote search query.</param>
  166. /// <response code="200">Music artist remote search executed.</response>
  167. /// <returns>
  168. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  169. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  170. /// </returns>
  171. [HttpPost("Items/RemoteSearch/MusicArtist")]
  172. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicArtistRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<ArtistInfo> query)
  173. {
  174. var results = await _providerManager.GetRemoteSearchResults<MusicArtist, ArtistInfo>(query, CancellationToken.None)
  175. .ConfigureAwait(false);
  176. return Ok(results);
  177. }
  178. /// <summary>
  179. /// Get music album remote search.
  180. /// </summary>
  181. /// <param name="query">Remote search query.</param>
  182. /// <response code="200">Music album remote search executed.</response>
  183. /// <returns>
  184. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  185. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  186. /// </returns>
  187. [HttpPost("Items/RemoteSearch/MusicAlbum")]
  188. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetMusicAlbumRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<AlbumInfo> query)
  189. {
  190. var results = await _providerManager.GetRemoteSearchResults<MusicAlbum, AlbumInfo>(query, CancellationToken.None)
  191. .ConfigureAwait(false);
  192. return Ok(results);
  193. }
  194. /// <summary>
  195. /// Get person remote search.
  196. /// </summary>
  197. /// <param name="query">Remote search query.</param>
  198. /// <response code="200">Person remote search executed.</response>
  199. /// <returns>
  200. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  201. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  202. /// </returns>
  203. [HttpPost("Items/RemoteSearch/Person")]
  204. [Authorize(Policy = Policies.RequiresElevation)]
  205. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetPersonRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<PersonLookupInfo> query)
  206. {
  207. var results = await _providerManager.GetRemoteSearchResults<Person, PersonLookupInfo>(query, CancellationToken.None)
  208. .ConfigureAwait(false);
  209. return Ok(results);
  210. }
  211. /// <summary>
  212. /// Get book remote search.
  213. /// </summary>
  214. /// <param name="query">Remote search query.</param>
  215. /// <response code="200">Book remote search executed.</response>
  216. /// <returns>
  217. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  218. /// The task result contains an <see cref="OkResult"/> containing the list of remote search results.
  219. /// </returns>
  220. [HttpPost("Items/RemoteSearch/Book")]
  221. public async Task<ActionResult<IEnumerable<RemoteSearchResult>>> GetBookRemoteSearchResults([FromBody, BindRequired] RemoteSearchQuery<BookInfo> query)
  222. {
  223. var results = await _providerManager.GetRemoteSearchResults<Book, BookInfo>(query, CancellationToken.None)
  224. .ConfigureAwait(false);
  225. return Ok(results);
  226. }
  227. /// <summary>
  228. /// Gets a remote image.
  229. /// </summary>
  230. /// <param name="imageUrl">The image url.</param>
  231. /// <param name="providerName">The provider name.</param>
  232. /// <response code="200">Remote image retrieved.</response>
  233. /// <returns>
  234. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  235. /// The task result contains an <see cref="FileStreamResult"/> containing the images file stream.
  236. /// </returns>
  237. [HttpGet("Items/RemoteSearch/Image")]
  238. public async Task<ActionResult> GetRemoteSearchImage(
  239. [FromQuery, Required] string imageUrl,
  240. [FromQuery, Required] string providerName)
  241. {
  242. var urlHash = imageUrl.GetMD5();
  243. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  244. try
  245. {
  246. var contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  247. if (System.IO.File.Exists(contentPath))
  248. {
  249. await using var fileStreamExisting = System.IO.File.OpenRead(pointerCachePath);
  250. return new FileStreamResult(fileStreamExisting, MediaTypeNames.Application.Octet);
  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. // Read the pointer file again
  263. await using var fileStream = System.IO.File.OpenRead(pointerCachePath);
  264. return new FileStreamResult(fileStream, MediaTypeNames.Application.Octet);
  265. }
  266. /// <summary>
  267. /// Applies search criteria to an item and refreshes metadata.
  268. /// </summary>
  269. /// <param name="itemId">Item id.</param>
  270. /// <param name="searchResult">The remote search result.</param>
  271. /// <param name="replaceAllImages">Optional. Whether or not to replace all images. Default: True.</param>
  272. /// <response code="204">Item metadata refreshed.</response>
  273. /// <returns>
  274. /// A <see cref="Task" /> that represents the asynchronous operation to get the remote search results.
  275. /// The task result contains an <see cref="NoContentResult"/>.
  276. /// </returns>
  277. [HttpPost("Items/RemoteSearch/Apply/{id}")]
  278. [Authorize(Policy = Policies.RequiresElevation)]
  279. public async Task<ActionResult> ApplySearchCriteria(
  280. [FromRoute] Guid itemId,
  281. [FromBody, BindRequired] 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. var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);
  315. var ext = result.ContentType.Split('/').Last();
  316. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  317. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  318. await using (var stream = result.Content)
  319. {
  320. await using var fileStream = new FileStream(
  321. fullCachePath,
  322. FileMode.Create,
  323. FileAccess.Write,
  324. FileShare.Read,
  325. IODefaults.FileStreamBufferSize,
  326. true);
  327. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  328. }
  329. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  330. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false);
  331. }
  332. /// <summary>
  333. /// Gets the full cache path.
  334. /// </summary>
  335. /// <param name="filename">The filename.</param>
  336. /// <returns>System.String.</returns>
  337. private string GetFullCachePath(string filename)
  338. => Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  339. }
  340. }