#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using Emby.Dlna.Didl;
using Emby.Dlna.Service;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
using Book = MediaBrowser.Controller.Entities.Book;
using Episode = MediaBrowser.Controller.Entities.TV.Episode;
using Genre = MediaBrowser.Controller.Entities.Genre;
using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Dlna.ContentDirectory
{
///
/// Defines the .
///
public class ControlHandler : BaseControlHandler
{
private const string NsDc = "http://purl.org/dc/elements/1.1/";
private const string NsDidl = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
private const string NsDlna = "urn:schemas-dlna-org:metadata-1-0/";
private const string NsUpnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
private readonly ILibraryManager _libraryManager;
private readonly IUserDataManager _userDataManager;
private readonly IServerConfigurationManager _config;
private readonly User _user;
private readonly IUserViewManager _userViewManager;
private readonly ITVSeriesManager _tvSeriesManager;
private readonly int _systemUpdateId;
private readonly DidlBuilder _didlBuilder;
private readonly DeviceProfile _profile;
///
/// Initializes a new instance of the class.
///
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The server address to use in this instance> for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The system id for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
/// The for use with the instance.
public ControlHandler(
ILogger logger,
ILibraryManager libraryManager,
DeviceProfile profile,
string serverAddress,
string accessToken,
IImageProcessor imageProcessor,
IUserDataManager userDataManager,
User user,
int systemUpdateId,
IServerConfigurationManager config,
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
IUserViewManager userViewManager,
IMediaEncoder mediaEncoder,
ITVSeriesManager tvSeriesManager)
: base(config, logger)
{
_libraryManager = libraryManager;
_userDataManager = userDataManager;
_user = user;
_systemUpdateId = systemUpdateId;
_userViewManager = userViewManager;
_tvSeriesManager = tvSeriesManager;
_profile = profile;
_config = config;
_didlBuilder = new DidlBuilder(
profile,
user,
imageProcessor,
serverAddress,
accessToken,
userDataManager,
localization,
mediaSourceManager,
Logger,
mediaEncoder,
libraryManager);
}
///
protected override void WriteResult(string methodName, IReadOnlyDictionary methodParams, XmlWriter xmlWriter)
{
if (xmlWriter == null)
{
throw new ArgumentNullException(nameof(xmlWriter));
}
if (methodParams == null)
{
throw new ArgumentNullException(nameof(methodParams));
}
const string DeviceId = "test";
if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase))
{
HandleGetSearchCapabilities(xmlWriter);
return;
}
if (string.Equals(methodName, "GetSortCapabilities", StringComparison.OrdinalIgnoreCase))
{
HandleGetSortCapabilities(xmlWriter);
return;
}
if (string.Equals(methodName, "GetSortExtensionCapabilities", StringComparison.OrdinalIgnoreCase))
{
HandleGetSortExtensionCapabilities(xmlWriter);
return;
}
if (string.Equals(methodName, "GetSystemUpdateID", StringComparison.OrdinalIgnoreCase))
{
HandleGetSystemUpdateID(xmlWriter);
return;
}
if (string.Equals(methodName, "Browse", StringComparison.OrdinalIgnoreCase))
{
HandleBrowse(xmlWriter, methodParams, DeviceId);
return;
}
if (string.Equals(methodName, "X_GetFeatureList", StringComparison.OrdinalIgnoreCase))
{
HandleXGetFeatureList(xmlWriter);
return;
}
if (string.Equals(methodName, "GetFeatureList", StringComparison.OrdinalIgnoreCase))
{
HandleGetFeatureList(xmlWriter);
return;
}
if (string.Equals(methodName, "X_SetBookmark", StringComparison.OrdinalIgnoreCase))
{
HandleXSetBookmark(methodParams);
return;
}
if (string.Equals(methodName, "Search", StringComparison.OrdinalIgnoreCase))
{
HandleSearch(xmlWriter, methodParams, DeviceId);
return;
}
if (string.Equals(methodName, "X_BrowseByLetter", StringComparison.OrdinalIgnoreCase))
{
HandleXBrowseByLetter(xmlWriter, methodParams, DeviceId);
return;
}
throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
///
/// Adds a "XSetBookmark" element to the xml document.
///
/// The method parameters.
private void HandleXSetBookmark(IReadOnlyDictionary sparams)
{
var id = sparams["ObjectID"];
var serverItem = GetItemFromObjectId(id);
var item = serverItem.Item;
var newbookmark = int.Parse(sparams["PosSecond"], CultureInfo.InvariantCulture);
var userdata = _userDataManager.GetUserData(_user, item);
userdata.PlaybackPositionTicks = TimeSpan.FromSeconds(newbookmark).Ticks;
_userDataManager.SaveUserData(
_user,
item,
userdata,
UserDataSaveReason.TogglePlayed,
CancellationToken.None);
}
///
/// Adds the "SearchCaps" element to the xml document.
///
/// The .
private static void HandleGetSearchCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SearchCaps",
"res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords");
}
///
/// Adds the "SortCaps" element to the xml document.
///
/// The .
private static void HandleGetSortCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SortCaps",
"res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
///
/// Adds the "SortExtensionCaps" element to the xml document.
///
/// The .
private static void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SortExtensionCaps",
"res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
///
/// Adds the "Id" element to the xml document.
///
/// The .
private void HandleGetSystemUpdateID(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString("Id", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
///
/// Adds the "FeatureList" element to the xml document.
///
/// The .
private static void HandleGetFeatureList(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString("FeatureList", WriteFeatureListXml());
}
///
/// Adds the "FeatureList" element to the xml document.
///
/// The .
private static void HandleXGetFeatureList(XmlWriter xmlWriter)
=> HandleGetFeatureList(xmlWriter);
///
/// Builds a static feature list.
///
/// The xml feature list.
private static string WriteFeatureListXml()
{
return ""
+ ""
+ ""
+ ""
+ ""
+ ""
+ ""
+ "";
}
///
/// Builds the "Browse" xml response.
///
/// The .
/// The method parameters.
/// The device Id to use.
private void HandleBrowse(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId)
{
var id = sparams["ObjectID"];
var flag = sparams["BrowseFlag"];
var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));
var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty));
var provided = 0;
// Default to null instead of 0
// Upnp inspector sends 0 as requestedCount when it wants everything
int? requestedCount = null;
int? start = 0;
if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out var requestedVal) && requestedVal > 0)
{
requestedCount = requestedVal;
}
if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out var startVal) && startVal > 0)
{
start = startVal;
}
int totalCount;
using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
{
var settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
CloseOutput = false,
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment
};
using (var writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
writer.WriteAttributeString("xmlns", "dc", null, NsDc);
writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
DidlBuilder.WriteXmlRootAttributes(_profile, writer);
var serverItem = GetItemFromObjectId(id);
var item = serverItem.Item;
if (string.Equals(flag, "BrowseMetadata", StringComparison.Ordinal))
{
totalCount = 1;
if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue)
{
var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount);
_didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id);
}
else
{
_didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter);
}
provided++;
}
else
{
var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount);
totalCount = childrenResult.TotalRecordCount;
provided = childrenResult.Items.Count;
foreach (var i in childrenResult.Items)
{
var childItem = i.Item;
var displayStubType = i.StubType;
if (childItem.IsDisplayedAsFolder || displayStubType.HasValue)
{
var childCount = GetUserItems(childItem, displayStubType, _user, sortCriteria, null, 0)
.TotalRecordCount;
_didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter);
}
else
{
_didlBuilder.WriteItemElement(writer, childItem, _user, item, serverItem.StubType, deviceId, filter);
}
}
}
writer.WriteFullEndElement();
}
xmlWriter.WriteElementString("Result", builder.ToString());
}
xmlWriter.WriteElementString("NumberReturned", provided.ToString(CultureInfo.InvariantCulture));
xmlWriter.WriteElementString("TotalMatches", totalCount.ToString(CultureInfo.InvariantCulture));
xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
///
/// Builds the response to the "X_BrowseByLetter request.
///
/// The .
/// The method parameters.
/// The device id.
private void HandleXBrowseByLetter(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId)
{
// TODO: Implement this method
HandleSearch(xmlWriter, sparams, deviceId);
}
///
/// Builds a response to the "Search" request.
///
/// The xmlWriter.
/// The method parameters.
/// The deviceId.
private void HandleSearch(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId)
{
var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", string.Empty));
var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty));
var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));
// sort example: dc:title, dc:date
// Default to null instead of 0
// Upnp inspector sends 0 as requestedCount when it wants everything
int? requestedCount = null;
int? start = 0;
if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out var requestedVal) && requestedVal > 0)
{
requestedCount = requestedVal;
}
if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out var startVal) && startVal > 0)
{
start = startVal;
}
QueryResult childrenResult;
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
CloseOutput = false,
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment
};
using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
using (var writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
writer.WriteAttributeString("xmlns", "dc", null, NsDc);
writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
DidlBuilder.WriteXmlRootAttributes(_profile, writer);
var serverItem = GetItemFromObjectId(sparams["ContainerID"]);
var item = serverItem.Item;
childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount);
foreach (var i in childrenResult.Items)
{
if (i.IsDisplayedAsFolder)
{
var childCount = GetChildrenSorted(i, _user, searchCriteria, sortCriteria, null, 0)
.TotalRecordCount;
_didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter);
}
else
{
_didlBuilder.WriteItemElement(writer, i, _user, item, serverItem.StubType, deviceId, filter);
}
}
writer.WriteFullEndElement();
xmlWriter.WriteElementString("Result", builder.ToString());
}
xmlWriter.WriteElementString("NumberReturned", childrenResult.Items.Count.ToString(CultureInfo.InvariantCulture));
xmlWriter.WriteElementString("TotalMatches", childrenResult.TotalRecordCount.ToString(CultureInfo.InvariantCulture));
xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
///
/// Returns the child items meeting the criteria.
///
/// The .
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private static QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit)
{
var folder = (Folder)item;
var sortOrders = folder.IsPreSorted
? Array.Empty<(string, SortOrder)>()
: new[] { (ItemSortBy.SortName, sort.SortOrder) };
string[] mediaTypes = Array.Empty();
bool? isFolder = null;
if (search.SearchType == SearchType.Audio)
{
mediaTypes = new[] { MediaType.Audio };
isFolder = false;
}
else if (search.SearchType == SearchType.Video)
{
mediaTypes = new[] { MediaType.Video };
isFolder = false;
}
else if (search.SearchType == SearchType.Image)
{
mediaTypes = new[] { MediaType.Photo };
isFolder = false;
}
else if (search.SearchType == SearchType.Playlist)
{
// items = items.OfType();
isFolder = true;
}
else if (search.SearchType == SearchType.MusicAlbum)
{
// items = items.OfType();
isFolder = true;
}
return folder.GetItems(new InternalItemsQuery
{
Limit = limit,
StartIndex = startIndex,
OrderBy = sortOrders,
User = user,
Recursive = true,
IsMissing = false,
ExcludeItemTypes = new[] { nameof(Book) },
IsFolder = isFolder,
MediaTypes = mediaTypes,
DtoOptions = GetDtoOptions()
});
}
///
/// Returns a new DtoOptions object.
///
/// The .
private static DtoOptions GetDtoOptions()
{
return new DtoOptions(true);
}
///
/// Returns the User items meeting the criteria.
///
/// The .
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit)
{
switch (item)
{
case MusicGenre:
return GetMusicGenreItems(item, user, sort, startIndex, limit);
case MusicArtist:
return GetMusicArtistItems(item, user, sort, startIndex, limit);
case Genre:
return GetGenreItems(item, user, sort, startIndex, limit);
}
if (stubType != StubType.Folder && item is IHasCollectionType collectionFolder)
{
var collectionType = collectionFolder.CollectionType;
if (string.Equals(CollectionType.Music, collectionType, StringComparison.OrdinalIgnoreCase))
{
return GetMusicFolders(item, user, stubType, sort, startIndex, limit);
}
if (string.Equals(CollectionType.Movies, collectionType, StringComparison.OrdinalIgnoreCase))
{
return GetMovieFolders(item, user, stubType, sort, startIndex, limit);
}
if (string.Equals(CollectionType.TvShows, collectionType, StringComparison.OrdinalIgnoreCase))
{
return GetTvFolders(item, user, stubType, sort, startIndex, limit);
}
if (string.Equals(CollectionType.Folders, collectionType, StringComparison.OrdinalIgnoreCase))
{
return GetFolders(user, startIndex, limit);
}
if (string.Equals(CollectionType.LiveTv, collectionType, StringComparison.OrdinalIgnoreCase))
{
return GetLiveTvChannels(user, sort, startIndex, limit);
}
}
if (stubType.HasValue && stubType.Value != StubType.Folder)
{
// TODO should this be doing something?
return new QueryResult();
}
var folder = (Folder)item;
var query = new InternalItemsQuery(user)
{
Limit = limit,
StartIndex = startIndex,
IsVirtualItem = false,
ExcludeItemTypes = new[] { nameof(Book) },
IsPlaceHolder = false,
DtoOptions = GetDtoOptions(),
OrderBy = GetOrderBy(sort, folder.IsPreSorted)
};
var queryResult = folder.GetItems(query);
return ToResult(queryResult);
}
///
/// Returns the Live Tv Channels meeting the criteria.
///
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetLiveTvChannels(User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
StartIndex = startIndex,
Limit = limit,
IncludeItemTypes = new[] { nameof(LiveTvChannel) },
OrderBy = GetOrderBy(sort, false)
};
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the music folders meeting the criteria.
///
/// The .
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetMusicFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
StartIndex = startIndex,
Limit = limit,
OrderBy = GetOrderBy(sort, false)
};
switch (stubType)
{
case StubType.Latest:
return GetLatest(item, query, nameof(Audio));
case StubType.Playlists:
return GetMusicPlaylists(query);
case StubType.Albums:
return GetChildrenOfItem(item, query, nameof(MusicAlbum));
case StubType.Artists:
return GetMusicArtists(item, query);
case StubType.AlbumArtists:
return GetMusicAlbumArtists(item, query);
case StubType.FavoriteAlbums:
return GetChildrenOfItem(item, query, nameof(MusicAlbum), true);
case StubType.FavoriteArtists:
return GetFavoriteArtists(item, query);
case StubType.FavoriteSongs:
return GetChildrenOfItem(item, query, nameof(Audio), true);
case StubType.Songs:
return GetChildrenOfItem(item, query, nameof(Audio));
case StubType.Genres:
return GetMusicGenres(item, query);
}
var serverItems = new ServerItem[]
{
new (item, StubType.Latest),
new (item, StubType.Playlists),
new (item, StubType.Albums),
new (item, StubType.AlbumArtists),
new (item, StubType.Artists),
new (item, StubType.Songs),
new (item, StubType.Genres),
new (item, StubType.FavoriteArtists),
new (item, StubType.FavoriteAlbums),
new (item, StubType.FavoriteSongs)
};
if (limit < serverItems.Length)
{
serverItems = serverItems[..limit.Value];
}
return new QueryResult
{
Items = serverItems,
TotalRecordCount = serverItems.Length
};
}
///
/// Returns the movie folders meeting the criteria.
///
/// The .
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetMovieFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
StartIndex = startIndex,
Limit = limit,
OrderBy = GetOrderBy(sort, false)
};
switch (stubType)
{
case StubType.ContinueWatching:
return GetMovieContinueWatching(item, query);
case StubType.Latest:
return GetLatest(item, query, nameof(Movie));
case StubType.Movies:
return GetChildrenOfItem(item, query, nameof(Movie));
case StubType.Collections:
return GetMovieCollections(query);
case StubType.Favorites:
return GetChildrenOfItem(item, query, nameof(Movie), true);
case StubType.Genres:
return GetGenres(item, query);
}
var array = new ServerItem[]
{
new (item, StubType.ContinueWatching),
new (item, StubType.Latest),
new (item, StubType.Movies),
new (item, StubType.Collections),
new (item, StubType.Favorites),
new (item, StubType.Genres)
};
if (limit < array.Length)
{
array = array[..limit.Value];
}
return new QueryResult
{
Items = array,
TotalRecordCount = array.Length
};
}
///
/// Returns the folders meeting the criteria.
///
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetFolders(User user, int? startIndex, int? limit)
{
var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true);
var totalRecordCount = folders.Count;
// Handle paging
var items = folders
.OrderBy(i => i.SortName)
.Skip(startIndex ?? 0)
.Take(limit ?? int.MaxValue)
.Select(i => new ServerItem(i, StubType.Folder))
.ToArray();
return new QueryResult
{
Items = items,
TotalRecordCount = totalRecordCount
};
}
///
/// Returns the TV folders meeting the criteria.
///
/// The .
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
StartIndex = startIndex,
Limit = limit,
OrderBy = GetOrderBy(sort, false)
};
switch (stubType)
{
case StubType.ContinueWatching:
return GetMovieContinueWatching(item, query);
case StubType.NextUp:
return GetNextUp(item, query);
case StubType.Latest:
return GetLatest(item, query, nameof(Episode));
case StubType.Series:
return GetChildrenOfItem(item, query, nameof(Series));
case StubType.FavoriteSeries:
return GetChildrenOfItem(item, query, nameof(Series), true);
case StubType.FavoriteEpisodes:
return GetChildrenOfItem(item, query, nameof(Episode), true);
case StubType.Genres:
return GetGenres(item, query);
}
var serverItems = new ServerItem[]
{
new (item, StubType.ContinueWatching),
new (item, StubType.NextUp),
new (item, StubType.Latest),
new (item, StubType.Series),
new (item, StubType.FavoriteSeries),
new (item, StubType.FavoriteEpisodes),
new (item, StubType.Genres)
};
if (limit < serverItems.Length)
{
serverItems = serverItems[..limit.Value];
}
return new QueryResult
{
Items = serverItems,
TotalRecordCount = serverItems.Length
};
}
///
/// Returns the Movies that are part watched that meet the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetMovieContinueWatching(BaseItem parent, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.OrderBy = new[]
{
(ItemSortBy.DatePlayed, SortOrder.Descending),
(ItemSortBy.SortName, SortOrder.Ascending)
};
query.IsResumable = true;
query.Limit ??= 10;
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the Movie collections meeting the criteria.
///
/// The see cref="InternalItemsQuery"/>.
/// The .
private QueryResult GetMovieCollections(InternalItemsQuery query)
{
query.Recursive = true;
query.IncludeItemTypes = new[] { nameof(BoxSet) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the children that meet the criteria.
///
/// The .
/// The .
/// The item type.
/// A value indicating whether to only fetch favorite items.
/// The .
private QueryResult GetChildrenOfItem(BaseItem parent, InternalItemsQuery query, string itemType, bool isFavorite = false)
{
query.Recursive = true;
query.Parent = parent;
query.IsFavorite = isFavorite;
query.IncludeItemTypes = new[] { itemType };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the genres meeting the criteria.
/// The GetGenres.
///
/// The .
/// The .
/// The .
private QueryResult GetGenres(BaseItem parent, InternalItemsQuery query)
{
// Don't sort
query.OrderBy = Array.Empty<(string, SortOrder)>();
query.AncestorIds = new[] { parent.Id };
var genresResult = _libraryManager.GetGenres(query);
return ToResult(genresResult);
}
///
/// Returns the music genres meeting the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetMusicGenres(BaseItem parent, InternalItemsQuery query)
{
// Don't sort
query.OrderBy = Array.Empty<(string, SortOrder)>();
query.AncestorIds = new[] { parent.Id };
var genresResult = _libraryManager.GetMusicGenres(query);
return ToResult(genresResult);
}
///
/// Returns the music albums by artist that meet the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetMusicAlbumArtists(BaseItem parent, InternalItemsQuery query)
{
// Don't sort
query.OrderBy = Array.Empty<(string, SortOrder)>();
query.AncestorIds = new[] { parent.Id };
var artists = _libraryManager.GetAlbumArtists(query);
return ToResult(artists);
}
///
/// Returns the music artists meeting the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetMusicArtists(BaseItem parent, InternalItemsQuery query)
{
// Don't sort
query.OrderBy = Array.Empty<(string, SortOrder)>();
query.AncestorIds = new[] { parent.Id };
var artists = _libraryManager.GetArtists(query);
return ToResult(artists);
}
///
/// Returns the artists tagged as favourite that meet the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetFavoriteArtists(BaseItem parent, InternalItemsQuery query)
{
// Don't sort
query.OrderBy = Array.Empty<(string, SortOrder)>();
query.AncestorIds = new[] { parent.Id };
query.IsFavorite = true;
var artists = _libraryManager.GetArtists(query);
return ToResult(artists);
}
///
/// Returns the music playlists meeting the criteria.
///
/// The query.
/// The .
private QueryResult GetMusicPlaylists(InternalItemsQuery query)
{
query.Parent = null;
query.IncludeItemTypes = new[] { nameof(Playlist) };
query.Recursive = true;
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the next up item meeting the criteria.
///
/// The .
/// The .
/// The .
private QueryResult GetNextUp(BaseItem parent, InternalItemsQuery query)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
var result = _tvSeriesManager.GetNextUp(
new NextUpQuery
{
Limit = query.Limit,
StartIndex = query.StartIndex,
// User cannot be null here as the caller has set it
UserId = query.User!.Id
},
new[] { parent },
query.DtoOptions);
return ToResult(result);
}
///
/// Returns the latest items of [itemType] meeting the criteria.
///
/// The .
/// The .
/// The item type.
/// The .
private QueryResult GetLatest(BaseItem parent, InternalItemsQuery query, string itemType)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
var items = _userViewManager.GetLatestItems(
new LatestItemsQuery
{
// User cannot be null here as the caller has set it
UserId = query.User!.Id,
Limit = query.Limit ?? 50,
IncludeItemTypes = new[] { itemType },
ParentId = parent?.Id ?? Guid.Empty,
GroupItems = true
},
query.DtoOptions).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null).ToArray();
return ToResult(items);
}
///
/// Returns music artist items that meet the criteria.
///
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetMusicArtistItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
Recursive = true,
ArtistIds = new[] { item.Id },
IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions(),
OrderBy = GetOrderBy(sort, false)
};
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the genre items meeting the criteria.
///
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetGenreItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
Recursive = true,
GenreIds = new[] { item.Id },
IncludeItemTypes = new[]
{
nameof(Movie),
nameof(Series)
},
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions(),
OrderBy = GetOrderBy(sort, false)
};
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Returns the music genre items meeting the criteria.
///
/// The .
/// The .
/// The .
/// The start index.
/// The maximum number to return.
/// The .
private QueryResult GetMusicGenreItems(BaseItem item, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
{
Recursive = true,
GenreIds = new[] { item.Id },
IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions(),
OrderBy = GetOrderBy(sort, false)
};
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
///
/// Converts into a .
///
/// An array of .
/// A .
private static QueryResult ToResult(IReadOnlyCollection result)
{
var serverItems = result
.Select(i => new ServerItem(i, null))
.ToArray();
return new QueryResult
{
TotalRecordCount = result.Count,
Items = serverItems
};
}
///
/// Converts a to a .
///
/// A .
/// The .
private static QueryResult ToResult(QueryResult result)
{
var serverItems = new ServerItem[result.Items.Count];
for (var i = 0; i < result.Items.Count; i++)
{
serverItems[i] = new ServerItem(result.Items[i], null);
}
return new QueryResult
{
TotalRecordCount = result.TotalRecordCount,
Items = serverItems
};
}
///
/// Converts a query result to a .
///
/// A .
/// The .
private static QueryResult ToResult(QueryResult<(BaseItem, ItemCounts)> result)
{
var serverItems = new ServerItem[result.Items.Count];
for (var i = 0; i < result.Items.Count; i++)
{
serverItems[i] = new ServerItem(result.Items[i].Item1, null);
}
return new QueryResult
{
TotalRecordCount = result.TotalRecordCount,
Items = serverItems
};
}
///
/// Gets the sorting method on a query.
///
/// The .
/// True if pre-sorted.
private static (string, SortOrder)[] GetOrderBy(SortCriteria sort, bool isPreSorted)
{
return isPreSorted ? Array.Empty<(string, SortOrder)>() : new[] { (ItemSortBy.SortName, sort.SortOrder) };
}
///
/// Retrieves the ServerItem id.
///
/// The id.
/// The .
private ServerItem GetItemFromObjectId(string id)
{
return DidlBuilder.IsIdRoot(id)
? new ServerItem(_libraryManager.GetUserRootFolder(), null)
: ParseItemId(id);
}
///
/// Parses the item id into a .
///
/// The .
/// The corresponding .
private ServerItem ParseItemId(string id)
{
StubType? stubType = null;
// After using PlayTo, MediaMonkey sends a request to the server trying to get item info
const string ParamsSrch = "Params=";
var paramsIndex = id.IndexOf(ParamsSrch, StringComparison.OrdinalIgnoreCase);
if (paramsIndex != -1)
{
id = id.Substring(paramsIndex + ParamsSrch.Length);
var parts = id.Split(';');
id = parts[23];
}
var dividerIndex = id.IndexOf('_', StringComparison.Ordinal);
if (dividerIndex != -1 && Enum.TryParse(id.AsSpan(0, dividerIndex), true, out var parsedStubType))
{
id = id[(dividerIndex + 1)..];
stubType = parsedStubType;
}
if (Guid.TryParse(id, out var itemId))
{
var item = _libraryManager.GetItemById(itemId);
return new ServerItem(item, stubType);
}
Logger.LogError("Error parsing item Id: {Id}. Returning user root folder.", id);
return new ServerItem(_libraryManager.GetUserRootFolder(), null);
}
}
}