RemoteImageController.cs 11 KB

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