From 7fb0e66ddc9b779ec1e23e2ff92c5a5c56ba6238 Mon Sep 17 00:00:00 2001 From: wangbin05 Date: Sat, 3 Apr 2021 17:40:08 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- commands/command.go | 1 + controllers/BookController.go | 2 - controllers/CommentController.go | 67 ++++++++++++++++ controllers/DocumentController.go | 31 ++++++-- controllers/comment.go | 19 ----- models/BookResult.go | 11 +++ models/{comment.go => CommentModel.go} | 10 +++ static/js/kancloud.js | 104 +++++++++++++++++++----- utils/pagination/pagination.go | 25 ++++++ views/book/setting.tpl | 17 ++++ views/document/default_read.tpl | 105 +++++++++++++++---------- 11 files changed, 301 insertions(+), 91 deletions(-) create mode 100644 controllers/CommentController.go delete mode 100644 controllers/comment.go rename models/{comment.go => CommentModel.go} (89%) diff --git a/commands/command.go b/commands/command.go index 34a35ca2..59dbdc6b 100644 --- a/commands/command.go +++ b/commands/command.go @@ -109,6 +109,7 @@ func RegisterModel() { new(models.TeamMember), new(models.TeamRelationship), new(models.Itemsets), + new(models.Comment), ) gob.Register(models.Blog{}) gob.Register(models.Document{}) diff --git a/controllers/BookController.go b/controllers/BookController.go index 30e6a916..2b9b9a00 100644 --- a/controllers/BookController.go +++ b/controllers/BookController.go @@ -516,7 +516,6 @@ func (c *BookController) Create() { book.Identify = identify book.DocCount = 0 book.MemberId = c.Member.MemberId - book.CommentCount = 0 book.Version = time.Now().Unix() book.IsEnableShare = 0 book.IsUseFirstDocument = 1 @@ -634,7 +633,6 @@ func (c *BookController) Import() { book.Identify = identify book.DocCount = 0 book.MemberId = c.Member.MemberId - book.CommentCount = 0 book.Version = time.Now().Unix() book.ItemId = itemId diff --git a/controllers/CommentController.go b/controllers/CommentController.go new file mode 100644 index 00000000..9cb4a3ca --- /dev/null +++ b/controllers/CommentController.go @@ -0,0 +1,67 @@ +package controllers + +import ( + "strings" + "time" + + "github.com/astaxie/beego" + + "github.com/mindoc-org/mindoc/conf" + "github.com/mindoc-org/mindoc/models" + "github.com/mindoc-org/mindoc/utils/pagination" +) + +type CommentController struct { + BaseController +} + +func (c *CommentController) Lists() { + + docid, _ := c.GetInt("docid", 0) + pageIndex, _ := c.GetInt("page", 1) + + beego.Info("CommentController.Lists", docid, pageIndex) + + // 获取评论、分页 + comments, count := models.NewComment().QueryCommentByDocumentId(docid, pageIndex, conf.PageSize) + page := pagination.PageUtil(int(count), pageIndex, conf.PageSize, comments) + beego.Info("docid=", docid, "Page", page) + + var data struct { + DocId int `json:"doc_id"` + Page pagination.Page `json:"page"` + } + data.DocId = docid + data.Page = page + + c.JsonResult(0, "ok", data) + return +} + +func (c *CommentController) Create() { + content := c.GetString("content") + id, _ := c.GetInt("doc_id") + + m := models.NewComment() + m.DocumentId = id + if len(c.Member.RealName) != 0 { + m.Author = c.Member.RealName + } else { + m.Author = c.Member.Account + } + m.MemberId = c.Member.MemberId + m.IPAddress = c.Ctx.Request.RemoteAddr + m.IPAddress = strings.Split(m.IPAddress, ":")[0] + m.CommentDate = time.Now() + m.Content = content + beego.Info(m) + m.Insert() + + c.JsonResult(0, "ok") +} + +func (c *CommentController) Index() { + + c.Prepare() + c.TplName = "comment/index.tpl" +} diff --git a/controllers/DocumentController.go b/controllers/DocumentController.go index 6ba30842..46448494 100644 --- a/controllers/DocumentController.go +++ b/controllers/DocumentController.go @@ -65,6 +65,15 @@ func (c *DocumentController) Index() { c.Data["Content"] = template.HTML(doc.Release) c.Data["Description"] = utils.AutoSummary(doc.Release, 120) + doc.IncrViewCount(doc.DocumentId) + c.Data["ViewCount"] = doc.ViewCount + 1 + c.Data["DocumentId"] = doc.DocumentId + + // 获取评论、分页 + comments, count := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize) + page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) + c.Data["Page"] = page + beego.Info("docid=", doc.DocumentId, "Page", page) } } else { c.Data["Title"] = "概要" @@ -83,7 +92,6 @@ func (c *DocumentController) Index() { } c.Data["Model"] = bookResult c.Data["Result"] = template.HTML(tree) - } // 阅读文档 @@ -138,6 +146,7 @@ func (c *DocumentController) Read() { doc.Processor() + c.Data["DocumentId"] = doc.DocumentId attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId) if err == nil { doc.AttachList = attach @@ -146,19 +155,29 @@ func (c *DocumentController) Read() { doc.IncrViewCount(doc.DocumentId) c.Data["ViewCount"] = doc.ViewCount + 1 + // 获取评论、分页 + comments, count := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize) + page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) + c.Data["Page"] = page + beego.Info("docid=", doc.DocumentId, "Page", page) + if c.IsAjax() { var data struct { - DocTitle string `json:"doc_title"` - Body string `json:"body"` - Title string `json:"title"` - Version int64 `json:"version"` - ViewCount int `json:"view_count"` + DocTitle string `json:"doc_title"` + Body string `json:"body"` + Title string `json:"title"` + Version int64 `json:"version"` + ViewCount int `json:"view_count"` + DocId int `json:"doc_id"` + Page pagination.Page `json:"page"` } data.DocTitle = doc.DocumentName data.Body = doc.Release data.Title = doc.DocumentName + " - Powered by MinDoc" data.Version = doc.Version data.ViewCount = doc.ViewCount + 1 + data.DocId = doc.DocumentId + data.Page = page c.JsonResult(0, "ok", data) } diff --git a/controllers/comment.go b/controllers/comment.go deleted file mode 100644 index ff70e555..00000000 --- a/controllers/comment.go +++ /dev/null @@ -1,19 +0,0 @@ -package controllers - -type CommentController struct { - BaseController -} - -func (c *CommentController) Lists() { - -} - -func (c *CommentController) Create() { - - c.JsonResult(0, "ok") -} - -func (c *CommentController) Index() { - c.Prepare() - c.TplName = "comment/index.tpl" -} diff --git a/models/BookResult.go b/models/BookResult.go index 352a6b52..9fa31601 100644 --- a/models/BookResult.go +++ b/models/BookResult.go @@ -233,6 +233,17 @@ func (m *BookResult) ToBookResult(book Book) *BookResult { m.ItemName = item.ItemName } } + if m.CommentStatus == "closed" { + m.IsDisplayComment = false + } else if m.CommentStatus == "open" { + m.IsDisplayComment = true + } else if m.CommentStatus == "registered_only" { + // todo + } else if m.CommentStatus == "group_only" { + // todo + } else { + m.IsDisplayComment = false; + } return m } diff --git a/models/comment.go b/models/CommentModel.go similarity index 89% rename from models/comment.go rename to models/CommentModel.go index e99f8379..84a68100 100644 --- a/models/comment.go +++ b/models/CommentModel.go @@ -52,6 +52,7 @@ func (m *Comment) TableNameWithPrefix() string { func NewComment() *Comment { return &Comment{} } + func (m *Comment) Find(id int) (*Comment, error) { if id <= 0 { return m, ErrInvalidParameter @@ -62,6 +63,15 @@ func (m *Comment) Find(id int) (*Comment, error) { return m, err } +// 根据文档id查询文档评论 +func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize int) (comments []Comment, count int64) { + o := orm.NewOrm() + offset := (page - 1) * pagesize + o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).OrderBy("comment_date").Offset(offset).Limit(pagesize).All(&comments) + count, _ = o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).Count() + return +} + func (m *Comment) Update(cols ...string) error { o := orm.NewOrm() diff --git a/static/js/kancloud.js b/static/js/kancloud.js index 3363b395..7d80b40a 100644 --- a/static/js/kancloud.js +++ b/static/js/kancloud.js @@ -4,7 +4,6 @@ var events = function () { window.sessionStorage && window.sessionStorage.setItem("MinDoc::LastLoadDocument:" + window.book.identify, $param.$id); var prevState = window.history.state || {}; if ('pushState' in history) { - if ($param.$id) { prevState.$id === $param.$id || window.history.pushState($param, $param.$id, $param.$url); } else { @@ -43,6 +42,86 @@ var events = function () { }(); +function format(d) { + return d < 10 ? "0" + d : "" + d; +} + +function timeFormat(time) { + var span = Date.parse(time) + var date = new Date(span) + var year = date.getFullYear(); + var month = format(date.getMonth() + 1); + var day = format(date.getDate()); + var hour = format(date.getHours()); + var min = format(date.getMinutes()); + var sec = format(date.getSeconds()); + return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec; +} + +function onPageClicked(page, docid) { + $.ajax({ + url : "/comment/lists?page=" + page + "&docid=" + docid, + type : "GET", + beforeSend : function (xhr) { + NProgress.start(); + }, + success : function (res) { + console.log(res.data); + loadComment(res.data.page, res.data.doc_id); + }, + complete : function () { + NProgress.done(); + }, + error : function () { + layer.msg("加载失败"); + } + }); +} + +// 加载评论 +function loadComment(page, docid) { + $("#commentList").empty(); + var html = "" + var c = page.List; + for (var i = 0; c && i < c.length; i++) { + html += "
"; + html += "

" + c[i].author + "" + timeFormat(c[i].comment_date) + "

"; + html += "
" + c[i].content + "
"; + html += "

"; + html += ""; + html += "" + i + "#"; + html += ""; + html += "

"; + html += "
"; + } + $("#commentList").append(html); + + if (page.TotalPage > 1) { + $("#page").bootstrapPaginator({ + currentPage: page.PageNo, + totalPages: page.TotalPage, + bootstrapMajorVersion: 3, + size: "middle", + onPageClicked: function(e,originalEvent,type,page){ + onPageClicked(page, docid); + } + }); + } else { + $("#page").find("li").remove(); + } +} + +// 重新渲染页面 +function renderPage(data) { + $("#page-content").html(data.body); + $("title").text(data.title); + $("#article-title").text(data.doc_title); + $("#article-info").text(data.doc_info); + $("#view_count").text("阅读次数:" + data.view_count); + $("#doc_id").val(data.doc_id); + loadComment(data.page, data.doc_id); +} + /*** * 加载文档到阅读区 * @param $url @@ -61,11 +140,7 @@ function loadDocument($url, $id, $callback) { }else if(data.version && data.version != $callback){ return true; } - $("#page-content").html(data.body); - $("title").text(data.title); - $("#article-title").text(data.doc_title); - $("#article-info").text(data.doc_info); - $("#view_count").text("阅读次数:" + data.view_count); + renderPage(data); events.trigger('article.open', {$url: $url, $id: $id}); @@ -77,23 +152,13 @@ function loadDocument($url, $id, $callback) { }, success : function (res) { if (res.errcode === 0) { - var body = res.data.body; - var doc_title = res.data.doc_title; - var title = res.data.title; - var doc_info = res.data.doc_info; - var view_count = res.data.view_count; + renderPage(res.data); - $body = body; + $body = res.data.body; if (typeof $callback === "function" ) { $body = $callback(body); } - $("#page-content").html($body); - $("title").text(title); - $("#article-title").text(doc_title); - $("#article-info").text(doc_info); - $("#view_count").text("阅读次数:" + view_count); - events.data($id, res.data); events.trigger('article.open', { $url : $url, $id : $id }); @@ -129,9 +194,6 @@ function initHighlighting() { } } - - - $(function () { $(".view-backtop").on("click", function () { $('.manual-right').animate({ scrollTop: '0px' }, 200); diff --git a/utils/pagination/pagination.go b/utils/pagination/pagination.go index f6dcec43..e5fc93d9 100644 --- a/utils/pagination/pagination.go +++ b/utils/pagination/pagination.go @@ -112,3 +112,28 @@ func (p *Pagination) pageURL(page string) string { return u.String() } +type Page struct { + PageNo int `json:"PageNo"` + PageSize int `json:"PageSize"` + TotalPage int `json:"TotalPage"` + TotalCount int `json:"TotalCount"` + FirstPage bool `json:"FirstPage"` + LastPage bool `json:"LastPage"` + List interface{} `json:"List"` +} + +func PageUtil(count int, pageNo int, pageSize int, list interface{}) Page { + tp := count / pageSize + if count%pageSize > 0 { + tp = count/pageSize + 1 + } + return Page { + PageNo: pageNo, + PageSize: pageSize, + TotalPage: tp, + TotalCount: count, + FirstPage: pageNo == 1, + LastPage: pageNo == tp, + List: list, + } +} diff --git a/views/book/setting.tpl b/views/book/setting.tpl index 154c819c..70a665ef 100644 --- a/views/book/setting.tpl +++ b/views/book/setting.tpl @@ -93,6 +93,23 @@ +
+ +
+ + + + +
+
{{if eq .Model.PrivatelyOwned 1}}
diff --git a/views/document/default_read.tpl b/views/document/default_read.tpl index 27a47d42..58637df2 100644 --- a/views/document/default_read.tpl +++ b/views/document/default_read.tpl @@ -168,61 +168,51 @@
+
{{.Content}}
- +
+ {{range $i, $c := .Page.List}} +
+

{{$c.Author}}{{date $c.CommentDate "Y-m-d H:i:s"}}

+
{{$c.Content}}
+

+ + {{$i}}# + +

-
-
-
暂无相关评论
-
-

静夜思9月1日评论

-
一直不明白,控制器分层和模型分层调用起来到底有什么区别
-

- - - 4 - - - 回复 - - - 23# - -

+ {{end}} +
+ + +
    + + +
    +
    + +
    +
    -
    +
    {{end}} -*/}}--> + +
    -
    @@ -247,7 +237,7 @@
    - +
    @@ -276,7 +266,7 @@
    - +
    @@ -290,6 +280,7 @@ + @@ -299,6 +290,18 @@ {{.Scripts}} From 3d12583eba748de8084c1a88e62522489a1e5e0b Mon Sep 17 00:00:00 2001 From: wangbin05 Date: Sat, 3 Apr 2021 22:44:43 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E8=AF=84=E8=AE=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/CommentController.go | 27 +++++- controllers/DocumentController.go | 6 +- models/CommentModel.go | 30 +++++- routers/router.go | 1 + static/js/bootstrap-paginator.min.js | 1 + static/js/kancloud.js | 133 +++++++++++++++++++-------- views/document/default_read.tpl | 31 ++----- 7 files changed, 157 insertions(+), 72 deletions(-) create mode 100644 static/js/bootstrap-paginator.min.js diff --git a/controllers/CommentController.go b/controllers/CommentController.go index 9cb4a3ca..d8706a18 100644 --- a/controllers/CommentController.go +++ b/controllers/CommentController.go @@ -16,16 +16,14 @@ type CommentController struct { } func (c *CommentController) Lists() { - docid, _ := c.GetInt("docid", 0) pageIndex, _ := c.GetInt("page", 1) beego.Info("CommentController.Lists", docid, pageIndex) // 获取评论、分页 - comments, count := models.NewComment().QueryCommentByDocumentId(docid, pageIndex, conf.PageSize) + comments, count, pageIndex := models.NewComment().QueryCommentByDocumentId(docid, pageIndex, conf.PageSize, c.Member.MemberId) page := pagination.PageUtil(int(count), pageIndex, conf.PageSize, comments) - beego.Info("docid=", docid, "Page", page) var data struct { DocId int `json:"doc_id"` @@ -57,11 +55,30 @@ func (c *CommentController) Create() { beego.Info(m) m.Insert() - c.JsonResult(0, "ok") + var data struct { + DocId int `json:"doc_id"` + } + data.DocId = id + + c.JsonResult(0, "ok", data) } func (c *CommentController) Index() { - c.Prepare() c.TplName = "comment/index.tpl" } + +func (c *CommentController) Delete() { + if c.Ctx.Input.IsPost() { + id, _ := c.GetInt("id", 0) + beego.Info("delete id=", id) + m := models.NewComment() + m.CommentId = id + err := m.Delete() + if err != nil { + c.JsonResult(1, "删除错误") + } else { + c.JsonResult(0, "ok") + } + } +} diff --git a/controllers/DocumentController.go b/controllers/DocumentController.go index 46448494..2a7b06f8 100644 --- a/controllers/DocumentController.go +++ b/controllers/DocumentController.go @@ -70,10 +70,9 @@ func (c *DocumentController) Index() { c.Data["DocumentId"] = doc.DocumentId // 获取评论、分页 - comments, count := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize) + comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member.MemberId) page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) c.Data["Page"] = page - beego.Info("docid=", doc.DocumentId, "Page", page) } } else { c.Data["Title"] = "概要" @@ -156,10 +155,9 @@ func (c *DocumentController) Read() { c.Data["ViewCount"] = doc.ViewCount + 1 // 获取评论、分页 - comments, count := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize) + comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member.MemberId) page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) c.Data["Page"] = page - beego.Info("docid=", doc.DocumentId, "Page", page) if c.IsAjax() { var data struct { diff --git a/models/CommentModel.go b/models/CommentModel.go index 84a68100..7876da05 100644 --- a/models/CommentModel.go +++ b/models/CommentModel.go @@ -33,6 +33,8 @@ type Comment struct { ParentId int `orm:"column(parent_id);type(int);default(0)" json:"parent_id"` AgreeCount int `orm:"column(agree_count);type(int);default(0)" json:"agree_count"` AgainstCount int `orm:"column(against_count);type(int);default(0)" json:"against_count"` + Index int `orm:"-" json:"index"` + ShowDel int `orm:"-" json:"show_del"` } // TableName 获取对应数据库表名. @@ -64,11 +66,26 @@ func (m *Comment) Find(id int) (*Comment, error) { } // 根据文档id查询文档评论 -func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize int) (comments []Comment, count int64) { +func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize, userid int) (comments []Comment, count int64, ret_page int) { o := orm.NewOrm() - offset := (page - 1) * pagesize - o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).OrderBy("comment_date").Offset(offset).Limit(pagesize).All(&comments) count, _ = o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).Count() + if -1 == page { // 请求最后一页 + var total int = int(count) + if total % pagesize == 0 { + page = total / pagesize + } else { + page = total / pagesize + 1 + } + } + offset := (page - 1) * pagesize + ret_page = page + o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).OrderBy("comment_date").Offset(offset).Limit(pagesize).All(&comments) + for i := 0; i < len(comments); i++ { + comments[i].Index = (i + 1) + (page - 1) * pagesize + if userid == comments[i].MemberId { + comments[i].ShowDel = 1 + } + } return } @@ -145,3 +162,10 @@ func (m *Comment) Insert() error { return err } + +// 删除一条评论 +func (m *Comment) Delete() error { + o := orm.NewOrm() + _, err := o.Delete(m) + return err +} \ No newline at end of file diff --git a/routers/router.go b/routers/router.go index d6f4cf36..7cde2673 100644 --- a/routers/router.go +++ b/routers/router.go @@ -134,6 +134,7 @@ func init() { beego.Router("/attach_files/:key/:attach_id", &controllers.DocumentController{}, "get:DownloadAttachment") beego.Router("/comment/create", &controllers.CommentController{}, "post:Create") + beego.Router("/comment/delete", &controllers.CommentController{}, "post:Delete") beego.Router("/comment/lists", &controllers.CommentController{}, "get:Lists") beego.Router("/comment/index", &controllers.CommentController{}, "*:Index") diff --git a/static/js/bootstrap-paginator.min.js b/static/js/bootstrap-paginator.min.js new file mode 100644 index 00000000..d482d962 --- /dev/null +++ b/static/js/bootstrap-paginator.min.js @@ -0,0 +1 @@ +!function($){"use strict";var BootstrapPaginator=function(element,options){this.init(element,options)},old=null;BootstrapPaginator.prototype={init:function(element,options){this.$element=$(element);var version=options&&options.bootstrapMajorVersion?options.bootstrapMajorVersion:$.fn.bootstrapPaginator.defaults.bootstrapMajorVersion,id=this.$element.attr("id");if(2===version&&!this.$element.is("div"))throw"in Bootstrap version 2 the pagination must be a div element. Or if you are using Bootstrap pagination 3. Please specify it in bootstrapMajorVersion in the option";if(version>2&&!this.$element.is("ul"))throw"in Bootstrap version 3 the pagination root item must be an ul element.";this.currentPage=1,this.lastPage=1,this.setOptions(options),this.initialized=!0},setOptions:function(options){this.options=$.extend({},this.options||$.fn.bootstrapPaginator.defaults,options),this.totalPages=parseInt(this.options.totalPages,10),this.numberOfPages=parseInt(this.options.numberOfPages,10),options&&"undefined"!=typeof options.currentPage&&this.setCurrentPage(options.currentPage),this.listen(),this.render(),this.initialized||this.lastPage===this.currentPage||this.$element.trigger("page-changed",[this.lastPage,this.currentPage])},listen:function(){this.$element.off("page-clicked"),this.$element.off("page-changed"),"function"==typeof this.options.onPageClicked&&this.$element.bind("page-clicked",this.options.onPageClicked),"function"==typeof this.options.onPageChanged&&this.$element.on("page-changed",this.options.onPageChanged),this.$element.bind("page-clicked",this.onPageClicked)},destroy:function(){this.$element.off("page-clicked"),this.$element.off("page-changed"),this.$element.removeData("bootstrapPaginator"),this.$element.empty()},show:function(page){this.setCurrentPage(page),this.render(),this.lastPage!==this.currentPage&&this.$element.trigger("page-changed",[this.lastPage,this.currentPage])},showNext:function(){var pages=this.getPages();pages.next&&this.show(pages.next)},showPrevious:function(){var pages=this.getPages();pages.prev&&this.show(pages.prev)},showFirst:function(){var pages=this.getPages();pages.first&&this.show(pages.first)},showLast:function(){var pages=this.getPages();pages.last&&this.show(pages.last)},onPageItemClicked:function(event){var type=event.data.type,page=event.data.page;this.$element.trigger("page-clicked",[event,type,page])},onPageClicked:function(event,originalEvent,type,page){var currentTarget=$(event.currentTarget);switch(type){case"first":currentTarget.bootstrapPaginator("showFirst");break;case"prev":currentTarget.bootstrapPaginator("showPrevious");break;case"next":currentTarget.bootstrapPaginator("showNext");break;case"last":currentTarget.bootstrapPaginator("showLast");break;case"page":currentTarget.bootstrapPaginator("show",page)}},render:function(){var containerClass=this.getValueFromOption(this.options.containerClass,this.$element),size=this.options.size||"normal",alignment=this.options.alignment||"left",pages=this.getPages(),listContainer=2===this.options.bootstrapMajorVersion?$(""):this.$element,listContainerClass=2===this.options.bootstrapMajorVersion?this.getValueFromOption(this.options.listContainerClass,listContainer):null,first=null,prev=null,next=null,last=null,p=null,i=0;switch(this.$element.prop("class",""),this.$element.addClass("pagination"),size.toLowerCase()){case"large":case"small":case"mini":this.$element.addClass($.fn.bootstrapPaginator.sizeArray[this.options.bootstrapMajorVersion][size.toLowerCase()])}if(2===this.options.bootstrapMajorVersion)switch(alignment.toLowerCase()){case"center":this.$element.addClass("pagination-centered");break;case"right":this.$element.addClass("pagination-right")}for(this.$element.addClass(containerClass),this.$element.empty(),2===this.options.bootstrapMajorVersion&&(this.$element.append(listContainer),listContainer.addClass(listContainerClass)),this.pageRef=[],pages.first&&(first=this.buildPageItem("first",pages.first),first&&listContainer.append(first)),pages.prev&&(prev=this.buildPageItem("prev",pages.prev),prev&&listContainer.append(prev)),i=0;i"),itemContent=$(""),text="",title="",itemContainerClass=this.options.itemContainerClass(type,page,this.currentPage),itemContentClass=this.getValueFromOption(this.options.itemContentClass,type,page,this.currentPage),tooltipOpts=null;switch(type){case"first":if(!this.getValueFromOption(this.options.shouldShowPage,type,page,this.currentPage))return;text=this.options.itemTexts(type,page,this.currentPage),title=this.options.tooltipTitles(type,page,this.currentPage);break;case"last":if(!this.getValueFromOption(this.options.shouldShowPage,type,page,this.currentPage))return;text=this.options.itemTexts(type,page,this.currentPage),title=this.options.tooltipTitles(type,page,this.currentPage);break;case"prev":if(!this.getValueFromOption(this.options.shouldShowPage,type,page,this.currentPage))return;text=this.options.itemTexts(type,page,this.currentPage),title=this.options.tooltipTitles(type,page,this.currentPage);break;case"next":if(!this.getValueFromOption(this.options.shouldShowPage,type,page,this.currentPage))return;text=this.options.itemTexts(type,page,this.currentPage),title=this.options.tooltipTitles(type,page,this.currentPage);break;case"page":if(!this.getValueFromOption(this.options.shouldShowPage,type,page,this.currentPage))return;text=this.options.itemTexts(type,page,this.currentPage),title=this.options.tooltipTitles(type,page,this.currentPage)}return itemContainer.addClass(itemContainerClass).append(itemContent),itemContent.addClass(itemContentClass).html(text).on("click",null,{type:type,page:page},$.proxy(this.onPageItemClicked,this)),this.options.pageUrl&&itemContent.attr("href",this.getValueFromOption(this.options.pageUrl,type,page,this.currentPage)),this.options.useBootstrapTooltip?(tooltipOpts=$.extend({},this.options.bootstrapTooltipOptions,{title:title}),itemContent.tooltip(tooltipOpts)):itemContent.attr("title",title),itemContainer},setCurrentPage:function(page){if(page>this.totalPages||1>page)throw"Page out of range";this.lastPage=this.currentPage,this.currentPage=parseInt(page,10)},getPages:function(){var totalPages=this.totalPages,pageStart=0===this.currentPage%this.numberOfPages?(parseInt(this.currentPage/this.numberOfPages,10)-1)*this.numberOfPages+1:parseInt(this.currentPage/this.numberOfPages,10)*this.numberOfPages+1,output=[],i=0,counter=0;for(pageStart=1>pageStart?1:pageStart,i=pageStart,counter=0;counter=i;i+=1,counter+=1)output.push(i);return output.first=1,output.prev=this.currentPage>1?this.currentPage-1:1,output.next=this.currentPage"; html += "

    " + c[i].author + "" + timeFormat(c[i].comment_date) + "

    "; html += "
    " + c[i].content + "
    "; html += "

    "; - html += ""; - html += "" + i + "#"; + if (c[i].show_del == 1) html += ""; + else html += ""; + html += "" + c[i].index + "#"; + if (c[i].show_del == 1) html += ""; html += ""; html += "

    "; html += ""; } $("#commentList").append(html); - if (page.TotalPage > 1) { + if ($page.TotalPage > 1) { $("#page").bootstrapPaginator({ - currentPage: page.PageNo, - totalPages: page.TotalPage, + currentPage: $page.PageNo, + totalPages: $page.TotalPage, bootstrapMajorVersion: 3, size: "middle", - onPageClicked: function(e,originalEvent,type,page){ - onPageClicked(page, docid); + onPageClicked: function(e, originalEvent, type, page){ + pageClicked(page, $docid); } }); } else { @@ -111,15 +124,36 @@ function loadComment(page, docid) { } } +// 删除评论 +function onDelComment($id) { + console.log($id); + $.ajax({ + url : "/comment/delete", + data : {"id": $id}, + type : "POST", + success : function ($res) { + if ($res.errcode == 0) { + layer.msg("删除成功"); + $("div[data-id=" + $id + "]").remove(); + } else { + layer.msg($res.message); + } + }, + error : function () { + layer.msg("删除失败"); + } + }); +} + // 重新渲染页面 -function renderPage(data) { - $("#page-content").html(data.body); - $("title").text(data.title); - $("#article-title").text(data.doc_title); - $("#article-info").text(data.doc_info); - $("#view_count").text("阅读次数:" + data.view_count); - $("#doc_id").val(data.doc_id); - loadComment(data.page, data.doc_id); +function renderPage($data) { + $("#page-content").html($data.body); + $("title").text($data.title); + $("#article-title").text($data.doc_title); + $("#article-info").text($data.doc_info); + $("#view_count").text("阅读次数:" + $data.view_count); + $("#doc_id").val($data.doc_id); + loadComment($data.page, $data.doc_id); } /*** @@ -132,7 +166,7 @@ function loadDocument($url, $id, $callback) { $.ajax({ url : $url, type : "GET", - beforeSend : function (xhr) { + beforeSend : function () { var data = events.data($id); if(data) { if (typeof $callback === "function") { @@ -150,19 +184,19 @@ function loadDocument($url, $id, $callback) { NProgress.start(); }, - success : function (res) { - if (res.errcode === 0) { - renderPage(res.data); + success : function ($res) { + if ($res.errcode === 0) { + renderPage($res.data); - $body = res.data.body; + $body = $res.data.body; if (typeof $callback === "function" ) { $body = $callback(body); } - events.data($id, res.data); + events.data($id, $res.data); events.trigger('article.open', { $url : $url, $id : $id }); - } else if (res.errcode === 6000) { + } else if ($res.errcode === 6000) { window.location.href = "/"; } else { layer.msg("加载失败"); @@ -349,4 +383,25 @@ $(function () { console.log($param); } }; + + // 提交评论 + $("#commentForm").ajaxForm({ + beforeSubmit : function () { + $("#btnSubmitComment").button("loading"); + }, + success : function (res) { + if(res.errcode === 0){ + showSuccess("保存成功") + }else{ + showError("保存失败") + } + $("#btnSubmitComment").button("reset"); + $("#commentContent").val(""); + pageClicked(-1, res.data.doc_id); // -1 表示请求最后一页 + }, + error : function () { + showError("服务错误"); + $("#btnSaveBookInfo").button("reset"); + } + }); }); \ No newline at end of file diff --git a/views/document/default_read.tpl b/views/document/default_read.tpl index 58637df2..369eea76 100644 --- a/views/document/default_read.tpl +++ b/views/document/default_read.tpl @@ -167,6 +167,7 @@ +
    @@ -182,8 +183,11 @@

    {{$c.Author}}{{date $c.CommentDate "Y-m-d H:i:s"}}

    {{$c.Content}}

    - - {{$i}}# + + {{$c.Index}}# + {{if eq $c.ShowDel 1}} + + {{end}}

    @@ -197,11 +201,12 @@
    - + +
    @@ -297,7 +302,7 @@ if ({{.Page.TotalPage}} > 1) { bootstrapMajorVersion: 3, size: "middle", onPageClicked: function(e, originalEvent, type, page){ - onPageClicked(page, {{.DocumentId}}); + pageClicked(page, {{.DocumentId}}); } }); } @@ -349,22 +354,6 @@ $(function () { window.jsTree.jstree().open_all() } }) - - // 提交评论 - $("#commentForm").ajaxForm({ - beforeSubmit : function () { - }, - success : function (res) { - if(res.errcode === 0){ - console.log("success") - }else{ - console.log("error") - } - }, - error : function () { - console.log("server error") - } - }); }); {{.Scripts}} From 27dea7b8bd0d15393bbb2706ebc33a4aba51f68b Mon Sep 17 00:00:00 2001 From: wangbin05 Date: Sun, 4 Apr 2021 16:44:14 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E6=97=B6=EF=BC=8C=E5=88=A4=E6=96=AD=E6=96=87=E7=AB=A0=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E5=AD=98=E5=9C=A8=E3=80=82=E5=88=A0=E9=99=A4=E6=97=B6?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=98=AF=E5=90=A6=E6=9C=89=E6=9D=83=E9=99=90?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/CommentController.go | 37 +++++++++++++++++++++---------- controllers/DocumentController.go | 4 ++-- models/CommentModel.go | 30 ++++++++++++++++--------- static/js/kancloud.js | 24 ++++---------------- views/document/default_read.tpl | 1 - 5 files changed, 51 insertions(+), 45 deletions(-) diff --git a/controllers/CommentController.go b/controllers/CommentController.go index d8706a18..487c855b 100644 --- a/controllers/CommentController.go +++ b/controllers/CommentController.go @@ -4,8 +4,6 @@ import ( "strings" "time" - "github.com/astaxie/beego" - "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/utils/pagination" @@ -19,10 +17,8 @@ func (c *CommentController) Lists() { docid, _ := c.GetInt("docid", 0) pageIndex, _ := c.GetInt("page", 1) - beego.Info("CommentController.Lists", docid, pageIndex) - // 获取评论、分页 - comments, count, pageIndex := models.NewComment().QueryCommentByDocumentId(docid, pageIndex, conf.PageSize, c.Member.MemberId) + comments, count, pageIndex := models.NewComment().QueryCommentByDocumentId(docid, pageIndex, conf.PageSize, c.Member) page := pagination.PageUtil(int(count), pageIndex, conf.PageSize, comments) var data struct { @@ -40,6 +36,11 @@ func (c *CommentController) Create() { content := c.GetString("content") id, _ := c.GetInt("doc_id") + _, err := models.NewDocument().Find(id) + if err != nil { + c.JsonResult(1, "文章不存在") + } + m := models.NewComment() m.DocumentId = id if len(c.Member.RealName) != 0 { @@ -52,7 +53,6 @@ func (c *CommentController) Create() { m.IPAddress = strings.Split(m.IPAddress, ":")[0] m.CommentDate = time.Now() m.Content = content - beego.Info(m) m.Insert() var data struct { @@ -71,14 +71,27 @@ func (c *CommentController) Index() { func (c *CommentController) Delete() { if c.Ctx.Input.IsPost() { id, _ := c.GetInt("id", 0) - beego.Info("delete id=", id) - m := models.NewComment() - m.CommentId = id - err := m.Delete() + m, err := models.NewComment().Find(id) if err != nil { - c.JsonResult(1, "删除错误") + c.JsonResult(1, "评论不存在") + } + + doc, err := models.NewDocument().Find(m.DocumentId) + if err != nil { + c.JsonResult(1, "文章不存在") + } + + // 判断是否有权限删除 + bookRole, _ := models.NewRelationship().FindForRoleId(doc.BookId, c.Member.MemberId) + if m.CanDelete(c.Member.MemberId, bookRole) { + err := m.Delete() + if err != nil { + c.JsonResult(1, "删除错误") + } else { + c.JsonResult(0, "ok") + } } else { - c.JsonResult(0, "ok") + c.JsonResult(1, "没有权限删除") } } } diff --git a/controllers/DocumentController.go b/controllers/DocumentController.go index 2a7b06f8..8164a6f9 100644 --- a/controllers/DocumentController.go +++ b/controllers/DocumentController.go @@ -70,7 +70,7 @@ func (c *DocumentController) Index() { c.Data["DocumentId"] = doc.DocumentId // 获取评论、分页 - comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member.MemberId) + comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member) page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) c.Data["Page"] = page } @@ -155,7 +155,7 @@ func (c *DocumentController) Read() { c.Data["ViewCount"] = doc.ViewCount + 1 // 获取评论、分页 - comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member.MemberId) + comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member) page := pagination.PageUtil(int(count), 1, conf.PageSize, comments) c.Data["Page"] = page diff --git a/models/CommentModel.go b/models/CommentModel.go index 7876da05..fa0da10a 100644 --- a/models/CommentModel.go +++ b/models/CommentModel.go @@ -55,18 +55,18 @@ func NewComment() *Comment { return &Comment{} } -func (m *Comment) Find(id int) (*Comment, error) { - if id <= 0 { - return m, ErrInvalidParameter - } - o := orm.NewOrm() - err := o.Read(m) - - return m, err +// 是否有权限删除 +func (m *Comment) CanDelete(user_memberid int, user_bookrole conf.BookRole) bool { + return user_memberid == m.MemberId || user_bookrole == conf.BookFounder || user_bookrole == conf.BookAdmin } // 根据文档id查询文档评论 -func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize, userid int) (comments []Comment, count int64, ret_page int) { +func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize int, member *Member) (comments []Comment, count int64, ret_page int) { + doc, err := NewDocument().Find(doc_id) + if err != nil { + return + } + o := orm.NewOrm() count, _ = o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).Count() if -1 == page { // 请求最后一页 @@ -80,9 +80,11 @@ func (m *Comment) QueryCommentByDocumentId(doc_id, page, pagesize, userid int) ( offset := (page - 1) * pagesize ret_page = page o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc_id).OrderBy("comment_date").Offset(offset).Limit(pagesize).All(&comments) + + bookRole, _ := NewRelationship().FindForRoleId(doc.BookId, member.MemberId) for i := 0; i < len(comments); i++ { comments[i].Index = (i + 1) + (page - 1) * pagesize - if userid == comments[i].MemberId { + if comments[i].CanDelete(member.MemberId, bookRole) { comments[i].ShowDel = 1 } } @@ -168,4 +170,12 @@ func (m *Comment) Delete() error { o := orm.NewOrm() _, err := o.Delete(m) return err +} + +func (m *Comment) Find(id int, cols ...string) (*Comment, error) { + o := orm.NewOrm() + if err := o.QueryTable(m.TableNameWithPrefix()).Filter("comment_id", id).One(m, cols...); err != nil { + return m, err + } + return m, nil } \ No newline at end of file diff --git a/static/js/kancloud.js b/static/js/kancloud.js index 2c0201c6..dd024d0c 100644 --- a/static/js/kancloud.js +++ b/static/js/kancloud.js @@ -46,22 +46,6 @@ function format($d) { return $d < 10 ? "0" + $d : "" + $d; } -function showError($msg, $id) { - if (!$id) { - $id = "#form-error-message" - } - $($id).addClass("text-danger").removeClass("text-success").text($msg); - return false; -} - -function showSuccess($msg, $id) { - if (!$id) { - $id = "#form-error-message" - } - $($id).addClass("text-success").removeClass("text-danger").text($msg); - return true; -} - function timeFormat($time) { var span = Date.parse($time) var date = new Date(span) @@ -391,17 +375,17 @@ $(function () { }, success : function (res) { if(res.errcode === 0){ - showSuccess("保存成功") + layer.msg("保存成功"); }else{ - showError("保存失败") + layer.msg("保存失败"); } $("#btnSubmitComment").button("reset"); $("#commentContent").val(""); pageClicked(-1, res.data.doc_id); // -1 表示请求最后一页 }, error : function () { - showError("服务错误"); - $("#btnSaveBookInfo").button("reset"); + layer.msg("服务错误"); + $("#btnSubmitComment").button("reset"); } }); }); \ No newline at end of file diff --git a/views/document/default_read.tpl b/views/document/default_read.tpl index 369eea76..e936d8fb 100644 --- a/views/document/default_read.tpl +++ b/views/document/default_read.tpl @@ -205,7 +205,6 @@
    -
    From 1eccb69105ba0d2d3ab2677366d32ec9e41b3c28 Mon Sep 17 00:00:00 2001 From: wangbin13 Date: Sat, 5 Mar 2022 18:15:38 +0800 Subject: [PATCH 4/5] Update setting.tpl --- views/book/setting.tpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/views/book/setting.tpl b/views/book/setting.tpl index 70a665ef..963e6316 100644 --- a/views/book/setting.tpl +++ b/views/book/setting.tpl @@ -100,14 +100,14 @@ 关闭评论 -
    {{if eq .Model.PrivatelyOwned 1}} From a97eb0adb1ab127e7e89acf050c7f2ba03456773 Mon Sep 17 00:00:00 2001 From: wangbin13 Date: Sun, 6 Mar 2022 14:18:24 +0800 Subject: [PATCH 5/5] Update pagination.go --- utils/pagination/pagination.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/utils/pagination/pagination.go b/utils/pagination/pagination.go index 6a3067c8..ecce6c8c 100644 --- a/utils/pagination/pagination.go +++ b/utils/pagination/pagination.go @@ -132,3 +132,29 @@ func (p *Pagination) getLang() string { } return ulang } + +type Page struct { + PageNo int `json:"PageNo"` + PageSize int `json:"PageSize"` + TotalPage int `json:"TotalPage"` + TotalCount int `json:"TotalCount"` + FirstPage bool `json:"FirstPage"` + LastPage bool `json:"LastPage"` + List interface{} `json:"List"` +} + +func PageUtil(count int, pageNo int, pageSize int, list interface{}) Page { + tp := count / pageSize + if count%pageSize > 0 { + tp = count/pageSize + 1 + } + return Page { + PageNo: pageNo, + PageSize: pageSize, + TotalPage: tp, + TotalCount: count, + FirstPage: pageNo == 1, + LastPage: pageNo == tp, + List: list, + } +}