public async Task <Photo> Add(string id, PhotoResource photoResource) { //var user = repository.Get(id); var user = await context.Users.FindAsync(id); if (user == null) { return(null); } if (user != null) { var uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); if (!Directory.Exists(uploadsFolder)) { Directory.CreateDirectory(uploadsFolder); } var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(photoResource.PhotoPath.FileName); var filePath = Path.Combine(uploadsFolder, uniqueFileName); photoResource.PhotoPath.CopyTo(new FileStream(filePath, FileMode.Create)); var file = new Photo { PhotoPath = filePath }; //await unitOfWork.CompleteAsync(); var photo = mapper.Map <PhotoResource, Photo>(photoResource); photo.PhotoPath = filePath; user.Photo = photo; await context.SaveChangesAsync(); return(photo); } return(null); }
public async Task <IActionResult> Upload(string id, PhotoResource photoResource) { if (!ModelState.IsValid) { return(BadRequest()); } var resulut = await repository.Add(id, photoResource); return(Ok()); }
public async Task GetPhoto() { // Arrange var seedIds = new List <int> { new Random().Next(1, 50), new Random().Next(51, 100) }; var seedPhotos = SeedPhotos(seedIds); var mockPhotoRepository = new Mock <IPhotoRepository>(); var mockCommentRepository = new Mock <ICommentRepository>(); var mockCategoryRepository = new Mock <ICategoryRepository>(); var mockUserRepository = new Mock <IUserRepository>(); var mockAlbumRepository = new Mock <IAlbumRepository>(); var mockUnitOfWork = new Mock <IUnitOfWork>(); var mockPhotoUploadService = new Mock <IPhotoUploadService>(); var mockHost = new Mock <IWebHostEnvironment>(); mockHost.SetupGet(m => m.WebRootPath).Returns(string.Empty); var mockObjectDetectionService = new Mock <IObjectDetectionService>(); PhotosController controller = new PhotosController(this._mapper, mockPhotoRepository.Object, mockCategoryRepository.Object, mockUserRepository.Object, mockCommentRepository.Object, mockAlbumRepository.Object, mockUnitOfWork.Object, mockPhotoUploadService.Object, mockHost.Object, mockObjectDetectionService.Object); foreach (var seedPhoto in seedPhotos) { var id = seedPhoto.Id; var seedPhotoResource = this._mapper.Map <Photo, PhotoResource>(seedPhoto); mockPhotoRepository.Setup(m => m.GetAsync(id, true)).ReturnsAsync(seedPhoto); seedPhotoResource.BoundingBoxFilePath = string.Format("{0}/{1}", controller.OutputFolderUrl, seedPhotoResource.FilePath); seedPhotoResource.FilePath = string.Format("{0}/{1}", controller.UploadFolderUrl, seedPhotoResource.FilePath); // Act var result = await controller.GetPhoto(id); // Assert Assert.IsType <OkObjectResult>(result); Assert.IsType <PhotoResource>(((OkObjectResult)result).Value); PhotoResource returnedPhotoResource = (PhotoResource)((OkObjectResult)result).Value; Assert.True(returnedPhotoResource.Equals(seedPhotoResource)); } }
public async Task <IActionResult> UpdatePhoto([FromRoute] int id, [FromForm] PhotoResource photoResource) { Photo photo = await photoRepository.GetAsync(id); if (photoResource != null && photo != null) { var userName = User.FindFirstValue(ClaimTypes.Name); if (photo.Author.UserName != userName) { return(Forbid()); } if (string.IsNullOrEmpty(photoResource.Name)) { return(BadRequest()); } if (photoResource.FileToUpload != null) { var fileToUpload = photoResource.FileToUpload; var originalFilePath = photo.FilePath; photo.FilePath = await this.photoUploadService.UploadPhoto(fileToUpload, this.uploadsFolderPath); var dimensions = await this.photoRepository.GetImageDimensions(fileToUpload); photo.Height = dimensions.Height; photo.Width = dimensions.Width; this.photoUploadService.CopyPhoto(photo.FilePath, this.uploadsFolderPath, this.outputFolderPath); if (!string.IsNullOrEmpty(originalFilePath)) { this.photoUploadService.DeletePhoto(originalFilePath, this.uploadsFolderPath, this.outputFolderPath); } } photo.Name = photoResource.Name; photo.LocLng = photoResource.LocLng; photo.LocLat = photoResource.LocLat; photo.CenterLng = photoResource.CenterLng; photo.CenterLat = photoResource.CenterLat; photo.MapZoom = photoResource.MapZoom; var currentCategories = photo.PhotoCategories.ToList(); var currentCategoriesIds = currentCategories.Select(cat => cat.CategoryId); var strSelectedCategories = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString())["PhotoCategories"]; var selectedCategoryResources = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable <CategoryResource> >(strSelectedCategories) ?? new List <CategoryResource>(); var selectedCategoryIds = selectedCategoryResources.Select(cat => cat.Id); var deletedCategoryIds = photo.PhotoCategories.Where(cat => !selectedCategoryIds.Contains(cat.CategoryId)).Select(cat => cat.CategoryId); var newCategoryResources = selectedCategoryResources.Where(selectedCat => !currentCategoriesIds.Contains(selectedCat.Id)); var newCategories = mapper.Map <IEnumerable <CategoryResource>, IEnumerable <PhotoCategory> >(newCategoryResources).ToList(); currentCategories.RemoveAll(c => deletedCategoryIds.Contains(c.CategoryId)); currentCategories.AddRange(newCategories); photo.PhotoCategories = currentCategories; if (photoResource.Album != null && photoResource.Album.Id > 0) { var newAlbum = await this.albumRepository.GetAsync(photoResource.Album.Id, false); if (newAlbum != null) { photo.Album = newAlbum; } else { return(BadRequest()); } } else { photo.Album = null; } photo.ModifiedDate = DateTime.UtcNow; await this.unitOfWork.CompleteAsync(); var outputPhotoResource = mapper.Map <Photo, PhotoResource>(photo); string orgFilePath = outputPhotoResource.FilePath; outputPhotoResource.FilePath = string.Format("{0}/{1}", this.uploadsFolderUrl, orgFilePath); outputPhotoResource.BoundingBoxFilePath = string.Format("{0}/{1}", this.outputFolderUrl, orgFilePath); return(Ok(outputPhotoResource)); } else { return(NotFound()); } }
public async Task <IActionResult> CreatePhoto([FromForm] PhotoResource photoResource) { if (photoResource != null && photoResource.FileToUpload != null) { var photo = this.mapper.Map <PhotoResource, Photo>(photoResource); var fileToUpload = photoResource.FileToUpload; photo.FilePath = await this.photoUploadService.UploadPhoto(fileToUpload, this.uploadsFolderPath); var dimensions = await this.photoRepository.GetImageDimensions(fileToUpload); photo.Height = dimensions.Height; photo.Width = dimensions.Width; string imageFilePath = Path.Combine(this.uploadsFolderPath, photo.FilePath); var boxDicts = this.objectDetectionService.DetectObjectsFromImages(new List <string>() { imageFilePath }, this.uploadsFolderPath, this.outputFolderPath); var labels = boxDicts[imageFilePath].Select(b => b.Label); if (labels.Any()) { var categories = this.categoryRepository.GetByNames(labels); photo.PhotoCategories = categories.Select(cat => new PhotoCategory() { Category = cat, Photo = photo }).ToList(); } var currentUser = new User() { UserName = User.FindFirstValue(ClaimTypes.Name) }; if (photoResource.Album != null && photoResource.Album.Id > 0) { var newAlbum = await this.albumRepository.GetAsync(photoResource.Album.Id, false); if (newAlbum != null) { photo.Album = newAlbum; } else { return(BadRequest()); } } else { photo.Album = null; } photo.Author = this.userRepository.GetOrAdd(currentUser); this.photoRepository.Add(photo); await this.unitOfWork.CompleteAsync(); return(Ok(mapper.Map <Photo, PhotoResource>(photo))); } else { return(NoContent()); } }
public async Task AddPhoto() { // Arrange string seed = Guid.NewGuid().ToString(); string expectedFilePath = string.Format("1_{0}.jpg", seed); var photoUploadService = new Mock <IPhotoUploadService>(); photoUploadService.Setup(m => m.UploadPhoto(It.IsAny <IFormFile>(), It.IsAny <string>())) .ReturnsAsync(expectedFilePath); int expectedWidth = new Random().Next(1, 5000); int expectedHeight = new Random().Next(1, 5000); var mockPhotoRepository = new Mock <IPhotoRepository>(); mockPhotoRepository.Setup(m => m.GetImageDimensions(It.IsAny <IFormFile>())) .ReturnsAsync((expectedHeight, expectedWidth)); var mockCommentRepository = new Mock <ICommentRepository>(); var mockHost = new Mock <IWebHostEnvironment>(); string expectedWebRootPath = seed; mockHost.SetupGet(m => m.WebRootPath).Returns(expectedWebRootPath); IDictionary <string, IList <YoloBoundingBox> > expectedObjectsDict = new Dictionary <string, IList <YoloBoundingBox> >(); string expectedLabel = string.Format("bird_{0}", seed); YoloBoundingBox expectedBoundingBox = new YoloBoundingBox() { Label = expectedLabel }; string expectedKey = Path.Combine(expectedWebRootPath, "uploads", expectedFilePath); expectedObjectsDict.Add(expectedKey, new List <YoloBoundingBox>() { expectedBoundingBox }); var mockObjectDetectionService = new Mock <IObjectDetectionService>(); mockObjectDetectionService.Setup(m => m.DetectObjectsFromImages(It.IsAny <List <string> >(), It.IsAny <string>(), It.IsAny <string>())) .Returns(expectedObjectsDict); var mockCategoryRepository = new Mock <ICategoryRepository>(); Category expectedCategory = new Category() { Name = expectedLabel }; mockCategoryRepository.Setup(m => m.GetByNames(new List <string>() { expectedLabel })) .Returns(new List <Category>() { expectedCategory }); string expectedUserName = string.Format("test_{0}@gmail.com", seed); ControllerContext controllerContext = Utilities.SetupCurrentUserForController(expectedUserName); var mockUserRepository = new Mock <IUserRepository>(); User expectedUser = new User() { Id = seed, UserName = expectedUserName }; mockUserRepository.Setup(m => m.GetOrAdd(It.IsAny <User>())).Returns(expectedUser); var mockAlbumRepository = new Mock <IAlbumRepository>(); var mockUnitOfWork = new Mock <IUnitOfWork>(); PhotosController controller = new PhotosController(this._mapper, mockPhotoRepository.Object, mockCategoryRepository.Object, mockUserRepository.Object, mockCommentRepository.Object, mockAlbumRepository.Object, mockUnitOfWork.Object, photoUploadService.Object, mockHost.Object, mockObjectDetectionService.Object); controller.ControllerContext = controllerContext; PhotoResource originalResource = new PhotoResource() { Id = new Random().Next(1, 100), FileToUpload = new Mock <IFormFile>().Object, Name = seed, LocLng = new Random().Next(1, 100), LocLat = new Random().Next(1, 100), CenterLng = new Random().Next(1, 100), CenterLat = new Random().Next(1, 100), MapZoom = new Random().Next(1, 100), FilePath = expectedFilePath, Width = expectedWidth, Height = expectedHeight, PhotoCategories = new List <CategoryResource>() { new CategoryResource() { Name = expectedLabel } }, Author = new UserResource() { UserName = expectedUserName } }; // Act var result = await controller.CreatePhoto(originalResource); // Assert Assert.IsType <OkObjectResult>(result); Assert.IsType <PhotoResource>(((OkObjectResult)result).Value); PhotoResource returnedPhotoResource = (PhotoResource)((OkObjectResult)result).Value; Assert.True(returnedPhotoResource.Equals(originalResource)); }
/// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public SharedcontactsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { contact = new ContactResource(this); photo = new PhotoResource(this); }
public async Task <IActionResult> UpdatePhotoInformation(int userId, int photoId, PhotoResource resource) { if (!ControllerHelper.IsAllowedUser(userId, User)) { return(Unauthorized()); } var photo = await photoRepo.Get(photoId); if (photo == null) { return(NotFound()); } photo.Name = resource.Name; photo.Description = resource.Description; await unit.CompleteAsync(); return(Ok(mapper.Map <PhotoResource>(photo))); }