forked from bakape/shamichan
/
post_creation.go
367 lines (322 loc) · 7.41 KB
/
post_creation.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package websockets
import (
"errors"
"meguca/auth"
"meguca/common"
"meguca/config"
"meguca/db"
"meguca/geoip"
"meguca/parser"
"meguca/websockets/feeds"
"strings"
"time"
"unicode/utf8"
)
var (
errReadOnly = errors.New("read only board")
errInvalidImageToken = errors.New("invalid image token")
errImageNameTooLong = errors.New("image name too long")
errNoTextOrImage = errors.New("no text or image")
)
// ThreadCreationRequest contains data for creating a new thread
type ThreadCreationRequest struct {
NonLive bool
ReplyCreationRequest
Subject, Board string
}
// ReplyCreationRequest contains common fields for both thread and reply
// creation
type ReplyCreationRequest struct {
Sage, Open bool
Image ImageRequest
auth.SessionCreds
auth.Captcha
Name, Password, Body string
}
// ImageRequest contains data for allocating an image
type ImageRequest struct {
Spoiler bool
Token, Name string
}
// CreateThread creates a new tread and writes it to the database.
// open specifies, if the thread OP should stay open after creation.
func CreateThread(req ThreadCreationRequest, ip string) (
post db.Post, err error,
) {
switch {
case !auth.IsNonMetaBoard(req.Board):
err = errInvalidBoard
return
case auth.IsBanned(req.Board, ip):
err = errBanned
return
case !auth.AuthenticateCaptcha(req.Captcha):
err = errInValidCaptcha
return
}
conf, err := getBoardConfig(req.Board)
if err != nil {
return
}
post, err = constructPost(req.ReplyCreationRequest, conf, ip)
if err != nil {
return
}
subject, err := parser.ParseSubject(req.Subject)
if err != nil {
return
}
// Perform this last, so there are less dangling images because of any error
hasImage := !conf.TextOnly && req.Image.Token != "" && req.Image.Name != ""
if hasImage {
img := req.Image
post.Image, err = getImage(img.Token, img.Name, img.Spoiler)
if err != nil {
return
}
}
post.ID, err = db.NewPostID()
if err != nil {
return
}
post.OP = post.ID
err = db.InsertThread(subject, conf.NonLive || req.NonLive, post)
return
}
// CreatePost creates a new post and writes it to the database.
// open specifies, if the post should stay open after creation.
func CreatePost(
op uint64,
board, ip string,
needCaptcha bool,
req ReplyCreationRequest,
) (
post db.Post, msg []byte, err error,
) {
if auth.IsBanned(board, ip) {
err = errBanned
return
}
if needCaptcha {
if !auth.AuthenticateCaptcha(req.Captcha) {
err = errInValidCaptcha
return
} else if config.Get().Captcha {
// Captcha solved - reset spam score.
auth.ResetSpamScore(ip)
}
}
conf, err := getBoardConfig(board)
if err != nil {
return
}
// Post must have either at least one character or an image to be allocated
hasImage := !conf.TextOnly && req.Image.Token != "" && req.Image.Name != ""
if req.Body == "" && !hasImage {
err = errNoTextOrImage
return
}
// Disable live updates, if thread is non-live
if req.Open {
var disabled bool
disabled, err = db.CheckThreadNonLive(op)
if err != nil {
return
}
req.Open = !disabled
}
post, err = constructPost(req, conf, ip)
if err != nil {
return
}
if hasImage {
img := req.Image
post.Image, err = getImage(img.Token, img.Name, img.Spoiler)
if err != nil {
return
}
}
post.OP = op
post.ID, err = db.NewPostID()
if err != nil {
return
}
msg, err = common.EncodeMessage(common.MessageInsertPost, post.Post)
if err != nil {
return
}
err = db.InsertPost(post, req.Sage)
return
}
// Insert a new post into the database
func (c *Client) insertPost(data []byte) (err error) {
err = c.closePreviousPost()
if err != nil {
return
}
var req ReplyCreationRequest
err = decodeMessage(data, &req)
if err != nil {
return
}
_, op, board := feeds.GetSync(c)
post, msg, err := CreatePost(op, board, c.ip, !auth.CanPost(c.ip), req)
if err != nil {
return
}
// Ensure the client knows the post ID, before the public post insertion
// update message is sent
err = c.sendMessage(common.MessagePostID, post.ID)
if err != nil {
return
}
if post.Editing {
c.post.init(post.StandalonePost)
}
c.feed.InsertPost(post.StandalonePost, c.post.body, msg)
score := auth.PostCreationScore + auth.CharScore*time.Duration(c.post.len)
if post.Image != nil {
score += auth.ImageScore
}
return c.incrementSpamScore(score)
}
// Reset the IP's spam score, by submitting a captcha
func (c *Client) submitCaptcha(data []byte) (err error) {
var msg auth.Captcha
err = decodeMessage(data, &msg)
if err != nil {
return
}
if !auth.AuthenticateCaptcha(msg) {
return errInValidCaptcha
}
auth.ResetSpamScore(c.ip)
return nil
}
// If the client has a previous post, close it silently
func (c *Client) closePreviousPost() error {
if c.post.id != 0 {
return c.closePost()
}
return nil
}
// Retrieve post-related board configurations
func getBoardConfig(board string) (conf config.BoardConfigs, err error) {
conf = config.GetBoardConfigs(board).BoardConfigs
if conf.ReadOnly {
err = errReadOnly
}
return
}
// Construct the common parts of the new post for both threads and replies
func constructPost(
req ReplyCreationRequest,
conf config.BoardConfigs,
ip string,
) (
post db.Post, err error,
) {
post = db.Post{
StandalonePost: common.StandalonePost{
Post: common.Post{
Time: time.Now().Unix(),
Sage: req.Sage,
Body: req.Body,
},
Board: conf.ID,
},
IP: ip,
}
if !conf.ForcedAnon {
post.Name, post.Trip, err = parser.ParseName(req.Name)
if err != nil {
return
}
}
if conf.Flags {
post.Flag = geoip.LookUp(ip)
}
if utf8.RuneCountInString(req.Body) > common.MaxLenBody {
err = common.ErrBodyTooLong
return
}
lines := 0
for _, r := range req.Body {
if r == '\n' {
lines++
}
}
if lines > common.MaxLinesBody {
err = errTooManyLines
return
}
// Attach staff position title after validations
if req.UserID != "" {
var pos auth.ModerationLevel
pos, err = db.FindPosition(conf.ID, req.UserID)
if err != nil {
return
}
post.Auth = pos.String()
var loggedIn bool
loggedIn, err = db.IsLoggedIn(req.UserID, req.Session)
if err != nil {
return
}
if !loggedIn {
err = common.ErrInvalidCreds
return
}
}
if req.Open {
post.Editing = true
// Posts that are committed in one action need not a password, as they
// are closed on commit and can not be reclaimed
err = parser.VerifyPostPassword(req.Password)
if err != nil {
return
}
post.Password, err = auth.BcryptHash(req.Password, 4)
if err != nil {
return
}
} else {
post.Links, post.Commands, err = parser.ParseBody(
[]byte(req.Body),
conf.ID,
)
if err != nil {
return
}
}
return
}
// Performs some validations and retrieves processed image data by token ID.
// Embeds spoiler and image name in result struct. The last extension is
// stripped from the name.
func getImage(token, name string, spoiler bool) (img *common.Image, err error) {
if len(name) > 200 {
return nil, errImageNameTooLong
}
imgCommon, err := db.UseImageToken(token)
switch err {
case nil:
case db.ErrInvalidToken:
return nil, errInvalidImageToken
default:
return nil, err
}
// Trim on the last dot in the file name, but also strip for .tar.gz and
// .tar.xz as special cases.
if i := strings.LastIndexByte(name, '.'); i != -1 {
name = name[:i]
}
if strings.HasSuffix(name, ".tar") {
name = name[:len(name)-4]
}
return &common.Image{
ImageCommon: imgCommon,
Spoiler: spoiler,
Name: name,
}, nil
}