-
Notifications
You must be signed in to change notification settings - Fork 0
/
livestream_handler.go
531 lines (445 loc) · 18.3 KB
/
livestream_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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
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 ReserveLivestreamRequest struct {
Tags []int64 `json:"tags"`
Title string `json:"title"`
Description string `json:"description"`
PlaylistUrl string `json:"playlist_url"`
ThumbnailUrl string `json:"thumbnail_url"`
StartAt int64 `json:"start_at"`
EndAt int64 `json:"end_at"`
}
type LivestreamViewerModel struct {
UserID int64 `db:"user_id" json:"user_id"`
LivestreamID int64 `db:"livestream_id" json:"livestream_id"`
CreatedAt int64 `db:"created_at" json:"created_at"`
}
type LivestreamModel struct {
ID int64 `db:"id" json:"id"`
UserID int64 `db:"user_id" json:"user_id"`
Title string `db:"title" json:"title"`
Description string `db:"description" json:"description"`
PlaylistUrl string `db:"playlist_url" json:"playlist_url"`
ThumbnailUrl string `db:"thumbnail_url" json:"thumbnail_url"`
StartAt int64 `db:"start_at" json:"start_at"`
EndAt int64 `db:"end_at" json:"end_at"`
}
type Livestream struct {
ID int64 `json:"id"`
Owner User `json:"owner"`
Title string `json:"title"`
Description string `json:"description"`
PlaylistUrl string `json:"playlist_url"`
ThumbnailUrl string `json:"thumbnail_url"`
Tags []Tag `json:"tags"`
StartAt int64 `json:"start_at"`
EndAt int64 `json:"end_at"`
}
type LivestreamTagModel struct {
ID int64 `db:"id" json:"id"`
LivestreamID int64 `db:"livestream_id" json:"livestream_id"`
TagID int64 `db:"tag_id" json:"tag_id"`
}
type ReservationSlotModel struct {
ID int64 `db:"id" json:"id"`
Slot int64 `db:"slot" json:"slot"`
StartAt int64 `db:"start_at" json:"start_at"`
EndAt int64 `db:"end_at" json:"end_at"`
}
func reserveLivestreamHandler(c echo.Context) error {
ctx := c.Request().Context()
defer c.Request().Body.Close()
if err := verifyUserSession(c); err != nil {
// echo.NewHTTPErrorが返っているのでそのまま出力
return err
}
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
var req *ReserveLivestreamRequest
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()
// 2023/11/25 10:00からの1年間の期間内であるかチェック
var (
termStartAt = time.Date(2023, 11, 25, 1, 0, 0, 0, time.UTC)
termEndAt = time.Date(2024, 11, 25, 1, 0, 0, 0, time.UTC)
reserveStartAt = time.Unix(req.StartAt, 0)
reserveEndAt = time.Unix(req.EndAt, 0)
)
if (reserveStartAt.Equal(termEndAt) || reserveStartAt.After(termEndAt)) || (reserveEndAt.Equal(termStartAt) || reserveEndAt.Before(termStartAt)) {
return echo.NewHTTPError(http.StatusBadRequest, "bad reservation time range")
}
// 予約枠をみて、予約が可能か調べる
// NOTE: 並列な予約のoverbooking防止にFOR UPDATEが必要
var slots []*ReservationSlotModel
if err := tx.SelectContext(ctx, &slots, "SELECT * FROM reservation_slots WHERE start_at >= ? AND end_at <= ? FOR UPDATE", req.StartAt, req.EndAt); err != nil {
c.Logger().Warnf("予約枠一覧取得でエラー発生: %+v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get reservation_slots: "+err.Error())
}
for _, slot := range slots {
var count int
if err := tx.GetContext(ctx, &count, "SELECT slot FROM reservation_slots WHERE start_at = ? AND end_at = ?", slot.StartAt, slot.EndAt); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get reservation_slots: "+err.Error())
}
c.Logger().Infof("%d ~ %d予約枠の残数 = %d\n", slot.StartAt, slot.EndAt, slot.Slot)
if count < 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("予約期間 %d ~ %dに対して、予約区間 %d ~ %dが予約できません", termStartAt.Unix(), termEndAt.Unix(), req.StartAt, req.EndAt))
}
}
var (
livestreamModel = &LivestreamModel{
UserID: int64(userID),
Title: req.Title,
Description: req.Description,
PlaylistUrl: req.PlaylistUrl,
ThumbnailUrl: req.ThumbnailUrl,
StartAt: req.StartAt,
EndAt: req.EndAt,
}
)
if _, err := tx.ExecContext(ctx, "UPDATE reservation_slots SET slot = slot - 1 WHERE start_at >= ? AND end_at <= ?", req.StartAt, req.EndAt); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to update reservation_slot: "+err.Error())
}
rs, err := tx.NamedExecContext(ctx, "INSERT INTO livestreams (user_id, title, description, playlist_url, thumbnail_url, start_at, end_at) VALUES(:user_id, :title, :description, :playlist_url, :thumbnail_url, :start_at, :end_at)", livestreamModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert livestream: "+err.Error())
}
livestreamID, err := rs.LastInsertId()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get last inserted livestream id: "+err.Error())
}
livestreamModel.ID = livestreamID
// タグ追加
for _, tagID := range req.Tags {
if _, err := tx.NamedExecContext(ctx, "INSERT INTO livestream_tags (livestream_id, tag_id) VALUES (:livestream_id, :tag_id)", &LivestreamTagModel{
LivestreamID: livestreamID,
TagID: tagID,
}); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert livestream tag: "+err.Error())
}
}
livestream, err := fillLivestreamResponse(ctx, tx, *livestreamModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livestream: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusCreated, livestream)
}
func searchLivestreamsHandler(c echo.Context) error {
ctx := c.Request().Context()
keyTagName := c.QueryParam("tag")
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
var livestreamModels []*LivestreamModel
if c.QueryParam("tag") != "" {
// タグによる取得
var tagIDList []int
if err := tx.SelectContext(ctx, &tagIDList, "SELECT id FROM tags WHERE name = ?", keyTagName); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get tags: "+err.Error())
}
query, params, err := sqlx.In("SELECT * FROM livestream_tags WHERE tag_id IN (?) ORDER BY livestream_id DESC", tagIDList)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to construct IN query: "+err.Error())
}
var keyTaggedLivestreams []*LivestreamTagModel
if err := tx.SelectContext(ctx, &keyTaggedLivestreams, query, params...); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get keyTaggedLivestreams: "+err.Error())
}
for _, keyTaggedLivestream := range keyTaggedLivestreams {
ls := LivestreamModel{}
if err := tx.GetContext(ctx, &ls, "SELECT * FROM livestreams WHERE id = ?", keyTaggedLivestream.LivestreamID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestreams: "+err.Error())
}
livestreamModels = append(livestreamModels, &ls)
}
} else {
// 検索条件なし
query := `SELECT * FROM livestreams ORDER BY id 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)
}
if err := tx.SelectContext(ctx, &livestreamModels, query); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestreams: "+err.Error())
}
}
livestreams := make([]Livestream, len(livestreamModels))
for i := range livestreamModels {
livestream, err := fillLivestreamResponse(ctx, tx, *livestreamModels[i])
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livestream: "+err.Error())
}
livestreams[i] = livestream
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, livestreams)
}
func getMyLivestreamsHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
return err
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
// error already checked
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already checked
userID := sess.Values[defaultUserIDKey].(int64)
var livestreamModels []*LivestreamModel
if err := tx.SelectContext(ctx, &livestreamModels, "SELECT * FROM livestreams WHERE user_id = ?", userID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestreams: "+err.Error())
}
livestreams := make([]Livestream, len(livestreamModels))
for i := range livestreamModels {
livestream, err := fillLivestreamResponse(ctx, tx, *livestreamModels[i])
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livestream: "+err.Error())
}
livestreams[i] = livestream
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, livestreams)
}
func getUserLivestreamsHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
return err
}
username := c.Param("username")
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
var user UserModel
if err := tx.GetContext(ctx, &user, "SELECT * FROM users WHERE name = ?", username); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, "user not found")
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get user: "+err.Error())
}
}
var livestreamModels []*LivestreamModel
if err := tx.SelectContext(ctx, &livestreamModels, "SELECT * FROM livestreams WHERE user_id = ?", user.ID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestreams: "+err.Error())
}
livestreams := make([]Livestream, len(livestreamModels))
for i := range livestreamModels {
livestream, err := fillLivestreamResponse(ctx, tx, *livestreamModels[i])
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livestream: "+err.Error())
}
livestreams[i] = livestream
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, livestreams)
}
// viewerテーブルの廃止
func enterLivestreamHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
// echo.NewHTTPErrorが返っているのでそのまま出力
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 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()
viewer := LivestreamViewerModel{
UserID: int64(userID),
LivestreamID: int64(livestreamID),
CreatedAt: time.Now().Unix(),
}
if _, err := tx.NamedExecContext(ctx, "INSERT INTO livestream_viewers_history (user_id, livestream_id, created_at) VALUES(:user_id, :livestream_id, :created_at)", viewer); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to insert livestream_view_history: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.NoContent(http.StatusOK)
}
func exitLivestreamHandler(c echo.Context) error {
ctx := c.Request().Context()
if err := verifyUserSession(c); err != nil {
// echo.NewHTTPErrorが返っているのでそのまま出力
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()
if _, err := tx.ExecContext(ctx, "DELETE FROM livestream_viewers_history WHERE user_id = ? AND livestream_id = ?", userID, livestreamID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to delete livestream_view_history: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.NoContent(http.StatusOK)
}
func getLivestreamHandler(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")
}
tx, err := dbConn.BeginTxx(ctx, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to begin transaction: "+err.Error())
}
defer tx.Rollback()
livestreamModel := LivestreamModel{}
err = tx.GetContext(ctx, &livestreamModel, "SELECT * FROM livestreams WHERE id = ?", livestreamID)
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, "not found livestream that has the given id")
}
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestream: "+err.Error())
}
livestream, err := fillLivestreamResponse(ctx, tx, livestreamModel)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livestream: "+err.Error())
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, livestream)
}
func getLivecommentReportsHandler(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")
}
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 {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livestream: "+err.Error())
}
// error already check
sess, _ := session.Get(defaultSessionIDKey, c)
// existence already check
userID := sess.Values[defaultUserIDKey].(int64)
if livestreamModel.UserID != userID {
return echo.NewHTTPError(http.StatusForbidden, "can't get other streamer's livecomment reports")
}
var reportModels []*LivecommentReportModel
if err := tx.SelectContext(ctx, &reportModels, "SELECT * FROM livecomment_reports WHERE livestream_id = ?", livestreamID); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get livecomment reports: "+err.Error())
}
reports := make([]LivecommentReport, len(reportModels))
for i := range reportModels {
report, err := fillLivecommentReportResponse(ctx, tx, *reportModels[i])
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to fill livecomment report: "+err.Error())
}
reports[i] = report
}
if err := tx.Commit(); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to commit: "+err.Error())
}
return c.JSON(http.StatusOK, reports)
}
func fillLivestreamResponse(ctx context.Context, tx *sqlx.Tx, livestreamModel LivestreamModel) (Livestream, error) {
ownerModel := UserModel{}
if err := tx.GetContext(ctx, &ownerModel, "SELECT * FROM users WHERE id = ?", livestreamModel.UserID); err != nil {
return Livestream{}, err
}
owner, err := fillUserResponse(ctx, tx, ownerModel)
if err != nil {
return Livestream{}, err
}
var livestreamTagModels []*LivestreamTagModel
if err := tx.SelectContext(ctx, &livestreamTagModels, "SELECT * FROM livestream_tags WHERE livestream_id = ?", livestreamModel.ID); err != nil {
return Livestream{}, err
}
tagIDs := make([]int64, len(livestreamTagModels))
for i := range livestreamTagModels {
tagIDs[i] = livestreamTagModels[i].TagID
}
tags := make([]Tag, 0, len(tagIDs))
if len(tagIDs) > 0 {
query, params, err := sqlx.In("SELECT * FROM tags WHERE id IN (?)", tagIDs)
if err != nil {
return Livestream{}, err
}
if err := tx.SelectContext(ctx, &tags, query, params...); err != nil {
return Livestream{}, err
}
}
livestream := Livestream{
ID: livestreamModel.ID,
Owner: owner,
Title: livestreamModel.Title,
Tags: tags,
Description: livestreamModel.Description,
PlaylistUrl: livestreamModel.PlaylistUrl,
ThumbnailUrl: livestreamModel.ThumbnailUrl,
StartAt: livestreamModel.StartAt,
EndAt: livestreamModel.EndAt,
}
return livestream, nil
}