forked from scakemyer/quasar
/
maintenance.go
289 lines (241 loc) · 7.7 KB
/
maintenance.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
package api
import (
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/elgatito/elementum/bittorrent"
"github.com/elgatito/elementum/cache"
"github.com/elgatito/elementum/config"
"github.com/elgatito/elementum/exit"
"github.com/elgatito/elementum/library"
"github.com/gin-gonic/gin"
"github.com/goccy/go-json"
)
var seekCatched = false
// Notification serves callbacks from Kodi
func Notification(s *bittorrent.Service) gin.HandlerFunc {
return func(ctx *gin.Context) {
sender := ctx.Query("sender")
method := ctx.Query("method")
data := ctx.Query("data")
jsonData, jsonErr := base64.StdEncoding.DecodeString(data)
if jsonErr != nil {
// Base64 is not URL safe and, probably, Kodi is not well encoding it,
// so we just take it from URL and decode.
// Hoping "data=" is always in the end of url.
if strings.Contains(ctx.Request.URL.RawQuery, "&data=") {
data = ctx.Request.URL.RawQuery[strings.Index(ctx.Request.URL.RawQuery, "&data=")+6:]
}
jsonData, _ = base64.StdEncoding.DecodeString(data)
}
log.Debugf("Got notification from %s/%s: %s", sender, method, string(jsonData))
if sender != "xbmc" {
return
}
switch method {
case "System.OnQuit":
// Do not send SIGHUP when running as a shared library, because we will kill ourselves
if exit.IsShared {
log.Infof("Sending main closer to shutdown Elementum properly")
exit.Closer.Set()
return
}
case "Playlist.OnAdd":
p := s.GetActivePlayer()
if p == nil || p.Params().VideoDuration == 0 {
return
}
var request struct {
Item struct {
ID int `json:"id"`
Type string `json:"type"`
} `json:"item"`
Position int `json:"position"`
}
request.Position = -1
if err := json.Unmarshal(jsonData, &request); err != nil {
log.Error(err)
return
}
p.Params().KodiPosition = request.Position
case "Player.OnSeek":
seekCatched = true
p := s.GetActivePlayer()
if p == nil || p.Params().VideoDuration == 0 {
return
}
p.Params().Seeked = true
// Run prioritization over Player's torrent
go func() {
// TODO: Do we need to clear deadlines? It can be just few pieces in the waitlist.
// p.GetTorrent().ClearDeadlines()
p.GetTorrent().PrioritizePieces()
}()
case "Player.OnPause":
p := s.GetActivePlayer()
if p == nil || p.Params().VideoDuration == 0 {
return
}
if !p.Params().Paused {
p.Params().Paused = true
}
case "Player.OnPlay":
seekCatched = false
// We should stop torrents, waiting for "next" playback
go s.StopNextFiles()
var p *bittorrent.Player
// Try N times to get active player, maybe it takes more time to find active player
for i := 0; i <= 15; i++ {
p = s.GetActivePlayer()
if p != nil && p.Params().VideoDuration > 0 {
break
}
time.Sleep(300 * time.Millisecond) // Let player get its WatchedTime and VideoDuration
}
if p == nil || p.IsClosed() {
log.Warningf("OnPlay. No active player found")
return
}
go p.InitSubtitles()
// TODO: enable when find a way to provide external audio tracks
// go p.InitAudio()
if p.Params().WasSeeked {
log.Warningf("OnPlay. Player has been seeked already")
return
}
if p.Params().Paused { // Prevent seeking when simply unpausing
p.Params().Paused = false
log.Warningf("OnPlay. Skipping seek for paused player")
return
}
log.Infof("OnPlay. Resume check. Resume: %#v, StoredResume: %#v", p.Params().Resume, p.Params().StoredResume)
p.Params().WasSeeked = true
resumePosition := float64(-1)
if p.Params().ResumePlayback == bittorrent.ResumeNo {
// If we don't need to Seek, then make sure Kodi will start from the beginning and not resume on it's own
resumePosition = 0
} else if p.Params().StoredResume != nil && p.Params().StoredResume.Position > 0 {
resumePosition = p.Params().StoredResume.Position
} else if p.Params().Resume != nil && p.Params().Resume.Position > 0 {
resumePosition = p.Params().Resume.Position
}
if config.Get().PlayResumeBack > 0 {
resumePosition -= float64(config.Get().PlayResumeBack)
if resumePosition < 0 {
resumePosition = 0
}
}
if resumePosition > -1 {
go func(resume float64) {
log.Infof("OnPlay. Seeking to %v", resume)
// Waiting max 9 seconds for having video duration, only then seek is accepted by Kodi.
maxRetry := 30
if resume == 0 {
maxRetry = 3
}
for i := 1; i <= maxRetry; i++ {
if p.IsClosed() {
log.Infof("OnPlay. Seek aborted due to Player close")
return
}
time.Sleep(time.Duration(i*300) * time.Millisecond)
if seekCatched {
log.Infof("OnPlay. Seek completed")
return
} else if p.Params().VideoDuration <= 0 {
log.Infof("OnPlay. Waiting for available duration")
continue
}
log.Infof("OnPlay. Triggering Seek to %v", resume)
p.GetXBMCHost().PlayerSeek(resume)
}
}(resumePosition)
}
case "Player.OnStop":
p := s.GetActivePlayer()
if p == nil || p.Params().VideoDuration <= 1 {
return
}
var stopped struct {
Ended bool `json:"end"`
Item struct {
ID int `json:"id"`
Type string `json:"type"`
} `json:"item"`
}
if err := json.Unmarshal(jsonData, &stopped); err != nil {
log.Error(err)
return
}
progress := p.Params().WatchedProgress
log.Infof("Stopped at %f%%", progress)
case "Playlist.OnClear":
// TODO: Do we need this endpoint?
case "VideoLibrary.OnUpdate":
var request struct {
Item struct {
ID int `json:"id"`
Type string `json:"type"`
} `json:"item"`
Added bool `json:"added"`
Playcount int `json:"playcount"`
}
request.Playcount = -1
if err := json.Unmarshal(jsonData, &request); err != nil {
log.Error(err)
return
}
go func() {
if request.Added {
library.MarkKodiUpdated()
library.MarkKodiAdded()
}
if request.Playcount != -1 {
library.MarkKodiUpdated()
}
if request.Item.Type == movieType {
library.RefreshMovie(request.Item.ID, library.ActionUpdate)
} else if request.Item.Type == showType {
library.RefreshShow(request.Item.ID, library.ActionUpdate)
} else if request.Item.Type == episodeType {
library.RefreshEpisode(request.Item.ID, library.ActionUpdate)
}
}()
case "VideoLibrary.OnRemove":
var item struct {
ID int `json:"id"`
Type string `json:"type"`
}
if err := json.Unmarshal(jsonData, &item); err != nil {
log.Error(err)
return
}
go func() {
// TODO: to implement auto-remove we will need to change ActionSafeDelete to ActionDelete
if item.Type == movieType {
library.RefreshMovie(item.ID, library.ActionSafeDelete)
// Remove local playcount history to allow re-setting watched status
cacheStore := cache.NewDBStore()
cacheStore.Delete(fmt.Sprintf(cache.LibraryWatchedPlaycountKey, "movies"))
} else if item.Type == showType {
library.RefreshShow(item.ID, library.ActionSafeDelete)
// Remove local playcount history to allow re-setting watched status
cacheStore := cache.NewDBStore()
cacheStore.Delete(fmt.Sprintf(cache.LibraryWatchedPlaycountKey, "shows"))
} else if item.Type == episodeType {
library.RefreshEpisode(item.ID, library.ActionSafeDelete)
// Remove local playcount history to allow re-setting watched status
cacheStore := cache.NewDBStore()
cacheStore.Delete(fmt.Sprintf(cache.LibraryWatchedPlaycountKey, "shows"))
}
}()
case "VideoLibrary.OnScanStarted":
go library.MarkKodiRefresh()
case "VideoLibrary.OnScanFinished":
go library.RefreshOnScan()
case "VideoLibrary.OnCleanFinished":
go library.PlanOverallUpdate()
}
}
}