Example #1
0
        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static Size GetDimensions(string path, ILogger logger, IFileSystem fileSystem)
        {
            try
            {
                using (var fs = File.OpenRead(path))
                {
                    using (var binaryReader = new BinaryReader(fs))
                    {
                        return GetDimensions(binaryReader);
                    }
                }
            }
            catch
            {
                logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
            }

            // Buffer to memory stream to avoid image locking file
            using (var fs = fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var memoryStream = new MemoryStream())
                {
                    fs.CopyTo(memoryStream);

                    // Co it the old fashioned way
                    using (var b = Image.FromStream(memoryStream, true, false))
                    {
                        return b.Size;
                    }
                }
            }
        }
        public static async Task<Stream> GetThumbCollage(List<string> files,
            IFileSystem fileSystem,
            int width,
            int height)
        {
            if (files.Count < 3)
            {
                return await GetSingleImage(files, fileSystem).ConfigureAwait(false);
            }

            const int rows = 1;
            const int cols = 3;

            int cellWidth = 2 * (width / 3);
            int cellHeight = height;
            var index = 0;

            var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb);

            using (var graphics = Graphics.FromImage(img))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphics.CompositingMode = CompositingMode.SourceCopy;

                for (var row = 0; row < rows; row++)
                {
                    for (var col = 0; col < cols; col++)
                    {
                        var x = col * (cellWidth / 2);
                        var y = row * cellHeight;

                        if (files.Count > index)
                        {
                            using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true))
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);

                                    memoryStream.Position = 0;

                                    using (var imgtemp = Image.FromStream(memoryStream, true, false))
                                    {
                                        graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight);
                                    }
                                }
                            }
                        }

                        index++;
                    }
                }
            }

            return GetStream(img);
        }
Example #3
0
        public static void CreateThumbCollage(List<string> files,
            IFileSystem fileSystem,
            string file,
            int width,
            int height)
        {
            const int numStrips = 4;
            files = ImageHelpers.ProjectPaths(files, numStrips);

            const int rows = 1;
            int cols = numStrips;

            int cellWidth = 2 * (width / 3);
            int cellHeight = height;
            var index = 0;

            using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
            {
                using (var graphics = Graphics.FromImage(img))
                {
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphics.CompositingMode = CompositingMode.SourceCopy;

                    for (var row = 0; row < rows; row++)
                    {
                        for (var col = 0; col < cols; col++)
                        {
                            var x = col * (cellWidth / 2);
                            var y = row * cellHeight;

                            if (files.Count > index)
                            {
                                using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true))
                                {
                                    using (var memoryStream = new MemoryStream())
                                    {
                                        fileStream.CopyTo(memoryStream);

                                        memoryStream.Position = 0;

                                        using (var imgtemp = Image.FromStream(memoryStream, true, false))
                                        {
                                            graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight);
                                        }
                                    }
                                }
                            }

                            index++;
                        }
                    }
                    img.Save(file);
                }
            }
        }
Example #4
0
        public async Task <SyncedFileInfo> SendFile(Stream stream, string[] remotePath, SyncTarget target, IProgress <double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(remotePath, target);

            _fileSystem.CreateDirectory(Path.GetDirectoryName(fullPath));

            _logger.Debug("Folder sync saving stream to {0}", fullPath);

            using (var fileStream = _fileSystem.GetFileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
            {
                await stream.CopyToAsync(fileStream).ConfigureAwait(false);

                return(GetSyncedFileInfo(fullPath));
            }
        }
Example #5
0
        public async Task <SyncedFileInfo> SendFile(SyncJob syncJob, string originalMediaPath, Stream inputStream, bool isMedia, string[] outputPathParts, SyncTarget target, IProgress <double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(outputPathParts, target);

            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fullPath));

            _logger.Debug("Folder sync saving stream to {0}", fullPath);

            using (var fileStream = _fileSystem.GetFileStream(fullPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
            {
                await inputStream.CopyToAsync(fileStream).ConfigureAwait(false);

                return(GetSyncedFileInfo(fullPath));
            }
        }
Example #6
0
        private async Task <SyncedFileInfo> SendFile(IServerSyncProvider provider, string inputPath, string[] pathParts, SyncTarget target, SyncOptions options, IProgress <double> progress, CancellationToken cancellationToken)
        {
            _logger.Debug("Sending {0} to {1}. Remote path: {2}", inputPath, provider.Name, string.Join("/", pathParts));
            using (var fileStream = _fileSystem.GetFileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
            {
                Stream stream = fileStream;

                if (options.UploadSpeedLimitBytes > 0 && provider is IRemoteSyncProvider)
                {
                    stream = new ThrottledStream(stream, options.UploadSpeedLimitBytes);
                }

                return(await provider.SendFile(stream, pathParts, target, progress, cancellationToken).ConfigureAwait(false));
            }
        }
Example #7
0
        private async Task <Stream> GetSubtitleStream(string path, bool requiresCharset)
        {
            if (requiresCharset)
            {
                var charset = GetSubtitleFileCharacterSet(path);

                if (!string.IsNullOrEmpty(charset))
                {
                    using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
                    {
                        using (var reader = new StreamReader(fs, GetEncoding(charset)))
                        {
                            var text = await reader.ReadToEndAsync().ConfigureAwait(false);

                            var bytes = Encoding.UTF8.GetBytes(text);

                            return(new MemoryStream(bytes));
                        }
                    }
                }
            }

            return(File.OpenRead(path));
        }
        private int ExtractEpisodes(string xmlFile)
        {
            using (
                var element = _fileSystem.GetFileStream(xmlFile, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
            {
                var el = XElement.Load(element);

                return(el.Descendants("Episode")
                       .Where(
                           x =>
                           DateTime.Now.Date >=
                           Convert.ToDateTime(StringToDateTime(x.Descendants("FirstAired").FirstOrDefault()?.Value)))
                       .Sum(x => x.Descendants("SeasonNumber").Count(y => y.Value != "0")));
            }
        }
Example #9
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.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 = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                    {
                        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 #10
0
        /// <summary>
        /// Try and determine if a file is locked
        /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
        private bool IsFileLocked(string path)
        {
            try
            {
                var data = _fileSystem.GetFileSystemInfo(path);

                if (!data.Exists ||
                    data.Attributes.HasFlag(FileAttributes.Directory) ||
                    data.Attributes.HasFlag(FileAttributes.ReadOnly))
                {
                    return(false);
                }
            }
            catch (IOException)
            {
                return(false);
            }

            try
            {
                using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    //file is not locked
                    return(false);
                }
            }
            catch (DirectoryNotFoundException)
            {
                return(false);
            }
            catch (FileNotFoundException)
            {
                return(false);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                Logger.Debug("{0} is locked.", path);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #11
0
        public Dvd(string path, IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
            Titles      = new List <Title>();
            var allFiles = _fileSystem.GetFiles(path, true).ToList();

            var vmgPath = allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.IFO", StringComparison.OrdinalIgnoreCase)) ??
                          allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.BUP", StringComparison.OrdinalIgnoreCase));

            if (vmgPath == null)
            {
                foreach (var ifo in allFiles)
                {
                    if (!string.Equals(ifo.Extension, ".ifo", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var nums = ifo.Name.Split(new [] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (nums.Length >= 2 && ushort.TryParse(nums[1], out var ifoNumber))
                    {
                        ReadVTS(ifoNumber, ifo.FullName);
                    }
                }
            }
            else
            {
                using (var vmgFs = _fileSystem.GetFileStream(vmgPath.FullName, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
                {
                    using (var vmgRead = new BigEndianBinaryReader(vmgFs))
                    {
                        vmgFs.Seek(0x3E, SeekOrigin.Begin);
                        _titleSetCount = vmgRead.ReadUInt16();

                        // read address of TT_SRPT
                        vmgFs.Seek(0xC4, SeekOrigin.Begin);
                        uint ttSectorPtr = vmgRead.ReadUInt32();
                        vmgFs.Seek(ttSectorPtr * 2048, SeekOrigin.Begin);
                        ReadTT_SRPT(vmgRead);
                    }
                }

                for (ushort titleSetNum = 1; titleSetNum <= _titleSetCount; titleSetNum++)
                {
                    ReadVTS(titleSetNum, allFiles);
                }
            }
        }
Example #12
0
        public Dvd(string path, IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
            Titles      = new List <Title>();
            var allFiles = _fileSystem.GetFiles(path, true).ToList();

            var vmgPath = allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.IFO", StringComparison.OrdinalIgnoreCase)) ??
                          allFiles.FirstOrDefault(i => string.Equals(i.Name, "VIDEO_TS.BUP", StringComparison.OrdinalIgnoreCase));

            if (vmgPath == null)
            {
                var allIfos = allFiles.Where(i => string.Equals(i.Extension, ".ifo", StringComparison.OrdinalIgnoreCase));

                foreach (var ifo in allIfos)
                {
                    var num         = ifo.Name.Split('_').ElementAtOrDefault(1);
                    var numbersRead = new List <ushort>();

                    if (!string.IsNullOrEmpty(num) && ushort.TryParse(num, out var ifoNumber) && !numbersRead.Contains(ifoNumber))
                    {
                        ReadVTS(ifoNumber, ifo.FullName);
                        numbersRead.Add(ifoNumber);
                    }
                }
            }
            else
            {
                using (var vmgFs = _fileSystem.GetFileStream(vmgPath.FullName, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
                {
                    using (var vmgRead = new BigEndianBinaryReader(vmgFs))
                    {
                        vmgFs.Seek(0x3E, SeekOrigin.Begin);
                        _titleSetCount = vmgRead.ReadUInt16();

                        // read address of TT_SRPT
                        vmgFs.Seek(0xC4, SeekOrigin.Begin);
                        uint ttSectorPtr = vmgRead.ReadUInt32();
                        vmgFs.Seek(ttSectorPtr * 2048, SeekOrigin.Begin);
                        ReadTT_SRPT(vmgRead);
                    }
                }

                for (ushort titleSetNum = 1; titleSetNum <= _titleSetCount; titleSetNum++)
                {
                    ReadVTS(titleSetNum, allFiles);
                }
            }
        }
Example #13
0
        internal async Task DownloadGameInfo(string gamesDbId, CancellationToken cancellationToken)
        {
            var url = string.Format(TgdbUrls.GetInfo, gamesDbId);

            var xmlPath = GetCacheFilePath(gamesDbId);

            using (var stream = await _httpClient.Get(url, Plugin.Instance.TgdbSemiphore, cancellationToken).ConfigureAwait(false))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));

                using (var fileStream = _fileSystem.GetFileStream(xmlPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                {
                    await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                }
            }
        }
Example #14
0
        internal async Task DownloadIssueInfo(string volumeId, string issueNumber, CancellationToken cancellationToken)
        {
            var url = string.Format(IssueSearchUrl, ApiKey, issueNumber, volumeId);

            var xmlPath = GetCacheFilePath(volumeId, issueNumber);

            using (var stream = await _httpClient.Get(url, Plugin.Instance.ComicVineSemiphore, cancellationToken).ConfigureAwait(false))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));

                using (var fileStream = _fileSystem.GetFileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                {
                    await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                }
            }
        }
Example #15
0
        public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
        {
            var device         = GetDevice(deviceId, false);
            var uploadPathInfo = GetUploadPath(device);

            var path = uploadPathInfo.Item1;

            if (!string.IsNullOrWhiteSpace(file.Album))
            {
                path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
            }

            path = Path.Combine(path, file.Name);
            path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");

            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));

            await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);

            _libraryMonitor.ReportFileSystemChangeBeginning(path);

            try
            {
                using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
                {
                    await stream.CopyToAsync(fs).ConfigureAwait(false);
                }

                AddCameraUpload(deviceId, file);
            }
            finally
            {
                _libraryMonitor.ReportFileSystemChangeComplete(path, true);
            }

            if (CameraImageUploaded != null)
            {
                CameraImageUploaded?.Invoke(this, new GenericEventArgs <CameraImageUploadInfo>
                {
                    Argument = new CameraImageUploadInfo
                    {
                        Device   = device,
                        FileInfo = file
                    }
                });
            }
        }
Example #16
0
        /// <summary>
        /// Refreshes from provider.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="savedOptions">The saved options.</param>
        /// <param name="result">The result.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task RefreshFromProvider(IHasImages item, IDynamicImageProvider provider, MetadataOptions savedOptions, RefreshResult result, CancellationToken cancellationToken)
        {
            try
            {
                var images = provider.GetSupportedImages(item);

                foreach (var imageType in images)
                {
                    if (!item.HasImage(imageType) && savedOptions.IsEnabled(imageType))
                    {
                        _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);

                        var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);

                        if (response.HasImage)
                        {
                            if (!string.IsNullOrEmpty(response.Path))
                            {
                                var mimeType = "image/" + Path.GetExtension(response.Path).TrimStart('.').ToLower();

                                var stream = _fileSystem.GetFileStream(response.Path, FileMode.Open, FileAccess.Read, FileShare.Read, true);

                                await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                            }
                            else
                            {
                                var mimeType = "image/" + response.Format.ToString().ToLower();

                                await _providerManager.SaveImage(item, response.Stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                            }

                            result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                result.Status       = ProviderRefreshStatus.CompletedWithErrors;
                _logger.ErrorException("Error in {0}", ex, provider.Name);
            }
        }
Example #17
0
        public object Get(GetAppThemeImage request)
        {
            var info = _themeManager.GetImageImageInfo(request.App, request.Theme, request.Name);

            var cacheGuid = new Guid(info.CacheTag);

            TimeSpan?cacheDuration = null;

            if (!string.IsNullOrEmpty(request.CacheTag) && cacheGuid == new Guid(request.CacheTag))
            {
                cacheDuration = TimeSpan.FromDays(365);
            }

            var contentType = MimeTypes.GetMimeType(info.Path);

            return(ToCachedResult(cacheGuid, info.DateModified, cacheDuration, () => _fileSystem.GetFileStream(info.Path, FileMode.Open, FileAccess.Read, FileShare.Read), contentType));
        }
Example #18
0
        public async Task <SyncedFileInfo> SendFile(Stream stream, string[] remotePath, SyncTarget target, IProgress <double> progress, CancellationToken cancellationToken)
        {
            var fullPath = GetFullPath(remotePath, target);

            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
            using (var fileStream = _fileSystem.GetFileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
            {
                await stream.CopyToAsync(fileStream).ConfigureAwait(false);

                return(new SyncedFileInfo
                {
                    Path = fullPath,
                    Protocol = MediaProtocol.File,
                    Id = fullPath
                });
            }
        }
Example #19
0
        /// <summary>
        /// Serializes to file.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="file">The file.</param>
        /// <exception cref="ArgumentNullException">obj</exception>
        public void SerializeToFile(object obj, string file)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            if (string.IsNullOrEmpty(file))
            {
                throw new ArgumentNullException(nameof(file));
            }

            using (var stream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
            {
                SerializeToStream(obj, stream);
            }
        }
Example #20
0
        /// <summary>
        /// Saves the image to location.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="path">The path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
        {
            _logger.Debug("Saving image to {0}", path);

            var parentFolder = Path.GetDirectoryName(path);

            _libraryMonitor.ReportFileSystemChangeBeginning(path);
            _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);

            try
            {
                _fileSystem.CreateDirectory(Path.GetDirectoryName(path));

                // If the file is currently hidden we'll have to remove that or the save will fail
                var file = _fileSystem.GetFileInfo(path);

                // This will fail if the file is hidden
                if (file.Exists)
                {
                    if (file.IsHidden)
                    {
                        _fileSystem.SetHidden(file.FullName, false);
                    }
                    if (file.IsReadOnly)
                    {
                        _fileSystem.SetReadOnly(path, false);
                    }
                }

                using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                {
                    await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken)
                    .ConfigureAwait(false);
                }

                if (_config.Configuration.SaveMetadataHidden)
                {
                    _fileSystem.SetHidden(file.FullName, true);
                }
            }
            finally
            {
                _libraryMonitor.ReportFileSystemChangeComplete(path, false);
                _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
            }
        }
Example #21
0
        public async Task <DynamicImageResponse> GetImage(Audio item, List <MediaStream> imageStreams, CancellationToken cancellationToken)
        {
            var path = GetAudioImagePath(item);

            if (!_fileSystem.FileExists(path))
            {
                var semaphore = GetLock(path);

                // Acquire a lock
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    // Check again in case it was saved while waiting for the lock
                    if (!_fileSystem.FileExists(path))
                    {
                        _fileSystem.CreateDirectory(Path.GetDirectoryName(path));

                        var imageStream = imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("front", StringComparison.OrdinalIgnoreCase) != -1) ??
                                          imageStreams.FirstOrDefault(i => (i.Comment ?? string.Empty).IndexOf("cover", StringComparison.OrdinalIgnoreCase) != -1) ??
                                          imageStreams.FirstOrDefault();

                        var imageStreamIndex = imageStream == null ? (int?)null : imageStream.Index;

                        using (var stream = await _mediaEncoder.ExtractAudioImage(item.Path, imageStreamIndex, cancellationToken).ConfigureAwait(false))
                        {
                            using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                            {
                                await stream.CopyToAsync(fileStream).ConfigureAwait(false);
                            }
                        }
                    }
                }
                finally
                {
                    semaphore.Release();
                }
            }

            return(new DynamicImageResponse
            {
                HasImage = true,
                Path = path
            });
        }
Example #22
0
        /// <summary>
        /// Downloads the image.
        /// </summary>
        /// <param name="providerName">Name of the provider.</param>
        /// <param name="url">The URL.</param>
        /// <param name="urlHash">The URL hash.</param>
        /// <param name="pointerCachePath">The pointer cache path.</param>
        /// <returns>Task.</returns>
        private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath)
        {
            var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);

            var ext = result.ContentType.Split('/').Last();

            var fullCachePath = GetFullCachePath(urlHash + "." + ext);

            Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
            using (var stream = result.Content)
                using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                {
                    await stream.CopyToAsync(filestream).ConfigureAwait(false);
                }

            Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
            File.WriteAllText(pointerCachePath, fullCachePath);
        }
Example #23
0
        private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
        {
            if (File.Exists(responseCachePath) &&
                _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
            {
                var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);

                return(new HttpResponseInfo
                {
                    ResponseUrl = url,
                    Content = stream,
                    StatusCode = HttpStatusCode.OK,
                    ContentLength = stream.Length
                });
            }

            return(null);
        }
Example #24
0
        /// <summary>
        /// Writes the font config file.
        /// </summary>
        /// <param name="fontsDirectory">The fonts directory.</param>
        /// <returns>Task.</returns>
        private async Task WriteFontConfigFile(string fontsDirectory)
        {
            const string fontConfigFilename = "fonts.conf";
            var          fontConfigFile     = Path.Combine(fontsDirectory, fontConfigFilename);

            if (!_fileSystem.FileExists(fontConfigFile))
            {
                var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);

                var bytes = Encoding.UTF8.GetBytes(contents);

                using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
                                                                  FileShare.Read, true))
                {
                    await fileStream.WriteAsync(bytes, 0, bytes.Length);
                }
            }
        }
Example #25
0
        public async Task LoadAll()
        {
            const string ratingsResource = "Emby.Server.Implementations.Localization.Ratings.";

            Directory.CreateDirectory(LocalizationPath);

            var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName);

            // Extract from the assembly
            foreach (var resource in _assembly.GetManifestResourceNames())
            {
                if (!resource.StartsWith(ratingsResource))
                {
                    continue;
                }

                string filename = "ratings-" + resource.Substring(ratingsResource.Length);

                if (existingFiles.Contains(filename))
                {
                    continue;
                }

                using (var stream = _assembly.GetManifestResourceStream(resource))
                {
                    string target = Path.Combine(LocalizationPath, filename);
                    _logger.LogInformation("Extracting ratings to {0}", target);

                    using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
                    {
                        await stream.CopyToAsync(fs);
                    }
                }
            }

            foreach (var file in GetRatingsFiles(LocalizationPath))
            {
                await LoadRatings(file);
            }

            LoadAdditionalRatings();

            await LoadCultures();
        }
Example #26
0
        public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
        {
            var device = GetDevice(deviceId);
            var path   = GetUploadPath(device);

            if (!string.IsNullOrWhiteSpace(file.Album))
            {
                path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
            }

            path = Path.Combine(path, file.Name);
            path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");

            _libraryMonitor.ReportFileSystemChangeBeginning(path);

            _fileSystem.CreateDirectory(Path.GetDirectoryName(path));

            try
            {
                using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    await stream.CopyToAsync(fs).ConfigureAwait(false);
                }

                _repo.AddCameraUpload(deviceId, file);
            }
            finally
            {
                _libraryMonitor.ReportFileSystemChangeComplete(path, true);
            }

            if (CameraImageUploaded != null)
            {
                EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs <CameraImageUploadInfo>
                {
                    Argument = new CameraImageUploadInfo
                    {
                        Device   = device,
                        FileInfo = file
                    }
                }, _logger);
            }
        }
Example #27
0
        private void ExtractAll()
        {
            var type         = GetType();
            var resourcePath = type.Namespace + ".Ratings.";

            var localizationPath = LocalizationPath;

            _fileSystem.CreateDirectory(localizationPath);

            var existingFiles = GetRatingsFiles(localizationPath)
                                .Select(Path.GetFileName)
                                .ToList();

            // Extract from the assembly
            foreach (var resource in _assemblyInfo
                     .GetManifestResourceNames(type)
                     .Where(i => i.StartsWith(resourcePath)))
            {
                var filename = "ratings-" + resource.Substring(resourcePath.Length);

                if (!existingFiles.Contains(filename))
                {
                    using (var stream = _assemblyInfo.GetManifestResourceStream(type, resource))
                    {
                        var target = Path.Combine(localizationPath, filename);
                        _logger.LogInformation("Extracting ratings to {0}", target);

                        using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
                        {
                            stream.CopyTo(fs);
                        }
                    }
                }
            }

            foreach (var file in GetRatingsFiles(localizationPath))
            {
                LoadRatings(file);
            }

            LoadAdditionalRatings();
        }
Example #28
0
        private async Task TrySaveToFiles(Stream stream, List <string> savePaths)
        {
            Exception exceptionToThrow = null;

            foreach (var savePath in savePaths)
            {
                _logger.LogInformation("Saving subtitles to {0}", savePath);

                _monitor.ReportFileSystemChangeBeginning(savePath);

                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));

                    using (var fs = _fileSystem.GetFileStream(savePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                    {
                        await stream.CopyToAsync(fs).ConfigureAwait(false);
                    }

                    return;
                }
                catch (Exception ex)
                {
                    if (exceptionToThrow == null)
                    {
                        exceptionToThrow = ex;
                    }
                }
                finally
                {
                    _monitor.ReportFileSystemChangeComplete(savePath, false);
                }

                stream.Position = 0;
            }

            if (exceptionToThrow != null)
            {
                throw exceptionToThrow;
            }
        }
Example #29
0
        public static async Task <string> GetHash(string path, CancellationToken cancellationToken, IFileSystem fileSystem, ILogger logger)
        {
            var buffer = new byte[10485760];

            logger.Info($"Reading {path}");

            using (var stream = fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
            {
                await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
            }

            string hash;

            using (var md5 = MD5.Create())
            {
                hash = ToHex(md5.ComputeHash(buffer));
            }

            logger.Info($"Computed hash {hash} of {path} for NapiSub");
            return(hash);
        }
Example #30
0
        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static ImageSize GetDimensions(string path, ILogger logger, IFileSystem fileSystem)
        {
            try
            {
                using (var fs = File.OpenRead(path))
                {
                    using (var binaryReader = new BinaryReader(fs))
                    {
                        return(GetDimensions(binaryReader));
                    }
                }
            }
            catch
            {
                logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
            }

            // Buffer to memory stream to avoid image locking file
            using (var fs = fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var memoryStream = new MemoryStream())
                {
                    fs.CopyTo(memoryStream);

                    memoryStream.Position = 0;

                    // Co it the old fashioned way
                    using (var b = System.Drawing.Image.FromStream(memoryStream, true, false))
                    {
                        var size = b.Size;

                        return(new ImageSize
                        {
                            Width = size.Width,
                            Height = size.Height
                        });
                    }
                }
            }
        }
Example #31
0
        private void ExtractAll()
        {
            var type         = GetType();
            var resourcePath = type.Namespace + ".Ratings.";

            var localizationPath = LocalizationPath;

            _fileSystem.CreateDirectory(localizationPath);

            var existingFiles = Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly)
                                .Select(Path.GetFileName)
                                .ToList();

            // Extract from the assembly
            foreach (var resource in type.Assembly
                     .GetManifestResourceNames()
                     .Where(i => i.StartsWith(resourcePath)))
            {
                var filename = "ratings-" + resource.Substring(resourcePath.Length);

                if (!existingFiles.Contains(filename))
                {
                    using (var stream = type.Assembly.GetManifestResourceStream(resource))
                    {
                        var target = Path.Combine(localizationPath, filename);
                        _logger.Info("Extracting ratings to {0}", target);

                        using (var fs = _fileSystem.GetFileStream(target, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            stream.CopyTo(fs);
                        }
                    }
                }
            }

            foreach (var file in Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly))
            {
                LoadRatings(file);
            }
        }
Example #32
0
        /// <summary>
        /// Gets the log lines.
        /// </summary>
        /// <param name="logFilePath">The log file path.</param>
        /// <param name="startLine">The start line.</param>
        /// <returns>Task{IEnumerable{System.String}}.</returns>
        internal static async Task <List <string> > GetLogLines(string logFilePath, int startLine, IFileSystem fileSystem)
        {
            var lines = new List <string>();

            using (var fs = fileSystem.GetFileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
            {
                using (var reader = new StreamReader(fs))
                {
                    while (!reader.EndOfStream)
                    {
                        lines.Add(await reader.ReadLineAsync().ConfigureAwait(false));
                    }
                }
            }

            if (startLine > 0)
            {
                lines = lines.Skip(startLine).ToList();
            }

            return(lines);
        }
Example #33
0
        internal async Task DownloadInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var url = AudioDbArtistProvider.BaseUrl + "/album-mb.php?i=" + musicBrainzReleaseGroupId;

            var path = GetAlbumInfoPath(_config.ApplicationPaths, musicBrainzReleaseGroupId);

            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));

            using (var response = await _httpClient.Get(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken
            }).ConfigureAwait(false))
            {
                using (var xmlFileStream = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
                {
                    await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
                }
            }
        }
Example #34
0
 private static Task<Stream> GetSingleImage(List<string> files, IFileSystem fileSystem)
 {
     return Task.FromResult<Stream>(fileSystem.GetFileStream(files[0], FileMode.Open, FileAccess.Read, FileShare.Read));
 }
Example #35
0
        private static async Task<Image> GetImage(string file, IFileSystem fileSystem)
        {
            using (var fileStream = fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true))
            {
                var memoryStream = new MemoryStream();

                await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);

                memoryStream.Position = 0;

                return Image.FromStream(memoryStream, true, false);
            }
        }