RemoteImageController.cs 9.4 KB

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