Exemplo n.º 1
0
        public async Task <IActionResult> AddPhotoForUser(int userid,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userid != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var userFromRepo = await _repo.GetUser(userid);

            var file         = photoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

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

            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }
            return(BadRequest("Could not added the photo!"));
        }
Exemplo n.º 2
0
        //Route("api/users/{userId}/photos")
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId, true);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)                            // had file
            {
                using (var stream = file.OpenReadStream()){ // when complete method we depose file out off server
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")// crop image to square
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            //if(!userFromRepo.Photos.Any(u => u.IsMain))
            //    photo.IsMain = true;

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);               // photo need to generate id propery first, so we implements after SaveAll
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn)); // you will see the result when test with angular
            }
            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoData)
        {
            var user = await this.users.GetUser(userId);

            if (user == null)
            {
                return(this.BadRequest("Could not find user!"));
            }

            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != user.Id)
            {
                return(this.Unauthorized());
            }

            var file         = photoData.File;
            var uploadResult = new ImageUploadResult();

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

                    uploadResult = this.cloudinary.Upload(uploadParams);
                }
            }

            photoData.Url      = uploadResult.Uri.ToString();
            photoData.PublicId = uploadResult.PublicId;

            var photoId = await this.photos
                          .AddPhoto(userId, photoData.Url, photoData.Description, photoData.PublicId);

            var photoToReturn = await this.photos.ById(photoId);

            return(this.CreatedAtRoute("GetPhoto", new { id = photoId }, photoToReturn));
        }
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoForCreationDto)
        {
            // if the id passed is not the user from the token we throw unauthorised
            if (!IsUserAuthorized(userId))
            {
                return(Unauthorized());
            }

            var dbUser = await _datingRepository.GetUser(userId);

            var file = photoForCreationDto.File;

            string cloudinaryUrl      = string.Empty;
            string cloudinaryPublicId = string.Empty;

            if (file.Length > 0)
            {
                UploadPhoto(file, out cloudinaryUrl, out cloudinaryPublicId);
            }

            photoForCreationDto.Url      = cloudinaryUrl;
            photoForCreationDto.PublicId = cloudinaryPublicId;

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

            if (!dbUser.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            dbUser.Photos.Add(photo);

            if (await _datingRepository.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
        private PhotoForCreationDto UploadingToCloudinary(PhotoForCreationDto photoDto)
        {
            var file         = photoDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = this.cloudinary.Upload(uploadParams);
                }
            }

            photoDto.Url      = uploadResult.Uri.ToString();
            photoDto.PublicId = uploadResult.PublicId;
            return(photoDto);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> AddPhoto(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userForRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            if (file == null || file.Length == 0)
            {
                return(Content("file not selected"));
            }

            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            photoForCreationDto.Url = Path.Combine("/images", file.FileName);
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            if (!userForRepo.Photos.Any(o => o.IsMain))
            {
                photo.IsMain = true;
            }
            userForRepo.Photos.Add(photo);
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }
            return(BadRequest("Could not add the photo"));
        }
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            //check user is authorized:
            //compare token in route to user's token.
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            var uploadedResult = new ImageUploadResult(); //a Cloudinary class.

            //upload the file if there is something to upload:
            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream()) //using because it's a stream and will auto-dispose when done.
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    //the uploadParams are just the info we pass along with the upload.
                    //the first one IDs the file
                    //the second one is a Cloudinary transformation to make a square of the face.

                    uploadedResult = _cloudinary.Upload(uploadParams);
                    //uploadedResult is something this gets back from Cloudinary.
                }
            }

            //map what comes back from Cloudinary to the Dto properties:
            photoForCreationDto.Url      = uploadedResult.Url.ToString();
            photoForCreationDto.PublicId = uploadedResult.PublicId;

            //then map the Dto properties to the Photo class:
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            //if it's the first photo uploaded, it will be set to main photo.
            //otherwise, not set.
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            //each new photo is added to the Photos collection.
            userFromRepo.Photos.Add(photo);


            //upon a success save, return success/info message.
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                //with a Post, you _could_ just return Ok()
                //but much better is this, to confirm the item was posted and where:
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
                //that basically gets the info about the photo by calling GetPhoto() and returning it.
            }

            //"else"
            return(BadRequest("Something went wrong - photo not added."));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoDto)
        {
            // get the user from the repo
            var user = await _repo.GetUser(userId);

            // check if the user is null then return badrequest
            if (user == null)
            {
                return(BadRequest("Could not find user"));
            }

            // get the current userid
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            // checked if the user is the
            // actual current user
            if (currentUserId != user.Id)
            {
                return(Unauthorized());
            }

            var file = photoDto.File;

            // variable to store the result of our upload to cloudinary
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // this will allow us to read our
                // uploaded file
                using (var stream = file.OpenReadStream())
                {
                    // initialize cloudinary image upload parameters
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),
                        // apply tranformation that will crop the photos
                        // when uploading long photos and set gravity to face
                        // so that it will focus on it
                        Transformation = new Transformation()
                                         .Width(500)
                                         .Height(500)
                                         .Crop("fill")
                                         .Gravity("face")
                    };

                    // use the cloudinary upload method to
                    // actually uploud our file in cloudinary platform
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            ;

            photoDto.Url      = uploadResult.Uri.ToString();
            photoDto.PublicId = uploadResult.PublicId;

            // map our photoDto to our actual
            // photo enitity
            var photo = _mapper.Map <Photo>(photoDto);

            photo.User = user;

            // decide for main photo if theres none
            if (!user.Photos.Any(m => m.IsMain))
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            // persist the changes to database
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // return createdAtroute
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 9
0
        [HttpPost] // note that the paramter userId is already set in the main route config at the top of this file, so that's where the first arg is coming from
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // the claim types on a user which contain the authorized user's id is stored as a string and it needs to be parsed to an into for comparison to the id in the url param
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;
            // this variable is used to store the result we get bak from Cloudinary
            var uploadResult = new ImageUploadResult();

            // check that there is something inside the file first: (Length is number of bytes)
            if (file.Length > 0)
            {
                // Read the file into memory - using is used here to dispose of the file in memory used in this filestream once the method is done
                //OpenReadStream reads the file into memory
                using (var stream = file.OpenReadStream())
                {
                    // create a Cloudinary compatible upload object using the stream read into memory to send to Cloudinary
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),
                        // use the transformation to crop the image and focus on the users face if the file is too long
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };
                    uploadResult = _cloudinary.Upload(uploadParams);
                };
            }

            //Now start populating the Dto with information from the upload result from Cloudinary
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;
            // map the dto into the photo model based on the new properties just added.  the first arg passed in is the destination and the second arg passed into the method is the source
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // if the user has no photos then none are main - check this and if so, then make the first photo uploaded the main photo for the user
            if (!userFromRepo.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                //NOTE: the photo will not have an id generated by the db until after the save is complete, so it is mapped here inside the if on successful save.
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // response from a post should return a CreatedAtRoute response which automatically does include a location header with the location of the created resource (the url to your api to get the photo - myapi.com/api/users/1/photos)
                // you can use this location to perform a get request to that endpoint
                // the first overload in this method is the route to get a photo - this is created up above in this class,
                // first parameter is you need to give the route a NAme to pass in which is done above on the route config
                //the second param or third overload is the id of the photo and core 3.0 also needs the userId
                //third param is the photo itself, use the dto to return the mapped props we want
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not update Photo."));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            /* if the passed in ID of the route doesn't match the ID in token, return unauthorized */
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            /* get user data from repo */
            var userFromRepo = await _repo.GetUser(userId, true);

            var file = photoForCreationDto.File;

            //var uploadResult = new ImageUploadResult();
            // if (file.Length > 0)
            // {
            //     // read the file into memory
            //     using (var stream = file.OpenReadStream())
            //     {
            //         var uploadParams = new ImageUploadParams()
            //         {
            //             File = new FileDescription(file.Name, stream),
            //             Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
            //             // if image is large, it focus on the face of the image
            //             // and crop the image around the face to target size
            //         };

            //         uploadResult = _cloudinary.Upload(uploadParams);
            //     }
            // }
            // photoForCreationDto.Url = uploadResult.Uri.ToString();
            // photoForCreationDto.PublicId = uploadResult.PublicId;

            try
            {
                var folderName = Path.Combine("StaticFiles", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    var uri        = new Uri(HttpContext.Request.GetDisplayUrl());
                    var domainName = uri.GetLeftPart(UriPartial.Authority); //get http://localhost:5000
                    var fileName   = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath   = Path.Combine(pathToSave, fileName);
                    photoForCreationDto.Url = domainName + Path.AltDirectorySeparatorChar +
                                              Path.Combine(folderName, fileName).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    //photoForCreationDto.PublicId = domainName;

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                    //return Ok(new { dbPath });
                }
                else
                {
                    return(BadRequest("Upload file is empty"));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }

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

            // if the photo is the first photo, set it as main photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                // suppose to return CreatedAtRoute with location header about the created resource
                // ie. the route to get individua,l photo
                //return Ok(); //temporary use Ok for now
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            /*
             *   we need to match the user attempting to update his profile matching the id which part of the token in the server
             */
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            //uploadResult is storing the result we getting back from Cloudinary
            var uploadResult = new ImageUploadResult();

            //if the file length we getting from the user is > 0 the we read it.
            if (file.Length > 0)
            {
                //stream read the file loaded into memory!
                using (var stream = file.OpenReadStream())
                {
                    //we provide Cloudinary params as an ImageUploadParams object!
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    //uploadResult is storing the result we getting back from Cloudinary
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            //fill in the info we got from Cloudinary response : url to photo in Cloudinary + publicId
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            //map the photoForCreationDto to Photo object for persistance.
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            //photo.IsMain = !userFroRepo.Photos.Any(u => u.IsMain)
            //set main photo to true if the first photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                //we return to the user the CreatedAtRoute with the location header with the location of created result.
                //we have to provide the root to get an individual photo for the current user (the photo is stored in cloudinary!!!)
                return(CreatedAtRoute(/*string routename = */ "GetPhoto",
                                      /*routeValue= id of the photo*/ new { id = photo.Id },
                                      /*objectValue = entity to return*/ photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // Check if the user that passed the token is the actual user by the Id
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // Get the user from the inputted id
            var userFromRepo = await _repo.GetUser(userId);

            // Store the dto file data into a file var
            var file = photoForCreationDto.File;

            // Store the image upload response into a var
            var uploadResult = new ImageUploadResult();

            // If there is actually data in the dto file prop
            if (file.Length > 0)
            {
                // Use a file stream reader
                using (var stream = file.OpenReadStream())
                {
                    // Set upload parameters for Cloudinary
                    var uploadParams = new ImageUploadParams()
                    {
                        // Get file description data from Cloudinary for the file to be uploaded
                        File = new FileDescription(file.Name, stream),
                        // Transform the photo using specific parameters
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // Upload the photo to cloudninary using the parameters above
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // Set the photo creation dto url prop to the upload result uri
            photoForCreationDto.Url = uploadResult.Uri.ToString();

            // Set the photo creation dto publicid prop to the upload publicid
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // Map the photo for creation dto to the photo model
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // If the user has no photos that are set as main (no photos)
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                // Set this photo to be the main photo
                photo.IsMain = true;
            }

            // Add the photo data to the post
            userFromRepo.Photos.Add(photo);

            // Attempt to save the upload
            if (await _repo.SaveAll())
            {
                // Map the photo to the photo to return dto to modify the return data
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // Return CreatedAtRoute using the GetPhoto route, user id and photo id prop, and the mapped photo to return
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            // If the upload failed to save
            return(BadRequest("Could not add the photo."));
        }
Exemplo n.º 13
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            //check if the user id attempting update is a part of the token
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            //get the actual file
            var file = photoForCreationDto.File;

            //results from cloudinary
            var uploadResult = new ImageUploadResult();

            //check if theres a file or not
            if (file.Length > 0)
            {
                //read the file to memmory
                using (var stream = file.OpenReadStream())
                {
                    //create cloudinary upload params
                    var uploadParams = new ImageUploadParams()
                    {
                        //get file
                        File = new FileDescription(file.Name, stream),
                        //tranform the large image to square size
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    //upload results from cloudinary
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            //filling the fields
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            //mapping the values
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            //if users doesnt have any photo make it as main photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            //adding the photo
            userFromRepo.Photos.Add(photo);

            //saves the photo
            if (await _repo.SaveAll())
            {
                //this photo variable wont have an id if we use this outside this if statement
                //once it saved properly it will return an id
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // Считываем данные пользователя из базы данных
            var userFromRepo = await _repo.GetUser(userId);

            var file         = photoForCreationDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // Всегда, когда мы работаем с большими объёмами данных, что
                // часто происходит при использовании stream, следует использовать
                // using, чтобы данные были максимально быстро выгружены из
                // оперативной памяти
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // Сохраняем в базу данных информацию об изображении, которую
            // нам вернул сервис Cloudinary: публичный Url, публичный
            // идентификатор файла, и т.д.
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // На основании полученных данных от Angular-приложения и от сервиса
            // Cloudinary, формируем объект типа Photo
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // Если у пользователя ещё не назначен основной файл, то назначаем
            // загруженный на сервис Cloudinary
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // Сохраняем данные об изображении в базу данных
            userFromRepo.Photos.Add(photo);
            if (await _repo.SaveAll())
            {
                // Метод CreatedAtRoute() генерирует код ответа HTTP Status 201,
                // который означает "Ресурс был успешно создан". Этот код ответа
                // отличается от 200 тем, что содержит поле "Location" - указывающее
                // на URL созданного документа. Чтобы корректно создать URL,
                // методу нужно знать фактическое имя обработчика адреса из
                // "Location", который указывается в первом параметре вызова
                // "GetPhoto". Второй параметр указывает на значение дополнительного
                // параметра обработчика GetPhoto(id). Третий параметр - объект,
                // который должен быть возвращён как JSON-Документ
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm]  PhotoForCreationDto photoForCreationDto)
        {
            // as we are authorising we want to check the token - copy the authorisation frm UsersController
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            // use the variable to store result we get back from cloudinary - comes from CloudinaryDotNet.Actions;
            var uploadResult = new ImageUploadResult();

            // check if the file contains something
            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),
                        // Another thing we want to transform any image to a square image
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                    // at this time we will get uploadResult from Cloudinary
                }
            }

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

            // map the photoForCreationDto into our Photo
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // If this is first photo then set this as the main photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // Add the photo to the repo
            userFromRepo.Photos.Add(photo);

            // save the repo
            if (await _repo.SaveAll())
            {
                // If the save is successfull we want to return the photo object (photoToReturn)
                // when save is successfull the SqlLite will create an Id on the photo
                // map the photo to the PhotoForReturnDtop
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // to return the photo object (photoToReturn), the createdAtRoute call is required
                // The CreatedAtRoute overload we are using takes 3 parameters:
                // 1.  The name of the route to get the resource that has been created.
                // 2.  The parameters needed to be passed to the route to get the resource (in this case the ID)
                // 3.  The actual resource we want to return.
                // Parameters 1 and 2 allow the response to contain the route
                // and params needed to get the individual response in the header
                // and the third parameter is the photo we are returning.
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }
            ;

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // first check the user id against the token to make sure the user logged in is user uploading photos
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId, true);

            // using a dto to send photos from our api to cloudinary
            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            // make sure theres a photo to upload and then stream it to cloudinary
            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    // set upload params, we will transform it to be a square image and focus on face only
                    // using cloudinary settings
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // upload photo to cloudinary
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // after upload we now have the public url and id to view photo with
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // use the auto mapper to set the dto object to a photo object
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // if the user has not uploaded any photos yet, set the first one they upload to "main"
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // set the photo to the user
            userFromRepo.Photos.Add(photo);

            // save the repo
            if (await _repo.SaveAll())
            {
                // since the photo id doesnt exist until the phot is saved in the sql lite db
                // we dont map until after the save all has succeded
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                // we need to use created at route to return the photo, so we use the below method
                // param 1 calls the http get function we define above
                // param 2 is a new object with the params
                // param 3 is the mapped photo object
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add photo."));
        }
        public async Task <IActionResult> AddPhotoForUser(
            int userId,
            [FromForm] PhotoForCreationDto photoForCreationDto
            )
        {
            // Verify if the id is matched which we have in the token
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            // getting file from incoming request
            var file = photoForCreationDto.File;

            // image uploader object
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),

                        // if image is large: for transformation(crop image and focus on face)
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // After uploading media, we have response back
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // using that response
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // Now we map our Photo Dto with actual Photo model class
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // if this uploading photo is the first photo then we set it to Main
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // adding photo into table
            userFromRepo.Photos.Add(photo);

            // if save is successfull
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                // Now here we want the data which we have saved in db to return as response
                // So here we're calling above HttpGet method whose name is GetPhoto
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Couldn't add the photo"));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> AddPhotoForUserAsync(
            int userId,
            [FromForm]
            PhotoForCreationDto photoForCreationDto
            )
        {
            var isRequestUserUpdatingUser = userId == int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (!isRequestUserUpdatingUser)
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repository.GetUserAsync(userId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file != null && file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            // here is where errror NullReferenceException: Object reference not set to an instance of an object.
//            DatingApp.API.Controllers.PhotosController.AddPhotoForUser(int userId, PhotoForCreationDto photoForCreationDto) in PhotosController.cs
            else
            {
                return(BadRequest("no file was uploaded"));
            }

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

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

            var doesUserHaveMainPhoto = userFromRepo.Photos.Any(u => u.IsMain);

            if (!doesUserHaveMainPhoto)
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);


            if (await _repository.SaveAllAsync())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                // TODO-Tom: replace with a created at route response.
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo."));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            //Using [Apicontroller] at the creation of the class doesn't allow netcore to identify
            //where the photoForCreationDto is coming, so we need to add [FromForm] on the parameter
            //so netcore can identify it is coming from the form
            //compares the id of the user in the context and the id passed on the httpput
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            //gets user from the repo
            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                //using for disposing memory once completed its use
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        //Transformation is used to crop an image, focusing on the face of the user,  that might be very large
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                //Had to create new object photo, current photo has user as a navigation property which is not ok,
                //that is why had to make all steps on GetPhoto so we can map a different object
                //This is created inside the if given that the saveAll is the one that
                //would create the id for the object on SQL
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                //Need to provide the location of the object created (route)
                //Object route values like Id
                //Entity returning -> photo object
                //After NetCore 3.0, the second parameter needs all route parameters
                //so needed to add the userid...
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id, userId = photo.UserId }, photoToReturn));
            }

            return(BadRequest("could not add the photo"));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> AddPhotoForUser(int userid, PhotoForCreationDto photoDto)
        {
            var user = await _repo.GetUser(userid);

            if (user == null)
            {
                return(BadRequest("Could not find user"));
            }

            // get the current user
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != user.Id)
            {
                return(Unauthorized());
            }

            var file = photoDto.File;

            // check cloudinary for any confusion
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // used for reading uploaded file
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    //upload file
                    uploadResult = _cloudinary.Upload(uploadParams);
                }

                photoDto.Url      = uploadResult.Uri.ToString();
                photoDto.PublicId = uploadResult.PublicId;


                //mapping our photo to photodto(PhotoforCreation)
                var photo = _mapper.Map <Photo>(photoDto);
                //assign the user to our photo
                photo.User = user;

                // check if the user does not have a main pic
                if (!user.Photos.Any(m => m.isMain))
                {
                    photo.isMain = true;
                }

                //adds the photo
                user.Photos.Add(photo);

                if (await _repo.SaveAll())
                {
                    // map it
                    var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                    //return some data for the user
                    return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
                }
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // Compare the userID of the token to the one the user is attempting to upload to
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var file = photoForCreationDto.File;

            // This will be used to store the result from cloudinary
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // Because this is a file stream we ahve to use using.
                // File.OpenReadStream will open a stream to read the file into memory
                using (var stream = file.OpenReadStream())
                {
                    // Create params for uploading the photo to Cloudinary
                    var uploadParam = new ImageUploadParams()
                    {
                        // pass in the file anem and the stream of data
                        File = new FileDescription(file.Name, stream),
                        // transfomr the file in case it too long
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // Upload the actual photo.
                    uploadResult = _cloudinary.Upload(uploadParam);
                }
            }

            // Now that we've uploaded the photo we can get the URL and the PublicID of the photo and add it in to our photoForCreationDto
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // Map the photoForCreation we recieved into a Photo object for uploading to database.
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // Get ther user becuaes we will need to use the user info.
            var userFromRepo = await _repo.GetUser(userId, true);

            // Check if the user has a main photo already, if they don't, set this new photo to be their main photo.
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);


            if (await _repo.SaveAll())
            {
                // Now that the save is successfull our photo will have an ID generated by SQL.
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
                FaceDto assetsFromPhoto;
                using (var faceClient = new HttpClient())
                {
                    Uri         uri            = new Uri("https://face-finders.cognitiveservices.azure.com/face/v1.0/detect?returnFaceId=false&returnFaceAttributes=facialHair,glasses,hair,makeup");
                    var         photoParameter = "{\"url\": \"" + photo.Url + "\"}";
                    HttpContent content        = new StringContent(photoParameter, Encoding.UTF8, "application/json");
                    content.Headers.Add("Ocp-Apim-Subscription-Key", "a18f920438d74a0fa740f4532d342fb4");
                    faceClient.DefaultRequestHeaders.Add("Host", "face-finders.cognitiveservices.azure.com");

                    HttpResponseMessage response = await faceClient.PostAsync(uri, content);

                    string body = await response.Content.ReadAsStringAsync();

                    List <FaceDto> facesDto = JsonConvert.DeserializeObject <List <FaceDto> >(body);
                    assetsFromPhoto = facesDto[0];
                }

                var templateFromRepo = await _repo.GetUsersTemplate(userId);

                var template = _mapper.Map <FaceForTemplateDto>(assetsFromPhoto);

                templateFromRepo.FacialHair = template.FacialHair;
                templateFromRepo.Glasses    = template.Glasses;
                templateFromRepo.MakeUp     = template.MakeUp;
                templateFromRepo.Hair       = template.Hair;
            }

            userFromRepo.Photos.Add(photo);


            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Nie udało się dodać zdjęcia"));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // .... User from token mathces user from request route so I can't update photo of turd to sameone else's profile .....
            //...... User is controller property, NOT my User !!!! ....
            // ... NameIdentifier is a claim optional property assigned in Startup -> ConfigureSerrvices -> JWT initialization: new Claim(ClaimTypes.NameIdentifier, _user.Id.ToString()),
            //.... getting User id from claims
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            //... get my account
            var userFromRepo = await _repo.GetUser(userId);

            //... IFileForm represents a physical file sent with the HttpRequest (with lenth in bytes etc...)
            var file = photoForCreationDto.File;

            //... prepare pointer and instance  of RESULT for storing the result from cloud after upload
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    //... ImageUploadParams - Cloudinary libraries
                    var uploadParams = new ImageUploadParams()
                    {
                        //... FileDescription - Cloudinary libraries
                        File = new FileDescription(file.FileName, stream),
                        //... OPTIONALY if photo is too big Cloudinary will transform it and crop arounf the face and shit and store it .
                        Transformation = new Transformation()
                                         .Width(500)
                                         .Height(500)
                                         .Crop("fill")
                                         .Gravity("face")
                    };

                    //... UPLOADING the photo ! ...
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            //... POPULATE DTO by upload result
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            //... and populate domain model
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            //... find if there is MAIN PHOTO set already in User in Repostory we are pointed to,
            //... if not then set uploaded photo as MAIN
            if (!userFromRepo.Photos.Any(p => p.IsMain))
            {
                photo.IsMain = true;
            }

            //... add photo into photo-collection in User model ...
            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                //... result is f.e.: "http://res.cloudinary.com/cembo/image/upload/v1557112028/au7cvae5hyzvqbmrbgw1.jpg"
                var result = CreatedAtRoute("GetPhoto", new { id = photoToReturn.Id }, photoToReturn);

                return(result);
            }
            ;

            return(BadRequest("Could not add the photo."));
        }
Exemplo n.º 24
0
        public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // we need to compare the id of the path to the users id thats being passed in as part of their token
            // if the user id doesnt match the id in the token then an unauthrorized is given
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // get user from repos
            var userFromRepo = await _repo.GetUser(userId, true);

            // one of the properties inside photoForCreationDto should be the file itself
            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // reads file into memory,
                // since this is going to be a file stream, we'll use 'using' so that we can dispose of the file in memory once we completed this method
                using (var stream = file.OpenReadStream())
                {
                    // give cloudinary our upload param
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),
                        // we want to transform the image so that if we upload an incredibly long photo of a user for instance,
                        // its going to crop the image automatically for us and focus in on the face and crop the area around the face and store a square image
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // response from cloudinary upload
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // start populating other fields inside photoForCreationDto
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // map photoForCreationDto into the photo model
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // when a user uploads a photo this might be an additional photo to their other photos, or first photo and if so then we want to set it to be their main photo

            // user doesnt have a main photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // .Net Core 3.0 - we need to provide all route parameters
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // The first thing that we want to do is to check the user that is
            // attempting to update their profile matches the token that the
            // service is receiving. On the AuthController at line #77, we are
            // setting the ClaimTypes.NameIdentifier equal to the user identifier
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId, true);

            // Store the file that will be send to the storage
            var file = photoForCreationDto.File;

            // Store the result that we get back from Cloudinary
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // Read the file into a memory and dispose it right after using
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams
                    {
                        File = new FileDescription(file.Name, stream),
                        // Transform the image that if we have created a very long photo
                        // for instance of the user, Cloudinary is gonna crop the image
                        // for us focusing on the face and crop the image around the face
                        // and return a square image
                        Transformation = new Transformation()
                                         .Width(500).Height(500)
                                         .Crop("fill")
                                         .Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

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

            // Check if this is the first photo the user is uploading
            if (!userFromRepo.Photos.Any(a => a.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                // We will create a photo to return object since we cannot return "var photo"
                // object because it contains the user navigation properties
                // We must have this inside the SaveAll() so that we can have the photo Id
                // generated by the sql server.
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // Because this is an HttpPost, what we are supposed to return is a
                // CreatedAtRoute so that we will return a location header with the location
                // of the created result.
                // This will return an Http status code of 201.
                // In the first parameter, we need to provide it a string of routeName which
                // means we need to provide the location of the resource we have just
                // created which also means we need
                // to provide a "route" to actually get an individual photo ---
                // The second parameter needs an object routeValues and in this case, we need
                // to pass the Id of the photo we are going to return
                // The third parameter is the object value which is the entity that
                // we are actually returning which is our photo object
                return(CreatedAtRoute("GetPhoto", new { id = photoToReturn.Id },
                                      photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId, true);

            // photo from upload form
            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    // prepare image object upload to cloudinary
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // upload image and get the result back (e.g. Uri and publicId)
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // add Uri and PublicId to photo creation object
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // map photo creation object to photo object (databse)
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // mark photo as main, if it is the first upload/photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // add photo to user object
            userFromRepo.Photos.Add(photo);

            // save back to database
            // if succeed, we have an (photo) id
            if (await _repo.SaveAll())
            {
                // prepare photo object for return without user object (relationship)
                var photoForReturn = _mapper.Map <PhotoForReturnDto>(photo);
                // return a "201 Created" by execute a HttpGet with routename "GetPhoto"
                // This task will get the photo(ForReturn) object by its id
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoForReturn));
            }

            return(BadRequest("Could add the photo"));
        }
Exemplo n.º 27
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoDto)
        {
            var user = await _repo.GetUser(userId);

            if (user == null)
            {
                return(BadRequest("Could not find user"));
            }

            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (currentUserId != user.Id)
            {
                return(Unauthorized());
            }

            var file = photoDto.File;
            //ImageUploadResult is model from cloudinary also
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                //within the using statement the object can only read, it can not be assigned or modified
                //Using statement provide a convenient syntax the ensures the correct use of IDisposable object
                //unmanaged resources such as window handles, or open files and streams.
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            photoDto.Url      = uploadResult.Uri.ToString();
            photoDto.PublicId = uploadResult.PublicId;

            var photo = _mapper.Map <Photo>(photoDto);

            photo.User = user;

            if (!user.Photos.Any(m => m.IsMain))
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            //if have any to save to database. then map the photo model to PhotoForReturn.
            //create a new route for client to call. the model to return to client side is PhotoForReturnDto
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add photo"));
        }
Exemplo n.º 28
0
        public async Task <IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoForCreationDto)
        {
            // Authorise the user
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(file.Name, stream),

                        // If the file is ridiculously big, then transform it...
                        // we want it to fit in a square.
                        Transformation = new Transformation()
                                         .Height(500)
                                         .Width(500)
                                         .Crop("fill")
                                         .Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

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

            photoForCreationDto.PublicId = uploadResult.PublicId;

            // Map the DTO into the Photo class:
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // If it's the first photo, then by default it is the main photo:
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true; // Make it the default photo
            }
            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                // You must have the Id of the photo in order to return it, so the
                // automapping must be done after the SaveAll().
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // Use the overload with the
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            return(BadRequest("Could not add the photo"));
        }
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // Check if the user submitting this request is the current user that is passed into this method
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // Get user from the database repo
            var userFromRepo = await _repo.GetUser(userId);

            // Store the file information
            var file = photoForCreationDto.File;

            // Instantiating the image upload result object
            var uploadResult = new ImageUploadResult();

            // Checking the file length is valid
            if (file.Length > 0)
            {
                // Create a file stream
                using (var stream = file.OpenReadStream())
                {
                    //Create upload parameters including the Transformation parameter that will ensure we get a square photo
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // Upload the photo to the cloudinary API
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            // Add the cloudinary URL and PublicId
            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // Map the photoForCreationDto into a Photo and store it in a photo variable
            var photo = _mapper.Map <Photo>(photoForCreationDto);

            // Checking if the user has any other main photos if not then set this uploaded photo as the main photo
            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // Add the photo record to the database repository
            userFromRepo.Photos.Add(photo);

            // Attempt to save the new photo object to our daabase and return the photoToReturnDto to the client
            if (await _repo.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, photoToReturn));
            }

            // If we have any issues saving tell the user
            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> AddPhotoForUser
            (int userId, [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            // Check if the current User is the one that passed the token to the server
            // Trying to match passed id to what is in their token ... see authController line 79
            // User = check the passed token and get info from it .. we are [Authorize] this request
            //
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            // Call the repo method to return a single user from the repo <-> DB based on Id
            //
            User userFromRepo = await _repo.GetUser(userId);

            // call Dto instance that is being passed and get its File property (has photo)
            //
            IFormFile file = photoForCreationDto.File;

            //To hold the results we get back from Cloudinary.  ImageUploadResult= Cloudinary class
            //
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                // read this file into memory then dispose whne done
                //
                using (var stream = file.OpenReadStream())
                {
                    // Populate the "uploadResult" from Cloudinary w/ the Photo from Client
                    // IFormFile as file which we will read as a stream, get name tied to this object
                    // Transform the Photo to meet our shape/size specs for the site
                    // Use all of these as params which we use to initialize uploadresult
                    // This is what we are going to pass to cloud storage
                    //
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    // Calls method to upload to 3rd party storage + store in local variable
                    //
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            //These are to populate Dto w/ results returned back from Cloudinay
            //
            photoForCreationDto.Url      = uploadResult.Url.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            // map returned results from our Dto -> Photo object
            //
            Photo photo = _mapper.Map <Photo>(photoForCreationDto);

            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            // Track changes to the User object which now has updated Photo
            // details that we are adding from Dto (has upload response + isMain)
            //
            userFromRepo.Photos.Add(photo);



            if (await _repo.SaveAll())
            {
                // Convert updated Photo object to Dto because, we want the return
                // status code 201 also, include header info about this photo
                // Once saved the photo will have a DB generated Id
                //
                var phototoReturn = _mapper.Map <PhotoForReturnDto>(photo);

                // Show location header of created resource
                // string routeName = Name [httpGet{"{id}"}, Nme = "GetPhoto"]
                // object routeValues= new object with values (params) that are required
                // by this route to call the controler method
                // object value = The object being created and returned
                return(CreatedAtRoute("GetPhoto",
                                      new { userId = userId, id = photo.Id }, phototoReturn));
            }

            else
            {
                return(BadRequest("Could not add the Photo"));
            }
        }