public ActionResult Create(PostEditModel model)
        {
            ViewBag.Title = "Create";
            if (ModelState.IsValid)
            {
                var url = PostHelpers.MakeUrl(_dateTime.Today.Year, _dateTime.Today.Month, _dateTime.Today.Day, model.Title);

                _postRepository.Create(new Post
                {
                    AuthorId         = _securityHelper.CurrentUser.Id,
                    DraftBody        = model.Body,
                    DraftDescription = model.Description,
                    Posted           = _dateTime.Now,
                    DraftTitle       = model.Title,
                    Status           = PostStatus.Draft,
                    Path             = url,
                    Canonical        = model.Reposted ? model.CanonicalUrl : "/" + url,
                    ExcludeFromFeed  = false,
                    PostGuid         = Guid.NewGuid(),
                    BlogId           = CurrentBlog.Id
                });

                return(RedirectToAction("Index", "Dashboard"));
            }
            return(View("Edit", model));
        }
        public async Task <string> Handle(CreatePostWithFileCommand request, CancellationToken cancellationToken)
        {
            Domain.Entities.Post post =
                await _postService.CreatePostWithFileAsync(request.UserId, request.CreatePostWithFileDto);

            if (!PostHelpers.IsContentFile(request.CreatePostWithFileDto.Content))
            {
                throw new HttpStatusCodeException(HttpStatusCode.BadRequest, "Post creation failed");
            }

            FileData data = BaseHelpers.GetContentFileData <Domain.Entities.Post>(
                request.CreatePostWithFileDto.Content, post.Id
                );

            if (post.ContentType.Equals(data.FileName.GetContentType()))
            {
                await _blobService.UploadImageBlobAsync(data.Content, data.FileName);

                request.CreatePostWithFileDto.Content     = data.FileName;
                request.CreatePostWithFileDto.ContentType = data.FileName.GetContentType();

                await _postService.UpdatePostAsync(post, new UpdatePostDto
                {
                    Content = request.CreatePostWithFileDto.Content,
                    Title   = post.Title,
                });
            }
            else
            {
                throw new HttpStatusCodeException(HttpStatusCode.BadRequest,
                                                  "Can not update content type of a post");
            }

            return(post.Id);
        }
Esempio n. 3
0
        public async Task <PostViewModel> GetPostByIdAsync(string postId)
        {
            var post = await _postRepository.GetByConditionAsync <PostViewModel>(x => x.Id == postId,
                                                                                 PostHelpers.GetPostMapperConfiguration());

            Guard.Against.NullItem(post, nameof(post));

            return(post);
        }
        public ActionResult RebuildAllUrls()
        {
            var posts = _postRepository.PostsForBlog(CurrentBlog.Id).ToList();

            foreach (var post in posts)
            {
                post.Path = PostHelpers.MakeUrl(post.Posted.Year, post.Posted.Month, post.Posted.Day, post.Title);
                _postRepository.Update(post);
            }
            return(RedirectToAction("Index", "Dashboard"));
        }
Esempio n. 5
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CanUpdatePostAuthorizationRequirement requirement,
                                                       Sharporum.Domain.Entities.Post post)
        {
            if (PostHelpers.UserOwnsPost(context.User.FindFirstValue("sub"), post.AuthorId))
            {
                context.Succeed(requirement);
                return(Task.CompletedTask);
            }

            context.Fail();
            return(Task.CompletedTask);
        }
Esempio n. 6
0
        public async Task <IEnumerable <PostViewModel> > GetNewsFeedPosts(string userId, PostSearchParams searchParams)
        {
            Community community =
                await _communityRepository.GetByConditionAsync(x => x.Name == searchParams.CommunityName);

            Guard.Against.NullItem(community, nameof(community));

            searchParams.Followers = await _userRepository.ListUserFollowingsAsync(userId);

            var specification = new PostFilterSpecification(searchParams);

            return(await _postRepository.ListAsync <PostViewModel>(specification,
                                                                   PostHelpers.GetPostMapperConfiguration()));
        }
Esempio n. 7
0
            public async Task <PostsEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var site = await _context.Sites.FirstOrDefaultAsync(x => x.SiteType == SiteTypeEnum.Blog);

                // pagination, sorting and filtering
                var helperTDO = await PostHelpers.PaginateAndFilterAndSort(
                    _context,
                    request.Limit, request.Offset,
                    request.Field, request.Order,
                    request.FilterKey, request.FilterValue,
                    request.StartDate, request.EndDate,
                    request.StartNumber, request.EndNumber
                    );

                var maxAttachmentsNumber = helperTDO.PostCount > 0 ?
                                           _context.Posts
                                           .Where(x => x.Type == PostTypeEnum.Posts)
                                           .OrderByDescending(x => x.PostAttachments.Count)
                                           .First().PostAttachments.Count :
                                           0;
                var maxViewCount = helperTDO.PostCount > 0 ? await
                                   _context.Posts
                                   .Where(x => x.Type == PostTypeEnum.Posts)
                                   .MaxAsync(x => x.ViewCount) :
                                   0;

                var maxComments = helperTDO.PostCount > 0 ?
                                  _context.Posts
                                  .Where(x => x.Type == PostTypeEnum.Posts)
                                  .OrderByDescending(x => x.Comments.Count)
                                  .First().Comments.Count :
                                  0;

                await _logger.LogActivity(
                    site.Id,
                    ActivityCodeEnum.PostList,
                    ActivitySeverityEnum.Information,
                    ActivityObjectEnum.Post,
                    "A list of all posts has been requested and recieved by user");

                return(new PostsEnvelope
                {
                    Posts = _mapper.Map <List <PostDto> >(helperTDO.PostsEnvelope),
                    PostCount = helperTDO.PostCount,
                    MaxAttachmentsNumber = maxAttachmentsNumber,
                    MaxViewCount = maxViewCount,
                    MaxComments = maxComments,
                });
            }
Esempio n. 8
0
        public async Task <IEnumerable <PostViewModel> > GetPostsAsync(PostSearchParams searchParams)
        {
            User user = await _userManager.FindByIdAsync(searchParams.UserId);

            Guard.Against.NullItem(user, nameof(user));

            Community community =
                await _communityRepository.GetByConditionAsync(x => x.Name == searchParams.CommunityName);

            Guard.Against.NullItem(community, nameof(community));

            var specification = new PostFilterSpecification(searchParams);

            return(await _postRepository.ListAsync <PostViewModel>(specification,
                                                                   PostHelpers.GetPostMapperConfiguration()));
        }
Esempio n. 9
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CanDeletePostAuthorizationRequirement requirement,
                                                       Sharporum.Domain.Entities.Post post)
        {
            string roleBase = $"{nameof(Community)}/{post.CommunityId}";

            if (context.User.HasClaim(JwtClaimTypes.Role, $"{roleBase}/{Roles.Admin}") ||
                context.User.HasClaim(JwtClaimTypes.Role, $"{roleBase}/{Roles.Moderator}") ||
                PostHelpers.UserOwnsPost(context.User.FindFirstValue("sub"), post.AuthorId))
            {
                context.Succeed(requirement);
                return(Task.CompletedTask);
            }

            context.Fail();
            return(Task.CompletedTask);
        }
Esempio n. 10
0
        public async Task <PostViewModel> Handle(UpdatePostCommand request,
                                                 CancellationToken cancellationToken)
        {
            if (PostHelpers.IsContentFile(request.UpdatePostDto.Content) &&
                !request.Post.ContentType.Equals("application/text"))
            {
                FileData data = BaseHelpers.GetContentFileData <Domain.Entities.Post>(
                    request.UpdatePostDto.Content, request.Post.Id
                    );
                request.UpdatePostDto.Content = data.FileName;
                if (request.Post.ContentType.Equals(request.UpdatePostDto.Content.GetContentType()))
                {
                    await _blobService.UploadImageBlobAsync(data.Content, data.FileName);
                }
            }

            return(await _postService.UpdatePostAsync(request.Post, request.UpdatePostDto));
        }
        public async Task <IActionResult> CreatePost(Post post)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit", post));
            }

            var    newPost  = new Post();
            string formTags = Request.Form["categories"];

            newPost.Title = post.Title.Trim();
            if (!string.IsNullOrWhiteSpace(post.Slug))
            {
                newPost.Slug = PostHelpers.CreateSlug(post.Slug);
            }

            newPost.PubDate      = DateTime.UtcNow;
            newPost.IsPublished  = post.IsPublished;
            newPost.Content      = post.Content.Trim();
            newPost.Excerpt      = PostHelpers.ShortenAndFormatText(post.Excerpt.Trim(), _excerptMaxLength);
            newPost.LastModified = DateTime.UtcNow;
            //  Do we have a cover photo?
            //  Check the file length and don't bother attempting to read it if the file contains no content.
            if (HttpContext.Request.Form.Files.Count != 0)
            {
                var newCoverPhoto = HttpContext.Request.Form.Files[0];
                //  yes
                if (newCoverPhoto.Length > 0)
                {
                    newPost.PostCoverPhoto = await _blog.SaveCoverPhotoAsync(newPost.Slug, newCoverPhoto);
                }
            }


            //  1.  We need to save post to db first to get id
            await _blog.SavePostAsync(newPost);

            //  2.  Save files to disk
            await _blog.SaveFilesToDiskAsync(newPost);

            //  3   Update any changes from SaveFileToDiskAsync()
            await _blog.UpdatePostAsync(newPost);



            //  Update post media
            var oldMedia = await _blogContext.PostMedias
                           .AsNoTracking()
                           .Where(x => x.PostId == newPost.Id)
                           .ToListAsync();

            var postMedia = await _blog.UpdatePostMediaAsync(newPost, oldMedia);

            //  new media?
            if (postMedia.newMedia.Any())
            {
                foreach (var media in postMedia.newMedia)
                {
                    await _blogContext.PostMedias.AddAsync(media);

                    await _blogContext.SaveChangesAsync();
                }
            }
            //  oldMedia
            if (postMedia.oldMedia.Any())
            {
                foreach (var media in postMedia.oldMedia)
                {
                    //await _blogContext.PostMedias.r(media)
                    var old = await _blogContext.PostMedias
                              .AsNoTracking()
                              .FirstOrDefaultAsync(x => x.Id == media.Id);

                    if (old == null)
                    {
                        continue;
                    }
                    _blogContext.PostMedias.Remove(old);
                    await _blogContext.SaveChangesAsync();
                }
            }

            //  Tags
            //  has tags, add them
            if (!string.IsNullOrEmpty(formTags))
            {
                var tags = new List <PostTag>();
                if (!string.IsNullOrEmpty(formTags))
                {
                    tags = await formTags.Split(',').ToList().ProcessTagsAsync(newPost.Id);

                    if (tags.Any())
                    {
                        foreach (var t in tags)
                        {
                            await _blog.SavePostTagAsync(t);
                        }
                    }
                }
            }



            var redirectLink = $"/Console/BlogPreview/{newPost.Id}";

            return(Redirect(redirectLink));
        }
        public async Task <IActionResult> Edit(Post post)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit", post));
            }

            var existing = await _blog.GetPostByIdAsync(post.Id);

            if (existing == null)
            {
                return(NotFound());
            }

            string formTags = Request.Form["categories"];

            existing.IsPublished  = post.IsPublished;
            existing.Content      = post.Content.Trim();
            existing.Excerpt      = PostHelpers.ShortenAndFormatText(post.Excerpt.Trim(), _excerptMaxLength);
            existing.LastModified = DateTime.UtcNow;

            var oldMedia = await _blogContext.PostMedias
                           .AsNoTracking()
                           .Where(x => x.PostId == existing.Id)
                           .ToListAsync();

            //  1.  Save Files to disk
            await _blog.SaveFilesToDiskAsync(existing);

            await _blog.UpdatePostAsync(existing);

            //  Update post media
            var postMedia = await _blog.UpdatePostMediaAsync(existing, oldMedia);

            //  new media?
            if (postMedia.newMedia.Any())
            {
                foreach (var media in postMedia.newMedia)
                {
                    await _blogContext.PostMedias.AddAsync(media);

                    await _blogContext.SaveChangesAsync();
                }
            }
            //  oldMedia
            if (postMedia.oldMedia.Any())
            {
                foreach (var media in postMedia.oldMedia)
                {
                    // remove from db
                    var old = await _blogContext.PostMedias
                              .AsNoTracking()
                              .FirstOrDefaultAsync(x => x.Id == media.Id);

                    if (old == null)
                    {
                        continue;
                    }
                    _blogContext.PostMedias.Remove(old);
                    await _blogContext.SaveChangesAsync();

                    //  Remove from file store
                    //await _blog.DeletePostFileAsync()
                }
            }

            var newTags = await formTags.Split(',').ToList().ProcessTagsAsync(existing.Id);

            var oldTags = await _blog.GetPostTags(post.Id);

            // tags equal? take no action
            if (!newTags.SequenceEqual(oldTags, new DefaultPostTagComparer()))
            {
                // delete old tags
                foreach (var t in oldTags)
                {
                    await _blog.DeletePostTagAsync(t.Id);
                }

                //  add new tags
                if (newTags.Any())
                {
                    foreach (var t in newTags)
                    {
                        await _blog.SavePostTagAsync(t);
                    }
                }
            }


            var redirectLink = $"/Console/BlogPreview/{post.Id}";

            return(Redirect(redirectLink));
        }
Esempio n. 13
0
        protected override void Seed(StaticVoid.Blog.Data.BlogContext context)
        {
#if DEBUG
#if !DISABLE_SEED
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            var admin = new User
            {
                Id = 1,
                ClaimedIdentifier = "",
                Email             = "*****@*****.**",
                FirstName         = "Luke",
                LastName          = "McGregor",
                IsAuthor          = true
            };

            context.Users.AddOrUpdate(admin);

            var blogCreatorSecurable = new Securable {
                Name = "Blog Creator", Members = new List <User> {
                    admin
                }
            };
            context.Securables.AddOrUpdate(blogCreatorSecurable);

            if (!context.Blogs.Any())
            {
                var blog = new Data.Blog
                {
                    AuthoritiveUrl = "http://*****:*****@staticv0id",
                    Style          = new Style
                    {
                        Css =
                            @".test{
}"
                    },
                    AuthorSecurable = new Securable {
                        Name = "Author : StaticVoid - Test"
                    }
                };

                context.Blogs.AddOrUpdate(blog);
            }

            var postDate = new DateTime(2012, 10, 7, 12, 0, 0);

            context.Posts.AddOrUpdate(
                new Post
            {
                Id        = 1,
                AuthorId  = 1,
                Title     = "First Post",
                Body      = "First Post!",
                Posted    = postDate,
                Status    = PostStatus.Published,
                Path      = PostHelpers.MakeUrl(postDate.Year, postDate.Month, postDate.Day, "First Post"),
                Canonical = "/" + PostHelpers.MakeUrl(postDate.Year, postDate.Month, postDate.Day, "First Post")
            });

            postDate = postDate.AddDays(1);
            context.Posts.AddOrUpdate(
                new Post
            {
                Id        = 2,
                AuthorId  = 1,
                Title     = "Second Post",
                Body      = "Second Post!",
                Posted    = postDate,
                Status    = PostStatus.Published,
                Path      = PostHelpers.MakeUrl(postDate.Year, postDate.Month, postDate.Day, "Second Post"),
                Canonical = "/" + PostHelpers.MakeUrl(postDate.Year, postDate.Month, postDate.Day, "Second Post")
            });
#endif
#endif
        }