RemoteImageController.cs 11 KB

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