Example #1
0
        private static void WritePost()
        {
            string lang     = string.Empty;
            string message  = string.Empty;
            string postURL  = string.Empty;
            string imageURL = string.Empty;

            Console.WriteLine("Input language( en or ru): ");
            lang = Console.ReadLine();
            lang = lang.Trim();

            Console.WriteLine("Input message:");
            message = Console.ReadLine();

            Console.WriteLine("Input link to post:");
            postURL = Console.ReadLine();
            postURL = postURL.Trim();

            Console.WriteLine("Input image URL");
            imageURL = Console.ReadLine();
            imageURL = imageURL.Trim();

            PostEntry entry = new PostEntry {
                imageURL = imageURL,
                lang     = lang,
                message  = message,
                postID   = Guid.NewGuid().ToString(),
                postURL  = postURL,
                time     = CommonUtils.SecondsFrom1970()
            };

            news.Insert(entry);
            Console.WriteLine("Post inserted");
        }
Example #2
0
        public ActionResult Create(PostEntry entry)
        {
            if (ModelState.IsValid)
            {
                Posts post = new Posts(

                    entry.CategoryId,
                    User.Identity.GetUserId(),
                    entry.Title,
                    entry.Description,
                    entry.Content,
                    entry.ImgUrl,
                    DateTime.Now,
                    null

                    );

                db.Posts.Add(post);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", entry.CategoryId);
            return(View(entry));
        }
Example #3
0
        public async Task <IActionResult> AddOrUpdate(PostEntry contentEntry)
        {
            var UserId  = HttpContext.Session.GetString(UserAccountBusiness.UserAccountSessionkey);
            var _userId = Guid.Parse(UserId);

            ViewData["DataType"] = typeof(ContentEntry);
            //await contentBusiness.CreateContentWithCategoryAndTag(contentEntry, "论坛", "论坛");
            return(RedirectToAction("Index"));
        }
Example #4
0
        public void CanCreateWithNullObjectTest()
        {
            var name = Guid.NewGuid().ToString();

            var target = new PostEntry(name, (object)null);

            target.Name.Should().Be(name);
            target.Value.Should().BeNull();
        }
Example #5
0
        public void CanCreateWithBooleanTest()
        {
            var        name  = Guid.NewGuid().ToString();
            const bool Value = true;

            var target = new PostEntry(name, Value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(Value.ToString(CultureInfo.InvariantCulture));
        }
Example #6
0
        public void CanCreateWithBooleanTest()
        {
            var name = Guid.NewGuid().ToString();
            const bool Value = true;

            var target = new PostEntry(name, Value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(Value.ToString(CultureInfo.InvariantCulture));
        }
Example #7
0
        public void CanCreateWithInt32Test()
        {
            var name  = Guid.NewGuid().ToString();
            var value = Environment.TickCount;

            var target = new PostEntry(name, value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(value.ToString(CultureInfo.InvariantCulture));
        }
Example #8
0
        public void CanCreateWithGuidTest()
        {
            var name = Guid.NewGuid().ToString();
            var value = Guid.NewGuid();

            var target = new PostEntry(name, value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(value.ToString());
        }
Example #9
0
        public void CanCreateWithInt64Test()
        {
            var        name  = Guid.NewGuid().ToString();
            const long Value = 234;

            var target = new PostEntry(name, Value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(Value.ToString(CultureInfo.InvariantCulture));
        }
Example #10
0
        public void CanCreateWithInt16Test()
        {
            var name = Guid.NewGuid().ToString();
            const short Value = 234;

            var target = new PostEntry(name, Value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(Value.ToString(CultureInfo.InvariantCulture));
        }
Example #11
0
        public void CanCreateWithInt32Test()
        {
            var name = Guid.NewGuid().ToString();
            var value = Environment.TickCount;

            var target = new PostEntry(name, value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(value.ToString(CultureInfo.InvariantCulture));
        }
Example #12
0
        public void CanCreateWithGuidTest()
        {
            var name  = Guid.NewGuid().ToString();
            var value = Guid.NewGuid();

            var target = new PostEntry(name, value);

            target.Name.Should().Be(name);
            target.Value.Should().Be(value.ToString());
        }
Example #13
0
        public static async Task AnalysisPost(IWebElement element, Dictionary <string, string> state, WebDriverWrapper webDriverWrapper)
        {
            var tagList        = element.FindElements(By.CssSelector(".dm-tag.dm-tag-a"));
            var createTiem     = element.FindElement(By.CssSelector(".meta-info.mb20 span")).GetAttribute("innerText");
            var content        = Encoding.UTF8.GetString(Encoding.Default.GetBytes(element.FindElement(By.CssSelector(".content")).GetAttribute("innerHTML")));
            var postImgUrlList = element.FindElements(By.CssSelector(".album .inner-container img"));
            var nickName       = state["nickName"];
            var avatar         = state["avatar"];
            var userModel      = GetOrSetUser(nickName, avatar);
            var dbContext      = GetDbContext();
            var postImgList    = new List <PostEntryFile>();
            var imgindex       = 1;

            if (dbContext.PostEntry.Any(x => x.TextContent == content))
            {
                return;
            }
            foreach (var item in postImgUrlList)
            {
                var oldPath = item.GetAttribute("src");
                var key     = "postEntryFile/" + nickName + "/" + Guid.NewGuid().ToString();
                await UploadQiniu(oldPath, key);

                postImgList.Add(new PostEntryFile
                {
                    ActualPath = "https://mioto.milbit.com/" + key,
                    Name       = key,
                    Type       = PostEntryFileType.Image,
                    Order      = imgindex,
                    Tag        = "半次元"
                });
                imgindex++;
            }

            var postEntry = new PostEntry
            {
                Id                = Guid.NewGuid(),
                CreateTime        = DateTime.Parse(createTiem),
                TimeStamp         = TimeStamp.Get(),
                TextContent       = content,
                PostEntryFileList = postImgList,
                UserId            = userModel.Id,
                PostEntryTags     = new List <PostEntryTag> {
                    new PostEntryTag {
                        CreateTime = DateTime.Now,
                        Id         = Guid.NewGuid(),
                        Name       = "Coser"
                    }
                }
            };

            dbContext.PostEntry.Add(postEntry);
            await dbContext.SaveChangesAsync();
        }
Example #14
0
        private SyndicationItem TransformPost(PostEntry entry)
        {
            entry = RenderEntry(entry);
            SyndicationItem item = new SyndicationItem();

            item.Id      = entry.Name;
            item.Title   = SyndicationContent.CreatePlaintextContent(entry.Title);
            item.Content = SyndicationContent.CreateHtmlContent(Transformer.Transform(entry.Content));
            item.AddPermalink(new Uri("http://otakustay.com/" + entry.Name + "/"));
            item.PublishDate     = new DateTimeOffset(entry.PostDate);
            item.LastUpdatedTime = new DateTimeOffset(entry.UpdateDate);
            item.Authors.Add(Author.Clone());
            return(item);
        }
Example #15
0
        public async Task CreateContentCommentExtPostEntry(Comment comment)
        {
            var contentModel = await ContentAccessor.OneAsync <ContentEntry>(x => x.Id == comment.ContentEntry.Id, "Category");

            var topicTxt = contentModel.Category.Name + "|" + contentModel.Title;
            //设置话题为漫画名
            var topic = new PostEntryTopic()
            {
                CreateTime = DateTime.Now,
                Id         = Guid.NewGuid(),
                Text       = topicTxt,
                PosterId   = comment.UserAccount.Id
            };
            var topicExt = new ContentExtPostEntryTopic()
            {
                Id        = Guid.NewGuid(),
                TopicText = topicTxt,
                LinkId    = contentModel.Id,
                LinkType  = "category"
            };
            //评论
            var postentryModel = new PostEntry()
            {
                Id             = Guid.NewGuid(),
                CreateTime     = DateTime.Now,
                PostEntryTopic = topicTxt,
                UserId         = comment.UserAccount.Id,
                TimeStamp      = TimeStamp.Get(),
                TextContent    = comment.Content
            };

            //目前是一条漫画评论对应一个话题, 为防止以后出现多话题, 保留此表
            var contentPostentryMapping = new ContentPostEntryMapping()
            {
                Id          = Guid.NewGuid(),
                ContentId   = contentModel.Id,
                PostEntryId = postentryModel.Id,
                CreateTime  = DateTime.Now
            };

            await ContentAccessor.Add(topic);

            await ContentAccessor.Add(topicExt);

            await ContentAccessor.Add(postentryModel);

            await ContentAccessor.Add(contentPostentryMapping);
        }
Example #16
0
        public static PostEntry AddPost(string title, string text, int authorId, int?imageId)
        {
            PostEntry entry = new PostEntry
            {
                Id          = Posts.Count,
                Title       = title,
                Text        = text,
                AuthorId    = authorId,
                CreatedDate = DateTime.Now,
                ImageId     = imageId
            };

            Posts.Add(entry);

            return(entry);
        }
Example #17
0
        public ActionResult ViewPost(string name)
        {
            PostEntry entry = DbSession.QueryOver <PostEntry>()
                              .Where(p => p.Name == name)
                              .SingleOrDefault();

            if (entry == null)
            {
                return(new HttpStatusCodeResult(404));
            }
            else
            {
                ViewBag.Title = String.Format("{0} - 宅居 - 宅并技术着", entry.Title);
                return(View("ViewPost", RenderEntry(entry)));
            }
        }
        public Tuple <bool, string> Edit(HttpContext context)
        {
            string    path      = context.Request.Path.Value;
            PostEntry postEntry = new PostEntry();

            postEntry.AuthorName = context.Request.Form["name"];
            postEntry.Post       = context.Request.Form["post"];
            var validationResult = Validation.Validation.Validate(postEntry);

            if (validationResult.IsValid)
            {
                File.WriteAllLines(string.Format("Files/{0}.txt", path.Split("/").Last()),
                                   new string[] { postEntry.AuthorName, postEntry.Post });
                return(new Tuple <bool, string>(true, "Ok"));
            }
            return(new Tuple <bool, string>(false, validationResult.ErrorMessage));
        }
Example #19
0
        public void AddPostEntry()
        {
            var postEntry = new PostEntry
            {
                FirstName       = "Maxym",
                LastName        = "Goliak",
                ContainerID     = "F**K'N CONTAINER",
                DateOfDischarge = DateTime.Now,
                DateOfReport    = DateTime.Now,
                DateUplifted    = DateTime.Now,
                Balance         = 100,
                TSDocId         = 1
            };

            provider.PostEntries.AddNew(postEntry);
            Items.Add(new PostEntryVM(postEntry));
        }
Example #20
0
        public async Task CreatePostEntry(PostEntry model)
        {
            if (!string.IsNullOrEmpty(model.PostEntryTopic))
            {
                var oriModel = await postEntryDataAccessor.OneAsync <PostEntryTopic>(x => x.Text == model.PostEntryTopic);

                if (oriModel == null)
                {
                    await postEntryDataAccessor.Add(new PostEntryTopic
                    {
                        Id         = Guid.NewGuid(),
                        CreateTime = DateTime.Now,
                        Text       = model.PostEntryTopic,
                        PosterId   = model.UserId
                    });
                }
            }
            await postEntryDataAccessor.Add(model);
        }
Example #21
0
        public async Task <Tuple <bool, string> > Save(HttpContext context)
        {
            string filePath  = "Files";
            var    postId    = context.Request.Path.Value.Split("/").Last();
            int    fileCount = Directory.GetFiles(filePath, string.Format("{0}.comment*", postId),
                                                  SearchOption.AllDirectories).Length;
            PostEntry postEntry = new PostEntry();

            postEntry.AuthorName = context.Request.Form["name"];
            postEntry.Post       = context.Request.Form["post"];
            var validationResult = Validation.Validation.Validate(postEntry);
            var txtFileName      = Path.Combine(filePath, postId + ".comment" + fileCount);

            if (validationResult.IsValid)
            {
                File.AppendAllLines(txtFileName, new string[] { postEntry.AuthorName, postEntry.Post });
                return(new Tuple <bool, string>(true, "Ok"));
            }
            return(new Tuple <bool, string>(false, validationResult.ErrorMessage));
        }
Example #22
0
        public async Task <IActionResult> CreatEntry([FromBody] PostEntry model)
        {
            var userIdStr = User.Claims.FirstOrDefault(x => x.Type == "OryxUser").Value;

            if (string.IsNullOrEmpty(userIdStr))
            {
                return(Content("Empty User"));
            }
            model.UserId = Guid.Parse(userIdStr);
            if (model != null)
            {
                model.CreateTime = DateTime.Now;
                model.TimeStamp  = TimeStamp.Get();
            }
            var apiMsg = await ApiMessage.Wrap(async() =>
            {
                await postEntryBusiness.CreatePostEntry(model);
            });

            return(Json(apiMsg));
        }
Example #23
0
        public async Task <ActionResult <PostEntry> > PostEntry(PostEntry entry)
        {
            var sql = "INSERT INTO Entries (`FirstName`, `LastName`, `Number`) VALUES(@firstName, @lastName, @number);";

            using var command = new MySqlCommand(sql, connection);

            command.Parameters.AddWithValue("@firstName", entry.firstName);
            command.Parameters.AddWithValue("@lastName", entry.lastName);
            command.Parameters.AddWithValue("@number", entry.number);
            command.Prepare();
            using var reader = await command.ExecuteReaderAsync();

            reader.Close();

            var result = new PostEntry();

            result.firstName = entry.firstName;
            result.lastName  = entry.lastName;
            result.number    = entry.number;
            return(result);
        }
    public PostEntry[] GetPosts(JToken displayData, string imagePath, int timeFilter)
    {
        List <PostEntry> posts = new List <PostEntry> ();
        JToken           data  = displayData.SelectToken("$.data");
        JToken           item;

        PostEntry postEntry;

        for (int i = 0; i < data.Children().Count(); i++)
        {
            item = data.Children().ElementAt(i);

            DateTime creationTime = DateTime.Parse(item.SelectToken("$.created_at").ToString());
            if (Mathf.Abs((float)(DateTime.UtcNow - creationTime).TotalHours) < timeFilter)
            {
                postEntry = new PostEntry();

                //picture
                string fileName = Path.GetFileName(item.SelectToken("$." + imagePath).ToString());
                postEntry.texture = LoadImage(Path.Combine(DOWNLOAD_PATH, fileName));

                //Text
                postEntry.text = item.SelectToken("$.text").ToString();

                //UserName
                postEntry.userName = item.SelectToken("$.user.username").ToString();

                //Hashtag
                postEntry.hashtag = item.SelectToken("$.hashtags").Children().ElementAt(0).SelectToken("$.name").ToString();

                posts.Add(postEntry);
            }
        }

        return(posts.ToArray());
    }
        public async Task <Tuple <bool, string> > Save(HttpContext context)
        {
            string filePath  = "Files";
            int    fileCount = Directory.GetFiles(filePath, "*.txt", SearchOption.AllDirectories).Length;

            fileCount++;
            PostEntry postEntry = new PostEntry();

            postEntry.AuthorName = context.Request.Form["name"];
            postEntry.Post       = context.Request.Form["post"];
            var validationResult = Validation.Validation.Validate(postEntry);

            if (context.Request.Form.Files.Count > 0 && validationResult.IsValid)
            {
                foreach (var file in context.Request.Form.Files)
                {
                    var path = Path.Combine(filePath, fileCount + System.IO.Path.GetExtension(file.FileName));
                    await using (var inputStream = new FileStream(path, FileMode.Create))
                    {
                        // read file to stream
                        await file.CopyToAsync(inputStream);

                        // stream to byte array
                        byte[] array = new byte[inputStream.Length];
                        inputStream.Seek(0, SeekOrigin.Begin);
                        inputStream.Read(array, 0, array.Length);
                        // get file name
                        var fName = file.FileName;
                    }
                }
                postEntry.PhotoName = Path.Combine(filePath, fileCount + ".txt");
                File.AppendAllLines(postEntry.PhotoName, new string[] { postEntry.AuthorName, postEntry.Post });
                return(new Tuple <bool, string>(true, "Ok"));
            }
            return(new Tuple <bool, string>(false, validationResult.ErrorMessage));
        }
Example #26
0
        public void CanCreateWithNullObjectTest()
        {
            var name = Guid.NewGuid().ToString();

            var target = new PostEntry(name, (object)null);

            target.Name.Should().Be(name);
            target.Value.Should().BeNull();
        }
Example #27
0
 public PostEntryVM(PostEntry pe)
 {
     this.entry = pe;
 }
Example #28
0
        public async Task CreateCategoryCommentExtPostEntry(CategoryComment comment)
        {
            var categoryModel = await ContentAccessor.OneAsync <Categories>(x => x.Status != ContentStatus.Close && x.Id == comment.CategoryId);

            //设置话题为漫画名
            var topic = new PostEntryTopic()
            {
                CreateTime = DateTime.Now,
                Id         = Guid.NewGuid(),
                Text       = categoryModel.Name,
                PosterId   = comment.UserAccountId
            };
            var topicExt = new ContentExtPostEntryTopic()
            {
                Id        = Guid.NewGuid(),
                TopicText = categoryModel.Name,
                LinkId    = categoryModel.Id,
                LinkType  = "category"
            };
            //评论
            var postentryModel = new PostEntry()
            {
                Id             = Guid.NewGuid(),
                CreateTime     = DateTime.Now,
                PostEntryTopic = categoryModel.Name,
                UserId         = comment.UserAccountId,
                TimeStamp      = TimeStamp.Get(),
                TextContent    = comment.Content,
            };

            //目前是一条漫画评论对应一个话题, 为防止以后出现多话题, 保留此表
            var categoryPostentryMapping = new CategoryPostEntryMapping()
            {
                Id          = Guid.NewGuid(),
                CategoryId  = categoryModel.Id,
                PostEntryId = postentryModel.Id,
                CreateTime  = DateTime.Now
            };

            await ContentAccessor.Add(topic);

            await ContentAccessor.Add(topicExt);

            await ContentAccessor.Add(postentryModel);

            await ContentAccessor.Add(categoryPostentryMapping);

            var sandBoxMsg = new SandBoxMessage()
            {
                Content           = $"您在漫画{topic}的回复,收到了新的评论.",
                CreateTime        = DateTime.Now,
                FromUserAccountId = comment.UserAccountId,
                ToUserAccountId   = postentryModel.UserId,
                Id           = Guid.NewGuid(),
                IsRead       = false,
                MessageType  = SandBoxMessageType.PostEntryComment,
                TimeStamp    = TimeStamp.Get(),
                RecieveToken = ""
            };
            await sandBoxBusiness.SendAlertTo(sandBoxMsg);
        }
Example #29
0
        public ActionResult PostComment(Comment comment)
        {
            comment.Author.Name  = comment.Author.Name.Trim();
            comment.Author.Email = comment.Author.Email.Trim();

            // 验证
            if (String.IsNullOrEmpty(comment.Author.Name) ||
                comment.Author.Name.Length > 60)
            {
                ModelState.AddModelError("name", validationMessages["name"]);
            }
            if (String.IsNullOrEmpty(comment.Author.Email) ||
                comment.Author.Email.Length > 100 ||
                !emailRule.IsMatch(comment.Author.Email))
            {
                ModelState.AddModelError("email", validationMessages["email"]);
            }
            if (String.IsNullOrEmpty(comment.Content.Trim()))
            {
                ModelState.AddModelError("content", validationMessages["content"]);
            }

            if (!ModelState.IsValid)
            {
                if (Request.IsAjaxRequest())
                {
                    Dictionary <string, string> result = ModelState
                                                         .Where(m => m.Value.Errors.Any())
                                                         .ToDictionary(m => m.Key, m => m.Value.Errors[0].ErrorMessage);
                    return(new NewtonJsonActionResult(result));
                }
                else
                {
                    PostEntry entry = DbSession.QueryOver <PostEntry>()
                                      .Where(p => p.Name == comment.PostName)
                                      .SingleOrDefault();
                    entry           = RenderEntry(entry);
                    ViewBag.Comment = comment;
                    ViewBag.Title   = String.Format("{0} - 宅居 - 宅并技术着", entry.Title);
                    return(View("ViewPost", entry));
                }
            }

            comment.PostTime         = DateTime.Now;
            comment.Author.IpAddress = Request.UserHostAddress;
            comment.Author.UserAgent = Request.UserAgent;
            comment.Audited          = true; // 默认为已审核,有需要的再屏蔽
            comment.Referrer         = Request.UrlReferrer == null ? String.Empty : Request.UrlReferrer.ToString();
            if (comment.Referrer.Length > 200)
            {
                comment.Referrer = comment.Referrer.Substring(0, 200);
            }

            Dictionary <int, string> targetAuthor = new Dictionary <int, string>();

            if (comment.Target.HasValue)
            {
                Comment target = DbSession.Get <Comment>(comment.Target);
                // 防止CSRF攻击,评论只能评论同一文章下的
                if (target == null || target.PostName != comment.PostName)
                {
                    comment.Target = null;
                }
                else
                {
                    targetAuthor[comment.Target.Value] = target.Author.Name;
                }
            }

            DbSession.Save(comment);

            // 审核评论要有网络交互,异步进行不影响用户收到响应
            Task task = new Task(() => ProcessComment(comment, Kernel));;

            task.Start();

            if (Request.IsAjaxRequest())
            {
                CommentView commentView = RenderComment(comment, targetAuthor);
                ViewResult  view        = View("Comment", commentView);
                return(new CreatedActionResult(Url.Content("~/" + comment.PostName), view));
            }
            else
            {
                return(Redirect(Url.Content("~/" + comment.PostName + "/")));
            }
        }
Example #30
0
 private PostEntry RenderEntry(PostEntry entry)
 {
     entry         = entry.Clone();
     entry.Content = Transformer.Transform(entry.Content);
     return(entry);
 }
    public PostEntry[] GetPosts(JToken displayData, string imagePath, int timeFilter)
    {
        List<PostEntry> posts = new List<PostEntry> ();
        JToken data = displayData.SelectToken ("$.data");
        JToken item;

        PostEntry postEntry;

        for (int i = 0; i < data.Children().Count(); i++) {
            item = data.Children().ElementAt(i);

            DateTime creationTime = DateTime.Parse(item.SelectToken("$.created_at").ToString());
            if(Mathf.Abs((float)(DateTime.UtcNow - creationTime).TotalHours) < timeFilter)
            {
                postEntry = new PostEntry();

                //picture
                string fileName = Path.GetFileName(item.SelectToken("$." + imagePath).ToString());
                postEntry.texture = LoadImage(Path.Combine(DOWNLOAD_PATH, fileName));

                //Text
                postEntry.text = item.SelectToken("$.text").ToString();

                //UserName
                postEntry.userName = item.SelectToken("$.user.username").ToString();

                //Hashtag
                postEntry.hashtag = item.SelectToken("$.hashtags").Children().ElementAt(0).SelectToken("$.name").ToString();

                posts.Add(postEntry);
            }
        }

        return posts.ToArray ();
    }
 public async Task <ActionResult <PostEntry> > PostEntry([FromForm] PostEntry entry)
 {
     return(await _context.PostEntry(entry));
 }