RemoteImageController.cs 9.8 KB

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