/// <summary>
        /// Sets pathes for archive image.
        /// </summary>
        /// <param name="archivedImage">The archived image object.</param>
        /// <param name="folderName">The folder name.</param>
        /// <param name="fileName">The file name.</param>
        public void SetPathForArchive(MediaImage archivedImage, string folderName, string fileName)
        {
            archivedImage.FileUri = mediaFileService.GetFileUri(MediaType.Image, folderName, fileName);
            archivedImage.PublicUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, fileName);

            if (!archivedImage.IsEdited())
            {
                archivedImage.OriginalUri = mediaFileService.GetFileUri(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + fileName);
                archivedImage.PublicOriginallUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + fileName);
            }

            archivedImage.ThumbnailUri = mediaFileService.GetFileUri(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");
            archivedImage.PublicThumbnailUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");
        }
Пример #2
0
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            MediaFolder parentFolder = null;
            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable<MediaFolder>()
                    .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                    .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var maxLength = configuration.Storage.MaximumFileNameLength > 0 ? configuration.Storage.MaximumFileNameLength : 100;
            // Fix for IIS express + IE (if full path is returned)
            var fileName = Path.GetFileName(request.Data.FileName);
            if (fileName.Length > maxLength)
            {
                fileName = string.Concat(Path.GetFileNameWithoutExtension(fileName.Substring(0, maxLength)), Path.GetExtension(fileName));
            }

            var mediaImage = new MediaImage
            {
                Id = request.Data.Id.GetValueOrDefault(),
                Type = Module.MediaManager.Models.MediaType.Image,
                Caption = request.Data.Caption,
                Title = request.Data.Title ?? fileName,
                Description = request.Data.Description,
                Size = request.Data.FileStream.Length,
                Folder = parentFolder,
                OriginalFileName = fileName,
                OriginalFileExtension = Path.GetExtension(fileName)
            };

            var savedImage = mediaImageService.UploadImageWithStream(request.Data.FileStream, mediaImage, request.Data.WaitForUploadResult);

            if (savedImage != null)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedImage);
            }

            return new UploadImageResponse
            {
                Data = savedImage.Id,
            };
        }
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            MediaFolder parentFolder = null;
            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable<MediaFolder>()
                    .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                    .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var mediaImage = new MediaImage
            {
                Id = request.Data.Id.GetValueOrDefault(),
                Type = Module.MediaManager.Models.MediaType.Image,
                Caption = request.Data.Caption,
                Title = request.Data.Title ?? Path.GetFileName(request.Data.FileName),
                Description = request.Data.Description,
                Size = request.Data.FileStream.Length,
                Folder = parentFolder,
                OriginalFileName = request.Data.FileName,
                OriginalFileExtension = Path.GetExtension(request.Data.FileName)
            };

            var savedImage = mediaImageService.UploadImageWithStream(request.Data.FileStream, mediaImage, request.Data.WaitForUploadResult);

            if (savedImage != null)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedImage);
            }

            return new UploadImageResponse
            {
                Data = savedImage.Id,
            };
        }
        /// <summary>
        /// Sets pathes for new original image.
        /// </summary>
        /// <param name="newOriginalImage">The new original image object.</param>
        /// <param name="folderName">The folder name.</param>
        /// <param name="fileName">The file name.</param>
        /// <param name="archivedImageOriginalUri">The original Uri for archived image.</param>
        /// <param name="archivedImagePublicOriginalUrl">The public original Url for archived image.</param>
        public void SetPathForNewOriginal(MediaImage newOriginalImage, string folderName, string fileName, Uri archivedImageOriginalUri = null, string archivedImagePublicOriginalUrl = "")
        {
            newOriginalImage.FileUri = mediaFileService.GetFileUri(MediaType.Image, folderName, fileName);
            newOriginalImage.PublicUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, fileName);

            
            if (!newOriginalImage.IsEdited())
            {
                newOriginalImage.OriginalUri = mediaFileService.GetFileUri(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + fileName);
                newOriginalImage.PublicOriginallUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + fileName);
            }
            else
            {
                if(archivedImageOriginalUri == null || archivedImagePublicOriginalUrl == null)
                    throw new CmsException("Not valid Url or Uri for original image");

                newOriginalImage.OriginalUri = archivedImageOriginalUri;
                newOriginalImage.PublicOriginallUrl = archivedImagePublicOriginalUrl;
            }

            newOriginalImage.ThumbnailUri = mediaFileService.GetFileUri(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");
            newOriginalImage.PublicThumbnailUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");
        }
        private MediaImage CreateImage(
            Guid? rootFolderId,
            string fileName,
            string extension,
            string imageTitle,
            Size size,
            long fileLength,
            long thumbnailImageLength,
            MediaImage filledInImage = null)
        {
            MediaImage image;

            if (filledInImage == null)
            {
                image = new MediaImage();

                if (rootFolderId != null && !((Guid)rootFolderId).HasDefaultValue())
                {
                    image.Folder = repository.AsProxy<MediaFolder>((Guid)rootFolderId);
                }

                image.Title = Path.GetFileName(imageTitle);
                image.Caption = null;
                image.Size = fileLength;
                image.IsTemporary = true;
            }
            else
            {
                image = filledInImage;
            }


            image.OriginalFileName = fileName;
            image.OriginalFileExtension = extension;
            image.Type = MediaType.Image;

            image.Width = size.Width;
            image.Height = size.Height;


            image.CropCoordX1 = null;
            image.CropCoordY1 = null;
            image.CropCoordX2 = null;
            image.CropCoordY2 = null;

            image.OriginalWidth = size.Width;
            image.OriginalHeight = size.Height;
            image.OriginalSize = fileLength;

            image.ThumbnailWidth = ThumbnailSize.Width;
            image.ThumbnailHeight = ThumbnailSize.Height;
            image.ThumbnailSize = thumbnailImageLength;

            image.ImageAlign = null;

            image.IsUploaded = null;
            image.IsThumbnailUploaded = null;
            image.IsOriginalUploaded = null;

            return image;
        }
        private MediaImage RevertChanges(MediaImage canceledImage)
        {
            var previousOriginal =
                repository.AsQueryable<MediaImage>().OrderByDescending(i => i.PublishedOn).FirstOrDefault(f => f.Original != null && f.Original.Id == canceledImage.Id);

            if (previousOriginal != null)
            {
                var folderName = Path.GetFileName(Path.GetDirectoryName(previousOriginal.FileUri.OriginalString));
                var publicFileName = MediaImageHelper.CreatePublicFileName(previousOriginal.OriginalFileName, previousOriginal.OriginalFileExtension);

                // Get original file stream
                using (var fileStream = DownloadFileStream(previousOriginal.PublicUrl))
                {
                    // Get thumbnail file stream
                    using (var thumbnailFileStream = DownloadFileStream(previousOriginal.PublicThumbnailUrl))
                    {
                        previousOriginal.CopyDataTo(canceledImage);

                        mediaImageVersionPathService.SetPathForArchive(canceledImage, folderName, publicFileName);

                        StartTasksForImage(canceledImage, fileStream, thumbnailFileStream, previousOriginal.IsEdited());

                        canceledImage.Original = null;
                        unitOfWork.BeginTransaction();
                        repository.Save(canceledImage);
                        unitOfWork.Commit();
                    }
                }
            }

            return previousOriginal;
        }
        /// <summary>
        /// Moves current original image to history.
        /// </summary>
        /// <param name="originalImage">The current original image.</param>
        /// <returns>The archived image.</returns>
        public MediaImage MoveToHistory(MediaImage originalImage)
        {
            var clonnedOriginalImage = (MediaImage)originalImage.Clone();
            clonnedOriginalImage.Original = originalImage;

            var historicalFileName = MediaImageHelper.CreateHistoricalVersionedFileName(
                                originalImage.OriginalFileName,
                                originalImage.OriginalFileExtension);

            var folderName = Path.GetFileName(Path.GetDirectoryName(originalImage.FileUri.OriginalString));
            
            using (var originalFileStream = DownloadFileStream(clonnedOriginalImage.PublicUrl))
            {
                using (var originalThumbnailFileStream = DownloadFileStream(clonnedOriginalImage.PublicThumbnailUrl))
                {
                    mediaImageVersionPathService.SetPathForArchive(clonnedOriginalImage, folderName, historicalFileName);

                    unitOfWork.BeginTransaction();
                    repository.Save(clonnedOriginalImage);
                    unitOfWork.Commit();

                    StartTasksForImage(clonnedOriginalImage, originalFileStream, originalThumbnailFileStream, originalImage.IsEdited());
                }
            }
            return clonnedOriginalImage;
        }
        /// <summary>
        /// Updates the thumbnail.
        /// </summary>
        /// <param name="mediaImage">The media image.</param>
        /// <param name="size">The size.</param>
        public void UpdateThumbnail(MediaImage mediaImage, Size size)
        {
            if (size.IsEmpty)
            {
                size = ThumbnailSize;
            }

            var downloadResponse = storageService.DownloadObject(mediaImage.FileUri);
            var imageType = ImageHelper.GetImageType(mediaImage.OriginalFileExtension);
            using (var memoryStream = new MemoryStream())
            {
                if (imageType == ImageType.Raster)
                {
                    CreatePngThumbnail(downloadResponse.ResponseStream, memoryStream, size);
                }
                else
                {
                    CreateSvgThumbnail(downloadResponse.ResponseStream, memoryStream, size);
                }

                mediaImage.ThumbnailWidth = size.Width;
                mediaImage.ThumbnailHeight = size.Height;
                mediaImage.ThumbnailSize = memoryStream.Length;

                storageService.UploadObject(new UploadRequest { InputStream = memoryStream, Uri = mediaImage.ThumbnailUri, IgnoreAccessControl = true});
            }
        }
Пример #9
0
        /// <summary>
        /// Uploads the image.
        /// </summary>
        /// <param name="rootFolderId">The root folder id.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileLength">Length of the file.</param>
        /// <param name="fileStream">The file stream.</param>
        /// <returns>Image entity.</returns>
        public MediaImage UploadImage(Guid rootFolderId, string fileName, long fileLength, Stream fileStream, Guid reuploadMediaId)
        {
            MediaImage originalMedia;
            string folderName;
            string versionedFileName;
            Size size;
            if (!reuploadMediaId.HasDefaultValue())
            {
                originalMedia = repository.First<MediaImage>(image => image.Id == reuploadMediaId);
                fileName = string.Concat(Path.GetFileNameWithoutExtension(originalMedia.OriginalFileName), Path.GetExtension(fileName));
                folderName = Path.GetFileName(Path.GetDirectoryName(originalMedia.FileUri.OriginalString));
                versionedFileName = MediaImageHelper.CreateVersionedFileName(fileName, originalMedia.Version + 1);
            }
            else
            {
                folderName = mediaFileService.CreateRandomFolderName();
                versionedFileName = MediaImageHelper.CreateVersionedFileName(fileName, 1);
            }

            try
            {
                size = GetImageSize(fileStream);
            }
            catch (ImagingException ex)
            {
                var message = MediaGlobalization.MultiFileUpload_ImageFormatNotSuported;
                const string logMessage = "Failed to get image size.";
                throw new ValidationException(() => message, logMessage, ex);
            }

            using (var thumbnailImage = new MemoryStream())
            {
                CreatePngThumbnail(fileStream, thumbnailImage, ThumbnailSize);

                MediaImage image = new MediaImage();
                if (!rootFolderId.HasDefaultValue())
                {
                    image.Folder = repository.AsProxy<MediaFolder>(rootFolderId);
                }

                image.Title = Path.GetFileName(fileName);
                image.Caption = null;
                image.OriginalFileName = fileName;
                image.OriginalFileExtension = Path.GetExtension(fileName);
                image.Type = MediaType.Image;

                image.Width = size.Width;
                image.Height = size.Height;
                image.Size = fileLength;
                image.FileUri = mediaFileService.GetFileUri(MediaType.Image, folderName, versionedFileName);
                image.PublicUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, versionedFileName);

                image.CropCoordX1 = null;
                image.CropCoordY1 = null;
                image.CropCoordX2 = null;
                image.CropCoordY2 = null;

                image.OriginalWidth = size.Width;
                image.OriginalHeight = size.Height;
                image.OriginalSize = fileLength;
                image.OriginalUri = mediaFileService.GetFileUri(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + versionedFileName);
                image.PublicOriginallUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, MediaImageHelper.OriginalImageFilePrefix + versionedFileName);
                    

                image.ThumbnailWidth = ThumbnailSize.Width;
                image.ThumbnailHeight = ThumbnailSize.Height;
                image.ThumbnailSize = thumbnailImage.Length;
                image.ThumbnailUri = mediaFileService.GetFileUri(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(versionedFileName) + ".png");
                image.PublicThumbnailUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(versionedFileName) + ".png");

                image.ImageAlign = null;
                image.IsTemporary = true;
                image.IsUploaded = null;
                image.IsThumbnailUploaded = null;
                image.IsOriginalUploaded = null;

                unitOfWork.BeginTransaction();
                repository.Save(image);
                unitOfWork.Commit();

                Task imageUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(fileStream, image.FileUri, image.Id, img => { img.IsUploaded = true; }, img => { img.IsUploaded = false; }, true);
                Task originalUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(fileStream, image.OriginalUri, image.Id, img => { img.IsOriginalUploaded = true; }, img => { img.IsOriginalUploaded = false; }, true);
                Task thumbnailUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(thumbnailImage, image.ThumbnailUri, image.Id, img => { img.IsThumbnailUploaded = true; }, img => { img.IsThumbnailUploaded = false; }, true);

                Task.Factory.ContinueWhenAll(
                    new[]
                        {
                            imageUpload, 
                            originalUpload, 
                            thumbnailUpload
                        },
                    result =>
                    {
                        // During uploading progress Cancel action can by executed. Need to remove uploaded images from the storage.
                        ExecuteActionOnThreadSeparatedSessionWithNoConcurrencyTracking(session =>
                            {
                                var media = session.Get<MediaImage>(image.Id);
                                var isUploaded = (media.IsUploaded.HasValue && media.IsUploaded.Value)
                                                  || (media.IsThumbnailUploaded.HasValue && media.IsThumbnailUploaded.Value)
                                                  || (media.IsOriginalUploaded.HasValue && media.IsOriginalUploaded.Value);
                                if (media.IsCanceled && isUploaded)
                                {
                                    RemoveImageWithFiles(media.Id, media.Version);
                                }
                            });
                    });

                imageUpload.Start();
                originalUpload.Start();
                thumbnailUpload.Start();

                return image;
            }
        }
Пример #10
0
 private void OnAfterUploadCompleted(MediaImage media, bool shouldNotUploadOriginal)
 {
     var isUploaded = (media.IsUploaded.HasValue && media.IsUploaded.Value) || (media.IsThumbnailUploaded.HasValue && media.IsThumbnailUploaded.Value)
                          || ((media.IsOriginalUploaded.HasValue && media.IsOriginalUploaded.Value) && shouldNotUploadOriginal);
     if (media.IsCanceled && isUploaded)
     {
         RemoveImageWithFiles(media.Id, media.Version, false, shouldNotUploadOriginal);
     }
 }
Пример #11
0
        private void StartTasksForImageSync(
            MediaImage mediaImage, 
            Stream fileStream, 
            MemoryStream thumbnailFileStream, 
            bool shouldNotUploadOriginal = false)
        {
            mediaFileService.UploadMediaFileToStorageSync(
                fileStream,
                mediaImage.FileUri, 
                mediaImage, 
                img =>
                {
                    if (img != null)
                    {
                        img.IsUploaded = true;
                    }
                },
                img =>
                {
                    if (img != null)
                    {
                        img.IsUploaded = false;
                    }
                },
                true);

            if (!shouldNotUploadOriginal)
            {
                mediaFileService.UploadMediaFileToStorageSync(
                    fileStream,
                    mediaImage.OriginalUri,
                    mediaImage,
                    img =>
                    {
                        if (img != null)
                        {
                            img.IsOriginalUploaded = true;
                        }
                    },
                    img =>
                    {
                        if (img != null)
                        {
                            img.IsOriginalUploaded = false;
                        }
                    },
                    true);
            }

            mediaFileService.UploadMediaFileToStorageSync(
                thumbnailFileStream,
                mediaImage.ThumbnailUri, 
                mediaImage, 
                img =>
                {
                    if (img != null)
                    {
                        img.IsThumbnailUploaded = true;
                    }
                },
                img =>
                {
                    if (img != null)
                    {
                        img.IsThumbnailUploaded = false;
                    }
                },
                true);

            OnAfterUploadCompleted(mediaImage, shouldNotUploadOriginal);
        }
        /// <summary>
        /// Updates the thumbnail.
        /// </summary>
        /// <param name="mediaImage">The media image.</param>
        /// <param name="size">The size.</param>
        private void UpdateThumbnail(MediaImage mediaImage, Size size)
        {
            var downloadResponse = storageService.DownloadObject(mediaImage.FileUri);

            using (var memoryStream = new MemoryStream())
            {
                ResizeImageAndCropToFit(downloadResponse.ResponseStream, memoryStream, size);

                storageService.UploadObject(new UploadRequest { InputStream = memoryStream, Uri = mediaImage.ThumbnailUri });

                mediaImage.ThumbnailWidth = size.Width;
                mediaImage.ThumbnailHeight = size.Height;
                mediaImage.ThumbnailSize = memoryStream.Length;
            }
        }
        /// <summary>
        /// Uploads the image.
        /// </summary>
        /// <param name="rootFolderId">The root folder id.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileLength">Length of the file.</param>
        /// <param name="fileStream">The file stream.</param>
        /// <returns>Image entity.</returns>
        public MediaImage UploadImage(Guid rootFolderId, string fileName, long fileLength, Stream fileStream)
        {
            string folderName = mediaFileService.CreateRandomFolderName();

            Size size = GetImageSize(fileStream);

            using (var thumbnailImage = new MemoryStream())
            {
                ResizeImageAndCropToFit(fileStream, thumbnailImage, ThumbnailSize);

                MediaImage image = new MediaImage();
                if (!rootFolderId.HasDefaultValue())
                {
                    image.Folder = repository.AsProxy<MediaFolder>(rootFolderId);
                }

                image.Title = Path.GetFileName(fileName);
                image.Caption = null;
                image.FileName = fileName;
                image.FileExtension = Path.GetExtension(fileName);
                image.Type = MediaType.Image;

                image.Width = size.Width;
                image.Height = size.Height;
                image.Size = fileLength;
                image.FileUri = mediaFileService.GetFileUri(MediaType.Image, folderName, fileName);
                image.PublicUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, fileName);

                image.CropCoordX1 = null;
                image.CropCoordY1 = null;
                image.CropCoordX2 = null;
                image.CropCoordY2 = null;

                image.OriginalWidth = size.Width;
                image.OriginalHeight = size.Height;
                image.OriginalSize = fileLength;
                image.OriginalUri = mediaFileService.GetFileUri(MediaType.Image, folderName, OriginalImageFilePrefix + fileName);
                image.PublicOriginallUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, OriginalImageFilePrefix + fileName);

                image.ThumbnailWidth = ThumbnailSize.Width;
                image.ThumbnailHeight = ThumbnailSize.Height;
                image.ThumbnailSize = thumbnailImage.Length;
                image.ThumbnailUri = mediaFileService.GetFileUri(MediaType.Image, folderName,  ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");
                image.PublicThumbnailUrl = mediaFileService.GetPublicFileUrl(MediaType.Image, folderName, ThumbnailImageFilePrefix + Path.GetFileNameWithoutExtension(fileName) + ".png");

                image.ImageAlign = null;
                image.IsTemporary = true;
                image.IsUploaded = false;
                image.IsThumbnailUploaded = false;
                image.IsOriginalUploaded = false;

                unitOfWork.BeginTransaction();
                repository.Save(image);
                unitOfWork.Commit();

                Task imageUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(fileStream, image.FileUri, image.Id, img => { img.IsUploaded = true; });
                Task originalUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(fileStream, image.OriginalUri, image.Id, img => { img.IsOriginalUploaded = true; });
                Task thumbnailUpload = mediaFileService.UploadMediaFileToStorage<MediaImage>(thumbnailImage, image.ThumbnailUri, image.Id, img => { img.IsThumbnailUploaded = true; });

                Task.Factory.ContinueWhenAll(
                    new[]
                        {
                            imageUpload,
                            originalUpload,
                            thumbnailUpload
                        },
                    result =>
                    {
                        // During uploading progress Cancel action can by executed. Need to remove uploaded images from the storage.
                        ExecuteActionOnThreadSeparatedSessionWithNoConcurrencyTracking(session =>
                            {
                                var media = session.Get<MediaImage>(image.Id);
                                if (media.IsCanceled && (media.IsUploaded || media.IsThumbnailUploaded || media.IsOriginalUploaded))
                                {
                                    RemoveImageWithFiles(media.Id, media.Version);
                                }
                            });
                    });

                imageUpload.Start();
                originalUpload.Start();
                thumbnailUpload.Start();

                return image;
            }
        }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageDimensionsCalculator" /> class.
 /// </summary>
 /// <param name="image">The image.</param>
 public ImageDimensionsCalculator(MediaImage image)
     : this(image.Width, image.Height, image.OriginalWidth, image.OriginalHeight, image.CropCoordX1, image.CropCoordX2, image.CropCoordY1, image.CropCoordY2)
 {
 }
 private void SetThumbnailParameters(MediaImage image, Size size, long length)
 {
     image.ThumbnailWidth = size.Width;
     image.ThumbnailHeight = size.Height;
     image.ThumbnailSize = length;
 }
Пример #16
0
 private int GetVersion(MediaImage image)
 {
     var versionsCount = repository.AsQueryable<MediaImage>().Count(i => i.Original != null && i.Original.Id == image.Id);
     return versionsCount;
 }
Пример #17
0
 private void StartTasksForImage(
     MediaImage mediaImage,
     Stream fileStream,
     MemoryStream thumbnailFileStream,
     bool shouldNotUploadOriginal = false,
     bool waitForUploadResult = false)
 {
     if (waitForUploadResult)
     {
         StartTasksForImageSync(mediaImage, fileStream, thumbnailFileStream, shouldNotUploadOriginal);
     }
     else
     {
         StartTasksForImageAsync(mediaImage, fileStream, thumbnailFileStream, shouldNotUploadOriginal);
     }
 }
Пример #18
0
        public MediaImage UploadImageWithStream(Stream fileStream, MediaImage image, bool waitForUploadResult = false)
        {
            using (var thumbnailFileStream = new MemoryStream())
            {
                fileStream = RotateImage(fileStream);
                var size = GetSize(fileStream);

                CreatePngThumbnail(fileStream, thumbnailFileStream, ThumbnailSize);

                var folderName = mediaFileService.CreateRandomFolderName();
                var publicFileName = MediaImageHelper.CreatePublicFileName(image.OriginalFileName, image.OriginalFileExtension);

                // Create new original image and upload file stream to the storage
                var originalImage = CreateImage(null, image.OriginalFileName, image.OriginalFileExtension, image.Title, size, image.Size, thumbnailFileStream.Length, image);
                mediaImageVersionPathService.SetPathForNewOriginal(originalImage, folderName, publicFileName);

                unitOfWork.BeginTransaction();
                repository.Save(originalImage);

                if (!waitForUploadResult)
                {
                    unitOfWork.Commit();
                }
                
                StartTasksForImage(originalImage, fileStream, thumbnailFileStream, false, waitForUploadResult);
                
                if (waitForUploadResult)
                {
                    unitOfWork.Commit();
                    Events.MediaManagerEvents.Instance.OnMediaFileUpdated(originalImage);
                }

                return originalImage;
            }
        }
Пример #19
0
        private void StartTasksForImageAsync(
            MediaImage mediaImage, 
            Stream fileStream, 
            MemoryStream thumbnailFileStream, 
            bool shouldNotUploadOriginal = false)
        {
            var publicImageUpload = mediaFileService.UploadMediaFileToStorageAsync<MediaImage>(
                fileStream,
                mediaImage.FileUri,
                mediaImage.Id,
                (img, session) =>
                {
                    if (img != null)
                    {
                        img.IsUploaded = true;
                    }
                },
                img =>
                {
                    if (img != null)
                    {
                        img.IsUploaded = false;
                    }
                },
                true);

            var publicThumbnailUpload = mediaFileService.UploadMediaFileToStorageAsync<MediaImage>(
                thumbnailFileStream,
                mediaImage.ThumbnailUri,
                mediaImage.Id,
                (img, session) =>
                {
                    if (img != null)
                    {
                        img.IsThumbnailUploaded = true;
                    }
                },
                img =>
                {
                    if (img != null)
                    {
                        img.IsThumbnailUploaded = false;
                    }
                },
                true);

            var allTasks = new List<Task> { publicImageUpload, publicThumbnailUpload };

            Task publicOriginalUpload = null;
            if (!shouldNotUploadOriginal)
            {
                publicOriginalUpload = mediaFileService.UploadMediaFileToStorageAsync<MediaImage>(
                fileStream,
                mediaImage.OriginalUri,
                mediaImage.Id,
                (img, session) =>
                {
                    if (img != null)
                    {
                        img.IsOriginalUploaded = true;
                    }
                },
                img =>
                {
                    if (img != null)
                    {
                        img.IsOriginalUploaded = false;
                    }
                },
                true);
                allTasks.Add(publicOriginalUpload);
            }

            allTasks.ForEach(task => task.ContinueWith((t) => { Log.Error("Error observed while executing parallel task during image upload.", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted));

            Task.Factory.ContinueWhenAll(
                allTasks.ToArray(),
                result =>
                    {
                        try
                        {
                            ExecuteActionOnThreadSeparatedSessionWithNoConcurrencyTracking(
                                session =>
                                    {
                                        var media = session.Get<MediaImage>(mediaImage.Id);
                                        if (media != null)
                                        {
                                            OnAfterUploadCompleted(media, shouldNotUploadOriginal);
                                        }
                                    });
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Failed to finalize upload.", ex);
                        }
                    });

            publicImageUpload.Start();
            if (publicOriginalUpload != null)
            {
                publicOriginalUpload.Start();
            }
            publicThumbnailUpload.Start();
        }
Пример #20
0
        /// <summary>
        /// Makes image as original.
        /// </summary>
        /// <param name="image">The new original image.</param>
        /// <param name="originalImage">The current original image.</param>
        /// <param name="archivedImage">The archived image.</param>
        /// <param name="overrideUrl">To override public Url ot not.</param>
        /// <returns>The new original image.</returns>
        public MediaImage MakeAsOriginal(MediaImage image, MediaImage originalImage, MediaImage archivedImage, bool overrideUrl = true)
        {
            overrideUrl = false; // TODO: temporary disabling feature #1055.
            var folderName = Path.GetFileName(Path.GetDirectoryName(originalImage.FileUri.OriginalString));
            
            using (var fileStream = DownloadFileStream(image.PublicUrl))
            {
                string publicUrlTemp = string.Empty, publicThumbnailUrlTemp = string.Empty, publicOriginallUrlTemp = string.Empty;
                Uri fileUriTemp = null, thumbnailUriTemp = null, originalUriTemp = null;

                if (overrideUrl)
                {
                    publicUrlTemp = originalImage.PublicUrl;
                    fileUriTemp = originalImage.FileUri;
                    publicThumbnailUrlTemp = originalImage.PublicThumbnailUrl;
                    thumbnailUriTemp = originalImage.ThumbnailUri;
                    publicOriginallUrlTemp = originalImage.PublicOriginallUrl;
                    originalUriTemp = originalImage.OriginalUri;
                }

                image.CopyDataTo(originalImage, false);
                MediaHelper.SetCollections(repository, image, originalImage);

                if (!overrideUrl)
                {
                    var publicFileName = MediaImageHelper.CreateVersionedFileName(originalImage.OriginalFileName, GetVersion(originalImage));
                    mediaImageVersionPathService.SetPathForNewOriginal(originalImage, folderName, publicFileName, archivedImage.OriginalUri, archivedImage.PublicOriginallUrl);
                }
                else
                {
                    originalImage.PublicUrl = publicUrlTemp;
                    originalImage.FileUri = fileUriTemp;
                    originalImage.PublicThumbnailUrl = publicThumbnailUrlTemp;
                    originalImage.ThumbnailUri = thumbnailUriTemp;
                    originalImage.PublicOriginallUrl = publicOriginallUrlTemp;
                    originalImage.OriginalUri = originalUriTemp;
                }

                
                originalImage.Original = null;
                originalImage.PublishedOn = DateTime.Now;
                
                if (image.IsEdited())
                {
                    originalImage.PublicOriginallUrl = image.PublicOriginallUrl;
                    originalImage.OriginalUri = image.OriginalUri;
                }

                unitOfWork.BeginTransaction();
                repository.Save(originalImage);
                unitOfWork.Commit();

                if (!image.IsEdited())
                {
                    using (var fileStreamReplica = new MemoryStream())
                    {
                        fileStream.CopyTo(fileStreamReplica);
                        storageService.UploadObject(new UploadRequest { InputStream = fileStreamReplica, Uri = originalImage.OriginalUri, IgnoreAccessControl = true });
                    }
                }
                storageService.UploadObject(new UploadRequest { InputStream = fileStream, Uri = originalImage.FileUri, IgnoreAccessControl = true });

                UpdateThumbnail(originalImage, Size.Empty);

                return originalImage;
            }
        }
Пример #21
0
        /// <summary>
        /// Replaces the image or if it doesn't exist, creates it.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <c>PutImageResponse</c> with a image id.
        /// </returns>
        public PutImageResponse Put(PutImageRequest request)
        {
            IEnumerable<MediaFolder> parentFolderFuture = null;
            if (request.Data.FolderId.HasValue)
            {
                parentFolderFuture = repository.AsQueryable<MediaFolder>()
                    .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                    .ToFuture();
            }

            var mediaImage = repository.AsQueryable<MediaImage>()
                .Where(file => file.Id == request.Id)
                .ToFuture()
                .FirstOrDefault();

            MediaFolder parentFolder = null;
            if (parentFolderFuture != null)
            {
                parentFolder = parentFolderFuture.First();
                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var createImage = mediaImage == null;
            if (createImage)
            {
                mediaImage = new MediaImage
                                 {
                                     Id = request.Id.GetValueOrDefault(),
                                     Type = Module.MediaManager.Models.MediaType.Image
                                 };
            }
            else if (request.Data.Version > 0)
            {
                mediaImage.Version = request.Data.Version;
            }

            unitOfWork.BeginTransaction();

            if (!createImage)
            {
                repository.Save(mediaImage.CreateHistoryItem());
            }

            mediaImage.Title = request.Data.Title;
            mediaImage.Description = request.Data.Description;
            mediaImage.Caption = request.Data.Caption;
            mediaImage.Size = request.Data.FileSize;
            mediaImage.PublicUrl = request.Data.ImageUrl;
            mediaImage.Width = request.Data.Width;
            mediaImage.Height = request.Data.Height;
            mediaImage.PublicThumbnailUrl = request.Data.ThumbnailUrl;
            mediaImage.ThumbnailWidth = request.Data.ThumbnailWidth;
            mediaImage.ThumbnailHeight = request.Data.ThumbnailHeight;
            mediaImage.ThumbnailSize = request.Data.ThumbnailSize;
            mediaImage.Folder = parentFolder;
            mediaImage.PublishedOn = request.Data.PublishedOn;
            mediaImage.OriginalFileName = request.Data.OriginalFileName;
            mediaImage.OriginalFileExtension = request.Data.OriginalFileExtension;
            mediaImage.OriginalWidth = request.Data.OriginalWidth;
            mediaImage.OriginalHeight = request.Data.OriginalHeight;
            mediaImage.OriginalSize = request.Data.OriginalSize;
            mediaImage.PublicOriginallUrl = request.Data.OriginalUrl;

            mediaImage.FileUri = new Uri(request.Data.FileUri);
            mediaImage.IsUploaded = request.Data.IsUploaded;
            mediaImage.IsTemporary = request.Data.IsTemporary;
            mediaImage.IsCanceled = request.Data.IsCanceled;
            mediaImage.OriginalUri = new Uri(request.Data.OriginalUri);
            mediaImage.ThumbnailUri = new Uri(request.Data.ThumbnailUri);

            var archivedMedias = new List<Media>();
            var unarchivedMedias = new List<Media>();
            if (mediaImage.IsArchived != request.Data.IsArchived)
            {
                if (request.Data.IsArchived)
                {
                    archivedMedias.Add(mediaImage);
                    mediaService.ArchiveSubMedias(mediaImage, archivedMedias);
                }
                else
                {
                    unarchivedMedias.Add(mediaImage);
                    mediaService.UnarchiveSubMedias(mediaImage, unarchivedMedias);
                }
            }

            mediaImage.IsArchived = request.Data.IsArchived;

            repository.Save(mediaImage);

            IList<Tag> newTags = null;
            if (request.Data.Tags != null)
            {
                tagService.SaveMediaTags(mediaImage, request.Data.Tags, out newTags);
            }

            unitOfWork.Commit();

            // Fire events.
            Events.RootEvents.Instance.OnTagCreated(newTags);
            if (createImage)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(mediaImage);
            }
            else
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUpdated(mediaImage);
            }

            foreach (var archivedMedia in archivedMedias.Distinct())
            {
                Events.MediaManagerEvents.Instance.OnMediaArchived(archivedMedia);
            }

            foreach (var archivedMedia in unarchivedMedias.Distinct())
            {
                Events.MediaManagerEvents.Instance.OnMediaUnarchived(archivedMedia);
            }

            return new PutImageResponse
                       {
                           Data = mediaImage.Id
                       };
        }
Пример #22
0
        /// <summary>
        /// Saves edited image as original.
        /// </summary>
        /// <param name="image">The edited image.</param>
        /// <param name="archivedImage">The archived image.</param>
        /// <param name="croppedImageFileStream">The stream with edited image.</param>
        /// <param name="overrideUrl">To override public url or not.</param>
        public void SaveEditedImage(MediaImage image, MediaImage archivedImage, MemoryStream croppedImageFileStream, bool overrideUrl = true)
        {
            overrideUrl = false; // TODO: temporary disabling feature #1055.
            var folderName = Path.GetFileName(Path.GetDirectoryName(image.FileUri.OriginalString));
            
            using (var fileStream = croppedImageFileStream ?? DownloadFileStream(image.PublicUrl))
            {
                image.Original = null;
                image.PublishedOn = DateTime.Now;

                if (!overrideUrl)
                {
                    var publicFileName = MediaImageHelper.CreateVersionedFileName(image.OriginalFileName, GetVersion(image));
                    mediaImageVersionPathService.SetPathForNewOriginal(image, folderName, publicFileName, archivedImage.OriginalUri, archivedImage.PublicOriginallUrl);
                }
                
                unitOfWork.BeginTransaction();
                repository.Save(image);
                unitOfWork.Commit();

                storageService.UploadObject(new UploadRequest { InputStream = fileStream, Uri = image.FileUri, IgnoreAccessControl = true });
                UpdateThumbnail(image, Size.Empty);
            }
        }
Пример #23
0
        /// <summary>
        /// Updates the thumbnail.
        /// </summary>
        /// <param name="mediaImage">The media image.</param>
        /// <param name="size">The size.</param>
        public void UpdateThumbnail(MediaImage mediaImage, Size size)
        {
            if (size.IsEmpty)
            {
                size = ThumbnailSize;
            }

            var downloadResponse = storageService.DownloadObject(mediaImage.FileUri);

            using (var memoryStream = new MemoryStream())
            {
                CreatePngThumbnail(downloadResponse.ResponseStream, memoryStream, size);

                mediaImage.ThumbnailWidth = size.Width;
                mediaImage.ThumbnailHeight = size.Height;
                mediaImage.ThumbnailSize = memoryStream.Length;

                storageService.UploadObject(new UploadRequest { InputStream = memoryStream, Uri = mediaImage.ThumbnailUri, IgnoreAccessControl = true});
            }
        }
Пример #24
0
 public void SaveImage(MediaImage image)
 {
     unitOfWork.BeginTransaction();
     repository.Save(image);
     unitOfWork.Commit();
 }