RemoteImageController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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(typeof(RemoteImageResult), StatusCodes.Status200OK)]
  63. [ProducesResponseType(StatusCodes.Status404NotFound)]
  64. [ProducesResponseType(typeof(string), StatusCodes.Status404NotFound)]
  65. public async Task<IActionResult> GetRemoteImages(
  66. [FromRoute] string id,
  67. [FromQuery] ImageType? type,
  68. [FromQuery] int? startIndex,
  69. [FromQuery] int? limit,
  70. [FromQuery] string providerName,
  71. [FromQuery] bool includeAllLanguages)
  72. {
  73. var item = _libraryManager.GetItemById(id);
  74. if (item == null)
  75. {
  76. return NotFound();
  77. }
  78. var images = await _providerManager.GetAvailableRemoteImages(
  79. item,
  80. new RemoteImageQuery
  81. {
  82. ProviderName = providerName,
  83. IncludeAllLanguages = includeAllLanguages,
  84. IncludeDisabledProviders = true,
  85. ImageType = type
  86. }, CancellationToken.None)
  87. .ConfigureAwait(false);
  88. var imageArray = images.ToArray();
  89. var allProviders = _providerManager.GetRemoteImageProviderInfo(item);
  90. if (type.HasValue)
  91. {
  92. allProviders = allProviders.Where(o => o.SupportedImages.Contains(type.Value));
  93. }
  94. var result = new RemoteImageResult
  95. {
  96. TotalRecordCount = imageArray.Length,
  97. Providers = allProviders.Select(o => o.Name)
  98. .Distinct(StringComparer.OrdinalIgnoreCase)
  99. .ToArray()
  100. };
  101. if (startIndex.HasValue)
  102. {
  103. imageArray = imageArray.Skip(startIndex.Value).ToArray();
  104. }
  105. if (limit.HasValue)
  106. {
  107. imageArray = imageArray.Take(limit.Value).ToArray();
  108. }
  109. result.Images = imageArray;
  110. return Ok(result);
  111. }
  112. /// <summary>
  113. /// Gets available remote image providers for an item.
  114. /// </summary>
  115. /// <param name="id">Item Id.</param>
  116. /// <returns>List of providers.</returns>
  117. [HttpGet("{Id}/RemoteImages/Providers")]
  118. [ProducesResponseType(typeof(ImageProviderInfo[]), StatusCodes.Status200OK)]
  119. [ProducesResponseType(StatusCodes.Status404NotFound)]
  120. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  121. public IActionResult GetRemoteImageProviders([FromRoute] string id)
  122. {
  123. var item = _libraryManager.GetItemById(id);
  124. if (item == null)
  125. {
  126. return NotFound();
  127. }
  128. var providers = _providerManager.GetRemoteImageProviderInfo(item);
  129. return Ok(providers);
  130. }
  131. /// <summary>
  132. /// Gets a remote image.
  133. /// </summary>
  134. /// <param name="imageUrl">The image url.</param>
  135. /// <returns>Image Stream.</returns>
  136. [HttpGet("Remote")]
  137. [ProducesResponseType(typeof(FileStreamResult), StatusCodes.Status200OK)]
  138. [ProducesResponseType(StatusCodes.Status404NotFound)]
  139. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  140. public async Task<IActionResult> GetRemoteImage([FromQuery, BindRequired] string imageUrl)
  141. {
  142. var urlHash = imageUrl.GetMD5();
  143. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  144. string? contentPath = null;
  145. bool hasFile = false;
  146. try
  147. {
  148. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  149. if (System.IO.File.Exists(contentPath))
  150. {
  151. hasFile = true;
  152. }
  153. }
  154. catch (FileNotFoundException)
  155. {
  156. // Means the file isn't cached yet
  157. }
  158. catch (IOException)
  159. {
  160. // Means the file isn't cached yet
  161. }
  162. if (!hasFile)
  163. {
  164. await DownloadImage(imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  165. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  166. }
  167. if (string.IsNullOrEmpty(contentPath))
  168. {
  169. return NotFound();
  170. }
  171. var contentType = MimeTypes.GetMimeType(contentPath);
  172. return new FileStreamResult(System.IO.File.OpenRead(contentPath), contentType);
  173. }
  174. /// <summary>
  175. /// Downloads a remote image for an item.
  176. /// </summary>
  177. /// <param name="id">Item Id.</param>
  178. /// <param name="type">The image type.</param>
  179. /// <param name="imageUrl">The image url.</param>
  180. /// <returns>Status.</returns>
  181. [HttpPost("{Id}/RemoteImages/Download")]
  182. [ProducesResponseType(StatusCodes.Status200OK)]
  183. [ProducesResponseType(StatusCodes.Status404NotFound)]
  184. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  185. public async Task<IActionResult> DownloadRemoteImage(
  186. [FromRoute] string id,
  187. [FromQuery, BindRequired] ImageType type,
  188. [FromQuery] string imageUrl)
  189. {
  190. var item = _libraryManager.GetItemById(id);
  191. if (item == null)
  192. {
  193. return NotFound();
  194. }
  195. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  196. .ConfigureAwait(false);
  197. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  198. return Ok();
  199. }
  200. /// <summary>
  201. /// Gets the full cache path.
  202. /// </summary>
  203. /// <param name="filename">The filename.</param>
  204. /// <returns>System.String.</returns>
  205. private string GetFullCachePath(string filename)
  206. {
  207. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  208. }
  209. /// <summary>
  210. /// Downloads the image.
  211. /// </summary>
  212. /// <param name="url">The URL.</param>
  213. /// <param name="urlHash">The URL hash.</param>
  214. /// <param name="pointerCachePath">The pointer cache path.</param>
  215. /// <returns>Task.</returns>
  216. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
  217. {
  218. using var result = await _httpClient.GetResponse(new HttpRequestOptions
  219. {
  220. Url = url,
  221. BufferContent = false
  222. }).ConfigureAwait(false);
  223. var ext = result.ContentType.Split('/').Last();
  224. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  225. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  226. using (var stream = result.Content)
  227. {
  228. using var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  229. await stream.CopyToAsync(filestream).ConfigureAwait(false);
  230. }
  231. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  232. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  233. .ConfigureAwait(false);
  234. }
  235. }
  236. }