Esempio n. 1
0
        public ActionResult Edit(int?id)
        {
            var userinfo = BLLSession.UserInfoSessioin;
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("blogTag", GetDataHelper.GetAllTag(BLLSession.UserInfoSessioin.Id).ToList());
            dic.Add("blogType", CacheData.GetAllType().Where(t => t.UsersId == BLLSession.UserInfoSessioin.Id).ToList());
            List <BlogsDTO> blogs = new List <BlogsDTO>();

            if (null != id)
            {
                int          ttt;
                BLL.BlogsBLL blogbll = new BlogsBLL();
                if (id == 0)//代表 未分类
                {
                    blogs = blogbll.GetList(1, 50, out ttt, t => t.BlogTypes.Count() == 0 && (t.UsersId == userinfo.Id), false, t => t.BlogCreateTime, false)
                            .ToList().Select(t => new BlogsDTO()
                    {
                        Id        = t.Id,
                        BlogTitle = t.BlogTitle
                    }).ToList();
                }
                else
                {
                    blogs = blogbll.GetList(1, 50, out ttt, t => t.BlogTypes.Where(v => v.Id == id).Count() > 0 && (t.UsersId == userinfo.Id), false, t => t.BlogCreateTime, false)
                            .ToList().Select(t => new BlogsDTO()
                    {
                        Id        = t.Id,
                        BlogTitle = t.BlogTitle
                    }).ToList();
                }
            }
            dic.Add("blogs", blogs);
            return(View(dic));
        }
Esempio n. 2
0
        public ActionResult Release(int?id)
        {
            if (BLLSession.UserInfoSessioin == null)
            {
                Response.Redirect("/Account/Login?href=/ManageBlog/Release");
                return(null);
            }
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("blogTag", GetDataHelper.GetAllTag(BLLSession.UserInfoSessioin.UserId).ToList());
            dic.Add("blogType", DataCache.GetAllType().Where(t => t.UserId == BLLSession.UserInfoSessioin.UserId).ToList());
            Blogs blog = null;

            if (null != id)
            {
                blog = new Blogs();
                BlogsBLL blogbll = new BlogsBLL();
                blog = blogbll.GetList(t => t.BlogId == id && (t.UserId == BLLSession.UserInfoSessioin.UserId || BLLSession.UserInfoSessioin.UserName == admin)).FirstOrDefault();
                if (blog == null)
                {
                    return(View("Error"));
                }
            }
            dic.Add("blog", blog);
            return(View(dic));
        }
Esempio n. 3
0
        public ActionResult authorize_author()
        {
            var json     = new StreamReader(Request.Body).ReadToEnd();
            var data     = JsonConvert.DeserializeObject <JGN_Blogs>(json);
            var isaccess = BlogsBLL.Check(_context, data.id, data.userid);

            return(Ok(new { isaccess = isaccess }));
        }
Esempio n. 4
0
        public async Task <ActionResult> load_reports()
        {
            var json     = new StreamReader(Request.Body).ReadToEnd();
            var data     = JsonConvert.DeserializeObject <BlogEntity>(json);
            var _reports = await BlogsBLL.LoadReport(_context, data);

            return(Ok(new { data = _reports }));
        }
Esempio n. 5
0
        public async Task <ActionResult> action()
        {
            var json = new StreamReader(Request.Body).ReadToEnd();
            var data = JsonConvert.DeserializeObject <List <BlogEntity> >(json);

            await BlogsBLL.ProcessAction(_context, data);

            return(Ok(new { status = "success", message = SiteConfig.generalLocalizer["_records_processed"].Value }));
        }
Esempio n. 6
0
        /// <summary>
        /// 检查 这个 url地址 是否被添加过
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsAreBlog(string url)
        {
            //BLL.BlogsBLL blog = new BLL.BlogsBLL();
            //var blogs = blog.GetList(t => t.BlogUrl == url);
            //return blogs.Count() >= 1;
            BlogsBLL blog  = new BlogsBLL();
            var      blogs = blog.GetList(t => t.BlogUrl == url);

            return(blogs.Count() >= 1);
        }
        /// <summary>
        /// 根据博客类型或标签返回博文列表
        /// </summary>
        /// <param name="name">博客用户名</param>
        /// <param name="blogtypeid">博文类型id</param>
        /// /// <param name="typeortag">有路由器提供的参数判断是博客类型还是博客标签</param>
        /// <param name="id">页码id</param>
        /// <returns></returns>
        public ActionResult UserBlogHomeByTypeOrTag(string name, int typeortagid, string typeortag, int?id)
        {
            if (new BlogUsersBLL().GetList(t => t.UserName == name).Count() <= 0)
            {
                return(View("Error"));
            }
            int indexPage = id ?? 1;
            int totalPage = 1;
            Dictionary <string, object> dic = new Dictionary <string, object>();

            if (typeortag == "type")
            {
                int blogTypeId = typeortagid;

                var blogsList = new BlogsBLL().GetList(indexPage, pageSize, out totalPage, t => t.BlogTypes.BlogTypeId == blogTypeId, t => t.UpTime, false).ToList().Select(t => new Blog.Domain.Blogs
                {
                    BlogId       = t.BlogId,
                    BlogReadNum  = t.BlogReadNum,
                    BlogComments = t.BlogComments,
                    CreateTime   = t.CreateTime,
                    Title        = t.Title,
                    Content      = Helper.MyHtmlHelper.GetHtmlText(t.Content)
                }).ToList();
                dic.Add("blogslist", blogsList);


                dic.Add("typeortagname", "文章类型-" + new BlogTypesBLL().GetList(t => t.BlogTypeId == blogTypeId).FirstOrDefault().TypeName);
                //     dic.Add("typeortag", "Type");
            }
            if (typeortag == "tag")
            {
                int blogTagId = typeortagid;
                var blogTag   = new BlogTagsBLL().GetList(t => t.BlogTagId == blogTagId).FirstOrDefault();
                totalPage = blogTag.Blogs.Count() / pageSize;
                var blogsList = blogTag.Blogs.Skip((indexPage - 1) * pageSize).Take(pageSize).ToList().Select(t => new Blog.Domain.Blogs
                {
                    BlogId       = t.BlogId,
                    BlogReadNum  = t.BlogReadNum,
                    BlogComments = t.BlogComments,
                    CreateTime   = t.CreateTime,
                    Content      = Helper.MyHtmlHelper.GetHtmlText(t.Content),
                    Title        = t.Title
                }).ToList();
                dic.Add("blogslist", blogsList);


                dic.Add("typeortagname", "文章标签-" + new BlogTagsBLL().GetList(t => t.BlogTagId == blogTagId).FirstOrDefault().BlogTagName);
                //     dic.Add("typeortag", "Tag");
            }

            dic.Add("totalpage", totalPage);
            SetDic(dic, name);
            return(View(dic));
        }
Esempio n. 8
0
        /// <summary>
        /// 根据类型id获取所属类型文章列表(返回分部视图)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PartialViewResult EditBlogsByType(int id)
        {
            var sessionUser = BLLSession.UserInfoSessioin;

            if (sessionUser == null)
            {
                Response.Redirect("/Account/Login?href=/ManageBlog/Release");
                return(null);
            }
            List <Blogs> blogList = new List <Blogs>();
            BlogsBLL     blogBLL  = new BlogsBLL();

            blogList = blogBLL.GetList(t => t.BlogTypes.BlogTypeId == id).ToList();
            return(PartialView(blogList));
        }
Esempio n. 9
0
        public PartialViewResult FlushTypeList(int?blogid)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("blogType", DataCache.GetAllType().Where(t => t.UserId == BLLSession.UserInfoSessioin.UserId).ToList());
            Blogs blog = null;

            if (null != blogid)
            {
                blog = new Blogs();
                BlogsBLL blogbll = new BlogsBLL();
                blog = blogbll.GetList(t => t.BlogId == blogid && (t.UserId == BLLSession.UserInfoSessioin.UserId || BLLSession.UserInfoSessioin.UserName == admin)).FirstOrDefault();
            }
            dic.Add("blog", blog);
            return(PartialView(dic));
        }
Esempio n. 10
0
        public async Task <ActionResult> load()
        {
            var json   = new StreamReader(Request.Body).ReadToEnd();
            var data   = JsonConvert.DeserializeObject <BlogEntity>(json);
            var _posts = await BlogsBLL.LoadItems(_context, data);

            /* setup thumb path */
            foreach (var ph in _posts)
            {
                ph.url         = BlogUrlConfig.Generate_Post_Url(ph);
                ph.description = BlogScripts.PrepareShortDescription(ph.description, 2);
                Setup_Item(ph);
            }
            var _categories = new List <JGN_Categories>();

            if (data.loadstats)
            {
                _categories = await CategoryBLL.LoadItems(_context, new CategoryEntity()
                {
                    id         = 0,
                    type       = 6,
                    mode       = 0,
                    isenabled  = EnabledTypes.All,
                    parentid   = -1,
                    order      = "level asc", // don't change this
                    issummary  = false,
                    isdropdown = true,
                    loadall    = true // load all data
                });
            }
            var _records = 0;

            if (data.postid == 0)
            {
                _records = await BlogsBLL.Count(_context, data);
            }

            var settings = new
            {
                general = Jugnoon.Blogs.Configs.BlogSettings,
                aws     = Jugnoon.Blogs.Configs.AwsSettings
            };

            return(Ok(new { posts = _posts, records = _records, categories = _categories, settings = settings }));
        }
Esempio n. 11
0
        /// <summary>
        /// 重新获取索引
        /// </summary>
        /// <returns></returns>
        public ActionResult getIndex()
        {
            HtmlAgilityPack.HtmlDocument documnet = new HtmlDocument();
            BlogsBLL bloglist = new BlogsBLL();
            var list = new List<SearchResult>();

            list = bloglist.GetList(t => true).ToList().Select(t => new SearchResult()
            {
                blogTag = "",
                url = "/" + t.BlogUsersSet.UserName + "/" + t.Id + ".html",// t.BlogUrl,
                id = t.Id,//DocumentNode
                content = getText(t.BlogContent, documnet),
                clickQuantity = 3,
                title = t.BlogTitle,
                flag = t.UsersId
            }).ToList();

            PanGuLuceneHelper.instance.DeleteAll();
            SafetyWriteHelper<SearchResult>.logWrite(list, PanGuLuceneHelper.instance.CreateIndex);
            return Content("ok");
        }
        /// <summary>
        /// 重新获取索引
        /// </summary>
        /// <returns></returns>
        public ActionResult getIndex()
        {
            HtmlAgilityPack.HtmlDocument documnet = new HtmlDocument();
            BlogsBLL bloglist = new BlogsBLL();
            var      list     = new List <SearchResult>();

            list = bloglist.GetList(t => true).ToList().Select(t => new SearchResult()
            {
                blogTag       = "",
                url           = "/" + t.BlogUsersSet.UserName + "/" + t.Id + ".html", // t.BlogUrl,
                id            = t.Id,                                                 //DocumentNode
                content       = getText(t.BlogContent, documnet),
                clickQuantity = 3,
                title         = t.BlogTitle,
                flag          = t.UsersId
            }).ToList();

            PanGuLuceneHelper.instance.DeleteAll();
            SafetyWriteHelper <SearchResult> .logWrite(list, PanGuLuceneHelper.instance.CreateIndex);

            return(Content("ok"));
        }
Esempio n. 13
0
        public ActionResult Release(int?id)
        {
            var userinfo = BLLSession.UserInfoSessioin;

            if (null == userinfo)
            {
                Response.Redirect("/UserManage/Login?href=/Admin/Release");
                return(null);
            }
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("blogTag", GetDataHelper.GetAllTag(BLLSession.UserInfoSessioin.Id).ToList());
            dic.Add("blogType", CacheData.GetAllType().Where(t => t.UsersId == BLLSession.UserInfoSessioin.Id).ToList());
            ModelDB.Blogs blog = new ModelDB.Blogs();
            if (null != id)
            {
                BLL.BlogsBLL blogbll = new BlogsBLL();
                blog = blogbll.GetList(t => t.Id == id && (t.UsersId == userinfo.Id || userinfo.UserName == admin)).FirstOrDefault();
            }
            dic.Add("blog", blog);
            return(View(dic));
        }
Esempio n. 14
0
        /// <summary>
        /// 删除 文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Del(int?id)
        {
            var          userinfo = BLLSession.UserInfoSessioin;
            List <Blogs> blogs    = new List <Blogs>();
            bool         isdelok  = false;

            if (null != id)
            {
                BLL.BlogsBLL    blogbll = new BlogsBLL();
                BLL.BlogTagsBLL tagbll  = new BlogTagsBLL();
                var             delBlog = blogbll.GetList(t => t.BlogId == id, isAsNoTracking: false).FirstOrDefault();
                List <BlogTags> tagList = delBlog.BlogTags.ToList();



                //blogbll.Mod(new Blogs() { BlogId = (int)id,IsDel=true }, "IsDel");
                try
                {
                    foreach (var tag in tagList)
                    {
                        if (tag.Blogs.Count(t => !t.IsDel) <= 1)
                        {
                            isdelok = tagbll.Del(tag, isAsTracking: false);
                        }
                    }

                    blogbll.Del(delBlog, isAsTracking: false);
                    isdelok = blogbll.save() > 0;
                    BLL.DataCache.GetAllType(true);
                }
                catch (Exception ex)
                {
                    isdelok = false;
                    return(Content(ex.ToString()));
                }
            }
            return(Content((isdelok).ToString()));
        }
Esempio n. 15
0
        /// <summary>
        /// 删除 文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Del(int?id)
        {
            var             userinfo = BLLSession.UserInfoSessioin;
            List <BlogsDTO> blogs    = new List <BlogsDTO>();
            int             isdelok  = -1;

            if (null != id)
            {
                BLL.BlogsBLL blogbll = new BlogsBLL();
                blogbll.Del(new ModelDB.Blogs()
                {
                    Id = (int)id
                }, true);
                isdelok = blogbll.save(false);
                List <SearchResult> list = new List <SearchResult>();
                list.Add(new SearchResult()
                {
                    id = (int)id
                });
                SafetyWriteHelper <SearchResult> .logWrite(list, PanGuLuceneHelper.instance.Delete);
            }
            return(Content((isdelok > 0).ToString()));
        }
        /// <summary>
        /// 获取博主首页
        /// </summary>
        /// <param name="name">博主用户名</param>
        /// <param name="id">博主首页博客列表当前页码(为空时为第一页)</param>
        /// <returns></returns>
        public ActionResult UserBlogHome(string name, int?id)
        {
            int      myId = id ?? 1;
            int      totalPage;
            BlogsBLL blogsBLL  = new BlogsBLL();
            var      blogsList = blogsBLL.GetList(myId, pageSize, out totalPage, t => t.BlogUsers.UserName == name, t => t.UpTime, false).ToList() //linq 选择数据时候 不能new 已知的对象,只能匿名的。 但是如果从一个 List 列表 就可以new 已知的类。
                                 .Select(t => new Blog.Domain.Blogs
            {
                BlogId       = t.BlogId,
                Title        = t.Title,
                Content      = Blog.Helper.MyHtmlHelper.GetHtmlText(t.Content),
                UpTime       = t.UpTime,
                CreateTime   = t.CreateTime,
                BlogComments = t.BlogComments,
                BlogReadNum  = t.BlogReadNum
            }).ToList();
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("blogslist", blogsList);
            dic.Add("totalpage", totalPage);
            SetDic(dic, name);
            return(View(dic));
        }
Esempio n. 17
0
        public async Task <ActionResult> getinfo()
        {
            var json = new StreamReader(Request.Body).ReadToEnd();
            var data = JsonConvert.DeserializeObject <BlogEntity>(json);

            data.nofilter = true;
            var _posts = await BlogsBLL.LoadItems(_context, data);

            if (_posts.Count > 0)
            {
                if (_posts[0].picture_url != "")
                {
                    var _pics = _posts[0].picture_url.Split(char.Parse(","));
                    _posts[0].files = new List <FileEntity>();
                    foreach (var pic in _pics)
                    {
                        _posts[0].files.Add(new FileEntity()
                        {
                            filename = pic,
                            img_url  = pic
                        });
                    }
                }

                Setup_Item(_posts[0]);

                _posts[0].author.img_url = UserUrlConfig.ProfilePhoto(_posts[0].author.Id, _posts[0].author.picturename, 0);
                // array of associate category list
                _posts[0].category_list = await CategoryContentsBLL.FetchContentCategoryList(_context, data.id, (byte)CategoryContentsBLL.Types.Blogs);

                return(Ok(new { status = "success", post = _posts[0] }));
            }
            else
            {
                return(Ok(new { status = "error", message = SiteConfig.generalLocalizer["_no_records"].Value }));
            }
        }
Esempio n. 18
0
        //
        // GET: /Home/

        public ActionResult Index(int?page, int?sorttype)
        {
            BlogsBLL     blogBll   = new BlogsBLL();
            int          total     = 0;
            int          pageIndex = page ?? 1;
            int          sortType  = sorttype ?? 1;
            List <Blogs> bloglist  = null;

            if (sortType == 2)
            {
                bloglist = blogBll.GetList(pageIndex, pageSize, out total, t => t.IsShowHome == true, t => t.CreateTime, false).ToList();
            }
            else if (sortType == 4)
            {
                bloglist = blogBll.GetList(pageIndex, pageSize, out total, t => t.IsShowHome == true, t => t.CreateTime, false).ToList();
            }
            else if (sortType == 3)
            {
                bloglist = blogBll.GetList(pageIndex, pageSize, out total, t => t.IsShowHome == true, t => t.BlogReadNum, false).ToList();
            }
            else
            {
                bloglist = blogBll.GetList(pageIndex, pageSize, out total, t => t.IsShowHome == true, t => t.UpTime, false).ToList();
            }
            bloglist.ForEach(t =>
            {
                t.BlogRemarks = Blog.Helper.MyHtmlHelper.GetHtmlText(t.Content);
            });
            Dictionary <string, Object> dic = new Dictionary <string, object>();

            dic.Add("blog", bloglist);
            dic.Add("users", BLL.DataCache.GetUsersInfo());
            dic.Add("userSession", BLL.Common.BLLSession.UserInfoSessioin);
            dic.Add("total", total);
            return(View(dic));
        }
Esempio n. 19
0
        /// <summary>
        /// 删除文章类型
        /// </summary>
        /// <param name="id">要删除的类型id</param>
        /// <returns></returns>
        public String DeleteTypeById(int id)
        {
            bool         result        = false;
            BlogsBLL     blogBLL       = new BlogsBLL();
            BlogTypesBLL typeBLL       = new BlogTypesBLL();
            var          theTypeBlogs  = blogBLL.GetList(t => t.BlogTypeId == id, isAsNoTracking: false).ToList();
            var          defaultTypeID = typeBLL.GetList(t => t.TypeName == "未分类").FirstOrDefault().BlogTypeId;

            foreach (Blogs blog in theTypeBlogs)  //将属于要删除类型的博客分到 未分类 中
            {
                blog.BlogTypeId = defaultTypeID;
            }
            try
            {
                blogBLL.save();
                result = typeBLL.Del(t => t.BlogTypeId == id);
                BLL.DataCache.GetAllType(true);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
            return(result.ToString());
        }
Esempio n. 20
0
 public ActionResult Release(int? id)
 {
     var userinfo = BLLSession.UserInfoSessioin;
     if (null == userinfo)
     {
         Response.Redirect("/UserManage/Login?href=/Admin/Release");
         return null;
     }
     Dictionary<string, object> dic = new Dictionary<string, object>();
     dic.Add("blogTag", GetDataHelper.GetAllTag(BLLSession.UserInfoSessioin.Id).ToList());
     dic.Add("blogType", CacheData.GetAllType().Where(t => t.UsersId == BLLSession.UserInfoSessioin.Id).ToList());
     ModelDB.Blogs blog = new ModelDB.Blogs();
     if (null != id)
     {
         BLL.BlogsBLL blogbll = new BlogsBLL();
         blog = blogbll.GetList(t => t.Id == id && (t.UsersId == userinfo.Id || userinfo.UserName == admin)).FirstOrDefault();
     }
     dic.Add("blog", blog);
     return View(dic);
 }
Esempio n. 21
0
        public PartialViewResult SearchBlogResult()
        {
            if (!Request.QueryString.AllKeys.Contains("keyword"))
            {
                return(null);
            }
            string keyword = Request.QueryString["keyword"].Trim();

            if (String.IsNullOrEmpty(keyword))
            {
                return(null);
            }
            int type = int.Parse(Request.QueryString["type"]);

            if (type == 1)
            {
                BlogsBLL blogBLL   = new BlogsBLL();
                string   pIndex    = Request.QueryString.AllKeys.Contains("page") ? Request.QueryString["page"] : "";
                int      PageIndex = 1;
                int.TryParse(pIndex, out PageIndex);
                int totalPage  = 1;
                int totalCount = blogBLL.GetList(t => t.Title.Contains(keyword)).Count();
                var searchlist = blogBLL.GetList(PageIndex, pageSize, out totalPage, t => t.Title.Contains(keyword), t => t.CreateTime).ToList().Select(t => new Blogs
                {
                    Title      = t.Title,
                    Content    = Helper.MyHtmlHelper.GetHtmlText(t.Content).Count() > 300 ? Helper.MyHtmlHelper.GetHtmlText(t.Content).Substring(0, 300) : Helper.MyHtmlHelper.GetHtmlText(t.Content),
                    CreateTime = t.CreateTime,
                    BlogUrl    = t.BlogUrl,
                    BlogUsers  = t.BlogUsers
                }).ToList();
                CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo;
                searchlist.ForEach(t =>
                {
                    t.Title = t.Title.Insert(compareInfo.IndexOf(t.Title, keyword, CompareOptions.IgnoreCase), "<strong>");
                    t.Title = t.Title.Insert(compareInfo.IndexOf(t.Title, keyword, CompareOptions.IgnoreCase) + keyword.Count(), "</strong>");
                });
                Dictionary <string, object> dicResult = new Dictionary <string, object>();
                dicResult.Add("blogslist", searchlist);
                dicResult.Add("totalpage", totalPage);
                dicResult.Add("count", totalCount);
                return(PartialView(dicResult));
            }
            else if (type == 2)
            {
                BlogsBLL    blogBLL     = new BlogsBLL();
                CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo;
                string      pIndex      = Request.QueryString.AllKeys.Contains("page") ? Request.QueryString["page"] : "";
                int         PageIndex   = 1;
                int.TryParse(pIndex, out PageIndex);
                int totalPage  = 1;
                int totalCount = blogBLL.GetList(t => t.BlogRemarks.Contains(keyword)).Count();
                var searchlist = blogBLL.GetList(PageIndex, pageSize, out totalPage, t => (t.BlogRemarks).Contains(keyword), t => t.CreateTime, isAsc: false).ToList().Select(t => new Blogs
                {
                    Title   = t.Title,
                    Content = t.BlogRemarks.Substring(compareInfo.IndexOf(t.BlogRemarks, keyword, CompareOptions.IgnoreCase) >= 10 ? compareInfo.IndexOf(t.BlogRemarks, keyword, CompareOptions.IgnoreCase) - 10 : compareInfo.IndexOf(t.BlogRemarks, keyword, CompareOptions.IgnoreCase)
                                                      , t.BlogRemarks.Length - compareInfo.IndexOf(t.BlogRemarks, keyword, CompareOptions.IgnoreCase) > 300 ? 300 : t.BlogRemarks.Length - compareInfo.IndexOf(t.BlogRemarks, keyword, CompareOptions.IgnoreCase)),
                    CreateTime = t.CreateTime,
                    BlogUrl    = t.BlogUrl,
                    BlogUsers  = t.BlogUsers
                }).ToList();
                searchlist.ForEach(t =>
                {
                    t.Content = t.Content.Insert(compareInfo.IndexOf(t.Content, keyword, CompareOptions.IgnoreCase), "<strong>");
                    t.Content = t.Content.Insert(compareInfo.IndexOf(t.Content, keyword, CompareOptions.IgnoreCase) + keyword.Count(), "</strong>");
                });
                Dictionary <string, object> dicResult = new Dictionary <string, object>();
                dicResult.Add("blogslist", searchlist);
                dicResult.Add("totalpage", totalPage);
                dicResult.Add("count", totalCount);
                return(PartialView(dicResult));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 22
0
        public void ProcessRequest(HttpContext context)
        {
            var json        = new StreamReader(context.Request.InputStream).ReadToEnd();
            var responseMsg = new Dictionary <string, string>();

            long   PostID     = 0;
            int    Type       = 0;
            string UserName   = "";
            bool   IsUpdate   = false;
            long   GalleryID  = 0;
            int    Status     = 0;
            int    isApproved = 0;
            int    OldValue   = 0;
            int    NewValue   = 0;
            string Value      = "";
            string FieldName  = "";
            int    Records    = 0;
            bool   isAdmin    = false;

            var _videoobj      = new BlogsBLL();
            var _ld_video_data = new Dictionary <string, BlogsObject>();

            if ((context.Request.Params["action"] != null))
            {
                switch (context.Request.Params["action"])
                {
                case "add":
                    // Authentication
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Authentication Failed";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    if (context.Request.Params["isadmin"] != null)
                    {
                        isAdmin = Convert.ToBoolean(context.Request.Params["isadmin"]);
                    }

                    BlogsBLL.Add(JsonConvert.DeserializeObject <Blogs_Struct>(json), isAdmin);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);
                    break;


                case "check":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt64(context.Request.Params["vid"]);
                    }
                    if (context.Request.Params["user"] != null)
                    {
                        UserName = context.Request.Params["user"].ToString();
                    }
                    if (BlogsBLL.Check(PostID, UserName))
                    {
                        responseMsg["status"]  = "success";
                        responseMsg["message"] = "Validated";
                    }
                    else
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Not Validated";
                    }
                    context.Response.Write(responseMsg);
                    break;



                // This update is only for pubplishing pending videos (unpublished videos only)
                case "update":

                    // Authentication
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        responseMsg["status"]  = "error";
                        responseMsg["message"] = "Authentication Failed";
                        context.Response.Write(responseMsg);
                        return;
                    }

                    BlogsBLL.Update(JsonConvert.DeserializeObject <Blogs_Struct>(json));

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);
                    break;

                case "delete":

                    var _del_post = JsonConvert.DeserializeObject <Blogs_Struct>(json);

                    BlogsBLL.Delete(_del_post.PostID, _del_post.UserName);

                    break;


                case "count":

                    if (context.Request.Params["type"] != null)
                    {
                        Type = Convert.ToInt32(context.Request.Params["type"]);
                    }
                    if (context.Request.Params["status"] != null)
                    {
                        Status = Convert.ToInt32(context.Request.Params["status"]);
                    }
                    if (context.Request.Params["approved"] != null)
                    {
                        isApproved = Convert.ToInt32(context.Request.Params["approved"]);
                    }

                    var _Output = new Dictionary <string, int>();
                    _Output["records"] = BlogsBLL.Count(UserName, Status, isApproved);

                    context.Response.Write(_Output);

                    break;

                case "update_isenabled":

                    if (context.Request.Params["oval"] != null)
                    {
                        OldValue = Convert.ToInt32(context.Request.Params["oval"]);
                    }
                    if (context.Request.Params["nval"] != null)
                    {
                        NewValue = Convert.ToInt32(context.Request.Params["nval"]);
                    }

                    var _upd_isenabled = JsonConvert.DeserializeObject <Blogs_Struct>(json);

                    BlogsBLL.Update_IsEnabled(_upd_isenabled.PostID, OldValue, NewValue, _upd_isenabled.UserName);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);

                    break;

                case "update_isapproved":

                    if (context.Request.Params["oval"] != null)
                    {
                        OldValue = Convert.ToInt32(context.Request.Params["oval"]);
                    }
                    if (context.Request.Params["nval"] != null)
                    {
                        NewValue = Convert.ToInt32(context.Request.Params["nval"]);
                    }

                    var _upd_isreviewed = JsonConvert.DeserializeObject <Blogs_Struct>(json);

                    BlogsBLL.Update_IsApproved(_upd_isreviewed.PostID, OldValue, NewValue, _upd_isreviewed.UserName);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);

                    break;


                case "update_field":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    if (context.Request.Params["val"] != null)
                    {
                        Value = context.Request.Params["val"].ToString();
                    }
                    if (context.Request.Params["field"] != null)
                    {
                        FieldName = context.Request.Params["field"].ToString();
                    }

                    BlogsBLL.Update_Field(PostID, Value, FieldName);

                    responseMsg["status"]  = "success";
                    responseMsg["message"] = "Operation Commit";
                    context.Response.Write(responseMsg);
                    break;

                case "get_field_value":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }

                    if (context.Request.Params["field"] != null)
                    {
                        FieldName = context.Request.Params["field"].ToString();
                    }



                    responseMsg["value"] = BlogsBLL.Get_Field_Value(PostID, FieldName);

                    context.Response.Write(responseMsg);
                    break;

                case "load_blogs":

                    var _ld_video_json = JsonConvert.DeserializeObject <Blogs_Struct>(json);
                    var _vObject       = new BlogsObject()
                    {
                        Data  = BlogsBLL.Load_Blogs_V4(_ld_video_json),
                        Count = BlogsBLL.Cache_Count_Blogs_V4(_ld_video_json)
                    };

                    _ld_video_data["data"] = _vObject;

                    context.Response.Write(_ld_video_data);

                    break;

                case "load_photos_limit":
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Load_Blogs_Limit(JsonConvert.DeserializeObject <Blogs_Struct>(json)),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_record":
                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Fetch_Blog(PostID),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_sm":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Fetch_Blog_SM(PostID),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "get_sm_info":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Get_SM_Info(PostID),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "post_info":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Fetch_Post_Info(PostID),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "fetch_blog_information":

                    if (context.Request.Params["vid"] != null)
                    {
                        PostID = Convert.ToInt32(context.Request.Params["vid"]);
                    }
                    _ld_video_data["data"] = new BlogsObject()
                    {
                        Data  = BlogsBLL.Fetch_Blog_Info(PostID),
                        Count = 0
                    };
                    context.Response.Write(_ld_video_data);

                    break;

                case "archive_list":

                    if (context.Request.Params["type"] != null)
                    {
                        Type = Convert.ToInt32(context.Request.Params["type"]);
                    }
                    if (context.Request.Params["records"] != null)
                    {
                        Records = Convert.ToInt32(context.Request.Params["records"]);
                    }
                    bool isAll = false;
                    if (context.Request.Params["isall"] != null)
                    {
                        isAll = Convert.ToBoolean(context.Request.Params["isall"]);
                    }
                    var _archive = new Dictionary <string, List <Archive_Struct> >();
                    _archive["data"] = BlogsBLL.Load_Arch_List(Records, isAll);
                    context.Response.Write(_archive);

                    break;
                }
            }
            else
            {
                // No action found
                responseMsg["status"]  = "error";
                responseMsg["message"] = "No action found";
                context.Response.Write(JsonConvert.SerializeObject(responseMsg));
            }
        }
Esempio n. 23
0
        public async Task <ActionResult> proc()
        {
            var json  = new StreamReader(Request.Body).ReadToEnd();
            var model = JsonConvert.DeserializeObject <JGN_Blogs>(json);

            if (model.title != null && model.title.Length < 5)
            {
                return(Ok(new { status = "error", message = "Please enter title" }));
            }

            if (model.description == null || model.description == "" || model.description.Length < 10)
            {
                return(Ok(new { status = "error", message = "Please enter proper description" }));
            }

            // validate tags
            if (model.tags != null && Jugnoon.Settings.Configs.FeatureSettings.enable_tags)
            {
                if (!TagsBLL.Validate_Tags(model.tags))
                {
                    return(Ok(new { status = "error", message = "Tags not validated" }));
                }

                // Process tags
                if (model.tags != "")
                {
                    TagsBLL.Process_Tags(_context, model.tags, TagsBLL.Types.Blogs, 0);
                }
            }

            var b_settings = new Jugnoon.Blogs.Settings.General();
            // process categories
            int _isapproved = 1; // enable it bydefault

            if (b_settings.blogPostModeration == 1)
            {
                // Moderator Review Required
                _isapproved = 0;
            }

            //XSS CLEANUP
            string content = "";

            if (model.description != null && model.description != "")
            {
                content = UGeneral.SanitizeText(model.description);
            }


            // normal tags
            if (b_settings.tag_Processing)
            {
                content = BlogScripts.Generate_Auto_Tag_Links(_context, content);
            }
            // normal category
            if (b_settings.category_Processing)
            {
                content = BlogScripts.Generate_Auto_Category_Links(_context, content);
            }

            // blog banner upload functionality
            if (model.cover_url != null && model.cover_url != "")
            {
                if (model.cover_url.StartsWith("data:image"))
                {
                    // base 64 image
                    var    image_url = model.cover_url.Replace("data:image/png;base64,", "");
                    byte[] image     = Convert.FromBase64String(image_url);
                    // create image name
                    var _title = UtilityBLL.ReplaceSpaceWithHyphin(model.title);
                    if (_title.Length > 15)
                    {
                        _title = _title.Substring(0, 15);
                    }
                    string thumbFileName = _title + Guid.NewGuid().ToString().Substring(0, 8) + ".png";

                    var path = SiteConfig.Environment.ContentRootPath + DirectoryPaths.BlogsPhotoDirectoryPath;
                    if (System.IO.File.Exists(path + "" + thumbFileName))
                    {
                        System.IO.File.Delete(path + "" + thumbFileName);
                    }

                    // local storage
                    System.IO.File.WriteAllBytes(path + "" + thumbFileName, image);
                    model.cover_url = await Jugnoon.Helper.Aws.UploadPhoto(_context, thumbFileName, path, Jugnoon.Blogs.Configs.AwsSettings.midthumb_directory_path);
                }
            }
            // normal blog posts upload
            string _publish_path = "";

            // Add information in table
            var filename = new StringBuilder();

            if (model.files.Count > 0)
            {
                foreach (var item in model.files)
                {
                    if (filename.ToString().Length > 0)
                    {
                        filename.Append(",");
                    }
                    filename.Append(item.filename);
                }
            }

            if (filename.ToString() != "")
            {
                _publish_path = AwsCloud.UploadPostCover(filename.ToString(), model.userid);
            }
            else
            {
                _publish_path = filename.ToString();
            }


            if (model.id == 0)
            {
                var blg = new JGN_Blogs();
                blg.categories = model.categories;
                blg.userid     = model.userid;
                if (model.title != null)
                {
                    blg.title = model.title;
                    if (blg.title.Length > 100)
                    {
                        blg.title = blg.title.Substring(0, 99);
                    }
                }
                blg.description = content;
                if (model.tags != null)
                {
                    blg.tags = model.tags;
                    if (blg.tags.Length > 300)
                    {
                        blg.tags = blg.tags.Substring(0, 299);
                    }
                }
                blg.isenabled       = 1; // enabled in start
                blg.isapproved      = (byte)_isapproved;
                blg.picture_caption = model.picture_caption;
                blg.picture_url     = _publish_path; // filename
                blg.cover_url       = model.cover_url;
                blg = await BlogsBLL.Add(_context, blg);

                Setup_Item(blg);

                return(Ok(new { status = "success", record = blg, message = SiteConfig.generalLocalizer["_record_created"].Value }));
            }
            else
            {
                var blg = new JGN_Blogs();
                blg.id     = model.id;
                blg.userid = model.userid;
                if (model.title != null)
                {
                    blg.title = model.title;
                }
                blg.description = content;
                if (model.tags != null)
                {
                    blg.tags = model.tags;
                }
                blg.isapproved      = (byte)_isapproved;
                blg.categories      = model.categories;
                blg.picture_caption = model.picture_caption;
                blg.picture_url     = _publish_path;

                Setup_Item(blg);
                await BlogsBLL.Update(_context, blg);

                return(Ok(new { status = "success", record = blg, message = SiteConfig.generalLocalizer["_record_updated"].Value }));
            }
        }
Esempio n. 24
0
        // GET: blogs
        public async Task <IActionResult> Index(string order, string filter, int?pagenumber)
        {
            ViewBag.BlogsTabCss = "active";

            if (pagenumber == null)
            {
                pagenumber = 1;
            }

            string _order          = "blog.created_at desc";
            var    _dateFilter     = DateFilter.AllTime;
            var    _featuredFilter = FeaturedTypes.All;
            /* ***************************************/
            // Process Page Meta & BreaCrumb
            /* ***************************************/
            var pageOrder  = "recent";
            var pageFilter = "";

            if (order != null)
            {
                pageOrder = order;
            }
            if (filter != null)
            {
                pageFilter = filter;
            }
            var _meta = PageMeta.returnPageMeta(new PageQuery()
            {
                controller = ControllerContext.ActionDescriptor.ControllerName,
                index      = ControllerContext.ActionDescriptor.ActionName,
                order      = pageOrder,
                filter     = pageFilter,
                pagenumber = (int)pagenumber
            });

            // pagination
            var DefaultUrl    = Config.GetUrl("blogs/");
            var PaginationUrl = Config.GetUrl("blogs/page/[p]/");

            // order
            var selectedOrder  = SiteConfig.generalLocalizer["_recent"].Value;
            var selectedFilter = SiteConfig.generalLocalizer["_all_time"].Value;

            if (order != null)
            {
                DefaultUrl    = Config.GetUrl("blogs/" + order.ToLower().Trim());
                PaginationUrl = Config.GetUrl("blogs/" + order.ToLower().Trim() + "/[p]/");
                switch (order)
                {
                case "featured":
                    selectedOrder   = SiteConfig.generalLocalizer["_featured"].Value;
                    _order          = "blog.created_at desc";
                    _featuredFilter = FeaturedTypes.Featured;
                    break;
                }
            }

            if (filter != null)
            {
                // pagination setting
                if (filter == "today" || filter == "thisweek" || filter == "thismonth")
                {
                    DefaultUrl    = Config.GetUrl("blogs/added/" + filter.ToLower().Trim());
                    PaginationUrl = Config.GetUrl("blogs/added/" + filter.ToLower().Trim() + "/[p]/");
                }

                switch (filter)
                {
                case "today":
                    selectedFilter = SiteConfig.generalLocalizer["_today"].Value;
                    _dateFilter    = DateFilter.Today;
                    break;

                case "thisweek":
                    selectedFilter = SiteConfig.generalLocalizer["_this_week"].Value;
                    _dateFilter    = DateFilter.ThisWeek;
                    break;

                case "thismonth":
                    selectedFilter = SiteConfig.generalLocalizer["_this_month"].Value;
                    _dateFilter    = DateFilter.ThisWeek;
                    break;
                }
            }

            /* List Initialization */
            var ListEntity = new BlogListViewModel()
            {
                isListStatus = false,
                Navigation   = prepareFilterLinks("/blogs/", selectedOrder, selectedFilter),
                QueryOptions = new BlogEntity()
                {
                    pagenumber = (int)pagenumber,
                    term       = "",
                    iscache    = true,
                    ispublic   = true,
                    pagesize   = Jugnoon.Settings.Configs.GeneralSettings.pagesize,
                    isfeatured = _featuredFilter,
                    datefilter = _dateFilter,
                    order      = _order,
                },
                ListObject = new ListItems()
                {
                    // ColWidth = "col-md-4 col-masonry",
                    ListType = ListType.List, // 0: grid 1: list
                },
                HeadingTitle      = _meta.title,
                BreadItems        = _meta.BreadItems,
                DefaultUrl        = DefaultUrl,
                PaginationUrl     = PaginationUrl,
                NoRecordFoundText = SiteConfig.generalLocalizer["_no_records"].Value,
            };

            ListEntity.TotalRecords = await BlogsBLL.Count(_context, ListEntity.QueryOptions);

            if (ListEntity.TotalRecords > 0)
            {
                ListEntity.DataList = await BlogsBLL.LoadItems(_context, ListEntity.QueryOptions);
            }

            // Page Meta Description
            ViewBag.title       = _meta.title;
            ViewBag.description = _meta.description;
            ViewBag.keywords    = _meta.keywords;
            ViewBag.imageurl    = _meta.imageurl;

            return(View(ListEntity));
        }
Esempio n. 25
0
        /// <summary>
        /// 根据用户导入cnblog数据
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public string Import(string userName, string iszf, string isshowhome, string isshowmyhome)
        {
            userName = userName.Trim();
            int blosNumber = 0;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx";
            HtmlAgilityPack.HtmlWeb htmlweb = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
            var docment = htmlweb.Load(url);
            string userid = GetCnblogUserId(userName);
            var liS = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li");
            foreach (var item in liS)
            {
                var tXPath = item.XPath;
                var href = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value;
                var blogtype = htmlweb.Load(href);
                //var entrylistItem = blogtype.DocumentNode.SelectNodes("//*[@id='mainContent']/div/div[2]/div[@class='entrylistItem']");
                var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']");
                if (null == entrylistItem)//做兼容
                    entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); //
                if (null == entrylistItem)
                {
                    continue;
                }
                foreach (var typeitem in entrylistItem)
                {
                    var typeitemXPath = typeitem.XPath;
                    var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a");
                    if (null == typeitemhrefObj) //做兼容
                        typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a");
                    var typeitemhref = typeitemhrefObj.Attributes["href"].Value;
                    if (IsAreBlog(typeitemhref))
                        continue;//说明这篇文章已经备份过了的
                    var bloghtml = htmlweb.Load(typeitemhref);
                    var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml;
                    if (blogcontextobj == null) continue;//有可能是加密文章
                    var blogcontext = blogcontextobj.InnerHtml;

                    var blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='Header1_HeaderTitle']");
                    if (null == blogNameObj)
                        blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='lnkBlogTitle']");
                    try
                    {
                        blogName = blogNameObj.InnerText;
                    }
                    catch (Exception)
                    { }

                    var blogtitle = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText;
                    var blogurl = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value;
                    var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "&postId=" +
                        typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
                    var blogtag = Blogs.Common.Helper.MyHtmlHelper.GetRequest(blogtypetagurl);
                    var jsonobj = jss.Deserialize<Dictionary<string, string>>(blogtag);
                    if (null == jsonobj)
                        continue;//如果没有 则返回  (这里只能去 数字.html  不能取那种自定义的url)
                    var tagSplit = jsonobj["Tags"].Split(',');
                    var blogtagid = new List<int>();
                    for (int i = 0; i < tagSplit.Length; i++)
                    {
                        if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1);
                            blogtagid.Add(this.GetTagId(blogtagname, userName));
                        }
                    }
                    var categoriesSplit = jsonobj["Categories"].Split(',');
                    var blogtypeid = new List<int>();
                    for (int i = 0; i < categoriesSplit.Length; i++)
                    {
                        if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1);
                            blogtypeid.Add(this.GetTypeId(blogtypename, userName));
                        }
                    }
                    var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']");
                    var blogtime = "";
                    if (null != blogtimeobj)
                        blogtime = blogtimeobj.InnerText;

                    DateTime? createtime = null;
                    var Outcreatetime = DateTime.Now;
                    if (DateTime.TryParse(blogtime, out Outcreatetime))
                        createtime = Outcreatetime;
                    BlogsBLL blog = new BlogsBLL();
                    var myBlogTags = new BlogTagsBLL().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList();//.ToList();

                    var myBlogTypes = new BLL.BlogTypesBLL().GetList(t => blogtypeid.Contains(t.Id), isAsNoTracking: false).ToList();//.ToList();
                    try
                    {
                        var modelMyBlogs = new ModelDB.Blogs()
                        {
                            BlogContent = blogcontext,
                            BlogCreateTime = createtime,
                            BlogTitle = blogtitle,
                            BlogUrl = blogurl,
                            IsDel = false,
                            BlogTags = myBlogTags,
                            BlogTypes = myBlogTypes,
                            UsersId = GetUserId(userName),
                            BlogForUrl = blogurl,
                            IsForwarding = iszf == "true",
                            IsShowMyHome = isshowmyhome == "true",
                            IsShowHome = isshowhome == "true"
                        };
                        blog.Add(modelMyBlogs);
                        blog.save();
                        var newtag = string.Empty;
                        try
                        {
                            modelMyBlogs.BlogTags.Where(t => true).ToList().ForEach(t => newtag += t.TagName + " ");
                            var newblogurl = "/" + modelMyBlogs.BlogUsersSet.UserName + "/" + modelMyBlogs.Id + ".html";
                            SearchResult search = new SearchResult()
                            {
                                flag = modelMyBlogs.UsersId,
                                id = modelMyBlogs.Id,
                                title = blogtitle,
                                clickQuantity = 0,
                                blogTag = newtag,
                                content = getText(blogcontext, document),
                                url = newblogurl
                            };

                            SafetyWriteHelper<SearchResult>.logWrite(search, PanGuLuceneHelper.instance.CreateIndex);
                        }
                        catch (Exception)
                        {
                        }

                        var postid = blogurl.Substring(blogurl.LastIndexOf('/') + 1);
                        postid = postid.Substring(0, postid.LastIndexOf('.'));
                        testJumonyParser(modelMyBlogs.Id, postid, userName);

                        blosNumber++;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            if (blosNumber > 0)
            {
                Blogs.BLL.Common.GetDataHelper.GetAllTag();
                Blogs.BLL.Common.CacheData.GetAllType(true);
                Blogs.BLL.Common.CacheData.GetAllUserInfo(true);
                return "成功导入" + blosNumber + "篇Blog";
            }
            return "ok";
        }
        /// <summary>
        /// 根据用户导入cnblog数据
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public string Import(string userName, string iszf, string isshowhome, string isshowmyhome)
        {
            userName = userName.Trim();
            int blosNumber           = 0;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx";

            HtmlAgilityPack.HtmlWeb      htmlweb  = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
            var    docment = htmlweb.Load(url);
            string userid  = GetCnblogUserId(userName);
            var    liS     = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li");

            foreach (var item in liS)
            {
                var tXPath   = item.XPath;
                var href     = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value;
                var blogtype = htmlweb.Load(href);
                //var entrylistItem = blogtype.DocumentNode.SelectNodes("//*[@id='mainContent']/div/div[2]/div[@class='entrylistItem']");
                var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']");
                if (null == entrylistItem)                                                                    //做兼容
                {
                    entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); //
                }
                if (null == entrylistItem)
                {
                    continue;
                }
                foreach (var typeitem in entrylistItem)
                {
                    var typeitemXPath   = typeitem.XPath;
                    var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a");
                    if (null == typeitemhrefObj) //做兼容
                    {
                        typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a");
                    }
                    var typeitemhref = typeitemhrefObj.Attributes["href"].Value;
                    if (IsAreBlog(typeitemhref))
                    {
                        continue;//说明这篇文章已经备份过了的
                    }
                    var bloghtml       = htmlweb.Load(typeitemhref);
                    var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml;
                    if (blogcontextobj == null)
                    {
                        continue;                        //有可能是加密文章
                    }
                    var blogcontext = blogcontextobj.InnerHtml;

                    var blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='Header1_HeaderTitle']");
                    if (null == blogNameObj)
                    {
                        blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='lnkBlogTitle']");
                    }
                    try
                    {
                        blogName = blogNameObj.InnerText;
                    }
                    catch (Exception)
                    { }

                    var blogtitle      = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText;
                    var blogurl        = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value;
                    var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "&postId=" +
                                         typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
                    var blogtag = Blogs.Common.Helper.MyHtmlHelper.GetRequest(blogtypetagurl);
                    var jsonobj = jss.Deserialize <Dictionary <string, string> >(blogtag);
                    if (null == jsonobj)
                    {
                        continue;//如果没有 则返回  (这里只能去 数字.html  不能取那种自定义的url)
                    }
                    var tagSplit  = jsonobj["Tags"].Split(',');
                    var blogtagid = new List <int>();
                    for (int i = 0; i < tagSplit.Length; i++)
                    {
                        if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1);
                            blogtagid.Add(this.GetTagId(blogtagname, userName));
                        }
                    }
                    var categoriesSplit = jsonobj["Categories"].Split(',');
                    var blogtypeid      = new List <int>();
                    for (int i = 0; i < categoriesSplit.Length; i++)
                    {
                        if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1)
                        {
                            var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1);
                            blogtypeid.Add(this.GetTypeId(blogtypename, userName));
                        }
                    }
                    var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']");
                    var blogtime    = "";
                    if (null != blogtimeobj)
                    {
                        blogtime = blogtimeobj.InnerText;
                    }

                    DateTime?createtime    = null;
                    var      Outcreatetime = DateTime.Now;
                    if (DateTime.TryParse(blogtime, out Outcreatetime))
                    {
                        createtime = Outcreatetime;
                    }
                    BlogsBLL blog       = new BlogsBLL();
                    var      myBlogTags = new BlogTagsBLL().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList();   //.ToList();

                    var myBlogTypes = new BLL.BlogTypesBLL().GetList(t => blogtypeid.Contains(t.Id), isAsNoTracking: false).ToList(); //.ToList();
                    try
                    {
                        var modelMyBlogs = new ModelDB.Blogs()
                        {
                            BlogContent    = blogcontext,
                            BlogCreateTime = createtime,
                            BlogTitle      = blogtitle,
                            BlogUrl        = blogurl,
                            IsDel          = false,
                            BlogTags       = myBlogTags,
                            BlogTypes      = myBlogTypes,
                            UsersId        = GetUserId(userName),
                            BlogForUrl     = blogurl,
                            IsForwarding   = iszf == "true",
                            IsShowMyHome   = isshowmyhome == "true",
                            IsShowHome     = isshowhome == "true"
                        };
                        blog.Add(modelMyBlogs);
                        blog.save();
                        var newtag = string.Empty;
                        try
                        {
                            modelMyBlogs.BlogTags.Where(t => true).ToList().ForEach(t => newtag += t.TagName + " ");
                            var          newblogurl = "/" + modelMyBlogs.BlogUsersSet.UserName + "/" + modelMyBlogs.Id + ".html";
                            SearchResult search     = new SearchResult()
                            {
                                flag          = modelMyBlogs.UsersId,
                                id            = modelMyBlogs.Id,
                                title         = blogtitle,
                                clickQuantity = 0,
                                blogTag       = newtag,
                                content       = getText(blogcontext, document),
                                url           = newblogurl
                            };

                            SafetyWriteHelper <SearchResult> .logWrite(search, PanGuLuceneHelper.instance.CreateIndex);
                        }
                        catch (Exception)
                        {
                        }

                        var postid = blogurl.Substring(blogurl.LastIndexOf('/') + 1);
                        postid = postid.Substring(0, postid.LastIndexOf('.'));
                        testJumonyParser(modelMyBlogs.Id, postid, userName);

                        blosNumber++;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            if (blosNumber > 0)
            {
                Blogs.BLL.Common.GetDataHelper.GetAllTag();
                Blogs.BLL.Common.CacheData.GetAllType(true);
                Blogs.BLL.Common.CacheData.GetAllUserInfo(true);
                return("成功导入" + blosNumber + "篇Blog");
            }
            return("ok");
        }
Esempio n. 27
0
        public ActionResult Edit(int? id)
        {
            var userinfo = BLLSession.UserInfoSessioin;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("blogTag", GetDataHelper.GetAllTag(BLLSession.UserInfoSessioin.Id).ToList());
            dic.Add("blogType", CacheData.GetAllType().Where(t => t.UsersId == BLLSession.UserInfoSessioin.Id).ToList());
            List<BlogsDTO> blogs = new List<BlogsDTO>();
            if (null != id)
            {
                int ttt;
                BLL.BlogsBLL blogbll = new BlogsBLL();
                if (id == 0)//代表 未分类
                {
                    blogs = blogbll.GetList(1, 50, out ttt, t => t.BlogTypes.Count() == 0 && (t.UsersId == userinfo.Id), false, t => t.BlogCreateTime, false)
                      .ToList().Select(t => new BlogsDTO()
                      {
                          Id = t.Id,
                          BlogTitle = t.BlogTitle
                      }).ToList();
                }
                else
                {

                    blogs = blogbll.GetList(1, 50, out ttt, t => t.BlogTypes.Where(v => v.Id == id).Count() > 0 && (t.UsersId == userinfo.Id), false, t => t.BlogCreateTime, false)
                       .ToList().Select(t => new BlogsDTO()
                       {
                           Id = t.Id,
                           BlogTitle = t.BlogTitle
                       }).ToList();
                }
            }
            dic.Add("blogs", blogs);
            return View(dic);
        }
Esempio n. 28
0
 /// <summary>
 /// 删除 文章
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public ActionResult Del(int? id)
 {
     var userinfo = BLLSession.UserInfoSessioin;
     List<BlogsDTO> blogs = new List<BlogsDTO>();
     int isdelok = -1;
     if (null != id)
     {
         BLL.BlogsBLL blogbll = new BlogsBLL();
         blogbll.Del(new ModelDB.Blogs() { Id = (int)id }, true);
         isdelok = blogbll.save(false);
         List<SearchResult> list = new List<SearchResult>();
         list.Add(new SearchResult() { id = (int)id });
         SafetyWriteHelper<SearchResult>.logWrite(list, PanGuLuceneHelper.instance.Delete);
     }
     return Content((isdelok > 0).ToString());
 }
Esempio n. 29
0
 public BlogController(BlogsBLL blogsBLL)
 {
     this.blogsBLL = blogsBLL;
 }
Esempio n. 30
0
        // GET: post
        public async Task <IActionResult> Index(long?id, string title)
        {
            if (id == null)
            {
                return(Redirect(Config.GetUrl("blogs")));
            }

            var model = new PostViewModel();

            model.isExist = true;

            var _lst = await BlogsBLL.LoadItems(_context, new BlogEntity()
            {
                id         = (long)id,
                isapproved = ApprovedTypes.All,
                ispublic   = false,
                isenabled  = EnabledTypes.Enabled
            });

            if (_lst.Count == 0)
            {
                model.isExist = false;
                return(View(model));
            }

            model.Post = _lst[0];
            // fetch associated categories
            model.Post.category_list = await CategoryContentsBLL.FetchContentCategoryList(_context, model.Post.id, (byte)CategoryContentsBLL.Types.Blogs);

            model.PermaUrl = BlogUrlConfig.Generate_Post_Url(new JGN_Blogs()
            {
                id    = (long)id,
                title = model.Post.title
            });

            if (model.Post.isadult == 1)
            {
                // 1:-> adult content, 0:-> non adult content
                var getValue = HttpContext.Session.GetString("adultmember");
                if (getValue == null)
                {
                    return(Redirect(Config.GetUrl("default/validateadult?surl=" + WebUtility.UrlEncode(model.PermaUrl) + "")));;
                }
            }

            // increment views
            model.Post.views++;
            BlogsBLL.Update_Field_V3(_context, (long)id, _lst[0].views, "views");

            string meta_title = _lst[0].title;

            if (meta_title == "")
            {
                meta_title = "Post ID: " + _lst[0].id;
            }

            ViewBag.title = meta_title;

            string _desc = UtilityBLL.StripHTML(_lst[0].description);

            if (_desc == "")
            {
                _desc = _lst[0].title;
            }
            else if (_desc.Length > 160)
            {
                _desc = _desc.Substring(0, 160);
            }

            ViewBag.description = _desc + ", posted date: " + _lst[0].created_at + ", PostID: " + _lst[0].id;

            ViewBag.RSS = Config.GetUrl("agency/rss");

            ViewBag.ATOM = Config.GetUrl("agency/atom");

            return(View(model));
        }
Esempio n. 31
0
        public string Import(string userName, string BlogUserName = "******", string iszf = "false")
        {
            int blosNumber           = 0;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx";

            HtmlAgilityPack.HtmlWeb htmlweb = new HtmlAgilityPack.HtmlWeb();
            var    docment = htmlweb.Load(url);
            string userid  = GetCnblogUserId(userName);
            var    liS     = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li");
            //if (liS != null)
            //    foreach (var item in liS)
            //    {
            //        var tXPath = item.XPath;
            //        var href = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value;
            //        var blogtype = htmlweb.Load(href);
            //        var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']");
            //        if (null == entrylistItem)//做兼容
            //            entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); //
            //        if (null == entrylistItem)
            //        {
            //            continue;
            //        }
            //        foreach (var typeitem in entrylistItem)
            //        {
            //            var typeitemXPath = typeitem.XPath;
            //            var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a");
            //            if (null == typeitemhrefObj) //做兼容
            //                typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a");
            //            ///////////////////////////////////
            //            var typeitemhref = typeitemhrefObj.Attributes["href"].Value;

            //            var bloghtml = htmlweb.Load(typeitemhref);

            //            var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']");
            //            DateTime blogtime;
            //            if (null != blogtimeobj)
            //                blogtime = Convert.ToDateTime(blogtimeobj.InnerText);
            //            else
            //                blogtime = DateTime.Now;
            //            if (bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']") == null) continue;
            //            var blogurl = "/" + BlogUserName + "/" + bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
            //            if (IsAreBlog(blogurl))
            //                continue;
            //            var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml;
            //            if (blogcontextobj == null) continue;//有可能是加密文章
            //            var blogcontext = blogcontextobj.InnerHtml;

            //            var blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='Header1_HeaderTitle']");
            //            if (null == blogNameObj)
            //                blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='lnkBlogTitle']");
            //            string blogName = string.Empty;
            //            try
            //            {
            //                blogName = blogNameObj.InnerText;
            //            }
            //            catch (Exception)
            //            { }

            //            var blogtitle = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText;
            //            var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "&postId=" +
            //                typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
            //            var blogtag = Blog.Helper.MyHtmlHelper.GetRequest(blogtypetagurl);
            //            var jsonobj = jss.Deserialize<Dictionary<string, string>>(blogtag);

            //            List<int> blogtagid = null;
            //            List<int> blogtypeid = null;
            //            if (null == jsonobj)
            //            {//如果没有分类及标签信息 则添加到默认分类中
            //                blogtypeid = new List<int>();
            //                blogtypeid.Add(GetTypeId("未分类", BlogUserName));
            //                goto skip_typeidAndtagid;
            //            }
            //            var tagSplit = jsonobj["Tags"].Split(',');
            //            blogtagid = new List<int>();
            //            for (int i = 0; i < tagSplit.Length; i++)
            //            {
            //                if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1)
            //                {
            //                    var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1);
            //                    blogtagid.Add(this.GetTagId(blogtagname, BlogUserName));
            //                }
            //            }

            //            var categoriesSplit = jsonobj["Categories"].Split(',');
            //            blogtypeid = new List<int>();
            //            for (int i = 0; i < categoriesSplit.Length; i++)
            //            {
            //                if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1)
            //                {
            //                    var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1);
            //                    blogtypeid.Add(this.GetTypeId(blogtypename, BlogUserName));


            //                }
            //            }
            //        skip_typeidAndtagid:



            //            BlogsBLL blog = new BlogsBLL();
            //            List<BlogTags> myBlogTags = null;
            //            if (blogtagid != null)
            //                myBlogTags = new BlogTagsBLL().GetList(t => blogtagid.Contains(t.BlogTagId), isAsNoTracking: false).ToList();//.ToList();
            //            var myBlogTypes = new BLL.BlogTypesBLL().GetList(t => blogtypeid.Contains(t.BlogTypeId)).ToList().FirstOrDefault();//.ToList();
            //            var blogUserId = GetUserId(BlogUserName);
            //            try
            //            {
            //                var modelMyBlogs = new Blogs()
            //                {
            //                    Content = blogcontext,
            //                    CreateTime = blogtime,
            //                    Title = blogtitle,
            //                    IsDel = false,
            //                    BlogTags = myBlogTags,
            //                    BlogTypeId = myBlogTypes.BlogTypeId,
            //                    UserId = blogUserId,
            //                    IsForwarding = iszf == "checked",
            //                    IsShowHome = true
            //                };
            //                blog.Add(modelMyBlogs);
            //                blog.save(false);
            //                blosNumber++;
            //            }
            //            catch (Exception ex)
            //            {
            //                return ex.ToString();
            //            }
            //        }
            //    }
            BlogsBLL blogBLL   = new BlogsBLL();
            var      blogsList = blogBLL.GetList(t => true, isAsNoTracking: false, selectDel: true).ToList();

            blogsList.ForEach(t => { t.BlogUrl = "/" + BlogUserName + "/" + t.BlogId + ".html"; t.BlogRemarks = Blog.Helper.MyHtmlHelper.GetHtmlText(t.Content); });
            blogBLL.save(false);
            if (blosNumber > 0)
            {
                return("成功导入" + blosNumber + "篇Blog");
            }
            return("ok");
        }
Esempio n. 32
0
        // GET: blogs/archive
        public async Task <IActionResult> archive(string month, int?year, string order, int?pagenumber)
        {
            if (pagenumber == null)
            {
                pagenumber = 1;
            }

            if (month == null || year == null)
            {
                return(Redirect(Config.GetUrl("blogs/")));
            }

            /* ***************************************/
            // Process Page Meta & BreaCrumb
            /* ***************************************/
            var _meta = PageMeta.returnPageMeta(new PageQuery()
            {
                controller = ControllerContext.ActionDescriptor.ControllerName,
                index      = ControllerContext.ActionDescriptor.ActionName,
                pagenumber = (int)pagenumber,
                matchterm  = month,
                matchterm2 = year.ToString()
            });

            /* List Initialization */
            var ListEntity = new BlogListViewModel()
            {
                isListStatus = false,
                isListNav    = false,
                QueryOptions = new BlogEntity()
                {
                    pagenumber = (int)pagenumber,
                    term       = "",
                    month      = UtilityBLL.ReturnMonth(month),
                    year       = (int)year,
                    iscache    = false,
                    ispublic   = true,
                    isfeatured = FeaturedTypes.All,
                    pagesize   = 20,
                    order      = "blog.created_at desc",
                },
                ListObject = new ListItems()
                {
                    ListType = ListType.List,
                },
                HeadingTitle      = _meta.title,
                BreadItems        = _meta.BreadItems,
                DefaultUrl        = Config.GetUrl("blogs/archive/" + month + "/" + year + "/"),
                PaginationUrl     = Config.GetUrl("blogs/archive/" + month + "/" + year + "/[p]/"),
                NoRecordFoundText = SiteConfig.generalLocalizer["_no_records"].Value,
            };

            ListEntity.TotalRecords = await BlogsBLL.Count(_context, ListEntity.QueryOptions);

            if (ListEntity.TotalRecords > 0)
            {
                ListEntity.DataList = await BlogsBLL.LoadItems(_context, ListEntity.QueryOptions);
            }


            /**********************************************/
            // Page Meta Setup
            /**********************************************/
            ViewBag.title       = _meta.title;
            ViewBag.description = _meta.description;

            return(View(ListEntity));
        }