Example #1
0
        /// <summary>
        /// Posts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Post(AddVirtualFolder request)
        {
            var name = _fileSystem.GetValidFilename(request.Name);

            string rootFolderPath;

            if (string.IsNullOrEmpty(request.UserId))
            {
                rootFolderPath = _appPaths.DefaultUserViewsPath;
            }
            else
            {
                var user = _userManager.GetUserById(new Guid(request.UserId));

                rootFolderPath = user.RootFolderPath;
            }

            var virtualFolderPath = Path.Combine(rootFolderPath, name);

            if (Directory.Exists(virtualFolderPath))
            {
                throw new ArgumentException("There is already a media collection with the name " + name + ".");
            }

            _directoryWatchers.Stop();
            _directoryWatchers.TemporarilyIgnore(virtualFolderPath);

            try
            {
                Directory.CreateDirectory(virtualFolderPath);

                if (!string.IsNullOrEmpty(request.CollectionType))
                {
                    var path = Path.Combine(virtualFolderPath, request.CollectionType + ".collection");

                    File.Create(path);
                }

                // Need to add a delay here or directory watchers may still pick up the changes
                var task = Task.Delay(1000);
                // Have to block here to allow exceptions to bubble
                Task.WaitAll(task);
            }
            finally
            {
                _directoryWatchers.Start();
                _directoryWatchers.RemoveTempIgnore(virtualFolderPath);
            }

            if (request.RefreshLibrary)
            {
                _libraryManager.ValidateMediaLibrary(new Progress <double>(), CancellationToken.None);
            }
        }
        /// <summary>
        /// Downloads the trailer for item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task DownloadTrailerForItem(BaseItem item, CancellationToken cancellationToken)
        {
            var url = await GetTrailerUrl(item, cancellationToken).ConfigureAwait(false);

            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            var responseInfo = await _httpClient.GetTempFileResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                Progress          = new Progress <double>(),
                UserAgent         = GetUserAgent(url)
            });

            var extension = responseInfo.ContentType.Split('/').Last();

            if (string.Equals("quicktime", extension, StringComparison.OrdinalIgnoreCase))
            {
                extension = "mov";
            }

            var savePath = Directory.Exists(item.Path) ?
                           Path.Combine(item.Path, Path.GetFileNameWithoutExtension(item.Path) + "-trailer." + extension) :
                           Path.Combine(Path.GetDirectoryName(item.Path), Path.GetFileNameWithoutExtension(item.Path) + "-trailer." + extension);

            if (!EntityResolutionHelper.IsVideoFile(savePath))
            {
                _logger.Warn("Unrecognized video extension {0}", savePath);
                return;
            }

            _directoryWatchers.TemporarilyIgnore(savePath);

            _logger.Info("Moving {0} to {1}", responseInfo.TempFilePath, savePath);

            try
            {
                var parentPath = Path.GetDirectoryName(savePath);

                if (!Directory.Exists(parentPath))
                {
                    Directory.CreateDirectory(parentPath);
                }

                File.Move(responseInfo.TempFilePath, savePath);
            }
            finally
            {
                _directoryWatchers.RemoveTempIgnore(savePath);
            }

            await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
        }
Example #3
0
        /// <summary>
        /// Saves to library filesystem.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="path">The path.</param>
        /// <param name="dataToSave">The data to save.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException();
            }
            if (dataToSave == null)
            {
                throw new ArgumentNullException();
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException();
            }

            if (cancellationToken.IsCancellationRequested)
            {
                dataToSave.Dispose();
                cancellationToken.ThrowIfCancellationRequested();
            }

            //Tell the watchers to ignore
            _directoryWatchers.TemporarilyIgnore(path);

            if (dataToSave.CanSeek)
            {
                dataToSave.Position = 0;
            }

            try
            {
                using (dataToSave)
                {
                    using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
                    {
                        await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
                    }
                }

                // If this is ever used for something other than metadata we can add a file type param
                item.ResolveArgs.AddMetadataFile(path);
            }
            finally
            {
                //Remove the ignore
                _directoryWatchers.RemoveTempIgnore(path);
            }
        }
Example #4
0
        /// <summary>
        /// Saves the image.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="source">The source.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int?imageIndex, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = _config.Configuration.SaveLocalMeta;

            if (item is IItemByName)
            {
                saveLocally = true;
            }
            else if (item is User)
            {
                saveLocally = true;
            }
            else if (item is Audio || item.Parent == null || string.IsNullOrEmpty(item.MetaLocation))
            {
                saveLocally = false;
            }

            if (type != ImageType.Primary)
            {
                if (item is Episode)
                {
                    saveLocally = false;
                }
            }

            if (item.LocationType == LocationType.Remote || item.LocationType == LocationType.Virtual)
            {
                saveLocally = false;
            }

            var path = GetSavePath(item, type, imageIndex, mimeType, saveLocally);

            var currentPath = GetCurrentImagePath(item, type, imageIndex);

            try
            {
                _directoryWatchers.TemporarilyIgnore(path);

                using (source)
                {
                    using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
                    {
                        await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
                    }
                }

                SetImagePath(item, type, imageIndex, path);

                if (!string.IsNullOrEmpty(currentPath) && !string.Equals(path, currentPath, StringComparison.OrdinalIgnoreCase))
                {
                    File.Delete(currentPath);
                }
            }
            finally
            {
                _directoryWatchers.RemoveTempIgnore(path);
            }
        }
Example #5
0
        /// <summary>
        /// Saves the image.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="source">The source.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="sourceUrl">The source URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">mimeType</exception>
        public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int?imageIndex, string sourceUrl, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = _config.Configuration.SaveLocalMeta && item.Parent != null && !(item is Audio);

            if (item is IItemByName || item is User)
            {
                saveLocally = true;
            }

            if (type != ImageType.Primary && item is Episode)
            {
                saveLocally = false;
            }

            var locationType = item.LocationType;

            if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
            {
                saveLocally = false;
            }

            var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);

            // If there are more than one output paths, the stream will need to be seekable
            if (paths.Length > 1 && !source.CanSeek)
            {
                var memoryStream = new MemoryStream();
                using (source)
                {
                    await source.CopyToAsync(memoryStream).ConfigureAwait(false);
                }
                memoryStream.Position = 0;
                source = memoryStream;
            }

            var currentPath = GetCurrentImagePath(item, type, imageIndex);

            using (source)
            {
                var isFirst = true;

                foreach (var path in paths)
                {
                    // Seek back to the beginning
                    if (!isFirst)
                    {
                        source.Position = 0;
                    }

                    await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);

                    isFirst = false;
                }
            }

            // Set the path into the BaseItem
            SetImagePath(item, type, imageIndex, paths[0], sourceUrl);

            // Delete the current path
            if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
            {
                _directoryWatchers.TemporarilyIgnore(currentPath);

                try
                {
                    var currentFile = new FileInfo(currentPath);

                    // This will fail if the file is hidden
                    if (currentFile.Exists)
                    {
                        if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            currentFile.Attributes &= ~FileAttributes.Hidden;
                        }

                        currentFile.Delete();
                    }
                }
                finally
                {
                    _directoryWatchers.RemoveTempIgnore(currentPath);
                }
            }
        }