-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.go
480 lines (411 loc) · 12.5 KB
/
threads.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package main
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"net/url"
"strings"
"time"
"unicode"
"codeberg.org/FiskFan1999/gemini"
bolt "go.etcd.io/bbolt"
)
var CurrentlyMutedResponse = gemini.BadRequest.Response("You are currently muted")
var whichPrivCanReplyToLockedThread UserPriviledge = Mod
var ErrThreadIsLocked = errors.New("Thread is locked")
var UnauthorizedCert = gemini.ResponseFormat{
Status: gemini.CertificateNotAuthorised,
Mime: "Unauthorized",
Lines: nil,
}
type SubforumThreads []Thread
// required functions:
// Len() int
// Less(i, j int) bool (i < j = i is more recent)
// Swap(i, j int)
func (s SubforumThreads) Len() int {
return len(s)
}
func (s SubforumThreads) Less(i, j int) bool {
return !(s)[i].LastModified.Before((s)[j].LastModified)
}
func (s SubforumThreads) Swap(i, j int) {
a := (s)[i]
(s)[i] = (s)[j]
(s)[j] = a
}
type Thread struct {
ID []byte
Title []byte
User []byte
LastModified time.Time
Locked bool
Archived bool
}
func OnNewPost(username, threadID, text string, userPriv UserPriviledge) gemini.Response {
if err := db.Update(func(tx *bolt.Tx) error {
/*
Get thread sub-bucket
*/
threads := tx.Bucket(DBALLTHREADS)
if threads == nil {
return errors.New("threads == nil")
}
thread := threads.Bucket([]byte(threadID))
if thread == nil {
// not found
return ErrNotFound
}
if bytes.Equal(thread.Get([]byte("locked")), []byte("1")) && !userPriv.Is(whichPrivCanReplyToLockedThread) {
/*
Thread locked and is not moderator
*/
return ErrThreadIsLocked
}
// change LastModified time
nowBytes, err := time.Now().MarshalText()
if err != nil {
return err
}
thread.Put([]byte("lastmodified"), nowBytes)
err, postID := AddNewPostToDatabase(tx, text, username, nowBytes, []byte(threadID), thread)
if err != nil {
return err
}
sendPostToKeywordDB(username, text, itob(postID), []byte(threadID))
return nil
}); err != nil {
return gemini.TemporaryFailure.Error(err)
}
return gemini.RedirectTemporary.Response(fmt.Sprintf("/thread/%s/", threadID))
}
func NewPostHandler(u *url.URL, c *tls.Conn) gemini.Response {
fp := GetFingerprint(c)
if fp == nil {
return CertRequired
}
username, userPriv, isMuted, _ := GetUsernameFromFP(fp)
if username == "" {
return UnauthorizedCert
}
if isMuted {
return CurrentlyMutedResponse
}
parts := strings.FieldsFunc(u.EscapedPath(), func(r rune) bool { return r == '/' })
if len(parts) != 3 {
gemini.BadRequest.Response("Bad input")
}
id := parts[2]
/*
Get subforum, and then check priviledges
*/
var subforumID string
if err := db.View(func(tx *bolt.Tx) error {
idToSubforum := tx.Bucket(DBTHREADTOSF)
sf := idToSubforum.Get([]byte(id))
if sf == nil {
return errors.New("Thread ID not found")
}
subforumID = string(sf)
return nil
}); err != nil {
return gemini.BadRequest.Error(err)
}
_, threadPriv, err := GetSubforumPrivFromID(subforumID)
if err != nil {
return gemini.BadRequest.Error(err)
}
if !userPriv.Is(threadPriv) {
return gemini.BadRequest.Response("User is not priviledged to reply on this subforum.")
}
if err := CheckForPostNudge(username); errors.Is(err, ShouldPostNudge) {
UpdateForPostNudge(username)
return PostNudgeHandler(u, c)
} else if err != nil {
return gemini.TemporaryFailure.Error(err)
}
if u.RawQuery == "" {
return gemini.Input.Response("New post")
}
text, err := url.QueryUnescape(u.RawQuery)
if err != nil {
return gemini.TemporaryFailure.Error(err)
}
return OnNewPost(username, id, text, userPriv)
}
func AddNewPostToDatabase(tx *bolt.Tx, text string, username string, nowBytes []byte, threadIDBytes []byte, thread *bolt.Bucket) (err error, postID uint64) {
/*
3. Add post written by the user to allposts bucket (key=NextSequence)
in this sub-bucket: text=Text written by user, user=Username
thread=Thread ID (key of thread in subforum bucket)
index=NextSequence of posts subbucket in thread bucket
archived="0" ("1": do not show on thread, in search, etc.)
time=time.Now().MarshalText() (same as thread sub-bucket lastmodified)
*/
posts := tx.Bucket(DBALLPOSTS)
if posts == nil {
return errors.New("posts == nil"), 0
}
postsID, err := posts.NextSequence()
if err != nil {
return err, 0
}
postsIDBytes := itob(postsID)
post, err := posts.CreateBucket(postsIDBytes)
if err != nil {
return err, 0
}
post.Put([]byte("text"), []byte(text))
post.Put([]byte("user"), []byte(username))
post.Put([]byte("time"), nowBytes)
post.Put([]byte("thread"), threadIDBytes)
post.Put([]byte("index"), []byte{}) // will be updated later
post.Put([]byte("archived"), []byte("0"))
post.Put([]byte("reports"), []byte("0"))
/*
4. in the thread bucket posts sub-bucket, put a referral to the post
(key = NextSequence, value = allposts ID)
Assign this key to the post index (see 3.)
*/
threadPosts := thread.Bucket([]byte("posts"))
if threadPosts == nil {
return errors.New("threadPosts == nil"), 0
}
threadPostsNext, err := threadPosts.NextSequence()
if err != nil {
return err, 0
}
threadPostsNextBytes := itob(threadPostsNext)
threadPosts.Put(threadPostsNextBytes, postsIDBytes)
// set index in post in posts bucket to refer to this id
post.Put([]byte("index"), threadPostsNextBytes)
/*
5. in the usersposts bucket user sub-bucket, put a referral to the post (for search)
key=NextSequence val=posts bucket ID
*/
usersPosts := tx.Bucket(DBUSERPOSTS)
if usersPosts == nil {
return errors.New("usersPosts == nil"), 0
}
usersPostsSub, err := usersPosts.CreateBucketIfNotExists([]byte(username))
if err != nil {
return err, 0
}
usersPostsSubNext, err := usersPostsSub.NextSequence()
if err != nil {
return err, 0
}
usersPostsSub.Put(itob(usersPostsSubNext), postsIDBytes)
return nil, postsID
}
const (
TitleMaxLength = 96
)
var (
TitleTooLong = errors.New("Thread title is too long.")
TitleEmptyNotAllowed = errors.New("Empty thread title is not allowed.")
TitleIllegalCharacter = errors.New("Ascii characters are allowed only.")
)
func ValidateThreadTitle(t string) error {
title := strings.TrimSpace(t)
if len(title) == 0 {
return TitleEmptyNotAllowed
}
if len(title) > TitleMaxLength {
return TitleTooLong
}
// only ascii characters are allowed
for _, char := range t {
if !unicode.In(char, unicode.Latin, unicode.Space, unicode.P) {
return TitleIllegalCharacter
}
}
return nil
}
func OnNewThread(subforum, username, title, text string) gemini.Response {
/*
Steps:
1. In thread bucket, create sub-bucket (key=NextSequence) (now referred to as thread bucket)
In this bucket, title=Title, user=Username, lastmodified=time.Now().MarshalText() (for sorting)
locked="0" ("1": don't allow new posts) archived="0" ("1": do not show in lists etc.)
posts=sub-bucket
2. All referral to thread (by id) in the userthreads bucket for sorting
user sub-bucket within userthreads bucket, key=NextSequence value=thread id
3. Add post written by the user to allposts bucket (key=NextSequence)
in this sub-bucket: text=Text written by user, user=Username
thread=Thread ID (key of thread in subforum bucket)
index=NextSequence of posts subbucket in thread bucket
archived="0" ("1": do not show on thread, in search, etc.)
time=time.Now().MarshalText() (same as thread sub-bucket lastmodified)
4. in the thread bucket posts sub-bucket, put a referral to the post
(key = NextSequence, value = allposts ID)
Assign this key to the post index (see 3.)
5. in the usersposts bucket user sub-bucket, put a referral to the post (for search)
key=NextSequence val=posts bucket ID
6. Add reference to thread in subforum bucket (key=NextSequence, val=Thread ID)
7. Add key=threadID val=subforumID pair in DBTHREADTOSF
*/
/*
Validate thread title
*/
title = strings.TrimSpace(title)
if err := ValidateThreadTitle(title); err != nil {
return gemini.BadRequest.Error(err)
}
if err := db.Update(func(tx *bolt.Tx) error {
/*
1. In subforum bucket, create sub-bucket (key=NextSequence) (now referred to as thread bucket)
In this bucket, title=Title, author=Username, lastmodified=time.Now().MarshalText() (for sorting)
locked="0" ("1": don't allow new posts) archived="0" ("1": do not show in lists etc.)
posts=sub-bucket
*/
threads := tx.Bucket(DBALLTHREADS)
if threads == nil {
return errors.New("threads == nil")
}
threadID, err := threads.NextSequence()
if err != nil {
return err
}
threadIDBytes := itob(threadID)
thread, err := threads.CreateBucket(threadIDBytes)
if err != nil {
return err
}
thread.Put([]byte("title"), []byte(title))
thread.Put([]byte("user"), []byte(username))
thread.Put([]byte("locked"), []byte("0"))
thread.Put([]byte("archived"), []byte("0"))
nowBytes, err := time.Now().MarshalText()
if err != nil {
return err
}
thread.Put([]byte("lastmodified"), nowBytes)
if _, err := thread.CreateBucket([]byte("posts")); err != nil {
return err
}
/*
2. All referral to thread (by id) in the userthreads bucket for sorting
user sub-bucket within userthreads bucket, key=NextSequence value=thread id
*/
userthreads := tx.Bucket(DBUSERTHREADS)
if userthreads == nil {
return errors.New("userthreads == nil")
}
userthreadsSub, err := userthreads.CreateBucketIfNotExists([]byte(username))
if err != nil {
return err
}
userthreadsSubNext, err := userthreadsSub.NextSequence()
if err != nil {
return err
}
userthreadsSub.Put(itob(userthreadsSubNext), threadIDBytes)
err, postID := AddNewPostToDatabase(tx, text, username, nowBytes, threadIDBytes, thread)
if err != nil {
return err
}
sendPostToKeywordDB(username, text, itob(postID), itob(threadID))
/*
6. Add reference to thread in subforum bucket (key=NextSequence, val=Thread ID)
*/
subforumBucket := tx.Bucket(DBSUBFORUMS)
if subforumBucket == nil {
return errors.New("subforumBucket == nil")
}
subforumBucketSub := subforumBucket.Bucket([]byte(subforum))
if subforumBucketSub == nil {
return errors.New("subforumBucketSub == nil")
}
sfbsNext, err := subforumBucketSub.NextSequence()
if err != nil {
return err
}
subforumBucketSub.Put(itob(sfbsNext), threadIDBytes)
/*
7. Add key=threadID val=subforumID pair in DBTHREADTOSF
*/
threadToSubf := tx.Bucket(DBTHREADTOSF)
threadToSubf.Put(threadIDBytes, []byte(subforum))
return nil
}); err != nil {
return gemini.TemporaryFailure.Error(err)
}
return gemini.RedirectTemporary.Response(fmt.Sprintf("/f/%s/", subforum))
}
func CreateThreadHandler(u *url.URL, c *tls.Conn) gemini.Response {
// get fingerprint and user
fp := GetFingerprint(c)
if fp == nil {
return CertRequired
}
username, userPriv, isMuted, _ := GetUsernameFromFP(fp)
if username == "" {
return UnauthorizedCert
}
if isMuted {
return CurrentlyMutedResponse
}
if err := CheckForPostNudge(username); errors.Is(err, ShouldPostNudge) {
UpdateForPostNudge(username)
return PostNudgeHandler(u, c)
} else if err != nil {
return gemini.ResponseFormat{
Status: gemini.TemporaryFailure,
Mime: err.Error(),
Lines: nil,
}
}
parts := strings.FieldsFunc(u.EscapedPath(), func(r rune) bool { return r == '/' })
if len(parts) < 3 {
return gemini.BadRequest.Response("Bad request")
}
subforum := parts[2]
threadPriv, _, err := GetSubforumPrivFromID(subforum)
if err != nil {
return gemini.BadRequest.Error(err)
}
if !userPriv.Is(threadPriv) {
// user is not authorized to make threads in this subforum
return gemini.BadRequest.Response("User is not authorized to make a thread in this subforum")
}
switch len(parts) {
case 3:
if u.RawQuery == "" {
return gemini.Input.Response("Thread title")
} else {
return gemini.RedirectTemporary.Response(fmt.Sprintf("/%s/%s/", strings.Join(parts, "/"), u.RawQuery))
}
case 4:
if u.RawQuery == "" {
return gemini.Input.Response("Thread title") // TODO: fix this line mime type
} else {
title, err := url.PathUnescape(parts[3])
if err != nil {
return gemini.BadRequest.Error(err)
}
text, err := url.QueryUnescape(u.RawQuery)
if err != nil {
return gemini.BadRequest.Error(err)
}
return OnNewThread(subforum, username, title, text)
}
default:
return BadUserInput
}
}
var SubforumNotFound = errors.New("Subforum not found")
func GetSubforumPrivFromID(subforum string) (thread, reply UserPriviledge, err error) {
for _, forum := range Configuration.Forum {
for _, subf := range forum.Subforum {
if subf.ID == subforum {
thread = subf.ThreadPriviledge
reply = subf.ReplyPriviledge
return
}
}
}
err = SubforumNotFound
return
}