예제 #1
0
        /// <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)
        {
            var options = new DtoOptions
            {
                Fields = fields
            };

            return GetBaseItemDto(item, options, user, owner);
        }
        private IEnumerable <RecommendationDto> GetSimilarTo(User user, List <BaseItem> baselineItems, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
        {
            var itemTypes = new List <string> {
                typeof(Movie).Name
            };

            if (_config.Configuration.EnableExternalContentInSuggestions)
            {
                itemTypes.Add(typeof(Trailer).Name);
                itemTypes.Add(typeof(LiveTvProgram).Name);
            }

            foreach (var item in baselineItems)
            {
                var similar = _libraryManager.GetItemList(new InternalItemsQuery(user)
                {
                    Limit                    = itemLimit,
                    IncludeItemTypes         = itemTypes.ToArray(itemTypes.Count),
                    IsMovie                  = true,
                    SimilarTo                = item,
                    EnableGroupByMetadataKey = true,
                    DtoOptions               = dtoOptions
                });

                if (similar.Count > 0)
                {
                    var returnItems = _dtoService.GetBaseItemDtos(similar, dtoOptions, user);

                    yield return(new RecommendationDto
                    {
                        BaselineItemName = item.Name,
                        CategoryId = item.Id.ToString("N"),
                        RecommendationType = type,
                        Items = returnItems
                    });
                }
            }
        }
예제 #3
0
        public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);

            var returnList = new List<ChannelInfoDto>();

            var now = DateTime.UtcNow;

            var programs = query.AddCurrentProgram ? _libraryManager.QueryItems(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                MaxStartDate = now,
                MinEndDate = now,
                ChannelIds = internalResult.Items.Select(i => i.Id.ToString("N")).ToArray()

            }).Items.Cast<LiveTvProgram>().OrderBy(i => i.StartDate).ToList() : new List<LiveTvProgram>();

            foreach (var channel in internalResult.Items)
            {
                var channelIdString = channel.Id.ToString("N");
                var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString, StringComparison.OrdinalIgnoreCase));

                returnList.Add(_tvDtoService.GetChannelInfoDto(channel, options, currentProgram, user));
            }

            var result = new QueryResult<ChannelInfoDto>
            {
                Items = returnList.ToArray(),
                TotalRecordCount = internalResult.TotalRecordCount
            };

            return result;
        }
예제 #4
0
        private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
        {
            var numComplete = 0;
            double progressPerService = _services.Count == 0
                ? 0
                : 1 / _services.Count;

            var newChannelIdList = new List<Guid>();
            var newProgramIdList = new List<Guid>();

            foreach (var service in _services)
            {
                cancellationToken.ThrowIfCancellationRequested();

                _logger.Debug("Refreshing guide from {0}", service.Name);

                try
                {
                    var innerProgress = new ActionableProgress<double>();
                    innerProgress.RegisterAction(p => progress.Report(p * progressPerService));

                    var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);

                    newChannelIdList.AddRange(idList.Item1);
                    newProgramIdList.AddRange(idList.Item2);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error refreshing channels for service", ex);
                }

                numComplete++;
                double percent = numComplete;
                percent /= _services.Count;

                progress.Report(100 * percent);
            }

            await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
            await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);

            var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();

            if (coreService != null)
            {
                await coreService.RefreshSeriesTimers(cancellationToken, new Progress<double>()).ConfigureAwait(false);
            }

            // Load these now which will prefetch metadata
            var dtoOptions = new DtoOptions();
            dtoOptions.Fields.Remove(ItemFields.SyncInfo);
            await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);

            progress.Report(100);
        }
예제 #5
0
        public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null)
        {
            var syncProgress = GetSyncedItemProgress(options);

            var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user);

            if (options.Fields.Contains(ItemFields.ItemCounts))
            {
                SetItemByNameInfo(item, dto, taggedItems, user);
            }

            FillSyncInfo(dto, item, options, user, syncProgress);

            return dto;
        }
예제 #6
0
        private SyncedItemProgress[] GetSyncedItemProgress(DtoOptions options)
        {
            if (!options.Fields.Contains(ItemFields.SyncInfo))
            {
                return new SyncedItemProgress[] { };
            }

            var deviceId = options.DeviceId;
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                return new SyncedItemProgress[] { };
            }

            var caps = _deviceManager().GetCapabilities(deviceId);
            if (caps == null || !caps.SupportsSync)
            {
                return new SyncedItemProgress[] { };
            }

            return _syncManager.GetSyncedItemProgresses(new SyncJobItemQuery
            {
                TargetId = deviceId,
                Statuses = new[]
                {
                    SyncJobItemStatus.Converting,
                    SyncJobItemStatus.Queued,
                    SyncJobItemStatus.Transferring,
                    SyncJobItemStatus.ReadyToTransfer,
                    SyncJobItemStatus.Synced
                }
            }).Items;
        }
예제 #7
0
        public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var internalQuery = new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                MinEndDate = query.MinEndDate,
                MinStartDate = query.MinStartDate,
                MaxEndDate = query.MaxEndDate,
                MaxStartDate = query.MaxStartDate,
                ChannelIds = query.ChannelIds,
                IsMovie = query.IsMovie,
                IsSports = query.IsSports,
                IsKids = query.IsKids,
                Genres = query.Genres,
                StartIndex = query.StartIndex,
                Limit = query.Limit,
                SortBy = query.SortBy,
                SortOrder = query.SortOrder ?? SortOrder.Ascending,
                EnableTotalRecordCount = query.EnableTotalRecordCount
            };

            if (query.HasAired.HasValue)
            {
                if (query.HasAired.Value)
                {
                    internalQuery.MaxEndDate = DateTime.UtcNow;
                }
                else
                {
                    internalQuery.MinEndDate = DateTime.UtcNow;
                }
            }

            var queryResult = _libraryManager.QueryItems(internalQuery);

            var returnArray = _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ToArray();

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = queryResult.TotalRecordCount
            };

            return result;
        }
예제 #8
0
        public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);

            if (query.SortBy.Length == 0)
            {
                // Unless something else was specified, order by start date to take advantage of a specialized index
                query.SortBy = new[] { ItemSortBy.StartDate };
            }

            var internalQuery = new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                MinEndDate = query.MinEndDate,
                MinStartDate = query.MinStartDate,
                MaxEndDate = query.MaxEndDate,
                MaxStartDate = query.MaxStartDate,
                ChannelIds = query.ChannelIds,
                IsMovie = query.IsMovie,
                IsSeries = query.IsSeries,
                IsSports = query.IsSports,
                IsKids = query.IsKids,
                IsNews = query.IsNews,
                Genres = query.Genres,
                StartIndex = query.StartIndex,
                Limit = query.Limit,
                SortBy = query.SortBy,
                SortOrder = query.SortOrder ?? SortOrder.Ascending,
                EnableTotalRecordCount = query.EnableTotalRecordCount,
                TopParentIds = new[] { topFolder.Id.ToString("N") },
                Name = query.Name,
                DtoOptions = options
            };

            if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
            {
                var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery { }, cancellationToken).ConfigureAwait(false);
                var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
                if (seriesTimer != null)
                {
                    internalQuery.ExternalSeriesId = seriesTimer.SeriesId;

                    if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
                    {
                        // Better to return nothing than every program in the database
                        return new QueryResult<BaseItemDto>();
                    }
                }
                else
                {
                    // Better to return nothing than every program in the database
                    return new QueryResult<BaseItemDto>();
                }
            }

            if (query.HasAired.HasValue)
            {
                if (query.HasAired.Value)
                {
                    internalQuery.MaxEndDate = DateTime.UtcNow;
                }
                else
                {
                    internalQuery.MinEndDate = DateTime.UtcNow;
                }
            }

            var queryResult = _libraryManager.QueryItems(internalQuery);

            RemoveFields(options);

            var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ConfigureAwait(false)).ToArray();

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = queryResult.TotalRecordCount
            };

            return result;
        }
예제 #9
0
        public ActionResult <QueryResult <BaseItemDto> > GetSimilarItems(
            [FromRoute, Required] Guid itemId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
            [FromQuery] Guid?userId,
            [FromQuery] int?limit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
        {
            var item = itemId.Equals(Guid.Empty)
                ? (!userId.Equals(Guid.Empty)
                    ? _libraryManager.GetUserRootFolder()
                    : _libraryManager.RootFolder)
                : _libraryManager.GetItemById(itemId);

            if (item is Episode || (item is IItemByName && !(item is MusicArtist)))
            {
                return(new QueryResult <BaseItemDto>());
            }

            var user = userId.HasValue && !userId.Equals(Guid.Empty)
                ? _userManager.GetUserById(userId.Value)
                : null;
            var dtoOptions = new DtoOptions {
                Fields = fields
            }
            .AddClientFields(Request);

            var  program  = item as IHasProgramAttributes;
            bool?isMovie  = item is Movie || (program != null && program.IsMovie) || item is Trailer;
            bool?isSeries = item is Series || (program != null && program.IsSeries);

            var includeItemTypes = new List <string>();

            if (isMovie.Value)
            {
                includeItemTypes.Add(nameof(Movie));
                if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
                {
                    includeItemTypes.Add(nameof(Trailer));
                    includeItemTypes.Add(nameof(LiveTvProgram));
                }
            }
            else if (isSeries.Value)
            {
                includeItemTypes.Add(nameof(Series));
            }
            else
            {
                // For non series and movie types these columns are typically null
                isSeries = null;
                isMovie  = null;
                includeItemTypes.Add(item.GetType().Name);
            }

            var query = new InternalItemsQuery(user)
            {
                Limit                    = limit,
                IncludeItemTypes         = includeItemTypes.ToArray(),
                SimilarTo                = item,
                DtoOptions               = dtoOptions,
                EnableTotalRecordCount   = !isMovie ?? true,
                EnableGroupByMetadataKey = isMovie ?? false,
                MinSimilarityScore       = 2 // A remnant from album/artist scoring
            };

            // ExcludeArtistIds
            if (excludeArtistIds.Length != 0)
            {
                query.ExcludeArtistIds = excludeArtistIds;
            }

            List <BaseItem> itemsResult = _libraryManager.GetItemList(query);

            var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);

            return(new QueryResult <BaseItemDto>
            {
                Items = returnList,
                TotalRecordCount = itemsResult.Count
            });
        }
예제 #10
0
        public List <BaseItem> GetSeasonEpisodes(Season parentSeason, User user, IEnumerable <BaseItem> allSeriesEpisodes, DtoOptions options)
        {
            if (allSeriesEpisodes == null)
            {
                return(GetSeasonEpisodes(parentSeason, user, options));
            }

            var episodes = FilterEpisodesBySeason(allSeriesEpisodes, parentSeason, ConfigurationManager.Configuration.DisplaySpecialsWithinSeasons);

            var sortBy = (parentSeason.IndexNumber ?? -1) == 0 ? ItemSortBy.SortName : ItemSortBy.AiredEpisodeOrder;

            return(LibraryManager.Sort(episodes, user, new[] { sortBy }, SortOrder.Ascending).ToList());
        }
예제 #11
0
        public ActionResult <IEnumerable <BaseItemDto> > GetLatestMedia(
            [FromRoute, Required] Guid userId,
            [FromQuery] Guid?parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
            [FromQuery] bool?isPlayed,
            [FromQuery] bool?enableImages,
            [FromQuery] int?imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] bool?enableUserData,
            [FromQuery] int limit       = 20,
            [FromQuery] bool groupItems = true)
        {
            var user = _userManager.GetUserById(userId);

            if (!isPlayed.HasValue)
            {
                if (user.HidePlayedInLatest)
                {
                    isPlayed = false;
                }
            }

            var dtoOptions = new DtoOptions {
                Fields = fields
            }
            .AddClientFields(Request)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            var list = _userViewManager.GetLatestItems(
                new LatestItemsQuery
            {
                GroupItems       = groupItems,
                IncludeItemTypes = includeItemTypes,
                IsPlayed         = isPlayed,
                Limit            = limit,
                ParentId         = parentId ?? Guid.Empty,
                UserId           = userId,
            },
                dtoOptions);

            var dtos = list.Select(i =>
            {
                var item       = i.Item2[0];
                var childCount = 0;

                if (i.Item1 != null && (i.Item2.Count > 1 || i.Item1 is MusicAlbum))
                {
                    item       = i.Item1;
                    childCount = i.Item2.Count;
                }

                var dto = _dtoService.GetBaseItemDto(item, dtoOptions, user);

                dto.ChildCount = childCount;

                return(dto);
            });

            return(Ok(dtos));
        }
예제 #12
0
        public ActionResult <QueryResult <BaseItemDto> > GetStudios(
            [FromQuery] int?startIndex,
            [FromQuery] int?limit,
            [FromQuery] string?searchTerm,
            [FromQuery] string?parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery] string?excludeItemTypes,
            [FromQuery] string?includeItemTypes,
            [FromQuery] bool?isFavorite,
            [FromQuery] bool?enableUserData,
            [FromQuery] int?imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] Guid?userId,
            [FromQuery] string?nameStartsWithOrGreater,
            [FromQuery] string?nameStartsWith,
            [FromQuery] string?nameLessThan,
            [FromQuery] bool?enableImages           = true,
            [FromQuery] bool enableTotalRecordCount = true)
        {
            var dtoOptions = new DtoOptions {
                Fields = fields
            }
            .AddClientFields(Request)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            User?user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;

            var parentItem = _libraryManager.GetParentItem(parentId, userId);

            var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true);
            var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true);

            var query = new InternalItemsQuery(user)
            {
                ExcludeItemTypes        = excludeItemTypesArr,
                IncludeItemTypes        = includeItemTypesArr,
                StartIndex              = startIndex,
                Limit                   = limit,
                IsFavorite              = isFavorite,
                NameLessThan            = nameLessThan,
                NameStartsWith          = nameStartsWith,
                NameStartsWithOrGreater = nameStartsWithOrGreater,
                DtoOptions              = dtoOptions,
                SearchTerm              = searchTerm,
                EnableTotalRecordCount  = enableTotalRecordCount
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                if (parentItem is Folder)
                {
                    query.AncestorIds = new[] { new Guid(parentId) };
                }
                else
                {
                    query.ItemIds = new[] { new Guid(parentId) };
                }
            }

            var result = _libraryManager.GetStudios(query);
            var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes);

            return(RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user));
        }
예제 #13
0
        private object GetResult(List <BaseItem> items, User user, BaseGetSimilarItems request, DtoOptions dtoOptions)
        {
            var list = items;

            var result = new QueryResult <BaseItemDto>
            {
                TotalRecordCount = list.Count
            };

            if (request.Limit.HasValue)
            {
                list = list.Take(request.Limit.Value).ToList();
            }

            var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user);

            result.Items = returnList;

            return(result);
        }
예제 #14
0
        private List <BaseItem> GetItemsForLatestItems(User user, LatestItemsQuery request, DtoOptions options)
        {
            var parentId = request.ParentId;

            var includeItemTypes = request.IncludeItemTypes;
            var limit            = request.Limit ?? 10;

            var parents = new List <BaseItem>();

            if (!parentId.Equals(Guid.Empty))
            {
                var parentItem        = _libraryManager.GetItemById(parentId);
                var parentItemChannel = parentItem as Channel;
                if (parentItemChannel != null)
                {
                    return(_channelManager.GetLatestChannelItemsInternal(new InternalItemsQuery(user)
                    {
                        ChannelIds = new [] { parentId },
                        IsPlayed = request.IsPlayed,
                        StartIndex = request.StartIndex,
                        Limit = request.Limit,
                        IncludeItemTypes = request.IncludeItemTypes,
                        EnableTotalRecordCount = false
                    }, CancellationToken.None).Result.Items.ToList());
                }

                var parent = parentItem as Folder;
                if (parent != null)
                {
                    parents.Add(parent);
                }
            }

            var isPlayed = request.IsPlayed;

            if (parents.OfType <ICollectionFolder>().Any(i => string.Equals(i.CollectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase)))
            {
                isPlayed = null;
            }

            if (parents.Count == 0)
            {
                parents = _libraryManager.GetUserRootFolder().GetChildren(user, true)
                          .Where(i => i is Folder)
                          .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N")))
                          .ToList();
            }

            if (parents.Count == 0)
            {
                return(new List <BaseItem>());
            }

            if (includeItemTypes.Length == 0)
            {
                // Handle situations with the grouping setting, e.g. movies showing up in tv, etc.
                // Thanks to mixed content libraries included in the UserView
                var hasCollectionType = parents.OfType <UserView>().ToArray();
                if (hasCollectionType.Length > 0)
                {
                    if (hasCollectionType.All(i => string.Equals(i.CollectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase)))
                    {
                        includeItemTypes = new string[] { "Movie" };
                    }
                    else if (hasCollectionType.All(i => string.Equals(i.CollectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)))
                    {
                        includeItemTypes = new string[] { "Episode" };
                    }
                }
            }

            var mediaTypes = new List <string>();

            if (includeItemTypes.Length == 0)
            {
                foreach (var parent in parents.OfType <ICollectionFolder>())
                {
                    switch (parent.CollectionType)
                    {
                    case CollectionType.Books:
                        mediaTypes.Add(MediaType.Book);
                        mediaTypes.Add(MediaType.Audio);
                        break;

                    case CollectionType.Games:
                        mediaTypes.Add(MediaType.Game);
                        break;

                    case CollectionType.Music:
                        mediaTypes.Add(MediaType.Audio);
                        break;

                    case CollectionType.Photos:
                        mediaTypes.Add(MediaType.Photo);
                        mediaTypes.Add(MediaType.Video);
                        break;

                    case CollectionType.HomeVideos:
                        mediaTypes.Add(MediaType.Photo);
                        mediaTypes.Add(MediaType.Video);
                        break;

                    default:
                        mediaTypes.Add(MediaType.Video);
                        break;
                    }
                }

                mediaTypes = mediaTypes.Distinct().ToList();
            }

            var excludeItemTypes = includeItemTypes.Length == 0 && mediaTypes.Count == 0 ? new[]
            {
                typeof(Person).Name,
                typeof(Studio).Name,
                typeof(Year).Name,
                typeof(GameGenre).Name,
                typeof(MusicGenre).Name,
                typeof(Genre).Name
            } : Array.Empty <string>();

            var query = new InternalItemsQuery(user)
            {
                IncludeItemTypes = includeItemTypes,
                OrderBy          = new[] { new ValueTuple <string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
                IsFolder         = includeItemTypes.Length == 0 ? false : (bool?)null,
                ExcludeItemTypes = excludeItemTypes,
                IsVirtualItem    = false,
                Limit            = limit * 5,
                IsPlayed         = isPlayed,
                DtoOptions       = options,
                MediaTypes       = mediaTypes.ToArray(mediaTypes.Count)
            };

            if (parents.Count == 0)
            {
                return(_libraryManager.GetItemList(query, false));
            }

            return(_libraryManager.GetItemList(query, parents));
        }
예제 #15
0
        public List <Tuple <BaseItem, List <BaseItem> > > GetLatestItems(LatestItemsQuery request, DtoOptions options)
        {
            var user = _userManager.GetUserById(request.UserId);

            var libraryItems = GetItemsForLatestItems(user, request, options);

            var list = new List <Tuple <BaseItem, List <BaseItem> > >();

            foreach (var item in libraryItems)
            {
                // Only grab the index container for media
                var container = item.IsFolder || !request.GroupItems ? null : item.LatestItemsIndexContainer;

                if (container == null)
                {
                    list.Add(new Tuple <BaseItem, List <BaseItem> >(null, new List <BaseItem> {
                        item
                    }));
                }
                else
                {
                    var current = list.FirstOrDefault(i => i.Item1 != null && i.Item1.Id == container.Id);

                    if (current != null)
                    {
                        current.Item2.Add(item);
                    }
                    else
                    {
                        list.Add(new Tuple <BaseItem, List <BaseItem> >(container, new List <BaseItem> {
                            item
                        }));
                    }
                }

                if (list.Count >= request.Limit)
                {
                    break;
                }
            }

            return(list);
        }
예제 #16
0
        private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, DtoOptions dtoOptions, User user)
        {
            if (user == null)
            {
                return new QueryResult<BaseItem>();
            }

            if ((query.IsInProgress ?? false))
            {
                return new QueryResult<BaseItem>();
            }

            var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
                .SelectMany(i => i.Locations)
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .Select(i => _libraryManager.FindByPath(i, true))
                .Where(i => i != null)
                .Where(i => i.IsVisibleStandalone(user))
                .ToList();

            if (folders.Count == 0)
            {
                return new QueryResult<BaseItem>();
            }

            var includeItemTypes = new List<string>();
            var excludeItemTypes = new List<string>();
            var genres = new List<string>();

            if (query.IsMovie.HasValue)
            {
                if (query.IsMovie.Value)
                {
                    includeItemTypes.Add(typeof(Movie).Name);
                }
                else
                {
                    excludeItemTypes.Add(typeof(Movie).Name);
                }
            }
            if (query.IsSeries.HasValue)
            {
                if (query.IsSeries.Value)
                {
                    includeItemTypes.Add(typeof(Episode).Name);
                }
                else
                {
                    excludeItemTypes.Add(typeof(Episode).Name);
                }
            }
            if (query.IsSports.HasValue)
            {
                if (query.IsSports.Value)
                {
                    genres.Add("Sports");
                }
            }
            if (query.IsKids.HasValue)
            {
                if (query.IsKids.Value)
                {
                    genres.Add("Kids");
                    genres.Add("Children");
                    genres.Add("Family");
                }
            }

            return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                MediaTypes = new[] { MediaType.Video },
                Recursive = true,
                AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
                IsFolder = false,
                ExcludeLocationTypes = new[] { LocationType.Virtual },
                Limit = query.Limit,
                SortBy = new[] { ItemSortBy.DateCreated },
                SortOrder = SortOrder.Descending,
                EnableTotalRecordCount = query.EnableTotalRecordCount,
                IncludeItemTypes = includeItemTypes.ToArray(),
                ExcludeItemTypes = excludeItemTypes.ToArray(),
                Genres = genres.ToArray(),
                DtoOptions = dtoOptions
            });
        }
예제 #17
0
        public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
        {
            var now = DateTime.UtcNow;

            var channelIds = tuples.Select(i => i.Item2.Id.ToString("N")).Distinct().ToArray();

            var programs = options.AddCurrentProgram ? _libraryManager.GetItemList(new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                ChannelIds = channelIds,
                MaxStartDate = now,
                MinEndDate = now,
                Limit = channelIds.Length,
                SortBy = new[] { "StartDate" },
                TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Result.Id.ToString("N") }

            }).ToList() : new List<BaseItem>();

            RemoveFields(options);

            foreach (var tuple in tuples)
            {
                var dto = tuple.Item1;
                var channel = tuple.Item2;

                dto.Number = channel.Number;
                dto.ChannelNumber = channel.Number;
                dto.ChannelType = channel.ChannelType;
                dto.ServiceName = channel.ServiceName;

                if (options.Fields.Contains(ItemFields.MediaSources))
                {
                    dto.MediaSources = channel.GetMediaSources(true).ToList();
                }

                if (options.AddCurrentProgram)
                {
                    var channelIdString = channel.Id.ToString("N");
                    var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString));

                    if (currentProgram != null)
                    {
                        dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
                    }
                }
            }
        }
예제 #18
0
        public IEnumerable <Episode> GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable <string> seriesKeys, DtoOptions dtoOptions)
        {
            // Avoid implicitly captured closure
            var currentUser = user;

            var allNextUp = seriesKeys
                            .Select(i => GetNextUp(i, currentUser, dtoOptions));

            // allNextUp = allNextUp.OrderByDescending(i => i.Item1);

            // If viewing all next up for all series, remove first episodes
            // But if that returns empty, keep those first episodes (avoid completely empty view)
            var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId);
            var anyFound = false;

            return(allNextUp
                   .Where(i =>
            {
                if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue)
                {
                    anyFound = true;
                    return true;
                }

                if (!anyFound && i.Item1 == DateTime.MinValue)
                {
                    return true;
                }

                return false;
            })
                   .Select(i => i.Item2())
                   .Where(i => i != null));
        }
예제 #19
0
        public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);

            var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ToArray();

            return new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = internalResult.TotalRecordCount
            };
        }
예제 #20
0
        /// <summary>
        /// Gets the next up.
        /// </summary>
        /// <returns>Task{Episode}.</returns>
        private Tuple <DateTime, Func <Episode> > GetNextUp(string seriesKey, User user, DtoOptions dtoOptions)
        {
            var lastWatchedEpisode = _libraryManager.GetItemList(new InternalItemsQuery(user)
            {
                AncestorWithPresentationUniqueKey = null,
                SeriesPresentationUniqueKey       = seriesKey,
                IncludeItemTypes           = new[] { nameof(Episode) },
                OrderBy                    = new[] { new ValueTuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Descending) },
                IsPlayed                   = true,
                Limit                      = 1,
                ParentIndexNumberNotEquals = 0,
                DtoOptions                 = new DtoOptions
                {
                    Fields = new ItemFields[]
                    {
                        ItemFields.SortName
                    },
                    EnableImages = false
                }
            }).FirstOrDefault();

            Func <Episode> getEpisode = () =>
            {
                return(_libraryManager.GetItemList(new InternalItemsQuery(user)
                {
                    AncestorWithPresentationUniqueKey = null,
                    SeriesPresentationUniqueKey = seriesKey,
                    IncludeItemTypes = new[] { nameof(Episode) },
                    OrderBy = new[] { new ValueTuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) },
                    Limit = 1,
                    IsPlayed = false,
                    IsVirtualItem = false,
                    ParentIndexNumberNotEquals = 0,
                    MinSortName = lastWatchedEpisode?.SortName,
                    DtoOptions = dtoOptions
                }).Cast <Episode>().FirstOrDefault());
            };

            if (lastWatchedEpisode != null)
            {
                var userData = _userDataManager.GetUserData(user, lastWatchedEpisode);

                var lastWatchedDate = userData.LastPlayedDate ?? DateTime.MinValue.AddDays(1);

                return(new Tuple <DateTime, Func <Episode> >(lastWatchedDate, getEpisode));
            }

            // Return the first episode
            return(new Tuple <DateTime, Func <Episode> >(DateTime.MinValue, getEpisode));
        }
예제 #21
0
        public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
        {
            var syncProgress = GetSyncedItemProgress(options);

            var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user, owner);

            var byName = item as IItemByName;

            if (byName != null)
            {
                if (options.Fields.Contains(ItemFields.ItemCounts))
                {
                    SetItemByNameInfo(item, dto, GetTaggedItems(byName, user), user);
                }

                FillSyncInfo(dto, item, options, user, syncProgress);
                return dto;
            }

            FillSyncInfo(dto, item, options, user, syncProgress);

            return dto;
        }
예제 #22
0
        public QueryResult <BaseItem> GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions dtoOptions)
        {
            var user = _userManager.GetUserById(request.UserId);

            if (user == null)
            {
                throw new ArgumentException("User not found");
            }

            string presentationUniqueKey = null;
            int?   limit = null;

            if (!string.IsNullOrEmpty(request.SeriesId))
            {
                var series = _libraryManager.GetItemById(request.SeriesId) as Series;

                if (series != null)
                {
                    presentationUniqueKey = GetUniqueSeriesKey(series);
                    limit = 1;
                }
            }

            if (!string.IsNullOrEmpty(presentationUniqueKey))
            {
                return(GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, dtoOptions), request));
            }

            if (limit.HasValue)
            {
                limit = limit.Value + 10;
            }

            var items = _libraryManager
                        .GetItemList(
                new InternalItemsQuery(user)
            {
                IncludeItemTypes            = new[] { nameof(Episode) },
                OrderBy                     = new[] { new ValueTuple <string, SortOrder>(ItemSortBy.DatePlayed, SortOrder.Descending) },
                SeriesPresentationUniqueKey = presentationUniqueKey,
                Limit      = limit,
                DtoOptions = new DtoOptions {
                    Fields = new[] { ItemFields.SeriesPresentationUniqueKey }, EnableImages = false
                },
                GroupBySeriesPresentationUniqueKey = true
            }, parentsFolders.ToList())
                        .Cast <Episode>()
                        .Where(episode => !string.IsNullOrEmpty(episode.SeriesPresentationUniqueKey))
                        .Select(GetUniqueSeriesKey);

            // Avoid implicitly captured closure
            var episodes = GetNextUpEpisodes(request, user, items, dtoOptions);

            return(GetResult(episodes, request));
        }
예제 #23
0
        private void FillSyncInfo(IHasSyncInfo dto, BaseItem item, SyncedItemProgress[] syncProgress, DtoOptions options, User user)
        {
            if (options.Fields.Contains(ItemFields.SyncInfo))
            {
                var userCanSync = user != null && user.Policy.EnableSync;
                dto.SupportsSync = userCanSync && _syncManager.SupportsSync(item);
            }

            if (dto.SupportsSync ?? false)
            {
                dto.HasSyncJob = syncProgress.Any(i => i.Status != SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));
                dto.IsSynced = syncProgress.Any(i => i.Status == SyncJobItemStatus.Synced && string.Equals(i.ItemId, dto.Id, StringComparison.OrdinalIgnoreCase));

                if (dto.IsSynced.Value)
                {
                    dto.SyncStatus = SyncJobItemStatus.Synced;
                }

                else if (dto.HasSyncJob.Value)
                {
                    dto.SyncStatus = SyncJobItemStatus.Queued;
                }
            }
        }
예제 #24
0
        public UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto itemDto, User user, DtoOptions options)
        {
            var userData = GetUserData(user, item);
            var dto      = GetUserItemDataDto(userData);

            item.FillUserDataDtoValues(dto, userData, itemDto, user, options);
            return(dto);
        }
예제 #25
0
        public IEnumerable<BaseItemDto> GetBaseItemDtos(IEnumerable<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
        {
            var syncJobItems = GetSyncedItemProgress(options);
            var syncDictionary = GetSyncedItemProgressDictionary(syncJobItems);

            var list = new List<BaseItemDto>();

            foreach (var item in items)
            {
                var dto = GetBaseItemDtoInternal(item, options, syncDictionary, user, owner);

                var byName = item as IItemByName;

                if (byName != null)
                {
                    if (options.Fields.Contains(ItemFields.ItemCounts))
                    {
                        var itemFilter = byName.GetItemFilter();

                        var libraryItems = user != null ?
                           user.RootFolder.GetRecursiveChildren(user, itemFilter) :
                           _libraryManager.RootFolder.GetRecursiveChildren(itemFilter);

                        SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
                    }
                }

                FillSyncInfo(dto, item, syncJobItems, options, user);

                list.Add(dto);
            }

            return list;
        }
예제 #26
0
        private QueryResult <BaseItemDto> GetResult(List <BaseItem> items, User?user, int?limit, DtoOptions dtoOptions)
        {
            var list = items;

            var result = new QueryResult <BaseItemDto>
            {
                TotalRecordCount = list.Count
            };

            if (limit.HasValue)
            {
                list = list.Take(limit.Value).ToList();
            }

            var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user);

            result.Items = returnList;

            return(result);
        }
예제 #27
0
        public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
        {
            var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);

            if (item == null)
            {
                return null;
            }

            return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
        }
예제 #28
0
        public static List <BaseItem> GetPlaylistItems(string playlistMediaType, IEnumerable <BaseItem> inputItems, User user, DtoOptions options)
        {
            if (user != null)
            {
                inputItems = inputItems.Where(i => i.IsVisible(user));
            }

            var list = new List <BaseItem>();

            foreach (var item in inputItems)
            {
                var playlistItems = GetPlaylistItems(item, user, playlistMediaType, options);
                list.AddRange(playlistItems);
            }

            return(list);
        }
예제 #29
0
        public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);

            var user = _userManager.GetUserById(query.UserId);

            var returnArray = internalResult.Items
                .Select(i => new Tuple<BaseItemDto, string, string>(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId))
                .ToArray();

            await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray.Select(i => i.Item1).ToArray(),
                TotalRecordCount = internalResult.TotalRecordCount
            };

            return result;
        }
예제 #30
0
 private static IEnumerable <BaseItem> GetPlaylistItems(BaseItem item, User user, string mediaType, DtoOptions options)
 {
     if (item is MusicGenre musicGenre)
     {
         return(LibraryManager.GetItemList(new InternalItemsQuery(user)
         {
             Recursive = true,
             IncludeItemTypes = new[] { nameof(Audio) },
             GenreIds = new[] { musicGenre.Id },
             OrderBy = new[] { (ItemSortBy.AlbumArtist, SortOrder.Ascending), (ItemSortBy.Album, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) },
예제 #31
0
        public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);

            if (query.SortBy.Length == 0)
            {
                // Unless something else was specified, order by start date to take advantage of a specialized index
                query.SortBy = new[] { ItemSortBy.StartDate };
            }

            var internalQuery = new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                MinEndDate = query.MinEndDate,
                MinStartDate = query.MinStartDate,
                MaxEndDate = query.MaxEndDate,
                MaxStartDate = query.MaxStartDate,
                ChannelIds = query.ChannelIds,
                IsMovie = query.IsMovie,
                IsSports = query.IsSports,
                IsKids = query.IsKids,
                Genres = query.Genres,
                StartIndex = query.StartIndex,
                Limit = query.Limit,
                SortBy = query.SortBy,
                SortOrder = query.SortOrder ?? SortOrder.Ascending,
                EnableTotalRecordCount = query.EnableTotalRecordCount,
                TopParentIds = new[] { topFolder.Id.ToString("N") }
            };

            if (query.HasAired.HasValue)
            {
                if (query.HasAired.Value)
                {
                    internalQuery.MaxEndDate = DateTime.UtcNow;
                }
                else
                {
                    internalQuery.MinEndDate = DateTime.UtcNow;
                }
            }

            var queryResult = _libraryManager.QueryItems(internalQuery);

            RemoveFields(options);

            var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ConfigureAwait(false)).ToArray();

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = queryResult.TotalRecordCount
            };

            return result;
        }
예제 #32
0
        public ActionResult <QueryResult <BaseItemDto> > GetArtists(
            [FromQuery] double?minCommunityRating,
            [FromQuery] int?startIndex,
            [FromQuery] int?limit,
            [FromQuery] string?searchTerm,
            [FromQuery] string?parentId,
            [FromQuery] string?fields,
            [FromQuery] string?excludeItemTypes,
            [FromQuery] string?includeItemTypes,
            [FromQuery] ItemFilter[] filters,
            [FromQuery] bool?isFavorite,
            [FromQuery] string?mediaTypes,
            [FromQuery] string?genres,
            [FromQuery] string?genreIds,
            [FromQuery] string?officialRatings,
            [FromQuery] string?tags,
            [FromQuery] string?years,
            [FromQuery] bool?enableUserData,
            [FromQuery] int?imageTypeLimit,
            [FromQuery] string?enableImageTypes,
            [FromQuery] string?person,
            [FromQuery] string?personIds,
            [FromQuery] string?personTypes,
            [FromQuery] string?studios,
            [FromQuery] string?studioIds,
            [FromQuery] Guid?userId,
            [FromQuery] string?nameStartsWithOrGreater,
            [FromQuery] string?nameStartsWith,
            [FromQuery] string?nameLessThan,
            [FromQuery] bool?enableImages           = true,
            [FromQuery] bool enableTotalRecordCount = true)
        {
            var dtoOptions = new DtoOptions()
                             .AddItemFields(fields)
                             .AddClientFields(Request)
                             .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            User?    user = null;
            BaseItem parentItem;

            if (userId.HasValue && !userId.Equals(Guid.Empty))
            {
                user       = _userManager.GetUserById(userId.Value);
                parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
            }
            else
            {
                parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
            }

            var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true);
            var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true);
            var mediaTypesArr       = RequestHelpers.Split(mediaTypes, ',', true);

            var query = new InternalItemsQuery(user)
            {
                ExcludeItemTypes        = excludeItemTypesArr,
                IncludeItemTypes        = includeItemTypesArr,
                MediaTypes              = mediaTypesArr,
                StartIndex              = startIndex,
                Limit                   = limit,
                IsFavorite              = isFavorite,
                NameLessThan            = nameLessThan,
                NameStartsWith          = nameStartsWith,
                NameStartsWithOrGreater = nameStartsWithOrGreater,
                Tags                   = RequestHelpers.Split(tags, ',', true),
                OfficialRatings        = RequestHelpers.Split(officialRatings, ',', true),
                Genres                 = RequestHelpers.Split(genres, ',', true),
                GenreIds               = RequestHelpers.GetGuids(genreIds),
                StudioIds              = RequestHelpers.GetGuids(studioIds),
                Person                 = person,
                PersonIds              = RequestHelpers.GetGuids(personIds),
                PersonTypes            = RequestHelpers.Split(personTypes, ',', true),
                Years                  = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(),
                MinCommunityRating     = minCommunityRating,
                DtoOptions             = dtoOptions,
                SearchTerm             = searchTerm,
                EnableTotalRecordCount = enableTotalRecordCount
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                if (parentItem is Folder)
                {
                    query.AncestorIds = new[] { new Guid(parentId) };
                }
                else
                {
                    query.ItemIds = new[] { new Guid(parentId) };
                }
            }

            // Studios
            if (!string.IsNullOrEmpty(studios))
            {
                query.StudioIds = studios.Split('|').Select(i =>
                {
                    try
                    {
                        return(_libraryManager.GetStudio(i));
                    }
                    catch
                    {
                        return(null);
                    }
                }).Where(i => i != null).Select(i => i !.Id).ToArray();
            }

            foreach (var filter in filters)
            {
                switch (filter)
                {
                case ItemFilter.Dislikes:
                    query.IsLiked = false;
                    break;

                case ItemFilter.IsFavorite:
                    query.IsFavorite = true;
                    break;

                case ItemFilter.IsFavoriteOrLikes:
                    query.IsFavoriteOrLiked = true;
                    break;

                case ItemFilter.IsFolder:
                    query.IsFolder = true;
                    break;

                case ItemFilter.IsNotFolder:
                    query.IsFolder = false;
                    break;

                case ItemFilter.IsPlayed:
                    query.IsPlayed = true;
                    break;

                case ItemFilter.IsResumable:
                    query.IsResumable = true;
                    break;

                case ItemFilter.IsUnplayed:
                    query.IsPlayed = false;
                    break;

                case ItemFilter.Likes:
                    query.IsLiked = true;
                    break;
                }
            }

            var result = _libraryManager.GetArtists(query);

            var dtos = result.Items.Select(i =>
            {
                var(baseItem, itemCounts) = i;
                var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);

                if (!string.IsNullOrWhiteSpace(includeItemTypes))
                {
                    dto.ChildCount   = itemCounts.ItemCount;
                    dto.ProgramCount = itemCounts.ProgramCount;
                    dto.SeriesCount  = itemCounts.SeriesCount;
                    dto.EpisodeCount = itemCounts.EpisodeCount;
                    dto.MovieCount   = itemCounts.MovieCount;
                    dto.TrailerCount = itemCounts.TrailerCount;
                    dto.AlbumCount   = itemCounts.AlbumCount;
                    dto.SongCount    = itemCounts.SongCount;
                    dto.ArtistCount  = itemCounts.ArtistCount;
                }

                return(dto);
            });

            return(new QueryResult <BaseItemDto>
            {
                Items = dtos.ToArray(),
                TotalRecordCount = result.TotalRecordCount
            });
        }
예제 #33
0
        public async Task<QueryResult<BaseItemDto>> GetRecordingSeries(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
            if (user != null && !IsLiveTvEnabled(user))
            {
                return new QueryResult<BaseItemDto>();
            }

            if (_services.Count > 1)
            {
                return new QueryResult<BaseItemDto>();
            }

            if (user == null || (query.IsInProgress ?? false))
            {
                return new QueryResult<BaseItemDto>();
            }

            var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
                .SelectMany(i => i.Locations)
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .Select(i => _libraryManager.FindByPath(i, true))
                .Where(i => i != null)
                .Where(i => i.IsVisibleStandalone(user))
                .ToList();

            if (folders.Count == 0)
            {
                return new QueryResult<BaseItemDto>();
            }

            var includeItemTypes = new List<string>();
            var excludeItemTypes = new List<string>();

            includeItemTypes.Add(typeof(Series).Name);

            var internalResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                Recursive = true,
                AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
                Limit = query.Limit,
                SortBy = new[] { ItemSortBy.DateCreated },
                SortOrder = SortOrder.Descending,
                EnableTotalRecordCount = query.EnableTotalRecordCount,
                IncludeItemTypes = includeItemTypes.ToArray(),
                ExcludeItemTypes = excludeItemTypes.ToArray()
            });

            RemoveFields(options);

            var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();

            return new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = internalResult.TotalRecordCount
            };
        }
예제 #34
0
        private void AddToPlaylistInternal(string playlistId, IEnumerable <Guid> itemIds, User user, DtoOptions options)
        {
            var playlist = _libraryManager.GetItemById(playlistId) as Playlist;

            if (playlist == null)
            {
                throw new ArgumentException("No Playlist exists with the supplied Id");
            }

            var list = new List <LinkedChild>();

            var items = (GetPlaylistItems(itemIds, playlist.MediaType, user, options))
                        .Where(i => i.SupportsAddingToPlaylist)
                        .ToList();

            foreach (var item in items)
            {
                list.Add(LinkedChild.Create(item));
            }

            var newList = playlist.LinkedChildren.ToList();

            newList.AddRange(list);
            playlist.LinkedChildren = newList.ToArray();

            playlist.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);

            if (playlist.IsFile)
            {
                SavePlaylistFile(playlist);
            }

            _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
            {
                ForceSave = true
            }, RefreshPriority.High);
        }
예제 #35
0
 private void RemoveFields(DtoOptions options)
 {
     options.Fields.Remove(ItemFields.CanDelete);
     options.Fields.Remove(ItemFields.CanDownload);
     options.Fields.Remove(ItemFields.DisplayPreferencesId);
     options.Fields.Remove(ItemFields.Etag);
 }
예제 #36
0
        private T GetItemFromSlugName <T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
            where T : BaseItem, new()
        {
            var result = libraryManager.GetItemList(new InternalItemsQuery
            {
                Name             = name.Replace(BaseItem.SlugChar, '&'),
                IncludeItemTypes = new[] { typeof(T).Name },
                DtoOptions       = dtoOptions
            }).OfType <Person>().FirstOrDefault();

            if (result == null)
            {
                result = libraryManager.GetItemList(new InternalItemsQuery
                {
                    Name             = name.Replace(BaseItem.SlugChar, '/'),
                    IncludeItemTypes = new[] { typeof(T).Name },
                    DtoOptions       = dtoOptions
                }).OfType <Person>().FirstOrDefault();
            }

            if (result == null)
            {
                result = libraryManager.GetItemList(new InternalItemsQuery
                {
                    Name             = name.Replace(BaseItem.SlugChar, '?'),
                    IncludeItemTypes = new[] { typeof(T).Name },
                    DtoOptions       = dtoOptions
                }).OfType <Person>().FirstOrDefault();
            }

            return(result as T);
        }
예제 #37
0
        public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = _userManager.GetUserById(query.UserId);

            var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);

            var internalQuery = new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                IsAiring = query.IsAiring,
                IsNews = query.IsNews,
                IsMovie = query.IsMovie,
                IsSeries = query.IsSeries,
                IsSports = query.IsSports,
                IsKids = query.IsKids,
                EnableTotalRecordCount = query.EnableTotalRecordCount,
                SortBy = new[] { ItemSortBy.StartDate },
                TopParentIds = new[] { topFolder.Id.ToString("N") },
                DtoOptions = options
            };

            if (query.Limit.HasValue)
            {
                internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
            }

            if (query.HasAired.HasValue)
            {
                if (query.HasAired.Value)
                {
                    internalQuery.MaxEndDate = DateTime.UtcNow;
                }
                else
                {
                    internalQuery.MinEndDate = DateTime.UtcNow;
                }
            }

            IEnumerable<LiveTvProgram> programs = _libraryManager.QueryItems(internalQuery).Items.Cast<LiveTvProgram>();

            var programList = programs.ToList();

            var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false) || (query.IsNews ?? false) || (query.IsSeries ?? false);

            programs = programList.OrderBy(i => i.StartDate.Date)
                .ThenByDescending(i => GetRecommendationScore(i, user.Id, factorChannelWatchCount))
                .ThenBy(i => i.StartDate);

            if (query.Limit.HasValue)
            {
                programs = programs.Take(query.Limit.Value);
            }

            programList = programs.ToList();

            var returnArray = programList.ToArray();

            var result = new QueryResult<LiveTvProgram>
            {
                Items = returnArray,
                TotalRecordCount = returnArray.Length
            };

            return result;
        }
예제 #38
0
        /// <summary>
        /// Gets the name of the item by.
        /// </summary>
        protected BaseItem GetItemByName(string name, string type, ILibraryManager libraryManager, DtoOptions dtoOptions)
        {
            BaseItem item;

            if (type.IndexOf("Person", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetPerson(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("Artist", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetArtist(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("Genre", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetGenre(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("MusicGenre", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetMusicGenre(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("GameGenre", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetGameGenre(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("Studio", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = GetStudio(name, libraryManager, dtoOptions);
            }
            else if (type.IndexOf("Year", StringComparison.OrdinalIgnoreCase) == 0)
            {
                item = libraryManager.GetYear(int.Parse(name));
            }
            else
            {
                throw new ArgumentException();
            }

            return(item);
        }
예제 #39
0
        public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
        {
            var now = DateTime.UtcNow;

            var channelIds = tuples.Select(i => i.Item2.Id.ToString("N")).Distinct().ToArray();

            var programs = _libraryManager.GetItemList(new InternalItemsQuery(user)
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                ChannelIds = channelIds,
                MaxStartDate = now,
                MinEndDate = now,
                Limit = channelIds.Length,
                SortBy = new[] { "StartDate" }

            }, new string[] { }).ToList();

            foreach (var tuple in tuples)
            {
                var dto = tuple.Item1;
                var channel = tuple.Item2;

                dto.Number = channel.Number;
                dto.ChannelNumber = channel.Number;
                dto.ChannelType = channel.ChannelType;
                dto.ServiceName = GetService(channel).Name;

                dto.MediaSources = channel.GetMediaSources(true).ToList();

                var channelIdString = channel.Id.ToString("N");
                var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString));

                if (currentProgram != null)
                {
                    dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
                }
            }
        }
예제 #40
0
        public ActionResult <QueryResult <BaseItemDto> > GetGenres(
            [FromQuery] int?startIndex,
            [FromQuery] int?limit,
            [FromQuery] string?searchTerm,
            [FromQuery] string?parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes,
            [FromQuery] bool?isFavorite,
            [FromQuery] int?imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] Guid?userId,
            [FromQuery] string?nameStartsWithOrGreater,
            [FromQuery] string?nameStartsWith,
            [FromQuery] string?nameLessThan,
            [FromQuery] bool?enableImages           = true,
            [FromQuery] bool enableTotalRecordCount = true)
        {
            var dtoOptions = new DtoOptions {
                Fields = fields
            }
            .AddClientFields(Request)
            .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);

            User?user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;

            var parentItem = _libraryManager.GetParentItem(parentId, userId);

            var query = new InternalItemsQuery(user)
            {
                ExcludeItemTypes        = excludeItemTypes,
                IncludeItemTypes        = includeItemTypes,
                StartIndex              = startIndex,
                Limit                   = limit,
                IsFavorite              = isFavorite,
                NameLessThan            = nameLessThan,
                NameStartsWith          = nameStartsWith,
                NameStartsWithOrGreater = nameStartsWithOrGreater,
                DtoOptions              = dtoOptions,
                SearchTerm              = searchTerm,
                EnableTotalRecordCount  = enableTotalRecordCount
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                if (parentItem is Folder)
                {
                    query.AncestorIds = new[] { new Guid(parentId) };
                }
                else
                {
                    query.ItemIds = new[] { new Guid(parentId) };
                }
            }

            QueryResult <(BaseItem, ItemCounts)> result;

            if (parentItem is ICollectionFolder parentCollectionFolder &&
                (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music, StringComparison.Ordinal) ||
                 string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos, StringComparison.Ordinal)))
            {
                result = _libraryManager.GetMusicGenres(query);
            }
예제 #41
0
        public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);

            var user = _userManager.GetUserById(query.UserId);

            var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ToArray();

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = internalResult.TotalRecordCount
            };

            return result;
        }
예제 #42
0
 /// <summary>
 /// Check if DtoOptions contains field.
 /// </summary>
 /// <param name="dtoOptions">DtoOptions object.</param>
 /// <param name="field">Field to check.</param>
 /// <returns>Field existence.</returns>
 internal static bool ContainsField(this DtoOptions dtoOptions, ItemFields field)
 => dtoOptions.Fields != null && dtoOptions.Fields.Contains(field);
예제 #43
0
        private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user, DtoOptions options)
        {
            List<BaseItem> linkedChildren = null;

            var backdropLimit = options.GetImageLimit(ImageType.Backdrop);

            if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
            {
                linkedChildren = user == null
                    ? folder.GetRecursiveChildren().ToList()
                    : folder.GetRecursiveChildren(user).ToList();

                var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());

                if (parentWithBackdrop != null)
                {
                    dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
                    dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
                }
            }

            if (!dto.ImageTags.ContainsKey(ImageType.Primary) && options.GetImageLimit(ImageType.Primary) > 0)
            {
                if (linkedChildren == null)
                {
                    linkedChildren = user == null
                        ? folder.GetRecursiveChildren().ToList()
                        : folder.GetRecursiveChildren(user).ToList();
                }
                var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());

                if (parentWithImage != null)
                {
                    dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
                    dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
                }
            }
        }
예제 #44
0
 public List <BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User user, DtoOptions dtoOptions)
 {
     return(GetInstantMixFromGenres(item.Genres, user, dtoOptions));
 }
예제 #45
0
        public void FillSyncInfo(IEnumerable<IHasSyncInfo> dtos, DtoOptions options, User user)
        {
            if (options.Fields.Contains(ItemFields.SyncInfo))
            {
                var syncProgress = GetSyncedItemProgress(options);

                foreach (var dto in dtos)
                {
                    var item = _libraryManager.GetItemById(dto.Id);

                    FillSyncInfo(dto, item, syncProgress, options, user);
                }
            }
        }
예제 #46
0
 public List <BaseItem> GetInstantMixFromPlaylist(Playlist item, User user, DtoOptions dtoOptions)
 {
     return(GetInstantMixFromGenres(item.Genres, user, dtoOptions));
 }
예제 #47
0
        private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, Dictionary<string, SyncedItemProgress> syncProgress, User user = null, BaseItem owner = null)
        {
            var fields = options.Fields;

            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (fields == null)
            {
                throw new ArgumentNullException("fields");
            }

            var dto = new BaseItemDto
            {
                ServerId = _appHost.SystemId
            };

            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, syncProgress);
            }

            var hasMediaSources = item as IHasMediaSources;
            if (hasMediaSources != null)
            {
                if (fields.Contains(ItemFields.MediaSources))
                {
                    if (user == null)
                    {
                        dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true).ToList();
                    }
                    else
                    {
                        dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(hasMediaSources, true, user).ToList();
                    }
                }
            }

            if (fields.Contains(ItemFields.Studios))
            {
                AttachStudios(dto, item);
            }

            AttachBasicFields(dto, item, owner, options);

            var tvChannel = item as LiveTvChannel;
            if (tvChannel != null)
            {
                _livetvManager().AddChannelInfo(dto, tvChannel, options, user);
            }

            var collectionFolder = item as ICollectionFolder;
            if (collectionFolder != null)
            {
                dto.CollectionType = user == null ?
                    collectionFolder.CollectionType :
                    collectionFolder.GetViewType(user);
            }

            var playlist = item as Playlist;
            if (playlist != null)
            {
                AttachLinkedChildImages(dto, playlist, user, options);
            }

            if (fields.Contains(ItemFields.CanDelete))
            {
                dto.CanDelete = user == null
                    ? item.CanDelete()
                    : item.CanDelete(user);
            }

            if (fields.Contains(ItemFields.CanDownload))
            {
                dto.CanDownload = user == null
                    ? item.CanDownload()
                    : item.CanDownload(user);
            }

            if (fields.Contains(ItemFields.Etag))
            {
                dto.Etag = item.GetEtag(user);
            }

            if (item is ILiveTvRecording)
            {
                _livetvManager().AddInfoToRecordingDto(item, dto, user);
            }

            else if (item is LiveTvProgram)
            {
                _livetvManager().AddInfoToProgramDto(item, dto, fields.Contains(ItemFields.ChannelInfo), user);
            }

            return dto;
        }
예제 #48
0
        public List <BaseItem> GetInstantMixFromGenres(IEnumerable <string> genres, User user, DtoOptions dtoOptions)
        {
            var genreIds = genres.DistinctNames().Select(i =>
            {
                try
                {
                    return(_libraryManager.GetMusicGenre(i).Id);
                }
                catch
                {
                    return(Guid.Empty);
                }
            }).Where(i => !i.Equals(Guid.Empty)).ToArray();

            return(GetInstantMixFromGenreIds(genreIds, user, dtoOptions));
        }
예제 #49
0
        private List <BaseItem> GetPlaylistItems(IEnumerable <Guid> itemIds, string playlistMediaType, User user, DtoOptions options)
        {
            var items = itemIds.Select(i => _libraryManager.GetItemById(i)).Where(i => i != null);

            return(Playlist.GetPlaylistItems(playlistMediaType, items, user, options));
        }
예제 #50
0
        private async Task AddToPlaylistInternal(Guid playlistId, IReadOnlyCollection <Guid> newItemIds, User user, DtoOptions options)
        {
            // Retrieve the existing playlist
            var playlist = _libraryManager.GetItemById(playlistId) as Playlist
                           ?? throw new ArgumentException("No Playlist exists with Id " + playlistId);

            // Retrieve all the items to be added to the playlist
            var newItems = GetPlaylistItems(newItemIds, playlist.MediaType, user, options)
                           .Where(i => i.SupportsAddingToPlaylist);

            // Filter out duplicate items, if necessary
            if (!_appConfig.DoPlaylistsAllowDuplicates())
            {
                var existingIds = playlist.LinkedChildren.Select(c => c.ItemId).ToHashSet();
                newItems = newItems
                           .Where(i => !existingIds.Contains(i.Id))
                           .Distinct();
            }

            // Create a list of the new linked children to add to the playlist
            var childrenToAdd = newItems
                                .Select(LinkedChild.Create)
                                .ToList();

            // Log duplicates that have been ignored, if any
            int numDuplicates = newItemIds.Count - childrenToAdd.Count;

            if (numDuplicates > 0)
            {
                _logger.LogWarning("Ignored adding {DuplicateCount} duplicate items to playlist {PlaylistName}.", numDuplicates, playlist.Name);
            }

            // Do nothing else if there are no items to add to the playlist
            if (childrenToAdd.Count == 0)
            {
                return;
            }

            // Create a new array with the updated playlist items
            var newLinkedChildren = new LinkedChild[playlist.LinkedChildren.Length + childrenToAdd.Count];

            playlist.LinkedChildren.CopyTo(newLinkedChildren, 0);
            childrenToAdd.CopyTo(newLinkedChildren, playlist.LinkedChildren.Length);

            // Update the playlist in the repository
            playlist.LinkedChildren = newLinkedChildren;
            await playlist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);

            // Update the playlist on disk
            if (playlist.IsFile)
            {
                SavePlaylistFile(playlist);
            }

            // Refresh playlist metadata
            _providerManager.QueueRefresh(
                playlist.Id,
                new MetadataRefreshOptions(new DirectoryService(_fileSystem))
            {
                ForceSave = true
            },
                RefreshPriority.High);
        }
예제 #51
0
        /// <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="options">The options.</param>
        private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
        {
            var fields = options.Fields;

            if (fields.Contains(ItemFields.DateCreated))
            {
                dto.DateCreated = item.DateCreated;
            }

            if (fields.Contains(ItemFields.DisplayMediaType))
            {
                dto.DisplayMediaType = item.DisplayMediaType;
            }

            if (fields.Contains(ItemFields.Settings))
            {
                dto.LockedFields = item.LockedFields;
                dto.LockData = item.IsLocked;
                dto.ForcedSortName = item.ForcedSortName;
            }

            var hasBudget = item as IHasBudget;
            if (hasBudget != null)
            {
                if (fields.Contains(ItemFields.Budget))
                {
                    dto.Budget = hasBudget.Budget;
                }

                if (fields.Contains(ItemFields.Revenue))
                {
                    dto.Revenue = hasBudget.Revenue;
                }
            }

            dto.EndDate = item.EndDate;

            if (fields.Contains(ItemFields.HomePageUrl))
            {
                dto.HomePageUrl = item.HomePageUrl;
            }

            if (fields.Contains(ItemFields.ExternalUrls))
            {
                dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
            }

            if (fields.Contains(ItemFields.Tags))
            {
                var hasTags = item as IHasTags;
                if (hasTags != null)
                {
                    dto.Tags = hasTags.Tags;
                }

                if (dto.Tags == null)
                {
                    dto.Tags = new List<string>();
                }
            }

            if (fields.Contains(ItemFields.Keywords))
            {
                var hasTags = item as IHasKeywords;
                if (hasTags != null)
                {
                    dto.Keywords = hasTags.Keywords;
                }

                if (dto.Keywords == null)
                {
                    dto.Keywords = new List<string>();
                }
            }

            if (fields.Contains(ItemFields.ProductionLocations))
            {
                SetProductionLocations(item, dto);
            }

            var hasAspectRatio = item as IHasAspectRatio;
            if (hasAspectRatio != null)
            {
                dto.AspectRatio = hasAspectRatio.AspectRatio;
            }

            if (fields.Contains(ItemFields.Metascore))
            {
                var hasMetascore = item as IHasMetascore;
                if (hasMetascore != null)
                {
                    dto.Metascore = hasMetascore.Metascore;
                }
            }

            if (fields.Contains(ItemFields.AwardSummary))
            {
                var hasAwards = item as IHasAwards;
                if (hasAwards != null)
                {
                    dto.AwardSummary = hasAwards.AwardSummary;
                }
            }

            var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
            if (backdropLimit > 0)
            {
                dto.BackdropImageTags = GetBackdropImageTags(item, backdropLimit);
            }

            if (fields.Contains(ItemFields.ScreenshotImageTags))
            {
                var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
                if (screenshotLimit > 0)
                {
                    dto.ScreenshotImageTags = GetScreenshotImageTags(item, screenshotLimit);
                }
            }

            if (fields.Contains(ItemFields.Genres))
            {
                dto.Genres = item.Genres;
            }

            dto.ImageTags = new Dictionary<ImageType, string>();

            // Prevent implicitly captured closure
            var currentItem = item;
            foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
                .ToList())
            {
                if (options.GetImageLimit(image.Type) > 0)
                {
                    var tag = GetImageCacheTag(item, image);

                    if (tag != null)
                    {
                        dto.ImageTags[image.Type] = tag;
                    }
                }
            }

            dto.Id = GetDtoId(item);
            dto.IndexNumber = item.IndexNumber;
            dto.IsFolder = item.IsFolder;
            dto.MediaType = item.MediaType;
            dto.LocationType = item.LocationType;
            dto.IsHD = item.IsHD;

            dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
            dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;

            var hasCriticRating = item as IHasCriticRating;
            if (hasCriticRating != null)
            {
                dto.CriticRating = hasCriticRating.CriticRating;

                if (fields.Contains(ItemFields.CriticRatingSummary))
                {
                    dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
                }
            }

            var hasTrailers = item as IHasTrailers;
            if (hasTrailers != null)
            {
                dto.LocalTrailerCount = hasTrailers.GetTrailerIds().Count;
            }

            var hasDisplayOrder = item as IHasDisplayOrder;
            if (hasDisplayOrder != null)
            {
                dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
            }

            var userView = item as UserView;
            if (userView != null)
            {
                dto.CollectionType = userView.ViewType;
            }

            if (fields.Contains(ItemFields.RemoteTrailers))
            {
                dto.RemoteTrailers = hasTrailers != null ?
                    hasTrailers.RemoteTrailers :
                    new List<MediaUrl>();
            }

            dto.Name = item.Name;
            dto.OfficialRating = item.OfficialRating;

            if (fields.Contains(ItemFields.Overview))
            {
                dto.Overview = item.Overview;
            }

            if (fields.Contains(ItemFields.ShortOverview))
            {
                var hasShortOverview = item as IHasShortOverview;
                if (hasShortOverview != null)
                {
                    dto.ShortOverview = hasShortOverview.ShortOverview;
                }
            }

            // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
            if (backdropLimit > 0 && dto.BackdropImageTags.Count == 0)
            {
                var parentWithBackdrop = GetParentBackdropItem(item, owner);

                if (parentWithBackdrop != null)
                {
                    dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
                    dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop, backdropLimit);
                }
            }

            if (fields.Contains(ItemFields.ParentId))
            {
                var displayParent = item.DisplayParent;
                if (displayParent != null)
                {
                    dto.ParentId = GetDtoId(displayParent);
                }
            }

            dto.ParentIndexNumber = item.ParentIndexNumber;

            // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasLogo && options.GetImageLimit(ImageType.Logo) > 0)
            {
                var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);

                if (parentWithLogo != null)
                {
                    dto.ParentLogoItemId = GetDtoId(parentWithLogo);

                    dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
                }
            }

            // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasArtImage && options.GetImageLimit(ImageType.Art) > 0)
            {
                var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);

                if (parentWithImage != null)
                {
                    dto.ParentArtItemId = GetDtoId(parentWithImage);

                    dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
                }
            }

            // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasThumb && options.GetImageLimit(ImageType.Thumb) > 0)
            {
                var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);

                if (parentWithImage != null)
                {
                    dto.ParentThumbItemId = GetDtoId(parentWithImage);

                    dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
                }
            }

            if (fields.Contains(ItemFields.Path))
            {
                dto.Path = GetMappedPath(item);
            }

            dto.PremiereDate = item.PremiereDate;
            dto.ProductionYear = item.ProductionYear;

            if (fields.Contains(ItemFields.ProviderIds))
            {
                dto.ProviderIds = item.ProviderIds;
            }

            dto.RunTimeTicks = item.RunTimeTicks;

            if (fields.Contains(ItemFields.SortName))
            {
                dto.SortName = item.SortName;
            }

            if (fields.Contains(ItemFields.CustomRating))
            {
                dto.CustomRating = item.CustomRating;
            }

            if (fields.Contains(ItemFields.Taglines))
            {
                var hasTagline = item as IHasTaglines;
                if (hasTagline != null)
                {
                    dto.Taglines = hasTagline.Taglines;
                }

                if (dto.Taglines == null)
                {
                    dto.Taglines = new List<string>();
                }
            }

            dto.Type = item.GetClientTypeName();
            dto.CommunityRating = item.CommunityRating;

            if (fields.Contains(ItemFields.VoteCount))
            {
                dto.VoteCount = item.VoteCount;
            }

            if (item.IsFolder)
            {
                var folder = (Folder)item;

                if (fields.Contains(ItemFields.IndexOptions))
                {
                    dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
                }
            }

            var supportsPlaceHolders = item as ISupportsPlaceHolders;
            if (supportsPlaceHolders != null)
            {
                dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
            }

            // Add audio info
            var audio = item as Audio;
            if (audio != null)
            {
                dto.Album = audio.Album;

                var albumParent = audio.AlbumEntity;

                if (albumParent != null)
                {
                    dto.AlbumId = GetDtoId(albumParent);

                    dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
                }

                //if (fields.Contains(ItemFields.MediaSourceCount))
                //{
                // Songs always have one
                //}
            }

            var hasArtist = item as IHasArtist;
            if (hasArtist != null)
            {
                dto.Artists = hasArtist.Artists;

                dto.ArtistItems = hasArtist
                    .Artists
                    .Select(i =>
                    {
                        try
                        {
                            var artist = _libraryManager.GetArtist(i);
                            return new NameIdPair
                            {
                                Name = artist.Name,
                                Id = artist.Id.ToString("N")
                            };
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting artist", ex);
                            return null;
                        }
                    })
                    .Where(i => i != null)
                    .ToList();
            }

            var hasAlbumArtist = item as IHasAlbumArtist;
            if (hasAlbumArtist != null)
            {
                dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();

                dto.AlbumArtists = hasAlbumArtist
                    .AlbumArtists
                    .Select(i =>
                    {
                        try
                        {
                            var artist = _libraryManager.GetArtist(i);
                            return new NameIdPair
                            {
                                Name = artist.Name,
                                Id = artist.Id.ToString("N")
                            };
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting album artist", ex);
                            return null;
                        }
                    })
                    .Where(i => i != null)
                    .ToList();
            }

            // Add video info
            var video = item as Video;
            if (video != null)
            {
                dto.VideoType = video.VideoType;
                dto.Video3DFormat = video.Video3DFormat;
                dto.IsoType = video.IsoType;

                if (video.HasSubtitles)
                {
                    dto.HasSubtitles = video.HasSubtitles;
                }

                if (video.AdditionalParts.Count != 0)
                {
                    dto.PartCount = video.AdditionalParts.Count + 1;
                }

                if (fields.Contains(ItemFields.MediaSourceCount))
                {
                    if (video.MediaSourceCount != 1)
                    {
                        dto.MediaSourceCount = video.MediaSourceCount;
                    }
                }

                if (fields.Contains(ItemFields.Chapters))
                {
                    dto.Chapters = GetChapterInfoDtos(item);
                }
            }

            if (fields.Contains(ItemFields.MediaStreams))
            {
                // Add VideoInfo
                var iHasMediaSources = item as IHasMediaSources;

                if (iHasMediaSources != null)
                {
                    List<MediaStream> mediaStreams;

                    if (dto.MediaSources != null && dto.MediaSources.Count > 0)
                    {
                        mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
                            .SelectMany(i => i.MediaStreams)
                            .ToList();
                    }
                    else
                    {
                        mediaStreams = _mediaSourceManager().GetStaticMediaSources(iHasMediaSources, true).First().MediaStreams;
                    }

                    dto.MediaStreams = mediaStreams;
                }
            }

            // Add MovieInfo
            var movie = item as Movie;
            if (movie != null)
            {
                if (fields.Contains(ItemFields.TmdbCollectionName))
                {
                    dto.TmdbCollectionName = movie.TmdbCollectionName;
                }
            }

            var hasSpecialFeatures = item as IHasSpecialFeatures;
            if (hasSpecialFeatures != null)
            {
                var specialFeatureCount = hasSpecialFeatures.SpecialFeatureIds.Count;

                if (specialFeatureCount > 0)
                {
                    dto.SpecialFeatureCount = specialFeatureCount;
                }
            }

            // Add EpisodeInfo
            var episode = item as Episode;
            if (episode != null)
            {
                dto.IndexNumberEnd = episode.IndexNumberEnd;

                if (fields.Contains(ItemFields.AlternateEpisodeNumbers))
                {
                    dto.DvdSeasonNumber = episode.DvdSeasonNumber;
                    dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
                    dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
                }

                if (fields.Contains(ItemFields.SpecialEpisodeNumbers))
                {
                    dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
                    dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
                    dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
                }

                var episodeSeason = episode.Season;
                if (episodeSeason != null)
                {
                    dto.SeasonId = episodeSeason.Id.ToString("N");

                    if (fields.Contains(ItemFields.SeasonName))
                    {
                        dto.SeasonName = episodeSeason.Name;
                    }
                }

                if (fields.Contains(ItemFields.SeriesGenres))
                {
                    var episodeseries = episode.Series;
                    if (episodeseries != null)
                    {
                        dto.SeriesGenres = episodeseries.Genres.ToList();
                    }
                }
            }

            // Add SeriesInfo
            var series = item as Series;
            if (series != null)
            {
                dto.AirDays = series.AirDays;
                dto.AirTime = series.AirTime;
                dto.SeriesStatus = series.Status;

                if (fields.Contains(ItemFields.Settings))
                {
                    dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
                }

                dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
            }

            if (episode != null)
            {
                series = episode.Series;

                if (series != null)
                {
                    dto.SeriesId = GetDtoId(series);
                    dto.SeriesName = series.Name;

                    if (fields.Contains(ItemFields.AirTime))
                    {
                        dto.AirTime = series.AirTime;
                    }

                    if (options.GetImageLimit(ImageType.Thumb) > 0)
                    {
                        dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
                    }

                    if (options.GetImageLimit(ImageType.Primary) > 0)
                    {
                        dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                    }

                    if (fields.Contains(ItemFields.SeriesStudio))
                    {
                        dto.SeriesStudio = series.Studios.FirstOrDefault();
                    }
                }
            }

            // Add SeasonInfo
            var season = item as Season;
            if (season != null)
            {
                series = season.Series;

                if (series != null)
                {
                    dto.SeriesId = GetDtoId(series);
                    dto.SeriesName = series.Name;
                    dto.AirTime = series.AirTime;
                    dto.SeriesStudio = series.Studios.FirstOrDefault();

                    if (options.GetImageLimit(ImageType.Primary) > 0)
                    {
                        dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                    }
                }
            }

            var game = item as Game;

            if (game != null)
            {
                SetGameProperties(dto, game);
            }

            var gameSystem = item as GameSystem;

            if (gameSystem != null)
            {
                SetGameSystemProperties(dto, gameSystem);
            }

            var musicVideo = item as MusicVideo;
            if (musicVideo != null)
            {
                SetMusicVideoProperties(dto, musicVideo);
            }

            var book = item as Book;
            if (book != null)
            {
                SetBookProperties(dto, book);
            }

            var photo = item as Photo;
            if (photo != null)
            {
                SetPhotoProperties(dto, photo);
            }

            dto.ChannelId = item.ChannelId;
            
            var channelItem = item as IChannelItem;
            if (channelItem != null)
            {
                dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
            }

            var channelMediaItem = item as IChannelMediaItem;
            if (channelMediaItem != null)
            {
                dto.ExtraType = channelMediaItem.ExtraType;
            }
        }
예제 #52
0
        private async Task <object> GetResult(List <BaseItem> items, User user, BaseGetSimilarItems request, DtoOptions dtoOptions)
        {
            var list = items;

            var result = new QueryResult <BaseItemDto>
            {
                TotalRecordCount = list.Count
            };

            if (request.Limit.HasValue)
            {
                list = list.Take(request.Limit.Value).ToList();
            }

            var returnList = (await _dtoService.GetBaseItemDtos(list, dtoOptions, user)
                              .ConfigureAwait(false));

            result.Items = returnList;

            return(ToOptimizedResult(result));
        }
예제 #53
0
        public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);

            var returnArray = internalResult.Items
                .Select(i => _dtoService.GetBaseItemDto(i, options, user))
                .ToArray();

            if (user != null)
            {
                _dtoService.FillSyncInfo(returnArray, new DtoOptions(), user);
            }

            return new QueryResult<BaseItemDto>
            {
                Items = returnArray,
                TotalRecordCount = internalResult.TotalRecordCount
            };
        }
예제 #54
0
        protected DtoOptions GetDtoOptions(IAuthorizationContext authContext, object request)
        {
            var options = new DtoOptions();

            var authInfo = authContext.GetAuthorizationInfo(Request);

            options.DeviceId = authInfo.DeviceId;

            var hasFields = request as IHasItemFields;

            if (hasFields != null)
            {
                options.Fields = hasFields.GetItemFields();
            }

            var client = authInfo.Client ?? string.Empty;

            if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1)
            {
                var list = options.Fields.ToList();
                list.Add(Model.Querying.ItemFields.RecursiveItemCount);
                options.Fields = list.ToArray(list.Count);
            }

            if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("wmc", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("roku", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("samsung", StringComparison.OrdinalIgnoreCase) != -1 ||
                client.IndexOf("androidtv", StringComparison.OrdinalIgnoreCase) != -1)
            {
                var list = options.Fields.ToList();
                list.Add(Model.Querying.ItemFields.ChildCount);
                options.Fields = list.ToArray(list.Count);
            }

            var hasDtoOptions = request as IHasDtoOptions;

            if (hasDtoOptions != null)
            {
                options.EnableImages = hasDtoOptions.EnableImages ?? true;

                if (hasDtoOptions.ImageTypeLimit.HasValue)
                {
                    options.ImageTypeLimit = hasDtoOptions.ImageTypeLimit.Value;
                }
                if (hasDtoOptions.EnableUserData.HasValue)
                {
                    options.EnableUserData = hasDtoOptions.EnableUserData.Value;
                }

                if (!string.IsNullOrWhiteSpace(hasDtoOptions.EnableImageTypes))
                {
                    options.ImageTypes = (hasDtoOptions.EnableImageTypes ?? string.Empty).Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)).ToArray();
                }
            }

            return(options);
        }
예제 #55
0
        public void AddChannelInfo(BaseItemDto dto, LiveTvChannel channel, DtoOptions options, User user)
        {
            dto.MediaSources = channel.GetMediaSources(true).ToList();

            var now = DateTime.UtcNow;

            var programs = _libraryManager.GetItems(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                ChannelIds = new[] { channel.Id.ToString("N") },
                MaxStartDate = now,
                MinEndDate = now,
                Limit = 1,
                SortBy = new[] { "StartDate" }

            }).Items.Cast<LiveTvProgram>();

            var currentProgram = programs.FirstOrDefault();

            if (currentProgram != null)
            {
                dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
            }
        }
예제 #56
0
        protected MusicGenre GetMusicGenre(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
        {
            if (name.IndexOf(BaseItem.SlugChar) != -1)
            {
                var result = GetItemFromSlugName <MusicGenre>(libraryManager, name, dtoOptions);

                if (result != null)
                {
                    return(result);
                }
            }

            return(libraryManager.GetMusicGenre(name));
        }
예제 #57
0
        public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
        {
            var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);

            var internalQuery = new InternalItemsQuery
            {
                IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
                MinEndDate = query.MinEndDate,
                MinStartDate = query.MinStartDate,
                MaxEndDate = query.MaxEndDate,
                MaxStartDate = query.MaxStartDate,
                ChannelIds = query.ChannelIds,
                IsMovie = query.IsMovie,
                IsSports = query.IsSports,
                IsKids = query.IsKids,
                Genres = query.Genres,
                StartIndex = query.StartIndex,
                Limit = query.Limit,
                SortBy = query.SortBy,
                SortOrder = query.SortOrder ?? SortOrder.Ascending
            };

            if (user != null)
            {
                internalQuery.MaxParentalRating = user.Policy.MaxParentalRating;

                if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram))
                {
                    internalQuery.HasParentalRating = true;
                }
            }

            if (query.HasAired.HasValue)
            {
                if (query.HasAired.Value)
                {
                    internalQuery.MaxEndDate = DateTime.UtcNow;
                }
                else
                {
                    internalQuery.MinEndDate = DateTime.UtcNow;
                }
            }

            var queryResult = _libraryManager.QueryItems(internalQuery);

            var returnArray = queryResult.Items
                .Cast<LiveTvProgram>()
                .Select(i => new Tuple<BaseItemDto, string, string>(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId))
                .ToArray();

            await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);

            var result = new QueryResult<BaseItemDto>
            {
                Items = returnArray.Select(i => i.Item1).ToArray(),
                TotalRecordCount = queryResult.TotalRecordCount
            };

            return result;
        }
예제 #58
0
파일: DtoService.cs 프로젝트: paul-777/Emby
        public IEnumerable<BaseItemDto> GetBaseItemDtos(IEnumerable<BaseItem> items, DtoOptions options, User user = null, BaseItem owner = null)
        {
            var syncJobItems = GetSyncedItemProgress(options);
            var syncDictionary = GetSyncedItemProgressDictionary(syncJobItems);

            var list = new List<BaseItemDto>();
            var programTuples = new List<Tuple<BaseItem, BaseItemDto>> { };
            var channelTuples = new List<Tuple<BaseItemDto, LiveTvChannel>> { };

            foreach (var item in items)
            {
                var dto = GetBaseItemDtoInternal(item, options, syncDictionary, user, owner);

                var tvChannel = item as LiveTvChannel;
                if (tvChannel != null)
                {
                    channelTuples.Add(new Tuple<BaseItemDto, LiveTvChannel>(dto, tvChannel));
                }
                else if (item is LiveTvProgram)
                {
                    programTuples.Add(new Tuple<BaseItem, BaseItemDto>(item, dto));
                }

                var byName = item as IItemByName;

                if (byName != null)
                {
                    if (options.Fields.Contains(ItemFields.ItemCounts))
                    {
                        var libraryItems = byName.GetTaggedItems(new InternalItemsQuery(user)
                        {
                            Recursive = true
                        });

                        SetItemByNameInfo(item, dto, libraryItems.ToList(), user);
                    }
                }

                FillSyncInfo(dto, item, syncJobItems, options, user);

                list.Add(dto);
            }

            if (programTuples.Count > 0)
            {
                var task = _livetvManager().AddInfoToProgramDto(programTuples, options.Fields, user);
                Task.WaitAll(task);
            }

            if (channelTuples.Count > 0)
            {
                _livetvManager().AddChannelInfo(channelTuples, options, user);
            }

            return list;
        }
예제 #59
0
        private SyncedItem GetJobItemInfo(SyncJobItem jobItem)
        {
            var job = _repo.GetJob(jobItem.JobId);

            if (job == null)
            {
                _logger.Error("GetJobItemInfo job id {0} no longer exists", jobItem.JobId);
                return null;
            }

            var libraryItem = _libraryManager.GetItemById(jobItem.ItemId);

            if (libraryItem == null)
            {
                _logger.Error("GetJobItemInfo library item with id {0} no longer exists", jobItem.ItemId);
                return null;
            }

            var syncedItem = new SyncedItem
            {
                SyncJobId = jobItem.JobId,
                SyncJobItemId = jobItem.Id,
                ServerId = _appHost.SystemId,
                UserId = job.UserId,
                SyncJobName = job.Name,
                SyncJobDateCreated = job.DateCreated,
                AdditionalFiles = jobItem.AdditionalFiles.Select(i => new ItemFileInfo
                {
                    ImageType = i.ImageType,
                    Name = i.Name,
                    Type = i.Type,
                    Index = i.Index

                }).ToList()
            };

            var dtoOptions = new DtoOptions();

            // Remove some bloat
            dtoOptions.Fields.Remove(ItemFields.MediaStreams);
            dtoOptions.Fields.Remove(ItemFields.IndexOptions);
            dtoOptions.Fields.Remove(ItemFields.MediaSourceCount);
            dtoOptions.Fields.Remove(ItemFields.Path);
            dtoOptions.Fields.Remove(ItemFields.SeriesGenres);
            dtoOptions.Fields.Remove(ItemFields.Settings);
            dtoOptions.Fields.Remove(ItemFields.SyncInfo);

            syncedItem.Item = _dtoService().GetBaseItemDto(libraryItem, dtoOptions);

            var mediaSource = jobItem.MediaSource;

            syncedItem.Item.MediaSources = new List<MediaSourceInfo>();

            syncedItem.OriginalFileName = Path.GetFileName(libraryItem.Path);
            if (string.IsNullOrWhiteSpace(syncedItem.OriginalFileName))
            {
                syncedItem.OriginalFileName = Path.GetFileName(mediaSource.Path);
            }

            // This will be null for items that are not audio/video
            if (mediaSource != null)
            {
                syncedItem.OriginalFileName = Path.ChangeExtension(syncedItem.OriginalFileName, Path.GetExtension(mediaSource.Path));
                syncedItem.Item.MediaSources.Add(mediaSource);
            }
            if (string.IsNullOrWhiteSpace(syncedItem.OriginalFileName))
            {
                syncedItem.OriginalFileName = libraryItem.Name;
            }

            return syncedItem;
        }
        private IEnumerable <RecommendationDto> GetWithActor(User user, IEnumerable <string> names, int itemLimit, DtoOptions dtoOptions, RecommendationType type)
        {
            var itemTypes = new List <string> {
                typeof(Movie).Name
            };

            if (_config.Configuration.EnableExternalContentInSuggestions)
            {
                itemTypes.Add(typeof(Trailer).Name);
                itemTypes.Add(typeof(LiveTvProgram).Name);
            }

            foreach (var name in names)
            {
                var items = _libraryManager.GetItemList(new InternalItemsQuery(user)
                {
                    Person = name,
                    // Account for duplicates by imdb id, since the database doesn't support this yet
                    Limit                    = itemLimit + 2,
                    IncludeItemTypes         = itemTypes.ToArray(itemTypes.Count),
                    IsMovie                  = true,
                    EnableGroupByMetadataKey = true,
                    DtoOptions               = dtoOptions
                }).DistinctBy(i => i.GetProviderId(MetadataProviders.Imdb) ?? Guid.NewGuid().ToString("N"))
                            .Take(itemLimit)
                            .ToList();

                if (items.Count > 0)
                {
                    var returnItems = _dtoService.GetBaseItemDtos(items, dtoOptions, user);

                    yield return(new RecommendationDto
                    {
                        BaselineItemName = name,
                        CategoryId = name.GetMD5().ToString("N"),
                        RecommendationType = type,
                        Items = returnItems
                    });
                }
            }
        }