RemoteImageController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. try
  74. {
  75. var item = _libraryManager.GetItemById(id);
  76. if (item == null)
  77. {
  78. return NotFound();
  79. }
  80. var images = await _providerManager.GetAvailableRemoteImages(
  81. item,
  82. new RemoteImageQuery
  83. {
  84. ProviderName = providerName,
  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 Ok(result);
  113. }
  114. catch (Exception e)
  115. {
  116. return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
  117. }
  118. }
  119. /// <summary>
  120. /// Gets available remote image providers for an item.
  121. /// </summary>
  122. /// <param name="id">Item Id.</param>
  123. /// <returns>List of providers.</returns>
  124. [HttpGet("{Id}/RemoteImages/Providers")]
  125. [ProducesResponseType(typeof(ImageProviderInfo[]), StatusCodes.Status200OK)]
  126. [ProducesResponseType(StatusCodes.Status404NotFound)]
  127. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  128. public IActionResult GetRemoteImageProviders([FromRoute] string id)
  129. {
  130. try
  131. {
  132. var item = _libraryManager.GetItemById(id);
  133. if (item == null)
  134. {
  135. return NotFound();
  136. }
  137. var providers = _providerManager.GetRemoteImageProviderInfo(item);
  138. return Ok(providers);
  139. }
  140. catch (Exception e)
  141. {
  142. return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
  143. }
  144. }
  145. /// <summary>
  146. /// Gets a remote image.
  147. /// </summary>
  148. /// <param name="imageUrl">The image url.</param>
  149. /// <returns>Image Stream.</returns>
  150. [HttpGet("Remote")]
  151. [ProducesResponseType(typeof(FileStreamResult), StatusCodes.Status200OK)]
  152. [ProducesResponseType(StatusCodes.Status404NotFound)]
  153. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  154. public async Task<IActionResult> GetRemoteImage([FromQuery, BindRequired] string imageUrl)
  155. {
  156. try
  157. {
  158. var urlHash = imageUrl.GetMD5();
  159. var pointerCachePath = GetFullCachePath(urlHash.ToString());
  160. string? contentPath = null;
  161. bool hasFile = false;
  162. try
  163. {
  164. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  165. if (System.IO.File.Exists(contentPath))
  166. {
  167. hasFile = true;
  168. }
  169. }
  170. catch (FileNotFoundException)
  171. {
  172. // Means the file isn't cached yet
  173. }
  174. catch (IOException)
  175. {
  176. // Means the file isn't cached yet
  177. }
  178. if (!hasFile)
  179. {
  180. await DownloadImage(imageUrl, urlHash, pointerCachePath).ConfigureAwait(false);
  181. contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false);
  182. }
  183. if (string.IsNullOrEmpty(contentPath))
  184. {
  185. return NotFound();
  186. }
  187. var contentType = MimeTypes.GetMimeType(contentPath);
  188. return new FileStreamResult(System.IO.File.OpenRead(contentPath), contentType);
  189. }
  190. catch (Exception e)
  191. {
  192. return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
  193. }
  194. }
  195. /// <summary>
  196. /// Downloads a remote image for an item.
  197. /// </summary>
  198. /// <param name="id">Item Id.</param>
  199. /// <param name="type">The image type.</param>
  200. /// <param name="imageUrl">The image url.</param>
  201. /// <returns>Status.</returns>
  202. [HttpPost("{Id}/RemoteImages/Download")]
  203. [ProducesResponseType(StatusCodes.Status200OK)]
  204. [ProducesResponseType(StatusCodes.Status404NotFound)]
  205. [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
  206. public async Task<IActionResult> DownloadRemoteImage(
  207. [FromRoute] string id,
  208. [FromQuery, BindRequired] ImageType type,
  209. [FromQuery] string imageUrl)
  210. {
  211. try
  212. {
  213. var item = _libraryManager.GetItemById(id);
  214. if (item == null)
  215. {
  216. return NotFound();
  217. }
  218. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  219. .ConfigureAwait(false);
  220. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  221. return Ok();
  222. }
  223. catch (Exception e)
  224. {
  225. return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
  226. }
  227. }
  228. /// <summary>
  229. /// Gets the full cache path.
  230. /// </summary>
  231. /// <param name="filename">The filename.</param>
  232. /// <returns>System.String.</returns>
  233. private string GetFullCachePath(string filename)
  234. {
  235. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  236. }
  237. /// <summary>
  238. /// Downloads the image.
  239. /// </summary>
  240. /// <param name="url">The URL.</param>
  241. /// <param name="urlHash">The URL hash.</param>
  242. /// <param name="pointerCachePath">The pointer cache path.</param>
  243. /// <returns>Task.</returns>
  244. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
  245. {
  246. using var result = await _httpClient.GetResponse(new HttpRequestOptions
  247. {
  248. Url = url,
  249. BufferContent = false
  250. }).ConfigureAwait(false);
  251. var ext = result.ContentType.Split('/').Last();
  252. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  253. Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
  254. using (var stream = result.Content)
  255. {
  256. using var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  257. await stream.CopyToAsync(filestream).ConfigureAwait(false);
  258. }
  259. Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
  260. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  261. .ConfigureAwait(false);
  262. }
  263. }
  264. }