-
Notifications
You must be signed in to change notification settings - Fork 41
/
progress.go
259 lines (234 loc) · 7.02 KB
/
progress.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
package api
import (
"errors"
"math"
"net/http"
"slices"
"strconv"
"sync"
"time"
"github.com/TUM-Dev/gocast/dao"
"github.com/TUM-Dev/gocast/model"
"github.com/TUM-Dev/gocast/tools"
"gorm.io/gorm"
"github.com/gin-gonic/gin"
)
var progressBuff *progressBuffer
// progressBuffer contains progresses to be written to the database
type progressBuffer struct {
lock sync.Mutex
progresses []model.StreamProgress
interval time.Duration
}
func newProgressBuffer() *progressBuffer {
return &progressBuffer{
lock: sync.Mutex{},
progresses: []model.StreamProgress{},
interval: time.Second * 5,
}
}
// add new progress to the list to be flushed eventually
func (b *progressBuffer) add(progress model.StreamProgress) {
b.lock.Lock()
defer b.lock.Unlock()
b.progresses = append(b.progresses, progress)
}
// flush writes the collected progresses to the database
func (b *progressBuffer) flush() error {
b.lock.Lock()
defer b.lock.Unlock()
if len(b.progresses) == 0 {
return nil
}
err := dao.Progress.SaveProgresses(b.progresses)
b.progresses = []model.StreamProgress{}
return err
}
// run flushes the progress buffer every interval
func (b *progressBuffer) run() {
for {
time.Sleep(b.interval)
err := b.flush()
if err != nil {
logger.Error("Error flushing progress buffer", "err", err)
}
}
}
// configProgressRouter sets up the router and initializes a progress buffer
// that is used to minimize writes to the database.
func configProgressRouter(router *gin.Engine, daoWrapper dao.DaoWrapper) {
routes := progressRoutes{daoWrapper}
progressBuff = newProgressBuffer()
go progressBuff.run()
router.POST("/api/progressReport", routes.saveProgress)
router.POST("/api/watched", routes.markWatched)
router.GET("/api/progress/streams", routes.getProgressBatch)
}
// progressRoutes contains a DaoWrapper object and all route functions dangle from it.
type progressRoutes struct {
dao.DaoWrapper
}
// progressRequest corresponds the request that is sent by the video player when it reports its progress for VODs
type progressRequest struct {
StreamID uint `json:"streamID"`
Progress float64 `json:"progress"` // A fraction that represents currentTime / totalTime for a given video
// Note: To be able to save the progress, we also need the userID, but it`s already contained in the Gin context
}
// saveProgress saves progress to a buffer that is flushed at a fixed interval.
func (r progressRoutes) saveProgress(c *gin.Context) {
var request progressRequest
err := c.BindJSON(&request)
if err != nil {
logger.Warn("Could not bind JSON.", "err", err)
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "can not bind body",
Err: err,
})
return
}
foundContext, exists := c.Get("TUMLiveContext")
if !exists {
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "context should exist but doesn't",
})
return
}
tumLiveContext := foundContext.(tools.TUMLiveContext)
if tumLiveContext.User == nil {
_ = c.Error(tools.RequestError{
Status: http.StatusForbidden,
CustomMessage: "not logged in",
})
return
}
stream, err := r.DaoWrapper.StreamsDao.GetStreamByID(c, strconv.FormatUint(uint64(request.StreamID), 10))
if err != nil {
return
}
watchedToLastSilence := false
// logger.Debug("Save progress")
duration := stream.Duration.Int32
if duration == 0 {
dur := stream.End.Sub(stream.Start)
duration += int32(dur.Seconds()) + int32(dur.Minutes())*60 + int32(dur.Minutes())*60*60
}
// logger.Debug("Duration", "duration", duration)
if duration != 0 && len(stream.Silences) > 0 {
lastSilence := slices.MaxFunc(stream.Silences, func(silence model.Silence, other model.Silence) int {
return int(silence.End) - int(other.End)
})
// Add a little wiggle time to the end if ffmpeg didn't detect the silence till the end
if math.Abs(float64(lastSilence.End-uint(duration))) < 10 {
lastSilencePercent := float64(lastSilence.Start) / float64(duration)
if request.Progress >= lastSilencePercent {
watchedToLastSilence = true
}
}
}
progressBuff.add(model.StreamProgress{
Progress: request.Progress,
StreamID: request.StreamID,
UserID: tumLiveContext.User.ID,
Watched: request.Progress > .9 || watchedToLastSilence,
})
}
// watchedRequest corresponds the request that is sent when a user marked the video as watched on the watch page.
type watchedRequest struct {
StreamID uint `json:"streamID"`
Watched bool `json:"watched"`
}
// markWatched marks a VoD as watched in the database.
func (r progressRoutes) markWatched(c *gin.Context) {
var request watchedRequest
err := c.BindJSON(&request)
if err != nil {
logger.Error("Could not bind JSON.", "err", err)
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "can not bind body",
Err: err,
})
return
}
foundContext, exists := c.Get("TUMLiveContext")
if !exists {
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "context should exist but doesn't",
})
return
}
tumLiveContext := foundContext.(tools.TUMLiveContext)
if tumLiveContext.User == nil {
_ = c.Error(tools.RequestError{
Status: http.StatusForbidden,
CustomMessage: "not logged in",
})
return
}
prog := model.StreamProgress{
UserID: tumLiveContext.User.ID,
StreamID: request.StreamID,
Watched: request.Watched,
}
err = r.ProgressDao.SaveWatchedState(&prog)
if err != nil {
logger.Error("can not mark VoD as watched.", "err", err)
_ = c.Error(tools.RequestError{
Status: http.StatusInternalServerError,
CustomMessage: "can not mark VoD as watched.",
Err: err,
})
return
}
}
func (r progressRoutes) getProgressBatch(c *gin.Context) {
tumLiveContext := c.MustGet("TUMLiveContext").(tools.TUMLiveContext)
if tumLiveContext.User == nil {
_ = c.Error(tools.RequestError{
Status: http.StatusForbidden,
CustomMessage: "Not logged-in",
})
return
}
var stringIds []string
var ok bool
if stringIds, ok = c.GetQueryArray("[]ids"); !ok {
_ = c.Error(tools.RequestError{
Status: http.StatusBadRequest,
CustomMessage: "invalid query 'ids'",
})
return
}
ids := make([]uint, 0, len(stringIds))
for _, stringId := range stringIds {
id, err := strconv.Atoi(stringId)
if err != nil {
continue
}
ids = append(ids, uint(id))
}
progressResults := make([]model.StreamProgress, len(ids))
streamProgresses, err := r.LoadProgress(tumLiveContext.User.ID, ids)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
_ = c.Error(tools.RequestError{
Status: http.StatusInternalServerError,
CustomMessage: "can not load progress",
Err: err,
})
return
}
for i, id := range ids {
progressResults[i] = model.StreamProgress{StreamID: id}
for _, progress := range streamProgresses {
if progress.StreamID == id {
progressResults[i].Progress = progress.Progress
progressResults[i].Watched = progress.Watched
break
}
}
}
c.JSON(http.StatusOK, progressResults)
}