コード例 #1
0
        public async Task SitemapXml()
        {
            string host = Request.Scheme + "://" + Request.Host;

            Response.ContentType = "application/xml";

            using (var xml = XmlWriter.Create(Response.Body, new XmlWriterSettings {
                Indent = true
            }))
            {
                xml.WriteStartDocument();
                xml.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

                var posts = await _blog.GetPosts(int.MaxValue);

                foreach (Models.Post post in posts)
                {
                    var lastMod = new[] { post.PubDate, post.LastModified };

                    xml.WriteStartElement("url");
                    xml.WriteElementString("loc", host + PostModule.GetLink(post));
                    xml.WriteElementString("lastmod", lastMod.Max().ToString("yyyy-MM-ddThh:mmzzz"));
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
            }
        }
コード例 #2
0
        public int AddPostModule(PostModule model, string user)
        {
            int order = 1;
            //并发问题
            var query = _kHomePostModuleRepository.GetQuery()
                        .Where(t => t.ROLEID == model.RoleId)
                        .Select(t => t.ORDER)
                        .ToList();

            if (query != null && query.Count > 0)
            {
                order  = query.Max();
                order += 1;
            }

            var entity = new PKS_KHOME_POST_MODULE
            {
                NAME            = model.Name,
                ORDER           = order,
                ROLEID          = model.RoleId,
                KHOMEMODULEID   = model.ModuleId,
                CREATEDBY       = user,
                CREATEDDATE     = DateTime.Now,
                LASTUPDATEDBY   = user,
                LASTUPDATEDDATE = DateTime.Now
            };

            _kHomePostModuleRepository.Add(entity);
            return(entity.Id);
        }
コード例 #3
0
        public async Task <IActionResult> AddComment(string postId, CommentVM comment)
        {
            var post = await _blog.GetPostById(postId);

            if (!ModelState.IsValid)
            {
                return(View("Post", post));
            }

            if (post == null || !PostModule.AreCommentsOpen(post, _settings.Value.CommentsCloseAfterDays))
            {
                return(NotFound());
            }
            var cleanComment = CommentVMModule.toComment(comment);

            // the website form key should have been removed by javascript
            // unless the comment was posted by a spam robot
            if (!Request.Form.ContainsKey("website"))
            {
                post = PostModule.AddComment(cleanComment, post);
                await _blog.SavePost(post);
            }

            return(Redirect(PostModule.GetLink(post) + "#" + cleanComment.ID));
        }
コード例 #4
0
        public async Task <IActionResult> GetAll([FromQuery] ELanguage Language)
        {
            var postModule       = new PostModule(googleBloggerAppSettings, Language);
            var lstPostsResponse = await postModule.GetPosts();

            return(Ok(lstPostsResponse));
        }
コード例 #5
0
        private async Task SaveFilesToDisk(Post post)
        {
            var imgRegex    = new Regex("<img[^>].+ />", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var base64Regex = new Regex("data:[^/]+/(?<ext>[a-z]+);base64,(?<base64>.+)", RegexOptions.IgnoreCase);

            foreach (Match match in imgRegex.Matches(post.Content))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<root>" + match.Value + "</root>");

                var img          = doc.FirstChild.FirstChild;
                var srcNode      = img.Attributes["src"];
                var fileNameNode = img.Attributes["data-filename"];

                // The HTML editor creates base64 DataURIs which we'll have to convert to image files on disk
                if (srcNode != null && fileNameNode != null)
                {
                    var base64Match = base64Regex.Match(srcNode.Value);
                    if (base64Match.Success)
                    {
                        byte[] bytes = Convert.FromBase64String(base64Match.Groups["base64"].Value);
                        srcNode.Value = await _blog.SaveFile(bytes, fileNameNode.Value).ConfigureAwait(false);

                        var newContent = post.Content.Replace(match.Value, img.OuterXml);
                        img.Attributes.Remove(fileNameNode);
                        post = PostModule.WithContent(newContent, post);
                    }
                }
            }
        }
コード例 #6
0
        public async Task <IActionResult> Get([FromQuery] PostRequest PostRequest)
        {
            var postModule   = new PostModule(googleBloggerAppSettings, PostRequest.Language);
            var postResponse = await postModule.GetPost(PostRequest.PostId);

            return(Ok(postResponse));
        }
コード例 #7
0
        public async Task SavePost(Post post)
        {
            string filePath  = GetFilePath(post);
            var    postSaved = PostModule.UpdatedNow(post);

            XDocument doc = new XDocument(
                new XElement("post",
                             new XElement("title", postSaved.Title),
                             new XElement("slug", postSaved.Slug),
                             new XElement("pubDate", postSaved.PubDate.ToString("yyyy-MM-dd HH:mm:ss")),
                             new XElement("lastModified", postSaved.LastModified.ToString("yyyy-MM-dd HH:mm:ss")),
                             new XElement("excerpt", postSaved.Excerpt),
                             new XElement("content", postSaved.Content),
                             new XElement("ispublished", postSaved.IsPublished),
                             new XElement("categories", string.Empty),
                             new XElement("comments", string.Empty)
                             ));

            XElement categories = doc.XPathSelectElement("post/categories");

            foreach (string category in post.Categories)
            {
                categories.Add(new XElement("category", category));
            }

            XElement comments = doc.XPathSelectElement("post/comments");

            foreach (Comment comment in post.Comments)
            {
                comments.Add(
                    new XElement("comment",
                                 new XElement("author", comment.Author),
                                 new XElement("email", comment.Email),
                                 new XElement("date", comment.PubDate.ToString("yyyy-MM-dd HH:m:ss")),
                                 new XElement("content", comment.Content),
                                 //new XAttribute("isAdmin", comment.IsAdmin),
                                 new XAttribute("id", comment.ID)
                                 ));
            }

            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                await doc.SaveAsync(fs, SaveOptions.None, CancellationToken.None).ConfigureAwait(false);
            }

            // not equality !!!
            if (!_cache.Exists(p => p.ID == post.ID))
            {
                _cache.Add(post);
                SortCache();
            }
            else
            {
                var toUpdate = _cache.Find(p => p.ID == post.ID);
                _cache.Remove(toUpdate);
                _cache.Add(post);
                SortCache();
            }
        }
コード例 #8
0
 private void _Share(string path)
 {
     if (File.Exists(path))
     {
         PostModule.File(_profile.Id, path);
     }
     else if (Directory.Exists(path))
     {
         PostModule.Directory(_profile.Id, path);
     }
     return;
 }
コード例 #9
0
        private void _SendText()
        {
            var str = uiInputBox.Text.TrimEnd(new char[] { '\0', '\r', '\n', '\t', ' ' });

            if (str.Length < 1)
            {
                return;
            }
            uiInputBox.Text = string.Empty;
            PostModule.Text(_profile.Id, str);
            ProfileModule.SetRecent(_profile);
        }
コード例 #10
0
        private WilderMinds.MetaWeblog.Post ToMetaWebLogPost(Models.Post post)
        {
            var    request = _context.HttpContext.Request;
            string url     = request.Scheme + "://" + request.Host;

            return(new WilderMinds.MetaWeblog.Post
            {
                postid = post.ID,
                title = post.Title,
                wp_slug = post.Slug,
                permalink = url + PostModule.GetLink(post),
                dateCreated = post.PubDate,
                description = post.Content,
                categories = post.Categories.ToArray()
            });
        }
コード例 #11
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            App_Start.AutoMapperConfig.Initialize();


            NinjectModule postModule    = new PostModule();
            NinjectModule serviceModule = new ServiceModule("DefaultConnection");
            var           kernel        = new StandardKernel(postModule, serviceModule);

            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        }
コード例 #12
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            NinjectModule studentModule = new StudentModule();
            NinjectModule postModule    = new PostModule();
            NinjectModule serviceModule = new ServiceModule();
            NinjectModule tagModule     = new TagModule();
            NinjectModule commentModule = new CommentModule();
            NinjectModule autoMapper    = new AutoMapperModule();
            var           kernel        = new StandardKernel(studentModule, postModule, serviceModule, tagModule, commentModule, autoMapper);

            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        }
コード例 #13
0
        public string AddPost(string blogid, string username, string password, WilderMinds.MetaWeblog.Post post, bool publish)
        {
            ValidateUser(username, password);

            var newPost = PostModule.Create(post.title, Microsoft.FSharp.Core.OptionModule.OfObj(post.wp_slug), string.Empty, post.description, publish);

            newPost = PostModule.WithCategories(String.Join(",", post.categories), newPost);

            if (post.dateCreated != DateTime.MinValue)
            {
                newPost = PostModule.WithPubDate(post.dateCreated, newPost);
            }

            _blog.SavePost(newPost).GetAwaiter().GetResult();

            return(newPost.ID);
        }
コード例 #14
0
        private static Post LoadCategories(Post post, XElement doc)
        {
            XElement categories = doc.Element("categories");

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

            List <string> list = new List <string>();

            foreach (var node in categories.Elements("category"))
            {
                list.Add(node.Value);
            }

            return(PostModule.WithCategories(string.Join(",", list), post));
        }
コード例 #15
0
        public async Task <IActionResult> DeleteComment(string postId, string commentId)
        {
            var post = await _blog.GetPostById(postId);

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

            var comment = post.Comments.FirstOrDefault(c => c.ID.Equals(commentId, StringComparison.OrdinalIgnoreCase));

            if (comment == null)
            {
                return(NotFound());
            }
            post = PostModule.RemoveComment(comment, post);
            await _blog.SavePost(post);

            return(Redirect(PostModule.GetLink(post) + "#comments"));
        }
コード例 #16
0
        public async Task <IActionResult> UpdatePost(Post post)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit", post));
            }

            var existing = await _blog.GetPostById(post.ID) ?? post;

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

            existing = PostModule.UpdateWith(existing, post);
            existing = PostModule.WithCategories(categories, post);

            await _blog.SavePost(existing);

            await SaveFilesToDisk(existing);

            return(Redirect(PostModule.GetLink(existing)));
        }
コード例 #17
0
        private static Post LoadComments(Post post, XElement doc)
        {
            var comments = doc.Element("comments");

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

            var seq = comments.Elements("comment").Select(node => new Comment(
                                                              iD: ReadAttribute(node, "id"),
                                                              author: ReadValue(node, "author"),
                                                              email: ReadValue(node, "email"),
                                                              isAdmin: bool.Parse(ReadAttribute(node, "isAdmin", "false")),
                                                              content: ReadValue(node, "content"),
                                                              pubDate: DateTime.Parse(ReadValue(node, "date", "2000-01-01"))
                                                              ));


            return(PostModule.WithComments(ListModule.OfSeq(seq), post));
        }
コード例 #18
0
        public async Task Rss(string type)
        {
            Response.ContentType = "application/xml";
            string host = Request.Scheme + "://" + Request.Host;

            using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var posts = await _blog.GetPosts(10);

                var writer = await GetWriter(type, xmlWriter, posts.Max(p => p.PubDate));

                foreach (Models.Post post in posts)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.Content,
                        Id          = host + PostModule.GetLink(post),
                        Published   = post.PubDate,
                        LastUpdated = post.LastModified,
                        ContentType = "html",
                    };

                    foreach (string category in post.Categories)
                    {
                        item.AddCategory(new SyndicationCategory(category));
                    }

                    item.AddContributor(new SyndicationPerson(_settings.Value.Owner, "*****@*****.**"));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
コード例 #19
0
        private void _PushImage()
        {
            var ofd = new OpenFileDialog()
            {
                Filter = "位图文件|*.bmp;*.png;*.jpg"
            };

            if (ofd.ShowDialog() != true)
            {
                return;
            }
            try
            {
                var buf = CacheModule.ImageZoom(ofd.FileName);
                PostModule.Image(_profile.Id, buf);
                ProfileModule.SetRecent(_profile);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Entrance.ShowError("发送图片失败", ex);
            }
        }
コード例 #20
0
        public bool EditPost(string postid, string username, string password, WilderMinds.MetaWeblog.Post post, bool publish)
        {
            ValidateUser(username, password);

            var existing = _blog.GetPostById(postid).GetAwaiter().GetResult();

            if (existing != null)
            {
                var update = PostModule.Create(post.title, Microsoft.FSharp.Core.OptionModule.OfObj(post.wp_slug), existing.Excerpt, post.description, existing.IsPublished);
                existing = PostModule.UpdateWith(existing, update);
                existing = PostModule.WithCategories(String.Join(",", post.categories), existing);

                if (post.dateCreated != DateTime.MinValue)
                {
                    existing = PostModule.WithPubDate(post.dateCreated, existing);
                }

                _blog.SavePost(existing).GetAwaiter().GetResult();

                return(true);
            }

            return(false);
        }
コード例 #21
0
ファイル: ProfileController.cs プロジェクト: afxres/messenger
 public void Request()
 {
     PostModule.UserProfile(Source);
 }
コード例 #22
0
ファイル: ShareReceiver.cs プロジェクト: afxres/messenger
        private async Task _Start()
        {
            var soc = default(Socket);
            var iep = default(IPEndPoint);

            for (var i = 0; i < _endpoints.Length; i++)
            {
                if (soc != null)
                {
                    break;
                }
                soc = new Socket(SocketType.Stream, ProtocolType.Tcp);
                iep = _endpoints[i];

                try
                {
                    await soc.ConnectAsyncEx(iep).TimeoutAfter("Share receiver timeout.");
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    soc.Dispose();
                    soc = null;
                }
            }

            if (soc == null)
            {
                Status = ShareStatus.失败;
                Dispose();
                return;
            }

            var buf = LinksHelper.Generator.Encode(new
            {
                path   = "share." + (_batch ? "directory" : "file"),
                data   = _key,
                source = LinkModule.Id,
                target = Id,
            });

            try
            {
                _ = soc.SetKeepAlive();
                await soc.SendAsyncExt(buf);

                Status = ShareStatus.运行;
                await _Receive(soc, _cancel.Token);

                Status = ShareStatus.成功;
                PostModule.Notice(Id, _batch ? "share.dir" : "share.file", _origin);
            }
            catch (OperationCanceledException)
            {
                Status = ShareStatus.取消;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                Status = ShareStatus.中断;
            }
            finally
            {
                soc.Dispose();
                Dispose();
            }
        }