ItemLookupController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. [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] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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, BindRequired] 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. public async Task<ActionResult> GetRemoteSearchImage(
  238. [FromQuery, Required] string imageUrl,
  239. [FromQuery, Required] string providerName)
  240. {
  241. var urlHash = imageUrl.GetMD5();
  242. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  243. try
  244. {
  245. var contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  246. if (System.IO.File.Exists(contentPath))
  247. {
  248. await using var fileStreamExisting = System.IO.File.OpenRead(pointerCachePath);
  249. return new FileStreamResult(fileStreamExisting, MediaTypeNames.Application.Octet);
  250. }
  251. }
  252. catch (FileNotFoundException)
  253. {
  254. // Means the file isn't cached yet
  255. }
  256. catch (IOException)
  257. {
  258. // Means the file isn't cached yet
  259. }
  260. await DownloadImage(providerName, imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  261. // Read the pointer file again
  262. await using var fileStream = System.IO.File.OpenRead(pointerCachePath);
  263. return new FileStreamResult(fileStream, MediaTypeNames.Application.Octet);
  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/{id}")]
  277. [Authorize(Policy = Policies.RequiresElevation)]
  278. public async Task<ActionResult> ApplySearchCriteria(
  279. [FromRoute] Guid itemId,
  280. [FromBody, BindRequired] RemoteSearchResult searchResult,
  281. [FromQuery] bool replaceAllImages = true)
  282. {
  283. var item = _libraryManager.GetItemById(itemId);
  284. _logger.LogInformation(
  285. "Setting provider id's to item {0}-{1}: {2}",
  286. item.Id,
  287. item.Name,
  288. JsonSerializer.Serialize(searchResult.ProviderIds));
  289. // Since the refresh process won't erase provider Ids, we need to set this explicitly now.
  290. item.ProviderIds = searchResult.ProviderIds;
  291. await _providerManager.RefreshFullItem(
  292. item,
  293. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  294. {
  295. MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
  296. ImageRefreshMode = MetadataRefreshMode.FullRefresh,
  297. ReplaceAllMetadata = true,
  298. ReplaceAllImages = replaceAllImages,
  299. SearchResult = searchResult
  300. }, CancellationToken.None).ConfigureAwait(false);
  301. return NoContent();
  302. }
  303. /// <summary>
  304. /// Downloads the image.
  305. /// </summary>
  306. /// <param name="providerName">Name of the provider.</param>
  307. /// <param name="url">The URL.</param>
  308. /// <param name="urlHash">The URL hash.</param>
  309. /// <param name="pointerCachePath">The pointer cache path.</param>
  310. /// <returns>Task.</returns>
  311. private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath)
  312. {
  313. var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);
  314. var ext = result.ContentType.Split('/').Last();
  315. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  316. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  317. await using (var stream = result.Content)
  318. {
  319. await using var fileStream = new FileStream(
  320. fullCachePath,
  321. FileMode.Create,
  322. FileAccess.Write,
  323. FileShare.Read,
  324. IODefaults.FileStreamBufferSize,
  325. true);
  326. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  327. }
  328. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  329. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false);
  330. }
  331. /// <summary>
  332. /// Gets the full cache path.
  333. /// </summary>
  334. /// <param name="filename">The filename.</param>
  335. /// <returns>System.String.</returns>
  336. private string GetFullCachePath(string filename)
  337. => Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  338. }
  339. }