forked from dingoblog/dingo
/
comment.go
236 lines (193 loc) · 5.7 KB
/
comment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package model
import (
// "database/sql"
"time"
"fmt"
"github.com/covrom/dingo/app/utils"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
// Comments are a slice of "Comment"s
type Comments []*Comment
// A Comment defines comment item data.
type Comment struct {
Id bson.ObjectId
PostId string
Author string
Email string
Avatar string
Website string
Ip string
CreatedAt *time.Time
Content string
Approved bool
UserAgent string
Type string
Parent string
UserId string
Children *Comments `json:"-" bson:"-"`
}
// Len returns the number of "Comment"s in a "Comments".
func (c Comments) Len() int {
return len(c)
}
// Get returns the Comment at the given index.
func (c Comments) Get(i int) *Comment {
return c[i]
}
// GetAll returns a slice of all the "Comment"s.
func (c Comments) GetAll() []*Comment {
return c
}
// NewComment returns a new comment, with the CreatedAt field set to the
// current time.
func NewComment() *Comment {
return &Comment{
Id: bson.NewObjectId(),
CreatedAt: utils.Now(),
}
}
// Save saves the comment in the DB.
func (c *Comment) Save() error {
c.Avatar = utils.Gravatar(c.Email, "50")
if len(c.Id) == 0 {
c.Id = bson.NewObjectId()
}
_, err := comSession.Clone().DB(DBName).C("comments").UpsertId(c.Id, c)
return err
}
// ToJson returns a comment as a map, in order to be encoded as JSON.
func (c *Comment) ToJson() map[string]interface{} {
m := make(map[string]interface{})
m["id"] = c.Id
m["author"] = c.Author
m["email"] = c.Email
m["website"] = c.Website
m["avatar"] = c.Avatar
m["content"] = c.Content
m["create_time"] = c.CreatedAt.Unix()
m["pid"] = c.Parent
m["approved"] = c.Approved
m["ip"] = c.Ip
m["user_agent"] = c.UserAgent
m["parent_content"] = c.ParentContent()
return m
}
// ParentContent returns the parent of a given comment, if it exists. Used for
// threaded comments.
func (c *Comment) ParentContent() string {
if len(c.Parent) == 0 {
return ""
}
comment := &Comment{Id: bson.ObjectIdHex(c.Parent)}
err := comment.GetCommentById()
if err != nil {
return "> Comment not found."
}
str := "> @" + comment.Author + "\n\n"
str += "> " + comment.Content + "\n"
return str
}
// GetNumberOfComments returns the total number of comments in the DB.
func GetNumberOfComments() (int64, error) {
count, err := comSession.Clone().DB(DBName).C("comments").Count()
if err != nil {
return 0, err
}
return int64(count), nil
}
// GetCommentList returns a new pager based on the total number of comments.
func (c *Comments) GetCommentList(page, size int64, onlyApproved bool) (*utils.Pager, error) {
var pager *utils.Pager
count, err := GetNumberOfComments()
pager = utils.NewPager(page, size, count)
if !pager.IsValid {
return pager, fmt.Errorf("Page not found")
}
if onlyApproved {
err = comSession.Clone().DB(DBName).C("comments").Find(bson.M{"approved": true}).Sort("-createdat").Skip(int(pager.Begin)).Limit(int(size)).All(c)
} else {
err = comSession.Clone().DB(DBName).C("comments").Find(bson.M{}).Sort("-createdat").Skip(int(pager.Begin)).Limit(int(size)).All(c)
}
return pager, err
}
// GetCommentById gets a comment by its ID, and populates that comment struct
// with the contents for that comment from the DB.
func (c *Comment) GetCommentById() error {
err := comSession.Clone().DB(DBName).C("comments").FindId(c.Id).One(c)
return err
}
func (c *Comment) getChildComments() (*Comments, error) {
comments := new(Comments)
err := comSession.Clone().DB(DBName).C("comments").Find(bson.M{"parent": c.Id.Hex(), "approved": true}).All(comments)
return comments, err
}
// ParentComment returns the associated parent Comment, if one exists.
func (c *Comment) ParentComment() (*Comment, error) {
parent := NewComment()
parent.Id = bson.ObjectIdHex(c.Parent)
return parent, parent.GetCommentById()
}
// Post returns the post associated with the commment.
func (c *Comment) Post() *Post {
post := NewPost()
post.Id = bson.ObjectIdHex(c.PostId)
post.GetPostById()
return post
}
// GetCommentsByPostId gets all the comments for the given post ID.
func (comments *Comments) GetCommentsByPostId(id string) error {
err := comSession.Clone().DB(DBName).C("comments").Find(bson.M{"postid": id, "parent": "", "approved": true}).All(comments)
for _, c := range *comments {
buildCommentTree(c, c, 1)
}
return err
}
func buildCommentTree(p *Comment, c *Comment, level int) {
childComments, _ := c.getChildComments()
if p.Children == nil {
p.Children = childComments
} else {
newChildComments := append(*p.Children, *childComments...)
p.Children = &newChildComments
}
for _, c := range *childComments {
if level >= 2 {
buildCommentTree(p, c, level+1)
} else {
buildCommentTree(c, c, level+1)
}
}
}
// DeleteComment deletes the comment with the given ID from the DB.
func DeleteComment(id string) error {
session := comSession.Clone()
childs := new(Comments)
err := session.DB(DBName).C("comments").Find(bson.M{"parent": id}).All(childs)
if err == nil {
for _, child := range *childs {
if len(child.Id) > 0 {
DeleteComment(child.Id.Hex())
}
}
}
err = session.DB(DBName).C("comments").RemoveId(bson.ObjectIdHex(id))
if err == mgo.ErrNotFound {
err = nil
}
return err
}
// ValidateComment validates a comment to ensure that all required data exists
// and is valid. Returns an empty string on success.
func (c *Comment) ValidateComment() string {
if utils.IsEmptyString(c.Author) || utils.IsEmptyString(c.Content) {
return "Name, Email and Content are required fields."
}
if !utils.IsEmail(c.Email) {
return "Email format not valid."
}
if !utils.IsEmptyString(c.Website) && !utils.IsURL(c.Website) {
return "Website URL format not valid."
}
return ""
}