/
handler.go
422 lines (393 loc) · 11.1 KB
/
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
package servers
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gorilla/mux"
"github.com/tidwall/gjson"
"gopkg.in/yaml.v2"
"github.com/hr3lxphr6j/bililive-go/src/configs"
"github.com/hr3lxphr6j/bililive-go/src/consts"
"github.com/hr3lxphr6j/bililive-go/src/instance"
"github.com/hr3lxphr6j/bililive-go/src/listeners"
"github.com/hr3lxphr6j/bililive-go/src/live"
"github.com/hr3lxphr6j/bililive-go/src/recorders"
)
// FIXME: remove this
func parseInfo(ctx context.Context, l live.Live) *live.Info {
inst := instance.GetInstance(ctx)
obj, _ := inst.Cache.Get(l)
info := obj.(*live.Info)
info.Listening = inst.ListenerManager.(listeners.Manager).HasListener(ctx, l.GetLiveId())
info.Recording = inst.RecorderManager.(recorders.Manager).HasRecorder(ctx, l.GetLiveId())
return info
}
func getAllLives(writer http.ResponseWriter, r *http.Request) {
inst := instance.GetInstance(r.Context())
lives := liveSlice(make([]*live.Info, 0, 4))
for _, v := range inst.Lives {
lives = append(lives, parseInfo(r.Context(), v))
}
sort.Sort(lives)
writeJSON(writer, lives)
}
func getLive(writer http.ResponseWriter, r *http.Request) {
inst := instance.GetInstance(r.Context())
vars := mux.Vars(r)
live, ok := inst.Lives[live.ID(vars["id"])]
if !ok {
writeJsonWithStatusCode(writer, http.StatusNotFound, commonResp{
ErrNo: http.StatusNotFound,
ErrMsg: fmt.Sprintf("live id: %s can not find", vars["id"]),
})
return
}
writeJSON(writer, parseInfo(r.Context(), live))
}
func parseLiveAction(writer http.ResponseWriter, r *http.Request) {
inst := instance.GetInstance(r.Context())
vars := mux.Vars(r)
resp := commonResp{}
live, ok := inst.Lives[live.ID(vars["id"])]
if !ok {
resp.ErrNo = http.StatusNotFound
resp.ErrMsg = fmt.Sprintf("live id: %s can not find", vars["id"])
writeJsonWithStatusCode(writer, http.StatusNotFound, resp)
return
}
room, err := inst.Config.GetLiveRoomByUrl(live.GetRawUrl())
if err != nil {
resp.ErrNo = http.StatusNotFound
resp.ErrMsg = fmt.Sprintf("room : %s can not find", live.GetRawUrl())
writeJsonWithStatusCode(writer, http.StatusNotFound, resp)
return
}
switch vars["action"] {
case "start":
if err := startListening(r.Context(), live); err != nil {
resp.ErrNo = http.StatusBadRequest
resp.ErrMsg = err.Error()
writeJsonWithStatusCode(writer, http.StatusBadRequest, resp)
return
} else {
room.IsListening = true
}
case "stop":
if err := stopListening(r.Context(), live.GetLiveId()); err != nil {
resp.ErrNo = http.StatusBadRequest
resp.ErrMsg = err.Error()
writeJsonWithStatusCode(writer, http.StatusBadRequest, resp)
return
} else {
room.IsListening = false
}
default:
resp.ErrNo = http.StatusBadRequest
resp.ErrMsg = fmt.Sprintf("invalid Action: %s", vars["action"])
writeJsonWithStatusCode(writer, http.StatusBadRequest, resp)
return
}
writeJSON(writer, parseInfo(r.Context(), live))
}
func startListening(ctx context.Context, live live.Live) error {
inst := instance.GetInstance(ctx)
return inst.ListenerManager.(listeners.Manager).AddListener(ctx, live)
}
func stopListening(ctx context.Context, liveId live.ID) error {
inst := instance.GetInstance(ctx)
return inst.ListenerManager.(listeners.Manager).RemoveListener(ctx, liveId)
}
/*
Post data example
[
{
"url": "http://live.bilibili.com/1030",
"listen": true
},
{
"url": "https://live.bilibili.com/493",
"listen": true
}
]
*/
func addLives(writer http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
writeJSON(writer, map[string]interface{}{
"error": err.Error(),
})
return
}
inst := instance.GetInstance(r.Context())
info := liveSlice(make([]*live.Info, 0))
errorMessages := make([]string, 0, 4)
gjson.ParseBytes(b).ForEach(func(key, value gjson.Result) bool {
isListen := value.Get("listen").Bool()
urlStr := strings.Trim(value.Get("url").String(), " ")
if retInfo, err := addLiveImpl(r.Context(), urlStr, isListen); err != nil {
msg := urlStr + ": " + err.Error()
inst.Logger.Error(msg)
errorMessages = append(errorMessages, msg)
return true
} else {
info = append(info, retInfo)
}
return true
})
sort.Sort(info)
// TODO return error messages too
writeJSON(writer, info)
}
func addLiveImpl(ctx context.Context, urlStr string, isListen bool) (info *live.Info, err error) {
if !strings.HasPrefix(urlStr, "http://") && !strings.HasPrefix(urlStr, "https://") {
urlStr = "https://" + urlStr
}
u, err := url.Parse(urlStr)
if err != nil {
return nil, errors.New("can't parse url: " + urlStr)
}
inst := instance.GetInstance(ctx)
opts := make([]live.Option, 0)
if v, ok := inst.Config.Cookies[u.Host]; ok {
opts = append(opts, live.WithKVStringCookies(u, v))
}
newLive, err := live.New(u, inst.Cache, opts...)
if err != nil {
return nil, err
}
if _, ok := inst.Lives[newLive.GetLiveId()]; !ok {
inst.Lives[newLive.GetLiveId()] = newLive
if isListen {
inst.ListenerManager.(listeners.Manager).AddListener(ctx, newLive)
}
info = parseInfo(ctx, newLive)
liveRoom := configs.LiveRoom{
Url: u.String(),
IsListening: isListen,
LiveId: newLive.GetLiveId(),
}
inst.Config.LiveRooms = append(inst.Config.LiveRooms, liveRoom)
}
return info, nil
}
func removeLive(writer http.ResponseWriter, r *http.Request) {
inst := instance.GetInstance(r.Context())
vars := mux.Vars(r)
live, ok := inst.Lives[live.ID(vars["id"])]
if !ok {
writeJsonWithStatusCode(writer, http.StatusNotFound, commonResp{
ErrNo: http.StatusNotFound,
ErrMsg: fmt.Sprintf("live id: %s can not find", vars["id"]),
})
return
}
if err := removeLiveImpl(r.Context(), live); err != nil {
writeJsonWithStatusCode(writer, http.StatusBadRequest, commonResp{
ErrNo: http.StatusBadRequest,
ErrMsg: err.Error(),
})
return
}
writeJSON(writer, commonResp{
Data: "OK",
})
}
func removeLiveImpl(ctx context.Context, live live.Live) error {
inst := instance.GetInstance(ctx)
lm := inst.ListenerManager.(listeners.Manager)
if lm.HasListener(ctx, live.GetLiveId()) {
if err := lm.RemoveListener(ctx, live.GetLiveId()); err != nil {
return err
}
}
delete(inst.Lives, live.GetLiveId())
inst.Config.RemoveLiveRoomByUrl(live.GetRawUrl())
return nil
}
func getConfig(writer http.ResponseWriter, r *http.Request) {
writeJSON(writer, instance.GetInstance(r.Context()).Config)
}
func putConfig(writer http.ResponseWriter, r *http.Request) {
config := instance.GetInstance(r.Context()).Config
config.RefreshLiveRoomIndexCache()
if err := config.Marshal(); err != nil {
writeJsonWithStatusCode(writer, http.StatusBadRequest, commonResp{
ErrNo: http.StatusBadRequest,
ErrMsg: err.Error(),
})
return
}
writeJsonWithStatusCode(writer, http.StatusOK, commonResp{
Data: "OK",
})
}
func getRawConfig(writer http.ResponseWriter, r *http.Request) {
b, err := yaml.Marshal(instance.GetInstance(r.Context()).Config)
if err != nil {
writeJsonWithStatusCode(writer, http.StatusInternalServerError, commonResp{
ErrNo: http.StatusBadRequest,
ErrMsg: err.Error(),
})
return
}
writeJSON(writer, map[string]string{
"config": string(b),
})
}
func putRawConfig(writer http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
writeJsonWithStatusCode(writer, http.StatusBadRequest, commonResp{
ErrNo: http.StatusBadRequest,
ErrMsg: err.Error(),
})
return
}
ctx := r.Context()
inst := instance.GetInstance(ctx)
var jsonBody map[string]interface{}
json.Unmarshal(b, &jsonBody)
configPath, err := inst.Config.GetFilePath()
if err != nil {
writeJsonWithStatusCode(writer, http.StatusInternalServerError, commonResp{
ErrNo: http.StatusInternalServerError,
ErrMsg: err.Error(),
})
return
}
newConfig, err := configs.NewConfigWithBytes([]byte(jsonBody["config"].(string)))
if err != nil {
writeJsonWithStatusCode(writer, http.StatusInternalServerError, commonResp{
ErrNo: http.StatusInternalServerError,
ErrMsg: err.Error(),
})
return
}
oldConfig := inst.Config
newConfig.File = oldConfig.File
if err := applyLiveRoomsByConfig(ctx, newConfig.LiveRooms); err != nil {
writeJSON(writer, map[string]interface{}{
"error": err.Error(),
})
return
}
newConfig.LiveRooms = oldConfig.LiveRooms
ioutil.WriteFile(configPath, []byte(jsonBody["config"].(string)), os.ModePerm)
inst.Config = newConfig
newConfig.RefreshLiveRoomIndexCache()
writeJSON(writer, commonResp{
Data: "OK",
})
}
func applyLiveRoomsByConfig(ctx context.Context, newLiveRooms []configs.LiveRoom) error {
inst := instance.GetInstance(ctx)
currentConfig := inst.Config
currentConfig.RefreshLiveRoomIndexCache()
newUrlMap := make(map[string]*configs.LiveRoom)
for _, newRoom := range newLiveRooms {
newUrlMap[newRoom.Url] = &newRoom
if room, err := currentConfig.GetLiveRoomByUrl(newRoom.Url); err != nil {
// add live
if _, err := addLiveImpl(ctx, newRoom.Url, newRoom.IsListening); err != nil {
return err
}
} else {
live, ok := inst.Lives[live.ID(room.LiveId)]
if !ok {
return errors.New(fmt.Sprintf("live id: %s can not find", room.LiveId))
}
if room.IsListening != newRoom.IsListening {
if newRoom.IsListening {
// start listening
if err := startListening(ctx, live); err != nil {
return err
}
} else {
// stop listening
if err := stopListening(ctx, live.GetLiveId()); err != nil {
return err
}
}
room.IsListening = newRoom.IsListening
}
}
}
loopRooms := currentConfig.LiveRooms
for _, room := range loopRooms {
if _, ok := newUrlMap[room.Url]; !ok {
// remove live
live, ok := inst.Lives[live.ID(room.LiveId)]
if !ok {
return errors.New(fmt.Sprintf("live id: %s can not find", room.LiveId))
}
removeLiveImpl(ctx, live)
}
}
return nil
}
func getInfo(writer http.ResponseWriter, r *http.Request) {
writeJSON(writer, consts.AppInfo)
}
func getFileInfo(writer http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
path := vars["path"]
inst := instance.GetInstance(r.Context())
base, err := filepath.Abs(inst.Config.OutPutPath)
if err != nil {
writeJSON(writer, commonResp{
ErrMsg: "无效输出目录",
})
return
}
absPath, err := filepath.Abs(filepath.Join(base, path))
if err != nil {
writeJSON(writer, commonResp{
ErrMsg: "无效路径",
})
return
}
if !strings.HasPrefix(absPath, base) {
writeJSON(writer, commonResp{
ErrMsg: "异常路径",
})
return
}
files, err := ioutil.ReadDir(absPath)
if err != nil {
writeJSON(writer, commonResp{
ErrMsg: "获取目录失败",
})
return
}
type jsonFile struct {
IsFolder bool `json:"is_folder"`
Name string `json:"name"`
LastModified int64 `json:"last_modified"`
Size int64 `json:"size"`
}
jsonFiles := make([]jsonFile, len(files))
json := struct {
Files []jsonFile `json:"files"`
Path string `json:"path`
}{
Path: path,
}
for i, file := range files {
jsonFiles[i].IsFolder = file.IsDir()
jsonFiles[i].Name = file.Name()
jsonFiles[i].LastModified = file.ModTime().Unix()
if !file.IsDir() {
jsonFiles[i].Size = file.Size()
}
}
json.Files = jsonFiles
writeJSON(writer, json)
}