You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
2.6 KiB

4 years ago
package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
4 years ago
"github.com/imdotdev/im.dev/server/internal/interaction"
4 years ago
"github.com/imdotdev/im.dev/server/internal/story"
4 years ago
"github.com/imdotdev/im.dev/server/internal/user"
4 years ago
"github.com/imdotdev/im.dev/server/pkg/common"
"github.com/imdotdev/im.dev/server/pkg/e"
"github.com/imdotdev/im.dev/server/pkg/models"
"github.com/imdotdev/im.dev/server/pkg/utils"
)
func SubmitComment(c *gin.Context) {
comment := &models.Comment{}
c.Bind(&comment)
comment.Md = strings.TrimSpace(comment.Md)
if comment.Md == "" {
c.JSON(http.StatusBadRequest, "评论内容不能为空")
return
}
// check story exist
4 years ago
exist := models.IdExist(comment.TargetID)
4 years ago
if !exist {
c.JSON(http.StatusNotFound, common.RespError(e.NotFound))
return
}
var err *e.Error
if comment.ID == "" { //add comment
4 years ago
user := user.CurrentUser(c)
4 years ago
comment.CreatorID = user.ID
4 years ago
comment.ID = utils.GenID(models.IDTypeComment)
4 years ago
err = story.AddComment(comment)
} else { // update comment
err = story.EditComment(comment)
}
if err != nil {
c.JSON(err.Status, common.RespError(err.Message))
return
}
c.JSON(http.StatusOK, common.RespSuccess(nil))
}
func GetStoryComments(c *gin.Context) {
storyID := c.Param("id")
sorter := c.Query("sorter")
if !models.ValidSearchFilter(sorter) {
c.JSON(http.StatusBadRequest, e.ParamInvalid)
return
}
comments, err := story.GetComments(storyID, sorter)
4 years ago
if err != nil {
c.JSON(err.Status, common.RespError(err.Message))
return
}
4 years ago
user := user.CurrentUser(c)
4 years ago
for _, comment := range comments {
if user != nil {
4 years ago
comment.Liked = interaction.GetLiked(comment.ID, user.ID)
4 years ago
}
replies, err := story.GetComments(comment.ID, sorter)
4 years ago
if err != nil {
continue
}
comment.Replies = replies
for _, reply := range replies {
if user != nil {
4 years ago
reply.Liked = interaction.GetLiked(reply.ID, user.ID)
4 years ago
}
}
}
c.JSON(http.StatusOK, common.RespSuccess(comments))
}
4 years ago
func DeleteStoryComment(c *gin.Context) {
4 years ago
id := c.Param("id")
//only admin and owner can delete comment
comment, err := story.GetComment(id)
if err != nil {
c.JSON(err.Status, common.RespError(err.Message))
return
}
4 years ago
user := user.CurrentUser(c)
4 years ago
canDel := false
if user.Role.IsAdmin() {
canDel = true
} else {
if user.ID == comment.CreatorID {
canDel = true
}
}
if !canDel {
c.JSON(http.StatusForbidden, common.RespError(e.NoPermission))
return
}
err = story.DeleteComment(id)
if err != nil {
c.JSON(err.Status, common.RespError(err.Message))
return
}
c.JSON(http.StatusOK, common.RespSuccess(nil))
}