Beispiel #1
0
        //Creates initial record (as well as replacements for existing records and additions for gallery images) for ALL types (listings, galleries, etc...)
        public static DataAccessResponseType ProcessAndRecordApplicationImage(Account account, ImageProcessingManifestModel imageManifest, ImageCropCoordinates imageCropCoordinates, ImageEnhancementInstructions imageEnhancementInstructions = null)
        {
            var tableStorageResult = new DataAccessResponseType();

            #region Get image format & group for this new record

            ImageFormatGroupModel imageGroup;
            var imageFormat = ImageFormatsManager.GetImageFormat(account.AccountNameKey, imageManifest.GroupTypeNameKey, imageManifest.GroupNameKey, imageManifest.FormatNameKey, out imageGroup);

            if (imageFormat == null)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Not a valid image format"
                });
            }

            #endregion

            #region Get Image Record for this image slot on this object (If one exists)

            ImageRecordModel existingImageRecord = null;

            var imageRecords = ImageRecordsManager.GetImageRecordsForObject(account.AccountID.ToString(), account.StoragePartition, account.AccountNameKey, imageManifest.GroupTypeNameKey, imageManifest.ObjectId);

            foreach (ImageRecordGroupModel imageRecordGroupModel in imageRecords)
            {
                if (imageRecordGroupModel.GroupNameKey == imageManifest.GroupNameKey)
                {
                    foreach (ImageRecordModel record in imageRecordGroupModel.ImageRecords)
                    {
                        if (record.FormatNameKey == imageManifest.FormatNameKey)
                        {
                            if (record.BlobPath != null || record.GalleryImages.Count > 0)
                            {
                                existingImageRecord = record; //<-- We only assign it if images exist (single or gallery)
                            }
                        }
                    }
                }
            }

            #endregion

            #region  Process image according to ImageFormat specs, save to blob storage for the AccountID

            //var folderName = account.AccountID.ToString() + "/" + imageManifest.GroupTypeNameKey + "images";
            var folderName = imageManifest.GroupTypeNameKey + "Images";

            //Override of "Product" to "Item" -----------------
            if (folderName == "productImages")
            {
                folderName = "itemImages";
            }
            //------------------------------------------------

            var applicationImageProcessor = new Imaging.ApplicationImageProcessor();

            if (imageManifest.Title.Length > Settings.Objects.Limitations.ImageFormatTitleMaxLength)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Image titles cannot be longer than " + Settings.Objects.Limitations.ImageFormatTitleMaxLength + " characters"
                });
            }
            if (imageManifest.Description.Length > Settings.Objects.Limitations.ImageFormatDescriptionMaxLength)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Image descriptions cannot be longer than " + Settings.Objects.Limitations.ImageFormatDescriptionMaxLength + " characters"
                });
            }

            //If this is an addition to an image gallery. Make sure we are within safe limits before creating the image
            if (existingImageRecord != null && imageFormat.Gallery && existingImageRecord.GalleryImages.Count >= account.PaymentPlan.MaxImagesPerGallery)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Your plan does not allow for more than " + account.PaymentPlan.MaxImagesPerGallery + " images per gallery"
                });
            }

            //If this is a gallery type we cannot use pipes "|" in titles or descriptions
            if (imageFormat.Gallery && imageManifest.Title.Contains("|"))
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Cannot use the '|' character in gallery titles."
                });
            }
            if (imageFormat.Gallery && imageManifest.Description.Contains("|"))
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Cannot use the '|' character in gallery descriptions."
                });
            }

            var processingResult = applicationImageProcessor.ProcessApplicationImage(account.AccountID.ToString(), account.StoragePartition, imageManifest.SourceContainerName, imageManifest.FileName, imageFormat.Width, imageFormat.Height, folderName, imageManifest.Type, imageManifest.Quality, imageCropCoordinates, imageEnhancementInstructions);

            #endregion

            if (processingResult.isSuccess)
            {
                //var cdnUrl = Settings.Azure.Storage.GetStoragePartition(account.StoragePartition).CDN;

                var newContainerName = account.AccountID.ToString();
                var newImageFileName = processingResult.SuccessMessage + "." + imageManifest.Type;
                //var newUrl = "http://" + cdnUrl + "/" + newContainerName + "/" + folderName + "/" + newImageFileName; //<-- CDN now assigned by consumers in case of future migration
                var newUrl      = newContainerName + "/" + folderName + "/" + newImageFileName;
                var newBlobPath = folderName + "/" + newImageFileName;
                var newFilePath = newContainerName + "/" + newBlobPath;

                #region Record data to table storage

                if (existingImageRecord == null || !imageFormat.Gallery)
                {
                    // This is the first image added to this record (gallery or single)
                    #region Store or Replace Image Record for this ObjectType/ObjectID

                    tableStorageResult = ImageRecordsManager.CreateImageRecordForObject(
                        account.AccountID.ToString(),
                        account.StoragePartition,
                        imageManifest.GroupTypeNameKey,
                        imageManifest.ObjectId,
                        imageGroup.ImageFormatGroupName,
                        imageGroup.ImageFormatGroupNameKey,
                        imageFormat.ImageFormatName,
                        imageFormat.ImageFormatNameKey,
                        imageManifest.Title,
                        imageManifest.Description,
                        newUrl,
                        newImageFileName,
                        newFilePath,
                        newContainerName,
                        newBlobPath,
                        imageFormat.Height,
                        imageFormat.Width,
                        imageFormat.Listing
                        );

                    #endregion
                }
                else
                {
                    //This is an addition to a Galley, Append to the array of gallery image (And do not delete any previous blobs)
                    #region Append to gallery Image Record for this ObjectType/ObjectID

                    tableStorageResult = ImageRecordsManager.AppendToImageGalleryRecordForObject(
                        account,
                        imageManifest.GroupTypeNameKey,
                        imageManifest.ObjectId,
                        imageGroup.ImageFormatGroupName,
                        imageGroup.ImageFormatGroupNameKey,
                        imageFormat.ImageFormatName,
                        imageFormat.ImageFormatNameKey,
                        imageManifest.Title,
                        imageManifest.Description,
                        newUrl,
                        newImageFileName,
                        newFilePath,
                        newBlobPath
                        );

                    #endregion
                }
                #endregion

                // Add URL for UI to preload:
                tableStorageResult.SuccessMessage = newUrl;

                #region Clean up previous blob data

                if (existingImageRecord == null || imageFormat.Gallery)
                {
                    //Do nothing, this was the first image created for this slot, or was an image appended to a gallery
                }
                else
                {
                    //This is a replacement on a single image. Delete the previous image from blob storage
                    #region Delete previous blob image

                    ImageStorageManager.DeleteImageBlobs(account.StoragePartition, existingImageRecord.ContainerName, existingImageRecord.BlobPath);

                    #endregion
                }

                #endregion

                if (!tableStorageResult.isSuccess)
                {
                    #region There was an issue recording data to table storage. Delete the blobs we just created

                    try
                    {
                        ImageStorageManager.DeleteImageBlobs(account.StoragePartition, newContainerName, newBlobPath);
                    }
                    catch
                    {
                    }

                    #endregion
                }
            }

            //Return results
            return(tableStorageResult);
        }
        public JsonNetResult ProcessImage(string imageId, string objectType, string objectId, string imageGroupNameKey, string imageFormatNameKey, string containerName, string imageFormat, string type, int quality, float top, float left, float right, float bottom, string title, string description, string tags, int brightness, int contrast, int saturation, int sharpness, bool sepia, bool polaroid, bool greyscale)
        {
            var response = new ApplicationImagesService.DataAccessResponseType();


            #region Generate Job Models

            var imageProcessingManifest = new ImageProcessingManifestModel
            {
                SourceContainerName = containerName,
                FileName            = imageId + "." + imageFormat,

                GroupTypeNameKey = objectType,
                ObjectId         = objectId,

                Type    = type,
                Quality = quality,

                GroupNameKey  = imageGroupNameKey,
                FormatNameKey = imageFormatNameKey,

                ImageId     = imageId,
                Title       = title,
                Description = description
            };


            var imageCropCoordinates = new ImageCropCoordinates
            {
                Top    = top,
                Left   = left,
                Right  = right,
                Bottom = bottom
            };

            var imageEnhancementInstructions = new ImageEnhancementInstructions();

            if (brightness != 0 || contrast != 0 || saturation != 0 || saturation != 0 || sharpness != 0 || sepia == true || polaroid == true || greyscale == true)
            {
                imageEnhancementInstructions.Brightness = brightness;
                imageEnhancementInstructions.Contrast   = contrast;
                imageEnhancementInstructions.Saturation = saturation;
                imageEnhancementInstructions.Sharpen    = sharpness;
                imageEnhancementInstructions.Sepia      = sepia;
                imageEnhancementInstructions.Greyscale  = greyscale;
                imageEnhancementInstructions.Polaroid   = polaroid;
            }
            else
            {
                imageEnhancementInstructions = null;
            }



            #endregion

            #region Submit Job

            var user    = AuthenticationCookieManager.GetAuthenticationCookie();
            var account = Common.GetAccountObject(user.AccountNameKey);

            try
            {
                var applicationImagesServicesClient = new ApplicationImagesServiceClient();
                response = applicationImagesServicesClient.ProcessImage(user.AccountID.ToString(), imageProcessingManifest, imageCropCoordinates, user.Id, ApplicationImagesService.RequesterType.AccountUser, imageEnhancementInstructions, Common.SharedClientKey);
            }
            catch (Exception e)
            {
                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            #endregion

            #region Handle Caching Expiration on Account image type

            if (objectType == "account")
            {
                //Expire accountimages cache
                RedisCacheKeys.AccountImages.Expire(user.AccountNameKey);
            }

            #endregion

            //Append account CDN url to Success message (newImageUrlPath)
            var storagePartition = CoreServices.PlatformSettings.StorageParitions.FirstOrDefault(partition => partition.Name == account.StoragePartition);
            response.SuccessMessage = "https://" + storagePartition.CDN + "/" + response.SuccessMessage;

            #region Handle Results

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = response;

            return(jsonNetResult);

            #endregion
        }
Beispiel #3
0
        /// <summary>
        /// Before "adding" an image to an object the client must upload a source file to a dated directory within intermediary storage.
        /// Pass in the source file info along with any cropping or enhancement instructions and you will get back the final image id after processing is complete/
        /// Intermediary directory MUST named by todays date: "DD-MM-YYYY", this directory will be garbage collected by the Custodian at a set interval
        /// </summary>
        public DataAccessResponseType ProcessImage(string accountId, ImageProcessingManifestModel imageManifest, ImageCropCoordinates imageCropCoordinates, string requesterId, RequesterType requesterType, ImageEnhancementInstructions imageEnhancementInstructions, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var account = AccountManager.GetAccount(accountId);

            #region Adjust negative crop coordinates for top/left pixel

            //if any top/left values fall below 0 we adjust to 0
            if (imageCropCoordinates.Top < 0)
            {
                imageCropCoordinates.Top = 0;
            }
            if (imageCropCoordinates.Left < 0)
            {
                imageCropCoordinates.Left = 0;
            }

            #endregion

            #region Validate Request

            var requesterName  = string.Empty;
            var requesterEmail = string.Empty;

            var requestResponseType = RequestManager.ValidateRequest(requesterId,
                                                                     requesterType, out requesterName, out requesterEmail,
                                                                     Sahara.Core.Settings.Platform.Users.Authorization.Roles.Manager,
                                                                     Sahara.Core.Settings.Accounts.Users.Authorization.Roles.Manager);

            if (!requestResponseType.isApproved)
            {
                //Request is not approved, send results:
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = requestResponseType.requestMessage
                });
            }

            #endregion

            #region Validate Plan Capabilities

            // If enhancement instructions are sent, verify that current plan allows for it
            if (imageEnhancementInstructions != null && account.PaymentPlan.AllowImageEnhancements == false)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Your account plan does not allow for image enhancements, please submit your job without enhancement instructions."
                });
            }

            //Verify that current image count is below maximum allowed by this plan
            //if (ApplicationImagesManager.GetApplicationImageCount(account) >= account.PaymentPlan.MaxProducts)
            //{
            //Log Limitation Issues (or send email) so that Platform Admins can immediatly contact Accounts that have hit their limits an upsell themm
            //Sahara.Core.Logging.PlatformLogs.Helpers.PlatformLimitationsHelper.LogLimitationAndAlertAdmins("images", account.AccountID.ToString(), account.AccountName);

            //return new DataAccessResponseType { isSuccess = false, ErrorMessage = "Your account plan does not allow for more than " + account.PaymentPlan.MaxProducts + " images, please update your plan." };
            //}

            #endregion

            var result = ApplicationImageProcessingManager.ProcessAndRecordApplicationImage(account, imageManifest, imageCropCoordinates, imageEnhancementInstructions);

            #region Log Account Activity


            if (result.isSuccess)
            {
                /*try
                 * {
                 *
                 *  //Object Log ---------------------------
                 *  AccountLogManager.LogActivity(
                 *      accountId,
                 *      CategoryType.ApplicationImage,
                 *      ActivityType.ApplicationImage_Created,
                 *      "Application image created",
                 *      requesterName + " created an application image",
                 *      requesterId,
                 *      requesterName,
                 *      requesterEmail,
                 *      null,
                 *      null,
                 *      result.SuccessMessage);
                 * }
                 * catch { }*/
            }

            #endregion

            #region Invalidate Account Capacity Cache

            //AccountCapacityManager.InvalidateAccountCapacitiesCache(accountId);

            #endregion

            #region Invalidate Account API Caching Layer

            Sahara.Core.Common.Redis.ApiRedisLayer.InvalidateAccountApiCacheLayer(account.AccountNameKey);

            #endregion

            return(result);
        }