RemoteImageController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net.Mime;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Constants;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Net;
  17. using MediaBrowser.Model.Providers;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Mvc;
  21. using Microsoft.AspNetCore.Mvc.ModelBinding;
  22. namespace Jellyfin.Api.Controllers
  23. {
  24. /// <summary>
  25. /// Remote Images Controller.
  26. /// </summary>
  27. [Route("Images")]
  28. [Authorize(Policy = Policies.DefaultAuthorization)]
  29. public class RemoteImageController : BaseJellyfinApiController
  30. {
  31. private readonly IProviderManager _providerManager;
  32. private readonly IServerApplicationPaths _applicationPaths;
  33. private readonly IHttpClient _httpClient;
  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="httpClient">Instance of the <see cref="IHttpClient"/> interface.</param>
  41. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  42. public RemoteImageController(
  43. IProviderManager providerManager,
  44. IServerApplicationPaths applicationPaths,
  45. IHttpClient httpClient,
  46. ILibraryManager libraryManager)
  47. {
  48. _providerManager = providerManager;
  49. _applicationPaths = applicationPaths;
  50. _httpClient = httpClient;
  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("{itemId}/RemoteImages")]
  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)
  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("{itemId}/RemoteImages/Providers")]
  122. [ProducesResponseType(StatusCodes.Status200OK)]
  123. [ProducesResponseType(StatusCodes.Status404NotFound)]
  124. public ActionResult<IEnumerable<ImageProviderInfo>> GetRemoteImageProviders([FromRoute] Guid itemId)
  125. {
  126. var item = _libraryManager.GetItemById(itemId);
  127. if (item == null)
  128. {
  129. return NotFound();
  130. }
  131. return Ok(_providerManager.GetRemoteImageProviderInfo(item));
  132. }
  133. /// <summary>
  134. /// Gets a remote image.
  135. /// </summary>
  136. /// <param name="imageUrl">The image url.</param>
  137. /// <response code="200">Remote image returned.</response>
  138. /// <response code="404">Remote image not found.</response>
  139. /// <returns>Image Stream.</returns>
  140. [HttpGet("Remote")]
  141. [Produces(MediaTypeNames.Application.Octet)]
  142. [ProducesResponseType(StatusCodes.Status200OK)]
  143. [ProducesResponseType(StatusCodes.Status404NotFound)]
  144. public async Task<ActionResult<FileStreamResult>> GetRemoteImage([FromQuery, BindRequired] string imageUrl)
  145. {
  146. var urlHash = imageUrl.GetMD5();
  147. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  148. string? contentPath = null;
  149. var hasFile = false;
  150. try
  151. {
  152. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  153. if (System.IO.File.Exists(contentPath))
  154. {
  155. hasFile = true;
  156. }
  157. }
  158. catch (FileNotFoundException)
  159. {
  160. // The file isn't cached yet
  161. }
  162. catch (IOException)
  163. {
  164. // The file isn't cached yet
  165. }
  166. if (!hasFile)
  167. {
  168. await DownloadImage(imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  169. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  170. }
  171. if (string.IsNullOrEmpty(contentPath))
  172. {
  173. return NotFound();
  174. }
  175. var contentType = MimeTypes.GetMimeType(contentPath);
  176. return File(System.IO.File.OpenRead(contentPath), contentType);
  177. }
  178. /// <summary>
  179. /// Downloads a remote image for an item.
  180. /// </summary>
  181. /// <param name="itemId">Item Id.</param>
  182. /// <param name="type">The image type.</param>
  183. /// <param name="imageUrl">The image url.</param>
  184. /// <response code="204">Remote image downloaded.</response>
  185. /// <response code="404">Remote image not found.</response>
  186. /// <returns>Download status.</returns>
  187. [HttpPost("{itemId}/RemoteImages/Download")]
  188. [ProducesResponseType(StatusCodes.Status204NoContent)]
  189. [ProducesResponseType(StatusCodes.Status404NotFound)]
  190. public async Task<ActionResult> DownloadRemoteImage(
  191. [FromRoute] Guid itemId,
  192. [FromQuery, BindRequired] ImageType type,
  193. [FromQuery] string? imageUrl)
  194. {
  195. var item = _libraryManager.GetItemById(itemId);
  196. if (item == null)
  197. {
  198. return NotFound();
  199. }
  200. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  201. .ConfigureAwait(false);
  202. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  203. return NoContent();
  204. }
  205. /// <summary>
  206. /// Gets the full cache path.
  207. /// </summary>
  208. /// <param name="filename">The filename.</param>
  209. /// <returns>System.String.</returns>
  210. private string GetFullCachePath(string filename)
  211. {
  212. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  213. }
  214. /// <summary>
  215. /// Downloads the image.
  216. /// </summary>
  217. /// <param name="url">The URL.</param>
  218. /// <param name="urlHash">The URL hash.</param>
  219. /// <param name="pointerCachePath">The pointer cache path.</param>
  220. /// <returns>Task.</returns>
  221. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
  222. {
  223. using var result = await _httpClient.GetResponse(new HttpRequestOptions
  224. {
  225. Url = url,
  226. BufferContent = false
  227. }).ConfigureAwait(false);
  228. var ext = result.ContentType.Split('/').Last();
  229. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  230. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  231. await using (var stream = result.Content)
  232. {
  233. await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  234. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  235. }
  236. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  237. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  238. .ConfigureAwait(false);
  239. }
  240. }
  241. }