jellyfin-server/MediaBrowser.Api/Images/ImageService.cs

787 lines
28 KiB
C#
Raw Normal View History

2014-05-07 02:28:19 +00:00
using MediaBrowser.Common.Extensions;
2013-09-18 18:49:06 +00:00
using MediaBrowser.Controller.Drawing;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
2013-06-18 19:16:27 +00:00
using MediaBrowser.Controller.Persistence;
2013-05-05 04:49:49 +00:00
using MediaBrowser.Controller.Providers;
2013-09-19 19:46:19 +00:00
using MediaBrowser.Model.Drawing;
2013-05-05 04:49:49 +00:00
using MediaBrowser.Model.Dto;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Model.Entities;
using System;
2013-05-05 04:49:49 +00:00
using System.Collections.Generic;
2013-02-21 01:33:05 +00:00
using System.IO;
using System.Linq;
using System.Threading;
2013-02-21 01:33:05 +00:00
using System.Threading.Tasks;
2017-05-26 06:48:54 +00:00
2017-05-22 04:54:02 +00:00
using MediaBrowser.Controller.Dto;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
2013-02-21 01:33:05 +00:00
namespace MediaBrowser.Api.Images
{
/// <summary>
/// Class GetItemImage
/// </summary>
2014-11-15 02:31:03 +00:00
[Route("/Items/{Id}/Images", "GET", Summary = "Gets information about an item's images")]
[Authenticated]
2013-05-05 04:49:49 +00:00
public class GetItemImageInfos : IReturn<List<ImageInfo>>
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get; set; }
}
2013-02-21 01:33:05 +00:00
[Route("/Items/{Id}/Images/{Type}", "GET")]
[Route("/Items/{Id}/Images/{Type}/{Index}", "GET")]
2014-09-26 03:47:46 +00:00
[Route("/Items/{Id}/Images/{Type}", "HEAD")]
[Route("/Items/{Id}/Images/{Type}/{Index}", "HEAD")]
2015-04-16 14:59:39 +00:00
[Route("/Items/{Id}/Images/{Type}/{Index}/{Tag}/{Format}/{MaxWidth}/{MaxHeight}/{PercentPlayed}/{UnplayedCount}", "GET")]
[Route("/Items/{Id}/Images/{Type}/{Index}/{Tag}/{Format}/{MaxWidth}/{MaxHeight}/{PercentPlayed}/{UnplayedCount}", "HEAD")]
2013-02-21 01:33:05 +00:00
public class GetItemImage : ImageRequest
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
2013-03-08 21:06:02 +00:00
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2013-02-21 01:33:05 +00:00
public string Id { get; set; }
}
2013-05-05 04:49:49 +00:00
/// <summary>
/// Class UpdateItemImageIndex
/// </summary>
2014-11-15 02:31:03 +00:00
[Route("/Items/{Id}/Images/{Type}/{Index}/Index", "POST", Summary = "Updates the index for an item image")]
2015-03-16 01:48:25 +00:00
[Authenticated(Roles = "admin")]
2013-05-05 04:49:49 +00:00
public class UpdateItemImageIndex : IReturnVoid
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2015-03-16 01:48:25 +00:00
public string Id { get; set; }
2013-05-05 04:49:49 +00:00
/// <summary>
/// Gets or sets the type of the image.
/// </summary>
/// <value>The type of the image.</value>
[ApiMember(Name = "Type", Description = "Image Type", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public ImageType Type { get; set; }
/// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
[ApiMember(Name = "Index", Description = "Image Index", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
public int Index { get; set; }
/// <summary>
/// Gets or sets the new index.
/// </summary>
/// <value>The new index.</value>
[ApiMember(Name = "NewIndex", Description = "The new image index", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public int NewIndex { get; set; }
}
2013-02-21 01:33:05 +00:00
/// <summary>
2013-08-03 14:38:56 +00:00
/// Class GetPersonImage
2013-02-21 01:33:05 +00:00
/// </summary>
2013-08-03 14:38:56 +00:00
[Route("/Artists/{Name}/Images/{Type}", "GET")]
[Route("/Artists/{Name}/Images/{Type}/{Index}", "GET")]
2013-02-21 01:33:05 +00:00
[Route("/Genres/{Name}/Images/{Type}", "GET")]
[Route("/Genres/{Name}/Images/{Type}/{Index}", "GET")]
2013-08-03 14:38:56 +00:00
[Route("/GameGenres/{Name}/Images/{Type}", "GET")]
[Route("/GameGenres/{Name}/Images/{Type}/{Index}", "GET")]
2013-06-11 03:31:00 +00:00
[Route("/MusicGenres/{Name}/Images/{Type}", "GET")]
[Route("/MusicGenres/{Name}/Images/{Type}/{Index}", "GET")]
2013-08-03 14:38:56 +00:00
[Route("/Persons/{Name}/Images/{Type}", "GET")]
[Route("/Persons/{Name}/Images/{Type}/{Index}", "GET")]
[Route("/Studios/{Name}/Images/{Type}", "GET")]
[Route("/Studios/{Name}/Images/{Type}/{Index}", "GET")]
[Route("/Years/{Year}/Images/{Type}", "GET")]
[Route("/Years/{Year}/Images/{Type}/{Index}", "GET")]
[Route("/Artists/{Name}/Images/{Type}", "HEAD")]
[Route("/Artists/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/Genres/{Name}/Images/{Type}", "HEAD")]
[Route("/Genres/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/GameGenres/{Name}/Images/{Type}", "HEAD")]
[Route("/GameGenres/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/MusicGenres/{Name}/Images/{Type}", "HEAD")]
[Route("/MusicGenres/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/Persons/{Name}/Images/{Type}", "HEAD")]
[Route("/Persons/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/Studios/{Name}/Images/{Type}", "HEAD")]
[Route("/Studios/{Name}/Images/{Type}/{Index}", "HEAD")]
[Route("/Years/{Year}/Images/{Type}", "HEAD")]
[Route("/Years/{Year}/Images/{Type}/{Index}", "HEAD")]
2013-08-03 14:38:56 +00:00
public class GetItemByNameImage : ImageRequest
2013-06-11 03:31:00 +00:00
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
2013-08-03 14:38:56 +00:00
[ApiMember(Name = "Name", Description = "Item name", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2013-06-11 03:31:00 +00:00
public string Name { get; set; }
}
2013-07-01 17:17:33 +00:00
2013-08-03 14:38:56 +00:00
/// <summary>
/// Class GetUserImage
/// </summary>
[Route("/Users/{Id}/Images/{Type}", "GET")]
[Route("/Users/{Id}/Images/{Type}/{Index}", "GET")]
2014-09-30 04:47:30 +00:00
[Route("/Users/{Id}/Images/{Type}", "HEAD")]
[Route("/Users/{Id}/Images/{Type}/{Index}", "HEAD")]
2013-08-03 14:38:56 +00:00
public class GetUserImage : ImageRequest
2013-07-01 17:17:33 +00:00
{
/// <summary>
2013-08-03 14:38:56 +00:00
/// Gets or sets the id.
2013-07-01 17:17:33 +00:00
/// </summary>
2013-08-03 14:38:56 +00:00
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2015-03-16 01:48:25 +00:00
public string Id { get; set; }
2013-07-01 17:17:33 +00:00
}
2013-02-21 01:33:05 +00:00
/// <summary>
2013-08-03 14:38:56 +00:00
/// Class DeleteItemImage
2013-02-21 01:33:05 +00:00
/// </summary>
2013-08-03 14:38:56 +00:00
[Route("/Items/{Id}/Images/{Type}", "DELETE")]
[Route("/Items/{Id}/Images/{Type}/{Index}", "DELETE")]
2015-03-16 01:48:25 +00:00
[Authenticated(Roles = "admin")]
2013-08-03 14:38:56 +00:00
public class DeleteItemImage : DeleteImageRequest, IReturnVoid
2013-02-21 01:33:05 +00:00
{
/// <summary>
2013-08-03 14:38:56 +00:00
/// Gets or sets the id.
2013-02-21 01:33:05 +00:00
/// </summary>
2013-08-03 14:38:56 +00:00
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
2015-03-16 01:48:25 +00:00
public string Id { get; set; }
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Class DeleteUserImage
/// </summary>
[Route("/Users/{Id}/Images/{Type}", "DELETE")]
[Route("/Users/{Id}/Images/{Type}/{Index}", "DELETE")]
[Authenticated]
2013-02-25 04:39:53 +00:00
public class DeleteUserImage : DeleteImageRequest, IReturnVoid
2013-02-21 01:33:05 +00:00
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
2013-03-08 21:06:02 +00:00
[ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
2015-03-16 01:48:25 +00:00
public string Id { get; set; }
2013-02-21 01:33:05 +00:00
}
2013-02-25 04:39:53 +00:00
2013-05-05 04:49:49 +00:00
/// <summary>
/// Class PostUserImage
/// </summary>
2013-02-25 04:39:53 +00:00
[Route("/Users/{Id}/Images/{Type}", "POST")]
[Route("/Users/{Id}/Images/{Type}/{Index}", "POST")]
[Authenticated]
2013-02-25 04:39:53 +00:00
public class PostUserImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
2013-03-08 21:06:02 +00:00
[ApiMember(Name = "Id", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
2015-03-16 01:48:25 +00:00
public string Id { get; set; }
2013-02-25 04:39:53 +00:00
/// <summary>
/// The raw Http Request Input Stream
/// </summary>
/// <value>The request stream.</value>
public Stream RequestStream { get; set; }
}
2013-05-05 04:49:49 +00:00
/// <summary>
/// Class PostItemImage
/// </summary>
[Route("/Items/{Id}/Images/{Type}", "POST")]
[Route("/Items/{Id}/Images/{Type}/{Index}", "POST")]
2015-03-16 01:48:25 +00:00
[Authenticated(Roles = "admin")]
public class PostItemImage : DeleteImageRequest, IRequiresRequestStream, IReturnVoid
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public string Id { get; set; }
/// <summary>
/// The raw Http Request Input Stream
/// </summary>
/// <value>The request stream.</value>
public Stream RequestStream { get; set; }
}
2013-05-05 04:49:49 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Class ImageService
/// </summary>
2013-03-16 05:52:33 +00:00
public class ImageService : BaseApiService
2013-02-21 01:33:05 +00:00
{
private readonly IUserManager _userManager;
private readonly ILibraryManager _libraryManager;
2013-05-05 04:49:49 +00:00
private readonly IProviderManager _providerManager;
2013-06-18 19:16:27 +00:00
private readonly IItemRepository _itemRepo;
2013-09-18 18:49:06 +00:00
private readonly IImageProcessor _imageProcessor;
2014-02-07 20:30:41 +00:00
private readonly IFileSystem _fileSystem;
2016-11-10 14:41:24 +00:00
private readonly IAuthorizationContext _authContext;
/// <summary>
/// Initializes a new instance of the <see cref="ImageService" /> class.
/// </summary>
2016-11-10 14:41:24 +00:00
public ImageService(IUserManager userManager, ILibraryManager libraryManager, IProviderManager providerManager, IItemRepository itemRepo, IImageProcessor imageProcessor, IFileSystem fileSystem, IAuthorizationContext authContext)
{
_userManager = userManager;
_libraryManager = libraryManager;
2013-05-05 04:49:49 +00:00
_providerManager = providerManager;
2013-06-18 19:16:27 +00:00
_itemRepo = itemRepo;
2013-09-18 18:49:06 +00:00
_imageProcessor = imageProcessor;
2014-02-07 20:30:41 +00:00
_fileSystem = fileSystem;
2016-11-10 14:41:24 +00:00
_authContext = authContext;
}
2013-05-05 04:49:49 +00:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get(GetItemImageInfos request)
{
2014-04-25 20:15:50 +00:00
var item = _libraryManager.GetItemById(request.Id);
2013-05-05 04:49:49 +00:00
2013-09-17 02:44:06 +00:00
var result = GetItemImageInfos(item);
2013-05-05 04:49:49 +00:00
return ToOptimizedSerializedResultUsingCache(result);
2013-05-05 04:49:49 +00:00
}
/// <summary>
/// Gets the item image infos.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Task{List{ImageInfo}}.</returns>
2013-09-17 02:44:06 +00:00
public List<ImageInfo> GetItemImageInfos(BaseItem item)
2013-05-05 04:49:49 +00:00
{
var list = new List<ImageInfo>();
2016-07-04 20:11:30 +00:00
var itemImages = item.ImageInfos;
foreach (var image in itemImages.Where(i => !item.AllowsMultipleImages(i.Type)))
2013-05-05 04:49:49 +00:00
{
2014-02-07 20:30:41 +00:00
var info = GetImageInfo(item, image, null);
2013-05-05 04:49:49 +00:00
if (info != null)
2013-05-05 04:49:49 +00:00
{
list.Add(info);
}
2013-05-05 04:49:49 +00:00
}
2016-07-04 20:11:30 +00:00
foreach (var imageType in itemImages.Select(i => i.Type).Distinct().Where(item.AllowsMultipleImages))
2013-05-05 04:49:49 +00:00
{
2014-02-07 20:30:41 +00:00
var index = 0;
2013-05-05 04:49:49 +00:00
2014-02-07 20:30:41 +00:00
// Prevent implicitly captured closure
var currentImageType = imageType;
2016-07-04 20:11:30 +00:00
foreach (var image in itemImages.Where(i => i.Type == currentImageType))
2013-05-05 04:49:49 +00:00
{
2014-02-07 20:30:41 +00:00
var info = GetImageInfo(item, image, index);
2013-05-05 04:49:49 +00:00
if (info != null)
{
list.Add(info);
}
index++;
}
2013-05-05 04:49:49 +00:00
}
return list;
}
2014-02-07 20:30:41 +00:00
private ImageInfo GetImageInfo(IHasImages item, ItemImageInfo info, int? imageIndex)
{
try
{
int? width = null;
int? height = null;
2015-10-18 13:10:30 +00:00
long length = 0;
try
{
2015-10-16 17:06:31 +00:00
if (info.IsLocalFile)
{
2016-11-01 03:07:45 +00:00
var fileInfo = _fileSystem.GetFileInfo(info.Path);
2015-10-18 13:10:30 +00:00
length = fileInfo.Length;
2015-10-16 17:06:31 +00:00
var size = _imageProcessor.GetImageSize(info);
2015-10-16 17:06:31 +00:00
width = Convert.ToInt32(size.Width);
height = Convert.ToInt32(size.Height);
2015-10-18 13:10:30 +00:00
2015-10-16 17:06:31 +00:00
}
}
catch
{
}
return new ImageInfo
{
2014-02-07 20:30:41 +00:00
Path = info.Path,
ImageIndex = imageIndex,
2014-02-07 20:30:41 +00:00
ImageType = info.Type,
ImageTag = _imageProcessor.GetImageCacheTag(item, info),
2015-10-18 13:10:30 +00:00
Size = length,
Width = width,
Height = height
};
}
2013-11-23 20:01:09 +00:00
catch (Exception ex)
{
2014-02-07 20:30:41 +00:00
Logger.ErrorException("Error getting image information for {0}", ex, info.Path);
return null;
}
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get(GetItemImage request)
{
2014-08-30 14:26:29 +00:00
var item = string.IsNullOrEmpty(request.Id) ?
2014-04-25 20:15:50 +00:00
_libraryManager.RootFolder :
_libraryManager.GetItemById(request.Id);
2013-02-21 01:33:05 +00:00
2014-08-08 04:36:51 +00:00
return GetImage(request, item, false);
}
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Head(GetItemImage request)
{
var item = string.IsNullOrEmpty(request.Id) ?
_libraryManager.RootFolder :
_libraryManager.GetItemById(request.Id);
return GetImage(request, item, true);
2013-02-21 01:33:05 +00:00
}
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get(GetUserImage request)
{
2014-09-28 15:27:26 +00:00
var item = _userManager.GetUserById(request.Id);
2013-02-21 01:33:05 +00:00
2014-08-08 04:36:51 +00:00
return GetImage(request, item, false);
2013-02-21 01:33:05 +00:00
}
2014-09-30 04:47:30 +00:00
public object Head(GetUserImage request)
{
var item = _userManager.GetUserById(request.Id);
return GetImage(request, item, true);
}
2013-08-03 14:38:56 +00:00
public object Get(GetItemByNameImage request)
2013-02-21 01:33:05 +00:00
{
2015-01-22 16:41:34 +00:00
var type = GetPathValue(0);
2013-02-21 01:33:05 +00:00
2017-05-22 04:54:02 +00:00
var item = GetItemByName(request.Name, type, _libraryManager, new DtoOptions(false));
2013-02-21 01:33:05 +00:00
2014-08-08 04:36:51 +00:00
return GetImage(request, item, false);
2013-02-21 01:33:05 +00:00
}
public object Head(GetItemByNameImage request)
{
2015-01-22 16:41:34 +00:00
var type = GetPathValue(0);
2017-05-22 04:54:02 +00:00
var item = GetItemByName(request.Name, type, _libraryManager, new DtoOptions(false));
return GetImage(request, item, true);
}
2013-04-22 04:38:03 +00:00
/// <summary>
2013-08-03 14:38:56 +00:00
/// Posts the specified request.
2013-04-22 04:38:03 +00:00
/// </summary>
/// <param name="request">The request.</param>
2013-08-03 14:38:56 +00:00
public void Post(PostUserImage request)
2013-04-22 04:38:03 +00:00
{
2015-03-16 01:48:25 +00:00
var userId = GetPathValue(1);
2017-04-21 20:03:07 +00:00
AssertCanUpdateUser(_authContext, _userManager, userId, true);
2013-05-05 04:49:49 +00:00
2015-01-22 16:41:34 +00:00
request.Type = (ImageType)Enum.Parse(typeof(ImageType), GetPathValue(3), true);
2013-02-21 01:33:05 +00:00
2015-03-16 01:48:25 +00:00
var item = _userManager.GetUserById(userId);
2013-02-21 01:33:05 +00:00
2013-12-07 15:52:38 +00:00
var task = PostImage(item, request.RequestStream, request.Type, Request.ContentType);
2013-06-11 03:31:00 +00:00
2013-08-03 14:38:56 +00:00
Task.WaitAll(task);
2013-06-11 03:31:00 +00:00
}
/// <summary>
/// Posts the specified request.
/// </summary>
/// <param name="request">The request.</param>
public void Post(PostItemImage request)
{
2015-03-16 01:48:25 +00:00
var id = GetPathValue(1);
2015-01-22 16:41:34 +00:00
request.Type = (ImageType)Enum.Parse(typeof(ImageType), GetPathValue(3), true);
var item = _libraryManager.GetItemById(id);
2013-12-07 15:52:38 +00:00
var task = PostImage(item, request.RequestStream, request.Type, Request.ContentType);
Task.WaitAll(task);
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Deletes the specified request.
/// </summary>
/// <param name="request">The request.</param>
public void Delete(DeleteUserImage request)
{
2015-03-16 01:48:25 +00:00
var userId = request.Id;
2017-04-21 20:03:07 +00:00
AssertCanUpdateUser(_authContext, _userManager, userId, true);
2015-03-16 01:48:25 +00:00
var item = _userManager.GetUserById(userId);
2013-02-21 01:33:05 +00:00
2014-02-07 20:30:41 +00:00
var task = item.DeleteImage(request.Type, request.Index ?? 0);
2013-02-21 01:33:05 +00:00
Task.WaitAll(task);
}
2013-05-05 04:49:49 +00:00
/// <summary>
/// Deletes the specified request.
/// </summary>
/// <param name="request">The request.</param>
public void Delete(DeleteItemImage request)
{
var item = _libraryManager.GetItemById(request.Id);
2014-02-07 20:30:41 +00:00
var task = item.DeleteImage(request.Type, request.Index ?? 0);
2013-05-05 04:49:49 +00:00
Task.WaitAll(task);
}
/// <summary>
/// Posts the specified request.
/// </summary>
/// <param name="request">The request.</param>
public void Post(UpdateItemImageIndex request)
{
var item = _libraryManager.GetItemById(request.Id);
var task = UpdateItemIndex(item, request.Type, request.Index, request.NewIndex);
Task.WaitAll(task);
}
/// <summary>
/// Updates the index of the item.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="currentIndex">Index of the current.</param>
/// <param name="newIndex">The new index.</param>
/// <returns>Task.</returns>
2013-12-19 21:51:32 +00:00
private Task UpdateItemIndex(IHasImages item, ImageType type, int currentIndex, int newIndex)
2013-05-05 04:49:49 +00:00
{
2013-12-19 21:51:32 +00:00
return item.SwapImages(type, currentIndex, newIndex);
2013-05-05 04:49:49 +00:00
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the image.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="item">The item.</param>
2014-08-08 04:36:51 +00:00
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
2013-02-21 01:33:05 +00:00
/// <returns>System.Object.</returns>
2014-08-08 04:36:51 +00:00
/// <exception cref="ResourceNotFoundException"></exception>
2016-06-19 06:18:29 +00:00
public Task<object> GetImage(ImageRequest request, IHasImages item, bool isHeadRequest)
2013-02-21 01:33:05 +00:00
{
2015-04-16 14:59:39 +00:00
if (request.PercentPlayed.HasValue)
{
if (request.PercentPlayed.Value <= 0)
{
request.PercentPlayed = null;
}
else if (request.PercentPlayed.Value >= 100)
{
request.PercentPlayed = null;
request.AddPlayedIndicator = true;
}
}
if (request.PercentPlayed.HasValue)
{
request.UnplayedCount = null;
}
if (request.UnplayedCount.HasValue)
{
if (request.UnplayedCount.Value <= 0)
{
request.UnplayedCount = null;
}
}
2014-02-07 20:30:41 +00:00
var imageInfo = GetImageInfo(request, item);
2013-02-21 01:33:05 +00:00
2014-02-07 20:30:41 +00:00
if (imageInfo == null)
2013-02-21 01:33:05 +00:00
{
throw new ResourceNotFoundException(string.Format("{0} does not have an image of type {1}", item.Name, request.Type));
2013-02-21 01:33:05 +00:00
}
2013-09-18 18:49:06 +00:00
var supportedImageEnhancers = request.EnableImageEnhancers ? _imageProcessor.ImageEnhancers.Where(i =>
{
try
{
return i.Supports(item, request.Type);
}
catch (Exception ex)
{
Logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
return false;
}
2013-06-05 12:35:18 +00:00
}).ToList() : new List<IImageEnhancer>();
2013-02-21 01:33:05 +00:00
2015-10-26 05:29:32 +00:00
var cropwhitespace = request.Type == ImageType.Logo || request.Type == ImageType.Art;
if (request.CropWhitespace.HasValue)
{
cropwhitespace = request.CropWhitespace.Value;
}
2015-11-09 18:18:37 +00:00
var outputFormats = GetOutputFormats(request, imageInfo, cropwhitespace, supportedImageEnhancers);
2013-02-21 01:33:05 +00:00
TimeSpan? cacheDuration = null;
if (!string.IsNullOrEmpty(request.Tag))
2013-02-21 01:33:05 +00:00
{
cacheDuration = TimeSpan.FromDays(365);
}
2014-02-28 05:22:36 +00:00
var responseHeaders = new Dictionary<string, string>
{
{"transferMode.dlna.org", "Interactive"},
{"realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*"}
};
2014-02-13 01:52:24 +00:00
2014-08-30 14:26:29 +00:00
return GetImageResult(item,
request,
imageInfo,
2015-10-26 05:29:32 +00:00
cropwhitespace,
2015-11-09 18:18:37 +00:00
outputFormats,
2014-08-30 14:26:29 +00:00
supportedImageEnhancers,
2014-07-17 22:21:35 +00:00
cacheDuration,
2014-08-08 04:36:51 +00:00
responseHeaders,
2016-06-19 06:18:29 +00:00
isHeadRequest);
2014-07-17 22:21:35 +00:00
}
2014-08-30 14:26:29 +00:00
private async Task<object> GetImageResult(IHasImages item,
2014-07-17 22:21:35 +00:00
ImageRequest request,
ItemImageInfo image,
2015-10-26 05:29:32 +00:00
bool cropwhitespace,
2015-11-09 18:18:37 +00:00
List<ImageFormat> supportedFormats,
2014-07-17 22:21:35 +00:00
List<IImageEnhancer> enhancers,
TimeSpan? cacheDuration,
2014-08-30 14:26:29 +00:00
IDictionary<string, string> headers,
2014-08-08 04:36:51 +00:00
bool isHeadRequest)
2014-07-17 22:21:35 +00:00
{
var options = new ImageProcessingOptions
2013-02-21 01:33:05 +00:00
{
2014-07-17 22:21:35 +00:00
CropWhiteSpace = cropwhitespace,
Enhancers = enhancers,
Height = request.Height,
ImageIndex = request.Index ?? 0,
Image = image,
Item = item,
2017-05-21 07:25:49 +00:00
ItemId = item.Id.ToString("N"),
ItemType = item.GetType().Name,
2014-07-17 22:21:35 +00:00
MaxHeight = request.MaxHeight,
MaxWidth = request.MaxWidth,
2015-10-27 14:02:30 +00:00
Quality = request.Quality ?? 100,
2014-07-17 22:21:35 +00:00
Width = request.Width,
AddPlayedIndicator = request.AddPlayedIndicator,
PercentPlayed = request.PercentPlayed ?? 0,
2014-07-17 22:21:35 +00:00
UnplayedCount = request.UnplayedCount,
2016-12-03 07:58:48 +00:00
Blur = request.Blur,
BackgroundColor = request.BackgroundColor,
2016-02-23 19:48:58 +00:00
ForegroundLayer = request.ForegroundLayer,
2015-11-09 18:18:37 +00:00
SupportedOutputFormats = supportedFormats
2014-07-17 22:21:35 +00:00
};
2013-02-21 01:33:05 +00:00
2015-11-09 18:18:37 +00:00
var imageResult = await _imageProcessor.ProcessImage(options).ConfigureAwait(false);
2014-07-17 22:21:35 +00:00
2015-05-22 19:16:14 +00:00
headers["Vary"] = "Accept";
2016-06-19 06:18:29 +00:00
return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
2014-08-30 14:26:29 +00:00
{
CacheDuration = cacheDuration,
ResponseHeaders = headers,
2015-11-09 18:18:37 +00:00
ContentType = imageResult.Item2,
2016-07-17 16:59:40 +00:00
DateLastModified = imageResult.Item3,
2014-08-30 14:26:29 +00:00
IsHeadRequest = isHeadRequest,
2015-12-13 04:53:56 +00:00
Path = imageResult.Item1,
// Sometimes imagemagick keeps a hold on the file briefly even after it's done writing to it.
// I'd rather do this than add a delay after saving the file
2016-10-25 19:02:04 +00:00
FileShare = FileShareMode.ReadWrite
2016-06-19 06:18:29 +00:00
}).ConfigureAwait(false);
2013-02-21 01:33:05 +00:00
}
2015-11-09 18:18:37 +00:00
private List<ImageFormat> GetOutputFormats(ImageRequest request, ItemImageInfo image, bool cropwhitespace, List<IImageEnhancer> enhancers)
{
if (!string.IsNullOrWhiteSpace(request.Format))
{
2014-11-29 19:51:30 +00:00
ImageFormat format;
if (Enum.TryParse(request.Format, true, out format))
{
2015-11-09 18:18:37 +00:00
return new List<ImageFormat> { format };
}
}
2015-10-26 05:29:32 +00:00
var extension = Path.GetExtension(image.Path);
ImageFormat? inputFormat = null;
if (string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
{
inputFormat = ImageFormat.Jpg;
}
else if (string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase))
{
inputFormat = ImageFormat.Png;
}
var clientSupportedFormats = GetClientSupportedFormats();
var serverFormats = _imageProcessor.GetSupportedImageOutputFormats();
2015-11-09 18:18:37 +00:00
var outputFormats = new List<ImageFormat>();
2015-10-26 05:29:32 +00:00
// Client doesn't care about format, so start with webp if supported
if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp))
{
2015-11-09 18:18:37 +00:00
outputFormats.Add(ImageFormat.Webp);
}
if (enhancers.Count > 0)
{
2015-11-09 18:18:37 +00:00
outputFormats.Add(ImageFormat.Png);
}
2015-10-26 05:29:32 +00:00
if (inputFormat.HasValue && inputFormat.Value == ImageFormat.Jpg)
{
2015-11-09 18:18:37 +00:00
outputFormats.Add(ImageFormat.Jpg);
}
// We can't predict if there will be transparency or not, so play it safe
2015-11-09 18:18:37 +00:00
outputFormats.Add(ImageFormat.Png);
return outputFormats;
}
2014-11-29 19:51:30 +00:00
private ImageFormat[] GetClientSupportedFormats()
{
2016-03-10 20:07:05 +00:00
//Logger.Debug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? new string[] { }));
2015-10-26 05:29:32 +00:00
var supportsWebP = (Request.AcceptTypes ?? new string[] { }).Contains("image/webp", StringComparer.OrdinalIgnoreCase);
2015-06-03 15:26:39 +00:00
var userAgent = Request.UserAgent ?? string.Empty;
2015-11-11 19:06:56 +00:00
if (!supportsWebP)
{
2015-11-11 19:06:56 +00:00
if (string.Equals(Request.QueryString["accept"], "webp", StringComparison.OrdinalIgnoreCase))
{
supportsWebP = true;
}
}
if (!supportsWebP)
{
if (userAgent.IndexOf("crosswalk", StringComparison.OrdinalIgnoreCase) != -1 &&
userAgent.IndexOf("android", StringComparison.OrdinalIgnoreCase) != -1)
{
supportsWebP = true;
}
2015-06-03 15:26:39 +00:00
}
2014-11-26 04:12:29 +00:00
2015-06-03 15:26:39 +00:00
if (supportsWebP)
{
2014-11-26 04:12:29 +00:00
// Not displaying properly on iOS
if (userAgent.IndexOf("cfnetwork", StringComparison.OrdinalIgnoreCase) == -1)
{
2014-11-29 19:51:30 +00:00
return new[] { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
2014-11-26 04:12:29 +00:00
}
}
2014-11-29 19:51:30 +00:00
return new[] { ImageFormat.Jpg, ImageFormat.Png };
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the image path.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="item">The item.</param>
/// <returns>System.String.</returns>
2014-02-07 20:30:41 +00:00
private ItemImageInfo GetImageInfo(ImageRequest request, IHasImages item)
2013-02-21 01:33:05 +00:00
{
var index = request.Index ?? 0;
2014-02-07 20:30:41 +00:00
return item.GetImageInfo(request.Type, index);
2013-02-21 01:33:05 +00:00
}
2013-02-25 04:39:53 +00:00
/// <summary>
/// Posts the image.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="inputStream">The input stream.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <returns>Task.</returns>
2013-12-19 21:51:32 +00:00
public async Task PostImage(BaseItem entity, Stream inputStream, ImageType imageType, string mimeType)
2013-02-25 04:39:53 +00:00
{
using (var reader = new StreamReader(inputStream))
{
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
var bytes = Convert.FromBase64String(text);
2013-09-04 17:02:19 +00:00
var memoryStream = new MemoryStream(bytes)
{
Position = 0
};
2013-02-25 04:39:53 +00:00
2013-06-29 15:47:36 +00:00
// Handle image/png; charset=utf-8
mimeType = mimeType.Split(';').FirstOrDefault();
2014-02-03 17:44:13 +00:00
await _providerManager.SaveImage(entity, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false);
await entity.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
2013-02-25 04:39:53 +00:00
}
}
2013-02-21 01:33:05 +00:00
}
}