private async Task <ThemeMediaResult> GetThemeSongs(GetThemeSongs request)
        {
            var user = request.UserId.HasValue ? _userManager.GetUserById(request.UserId.Value) : null;

            var item = string.IsNullOrEmpty(request.Id)
                           ? (request.UserId.HasValue
                                  ? user.RootFolder
                                  : (Folder)_libraryManager.RootFolder)
                           : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, request.UserId);

            while (item.ThemeSongIds.Count == 0 && request.InheritFromParent && item.Parent != null)
            {
                item = item.Parent;
            }

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields))
                         .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
                         .ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userDataRepository, _itemRepo);

            var tasks = item.ThemeSongIds.Select(_itemRepo.RetrieveItem)
                        .OrderBy(i => i.SortName)
                        .Select(i => dtoBuilder.GetBaseItemDto(i, fields, user, item));

            var items = await Task.WhenAll(tasks).ConfigureAwait(false);

            return(new ThemeMediaResult
            {
                Items = items,
                TotalRecordCount = items.Length,
                OwnerId = DtoBuilder.GetClientItemId(item)
            });
        }
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetAdditionalParts request)
        {
            var user = request.UserId.HasValue ? _userManager.GetUserById(request.UserId.Value) : null;

            var item = string.IsNullOrEmpty(request.Id)
                           ? (request.UserId.HasValue
                                  ? user.RootFolder
                                  : (Folder)_libraryManager.RootFolder)
                           : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, request.UserId);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields))
                         .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
                         .ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userDataRepository, _itemRepo);

            var video = (Video)item;

            var items = video.AdditionalPartIds.Select(_itemRepo.RetrieveItem)
                        .OrderBy(i => i.SortName)
                        .Select(i => dtoBuilder.GetBaseItemDto(i, fields, user, video))
                        .Select(t => t.Result)
                        .ToArray();

            var result = new ItemsResult
            {
                Items            = items,
                TotalRecordCount = items.Length
            };

            return(ToOptimizedResult(result));
        }
Beispiel #3
0
        /// <summary>
        /// Refreshes the item.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task.</returns>
        private async Task RefreshItem(RefreshItem request)
        {
            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            var folder = item as Folder;

            try
            {
                await item.RefreshMetadata(CancellationToken.None, forceRefresh : request.Forced).ConfigureAwait(false);

                if (folder != null)
                {
                    // Collection folders don't validate their children so we'll have to simulate that here
                    var collectionFolder = folder as CollectionFolder;

                    if (collectionFolder != null)
                    {
                        await RefreshCollectionFolderChildren(request, collectionFolder).ConfigureAwait(false);
                    }
                    else
                    {
                        await folder.ValidateChildren(new Progress <double>(), CancellationToken.None, request.Recursive, request.Forced).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error refreshing library", ex);
            }
        }
        /// <summary>
        /// Gets the similar items.
        /// </summary>
        /// <param name="userManager">The user manager.</param>
        /// <param name="itemRepository">The item repository.</param>
        /// <param name="libraryManager">The library manager.</param>
        /// <param name="userDataRepository">The user data repository.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="request">The request.</param>
        /// <param name="includeInSearch">The include in search.</param>
        /// <param name="getSimilarityScore">The get similarity score.</param>
        /// <returns>ItemsResult.</returns>
        internal static ItemsResult GetSimilarItems(IUserManager userManager, IItemRepository itemRepository, ILibraryManager libraryManager, IUserDataRepository userDataRepository, ILogger logger, BaseGetSimilarItems request, Func <BaseItem, bool> includeInSearch, Func <BaseItem, BaseItem, int> getSimilarityScore)
        {
            var user = request.UserId.HasValue ? userManager.GetUserById(request.UserId.Value) : null;

            var item = string.IsNullOrEmpty(request.Id) ?
                       (request.UserId.HasValue ? user.RootFolder :
                        (Folder)libraryManager.RootFolder) : DtoBuilder.GetItemByClientId(request.Id, userManager, libraryManager, request.UserId);

            var fields = request.GetItemFields().ToList();

            var dtoBuilder = new DtoBuilder(logger, libraryManager, userDataRepository, itemRepository);

            var inputItems = user == null
                                 ? libraryManager.RootFolder.RecursiveChildren
                                 : user.RootFolder.GetRecursiveChildren(user);

            var items = GetSimilaritems(item, inputItems, includeInSearch, getSimilarityScore).ToArray();

            var result = new ItemsResult
            {
                Items = items.Take(request.Limit ?? items.Length).Select(i => dtoBuilder.GetBaseItemDto(i, fields, user)).Select(t => t.Result).ToArray(),

                TotalRecordCount = items.Length
            };

            return(result);
        }
Beispiel #5
0
        private Task UpdateItem(UpdateItem request)
        {
            var item = DtoBuilder.GetItemByClientId(request.ItemId, _userManager, _libraryManager);

            UpdateItem(request, item);

            return(_libraryManager.UpdateItem(item, ItemUpdateType.MetadataEdit, CancellationToken.None));
        }
Beispiel #6
0
        public object Get(GetInstantMixFromSong request)
        {
            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            var result = GetInstantMixResult(request, item.Genres).Result;

            return(ToOptimizedResult(result));
        }
Beispiel #7
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItemImageInfos request)
        {
            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            var result = GetItemImageInfos(item).Result;

            return ToOptimizedResult(result);
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(OnPlaybackStart request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            _sessionManager.OnPlaybackStart(item, GetSession().Id);
        }
        /// <summary>
        /// Updates the played status.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="itemId">The item id.</param>
        /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
        /// <returns>Task.</returns>
        private async Task <UserItemDataDto> UpdatePlayedStatus(User user, string itemId, bool wasPlayed)
        {
            var item = DtoBuilder.GetItemByClientId(itemId, _userManager, _libraryManager, user.Id);

            await item.SetPlayedStatus(user, wasPlayed, _userDataRepository).ConfigureAwait(false);

            return(DtoBuilder.GetUserItemDataDto(_userDataRepository.GetUserData(user.Id, item.GetUserDataKey())));
        }
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetIntros request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var result = _libraryManager.GetIntros(item, user);

            return(ToOptimizedResult(result));
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(OnPlaybackProgress request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var task = _sessionManager.OnPlaybackProgress(item, request.PositionTicks, request.IsPaused, GetSession().Id);

            Task.WaitAll(task);
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Delete(OnPlaybackStopped request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var task = _sessionManager.OnPlaybackStopped(item, request.PositionTicks, GetSession().Id);

            Task.WaitAll(task);
        }
        private async Task DeleteItem(DeleteItem request)
        {
            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            var parent = item.Parent;

            if (item.LocationType == LocationType.Offline)
            {
                throw new InvalidOperationException(string.Format("{0} is currently offline.", item.Name));
            }

            if (item.LocationType == LocationType.FileSystem)
            {
                if (Directory.Exists(item.Path))
                {
                    Directory.Delete(item.Path, true);
                }
                else if (File.Exists(item.Path))
                {
                    File.Delete(item.Path);
                }

                if (parent != null)
                {
                    try
                    {
                        await
                        parent.ValidateChildren(new Progress <double>(), CancellationToken.None)
                        .ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorException("Error refreshing item", ex);
                    }
                }
            }
            else if (parent != null)
            {
                try
                {
                    await parent.RemoveChild(item, CancellationToken.None).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException("Error removing item", ex);
                }
            }
            else
            {
                throw new InvalidOperationException("Don't know how to delete " + item.Name);
            }
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(OnPlaybackStart request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var auth = RequestFilterAttribute.GetAuthorization(RequestContext);

            if (auth != null)
            {
                _userManager.OnPlaybackStart(user, item, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{ItemsResult}.</returns>
        protected async Task <ItemsResult> GetResult(GetItemsByName request)
        {
            var user = UserManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.ParentId, UserManager, LibraryManager, user.Id);

            IEnumerable <BaseItem> items;

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

                items = request.Recursive ? folder.GetRecursiveChildren(user) : folder.GetChildren(user);
            }
            else
            {
                items = new[] { item };
            }

            var ibnItemsArray = GetAllItems(request, items, user).ToArray();
            IEnumerable <Tuple <string, Func <int> > > ibnItems = ibnItemsArray;

            var result = new ItemsResult
            {
                TotalRecordCount = ibnItemsArray.Length
            };

            if (request.StartIndex.HasValue || request.Limit.HasValue)
            {
                if (request.StartIndex.HasValue)
                {
                    ibnItems = ibnItems.Skip(request.StartIndex.Value);
                }

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

            var fields = GetItemFields(request).ToList();

            var tasks = ibnItems.Select(i => GetDto(i, user, fields));

            var resultItems = await Task.WhenAll(tasks).ConfigureAwait(false);

            result.Items = resultItems.Where(i => i != null).ToArray();

            return(result);
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(UpdateUserItemRating request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = (Folder)DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get the user data for this item
            var data = item.GetUserData(user, true);

            data.Likes = request.Likes;

            var task = _userManager.SaveUserDataForItem(user, item, data);

            Task.WaitAll(task);
        }
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItem request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userDataRepository, _itemRepo);

            var result = dtoBuilder.GetBaseItemDto(item, fields, user).Result;

            return(ToOptimizedResult(result));
        }
        public object Get(GetFile request)
        {
            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            if (item.LocationType == LocationType.Remote || item.LocationType == LocationType.Virtual)
            {
                throw new ArgumentException("This command cannot be used for remote or virtual items.");
            }
            if (Directory.Exists(item.Path))
            {
                throw new ArgumentException("This command cannot be used for directories.");
            }

            return(ToStaticFileResult(item.Path));
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Delete(OnPlaybackStopped request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var auth = RequestFilterAttribute.GetAuthorization(RequestContext);

            if (auth != null)
            {
                var task = _userManager.OnPlaybackStopped(user, item, request.PositionTicks, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty);

                Task.WaitAll(task);
            }
        }
Beispiel #20
0
        public object Get(GetInstantMixFromAlbum request)
        {
            var album = (MusicAlbum)DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager);

            var genres = album
                         .RecursiveChildren
                         .OfType <Audio>()
                         .SelectMany(i => i.Genres)
                         .Concat(album.Genres)
                         .Distinct(StringComparer.OrdinalIgnoreCase);

            var result = GetInstantMixResult(request, genres).Result;

            return(ToOptimizedResult(result));
        }
Beispiel #21
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetLocalTrailers request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userDataRepository, _itemRepo);

            var items = item.LocalTrailerIds.Select(_itemRepo.RetrieveItem).OrderBy(i => i.SortName).Select(i => dtoBuilder.GetBaseItemDto(i, fields, user)).Select(t => t.Result).ToList();

            return(ToOptimizedResult(items));
        }
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItem request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager);

            var result = dtoBuilder.GetBaseItemDto(item, user, fields).Result;

            return(ToOptimizedResult(result));
        }
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetLocalTrailers request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager);

            var items = item.LocalTrailers.Select(i => dtoBuilder.GetBaseItemDto(i, user, fields)).AsParallel().Select(t => t.Result).ToList();

            return(ToOptimizedResult(items));
        }
        /// <summary>
        /// Deletes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Delete(UnmarkFavoriteItem request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = (Folder)DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get the user data for this item
            var data = item.GetUserData(user, true);

            // Set favorite status
            data.IsFavorite = false;

            var task = _userManager.SaveUserDataForItem(user, item, data);

            Task.WaitAll(task);
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(UpdateUserItemRating request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var key = item.GetUserDataKey();

            // Get the user data for this item
            var data = _userDataRepository.GetUserData(user.Id, key);

            data.Likes = request.Likes;

            var task = _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None);

            Task.WaitAll(task);
        }
        /// <summary>
        /// Deletes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Delete(UnmarkFavoriteItem request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            var key = item.GetUserDataKey();

            // Get the user data for this item
            var data = _userDataRepository.GetUserData(user.Id, key);

            // Set favorite status
            data.IsFavorite = false;

            var task = _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None);

            Task.WaitAll(task);
        }
        private Task <BaseItemDto[]> GetAsync(GetLocalTrailers request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var item = string.IsNullOrEmpty(request.Id) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.Id, _userManager, _libraryManager, user.Id);

            // Get everything
            var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager, _userDataRepository, _itemRepo);

            var tasks = item.LocalTrailerIds
                        .Select(_itemRepo.RetrieveItem)
                        .OrderBy(i => i.SortName)
                        .Select(i => dtoBuilder.GetBaseItemDto(i, fields, user, item));

            return(Task.WhenAll(tasks));
        }
        private async Task <UserItemDataDto> UpdateUserItemRating(Guid userId, string itemId, bool?likes)
        {
            var user = _userManager.GetUserById(userId);

            var item = string.IsNullOrEmpty(itemId) ? user.RootFolder : DtoBuilder.GetItemByClientId(itemId, _userManager, _libraryManager, user.Id);

            var key = item.GetUserDataKey();

            // Get the user data for this item
            var data = _userDataRepository.GetUserData(user.Id, key);

            data.Likes = likes;

            await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);

            data = _userDataRepository.GetUserData(user.Id, key);

            return(DtoBuilder.GetUserItemDataDto(data));
        }
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(UpdateDisplayPreferences request)
        {
            // We need to parse this manually because we told service stack not to with IRequiresRequestStream
            // https://code.google.com/p/servicestack/source/browse/trunk/Common/ServiceStack.Text/ServiceStack.Text/Controller/PathInfo.cs
            var pathInfo = PathInfo.Parse(RequestContext.PathInfo);
            var userId   = new Guid(pathInfo.GetArgumentValue <string>(1));
            var itemId   = pathInfo.GetArgumentValue <string>(3);

            var user = _userManager.GetUserById(userId);

            var item = (Folder)DtoBuilder.GetItemByClientId(itemId, _userManager, _libraryManager, user.Id);

            // Serialize to json and then back so that the core doesn't see the request dto type
            var displayPreferences = _jsonSerializer.DeserializeFromString <DisplayPreferences>(_jsonSerializer.SerializeToString(request));

            var task = _libraryManager.SaveDisplayPreferencesForFolder(user, item, displayPreferences);

            Task.WaitAll(task);
        }
Beispiel #30
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        private IEnumerable <BaseItem> GetItemsToSerialize(GetItems request, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.ParentId, _userManager, _libraryManager, user.Id);

            // Default list type = children

            if (!string.IsNullOrEmpty(request.Ids))
            {
                var idList = request.Ids.Split(',').ToList();

                return(idList.Select(i => DtoBuilder.GetItemByClientId(i, _userManager, _libraryManager, user.Id)));
            }

            if (request.Recursive)
            {
                return(((Folder)item).GetRecursiveChildren(user));
            }

            return(((Folder)item).GetChildren(user, true, request.IndexBy));
        }