FYJ.Blogs开发系列(四)-后台文章Controller
FYJ.Blogs开发系列(五)-前台基页Controller
FYJ.Blogs开发系列(六)-前台主页Controller
FYJ.Blogs开发系列(七)-前台文章Controller
using Blogs.Entity; using Blogs.UI.Main.Models; using FYJ.Common; using FYJ.Web.NetPager; using Microsoft.Practices.Unity; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Web.Mvc; namespace Blogs.UI.Main.Controllers { public class ArticleController : BaseController { [Dependency] public Blogs.IDAL.IComment CommentDal { get; set; } [Dependency] public Blogs.IDAL.IArticleView ArticleViewDal { get; set; } private string articleID { get { return this.RouteData.Values["id"].ToString(); } } public ActionResult Index() { int articleID = Convert.ToInt32(this.articleID); Entity.blog_view_article article = ArticleViewDal.GetEntities().Where(c => c.articleID == articleID).Select(c => new blog_view_article { isDisabled = c.isDisabled, articleIsDelete = c.articleIsDelete, themeName = c.themeName, linkScript = c.linkScript }).FirstOrDefault(); if (article == null) { return Content("文章不存在"); } if (article.isDisabled.Value) { return Content("文章、分类或博客被禁用"); } if (article.articleIsDelete) { return Content("文章被删除到回收站"); } if ((!String.IsNullOrEmpty(article.articlePassword)) && (Session["Autharticle"] == null || !Session["Autharticle"].ToString().Contains(this.articleID))) { return new RedirectResult("/articlePassword?articleID=" + articleID + "&BackUrl=" + Server.UrlEncode(Request.Url.ToString())); } //是否启用静态页 bool isUseStaticHtml = (System.Configuration.ConfigurationManager.AppSettings["isUseStaticHtml"] == "true"); if (isUseStaticHtml) { string absPath = Request.Url.AbsolutePath.TrimStart('/'); //文章最后更新时间 不用上面的article对象 因为EF缓存 long articleUpdateDate = ArticleDal.GetArticleUpdateLong(this.articleID); //如果目录不存在则创建 string foloderPath = Server.MapPath("~/App_Data/html/article/" + this.articleID.Substring(0, 1)); if (!Directory.Exists(foloderPath)) { Directory.CreateDirectory(foloderPath); } string s = Directory.GetFiles(foloderPath, "*-" + absPath).FirstOrDefault(); string filePath = String.Empty; if (s != null) { long updateDate = Convert.ToInt64(Regex.Match(Path.GetFileName(s), "(.*)-" + absPath).Groups[1].Value); filePath = foloderPath + "/" + updateDate + "-" + absPath; //默认刷新时间30 分钟 int refresh = 1800; string staticHtmlRefreshTimeout = System.Configuration.ConfigurationManager.AppSettings["staticHtmlRefreshTimeout"]; if (!String.IsNullOrEmpty(staticHtmlRefreshTimeout)) { refresh = Convert.ToInt32(staticHtmlRefreshTimeout); } //如果没有超过刷新时间 并且当前静态页时间大于等于文章最后更新时间 则从静态页读取 if (Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmss")) - updateDate < refresh && (updateDate >= articleUpdateDate)) { ArticleDal.UpdateExtend(this.articleID, Request.UserHostAddress, this.CurrentUser == null ? null : this.CurrentUser.userID); string content = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8); return Content(content); } } filePath = foloderPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + absPath; //删除以前生成的文件 if (s != null) { System.IO.File.Delete(s); } BlogPageModel model = GetModel(); model.ThemeName = article.themeName; model.linkScript = article.linkScript; string html = Blogs.Common.ControllerHelper.RenderPartialViewToString(this, "~/Views/Blog/Themes/" + article.themeName + "/Show.cshtml", model); TextWriter w = new StreamWriter(filePath, false, System.Text.Encoding.UTF8, 4096); w.Write(html); w.Close(); return Content(html); } else { BlogPageModel model = GetModel(); model.ThemeName = article.themeName; model.linkScript = article.linkScript; return View("~/Views/Blog/Themes/" + article.themeName + "/Show.cshtml", model); } } protected new BlogPageModel GetModel() { BlogUser user = base.CurrentUser; DataSet ds = ArticleDal.GetArticleByID(articleID, Request.UserHostAddress, user == null ? null : user.userID); DataTable articleTable = ds.Tables[0]; ShowPageModel model = articleTable.DataTableToModel<ShowPageModel>()[0]; //更新最后打开时间 ArticleDal.UpdateLastOpenDatetime(articleID); if (!articleTable.Rows[0]["articleHideContent"].IsNullOrEmptyOrDbNullOrWhiteSpace()) { if (this.isReplyed()) { model.articleHideContent = articleTable.Rows[0]["articleHideContent"].ToString(); } else { model.articleHideContent = "本文有隐藏内容,需要登录回复后刷新方能查看"; } } if (Convert.ToBoolean(articleTable.Rows[0]["articleIsOriginal"])) { model.Shenming = "欢迎转载,但请以超链接的形式给出原文链接:<a href=\"" + Request.Url.ToString() + "\">" + Request.Url.ToString() + "</a>"; } model.CommentStateCollection = ds.Tables[2].DataTableToModel<CommentTypeModel>(); model.CommentTagCollection = GetCommentTag(ds.Tables[3]); model.CommentPagerHtml = GetCommentPager(1, Convert.ToInt32(ds.Tables[1].Rows[0][0])); model.BeforeArticle = new ArticleModel(); model.AfterArticle = new ArticleModel(); if (ds.Tables[4].Rows.Count > 0) { model.BeforeArticle = ds.Tables[4].DataTableToModel<ArticleModel>()[0]; } if (ds.Tables[5].Rows.Count > 0) { model.AfterArticle = ds.Tables[5].DataTableToModel<ArticleModel>()[0]; } DataTable dt = ds.Tables[6]; int index = 0; if (dt.Columns.Contains("tagUrls") && dt.Rows[index]["tagUrls"] != null) { string[] tagUrls = dt.Rows[index]["tagUrls"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); string[] tagDisplays = dt.Rows[index]["tagDisplays"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List<TagModel> list = new List<TagModel>(); for (int i = 0; i < tagUrls.Length; i++) { TagModel tag = new TagModel { tagDisplay = tagDisplays[i], Url = tagUrls[i] }; list.Add(tag); } model.TagCollection = list; } BlogPageModel bm = base.GetModel(); model.Title = model.articleTitle + "-" + bm.BlogTitle; #region 获取附件 if (ds.Tables[7].Rows.Count > 0) { Blogs.Entity.AttachmentLimit attachementlimit = (Blogs.Entity.AttachmentLimit)Enum.Parse(typeof(Blogs.Entity.AttachmentLimit), model.articleAttachmentLimit + ""); bool b1 = (attachementlimit & Blogs.Entity.AttachmentLimit.禁止未登录用户下载) == Blogs.Entity.AttachmentLimit.禁止未登录用户下载; bool b2 = (attachementlimit & Blogs.Entity.AttachmentLimit.禁止未回复用户下载) == Blogs.Entity.AttachmentLimit.禁止未回复用户下载; bool b3 = (attachementlimit & Blogs.Entity.AttachmentLimit.禁止下载) == Blogs.Entity.AttachmentLimit.禁止下载; //未设置附件权限 if (model.articleAttachmentLimit == 0) { model.AttachmentCollection = ds.Tables[7].DataTableToModel<AttachmentModel>(); } if (b1) { if (CurrentUser == null) { AttachmentModel at = new AttachmentModel { fileUrl = "", fileName = "请登录后查看附件" }; model.AttachmentCollection = new List<AttachmentModel> { at }; } else { model.AttachmentCollection = ds.Tables[7].DataTableToModel<AttachmentModel>(); } } if (b2) { if (CurrentUser == null) { AttachmentModel at = new AttachmentModel { fileUrl = "", fileName = "请回复后查看附件" }; model.AttachmentCollection = new List<AttachmentModel> { at }; } else { if (CommentDal.GetEntities().Where(c => c.userID == CurrentUser.userID && c.articleID == model.articleID).Count() > 0) { model.AttachmentCollection = ds.Tables[7].DataTableToModel<AttachmentModel>(); } else { AttachmentModel at = new AttachmentModel { fileUrl = "", fileName = "请回复后查看附件" }; model.AttachmentCollection = new List<AttachmentModel> { at }; } } } } else { model.AttachmentCollection = new List<AttachmentModel>(); } #endregion if (model.articleIsOriginal) { model.Shenming = "本文为原创,欢迎转载,请注明出处和原文链接:" + model.articleUrl; } bm.SingleArticle = model; return bm; } private void RenderAttachment() { string str = ""; var model = ArticleDal.GetEntities().Where(c => c.articleID == Convert.ToInt32(this.articleID)).FirstOrDefault(); if (model != null) { if (model.articleAttachmentLimit == 0 || this.isReplyed()) { IDictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("userID", "8dc2885cd7bb44aa9344557dbc0c1630"); dic.Add("ak", "afbf3d192908477d9e24b3e351bc4ebe"); dic.Add("action", "getFileUrl"); dic.Add("objectTag", "attachment"); dic.Add("objectID", this.articleID); string par = ""; string sign = FYJ.Common.HttpHelper.Sign(dic, "493d453149f943e0b515f068e2d029d6", out par, "sign"); string url = "http://my.fyj.me/service/file.action?" + par + "&sign=" + sign; string json = FYJ.Common.HttpHelper.DoGet(url); DataTable dt = FYJ.Common.JsonHelper.JsonToDataTable(json); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { str += "<p><a href='" + dr["fileUrl"] + "' target='_blank'>" + dr["fileName"] + "</a></p>"; } } } else if (model.articleAttachmentLimit == 1) { str = "本文有附件,需要回复后刷新方能查看"; } } Response.Write(str); Response.End(); } //显示评论分页 分页大小10 private string GetCommentPager(int page, int total) { Pager pager = new Pager() { RecordCount = total, PageSize = 10, MaxShowPageSize = 10, PageIndex = page, ShowSpanText = true, EnableUrlRewriting = true, UrlRewritePattern = "javascript:commentPage({0})", FirstPageText = "<<", LastPageText = ">>", PrePageText = "<", NextPageText = ">", ClassName = "pagination", CurrentPageButtonCss = "current" }; string str = pager.ToString(); return str; } //获取回复标签 private IEnumerable<CommentTagModel> GetCommentTag(DataTable dt) { dt.Columns.Add("backgroundColor"); String[] colors = new string[] { "#910048", "#B7005B", "#D20069", "#F7007B", "#FF158A", "#FF3C9D", "#FF5BAD", "#FF80BF", "#FF9DCE", "#FFC1E0" }; DataTable table = dt.Clone(); List<String> tagList = new List<string>(); int index = 0; for (int i = 0; i < dt.Rows.Count && index < 10; i++) { if (!tagList.Contains(dt.Rows[i]["commentText"].ToString())) { DataRow newRow = table.NewRow(); newRow["commentID"] = dt.Rows[i]["commentID"]; newRow["commentText"] = dt.Rows[i]["commentText"]; newRow["supportCount"] = dt.Rows[i]["supportCount"]; newRow["backgroundColor"] = colors[index]; tagList.Add(dt.Rows[i]["commentText"].ToString()); //为了去掉重复 index++; table.Rows.Add(newRow); } } if (table.Rows.Count > 0) { return table.DataTableToModel<CommentTagModel>(); } else { return new List<CommentTagModel>(); } } //是否所有者 private bool isOwner(string articleUserID) { BlogUser user = base.CurrentUser; if (user != null) { String userID = user.userID; if (userID == articleUserID) { return true; } } return false; } /// <summary> /// 是否已经回复 如果是本文章作者 直接视为已回复 /// </summary> /// <param name="articleUserID"></param> /// <returns></returns> private bool isReplyed() { BlogUser user = base.CurrentUser; if (user != null) { string articleUserID = GetarticleUserID(); if (isOwner(articleUserID)) { return true; } String userID = user.userID; int articleID = Convert.ToInt32(this.articleID); if (CommentDal.GetEntities().Where(c => c.userID == userID && c.articleID == articleID).Count() > 0) { return true; } } return false; } /// <summary> /// 获取文章作者用户ID /// </summary> /// <returns></returns> private string GetarticleUserID() { int articleID = Convert.ToInt32(this.articleID); return ArticleDal.GetEntities().Where(c => c.articleID == articleID).Select(c => c.blog_tb_blog.userID).FirstOrDefault(); } } }