RemoteImageController.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Api.Constants;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Providers;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Http;
  21. using Microsoft.AspNetCore.Mvc;
  22. namespace Jellyfin.Api.Controllers
  23. {
  24. /// <summary>
  25. /// Remote Images Controller.
  26. /// </summary>
  27. [Route("")]
  28. public class RemoteImageController : BaseJellyfinApiController
  29. {
  30. private readonly IProviderManager _providerManager;
  31. private readonly IServerApplicationPaths _applicationPaths;
  32. private readonly IHttpClientFactory _httpClientFactory;
  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="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
  40. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  41. public RemoteImageController(
  42. IProviderManager providerManager,
  43. IServerApplicationPaths applicationPaths,
  44. IHttpClientFactory httpClientFactory,
  45. ILibraryManager libraryManager)
  46. {
  47. _providerManager = providerManager;
  48. _applicationPaths = applicationPaths;
  49. _httpClientFactory = httpClientFactory;
  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("Items/{itemId}/RemoteImages")]
  65. [Authorize(Policy = Policies.DefaultAuthorization)]
  66. [ProducesResponseType(StatusCodes.Status200OK)]
  67. [ProducesResponseType(StatusCodes.Status404NotFound)]
  68. public async Task<ActionResult<RemoteImageResult>> GetRemoteImages(
  69. [FromRoute, Required] Guid itemId,
  70. [FromQuery] ImageType? type,
  71. [FromQuery] int? startIndex,
  72. [FromQuery] int? limit,
  73. [FromQuery] string? providerName,
  74. [FromQuery] bool includeAllLanguages = false)
  75. {
  76. var item = _libraryManager.GetItemById(itemId);
  77. if (item == null)
  78. {
  79. return NotFound();
  80. }
  81. var images = await _providerManager.GetAvailableRemoteImages(
  82. item,
  83. new RemoteImageQuery(providerName ?? string.Empty)
  84. {
  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 result;
  113. }
  114. /// <summary>
  115. /// Gets available remote image providers for an item.
  116. /// </summary>
  117. /// <param name="itemId">Item Id.</param>
  118. /// <response code="200">Returned remote image providers.</response>
  119. /// <response code="404">Item not found.</response>
  120. /// <returns>List of remote image providers.</returns>
  121. [HttpGet("Items/{itemId}/RemoteImages/Providers")]
  122. [Authorize(Policy = Policies.DefaultAuthorization)]
  123. [ProducesResponseType(StatusCodes.Status200OK)]
  124. [ProducesResponseType(StatusCodes.Status404NotFound)]
  125. public ActionResult<IEnumerable<ImageProviderInfo>> GetRemoteImageProviders([FromRoute, Required] Guid itemId)
  126. {
  127. var item = _libraryManager.GetItemById(itemId);
  128. if (item == null)
  129. {
  130. return NotFound();
  131. }
  132. return Ok(_providerManager.GetRemoteImageProviderInfo(item));
  133. }
  134. /// <summary>
  135. /// Downloads a remote image for an item.
  136. /// </summary>
  137. /// <param name="itemId">Item Id.</param>
  138. /// <param name="type">The image type.</param>
  139. /// <param name="imageUrl">The image url.</param>
  140. /// <response code="204">Remote image downloaded.</response>
  141. /// <response code="404">Remote image not found.</response>
  142. /// <returns>Download status.</returns>
  143. [HttpPost("Items/{itemId}/RemoteImages/Download")]
  144. [Authorize(Policy = Policies.RequiresElevation)]
  145. [ProducesResponseType(StatusCodes.Status204NoContent)]
  146. [ProducesResponseType(StatusCodes.Status404NotFound)]
  147. public async Task<ActionResult> DownloadRemoteImage(
  148. [FromRoute, Required] Guid itemId,
  149. [FromQuery, Required] ImageType type,
  150. [FromQuery] string? imageUrl)
  151. {
  152. var item = _libraryManager.GetItemById(itemId);
  153. if (item == null)
  154. {
  155. return NotFound();
  156. }
  157. await _providerManager.SaveImage(item, imageUrl, type, null, CancellationToken.None)
  158. .ConfigureAwait(false);
  159. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  160. return NoContent();
  161. }
  162. /// <summary>
  163. /// Gets the full cache path.
  164. /// </summary>
  165. /// <param name="filename">The filename.</param>
  166. /// <returns>System.String.</returns>
  167. private string GetFullCachePath(string filename)
  168. {
  169. return Path.Combine(_applicationPaths.CachePath, "remote-images", filename.Substring(0, 1), filename);
  170. }
  171. /// <summary>
  172. /// Downloads the image.
  173. /// </summary>
  174. /// <param name="url">The URL.</param>
  175. /// <param name="urlHash">The URL hash.</param>
  176. /// <param name="pointerCachePath">The pointer cache path.</param>
  177. /// <returns>Task.</returns>
  178. private async Task DownloadImage(Uri url, Guid urlHash, string pointerCachePath)
  179. {
  180. var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
  181. using var response = await httpClient.GetAsync(url).ConfigureAwait(false);
  182. if (response.Content.Headers.ContentType?.MediaType == null)
  183. {
  184. throw new ResourceNotFoundException(nameof(response.Content.Headers.ContentType));
  185. }
  186. var ext = response.Content.Headers.ContentType.MediaType.AsSpan().RightPart('/').ToString();
  187. var fullCachePath = GetFullCachePath(urlHash + "." + ext);
  188. var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid.");
  189. Directory.CreateDirectory(fullCacheDirectory);
  190. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  191. await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, AsyncFile.UseAsyncIO);
  192. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  193. var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath));
  194. Directory.CreateDirectory(pointerCacheDirectory);
  195. await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
  196. .ConfigureAwait(false);
  197. }
  198. }
  199. }