RemoteImageController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Mime;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  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.Images
  23. {
  24. /// <summary>
  25. /// Remote Images Controller.
  26. /// </summary>
  27. [Route("Images")]
  28. [Authorize]
  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="id">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("{Id}/RemoteImages")]
  66. [ProducesResponseType(StatusCodes.Status200OK)]
  67. [ProducesResponseType(StatusCodes.Status404NotFound)]
  68. public async Task<ActionResult<RemoteImageResult>> GetRemoteImages(
  69. [FromRoute] string id,
  70. [FromQuery] ImageType? type,
  71. [FromQuery] int? startIndex,
  72. [FromQuery] int? limit,
  73. [FromQuery] string providerName,
  74. [FromQuery] bool includeAllLanguages)
  75. {
  76. var item = _libraryManager.GetItemById(id);
  77. if (item == null)
  78. {
  79. return NotFound();
  80. }
  81. var images = await _providerManager.GetAvailableRemoteImages(
  82. item,
  83. new RemoteImageQuery
  84. {
  85. ProviderName = providerName,
  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="id">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("{Id}/RemoteImages/Providers")]
  123. [ProducesResponseType(StatusCodes.Status200OK)]
  124. [ProducesResponseType(StatusCodes.Status404NotFound)]
  125. public ActionResult<IEnumerable<ImageProviderInfo>> GetRemoteImageProviders([FromRoute] string id)
  126. {
  127. var item = _libraryManager.GetItemById(id);
  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("Remote")]
  142. [Produces(MediaTypeNames.Application.Octet)]
  143. [ProducesResponseType(StatusCodes.Status200OK)]
  144. [ProducesResponseType(StatusCodes.Status404NotFound)]
  145. public async Task<ActionResult<FileStreamResult>> GetRemoteImage([FromQuery, BindRequired] 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 new FileStreamResult(System.IO.File.OpenRead(contentPath), contentType);
  178. }
  179. /// <summary>
  180. /// Downloads a remote image for an item.
  181. /// </summary>
  182. /// <param name="id">Item Id.</param>
  183. /// <param name="type">The image type.</param>
  184. /// <param name="imageUrl">The image url.</param>
  185. /// <response code="200">Remote image downloaded.</response>
  186. /// <response code="404">Remote image not found.</response>
  187. /// <returns>Download status.</returns>
  188. [HttpPost("{Id}/RemoteImages/Download")]
  189. [ProducesResponseType(StatusCodes.Status200OK)]
  190. [ProducesResponseType(StatusCodes.Status404NotFound)]
  191. public async Task<ActionResult> DownloadRemoteImage(
  192. [FromRoute] string id,
  193. [FromQuery, BindRequired] ImageType type,
  194. [FromQuery] string imageUrl)
  195. {
  196. var item = _libraryManager.GetItemById(id);
  197. if (item == null)
  198. {
  199. return NotFound();
  200. }
  201. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  202. .ConfigureAwait(false);
  203. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  204. return Ok();
  205. }
  206. /// <summary>
  207. /// Gets the full cache path.
  208. /// </summary>
  209. /// <param name="filename">The filename.</param>
  210. /// <returns>System.String.</returns>
  211. private string GetFullCachePath(string filename)
  212. {
  213. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  214. }
  215. /// <summary>
  216. /// Downloads the image.
  217. /// </summary>
  218. /// <param name="url">The URL.</param>
  219. /// <param name="urlHash">The URL hash.</param>
  220. /// <param name="pointerCachePath">The pointer cache path.</param>
  221. /// <returns>Task.</returns>
  222. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
  223. {
  224. using var result = await _httpClient.GetResponse(new HttpRequestOptions
  225. {
  226. Url = url,
  227. BufferContent = false
  228. }).ConfigureAwait(false);
  229. var ext = result.ContentType.Split('/').Last();
  230. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  231. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  232. await using (var stream = result.Content)
  233. {
  234. await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  235. await stream.CopyToAsync(fileStream).ConfigureAwait(false);
  236. }
  237. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  238. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  239. .ConfigureAwait(false);
  240. }
  241. }
  242. }