You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jellyfin/MediaBrowser.Server.Impleme.../Dto/DtoService.cs

1187 lines
38 KiB

using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Drawing;
11 years ago
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
11 years ago
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
11 years ago
using MediaBrowser.Model.Session;
using MoreLinq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
11 years ago
namespace MediaBrowser.Server.Implementations.Dto
{
11 years ago
public class DtoService : IDtoService
{
private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
11 years ago
private readonly IUserManager _userManager;
private readonly IUserDataRepository _userDataRepository;
private readonly IItemRepository _itemRepo;
private readonly IImageProcessor _imageProcessor;
public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataRepository userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor)
{
_logger = logger;
_libraryManager = libraryManager;
11 years ago
_userManager = userManager;
_userDataRepository = userDataRepository;
_itemRepo = itemRepo;
_imageProcessor = imageProcessor;
}
/// <summary>
/// Converts a BaseItem to a DTOBaseItem
/// </summary>
/// <param name="item">The item.</param>
/// <param name="fields">The fields.</param>
/// <param name="user">The user.</param>
/// <param name="owner">The owner.</param>
/// <returns>Task{DtoBaseItem}.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (fields == null)
{
throw new ArgumentNullException("fields");
}
var dto = new BaseItemDto();
if (fields.Contains(ItemFields.People))
{
AttachPeople(dto, item);
}
if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
{
try
{
AttachPrimaryImageAspectRatio(dto, item);
}
catch (Exception ex)
{
// Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
_logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
}
}
if (fields.Contains(ItemFields.DisplayPreferencesId))
{
dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
}
if (user != null)
{
AttachUserSpecificInfo(dto, item, user, fields);
}
if (fields.Contains(ItemFields.Studios))
{
AttachStudios(dto, item);
}
AttachBasicFields(dto, item, owner, fields);
if (fields.Contains(ItemFields.SoundtrackIds))
{
dto.SoundtrackIds = item.SoundtrackIds
.Select(i => i.ToString("N"))
.ToArray();
}
var itemByName = item as IItemByName;
if (itemByName != null)
{
AttachItemByNameCounts(dto, itemByName, user);
}
return dto;
}
/// <summary>
/// Attaches the item by name counts.
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
/// <param name="user">The user.</param>
private void AttachItemByNameCounts(BaseItemDto dto, IItemByName item, User user)
{
ItemByNameCounts counts;
if (user == null)
{
//counts = item.ItemCounts;
return;
}
else
{
if (!item.UserItemCounts.TryGetValue(user.Id, out counts))
{
counts = new ItemByNameCounts();
}
}
dto.ChildCount = counts.TotalCount;
dto.AdultVideoCount = counts.AdultVideoCount;
dto.AlbumCount = counts.AlbumCount;
dto.EpisodeCount = counts.EpisodeCount;
dto.GameCount = counts.GameCount;
dto.MovieCount = counts.MovieCount;
dto.MusicVideoCount = counts.MusicVideoCount;
dto.SeriesCount = counts.SeriesCount;
dto.SongCount = counts.SongCount;
dto.TrailerCount = counts.TrailerCount;
}
/// <summary>
/// Attaches the user specific info.
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
/// <param name="user">The user.</param>
/// <param name="fields">The fields.</param>
private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
{
if (item.IsFolder)
{
var folder = (Folder)item;
dto.ChildCount = folder.GetChildren(user, true).Count();
if (!(folder is UserRootFolder))
{
SetSpecialCounts(folder, user, dto, fields);
}
}
var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
dto.UserData = GetUserItemDataDto(userData);
if (item.IsFolder)
{
dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
}
}
public UserDto GetUserDto(User user)
{
11 years ago
if (user == null)
{
11 years ago
throw new ArgumentNullException("user");
}
11 years ago
var dto = new UserDto
{
11 years ago
Id = user.Id.ToString("N"),
Name = user.Name,
HasPassword = !String.IsNullOrEmpty(user.Password),
LastActivityDate = user.LastActivityDate,
LastLoginDate = user.LastLoginDate,
Configuration = user.Configuration
};
11 years ago
var image = user.PrimaryImagePath;
11 years ago
if (!string.IsNullOrEmpty(image))
{
dto.PrimaryImageTag = _imageProcessor.GetImageCacheTag(user, ImageType.Primary, image);
11 years ago
try
{
AttachPrimaryImageAspectRatio(dto, user);
}
catch (Exception ex)
{
11 years ago
// Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
_logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
}
11 years ago
}
11 years ago
return dto;
}
11 years ago
public SessionInfoDto GetSessionInfoDto(SessionInfo session)
{
var dto = new SessionInfoDto
{
Client = session.Client,
DeviceId = session.DeviceId,
DeviceName = session.DeviceName,
Id = session.Id.ToString("N"),
LastActivityDate = session.LastActivityDate,
NowPlayingPositionTicks = session.NowPlayingPositionTicks,
SupportsRemoteControl = session.SupportsRemoteControl,
IsPaused = session.IsPaused,
IsMuted = session.IsMuted,
NowViewingContext = session.NowViewingContext,
NowViewingItemId = session.NowViewingItemId,
NowViewingItemName = session.NowViewingItemName,
NowViewingItemType = session.NowViewingItemType,
ApplicationVersion = session.ApplicationVersion,
CanSeek = session.CanSeek,
QueueableMediaTypes = session.QueueableMediaTypes
11 years ago
};
11 years ago
if (session.NowPlayingItem != null)
{
11 years ago
dto.NowPlayingItem = GetBaseItemInfo(session.NowPlayingItem);
}
11 years ago
if (session.User != null)
{
dto.UserId = session.User.Id.ToString("N");
dto.UserName = session.User.Name;
}
return dto;
}
/// <summary>
11 years ago
/// Converts a BaseItem to a BaseItemInfo
/// </summary>
/// <param name="item">The item.</param>
11 years ago
/// <returns>BaseItemInfo.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public BaseItemInfo GetBaseItemInfo(BaseItem item)
{
11 years ago
if (item == null)
{
11 years ago
throw new ArgumentNullException("item");
}
11 years ago
var info = new BaseItemInfo
{
11 years ago
Id = GetDtoId(item),
Name = item.Name,
MediaType = item.MediaType,
Type = item.GetType().Name,
IsFolder = item.IsFolder,
RunTimeTicks = item.RunTimeTicks
};
11 years ago
var imagePath = item.PrimaryImagePath;
11 years ago
if (!string.IsNullOrEmpty(imagePath))
{
11 years ago
try
{
info.PrimaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary, imagePath);
11 years ago
}
catch (IOException)
{
}
}
11 years ago
return info;
}
11 years ago
const string IndexFolderDelimeter = "-index-";
11 years ago
/// <summary>
/// Gets client-side Id of a server-side BaseItem
/// </summary>
/// <param name="item">The item.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public string GetDtoId(BaseItem item)
{
if (item == null)
{
11 years ago
throw new ArgumentNullException("item");
}
11 years ago
var indexFolder = item as IndexFolder;
11 years ago
if (indexFolder != null)
{
11 years ago
return GetDtoId(indexFolder.Parent) + IndexFolderDelimeter + (indexFolder.IndexName ?? string.Empty) + IndexFolderDelimeter + indexFolder.Id;
}
11 years ago
return item.Id.ToString("N");
}
11 years ago
/// <summary>
/// Converts a UserItemData to a DTOUserItemData
/// </summary>
/// <param name="data">The data.</param>
/// <returns>DtoUserItemData.</returns>
/// <exception cref="System.ArgumentNullException"></exception>
public UserItemDataDto GetUserItemDataDto(UserItemData data)
{
if (data == null)
{
11 years ago
throw new ArgumentNullException("data");
}
11 years ago
return new UserItemDataDto
{
11 years ago
IsFavorite = data.IsFavorite,
Likes = data.Likes,
PlaybackPositionTicks = data.PlaybackPositionTicks,
PlayCount = data.PlayCount,
Rating = data.Rating,
Played = data.Played,
LastPlayedDate = data.LastPlayedDate
};
}
private void SetBookProperties(BaseItemDto dto, Book item)
{
dto.SeriesName = item.SeriesName;
}
11 years ago
private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
{
if (!string.IsNullOrEmpty(item.Album))
{
var parentAlbum = _libraryManager.RootFolder
.GetRecursiveChildren(i => i is MusicAlbum)
11 years ago
.FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
11 years ago
if (parentAlbum != null)
{
11 years ago
dto.AlbumId = GetDtoId(parentAlbum);
}
}
11 years ago
dto.Album = item.Album;
dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
11 years ago
}
11 years ago
private void SetGameProperties(BaseItemDto dto, Game item)
{
dto.Players = item.PlayersSupported;
dto.GameSystem = item.GameSystem;
}
11 years ago
/// <summary>
/// Gets the backdrop image tags.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>List{System.String}.</returns>
private List<Guid> GetBackdropImageTags(BaseItem item)
{
return item.BackdropImagePaths
.Select(p => GetImageCacheTag(item, ImageType.Backdrop, p))
.Where(i => i.HasValue)
.Select(i => i.Value)
.ToList();
}
11 years ago
/// <summary>
/// Gets the screenshot image tags.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>List{Guid}.</returns>
private List<Guid> GetScreenshotImageTags(BaseItem item)
{
return item.ScreenshotImagePaths
.Select(p => GetImageCacheTag(item, ImageType.Screenshot, p))
.Where(i => i.HasValue)
.Select(i => i.Value)
.ToList();
}
11 years ago
private Guid? GetImageCacheTag(BaseItem item, ImageType type, string path)
{
try
{
return _imageProcessor.GetImageCacheTag(item, type, path);
}
11 years ago
catch (IOException ex)
{
11 years ago
_logger.ErrorException("Error getting {0} image info for {1}", ex, type, path);
return null;
}
}
/// <summary>
11 years ago
/// Attaches People DTO's to a DTOBaseItem
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
/// <returns>Task.</returns>
private void AttachPeople(BaseItemDto dto, BaseItem item)
11 years ago
{
// Ordering by person type to ensure actors and artists are at the front.
// This is taking advantage of the fact that they both begin with A
// This should be improved in the future
var people = item.People.OrderBy(i => i.Type).ToList();
11 years ago
// Attach People by transforming them into BaseItemPerson (DTO)
dto.People = new BaseItemPerson[people.Count];
var dictionary = people.Select(p => p.Name)
11 years ago
.Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
{
try
{
return _libraryManager.GetPerson(c);
}
catch (IOException ex)
11 years ago
{
_logger.ErrorException("Error getting person {0}", ex, c);
return null;
}
}).Where(i => i != null)
11 years ago
.DistinctBy(i => i.Name)
.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < people.Count; i++)
{
11 years ago
var person = people[i];
11 years ago
var baseItemPerson = new BaseItemPerson
{
11 years ago
Name = person.Name,
Role = person.Role,
Type = person.Type
};
11 years ago
Person entity;
if (dictionary.TryGetValue(person.Name, out entity))
{
var primaryImagePath = entity.PrimaryImagePath;
if (!string.IsNullOrEmpty(primaryImagePath))
{
baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
}
}
11 years ago
dto.People[i] = baseItemPerson;
}
11 years ago
}
11 years ago
/// <summary>
/// Attaches the studios.
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
/// <returns>Task.</returns>
private void AttachStudios(BaseItemDto dto, BaseItem item)
11 years ago
{
var studios = item.Studios.ToList();
dto.Studios = new StudioDto[studios.Count];
var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
{
try
{
return _libraryManager.GetStudio(name);
}
catch (IOException ex)
{
_logger.ErrorException("Error getting studio {0}", ex, name);
return null;
}
})
.Where(i => i != null)
.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
11 years ago
for (var i = 0; i < studios.Count; i++)
{
11 years ago
var studio = studios[i];
11 years ago
var studioDto = new StudioDto
{
11 years ago
Name = studio
};
11 years ago
Studio entity;
if (dictionary.TryGetValue(studio, out entity))
{
var primaryImagePath = entity.PrimaryImagePath;
if (!string.IsNullOrEmpty(primaryImagePath))
{
studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary, primaryImagePath);
}
}
11 years ago
dto.Studios[i] = studioDto;
}
11 years ago
}
11 years ago
/// <summary>
/// If an item does not any backdrops, this can be used to find the first parent that does have one
/// </summary>
/// <param name="item">The item.</param>
/// <param name="owner">The owner.</param>
/// <returns>BaseItem.</returns>
private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
{
var parent = item.Parent ?? owner;
11 years ago
while (parent != null)
{
11 years ago
if (parent.BackdropImagePaths != null && parent.BackdropImagePaths.Count > 0)
{
return parent;
}
parent = parent.Parent;
}
11 years ago
return null;
}
11 years ago
/// <summary>
/// If an item does not have a logo, this can be used to find the first parent that does have one
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="owner">The owner.</param>
/// <returns>BaseItem.</returns>
private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
{
var parent = item.Parent ?? owner;
while (parent != null)
{
11 years ago
if (parent.HasImage(type))
{
return parent;
}
parent = parent.Parent;
}
11 years ago
return null;
}
/// <summary>
/// Gets the chapter info dto.
/// </summary>
/// <param name="chapterInfo">The chapter info.</param>
/// <param name="item">The item.</param>
/// <returns>ChapterInfoDto.</returns>
private ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
{
var dto = new ChapterInfoDto
{
11 years ago
Name = chapterInfo.Name,
StartPositionTicks = chapterInfo.StartPositionTicks
};
11 years ago
if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
{
11 years ago
dto.ImageTag = GetImageCacheTag(item, ImageType.Chapter, chapterInfo.ImagePath);
}
11 years ago
return dto;
}
/// <summary>
/// Gets a BaseItem based upon it's client-side item id
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>BaseItem.</returns>
public BaseItem GetItemByDtoId(string id, Guid? userId = null)
{
if (string.IsNullOrEmpty(id))
{
11 years ago
throw new ArgumentNullException("id");
}
11 years ago
// If the item is an indexed folder we have to do a special routine to get it
var isIndexFolder = id.IndexOf(IndexFolderDelimeter, StringComparison.OrdinalIgnoreCase) != -1;
11 years ago
if (isIndexFolder)
{
11 years ago
if (userId.HasValue)
{
11 years ago
return GetIndexFolder(id, userId.Value);
}
}
11 years ago
BaseItem item = null;
11 years ago
if (userId.HasValue || !isIndexFolder)
{
item = _libraryManager.GetItemById(new Guid(id));
}
11 years ago
// If we still don't find it, look within individual user views
if (item == null && !userId.HasValue && isIndexFolder)
{
foreach (var user in _userManager.Users)
{
11 years ago
item = GetItemByDtoId(id, user.Id);
11 years ago
if (item != null)
{
11 years ago
break;
}
}
}
12 years ago
11 years ago
return item;
}
12 years ago
11 years ago
/// <summary>
/// Finds an index folder based on an Id and userId
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>BaseItem.</returns>
private BaseItem GetIndexFolder(string id, Guid userId)
{
var user = _userManager.GetUserById(userId);
12 years ago
11 years ago
var stringSeparators = new[] { IndexFolderDelimeter };
11 years ago
// Split using the delimeter
var values = id.Split(stringSeparators, StringSplitOptions.None).ToList();
11 years ago
// Get the top folder normally using the first id
var folder = GetItemByDtoId(values[0], userId) as Folder;
11 years ago
values.RemoveAt(0);
11 years ago
// Get indexed folders using the remaining values in the id string
return GetIndexFolder(values, folder, user);
}
11 years ago
/// <summary>
/// Gets indexed folders based on a list of index names and folder id's
/// </summary>
/// <param name="values">The values.</param>
/// <param name="parentFolder">The parent folder.</param>
/// <param name="user">The user.</param>
/// <returns>BaseItem.</returns>
private BaseItem GetIndexFolder(List<string> values, Folder parentFolder, User user)
{
// The index name is first
var indexBy = values[0];
11 years ago
// The index folder id is next
var indexFolderId = new Guid(values[1]);
11 years ago
// Remove them from the lst
values.RemoveRange(0, 2);
11 years ago
// Get the IndexFolder
var indexFolder = parentFolder.GetChildren(user, false, indexBy).FirstOrDefault(i => i.Id == indexFolderId) as Folder;
11 years ago
// Nested index folder
if (values.Count > 0)
{
return GetIndexFolder(values, indexFolder, user);
}
11 years ago
return indexFolder;
}
11 years ago
/// <summary>
/// Sets simple property values on a DTOBaseItem
/// </summary>
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
/// <param name="owner">The owner.</param>
/// <param name="fields">The fields.</param>
private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
{
if (fields.Contains(ItemFields.DateCreated))
{
11 years ago
dto.DateCreated = item.DateCreated;
}
11 years ago
if (fields.Contains(ItemFields.OriginalRunTimeTicks))
{
11 years ago
dto.OriginalRunTimeTicks = item.OriginalRunTimeTicks;
}
11 years ago
dto.DisplayMediaType = item.DisplayMediaType;
11 years ago
if (fields.Contains(ItemFields.MetadataSettings))
{
dto.LockedFields = item.LockedFields;
dto.EnableInternetProviders = !item.DontFetchMeta;
}
11 years ago
if (fields.Contains(ItemFields.Budget))
{
11 years ago
dto.Budget = item.Budget;
}
11 years ago
if (fields.Contains(ItemFields.Revenue))
{
11 years ago
dto.Revenue = item.Revenue;
}
12 years ago
11 years ago
dto.EndDate = item.EndDate;
12 years ago
11 years ago
if (fields.Contains(ItemFields.HomePageUrl))
12 years ago
{
11 years ago
dto.HomePageUrl = item.HomePageUrl;
12 years ago
}
11 years ago
if (fields.Contains(ItemFields.Tags))
{
dto.Tags = item.Tags;
}
11 years ago
if (fields.Contains(ItemFields.ProductionLocations))
{
11 years ago
dto.ProductionLocations = item.ProductionLocations;
}
11 years ago
dto.AspectRatio = item.AspectRatio;
11 years ago
dto.BackdropImageTags = GetBackdropImageTags(item);
if (fields.Contains(ItemFields.ScreenshotImageTags))
{
dto.ScreenshotImageTags = GetScreenshotImageTags(item);
}
11 years ago
if (fields.Contains(ItemFields.Genres))
{
11 years ago
dto.Genres = item.Genres;
}
11 years ago
dto.ImageTags = new Dictionary<ImageType, Guid>();
11 years ago
foreach (var image in item.Images)
{
11 years ago
var type = image.Key;
11 years ago
var tag = GetImageCacheTag(item, type, image.Value);
if (tag.HasValue)
{
11 years ago
dto.ImageTags[type] = tag.Value;
}
}
11 years ago
dto.Id = GetDtoId(item);
dto.IndexNumber = item.IndexNumber;
dto.IsFolder = item.IsFolder;
dto.Language = item.Language;
dto.MediaType = item.MediaType;
dto.LocationType = item.LocationType;
11 years ago
dto.CriticRating = item.CriticRating;
11 years ago
if (fields.Contains(ItemFields.CriticRatingSummary))
{
dto.CriticRatingSummary = item.CriticRatingSummary;
}
11 years ago
var localTrailerCount = item.LocalTrailerIds.Count;
11 years ago
if (localTrailerCount > 0)
{
11 years ago
dto.LocalTrailerCount = localTrailerCount;
}
11 years ago
dto.Name = item.Name;
dto.OfficialRating = item.OfficialRating;
11 years ago
var hasOverview = fields.Contains(ItemFields.Overview);
var hasHtmlOverview = fields.Contains(ItemFields.OverviewHtml);
11 years ago
if (hasOverview || hasHtmlOverview)
{
var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
11 years ago
if (hasOverview)
{
11 years ago
dto.Overview = strippedOverview;
}
11 years ago
// Only supply the html version if there was actually html content
if (hasHtmlOverview)
{
11 years ago
dto.OverviewHtml = item.Overview;
}
}
11 years ago
// If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
if (dto.BackdropImageTags.Count == 0)
{
11 years ago
var parentWithBackdrop = GetParentBackdropItem(item, owner);
if (parentWithBackdrop != null)
{
dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
}
}
11 years ago
if (item.Parent != null && fields.Contains(ItemFields.ParentId))
{
11 years ago
dto.ParentId = GetDtoId(item.Parent);
}
11 years ago
dto.ParentIndexNumber = item.ParentIndexNumber;
11 years ago
// If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
if (!dto.HasLogo)
{
11 years ago
var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
11 years ago
if (parentWithLogo != null)
{
11 years ago
dto.ParentLogoItemId = GetDtoId(parentWithLogo);
11 years ago
dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo, parentWithLogo.GetImage(ImageType.Logo));
}
}
11 years ago
// If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
if (!dto.HasArtImage)
{
var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
if (parentWithImage != null)
{
11 years ago
dto.ParentArtItemId = GetDtoId(parentWithImage);
11 years ago
dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art, parentWithImage.GetImage(ImageType.Art));
}
11 years ago
}
11 years ago
if (fields.Contains(ItemFields.Path))
{
dto.Path = item.Path;
}
11 years ago
dto.PremiereDate = item.PremiereDate;
dto.ProductionYear = item.ProductionYear;
12 years ago
11 years ago
if (fields.Contains(ItemFields.ProviderIds))
{
dto.ProviderIds = item.ProviderIds;
}
12 years ago
11 years ago
dto.RunTimeTicks = item.RunTimeTicks;
12 years ago
11 years ago
if (fields.Contains(ItemFields.SortName))
{
dto.SortName = item.SortName;
}
12 years ago
11 years ago
if (fields.Contains(ItemFields.CustomRating))
{
dto.CustomRating = item.CustomRating;
}
12 years ago
11 years ago
if (fields.Contains(ItemFields.Taglines))
{
dto.Taglines = item.Taglines;
}
12 years ago
11 years ago
if (fields.Contains(ItemFields.RemoteTrailers))
12 years ago
{
11 years ago
dto.RemoteTrailers = item.RemoteTrailers;
}
12 years ago
11 years ago
dto.Type = item.GetType().Name;
dto.CommunityRating = item.CommunityRating;
12 years ago
11 years ago
if (item.IsFolder)
{
var folder = (Folder)item;
12 years ago
11 years ago
if (fields.Contains(ItemFields.IndexOptions))
12 years ago
{
11 years ago
dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
12 years ago
}
}
11 years ago
// Add audio info
var audio = item as Audio;
if (audio != null)
{
11 years ago
dto.Album = audio.Album;
dto.Artists = audio.Artists;
11 years ago
var albumParent = audio.FindParent<MusicAlbum>();
11 years ago
if (albumParent != null)
{
dto.AlbumId = GetDtoId(albumParent);
11 years ago
var imagePath = albumParent.PrimaryImagePath;
11 years ago
if (!string.IsNullOrEmpty(imagePath))
{
dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary, imagePath);
}
}
}
11 years ago
var album = item as MusicAlbum;
11 years ago
if (album != null)
{
dto.Artists = album.Artists;
11 years ago
}
var hasAlbumArtist = item as IHasAlbumArtist;
if (hasAlbumArtist != null)
{
dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
}
11 years ago
// Add video info
var video = item as Video;
if (video != null)
{
11 years ago
dto.VideoType = video.VideoType;
dto.Video3DFormat = video.Video3DFormat;
dto.IsoType = video.IsoType;
11 years ago
dto.PartCount = video.AdditionalPartIds.Count + 1;
11 years ago
if (fields.Contains(ItemFields.Chapters))
{
dto.Chapters = _itemRepo.GetChapters(video.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
}
}
11 years ago
if (fields.Contains(ItemFields.MediaStreams))
{
11 years ago
// Add VideoInfo
var iHasMediaStreams = item as IHasMediaStreams;
11 years ago
if (iHasMediaStreams != null)
{
dto.MediaStreams = iHasMediaStreams.MediaStreams;
}
}
// Add MovieInfo
var movie = item as Movie;
11 years ago
if (movie != null)
{
11 years ago
var specialFeatureCount = movie.SpecialFeatureIds.Count;
if (specialFeatureCount > 0)
{
11 years ago
dto.SpecialFeatureCount = specialFeatureCount;
}
}
11 years ago
// Add EpisodeInfo
var episode = item as Episode;
11 years ago
if (episode != null)
{
11 years ago
dto.IndexNumberEnd = episode.IndexNumberEnd;
}
11 years ago
// Add SeriesInfo
var series = item as Series;
11 years ago
if (series != null)
{
11 years ago
dto.AirDays = series.AirDays;
dto.AirTime = series.AirTime;
dto.Status = series.Status;
11 years ago
dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
11 years ago
dto.SeasonCount = series.SeasonCount;
}
if (episode != null)
{
11 years ago
series = item.FindParent<Series>();
dto.SeriesId = GetDtoId(series);
dto.SeriesName = series.Name;
}
11 years ago
// Add SeasonInfo
var season = item as Season;
11 years ago
if (season != null)
{
11 years ago
series = item.FindParent<Series>();
dto.SeriesId = GetDtoId(series);
dto.SeriesName = series.Name;
}
11 years ago
var game = item as Game;
11 years ago
if (game != null)
{
11 years ago
SetGameProperties(dto, game);
}
11 years ago
var musicVideo = item as MusicVideo;
11 years ago
if (musicVideo != null)
{
SetMusicVideoProperties(dto, musicVideo);
}
11 years ago
var book = item as Book;
if (book != null)
{
SetBookProperties(dto, book);
}
}
/// <summary>
11 years ago
/// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
/// </summary>
11 years ago
/// <param name="folder">The folder.</param>
/// <param name="user">The user.</param>
/// <param name="dto">The dto.</param>
/// <param name="fields">The fields.</param>
11 years ago
/// <returns>Task.</returns>
private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
{
11 years ago
var rcentlyAddedItemCount = 0;
var recursiveItemCount = 0;
var unplayed = 0;
long runtime = 0;
11 years ago
double totalPercentPlayed = 0;
11 years ago
// Loop through each recursive child
foreach (var child in folder.GetRecursiveChildren(user, i => !i.IsFolder))
11 years ago
{
var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
11 years ago
recursiveItemCount++;
11 years ago
// Check is recently added
if (child.IsRecentlyAdded())
{
rcentlyAddedItemCount++;
}
11 years ago
var isUnplayed = true;
11 years ago
// Incrememt totalPercentPlayed
if (userdata != null)
{
if (userdata.Played)
{
totalPercentPlayed += 100;
11 years ago
isUnplayed = false;
}
else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
{
double itemPercent = userdata.PlaybackPositionTicks;
itemPercent /= child.RunTimeTicks.Value;
totalPercentPlayed += itemPercent;
}
}
11 years ago
if (isUnplayed)
{
unplayed++;
}
11 years ago
runtime += child.RunTimeTicks ?? 0;
}
11 years ago
dto.RecursiveItemCount = recursiveItemCount;
dto.RecentlyAddedItemCount = rcentlyAddedItemCount;
dto.RecursiveUnplayedItemCount = unplayed;
if (recursiveItemCount > 0)
{
11 years ago
dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
}
if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
11 years ago
{
dto.CumulativeRunTimeTicks = runtime;
}
}
/// <summary>
11 years ago
/// Attaches the primary image aspect ratio.
/// </summary>
11 years ago
/// <param name="dto">The dto.</param>
/// <param name="item">The item.</param>
11 years ago
/// <returns>Task.</returns>
private void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
{
11 years ago
var path = item.PrimaryImagePath;
11 years ago
if (string.IsNullOrEmpty(path))
{
return;
}
var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(path);
// See if we can avoid a file system lookup by looking for the file in ResolveArgs
var dateModified = metaFileEntry == null ? File.GetLastWriteTimeUtc(path) : metaFileEntry.LastWriteTimeUtc;
ImageSize size;
try
{
size = _imageProcessor.GetImageSize(path, dateModified);
}
11 years ago
catch (FileNotFoundException)
{
11 years ago
_logger.Error("Image file does not exist: {0}", path);
return;
}
catch (Exception ex)
{
_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
return;
}
dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
11 years ago
foreach (var enhancer in supportedEnhancers)
{
try
{
size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
}
catch (Exception ex)
{
_logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
}
}
11 years ago
dto.PrimaryImageAspectRatio = size.Width / size.Height;
}
}
}