-
Notifications
You must be signed in to change notification settings - Fork 0
/
livecomment_handler.go
482 lines (408 loc) · 15.7 KB
/
livecomment_handler.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
481
482
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/jmoiron/sqlx"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
type PostLivecommentRequest struct {
Comment string `json:"comment"`
Tip int64 `json:"tip"`
}
type LivecommentModel struct {
ID int64 `db:"id"`
UserID int64 `db:"user_id"`
LivestreamID int64 `db:"livestream_id"`
Comment string `db:"comment"`
Tip int64 `db:"tip"`
CreatedAt int64 `db:"created_at"`
}
type Livecomment struct {
ID int64 `json:"id"`
User User `json:"user"`
Livestream Livestream `json:"livestream"`
Comment string `json:"comment"`
Tip int64 `json:"tip"`
CreatedAt int64 `json:"created_at"`
}
type LivecommentReport struct {
ID int64 `json:"id"`
Reporter User `json:"reporter"`
Livecomment Livecomment `json:"livecomment"`
CreatedAt int64 `json:"created_at"`
}
type LivecommentReportModel struct {
ID int64 `db:"id"`
UserID int64 `db:"user_id"`
LivestreamID int64 `db:"livestream_id"`
LivecommentID int64 `db:"livecomment_id"`
CreatedAt int64 `db:"created_at"`
}
type ModerateRequest struct {
NGWord string `json:"ng_word"`
}
type NGWord struct {
ID int64 `json:"id" db:"id"`
UserID int64 `json:"user_id" db:"user_id"`
LivestreamID int64 `json:"livestream_id" db:"livestream_id"`
Word string `json:"word" db:"word"`
CreatedAt int64 `json:"created_at" db:"created_at"`
}
func getLivecommentsHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
// echo.NewHTTPErrorが返っているのでそのまま出力
return err
}
livestreamID, err := strconv.Atoi(c.Param("livestream_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livestream_id in path must be integer")
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
query := "SELECT * FROM livecomments WHERE livestream_id = ? ORDER BY created_at DESC"
if c.QueryParam("limit") != "" {
limit, err := strconv.Atoi(c.QueryParam("limit"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "limit query parameter must be integer")
}
query += fmt.Sprintf(" LIMIT %d", limit)
}
livecommentModels := []LivecommentModel{}
err = tx.SelectContext(ctx, &livecommentModels, query, livestreamID)
if errors.Is(err, sql.ErrNoRows) {
return c.JSON(http.StatusOK, []*Livecomment{})
}
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livecomments: "+err.Error())
}
livecomments := make([]Livecomment, len(livecommentModels))
for i := range livecommentModels {
livecomment, err := fillLivecommentResponse(ctx, tx, livecommentModels[i])
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fil livecomments: "+err.Error())
}
livecomments[i] = livecomment
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, livecomments)
}
func getNgwords(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
return err
}
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
livestreamID, err := strconv.Atoi(c.Param("livestream_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livestream_id in path must be integer")
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
var ngWords []*NGWord
if err := tx.SelectContext(ctx, &ngWords, "SELECT * FROM ng_words WHERE user_id = ? AND livestream_id = ? ORDER BY created_at DESC", userID, livestreamID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return c.JSON(http.StatusOK, []*NGWord{})
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get NG words: "+err.Error())
}
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, ngWords)
}
func postLivecommentHandler(c echo.Context) error {
ctx := c.Request().Context()
defer c.Request().Body.Close()
if err := verifyUserSession(c); err != nil {
return err
}
livestreamID, err := strconv.Atoi(c.Param("livestream_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livestream_id in path must be integer")
}
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
var req *PostLivecommentRequest
if err := json.NewDecoder(c.Request().Body).Decode(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "failed to decode the request body as json")
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
var livestreamModel LivestreamModel
if err := tx.GetContext(ctx, &livestreamModel, "SELECT * FROM livestreams WHERE id = ?", livestreamID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, "livestream not found")
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestream: "+err.Error())
}
}
// スパム判定
var ngwords []*NGWord
if err := tx.SelectContext(ctx, &ngwords, "SELECT id, user_id, livestream_id, word FROM ng_words WHERE user_id = ? AND livestream_id = ?", livestreamModel.UserID, livestreamModel.ID); err != nil && !errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get NG words: "+err.Error())
}
var hitSpam int
for _, ngword := range ngwords {
query := `
SELECT COUNT(*)
FROM
(SELECT ? AS text) AS texts
INNER JOIN
(SELECT CONCAT('%', ?, '%') AS pattern) AS patterns
ON texts.text LIKE patterns.pattern;
`
if err := tx.GetContext(ctx, &hitSpam, query, req.Comment, ngword.Word); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get hitspam: "+err.Error())
}
c.Logger().Infof("[hitSpam=%d] comment = %s", hitSpam, req.Comment)
if hitSpam >= 1 {
return echo.NewHTTPError(http.StatusBadRequest, "このコメントがスパム判定されました")
}
}
now := time.Now().Unix()
livecommentModel := LivecommentModel{
UserID: userID,
LivestreamID: int64(livestreamID),
Comment: req.Comment,
Tip: req.Tip,
CreatedAt: now,
}
rs, err := tx.NamedExecContext(ctx, "INSERT INTO livecomments (user_id, livestream_id, comment, tip, created_at) VALUES (:user_id, :livestream_id, :comment, :tip, :created_at)", livecommentModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert livecomment: "+err.Error())
}
livecommentID, err := rs.LastInsertId()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get last inserted livecomment id: "+err.Error())
}
livecommentModel.ID = livecommentID
livecomment, err := fillLivecommentResponse(ctx, tx, livecommentModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livecomment: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusCreated, livecomment)
}
func reportLivecommentHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
return err
}
livestreamID, err := strconv.Atoi(c.Param("livestream_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livestream_id in path must be integer")
}
livecommentID, err := strconv.Atoi(c.Param("livecomment_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livecomment_id in path must be integer")
}
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
var livestreamModel LivestreamModel
if err := tx.GetContext(ctx, &livestreamModel, "SELECT * FROM livestreams WHERE id = ?", livestreamID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, "livestream not found")
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestream: "+err.Error())
}
}
var livecommentModel LivecommentModel
if err := tx.GetContext(ctx, &livecommentModel, "SELECT * FROM livecomments WHERE id = ?", livecommentID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, "livecomment not found")
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livecomment: "+err.Error())
}
}
now := time.Now().Unix()
reportModel := LivecommentReportModel{
UserID: int64(userID),
LivestreamID: int64(livestreamID),
LivecommentID: int64(livecommentID),
CreatedAt: now,
}
rs, err := tx.NamedExecContext(ctx, "INSERT INTO livecomment_reports(user_id, livestream_id, livecomment_id, created_at) VALUES (:user_id, :livestream_id, :livecomment_id, :created_at)", &reportModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert livecomment report: "+err.Error())
}
reportID, err := rs.LastInsertId()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get last inserted livecomment report id: "+err.Error())
}
reportModel.ID = reportID
report, err := fillLivecommentReportResponse(ctx, tx, reportModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livecomment report: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusCreated, report)
}
// NGワードを登録
func moderateHandler(c echo.Context) error {
ctx := c.Request().Context()
defer c.Request().Body.Close()
if err := verifyUserSession(c); err != nil {
return err
}
livestreamID, err := strconv.Atoi(c.Param("livestream_id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "livestream_id in path must be integer")
}
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
var req *ModerateRequest
if err := json.NewDecoder(c.Request().Body).Decode(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "failed to decode the request body as json")
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
// 配信者自身の配信に対するmoderateなのかを検証
var ownedLivestreams []LivestreamModel
if err := tx.SelectContext(ctx, &ownedLivestreams, "SELECT * FROM livestreams WHERE id = ? AND user_id = ?", livestreamID, userID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestreams: "+err.Error())
}
if len(ownedLivestreams) == 0 {
return echo.NewHTTPError(http.StatusBadRequest, "A streamer can't moderate livestreams that other streamers own")
}
rs, err := tx.NamedExecContext(ctx, "INSERT INTO ng_words(user_id, livestream_id, word, created_at) VALUES (:user_id, :livestream_id, :word, :created_at)", &NGWord{
UserID: int64(userID),
LivestreamID: int64(livestreamID),
Word: req.NGWord,
CreatedAt: time.Now().Unix(),
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert new NG word: "+err.Error())
}
wordID, err := rs.LastInsertId()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get last inserted NG word id: "+err.Error())
}
var ngwords []*NGWord
if err := tx.SelectContext(ctx, &ngwords, "SELECT * FROM ng_words WHERE livestream_id = ?", livestreamID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get NG words: "+err.Error())
}
// NGワードにヒットする過去の投稿も全削除する
for _, ngword := range ngwords {
// ライブコメント一覧取得
var livecomments []*LivecommentModel
if err := tx.SelectContext(ctx, &livecomments, "SELECT * FROM livecomments"); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livecomments: "+err.Error())
}
for _, livecomment := range livecomments {
query := `
DELETE FROM livecomments
WHERE
id = ? AND
livestream_id = ? AND
(SELECT COUNT(*)
FROM
(SELECT ? AS text) AS texts
INNER JOIN
(SELECT CONCAT('%', ?, '%') AS pattern) AS patterns
ON texts.text LIKE patterns.pattern) >= 1;
`
if _, err := tx.ExecContext(ctx, query, livecomment.ID, livestreamID, livecomment.Comment, ngword.Word); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to delete old livecomments that hit spams: "+err.Error())
}
}
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusCreated, map[string]interface{}{
"word_id": wordID,
})
}
func fillLivecommentResponse(ctx context.Context, tx *sqlx.Tx, livecommentModel LivecommentModel) (Livecomment, error) {
commentOwnerModel := UserModel{}
if err := tx.GetContext(ctx, &commentOwnerModel, "SELECT * FROM users WHERE id = ?", livecommentModel.UserID); err != nil {
return Livecomment{}, err
}
commentOwner, err := fillUserResponse(ctx, tx, commentOwnerModel)
if err != nil {
return Livecomment{}, err
}
livestreamModel := LivestreamModel{}
if err := tx.GetContext(ctx, &livestreamModel, "SELECT * FROM livestreams WHERE id = ?", livecommentModel.LivestreamID); err != nil {
return Livecomment{}, err
}
livestream, err := fillLivestreamResponse(ctx, tx, livestreamModel)
if err != nil {
return Livecomment{}, err
}
livecomment := Livecomment{
ID: livecommentModel.ID,
User: commentOwner,
Livestream: livestream,
Comment: livecommentModel.Comment,
Tip: livecommentModel.Tip,
CreatedAt: livecommentModel.CreatedAt,
}
return livecomment, nil
}
func fillLivecommentReportResponse(ctx context.Context, tx *sqlx.Tx, reportModel LivecommentReportModel) (LivecommentReport, error) {
reporterModel := UserModel{}
if err := tx.GetContext(ctx, &reporterModel, "SELECT * FROM users WHERE id = ?", reportModel.UserID); err != nil {
return LivecommentReport{}, err
}
reporter, err := fillUserResponse(ctx, tx, reporterModel)
if err != nil {
return LivecommentReport{}, err
}
livecommentModel := LivecommentModel{}
if err := tx.GetContext(ctx, &livecommentModel, "SELECT * FROM livecomments WHERE id = ?", reportModel.LivecommentID); err != nil {
return LivecommentReport{}, err
}
livecomment, err := fillLivecommentResponse(ctx, tx, livecommentModel)
if err != nil {
return LivecommentReport{}, err
}
report := LivecommentReport{
ID: reportModel.ID,
Reporter: reporter,
Livecomment: livecomment,
CreatedAt: reportModel.CreatedAt,
}
return report, nil
}