internal PostResult MakeNewReply(NewPost post, HttpPostedFileBase postFile, string shortName, string IPAddress) { bool imageExists = postFile != null; bool imageIsGood = !imageExists || ImageGood(postFile, shortName); string ip = IPAddress; DateTime cur = DateTime.UtcNow; bool isParentValid = db.Posts.Where(p => p.ID == post.resto) .Count() > 0; if (imageIsGood && isParentValid) { double iCur = DateService.DateTimeToUnixTimestamp(cur); if (imageExists) { SaveFileToBoardFolder(shortName, postFile, iCur, postFile.FileName); saveSmallFileToBoardFolder(shortName, postFile, iCur, postFile.FileName); int fsize = postFile.ContentLength; } savePostToDatabase(post, postFile, shortName, cur); return(PostResult.NewReplyCreated); } return(PostResult.PostFailure); }
public ActionResult PostTopic(int id) { var user = _userRetrievalShim.GetUser(HttpContext); if (user == null) { return(Content(Resources.LoginToPost)); } ForumPermissionContext permissionContext; var forum = GetForumByIdWithPermissionContext(id, out permissionContext); if (!permissionContext.UserCanView) { return(Content(Resources.ForumNoView)); } if (!permissionContext.UserCanPost) { return(Content(Resources.ForumNoPost)); } var profile = _profileService.GetProfile(user); var newPost = new NewPost { ItemID = forum.ForumID, IncludeSignature = profile.Signature.Length > 0, IsPlainText = _mobileDetectionWrapper.IsMobileDevice(HttpContext) || profile.IsPlainText, IsImageEnabled = _settingsManager.Current.AllowImages }; return(View("NewTopic", newPost)); }
public void InsertIntoPostRepository(NewPost newPost, HttpResponse response) { PostDocument postDocument = null; "Given a new post".x(() => newPost = new NewPost { Body = "my new post", Title = "my title" }); "When I submit the post".x(async() => response = await ExecuteHttpAsync(new AddPostCommand { Post = newPost })); "Then the post is available in the repository".x(async() => { Post returnedPost = response.GetJson <Post>(); Guid postId = returnedPost.Id; IPostRepository postRepository = ServiceProvider.GetRequiredService <IPostRepository>(); postDocument = await postRepository.Get(postId); }); "And the body and title match the submitted post".x(() => { Assert.Equal("my new post", postDocument.Body); Assert.Equal("my title", postDocument.Title); }); }
public void ReturnInsertedPost(NewPost newPost, HttpResponse response, Post savedPost) { DateTime utcStart = DateTime.UtcNow; "Given a new post".x(() => newPost = new NewPost { Body = "my new post", Title = "my title" }); "When I submit the post".x(async() => response = await ExecuteHttpAsync(new AddPostCommand { Post = newPost })); "Then I receive an OK result and a post".x(() => { Assert.Equal(200, response.StatusCode); savedPost = response.GetJson <Post>(); Assert.NotNull(savedPost); }); "And the returned post has an ID".x(() => Assert.NotEqual(Guid.Empty, savedPost.Id)); "And it has its post date set".x(() => Assert.True(savedPost.PostedAtUtc >= utcStart)); "And the body and title match the submitted post".x(() => { Assert.Equal("my new post", savedPost.Body); Assert.Equal("my title", savedPost.Title); }); }
private User DoUpNewTopic() { var forum = new Forum { ForumID = 1 }; var user = GetUser(); const string ip = "127.0.0.1"; const string title = "mah title"; const string text = "mah text"; var newPost = new NewPost { Title = title, FullText = text, ItemID = 1 }; var forumService = GetService(); _topicRepo.Setup(t => t.GetUrlNamesThatStartWith("parsed-title")).Returns(new List <string>()); _textParser.Setup(t => t.ClientHtmlToHtml("mah text")).Returns("parsed text"); _textParser.Setup(t => t.Censor("mah title")).Returns("parsed title"); _postRepo.Setup(p => p.Create(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>(), It.IsAny <bool>(), It.IsAny <string>(), null, It.IsAny <bool>(), It.IsAny <int>())).Returns(69); _forumRepo.Setup(x => x.GetForumViewRoles(forum.ForumID)).Returns(new List <string>()); _topicRepo.Setup(x => x.Create(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <DateTime>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <string>())).Returns(111); forumService.PostNewTopic(forum, user, new ForumPermissionContext { UserCanPost = true, UserCanView = true }, newPost, ip, It.IsAny <string>(), x => ""); return(user); }
public async Task <IActionResult> Post([FromBody] NewPost post) { try { if (ModelState.IsValid) { var topic = _topicService.GetById(post.TopicId); var user = _userManager.FindByIdAsync(post.User.Id).Result; post.User = user; post.Topic = topic; if (_context.Posts.Any(p => p.Content == post.Content)) { return(BadRequest("Post with this content already exist")); } await _postService.Add(post); await _context.SaveChangesAsync(); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. return(BadRequest("Unable to save changes. Try again...")); } return(CreatedAtAction(nameof(Get), new { id = post.Id }, post)); }
public string AddPost(string blogId, string userName, string password, NewPost post, bool isSend) { //参数的数量需要对应 var param = new object[] { blogId, userName, password, post, isSend }; var value = Invoke(MethodBase.GetCurrentMethod().Name, param); return value == null ? null : value.ToString(); }
public async Task <ActionResult> PostTopic(int id) { var user = _userRetrievalShim.GetUser(); if (user == null) { return(Content(Resources.LoginToPost)); } var(forum, permissionContext) = await GetForumByIdWithPermissionContext(id, user); if (!permissionContext.UserCanView) { return(Content(Resources.ForumNoView)); } if (!permissionContext.UserCanPost) { return(Content(Resources.ForumNoPost)); } var profile = await _profileService.GetProfile(user); var newPost = new NewPost { ItemID = forum.ForumID, IncludeSignature = profile.Signature.Length > 0, IsPlainText = profile.IsPlainText, IsImageEnabled = _settingsManager.Current.AllowImages }; return(View("NewTopic", newPost)); }
public IActionResult CreatePost(NewPost obj) { DatabaseConnector db = new DatabaseConnector(); if (DatabaseConnector.signeduser.id != -1) { if (ModelState.IsValid) { signdInUser = DatabaseConnector.signeduser; Post post = new Post(); post.content = obj.content; post.title = obj.title; post.userId = signdInUser.id; post.username = signdInUser.username; post.date = System.DateTime.Now.ToString("MMMM, dd yyyy"); db.AddNewPost(post); List <Post> list = db.getAllUsersPost(signdInUser); return(View("UsersPost", list)); } else { return(View()); } } else { return(View("Index")); } }
public ActionResult Create([Bind(Include = "UserId,BookId,Title,Content")] NewPost model) { Post post = new Post(); if (ModelState.IsValid) { try { post.UserId = User.Identity.GetUserId(); post.Title = model.Title; post.BookId = model.BookId; post.Content = model.Content; post.SelectedBook = db.Query <Book>().FirstOrDefault(b => b.BookId == model.BookId); post.User = db.Query <ApplicationUser>().FirstOrDefault(u => u.Id == User.Identity.GetUserId()); } catch { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } db.Add(post); db.SaveChanges(); Book book = db.Query <Book>().FirstOrDefault(b => b.BookId == model.BookId); return(RedirectToAction("Details", "Books", new { id = book.BookId, page = 1 })); } return(View(post)); }
public void PostNewTopicDoesNotPublishToFeedIfForumHasViewRestrictions() { var forum = new Forum(1); var user = GetUser(); const string ip = "127.0.0.1"; const string title = "mah title"; const string text = "mah text"; var newPost = new NewPost { Title = title, FullText = text, ItemID = 1 }; var topicService = GetService(); _mockForumRepo.Setup(x => x.GetForumViewRoles(forum.ForumID)).Returns(new List <string> { "Admin" }); _mockTopicRepo.Setup(t => t.GetUrlNamesThatStartWith("parsed-title")).Returns(new List <string>()); _mockTextParser.Setup(t => t.ClientHtmlToHtml("mah text")).Returns("parsed text"); _mockTextParser.Setup(t => t.EscapeHtmlAndCensor("mah title")).Returns("parsed title"); _mockTopicRepo.Setup(t => t.Create(forum.ForumID, "parsed title", 0, 0, user.UserID, user.Name, user.UserID, user.Name, It.IsAny <DateTime>(), false, false, false, false, "parsed-title")).Returns(2); var topic = topicService.PostNewTopic(forum, user, new ForumPermissionContext { UserCanPost = true, UserCanView = true }, newPost, ip, It.IsAny <string>(), x => ""); _eventPublisher.Verify(x => x.ProcessEvent(It.IsAny <string>(), It.IsAny <User>(), EventDefinitionService.StaticEventIDs.NewTopic, true), Times.Once()); }
public void Post(string title, string content) { if (NewPost != null) { NewPost.Invoke(this, EventArgs.Empty); } }
internal PostResult MakeNewThread(NewPost post, HttpPostedFileBase postFile, string shortName, string IPAddress) { bool imageExists = postFile != null; if (!imageExists) { return(PostResult.PostFailure); } bool imageIsGood = ImageGood(postFile, shortName); string ip = IPAddress; DateTime cur = DateTime.UtcNow; if (imageIsGood) { double iCur = DateService.DateTimeToUnixTimestamp(cur); SaveFileToBoardFolder(shortName, postFile, iCur, postFile.FileName); saveSmallFileToBoardFolder(shortName, postFile, iCur, postFile.FileName); int fsize = postFile.ContentLength; savePostToDatabase(post, postFile, shortName, cur); return(PostResult.NewThreadCreated); } return(PostResult.PostFailure); }
public void PostReplyReturnsHydratedObject() { var topic = new Topic(1); var user = GetUser(); var postTime = DateTime.UtcNow; var topicService = GetTopicService(); _forumRepo.Setup(x => x.GetForumViewRoles(It.IsAny <int>())).Returns(new List <string>()); _postRepo.Setup(p => p.Create(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), false, true, It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>(), false, It.IsAny <string>(), null, false, 0)).Returns(123); _textParser.Setup(t => t.ClientHtmlToHtml("mah text")).Returns("parsed text"); _textParser.Setup(t => t.EscapeHtmlAndCensor("mah title")).Returns("parsed title"); var newPost = new NewPost { FullText = "mah text", Title = "mah title", IncludeSignature = true }; var post = topicService.PostReply(topic, user, 0, "127.0.0.1", false, newPost, postTime, "", u => "", "", x => ""); Assert.AreEqual(topic.TopicID, post.TopicID); Assert.AreEqual("parsed text", post.FullText); Assert.AreEqual("127.0.0.1", post.IP); Assert.IsFalse(post.IsDeleted); Assert.IsFalse(post.IsEdited); Assert.IsFalse(post.IsFirstInTopic); Assert.AreEqual(user.Name, post.LastEditName); Assert.IsNull(post.LastEditTime); Assert.AreEqual(user.Name, post.Name); Assert.AreEqual(0, post.ParentPostID); Assert.AreEqual(123, post.PostID); Assert.AreEqual(postTime, post.PostTime); Assert.IsTrue(post.ShowSig); Assert.AreEqual("parsed title", post.Title); Assert.AreEqual(user.UserID, post.UserID); }
public bool IsNewPostDupeOrInTimeLimit(NewPost newPost, User user) { var postID = _profileRepository.GetLastPostID(user.UserID); if (postID == null) { return(false); } var lastPost = _postRepository.Get(postID.Value); if (lastPost == null) { return(false); } var minimumSeconds = _settingsManager.Current.MinimumSecondsBetweenPosts; if (DateTime.UtcNow.Subtract(lastPost.PostTime).TotalSeconds < minimumSeconds) { return(true); } var parsedText = newPost.IsPlainText ? _textParsingService.ForumCodeToHtml(newPost.FullText) : _textParsingService.ClientHtmlToHtml(newPost.FullText); if (parsedText == lastPost.FullText) { return(true); } return(false); }
public ActionResult Comment(NewPost form) { var post = Database.Session.Load <Post>(form.id); if (post == null) { return(HttpNotFound()); } var comment = new Comment() { post = post, author = Database.Session.Query <User>().FirstOrDefault(x => x.pseudo == User.Identity.Name), content = form.newComment, date = DateTime.Now }; if (comment.content != null) { Database.Session.Save(comment); Database.Session.Flush(); } return(RedirectToAction("display", new { id = post.id })); }
public async Task <IActionResult> Create([Bind("Content,Created,UserId")] NewPost post, int id) { try { if (ModelState.IsValid) { var topic = _topicService.GetById(id); var userId = _userManager.GetUserId(User); var user = _userManager.FindByIdAsync(userId).Result; post.User = user; post.Topic = topic; post.TopicId = id; if (_context.Posts.Any(p => p.Content == post.Content)) { ModelState.AddModelError("Content", "Post with this content already exist"); return(View(post)); } await _postService.Add(post); return(RedirectToAction("PostsByTopic", "Posts", new { id = post.Topic.Id })); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again..."); } return(View(post)); }
public async Task <IActionResult> PostTopic(NewPost newPost) { var user = _userRetrievalShim.GetUser(); if (user == null) { return(Forbid()); } var userProfileUrl = Url.Action("ViewProfile", "Account", new { id = user.UserID }); string TopicLinkGenerator(Topic t) => Url.Action("Topic", "Forum", new { id = t.UrlName }); string RedirectLinkGenerator(Topic t) => Url.RouteUrl(new { controller = "Forum", action = "Topic", id = t.UrlName }); var ip = HttpContext.Connection.RemoteIpAddress.ToString(); var result = await _postMasterService.PostNewTopic(user, newPost, ip, userProfileUrl, TopicLinkGenerator, RedirectLinkGenerator); if (result.IsSuccessful) { return(Json(new BasicJsonMessage { Result = true, Redirect = result.Redirect })); } return(Json(new BasicJsonMessage { Result = false, Message = result.Message })); }
public async Task <IActionResult> EditPostAsync(int id, NewPost post) { var postToUpdate = _postService.GetById(id); if (await TryUpdateModelAsync(postToUpdate, "", p => p.Content)) { if (_context.Posts.Any(p => p.Content == post.Content)) { ModelState.AddModelError("Content", "Post with this content already exist"); return(View(post)); } try { await _context.SaveChangesAsync(); return(RedirectToAction("PostsByTopic", "Posts", new { id = postToUpdate.Topic.Id })); } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes."); } } return(View(post)); }
public ActionResult Reply(NewPost form) { string val = Convert.ToString(Request.Params["CmtId"]); var comment = Database.Session.Load <Comment>(Int32.Parse(val)); if (comment == null) { return(HttpNotFound()); } var reply = new CommentReply() { comment = comment, author = Database.Session.Query <User>().FirstOrDefault(x => x.pseudo == User.Identity.Name), content = form.newReply, date = DateTime.Now }; if (reply.content != null) { Database.Session.Save(reply); Database.Session.Flush(); } return(RedirectToAction("display", new { id = comment.post.id })); }
public Task <HttpResponseMessage> NewWord(int id, [FromBody] NewPost newPost) { IEnumerable <string> headerValues; try { headerValues = Request.Headers.GetValues("AuthKey"); } catch (Exception) { return(Task.FromResult(Request.CreateResponse(HttpStatusCode.Unauthorized))); } var authKey = headerValues.FirstOrDefault(); Post created; try { created = this.threadService.AddWord(authKey, id, newPost.Word); } catch (Exception) { return(Task.FromResult(Request.CreateResponse(HttpStatusCode.Forbidden))); } return(Task.FromResult(Request.CreateResponse(HttpStatusCode.Created, created.Word))); }
public string AddPost(string blogId, string userName, string password, NewPost post, bool isSend) { //参数的数量需要对应 var param = new object[] { blogId, userName, password, post, isSend }; var value = Invoke(MethodBase.GetCurrentMethod().Name, param); return(value == null ? null : value.ToString()); }
public IActionResult Create(int id) { var model = new NewPost { TopicId = id, }; return(View(model)); }
public async Task <IHttpActionResult> Post(NewPost newPost) { if (newPost == null || !ModelState.IsValid) { return(ApiBadRequestFromModelState()); } var decodedId = newPost.CategoryId.FromEncodedId(); var category = await _dbContext.Categories.FirstOrDefaultAsync(p => p.Id == decodedId); if (category == null) { return(ApiBadRequest(ApiResources.CategoryNotFound)); } if (category.IsArchived) { return(ApiBadRequest(ApiResources.CategoryArchived)); } if (string.IsNullOrWhiteSpace(newPost.Email) && string.IsNullOrWhiteSpace(newPost.PhoneNumber)) { return(ApiBadRequest(ApiResources.ContactMethodRequired)); } var slug = newPost.Title.ToUrlSlug(); var post = new Post { UserId = User.Id, CategoryId = decodedId, Title = newPost.Title, Text = newPost.Text, IsNsfw = category.IsNsfw || newPost.IsNsfw, Type = newPost.Type, Price = Math.Max(newPost.Price, newPost.Type == PostType.Fixed ? 1 : 0), Slug = string.IsNullOrEmpty(slug) ? "_" : slug, Location = GeoLocation, PhoneNumber = newPost.PhoneNumber, Email = newPost.Email }; _dbContext.Posts.Add(post); await _dbContext.SaveChangesAsync(); _dbContext.PostVotes.Add(new PostVote { PostId = post.Id, UserId = User.Id, IpAddress = ClientIpAddress, IsUp = true }); await _dbContext.SaveChangesAsync(); return(CreatedData(post.Id.ToEncodedId())); }
public static NewPost GenerateObject() { NewPost post = new NewPost(); post.userId = 10; post.title = "Test Post"; post.body = Faker.Lorem.Paragraph(100);; return(post); }
// AddBlogImplementation### // ###AddPostImplementation public override IGraphQlObjectResult <Post?> AddPost(string blogId, NewPost newPost) => this.ResolveTask(async _ => { var post = new Data.Post { BlogId = int.Parse(blogId), Title = newPost.Title, Content = newPost.PostContent }; context.Add(post); await context.SaveChangesAsync(); return(post); }).Nullable(post => post.AsContract <PostResolver>());
public ActionResult PostReply(int id, int quotePostID = 0, int replyID = 0) { var user = this.CurrentUser(); if (user == null) { return(Content(Resources.LoginToPost)); } var topic = _topicService.Get(id); if (topic == null) { return(Content(Resources.TopicNotExist)); } var forum = _forumService.Get(topic.ForumID); if (forum == null) { throw new Exception(String.Format("TopicID {0} references ForumID {1}, which does not exist.", topic.TopicID, topic.ForumID)); } if (topic.IsClosed) { return(Content(Resources.Closed)); } var permissionContext = _forumService.GetPermissionContext(forum, this.CurrentUser(), topic); if (!permissionContext.UserCanView) { return(Content(Resources.ForumNoView)); } if (!permissionContext.UserCanPost) { return(Content(Resources.ForumNoPost)); } var title = topic.Title; if (!title.ToLower().StartsWith("re:")) { title = "Re: " + title; } var profile = _profileService.GetProfile(user); var forcePlainText = _mobileDetectionWrapper.IsMobileDevice(HttpContext); var newPost = new NewPost { ItemID = topic.TopicID, Title = title, IncludeSignature = profile.Signature.Length > 0, IsPlainText = forcePlainText || profile.IsPlainText, IsImageEnabled = _settingsManager.Current.AllowImages, ParentPostID = replyID }; if (quotePostID != 0) { var post = _postService.Get(quotePostID); newPost.FullText = _postService.GetPostForQuote(post, user, forcePlainText); } return(View("NewReply", newPost)); }
public void AddSampleData() { var context = ServiceProvider.GetService <DatabaseContext>(); var posts = NewPost .Generate(SampleCount); posts[0].Id = SampleGuid; context.Posts.AddRange(posts); context.SaveChanges(); }
public void Post(string title, string content) { //save the post _posts[title] = content; //notify the NewPost event subscribers //if (NewPost != null) //{ // NewPost.Invoke(this, EventArgs.Empty); //} NewPost?.Invoke(this, EventArgs.Empty); }
public Task <Post> CreateNewPostAsync(string teamName, NewPost post) { var url = BuildStringBuilderWithTeamName(teamName); url.Append("/posts"); var postObject = new NewPostRequest { post = post }; return(PostMessage <NewPostRequest, Post>(url.ToString(), postObject)); }
public void OnGet() { LoadModel(); if (IsItOwnProfile) { NewPost = new NewPost() { UserId = CurrentUserId }; } }
public IHttpActionResult Put(NewPost post) { _adapter.UpdatePost(post); return Ok(); }