Exemple #1
0
        public AuctionImageRepresentation ConvertTo(AuctionImageRepresentation imageRepresentation,
                                                    AuctionImageSize size)
        {
            using (var img = Image.Load(imageRepresentation.Img))
            {
                int destW = size.W;
                int destH = size.H;

                if (img.Width * size.H > size.W * img.Height)
                {
                    destH = (size.W * img.Height) / img.Width;
                }
                else
                {
                    destW = (size.H * img.Width) / img.Height;
                }

                img.Mutate(x => x.Resize(destW, destH));
                using (var mem = new MemoryStream())
                {
                    img.Save(mem, GetEncoderFromImage(imageRepresentation));
                    return(new AuctionImageRepresentation(imageRepresentation.Metadata, mem.ToArray()));
                }
            }
        }
Exemple #2
0
        private void AddTestImageToRepository(string imageId)
        {
            var testFile          = File.ReadAllBytes("./test_image.jpg");
            var imgRepresentation = new AuctionImageRepresentation(new AuctionImageMetadata("jpg"), testFile);

            auctionImageRepository.Add(imageId, imgRepresentation);
        }
Exemple #3
0
        private void ReplaceAuctionImage(UserReplaceAuctionImageCommand request, CancellationToken cancellationToken, CorrelationId correlationId)
        {
            var auction = _auctionRepository.FindAuction(request.AuctionId);

            if (auction == null)
            {
                throw new CommandException($"Cannot find auction {request.AuctionId}");
            }

            var file = File.ReadAllBytes(request.TempPath);

            File.Delete(request.TempPath);

            var img = new AuctionImageRepresentation(new AuctionImageMetadata(request.Extension), file);

            var newImg = _auctionImageService.AddAuctionImage(img);

            auction.ReplaceImage(newImg, request.ImgNum);

            _auctionRepository.UpdateAuction(auction);
            try
            {
                _eventBusService.Publish(auction.PendingEvents, correlationId, request);
            }
            catch (Exception)
            {
                _auctionImageService.RemoveAuctionImage(newImg);
                throw;
            }
        }
        public void ValidateImage_when_invalid_img_representation_returns_false()
        {
            var imgRepresentation = new AuctionImageRepresentation(new AuctionImageMetadata("jpg"), Enumerable.Range(0, 20).Select(i => (byte)i).ToArray());

            var isValid = service.ValidateImage(imgRepresentation, new[] { "jpg", "png" });

            Assert.AreEqual(false, isValid);
        }
        public void ValidateImage_returns_valid_result(string path, bool shouldBeValid)
        {
            var ext = path.Split('.', StringSplitOptions.RemoveEmptyEntries).Last();
            var imgRepresentation =
                new AuctionImageRepresentation(new AuctionImageMetadata(ext), File.ReadAllBytes(path));

            var isValid = service.ValidateImage(imgRepresentation, new[] { "jpg", "png" });

            Assert.AreEqual(shouldBeValid, isValid);
        }
Exemple #6
0
 public void Add(string imageId, AuctionImageRepresentation imageRepresentation)
 {
     if (Find(imageId) == null)
     {
         var fileUploadOptions = new GridFSUploadOptions();
         fileUploadOptions.Metadata = imageRepresentation.Metadata.ToBsonDocument();
         var o = _dbContext.Bucket.UploadFromBytes(imageId, imageRepresentation.Img, fileUploadOptions);
     }
     else
     {
         throw new Exception($"{imageId} already exists");
     }
 }
Exemple #7
0
        private IImageEncoder GetEncoderFromImage(AuctionImageRepresentation imageRepresentation)
        {
            switch (imageRepresentation.Metadata.Extension)
            {
            case "jpg":
                return(new JpegEncoder());

            case "png":
                return(new PngEncoder());

            default:
                throw new Exception($"Unknown image extension {imageRepresentation.Metadata.Extension}");
            }
        }
Exemple #8
0
        public void AddImage_when_valid_file_adds_image()
        {
            var testFile          = File.ReadAllBytes("./test_image.jpg");
            var imgRepresentation = new AuctionImageRepresentation(new AuctionImageMetadata("jpg"), testFile);

            auctionImageRepository.Add("img1", imgRepresentation);
            var fetched = auctionImageRepository.Find("img1");

            fetched.Metadata.IsAssignedToAuction.Should()
            .BeFalse();
            fetched.Should()
            .NotBeNull();
            fetched.Img.Length.Should()
            .Be(testFile.Length);
        }
Exemple #9
0
        public AuctionImage AddAuctionImage(AuctionImageRepresentation representation)
        {
            if (!_imageConverterService.ValidateImage(representation, AuctionImage.AllowedExtensions))
            {
                throw new DomainException("Invalid image");
            }

            var img = new AuctionImage(
                AuctionImage.GenerateImageId(AuctionImageSize.SIZE1),
                AuctionImage.GenerateImageId(AuctionImageSize.SIZE2),
                AuctionImage.GenerateImageId(AuctionImageSize.SIZE3)
                );

            AddConvertedImage(img.Size1Id, AuctionImageSize.SIZE1, representation);
            AddConvertedImage(img.Size2Id, AuctionImageSize.SIZE2, representation);
            AddConvertedImage(img.Size3Id, AuctionImageSize.SIZE3, representation);

            return(img);
        }
Exemple #10
0
        public bool ValidateImage(AuctionImageRepresentation imageRepresentation, string[] allowedExtensions)
        {
            //TODO
            var read = new List <string>();

            string[][] firstBytes = allowedExtensions.Select(ImgExtensionToFirstBytes).ToArray();

            for (int i = 0; i < 8; i++)
            {
                var b = imageRepresentation.Img[i].ToString("X2");
                read.Add(b);
                bool isValid = firstBytes.Any(imgBytes => !imgBytes.Except(read).Any());
                if (isValid)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #11
0
        public void UpdateMetadata_when_file_exists_changes_metadata()
        {
            var testFile          = File.ReadAllBytes("./test_image.jpg");
            var imgRepresentation = new AuctionImageRepresentation(new AuctionImageMetadata("jpg"), testFile);

            auctionImageRepository.Add("img1", imgRepresentation);

            auctionImageRepository.UpdateMetadata("img1", new AuctionImageMetadata("jpg")
            {
                IsAssignedToAuction = true
            });

            var fetched = auctionImageRepository.Find("img1");

            fetched.Metadata.IsAssignedToAuction.Should()
            .BeTrue();
            fetched.Should()
            .NotBeNull();
            fetched.Img.Length.Should()
            .Be(testFile.Length);
        }
        public void ConvertTo_returns_image_with_valid_size(string path, int desiredW, int desiredH)
        {
            var ext = path.Split('.', StringSplitOptions.RemoveEmptyEntries).Last();
            var imgRepresentation =
                new AuctionImageRepresentation(new AuctionImageMetadata(ext), File.ReadAllBytes(path));
            var size = new AuctionImageSize(desiredW, desiredH);

            var converted = service.ConvertTo(imgRepresentation, size);

            converted.Should().NotBeNull();
            converted.Img.Length.Should().BeGreaterThan(0);
            converted.Metadata.Should().NotBeNull();

            using (var img = Image.Load(converted.Img))
            {
                img.Width.Should().BeLessOrEqualTo(desiredW);
                img.Height.Should().BeLessOrEqualTo(desiredH);
                img.Width.Should().BeGreaterThan(0);
                img.Height.Should().BeGreaterThan(0);
            }
        }
Exemple #13
0
        private void AddConvertedImage(string imageId, AuctionImageSize size, AuctionImageRepresentation imgRepresentation)
        {
            AuctionImageRepresentation converted = null;

            try
            {
                converted = _imageConverterService.ConvertTo(imgRepresentation, size);
            }
            catch (Exception ex)
            {
                throw new DomainException("Cannot convert image", ex);
            }

            try
            {
                _imageRepository.Add(imageId, converted);
            }
            catch (Exception ex)
            {
                throw new DomainException("Cannot add image", ex);
            }
        }
Exemple #14
0
        protected override Task <RequestStatus> HandleCommand(AddAuctionImageCommand request, CancellationToken cancellationToken)
        {
            var file = File.ReadAllBytes(request.TempPath);

            File.Delete(request.TempPath);

            var img = new AuctionImageRepresentation(new AuctionImageMetadata(request.Extension), file);

            var added = _auctionImageService.AddAuctionImage(img);

            request.AuctionCreateSession.AddOrReplaceImage(added, request.ImgNum);

            var response = RequestStatus.CreateFromCommandContext(request.CommandContext, Status.COMPLETED, new Dictionary <string, object>()
            {
                { "imgSz1", added.Size1Id },
                { "imgSz2", added.Size2Id },
                { "imgSz3", added.Size3Id }
            });

            _logger.LogDebug("Image added: {@img}", added);

            return(Task.FromResult(response));
        }
Exemple #15
0
        private void AddImage(UserAddAuctionImageCommand request, CancellationToken cancellationToken, CorrelationId correlationId)
        {
            var auction = _auctionRepository.FindAuction(request.AuctionId);

            if (auction == null)
            {
                throw new CommandException($"Cannot find auction {request.AuctionId}");
            }

            if (!auction.Owner.UserId.Equals(request.SignedInUser.UserId))
            {
                throw new CommandException(
                          $"User {request.SignedInUser.UserId} cannot modify auction ${auction.AggregateId}");
            }

            var file = File.ReadAllBytes(request.TempPath);

            File.Delete(request.TempPath);

            var img = new AuctionImageRepresentation(new AuctionImageMetadata(request.Extension), file);

            var newImg = _auctionImageService.AddAuctionImage(img);

            auction.AddImage(newImg);

            _auctionRepository.UpdateAuction(auction);
            try
            {
                _eventBusService.Publish(auction.PendingEvents, correlationId, request);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Error while trying to publish events");
                _auctionImageService.RemoveAuctionImage(newImg);
                throw;
            }
        }