RemoteImageController.cs 10 KB

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