Exemplo n.º 1
0
        protected override async Task <PostView> HandleInput(PostUpdateParams input)
        {
            using (var connection = database.GetConnection()) {
                IPostRepo postRepo = database.GetRepo <IPostRepo>(connection);
                Post?     post     = await postRepo.FindById(input.PostId);

                if (post == null)
                {
                    throw new InvalidOperationException();
                }

                if (!(await this.postPermissionHandler.HasPermission(input.User, PermissionAction.UpdatePost, post)))
                {
                    throw new AuthorizationException();
                }

                if (post.Type == PostType.Link)
                {
                    throw new InvalidOperationException("Link posts can't be updated.");
                }

                if (post.WasDeleted)
                {
                    throw new InvalidOperationException("Post has already been deleted.");
                }


                post.Body = input.Body;
                await postRepo.Update(post);

                return(postMapper.Map(post));
            }
        }
Exemplo n.º 2
0
        private static Post ParseYamlFront(string markdown)
        {
            // Thanks https://markheath.net/post/markdown-html-yaml-front-matter
            var yamlDeserializer = new DeserializerBuilder()
                                   .WithNamingConvention(CamelCaseNamingConvention.Instance)
                                   .WithTypeConverter(new DateTimeConverter())
                                   .Build();

            try
            {
                Post?post = null;
                using var input = new StringReader(markdown);
                var parser = new Parser(input);
                parser.Consume <StreamStart>();
                parser.Consume <DocumentStart>();
                post = yamlDeserializer.Deserialize <Post>(parser);
                parser.Consume <DocumentEnd>();
                // assign completed markdown
                post.Content = markdown;
                return(post);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
Exemplo n.º 3
0
        public virtual Task <Post?> GetPostBySlug(string slug)
        {
            bool isAdmin = IsAdmin();
            Post?post    = _cache.FirstOrDefault(p => p.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase));

            return(Task.FromResult(
                       post is null || (post.PubDate > DateTime.UtcNow && !isAdmin) || (!post.IsPublished && !isAdmin)
                ? null
                : post));
        }
Exemplo n.º 4
0
        protected async override Task <CommentView> HandleInput(CommentCreateParams input)
        {
            using (var connection = database.GetConnection()) {
                IPostRepo    postRepo    = database.GetRepo <IPostRepo>(connection);
                ICommentRepo commentRepo = database.GetRepo <ICommentRepo>(connection);
                IVoteRepo    voteRepo    = database.GetRepo <IVoteRepo>(connection);

                // Locate the post to ensure it actually exists.
                Post?post = await postRepo.FindById(input.PostId);

                if (post == null)
                {
                    throw new InvalidOperationException();
                }

                using (var transaction = connection.BeginTransaction()) {
                    Comment comment = new Comment()
                    {
                        User         = input.User,
                        PostId       = post.Id,
                        Body         = input.Body,
                        CreationDate = DateTime.UtcNow
                    };

                    // Set the parent comment if needed.
                    if (input.ParentId != 0)
                    {
                        comment.Parent = await commentRepo.FindById(input.ParentId);
                    }

                    // Update the comment count cache on the post.
                    post.CommentCount++;

                    comment.Upvotes++;
                    await commentRepo.Add(comment);

                    Vote upvote = new Vote()
                    {
                        User         = input.User,
                        ResourceId   = comment.Id,
                        ResourceType = VoteResourceType.Comment,
                        Direction    = VoteDirection.Up
                    };

                    await postRepo.Update(post);

                    await voteRepo.Add(upvote);

                    comment.Vote = upvote;
                    transaction.Commit();

                    return(commentMapper.Map(comment));
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Check t osee if the post matches another object.
        /// </summary>
        /// <param name="obj">The other object to check.</param>
        /// <returns>True if the post matches</returns>
        public override bool Equals(object obj)
        {
            Post?p = obj as Post;

            if (p == null)
            {
                return(false);
            }

            return(Equals(p));
        }
Exemplo n.º 6
0
    public void Delete(int postId)
    {
        Post?post = context.Posts.Find(postId);

        if (post == null)
        {
            return;
        }
        context.Posts.Remove(post);
        context.SaveChanges();
    }
Exemplo n.º 7
0
        public async Task Delete(int postId, User user)
        {
            Post?p = await repo.FindById(postId);

            if (p == null)
            {
                throw new NotFoundException($"No post with Id {postId} found.");
            }

            p.Delete();
            await repo.Update(p);

            await bus.Dispatch(new PostDeleteEvent(p));
        }
Exemplo n.º 8
0
        public async Task <ActionResult <Post> > Index(int id)
        {
            var  query = _context.Posts.AsQueryable();
            Post?post  = null;

            if (!User.IsEditorOrPublisher())
            {
                query = query.Where(p => p.PublishDate != null);
            }

            post = await query.FirstOrDefaultAsync(p => p.Id == id);

            return((post != null) ? post : NotFound());
        }
Exemplo n.º 9
0
        //[Test]
        public void SimpleReadTransactionTest()
        {
            using var t = _srv.GetReadTransaction();

            Post?post = t.Read <Post, long>(1L);

            Assert.IsInstanceOf <Post>(post);
            Assert.AreEqual("Test", post !.Title);

            Comment?comment = t.Read <Comment>(1L);

            Assert.IsInstanceOf <Comment>(comment);
            Assert.AreEqual("It works!", comment !.Content);
        }
Exemplo n.º 10
0
        //[Test]
        public async Task FullyAsyncReadTransactionTest()
        {
            await using var t = _srv.GetReadTransaction();

            Post?post = await t.ReadAsync <Post, long>(1L);

            Assert.IsInstanceOf <Post>(post);
            Assert.AreEqual("Test", post !.Title);

            Comment?comment = await t.ReadAsync <Comment>(1L);

            Assert.IsInstanceOf <Comment>(comment);
            Assert.AreEqual("It works!", comment !.Content);
        }
Exemplo n.º 11
0
    public Post Update(Post post)
    {
        Post?existing = context.Posts.Find(post.Id);

        if (existing == null)
        {
            throw new Exception();
        }

        EntityEntry <Post> entry = context.Entry(existing);

        entry.CurrentValues.SetValues(post);
        context.SaveChanges();
        return(entry.Entity);
    }
Exemplo n.º 12
0
        public async Task Handle(VoteOnPostEvent domainEvent)
        {
            Post?p = await repo.FindById(domainEvent.PostId);

            if (p == null)
            {
                throw new InvalidOperationException();
            }

            if (domainEvent.OldVote != null)
            {
                p.Votes.RemoveVote(domainEvent.OldVote.Direction);
            }

            p.Votes.AddVote(domainEvent.NewVote.Direction);
            await repo.Update(p);
        }
Exemplo n.º 13
0
        protected override async Task <bool> AfterSaveAsync(Post item, PropertyChange[]?changes = null,
                                                            Post?oldItem = null, IBioRepositoryOperationContext?operationContext = null)
        {
            var version = new ContentVersion {
                Id = Guid.NewGuid(), ContentId = item.Id
            };

            version.SetContent(item);
            if (operationContext?.User != null)
            {
                version.ChangeAuthorId = operationContext.User.Id;
            }

            DbContext.Add(version);
            await DbContext.SaveChangesAsync();

            return(await base.AfterSaveAsync(item, changes, oldItem, operationContext));
        }
Exemplo n.º 14
0
        public async Task <bool> TryEditPostAsync(int postId, string newMessage)
        {
            _logger.LogInformation($"Attempting to edit post with id {postId}, new message: {newMessage}");

            if (newMessage.Length == 0)
            {
                _logger.LogError($"Editing post failed, message is empty!");
                return(false);
            }

            Post?post = await _repository.GetAsync(post => post.Id == postId);

            if (post == null)
            {
                _logger.LogError($"There is no post with id: {postId}");

                return(false);
            }

            IdentityUser?user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User);

            if (user == null)
            {
                _logger.LogError("Invalid current user: user is null");

                return(false);
            }

            if (user != post.Author)
            {
                _logger.LogError($"Invalid current user: {user}. Post author: {post.Author}");

                return(false);
            }

            post.Message = newMessage;
            await _forumContext.SaveChangesAsync();

            _logger.LogInformation($"Edited post with id {postId}, new message: {newMessage}");

            return(true);
        }
Exemplo n.º 15
0
 public static IActionResult GetPostFun(
     [HttpTrigger(
          authLevel: AuthorizationLevel.Function,
          "get",
          Route = "posts/{author}/{id}"
          )]
     HttpRequest req,
     [CosmosDB(
          databaseName: ConnectionParams.DatabaseName,
          collectionName: "Posts",
          ConnectionStringSetting = ConnectionParams.DbConnectionStringSetting,
          PartitionKey = "{author}",
          Id = "{id}"
          )]
     Post?post,
     string id
     ) =>
 post == null
         ? new NotFoundObjectResult(
     new { message = $"Couldn't find a post with id {id}" }
     )
         : (IActionResult) new OkObjectResult(post);
Exemplo n.º 16
0
        protected async override Task <PostView?> HandleInput(FindByValueParams <int> input)
        {
            using (var connection = database.GetConnection()) {
                IPostRepo postRepo = database.GetRepo <IPostRepo>(connection);
                IVoteRepo voteRepo = database.GetRepo <IVoteRepo>(connection);

                Post?post = await postRepo.FindById(input.Value);

                if (post == null)
                {
                    return(null);
                }

                //Pull in the vote if needed.
                if (input.User != null)
                {
                    post.Vote = await voteRepo.FindByUserAndPost(input.User.Username, input.Value);
                }

                return(postMapper.Map(post));
            }
        }
Exemplo n.º 17
0
        protected override async Task <PostView?> HandleInput(PostDeleteParams input)
        {
            using (var connection = database.GetConnection()) {
                IPostRepo postRepo = database.GetRepo <IPostRepo>(connection);

                Post?p = await postRepo.FindById(input.PostId);

                if (p == null)
                {
                    throw new InvalidOperationException();
                }

                if (!(await this.permissionHandler.HasPermission(input.User, PermissionAction.DeletePost, p)))
                {
                    throw new AuthorizationException();
                }

                await postRepo.Delete(p);

                return(postMapper.Map(p));
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PostPayloadBase"/> class.
 /// </summary>
 /// <param name="post">The post.</param>
 protected PostPayloadBase(Post post)
 {
     Post = post;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Get a completed post from the provided HTML div node.
        /// </summary>
        /// <param name="postDiv">Div node that contains the post.</param>
        /// <returns>Returns a post object with required information.</returns>
        private Post?GetPost(HtmlNode postDiv, IQuest quest)
        {
            string author = "";
            string id;
            string text;
            int    number = 0;

            var postTable = postDiv.Descendants("table").FirstOrDefault(a => a.Id.StartsWith("post", StringComparison.Ordinal));

            if (postTable == null)
            {
                return(null);
            }

            id = postTable.Id.Substring("post".Length);

            string postAuthorDivID = "postmenu_" + id;

            var authorAnchor = postTable.OwnerDocument.GetElementbyId(postAuthorDivID).Element("a");

            if (authorAnchor != null)
            {
                author = authorAnchor.InnerText;

                // ??
                if (authorAnchor.Element("span") != null)
                {
                    author = authorAnchor.Element("span").InnerText;
                }
            }

            string postNumberAnchorID = "postcount" + id;

            var anchor = postTable.OwnerDocument.GetElementbyId(postNumberAnchorID);

            if (anchor != null)
            {
                string postNumText = anchor.GetAttributeValue("name", "");
                number = int.Parse(postNumText);
            }

            string postMessageId = "post_message_" + id;

            var postContents = postTable.OwnerDocument.GetElementbyId(postMessageId);

            // Predicate filtering out elements that we don't want to include
            var exclusion = ForumPostTextConverter.GetClassExclusionPredicate("bbcode_quote");

            // Get the full post text.
            text = ForumPostTextConverter.ExtractPostText(postContents, exclusion, Host);


            Post?post = null;

            try
            {
                Origin origin = new Origin(author, id, number, Site, GetPermalinkForId(id));
                post = new Post(origin, text);
            }
            catch
            {
                //post = null;
            }

            return(post);
        }