public static XElement UploadDocument(IMediaFile media)
		{
			var data = IssuuApi.NewQuery("issuu.document.upload");
			data.Add("name", media.GetName());
			data.Add("title", media.Title);
			IssuuApi.Sign(data);

			var document = GetDocument(WebRequestFacade.UploadFileEx("http://upload.issuu.com/1_0", media.GetReadStream(), media.GetOrgName(), "file", data));
			document.SetAttributeValue("publishing", "true");
			return document;
		}
示例#2
0
        /// <summary>
        /// Thanks to C1 ImageResizer.cs.
        /// </summary>
        /// <returns></returns>
        private Size GetImageSizeFromCacheOrFile(IMediaFile mediaFile)
        {
            string imageKey          = mediaFile.CompositePath;
            string imageSizeCacheKey = "ShowMedia.ashx image size " + imageKey;
            var    imageSize         = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?;

            if (imageSize == null)
            {
                using (Stream fileStream = mediaFile.GetReadStream())
                {
                    Size calculatedSize;
                    if (!ImageSizeReader.TryGetSize(fileStream, out calculatedSize))
                    {
                        using (Stream manualFileStream = mediaFile.GetReadStream())
                        {
                            using (var bitmap = new Bitmap(manualFileStream))
                            {
                                calculatedSize = new Size {
                                    Width = bitmap.Width, Height = bitmap.Height
                                };
                            }
                        }
                    }

                    imageSize = calculatedSize;

                    bool isNativeProvider = mediaFile is FileSystemFileBase;

                    // We can provider cache dependency only for the native media provider
                    CacheDependency cacheDependency = isNativeProvider
                                                ? new CacheDependency((mediaFile as FileSystemFileBase).SystemPath)
                                                : null;

                    HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan,
                                          CacheItemPriority.Normal, null);
                }
            }

            return(imageSize.Value);
        }
        private void UpdateMediaFile(IMediaFile updatedFile)
        {
            Guid id = updatedFile.Id;

            IMediaFileData currentFileData = DataFacade.GetData <IMediaFileData>(x => x.Id == id).First();

            if (updatedFile.FolderPath != currentFileData.FolderPath || updatedFile.FileName != currentFileData.FileName)
            {
                ValidateMediaFileData(updatedFile);
            }
            CopyFileData(updatedFile, currentFileData);
            currentFileData.LastWriteTime = DateTime.Now;
            using (Stream stream = updatedFile.GetReadStream())
            {
                currentFileData.Length = (int)stream.Length;
            }
            TransactionFileSystemFileStreamManager.WriteFileToDisk(updatedFile);
            DataFacade.Update(currentFileData);
        }
        public List <T> AddNew <T>(IEnumerable <T> datas) where T : class, IData
        {
            List <T> result = new List <T>();

            foreach (IData data in datas)
            {
                if (data == null)
                {
                    throw new ArgumentException("Data in list to add must be non-null");
                }
                CheckInterface(typeof(T));
            }

            foreach (IData data in datas)
            {
                if (typeof(T) == typeof(IMediaFile))
                {
                    IMediaFile file     = (IMediaFile)data;
                    string     fullPath = Path.Combine(Path.Combine(_rootDir, file.FolderPath.Remove(0, 1)), file.FileName);

                    using (Stream readStream = file.GetReadStream())
                    {
                        using (Stream writeStream = C1File.Open(fullPath, FileMode.CreateNew))
                        {
                            readStream.CopyTo(writeStream);
                        }
                    }

                    result.Add(CreateFile(fullPath) as T);
                }
                else if (typeof(T) == typeof(IMediaFileFolder))
                {
                    IMediaFileFolder folder   = (IMediaFileFolder)data;
                    string           fullPath = Path.Combine(_rootDir, folder.Path.Remove(0, 1));

                    C1Directory.CreateDirectory(fullPath);
                    result.Add(CreateFolder(fullPath) as T);
                }
            }
            return(result);
        }
        private IMediaFile AddMediaFile(IMediaFile mediaFile)
        {
            ValidateMediaFileData(mediaFile);

            IMediaFileData fileData = DataFacade.BuildNew <IMediaFileData>();

            fileData.Id = Guid.NewGuid();
            CopyFileData(mediaFile, fileData);

            fileData.LastWriteTime = fileData.CreationTime = DateTime.Now;

            IMediaFile internalMediaFile;

            using (Stream readStream = mediaFile.GetReadStream())
            {
                Verify.IsNotNull(readStream, "GetReadStream returned null for type '{0}'", mediaFile.GetType());
                fileData.Length = (int)readStream.Length;

                string internalPath = Path.Combine(_workingDirectory, fileData.Id.ToString());
                internalMediaFile = new MediaFile(fileData, Store.Id, _context.CreateDataSourceId(
                                                      new MediaDataId
                {
                    MediaType = MediaElementType.File,
                    Id        = fileData.Id
                },
                                                      typeof(IMediaFile)), internalPath);

                using (Stream writeStream = internalMediaFile.GetNewWriteStream())
                {
                    readStream.CopyTo(writeStream);
                }
            }
            TransactionFileSystemFileStreamManager.WriteFileToDisk(internalMediaFile);
            fileData = DataFacade.AddNew <IMediaFileData>(fileData);

            return(internalMediaFile);
        }
        public void Update(IEnumerable <IData> datas)
        {
            foreach (IData data in datas)
            {
                if (data == null)
                {
                    throw new ArgumentException("Data in list to update must be non-null");
                }
            }

            foreach (IData data in datas)
            {
                MediaDataId dataId = data.DataSourceId.DataId as MediaDataId;
                if (dataId == null)
                {
                    throw new ArgumentException("Invalid IData");
                }

                if (dataId.MediaType == _fileType)
                {
                    IMediaFile updatedFile = (IMediaFile)data;

                    if (updatedFile.StoreId != this.Store.Id)
                    {
                        continue;
                    }
                    if (updatedFile.IsReadOnly)
                    {
                        throw new ArgumentException("Cannot update read only media file " + dataId.FileName);
                    }

                    if (updatedFile.FileName != dataId.FileName || updatedFile.FolderPath != dataId.Path)
                    {
                        string oldPos = GetAbsolutePath(dataId);
                        string newPos = GetAbsolutePath(updatedFile);
                        C1File.Move(oldPos, newPos);
                    }

                    using (Stream readStream = updatedFile.GetReadStream())
                    {
                        using (Stream writeStream = C1File.Open(GetAbsolutePath(updatedFile), FileMode.Create))
                        {
                            readStream.CopyTo(writeStream);
                        }
                    }
                }
                else
                {
                    IMediaFileFolder updatedFolder = (IMediaFileFolder)data;
                    if (updatedFolder.StoreId != this.Store.Id)
                    {
                        continue;
                    }
                    if (updatedFolder.IsReadOnly)
                    {
                        throw new ArgumentException("Cannot update read only media folder " + dataId.Path);
                    }
                    C1Directory.Move(GetAbsolutePath(dataId), GetAbsolutePath(updatedFolder));
                }
            }
        }
示例#7
0
        /// <summary>
        /// Gets the resized image.
        /// </summary>
        /// <param name="httpServerUtility">An instance of <see cref="System.Web.HttpServerUtility" />.</param>
        /// <param name="file">The media file.</param>
        /// <param name="resizingOptions">The resizing options.</param>
        /// <param name="targetImageFormat">The target image format.</param>
        /// <returns>A full file path to a resized image; null if there's no need to resize the image</returns>
        public static string GetResizedImage(HttpServerUtility httpServerUtility, IMediaFile file, ResizingOptions resizingOptions, ImageFormat targetImageFormat)
        {
            Verify.ArgumentNotNull(file, "file");
            Verify.That(ImageFormatIsSupported(targetImageFormat), "Unsupported image format '{0}'", targetImageFormat);

            if (_resizedImagesDirectoryPath == null)
            {
                _resizedImagesDirectoryPath = httpServerUtility.MapPath(ResizedImagesCacheDirectory);

                if (!C1Directory.Exists(_resizedImagesDirectoryPath))
                {
                    C1Directory.CreateDirectory(_resizedImagesDirectoryPath);
                }
            }

            string imageKey = file.CompositePath;

            bool isNativeProvider = file is FileSystemFileBase;

            string imageSizeCacheKey = "ShowMedia.ashx image size " + imageKey;
            Size? imageSize = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?;

            Bitmap bitmap = null;
            Stream fileStream = null;
            try
            {
                if (imageSize == null)
                {
                    fileStream = file.GetReadStream();

                    Size calculatedSize;
                    if (!ImageSizeReader.TryGetSize(fileStream, out calculatedSize))
                    {
                        fileStream.Dispose();
                        fileStream = file.GetReadStream();

                        bitmap = new Bitmap(fileStream);
                        calculatedSize = new Size { Width = bitmap.Width, Height = bitmap.Height };
                    }
                    imageSize = calculatedSize;

                    // We can provider cache dependency only for the native media provider
                    var cacheDependency = isNativeProvider ? new CacheDependency((file as FileSystemFileBase).SystemPath) : null;

                    HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan, CacheItemPriority.Normal, null);
                }

                int newWidth, newHeight;
                bool centerCrop;
                bool needToResize = CalculateSize(imageSize.Value.Width, imageSize.Value.Height, resizingOptions, out newWidth, out newHeight, out centerCrop);

                needToResize = needToResize || resizingOptions.CustomQuality;

                if (!needToResize)
                {
                    return null;
                }

                int filePathHash = imageKey.GetHashCode();

                string centerCroppedString = centerCrop ? "c" : string.Empty;

                string fileExtension = _ImageFormat2Extension[targetImageFormat];
                string resizedImageFileName = string.Format("{0}x{1}_{2}{3}_{4}.{5}", newWidth, newHeight, filePathHash, centerCroppedString, resizingOptions.Quality, fileExtension);

                string imageFullPath = Path.Combine(_resizedImagesDirectoryPath, resizedImageFileName);

                if (!C1File.Exists(imageFullPath) || C1File.GetLastWriteTime(imageFullPath) != file.LastWriteTime)
                {
                    if (bitmap == null)
                    {
                        fileStream = file.GetReadStream();
                        bitmap = new Bitmap(fileStream);
                    }

                    ResizeImage(bitmap, imageFullPath, newWidth, newHeight, centerCrop, targetImageFormat, resizingOptions.Quality);

                    if (file.LastWriteTime.HasValue)
                    {
                        C1File.SetLastWriteTime(imageFullPath, file.LastWriteTime.Value);
                    }
                }

                return imageFullPath;
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }

                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }
        }
        private string GetTextToIndex(IMediaFile mediaFile)
        {
            var mimeType = MimeTypeInfo.GetCanonical(mediaFile.MimeType);

            if (!IsIndexableMimeType(mimeType))
            {
                return(null);
            }

            // Checking if the parsing results are preserved in the cache
            var outputFilePath = GetTextOutputFilePath(mediaFile);
            var lastWriteTime  = mediaFile.LastWriteTime ?? mediaFile.CreationTime;

            if (File.Exists(outputFilePath) &&
                lastWriteTime != null &&
                File.GetCreationTime(outputFilePath) == lastWriteTime)
            {
                return(File.ReadAllText(outputFilePath));
            }

            string extension;

            try
            {
                var fileName = mediaFile.FileName;
                foreach (var ch in Path.GetInvalidFileNameChars())
                {
                    fileName = fileName.Replace(ch, '_');
                }
                extension = Path.GetExtension(fileName);
            }
            catch (ArgumentException)
            {
                Log.LogWarning(LogTitle, $"Failed to extract extension from file: '{mediaFile.FileName}', mime type: '{mediaFile.MimeType}' ");
                return(null);
            }

            if (string.IsNullOrEmpty(extension))
            {
                extension = MimeTypeInfo.GetExtensionFromMimeType(mediaFile.MimeType);
            }

            if (string.IsNullOrEmpty(extension))
            {
                Log.LogWarning(LogTitle, $"Failed to extract extension from file: '{mediaFile.FileName}', mime type: '{mediaFile.MimeType}' ");
                return(null);
            }

            // Saving the file to a temp directory
            var tempSourceFile = GetTempFileName(extension);

            try
            {
                using (var mediaStream = mediaFile.GetReadStream())
                    using (var file = File.Create(tempSourceFile))
                    {
                        mediaStream.CopyTo(file);
                    }
            }
            catch (FileNotFoundException)
            {
                if (Interlocked.Increment(ref _missingFilesLogged) <= MaxMissingFilesLogMessages)
                {
                    Log.LogWarning(LogTitle, $"Missing an underlying content file for the media file '{mediaFile.KeyPath}'");
                }
                return(null);
            }

            var exePath          = PathUtil.Resolve(IFilterExecutableRelativePath);
            var workingDirectory = Path.GetDirectoryName(exePath);

            string stdout, stderr;
            int    exitCode;

            using (var process = new Process
            {
                StartInfo =
                {
                    WorkingDirectory       = workingDirectory,
                    FileName               = "\"" + exePath + "\"",
                    Arguments              = $"\"{tempSourceFile}\" \"{outputFilePath}\"",
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    CreateNoWindow         = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    UseShellExecute        = false,
                    WindowStyle            = ProcessWindowStyle.Hidden
                }
            })
            {
                process.Start();

                stdout = process.StandardOutput.ReadToEnd();
                stderr = process.StandardError.ReadToEnd();

                process.WaitForExit();

                exitCode = process.ExitCode;
            }

            C1File.Delete(tempSourceFile);

            if (exitCode != 0)
            {
                var msg = $"Failed to parse the content of the media file '{Path.GetFileName(mediaFile.FileName)}'.";

                if ((uint)exitCode == 0x80004005 /*E_FAIL*/)
                {
                    Log.LogVerbose(LogTitle, msg + " Unspecified error.");
                    return(null);
                }

                if ((uint)exitCode == 0x80004002 /*E_NOINTERFACE*/)
                {
                    Log.LogWarning(LogTitle, msg + " IFilter not found for the given file extension.");
                    return(null);
                }

                Log.LogWarning(LogTitle,
                               msg +
                               $"\r\nExit Code: {exitCode}\r\nOutput: {stdout}"
                               + (!string.IsNullOrEmpty(stderr) ? $"\r\nError: {stderr}" : ""));
                return(null);
            }

            if (!File.Exists(outputFilePath))
            {
                return(null);
            }

            if (lastWriteTime != null)
            {
                File.SetLastWriteTime(outputFilePath, lastWriteTime.Value);
            }

            return(File.ReadAllText(outputFilePath));
        }
        private string GetTextToIndex(IMediaFile mediaFile)
        {
            var mimeType = MimeTypeInfo.GetCanonical(mediaFile.MimeType);

            if (!IsIndexableMimeType(mimeType))
            {
                return(null);
            }

            // Checking if the parsing results are preserved in the cache
            var outputFilePath = GetTextOutputFilePath(mediaFile);
            var lastWriteTime  = mediaFile.LastWriteTime ?? mediaFile.CreationTime;

            if (File.Exists(outputFilePath) &&
                lastWriteTime != null &&
                File.GetCreationTime(outputFilePath) == lastWriteTime)
            {
                string text = File.ReadAllText(outputFilePath);
                if (!string.IsNullOrEmpty(text))
                {
                    return(text);
                }
            }

            string extension = GetExtension(mediaFile);

            if (string.IsNullOrEmpty(extension))
            {
                Log.LogWarning(LogTitle, $"Failed to extract extension from file: '{mediaFile.FileName}', mime type: '{mediaFile.MimeType}' ");
                return(null);
            }

            // Saving the file to a temp directory
            var tempSourceFile = GetTempFileName(extension);

            try
            {
                using (var mediaStream = mediaFile.GetReadStream())
                    using (var file = File.Create(tempSourceFile))
                    {
                        mediaStream.CopyTo(file);
                    }
            }
            catch (FileNotFoundException)
            {
                if (Interlocked.Increment(ref _missingFilesLogged) <= MaxMissingFilesLogMessages)
                {
                    Log.LogWarning(LogTitle, $"Missing an underlying content file for the media file '{mediaFile.KeyPath}'");
                }
                return(null);
            }

            bool success = ExtractText(tempSourceFile, outputFilePath, mediaFile);

            C1File.Delete(tempSourceFile);

            if (!success)
            {
                return(null);
            }

            if (lastWriteTime != null)
            {
                File.SetLastWriteTime(outputFilePath, lastWriteTime.Value);
            }

            var result = File.ReadAllText(outputFilePath);

            if (result.Length == 0)
            {
                Log.LogWarning(LogTitle, $"Failed to extract text from media file '{mediaFile.FileName}', mime type: '{mediaFile.MimeType}', extension '{extension}'");
            }

            return(result);
        }
示例#10
0
        public static XElement UploadDocument(IMediaFile media)
        {
            var data = IssuuApi.NewQuery("issuu.document.upload");

            data.Add("name", media.GetName());
            data.Add("title", media.Title);
            IssuuApi.Sign(data);

            var document = GetDocument(WebRequestFacade.UploadFileEx("http://upload.issuu.com/1_0", media.GetReadStream(), media.GetOrgName(), "file", data));

            document.SetAttributeValue("publishing", "true");
            return(document);
        }
        /// <summary>
        /// Gets the resized image.
        /// </summary>
        /// <param name="httpServerUtility">An instance of <see cref="System.Web.HttpServerUtility" />.</param>
        /// <param name="file">The media file.</param>
        /// <param name="resizingOptions">The resizing options.</param>
        /// <param name="targetImageFormat">The target image format.</param>
        /// <returns>A full file path to a resized image; null if there's no need to resize the image</returns>
        public static string GetResizedImage(HttpServerUtility httpServerUtility, IMediaFile file, ResizingOptions resizingOptions, ImageFormat targetImageFormat)
        {
            Verify.ArgumentNotNull(file, "file");
            Verify.That(ImageFormatIsSupported(targetImageFormat), "Unsupported image format '{0}'", targetImageFormat);

            if (_resizedImagesDirectoryPath == null)
            {
                _resizedImagesDirectoryPath = httpServerUtility.MapPath(ResizedImagesCacheDirectory);

                if (!C1Directory.Exists(_resizedImagesDirectoryPath))
                {
                    C1Directory.CreateDirectory(_resizedImagesDirectoryPath);
                }
            }

            string imageKey = file.CompositePath;

            bool isNativeProvider = file is FileSystemFileBase;

            string imageSizeCacheKey = "ShowMedia.ashx image size " + imageKey;
            Size?  imageSize         = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?;

            Bitmap bitmap     = null;
            Stream fileStream = null;

            try
            {
                if (imageSize == null)
                {
                    fileStream = file.GetReadStream();

                    Size calculatedSize;
                    if (!ImageSizeReader.TryGetSize(fileStream, out calculatedSize))
                    {
                        fileStream.Dispose();
                        fileStream = file.GetReadStream();

                        bitmap         = new Bitmap(fileStream);
                        calculatedSize = new Size {
                            Width = bitmap.Width, Height = bitmap.Height
                        };
                    }
                    imageSize = calculatedSize;

                    // We can provider cache dependency only for the native media provider
                    var cacheDependency = isNativeProvider ? new CacheDependency((file as FileSystemFileBase).SystemPath) : null;

                    HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan, CacheItemPriority.Normal, null);
                }

                int  newWidth, newHeight;
                bool centerCrop;
                bool needToResize = CalculateSize(imageSize.Value.Width, imageSize.Value.Height, resizingOptions, out newWidth, out newHeight, out centerCrop);

                needToResize = needToResize || resizingOptions.CustomQuality;

                if (!needToResize)
                {
                    return(null);
                }

                int filePathHash = imageKey.GetHashCode();

                string centerCroppedString = centerCrop ? "c" : string.Empty;

                string fileExtension        = _ImageFormat2Extension[targetImageFormat];
                string resizedImageFileName = string.Format("{0}x{1}_{2}{3}_{4}.{5}", newWidth, newHeight, filePathHash, centerCroppedString, resizingOptions.Quality, fileExtension);

                string imageFullPath = Path.Combine(_resizedImagesDirectoryPath, resizedImageFileName);

                if (!C1File.Exists(imageFullPath) || C1File.GetLastWriteTime(imageFullPath) != file.LastWriteTime)
                {
                    if (bitmap == null)
                    {
                        fileStream = file.GetReadStream();
                        bitmap     = new Bitmap(fileStream);
                    }

                    ResizeImage(bitmap, imageFullPath, newWidth, newHeight, centerCrop, targetImageFormat, resizingOptions.Quality);

                    if (file.LastWriteTime.HasValue)
                    {
                        C1File.SetLastWriteTime(imageFullPath, file.LastWriteTime.Value);
                    }
                }

                return(imageFullPath);
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }

                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }
        }