using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using ServiceStack.ServiceHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MediaBrowser.Api.UserLibrary
{
///
/// Class GetItems
///
[Route("/Users/{UserId}/Items", "GET")]
[Api(Description = "Gets items based on a query.")]
public class GetItems : BaseItemsRequest, IReturn
{
///
/// Limit results to items containing a specific person
///
/// The person.
[ApiMember(Name = "Person", Description = "Optional. If specified, results will be filtered to include only those containing the specified person.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string Person { get; set; }
///
/// If the Person filter is used, this can also be used to restrict to a specific person type
///
/// The type of the person.
[ApiMember(Name = "PersonType", Description = "Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string PersonType { get; set; }
///
/// Search characters used to find items
///
/// The index by.
[ApiMember(Name = "SearchTerm", Description = "Optional. If specified, results will be filtered based on a search term.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string SearchTerm { get; set; }
///
/// The dynamic, localized index function name
///
/// The index by.
public string IndexBy { get; set; }
///
/// Limit results to items containing specific genres
///
/// The genres.
[ApiMember(Name = "Genres", Description = "Optional. If specified, results will be filtered based on genre. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string Genres { get; set; }
///
/// Limit results to items containing specific studios
///
/// The studios.
[ApiMember(Name = "Studios", Description = "Optional. If specified, results will be filtered based on studio. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string Studios { get; set; }
///
/// Limit results to items containing specific years
///
/// The years.
[ApiMember(Name = "Years", Description = "Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string Years { get; set; }
///
/// Gets or sets the image types.
///
/// The image types.
[ApiMember(Name = "ImageTypes", Description = "Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string ImageTypes { get; set; }
///
/// Gets or sets the item ids.
///
/// The item ids.
[ApiMember(Name = "Ids", Description = "Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string Ids { get; set; }
///
/// Gets or sets the media types.
///
/// The media types.
[ApiMember(Name = "MediaTypes", Description = "Optional filter by MediaType. Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string MediaTypes { get; set; }
///
/// Gets or sets the video types.
///
/// The video types.
[ApiMember(Name = "VideoTypes", Description = "Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string VideoTypes { get; set; }
///
/// Gets or sets the video formats.
///
/// The video formats.
[ApiMember(Name = "VideoFormats", Description = "Optional filter by VideoFormat (Standard, Digital3D, Sbs3D). Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string VideoFormats { get; set; }
///
/// Gets or sets the series status.
///
/// The series status.
[ApiMember(Name = "SeriesStatus", Description = "Optional filter by Series Status. Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string SeriesStatus { get; set; }
///
/// Gets or sets the air days.
///
/// The air days.
[ApiMember(Name = "AirDays", Description = "Optional filter by Series Air Days. Allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string AirDays { get; set; }
}
///
/// Class ItemsService
///
public class ItemsService : BaseApiService
{
///
/// The _user manager
///
private readonly IUserManager _userManager;
///
/// The _library manager
///
private readonly ILibraryManager _libraryManager;
private readonly ILibrarySearchEngine _searchEngine;
///
/// Initializes a new instance of the class.
///
/// The user manager.
/// The library manager.
/// The search engine.
public ItemsService(IUserManager userManager, ILibraryManager libraryManager, ILibrarySearchEngine searchEngine)
{
_userManager = userManager;
_libraryManager = libraryManager;
_searchEngine = searchEngine;
}
///
/// Gets the specified request.
///
/// The request.
/// System.Object.
public object Get(GetItems request)
{
var result = GetItems(request).Result;
return ToOptimizedResult(result);
}
///
/// Gets the items.
///
/// The request.
/// Task{ItemsResult}.
private async Task GetItems(GetItems request)
{
var user = _userManager.GetUserById(request.UserId);
var items = GetItemsToSerialize(request, user);
items = items.AsParallel();
items = ApplyAdditionalFilters(request, items);
// Apply filters
// Run them starting with the ones that are likely to reduce the list the most
foreach (var filter in request.GetFilters().OrderByDescending(f => (int)f))
{
items = ApplyFilter(items, filter, user, _userManager);
}
items = items.AsEnumerable();
items = ApplySearchTerm(request, items);
items = ApplySortOrder(request, items, user, _libraryManager);
var itemsArray = items.ToArray();
var pagedItems = ApplyPaging(request, itemsArray);
var fields = request.GetItemFields().ToList();
var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userManager);
var returnItems = await Task.WhenAll(pagedItems.Select(i => dtoBuilder.GetBaseItemDto(i, user, fields))).ConfigureAwait(false);
return new ItemsResult
{
TotalRecordCount = itemsArray.Length,
Items = returnItems
};
}
///
/// Gets the items to serialize.
///
/// The request.
/// The user.
/// IEnumerable{BaseItem}.
///
private IEnumerable GetItemsToSerialize(GetItems request, User user)
{
var item = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.ParentId, _userManager, _libraryManager, user.Id);
// Default list type = children
if (!string.IsNullOrEmpty(request.Ids))
{
var idList = request.Ids.Split(',').ToList();
return idList.Select(i => DtoBuilder.GetItemByClientId(i, _userManager, _libraryManager, user.Id));
}
if (request.Recursive)
{
return ((Folder)item).GetRecursiveChildren(user);
}
return ((Folder)item).GetChildren(user, request.IndexBy);
}
///
/// Applies sort order
///
/// The request.
/// The items.
/// The user.
/// The library manager.
/// IEnumerable{BaseItem}.
internal static IEnumerable ApplySortOrder(BaseItemsRequest request, IEnumerable items, User user, ILibraryManager libraryManager)
{
var orderBy = request.GetOrderBy().ToArray();
return orderBy.Length == 0 ? items : libraryManager.Sort(items, user, orderBy, request.SortOrder ?? SortOrder.Ascending);
}
///
/// Applies filtering
///
/// The items.
/// The filter.
/// The user.
/// The user manager.
/// IEnumerable{BaseItem}.
internal static IEnumerable ApplyFilter(IEnumerable items, ItemFilter filter, User user, IUserManager userManager)
{
// Avoids implicitly captured closure
var currentUser = user;
switch (filter)
{
case ItemFilter.Likes:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata != null && userdata.Likes.HasValue && userdata.Likes.Value;
});
case ItemFilter.Dislikes:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata != null && userdata.Likes.HasValue && !userdata.Likes.Value;
});
case ItemFilter.IsFavorite:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata != null && userdata.IsFavorite;
});
case ItemFilter.IsRecentlyAdded:
return items.Where(item => item.IsRecentlyAdded(currentUser));
case ItemFilter.IsResumable:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata != null && userdata.PlaybackPositionTicks > 0;
});
case ItemFilter.IsPlayed:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata != null && userdata.PlayCount > 0;
});
case ItemFilter.IsUnplayed:
return items.Where(item =>
{
var userdata = userManager.GetUserData(user.Id, item.UserDataId).Result;
return userdata == null || userdata.PlayCount == 0;
});
case ItemFilter.IsFolder:
return items.Where(item => item.IsFolder);
case ItemFilter.IsNotFolder:
return items.Where(item => !item.IsFolder);
}
return items;
}
///
/// Applies the additional filters.
///
/// The items request.
/// The items.
/// IEnumerable{BaseItem}.
internal static IEnumerable ApplyAdditionalFilters(BaseItemsRequest itemsRequest, IEnumerable items)
{
// Exclude item types
if (!string.IsNullOrEmpty(itemsRequest.ExcludeItemTypes))
{
var vals = itemsRequest.ExcludeItemTypes.Split(',');
items = items.Where(f => !vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
}
// Include item types
if (!string.IsNullOrEmpty(itemsRequest.IncludeItemTypes))
{
var vals = itemsRequest.IncludeItemTypes.Split(',');
items = items.Where(f => vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
}
var request = itemsRequest as GetItems;
if (request == null)
{
return items;
}
// Filter by Series Status
if (!string.IsNullOrEmpty(request.SeriesStatus))
{
var vals = request.SeriesStatus.Split(',');
items = items.OfType().Where(i => i.Status.HasValue && vals.Contains(i.Status.Value.ToString(), StringComparer.OrdinalIgnoreCase));
}
// Filter by Series AirDays
if (!string.IsNullOrEmpty(request.AirDays))
{
var days = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true));
items = items.OfType().Where(i => i.AirDays != null && days.Any(d => i.AirDays.Contains(d)));
}
// Filter by VideoFormat
if (!string.IsNullOrEmpty(request.VideoFormats))
{
var formats = request.VideoFormats.Split(',');
items = items.OfType