-
Notifications
You must be signed in to change notification settings - Fork 0
/
post.go
255 lines (222 loc) · 5.01 KB
/
post.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
package main
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
type Post struct {
DataModel
Name string `json:"name"`
Subject string `json:"subject"`
Text string `json:"text"`
Sage bool `json:"sage"`
Board string `json:"board"`
Parent uint `json:"parent"`
LastBump time.Time `json:"last_bump"`
IpHash string `json:"-"`
CaptchaId string `json:"-" gorm:"-:all"`
CaptchaValue string `json:"-" gorm:"-:all"`
FilesJson string `json:"-"`
Files []File `gorm:"-:all"`
}
func migratePost() error {
return db.AutoMigrate(&Post{})
}
func (t Post) FormatTimestamp() string {
return t.CreatedAt.Format("02/01/2006 15:04:05")
}
func (t Post) HasFiles() bool {
return len(t.Files) != 0
}
// Replace markdown tags with html tags.
func (t Post) RenderedText() template.HTML {
return replaceMarkdown(t.Text)
}
func (p *Post) CheckBanned() error {
var b Ban
err := db.Where(&Ban{Hash: p.IpHash}).First(&b).Error
switch err {
case nil:
break
case gorm.ErrRecordNotFound:
return nil
default:
return err
}
if b.HasExpired() {
return nil
}
return fmt.Errorf(
"banned until %v for %s",
b.Until,
b.Reason,
)
}
func (p *Post) CheckBoard() error {
var b Board
err := db.Where(&Board{Link: p.Board}).First(&b).Error
switch err {
case gorm.ErrRecordNotFound:
return errors.New("invalid board")
default:
return err
}
}
func (p *Post) CheckThread() error {
if p.Parent == 0 {
return nil
}
var f Post
err := db.Where(&Post{}).
First(&f, "parent = 0 AND board = ? AND id = ?", p.Board, p.Parent).
Error
switch err {
case gorm.ErrRecordNotFound:
return errors.New("invalid thread id")
default:
return err
}
}
func (p *Post) CheckSubject() error {
l := len(p.Subject)
if l == 0 && p.Parent == 0 {
return ErrorEmptySubject
}
if l > 80 {
p.Subject = p.Subject[:80]
}
return nil
}
func (p *Post) CheckName() error {
if p.Name == "" {
p.Name = "Anonymous"
}
if len(p.Name) > 80 {
return ErrorNameTooLong
}
return nil
}
// Validate post captcha.
func (p *Post) CheckCaptcha() error {
valid := captchas.Check(p.CaptchaValue, p.CaptchaId)
captchas.Delete(p.CaptchaId)
log.Debug().Msgf(
"captcha %s was deleted",
p.CaptchaId,
)
if !valid {
return ErrorInvalidCaptcha
}
return nil
}
func (p *Post) GetFiles(tx *gorm.DB) ([]File, error) {
var fs FilesJson
if err := json.Unmarshal([]byte(p.FilesJson), &fs); err != nil {
return nil, err
}
if len(fs.Ids) == 0 {
log.Debug().Msgf("(*Post).FilesJson=%s", p.FilesJson)
return nil, nil
}
var files []File
res := tx.Find(&files, fs.Ids)
return files, res.Error
}
func (p *Post) SetFiles(tx *gorm.DB, fs []File) error {
ids := FilesJson{make([]int, 0)}
for i := range fs {
ids.Ids = append(ids.Ids, int(fs[i].ID))
}
m, err := json.Marshal(ids)
if err != nil {
return err
}
res := tx.Model(p).Updates(Post{
FilesJson: string(m),
})
return res.Error
}
func (p *Post) BumpParent(tx *gorm.DB) error {
if p.Sage || p.Parent == 0 {
return nil
}
res := tx.Model(&Post{}).
Where("id = ?", p.Parent).
Update("last_bump", time.Now())
return res.Error
}
// Create post record using database transation.
func (p *Post) Create(ctx echo.Context) error {
return db.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(p).Error; err != nil {
return err
}
// Bump parent thread optionally.
if err := p.BumpParent(tx); err != nil {
return err
}
// todo(zvezdochka):
// manage files as kind of `transaction` also.
// eg. if there is fail to create record in db,
// then files should be removed from disk.
// also: maybe use some /temp place?
// Upload files on disk.
fs, err := processFiles(ctx)
if err != nil {
return err
}
// Create files records in db.
for i := range fs {
if err := tx.Create(&fs[i]).Error; err != nil {
return err
}
}
// Assosiate files with current post.
return p.SetFiles(tx, fs)
})
}
func createPost(c echo.Context) error {
post := new(Post)
err := echo.FormFieldBinder(c).
String("name", &post.Name).
String("subject", &post.Subject).
String("text", &post.Text).
String("board", &post.Board).
String("captcha_id", &post.CaptchaId).
String("captcha_value", &post.CaptchaValue).
Uint("parent", &post.Parent).
Bool("sage", &post.Sage).
BindError()
if err != nil {
log.Error().Msg(err.Error())
return c.JSON(http.StatusBadRequest, ErrorBadRequest)
}
post.IpHash = hash(c.RealIP())
post.LastBump = time.Now()
checks := Maybe{
post.CheckBanned,
post.CheckBoard,
post.CheckThread,
post.CheckSubject,
post.CheckName,
post.CheckCaptcha,
}
if err := checks.Eval(); err != nil {
log.Debug().Msg(err.Error())
return c.JSON(http.StatusBadRequest, Error{err.Error()})
}
if err := post.Create(c); err != nil {
log.Error().Msg(err.Error())
jsonerr := Error{
E: fmt.Sprintf("transaction failed: %v", err),
}
return c.JSON(http.StatusInternalServerError, jsonerr)
}
return c.JSON(http.StatusCreated, post)
}