Esempio n. 1
0
        public IActionResult AddPhotoForCity(int cityId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            var city = _cityService.GetCityById(cityId).Data;

            if (city == null)
            {
                return(BadRequest("Could not find city"));
            }
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != city.UserId)
            {
                return(Unauthorized());
            }

            var file = photoForCreationDto.Files;

            try
            {
                var uploadResult = new ImageUploadResult();
                if (file.Length > 0)
                {
                    using (var stream = file.OpenReadStream())
                    {
                        var uploadParam = new ImageUploadParams
                        {
                            File = new FileDescription(file.Name, stream)
                        };

                        uploadResult = _cloudinary.Upload(uploadParam);
                    };

                    photoForCreationDto.Url      = uploadResult.Url.ToString();
                    photoForCreationDto.PublicId = uploadResult.PublicId;

                    var photo = _mapper.Map <Photo>(photoForCreationDto);
                    photo.CityId = city.Id;

                    if (!city.Photos.Any(p => p.IsMain))
                    {
                        photo.IsMain = true;
                    }

                    var photoDbResult = _photoService.AddPhotoForCity(photo);

                    if (photoDbResult.Success)
                    {
                        var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                        return(Ok(photoToReturn));
                    }
                    return(BadRequest("Could not add the photo"));
                }
            }

            catch (Exception ex)
            {
                return(BadRequest(ex.Message.ToString()));
            }

            return(BadRequest("Failed"));
        }