RemoteImageController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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.Http;
  7. using System.Net.Mime;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Api.Constants;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Net;
  19. using MediaBrowser.Model.Providers;
  20. using Microsoft.AspNetCore.Authorization;
  21. using Microsoft.AspNetCore.Http;
  22. using Microsoft.AspNetCore.Mvc;
  23. namespace Jellyfin.Api.Controllers
  24. {
  25. /// <summary>
  26. /// Remote Images Controller.
  27. /// </summary>
  28. [Route("")]
  29. public class RemoteImageController : BaseJellyfinApiController
  30. {
  31. private readonly IProviderManager _providerManager;
  32. private readonly IServerApplicationPaths _applicationPaths;
  33. private readonly IHttpClientFactory _httpClientFactory;
  34. private readonly ILibraryManager _libraryManager;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="RemoteImageController"/> class.
  37. /// </summary>
  38. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  39. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  40. /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
  41. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  42. public RemoteImageController(
  43. IProviderManager providerManager,
  44. IServerApplicationPaths applicationPaths,
  45. IHttpClientFactory httpClientFactory,
  46. ILibraryManager libraryManager)
  47. {
  48. _providerManager = providerManager;
  49. _applicationPaths = applicationPaths;
  50. _httpClientFactory = httpClientFactory;
  51. _libraryManager = libraryManager;
  52. }
  53. /// <summary>
  54. /// Gets available remote images for an item.
  55. /// </summary>
  56. /// <param name="itemId">Item Id.</param>
  57. /// <param name="type">The image type.</param>
  58. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  59. /// <param name="limit">Optional. The maximum number of records to return.</param>
  60. /// <param name="providerName">Optional. The image provider to use.</param>
  61. /// <param name="includeAllLanguages">Optional. Include all languages.</param>
  62. /// <response code="200">Remote Images returned.</response>
  63. /// <response code="404">Item not found.</response>
  64. /// <returns>Remote Image Result.</returns>
  65. [HttpGet("Items/{itemId}/RemoteImages")]
  66. [Authorize(Policy = Policies.DefaultAuthorization)]
  67. [ProducesResponseType(StatusCodes.Status200OK)]
  68. [ProducesResponseType(StatusCodes.Status404NotFound)]
  69. public async Task<ActionResult<RemoteImageResult>> GetRemoteImages(
  70. [FromRoute, Required] Guid itemId,
  71. [FromQuery] ImageType? type,
  72. [FromQuery] int? startIndex,
  73. [FromQuery] int? limit,
  74. [FromQuery] string? providerName,
  75. [FromQuery] bool includeAllLanguages = false)
  76. {
  77. var item = _libraryManager.GetItemById(itemId);
  78. if (item == null)
  79. {
  80. return NotFound();
  81. }
  82. var images = await _providerManager.GetAvailableRemoteImages(
  83. item,
  84. new RemoteImageQuery(providerName ?? string.Empty)
  85. {
  86. IncludeAllLanguages = includeAllLanguages,
  87. IncludeDisabledProviders = true,
  88. ImageType = type
  89. }, CancellationToken.None)
  90. .ConfigureAwait(false);
  91. var imageArray = images.ToArray();
  92. var allProviders = _providerManager.GetRemoteImageProviderInfo(item);
  93. if (type.HasValue)
  94. {
  95. allProviders = allProviders.Where(o => o.SupportedImages.Contains(type.Value));
  96. }
  97. var result = new RemoteImageResult
  98. {
  99. TotalRecordCount = imageArray.Length,
  100. Providers = allProviders.Select(o => o.Name)
  101. .Distinct(StringComparer.OrdinalIgnoreCase)
  102. .ToArray()
  103. };
  104. if (startIndex.HasValue)
  105. {
  106. imageArray = imageArray.Skip(startIndex.Value).ToArray();
  107. }
  108. if (limit.HasValue)
  109. {
  110. imageArray = imageArray.Take(limit.Value).ToArray();
  111. }
  112. result.Images = imageArray;
  113. return result;
  114. }
  115. /// <summary>
  116. /// Gets available remote image providers for an item.
  117. /// </summary>
  118. /// <param name="itemId">Item Id.</param>
  119. /// <response code="200">Returned remote image providers.</response>
  120. /// <response code="404">Item not found.</response>
  121. /// <returns>List of remote image providers.</returns>
  122. [HttpGet("Items/{itemId}/RemoteImages/Providers")]
  123. [Authorize(Policy = Policies.DefaultAuthorization)]
  124. [ProducesResponseType(StatusCodes.Status200OK)]
  125. [ProducesResponseType(StatusCodes.Status404NotFound)]
  126. public ActionResult<IEnumerable<ImageProviderInfo>> GetRemoteImageProviders([FromRoute, Required] Guid itemId)
  127. {
  128. var item = _libraryManager.GetItemById(itemId);
  129. if (item == null)
  130. {
  131. return NotFound();
  132. }
  133. return Ok(_providerManager.GetRemoteImageProviderInfo(item));
  134. }
  135. /// <summary>
  136. /// Gets a remote image.
  137. /// </summary>
  138. /// <param name="imageUrl">The image url.</param>
  139. /// <response code="200">Remote image returned.</response>
  140. /// <response code="404">Remote image not found.</response>
  141. /// <returns>Image Stream.</returns>
  142. [HttpGet("Images/Remote")]
  143. [Produces(MediaTypeNames.Application.Octet)]
  144. [ProducesResponseType(StatusCodes.Status200OK)]
  145. [ProducesResponseType(StatusCodes.Status404NotFound)]
  146. public async Task<ActionResult> GetRemoteImage([FromQuery, Required] string imageUrl)
  147. {
  148. var urlHash = imageUrl.GetMD5();
  149. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  150. string? contentPath = null;
  151. var hasFile = false;
  152. try
  153. {
  154. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  155. if (System.IO.File.Exists(contentPath))
  156. {
  157. hasFile = true;
  158. }
  159. }
  160. catch (FileNotFoundException)
  161. {
  162. // The file isn't cached yet
  163. }
  164. catch (IOException)
  165. {
  166. // The file isn't cached yet
  167. }
  168. if (!hasFile)
  169. {
  170. await DownloadImage(imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  171. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  172. }
  173. if (string.IsNullOrEmpty(contentPath))
  174. {
  175. return NotFound();
  176. }
  177. var contentType = MimeTypes.GetMimeType(contentPath);
  178. return File(System.IO.File.OpenRead(contentPath), contentType);
  179. }
  180. /// <summary>
  181. /// Downloads a remote image for an item.
  182. /// </summary>
  183. /// <param name="itemId">Item Id.</param>
  184. /// <param name="type">The image type.</param>
  185. /// <param name="imageUrl">The image url.</param>
  186. /// <response code="204">Remote image downloaded.</response>
  187. /// <response code="404">Remote image not found.</response>
  188. /// <returns>Download status.</returns>
  189. [HttpPost("Items/{itemId}/RemoteImages/Download")]
  190. [Authorize(Policy = Policies.RequiresElevation)]
  191. [ProducesResponseType(StatusCodes.Status204NoContent)]
  192. [ProducesResponseType(StatusCodes.Status404NotFound)]
  193. public async Task<ActionResult> DownloadRemoteImage(
  194. [FromRoute, Required] Guid itemId,
  195. [FromQuery, Required] ImageType type,
  196. [FromQuery] string? imageUrl)
  197. {
  198. var item = _libraryManager.GetItemById(itemId);
  199. if (item == null)
  200. {
  201. return NotFound();
  202. }
  203. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  204. .ConfigureAwait(false);
  205. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  206. return NoContent();
  207. }
  208. /// <summary>
  209. /// Gets the full cache path.
  210. /// </summary>
  211. /// <param name="filename">The filename.</param>
  212. /// <returns>System.String.</returns>
  213. private string GetFullCachePath(string filename)
  214. {
  215. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  216. }
  217. /// <summary>
  218. /// Downloads the image.
  219. /// </summary>
  220. /// <param name="url">The URL.</param>
  221. /// <param name="urlHash">The URL hash.</param>
  222. /// <param name="pointerCachePath">The pointer cache path.</param>
  223. /// <returns>Task.</returns>
  224. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
  225. {
  226. var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
  227. using var response = await httpClient.GetAsync(url).ConfigureAwait(false);
  228. var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last();
  229. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  230. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  231. await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  232. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  233. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  234. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  235. .ConfigureAwait(false);
  236. }
  237. }
  238. }