예제 #1
0
        public async Task <IActionResult> AddWork([FromBody] WorkDTO workDTO)
        {
            var user = await userManager.FindByNameAsync(currentUserAccessor.GetCurrentUsername());

            if (user != null)
            {
                var work = new Work()
                {
                    Name      = workDTO.Name,
                    Author    = user,
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now,
                    Body      = workDTO.Body,
                    Slug      = workDTO.Name.GenerateSlug()
                };
                List <WorkGenre> workGenres = new List <WorkGenre>();
                foreach (var genre in workDTO.Genres)
                {
                    if (context.Genres.Where(g => g.Name == genre).Any())
                    {
                        workGenres.Add(new WorkGenre()
                        {
                            Genre = context.Genres.Where(g => g.Name == genre).FirstOrDefault(),
                            Work  = work
                        });
                    }
                }
                work.WorkGenres = workGenres;
                context.Works.Add(work);
                user.Works.Add(work);
                await context.SaveChangesAsync();
            }
            return(Ok());
        }
예제 #2
0
            public async Task <CommentDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var activity = await _context.Activities
                               .Include(x => x.Comments)
                               .FirstOrDefaultAsync(x => x.Id == request.ActivityId, cancellationToken);

                if (activity == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Activity = Constants.NOT_FOUND });
                }

                var author = await _context.Users.FirstAsync(x => x.UserName == _currentUserAccessor.GetCurrentUsername());

                var comment = new Comment
                {
                    Author    = author,
                    Body      = request.Comment.Body,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };
                await _context.Comments.AddAsync(comment, cancellationToken);

                activity.Comments.Add(comment);

                await _context.SaveChangesAsync(cancellationToken);

                var commentDto = _mapper.Map <Comment, CommentDto>(comment);

                return(commentDto);
            }
예제 #3
0
            public async Task <ArticleEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                var article = await _context.Articles.FirstOrDefaultAsync(
                    x => x.Slug == request.Slug, cancellationToken);

                if (article == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.NotFound);
                }

                var person = await _context.Persons.FirstOrDefaultAsync(
                    x => x.Username == _currentUserAccessor.GetCurrentUsername(), cancellationToken);

                var favorite = await _context.ArticleFavorites.FirstOrDefaultAsync(
                    x => x.ArticleId == article.ArticleId &&
                    x.PersonId == person.PersonId,
                    cancellationToken
                    );

                if (favorite != null)
                {
                    _context.ArticleFavorites.Remove(favorite);
                    await _context.SaveChangesAsync(cancellationToken);
                }


                return(new ArticleEnvelope(await _context.Articles.GetAllData()
                                           .FirstOrDefaultAsync(
                                               x => x.ArticleId == article.ArticleId,
                                               cancellationToken)));
            }
예제 #4
0
            public async Task <ActivityDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var activity = _mapper.Map <ActivityData, Activity>(request.Activity);

                var username = _currentUserAccessor.GetCurrentUsername();

                var user = _context.Users.FirstOrDefaultAsync(x => x.UserName == username, cancellationToken).Result;

                await _context.Activities.AddAsync(activity, cancellationToken);

                var attendee = new ActivityAttendee
                {
                    AppUser    = user,
                    Activity   = activity,
                    DateJoined = DateTime.Now,
                    IsHost     = true,
                    ActivityId = activity.Id,
                    AppUserId  = user.Id
                };

                await _context.ActivityAttendees.AddAsync(attendee, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var activityToReturn = _mapper.Map <Activity, ActivityDto>(activity);

                return(activityToReturn);
            }
        public async Task <ProfileEnvelope> ReadProfile(string username)
        {
            var currentUserName = _currentUserAccessor.GetCurrentUsername();

            var person = await _context.Persons.AsNoTracking()
                         .FirstOrDefaultAsync(x => x.Username == username);

            if (person == null)
            {
                throw new RestException(HttpStatusCode.NotFound, new { User = Constants.NOT_FOUND });
            }
            var profile = _mapper.Map <Domain.Person, Profile>(person);

            if (currentUserName != null)
            {
                var currentPerson = await _context.Persons
                                    .Include(x => x.Following)
                                    .Include(x => x.Followers)
                                    .FirstOrDefaultAsync(x => x.Username == currentUserName);

                if (currentPerson.Followers.Any(x => x.TargetId == person.PersonId))
                {
                    profile.IsFollowed = true;
                }
            }
            return(new ProfileEnvelope(profile));
        }
예제 #6
0
            public async Task <ProfileEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var target = await _context.Persons.FirstOrDefaultAsync(x => x.Username == message.Username, cancellationToken);

                if (target == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.NotFound);
                }

                var observer = await _context.Persons.FirstOrDefaultAsync(
                    x => x.Username == _currentUserAccessor.GetCurrentUsername(),
                    cancellationToken);

                var followedPeople = await _context.FollowedPeople.FirstOrDefaultAsync(
                    x => x.ObserverId == observer.PersonId &&
                    x.TargetId == target.PersonId, cancellationToken);

                if (followedPeople == null)
                {
                    followedPeople = new Domain.FollowedPeople
                    {
                        Observer   = observer,
                        ObserverId = observer.PersonId,
                        Target     = target,
                        TargetId   = target.PersonId
                    };

                    await _context.FollowedPeople.AddAsync(followedPeople,
                                                           cancellationToken);

                    await _context.SaveChangesAsync(cancellationToken);
                }

                return(await _profileReader.ReadProfile(message.Username));
            }
예제 #7
0
            protected override async Task <Result> HandleCore(Command message)
            {
                var currentUsername = _currentUserAccessor.GetCurrentUsername();

                var user = await SingleAsync(currentUsername);

                if (user == null)
                {
                    return(Result.Fail <Command> ("User does not exist"));
                }

                user.Username = message.Username ?? user.Username;
                user.Email    = message.Email ?? user.Email;

                if (!string.IsNullOrWhiteSpace(message.Password))
                {
                    var salt = Guid.NewGuid().ToByteArray();
                    user.HashedPassword = _passwordHasher.Hash(message.Password, salt);
                    user.Salt           = salt;
                }

                await _context.SaveChangesAsync();

                return(Result.Ok());
            }
예제 #8
0
파일: Create.cs 프로젝트: yminhua/Bloggy
            protected override async Task <Result <Model> > HandleCore(Command message)
            {
                var author = await SingleUserAsync(_currentUserAccessor.GetCurrentUsername());

                if (author == null)
                {
                    return(Result.Fail <Model> ("Author does not exit"));
                }

                var category = await SingleCategoryAsync(message.CategoryId);

                if (category == null)
                {
                    return(Result.Fail <Model> ("Category does not exit"));
                }

                var post = new Post
                {
                    Title       = message.Title,
                    Body        = message.Body,
                    Category    = category,
                    Author      = author,
                    CreatedDate = DateTime.UtcNow
                };

                if (message.Tags != null)
                {
                    var tags     = new List <Tag> ();
                    var postTags = new List <PostTag> ();
                    foreach (var tag in message.Tags)
                    {
                        var t = await SingleTagAsync(tag);

                        if (t == null)
                        {
                            t = new Tag {
                                Name = tag
                            };
                            await _context.Tags.AddAsync(t);

                            await _context.SaveChangesAsync();
                        }
                        tags.Add(t);
                        var pt = new PostTag
                        {
                            Post = post,
                            Tag  = t
                        };
                        postTags.Add(pt);
                    }
                    await _context.PostTags.AddRangeAsync(postTags);
                }
                await _context.Posts.AddAsync(post);

                await _context.SaveChangesAsync();

                var model = _mapper.Map <Post, Model> (post);

                return(Result.Ok(model));
            }
예제 #9
0
 public Task <UserEnvelope> GetCurrent(CancellationToken cancellationToken)
 {
     return(_mediator.Send(new Details.Query()
     {
         Username = _currentUserAccessor.GetCurrentUsername()
     }, cancellationToken));
 }
예제 #10
0
        public async Task <IActionResult> AddComment([FromBody] CommentDTO commentDTO)
        {
            var work = await context.Works.Include(x => x.Comments).Where(x => x.Slug == commentDTO.WorkSlug).FirstOrDefaultAsync();

            if (work == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound, new { Status = "Error", Message = "Cant add comment, work wasnt found" }));
            }
            var user = await userManager.FindByNameAsync(currentUserAccessor.GetCurrentUsername());

            Comment comment = new Comment()
            {
                Author       = user,
                CreationDate = DateTime.Now,
                Value        = commentDTO.Value,
                Work         = work
            };

            work.Comments.Add(comment);
            context.Comments.Add(comment);

            await context.SaveChangesAsync();

            return(Ok());
        }
            public async Task <CommentEnvelope> Handle(Command message)
            {
                var article = await _db.Articles
                              .Include(x => x.Comments)
                              .FirstOrDefaultAsync(x => x.Slug == message.Slug);

                if (article == null)
                {
                    throw new RestException(HttpStatusCode.NotFound);
                }

                var author = await _db.Persons.FirstAsync(x => x.Username == _currentUserAccessor.GetCurrentUsername());

                var comment = new Comment()
                {
                    Author    = author,
                    Body      = message.Comment.Body,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };
                await _db.Comments.AddAsync(comment);

                article.Comments.Add(comment);

                await _db.SaveChangesAsync();

                return(new CommentEnvelope(comment));
            }
예제 #12
0
 public async Task <UserEnvelope> GetCurrent()
 {
     return(await _mediator.Send(new Details.Query()
     {
         Username = _currentUserAccessor.GetCurrentUsername()
     }));
 }
예제 #13
0
            public async Task <CommentDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await userManager.FindByNameAsync(currentUserAccessor.GetCurrentUsername());

                var recipe = await context.Recipes.FirstOrDefaultAsync(x => x.Id == request.RecipeId, cancellationToken : cancellationToken);

                if (recipe == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { message = "Recipe not found" });
                }

                var comment = new Comment()
                {
                    Body      = request.Body,
                    Recipe    = recipe,
                    Author    = user,
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now,
                    Id        = Guid.NewGuid().ToString()
                };

                await context.Comments.AddAsync(comment, cancellationToken);

                if (await context.SaveChangesAsync(cancellationToken) > 0)
                {
                    return(mapper.Map <Comment, CommentDto>(comment));
                }

                throw new Exception("Problem when creating comment");
            }
예제 #14
0
            public async Task <UserEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var currentUsername = _currentUserAccessor.GetCurrentUsername();
                var person          = await _context.Persons
                                      .AsNoTracking()
                                      .FirstOrDefaultAsync(x => x.Username == request.Username, cancellationToken);

                if (person == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { User = Constants.NOT_FOUND });
                }

                if (_currentUserAccessor.GetCurrentUserType().Equals(UserConstants.User) &&
                    !currentUsername.Equals(person.Username)
                    )
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { User = Constants.UNAUTHERIZE });
                }

                var user = _mapper.Map <Person, User>(person);

                user.Type = UserConstants.GetUserTypeString(person.UserType);

                if (!user.Username.Equals(currentUsername))
                {
                    return(new UserEnvelope(user));
                }
                // To mark the profile UI is current user
                user.IsCurrentUser = true;
                return(new UserEnvelope(user));
            }
예제 #15
0
            public async Task <ArticleEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var article = await _context.Articles.FirstOrDefaultAsync(x => x.Slug == message.Slug, cancellationToken);

                if (article == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Article = Constants.NotFound });
                }

                var person = await _context.Persons
                             .FirstOrDefaultAsync(x => x.Username == _currentUserAccessor.GetCurrentUsername(), cancellationToken);

                var favorite = await _context.ArticleFavorites
                               .FirstOrDefaultAsync(x => x.ArticleId == article.ArticleId &&
                                                    x.PersonId == person.PersonId, cancellationToken);

                if (favorite == null)
                {
                    favorite = new ArticleFavorite
                    {
                        Article   = article,
                        ArticleId = article.ArticleId,
                        Person    = person,
                        PersonId  = person.PersonId
                    };

                    await _context.ArticleFavorites.AddAsync(favorite, cancellationToken);

                    await _context.SaveChangesAsync(cancellationToken);
                }

                return(new ArticleEnvelope(await _context.Articles
                                           .GetAllData()
                                           .FirstOrDefaultAsync(x => x.ArticleId == article.ArticleId, cancellationToken)));
            }
예제 #16
0
파일: Create.cs 프로젝트: yminhua/Bloggy
            protected override async Task <Result <Model> > HandleCore(Command message)
            {
                var post = await SinglePostAsync(message.PostId);

                if (post == null)
                {
                    return(Result.Fail <Model> ("Post does not exit"));
                }

                var comment = new Comment
                {
                    Author      = await SingleUserAsync(_currentUserAccessor.GetCurrentUsername()),
                    Body        = message.Body,
                    CreatedDate = DateTime.UtcNow
                };

                await _context.Comments.AddAsync(comment);

                post.Comments.Add(comment);

                await _context.SaveChangesAsync();

                var model = _mapper.Map <Comment, Model> (comment);

                return(Result.Ok(model));
            }
예제 #17
0
            public async Task <CommentEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var article = await _context.Articles
                              .Include(x => x.Comments)
                              .FirstOrDefaultAsync(x => x.Slug == message.Slug, cancellationToken);

                if (article == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, new { Article = Constants.NOT_FOUND });
                }

                var author = await _context.Persons.FirstAsync(x => x.Username == _currentUserAccessor.GetCurrentUsername(), cancellationToken);

                var comment = new Comment()
                {
                    Author    = author,
                    Body      = message.Comment.Body,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };
                await _context.Comments.AddAsync(comment, cancellationToken);

                article.Comments.Add(comment);

                await _context.SaveChangesAsync(cancellationToken);

                return(new CommentEnvelope(comment));
            }
예제 #18
0
            public async Task <Photo> Handle(Command request, CancellationToken cancellationToken)
            {
                var result = photoAccessor.CreatePhoto(request.File);

                var user = await userManager.FindByNameAsync(currentUserAccessor.GetCurrentUsername());

                user.Photo = result;

                context.Images.Add(user.Photo);

                await context.SaveChangesAsync(cancellationToken);

                return(user.Photo);
            }
예제 #19
0
            public async Task <ActivityDto> Handle(Command request, CancellationToken cancellationToken)
            {
                // get the current event from db
                var activity = await _context.Activities
                               .Include(x => x.Attendees)
                               .ThenInclude(a => a.AppUser)
                               .FirstOrDefaultAsync(x => x.Id == request.Id);

                var username = _currentUserAccessor.GetCurrentUsername();
                // get the currently logged in user
                var user = await _userManager.FindByNameAsync(_currentUserAccessor.GetCurrentUsername());

                // create the attendance - check to see if it exists first
                var attendance = await _context.ActivityAttendees.FirstOrDefaultAsync(
                    x => x.ActivityId == activity.Id && x.AppUserId == user.Id, cancellationToken);

                if (attendance == null)
                {
                    attendance = new ActivityAttendee()
                    {
                        Activity   = activity,
                        ActivityId = activity.Id,
                        AppUser    = user,
                        AppUserId  = user.Id,
                        DateJoined = DateTime.Now,
                        IsHost     = false
                    };

                    await _context.ActivityAttendees.AddAsync(attendance, cancellationToken);

                    await _context.SaveChangesAsync(cancellationToken);
                }

                var activityDto = _mapper.Map <Activity, ActivityDto>(activity);

                return(activityDto);
            }
예제 #20
0
            public async Task <ArticleEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var author = await _context.Persons
                             .FirstAsync(x => x.Username == _currentUserAccessor.GetCurrentUsername(), cancellationToken);

                var tags = new List <Tag>();

                foreach (var tag in message.Article.TagList ?? Enumerable.Empty <string>())
                {
                    var t = await _context.Tags.FindAsync(tag);

                    if (t == null)
                    {
                        t = new Tag {
                            TagId = tag
                        };

                        await _context.Tags.AddAsync(t, cancellationToken);

                        await _context.SaveChangesAsync(cancellationToken);
                    }

                    tags.Add(t);
                }

                var article = new Article
                {
                    Author      = author,
                    Body        = message.Article.Body,
                    CreatedAt   = DateTime.UtcNow,
                    UpdatedAt   = DateTime.UtcNow,
                    Description = message.Article.Description,
                    Title       = message.Article.Title,
                    Slug        = message.Article.Title.GenerateSlug()
                };

                await _context.Articles.AddAsync(article, cancellationToken);

                await _context.ArticleTags
                .AddRangeAsync(tags.Select(x => new ArticleTag
                {
                    Article = article,
                    Tag     = x
                }), cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(new ArticleEnvelope(article));
            }
예제 #21
0
        public async Task <IActionResult> Details([FromRoute] string username)
        {
            var currentUsername = _currentUserAccessor.GetCurrentUsername();
            var query           = new DetailsQ.Query();

            if (currentUsername != null && username == currentUsername)
            {
                query = new DetailsQ.Query {
                    Username = _currentUserAccessor.GetCurrentUsername()
                };
            }
            else
            {
                query = new DetailsQ.Query {
                    Username = username
                };
            }

            var result = await _mediator.Send(query);

            return(result.IsSuccess ?
                   (IActionResult)Ok(result.Value) :
                   (IActionResult)BadRequest(result.Error));
        }
예제 #22
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await userManager.FindByNameAsync(currentUserAccessor.GetCurrentUsername());

                var recipe = new Recipe()
                {
                    Author         = user,
                    CreatedAt      = DateTime.Now,
                    UpdatedAt      = DateTime.Now,
                    Servings       = request.Servings,
                    Description    = request.Description,
                    Id             = Guid.NewGuid().ToString(),
                    Title          = request.Title,
                    TimeOfCooking  = request.TimeOfCooking,
                    Ingredients    = request.Ingredients,
                    Cuisine        = context.Cuisines.FirstOrDefault(x => x.Name == request.Cuisine),
                    NutritionValue = request.NutritionValue
                };

                if (Enum.TryParse(typeof(Domain.Difficulty), request.Difficulty, out object res))
                {
                    if (res != null)
                    {
                        recipe.Difficulty = (Domain.Difficulty)res;
                    }
                }
                else
                {
                    throw new RestException(System.Net.HttpStatusCode.BadRequest, new { message = "Wrong difficulty" });
                }

                recipe.Categories = new List <Category>();
                foreach (var cat in request.Categories)
                {
                    recipe.Categories.Add(context.Categories.FirstOrDefault(x => x.Name == cat.Name));
                }

                if (request.MainImage == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.BadRequest, new { message = "Main image is required" });
                }

                recipe.MainImage = photoAccessor.CreatePhoto(request.MainImage);

                if (request.Images is { Count : > 0 })
예제 #23
0
파일: Edit.cs 프로젝트: f1nzer/yapp
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var currentUsername = _currentUserAccessor.GetCurrentUsername();
                var person          = await _context.Persons.Where(x => x.UserName == currentUsername).FirstOrDefaultAsync(cancellationToken);

                person.UserName = message.User.UserName ?? person.UserName;
                person.Email    = message.User.Email ?? person.Email;
                person.Image    = message.User.Image ?? person.Image;

                if (!string.IsNullOrWhiteSpace(message.User.Password))
                {
                    var salt = Guid.NewGuid().ToByteArray();
                    person.Hash = _passwordHasher.Hash(message.User.Password, salt);
                    person.Salt = salt;
                }

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserEnvelope(_mapper.Map <Domain.Person, User>(person)));
            }
예제 #24
0
            public async Task <UserEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                var currentUserName = _currentUserAccessor.GetCurrentUsername();
                var person          = await _context.Persons
                                      .Where(x => x.Username == currentUserName)
                                      .FirstOrDefaultAsync(cancellationToken);

                person.Username   = request.User.Username ?? person.Username;
                person.ProfileUrl = request.User.ProfileUrl ?? person.ProfileUrl;
                person.Phone      = request.User.Phone ?? person.Phone;
                person.UserType   = request.User.UserType == 0 ? person.UserType : request.User.UserType;

                if (!string.IsNullOrWhiteSpace(request.User.Password))
                {
                    person.Password = _passwordHasher.Hash(request.User.Password);
                }

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserEnvelope(_mapper.Map <Person, User>(person)));
            }
예제 #25
0
 public IActionResult getCourseByCategory([FromRoute] int id)
 {
     //authenticated users
     if (!string.IsNullOrWhiteSpace(_currentUserAccessor.GetCurrentUsername()))
     {
         //for authenticated user get all inactive and active courses
         var results = new ObjectResult(_courseRepository.GetCourseByCategory(id, isAuthenticated: true))
         {
             StatusCode = (int)HttpStatusCode.OK
         };
         return(results);
     }
     else
     {
         var results = new ObjectResult(_courseRepository.GetCourseByCategory(id))
         {
             StatusCode = (int)HttpStatusCode.OK
         };
         return(results);
     }
 }
예제 #26
0
            public async Task <EventEnvelope> Handle(Command request, CancellationToken cancellationToken)
            {
                var currentUser =
                    await _context.Users.FirstAsync(x => x.UserName == _currentUserAccessor.GetCurrentUsername(),
                                                    cancellationToken);

                var evt = new Event
                {
                    Title       = request.Event.Title,
                    Category    = request.Event.Category,
                    Description = request.Event.Description,
                    Date        = request.Event.Date,
                    City        = request.Event.City,
                    Venue       = request.Event.Venue,
                    Image       = request.Event.Image,
                    Latitude    = request.Event.Latitude,
                    Longitude   = request.Event.Longitude,
                };

                // save event so that can get event id to add attendees to
                await _context.Events.AddAsync(evt, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var attendee = new EventAttendee
                {
                    AppUser    = currentUser,
                    Event      = evt,
                    IsHost     = true,
                    DateJoined = DateTime.Now
                };

                await _context.EventAttendees.AddAsync(attendee, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var eventToReturn = _mapper.Map <Event, EventToReturnDto>(evt);

                return(new EventEnvelope(eventToReturn));
            }
예제 #27
0
 public IActionResult GetKeyValue()
 {
     //authenticated users
     if (!string.IsNullOrWhiteSpace(_currentUserAccessor.GetCurrentUsername()))
     {
         //for authenticated user get all inactive and active categories
         var results = new ObjectResult(_categoryRepository.GetkeyValue(isAuthenticated: true))
         {
             StatusCode = (int)HttpStatusCode.OK
         };
         return(results);
     }
     else
     {
         //for non authenticated user get all  active categories
         var results = new ObjectResult(_categoryRepository.GetkeyValue())
         {
             StatusCode = (int)HttpStatusCode.OK
         };
         return(results);
     }
 }
예제 #28
0
            public async Task <RecipesEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await context.Users.Include(x => x.RecipeFavorites)
                           .ThenInclude(x => x.Recipe)
                           .ThenInclude(x => x.MainImage)
                           .Include(x => x.RecipeFavorites)
                           .ThenInclude(x => x.Recipe)
                           .ThenInclude(x => x.Author)
                           .SingleOrDefaultAsync(x => x.UserName == currentUserAccessor.GetCurrentUsername(), cancellationToken: cancellationToken);

                var recipes = user.RecipeFavorites.OrderBy(x => x.Recipe.UpdatedAt).Select(o => o.Recipe).ToList();

                if (recipes == null)
                {
                    throw new RestException(System.Net.HttpStatusCode.NotFound, "Could not find favorite recipes");
                }

                var recipesToReturn = mapper.Map <List <Recipe>, List <ShortRecipeDto> >(recipes);


                return(new RecipesEnvelope(recipesToReturn, recipesToReturn.Count));
            }
예제 #29
0
            public async Task <PhotoDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var username = _currentUserAccessor.GetCurrentUsername();

                var user = await _context.Users.Include(p => p.Photos)
                           .FirstOrDefaultAsync(u => u.UserName == username, cancellationToken);

                var photo = _cloudinary.AddPhotoForUser(request.Photo.File);

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

                user.Photos.Add(photo);

                await _context.SaveChangesAsync(cancellationToken);

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

                return(photoDto);
            }
예제 #30
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var username = _currentUserAccessor.GetCurrentUsername();

                var user = await _context.Users.Include(p => p.Photos)
                           .FirstOrDefaultAsync(u => u.UserName == username, cancellationToken);

                if (user.Photos.All(p => p.Id != request.Id))
                {
                    throw new RestException(HttpStatusCode.Unauthorized);
                }

                var photoFromDb = await _context.Photos.FirstOrDefaultAsync(p => p.Id == request.Id, cancellationToken);

                if (photoFromDb.IsMain)
                {
                    throw new RestException(HttpStatusCode.BadRequest);
                }

                _cloudinary.DeletePhotoForUser(photoFromDb);

                return(Unit.Value);
            }