summaryrefslogtreecommitdiff
path: root/recording/watcher.go
blob: ff9bde14c72264e8a7981d75ea92300b5a0b9ebe (plain)
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
package recording

import (
	"context"
	"encoding/base64"
	"encoding/json"
	errs "github.com/keuin/slbr/bilibili"
	"github.com/keuin/slbr/bilibili/errors"
	"github.com/keuin/slbr/danmaku"
	"github.com/keuin/slbr/danmaku/dmmsg"
	"github.com/keuin/slbr/danmaku/dmpkg"
	"github.com/keuin/slbr/logging"
	"time"
)

type liveCommand string

const (
	CommandLiveStart       = "LIVE"
	CommandStreamPreparing = "PREPARING"
)

type liveInfo struct {
	Command liveCommand            `json:"cmd"`
	Data    map[string]interface{} `json:"data"`
}

const (
	heartBeatInterval = 30 * time.Second
)

// watch monitors live room status by subscribing messages from Bilibili danmaku server,
// which talks to the client via a WebSocket or TCP connection.
// In our implementation, we use WebSocket over SSL/TLS.
// This function will return after the live is started,
// since one connection cannot receive more than one live start event.
// Error types:
// - UnrecoverableError
// - RecoverableError
// - context.Cancelled
func watch(
	ctx context.Context,
	t TaskConfig,
	url string,
	authKey, buvid3 string,
	liveStatusChecker func() (bool, error),
	logger logging.Logger,
	bi *bilibili.Bilibili,
) error {
	var err error

	ws, err := bi.DialWebSocket(ctx, url)
	if err != nil {
		return errs.NewError(errs.DanmakuServerConnection, err)
	}

	dm := danmaku.NewClient(ctx, ws)
	defer func() {
		// this operation may be time-consuming, so run in another goroutine
		go func() {
			_ = dm.Disconnect()
		}()
	}()

	// the danmaku server requires an auth token and room id when connected
	logger.Info("ws connected. Authenticating...")
	err = dm.Authenticate(t.RoomId, authKey, buvid3)
	if err != nil {
		return errs.NewError(errs.InvalidAuthProtocol, err)
	}

	// the danmaku server requires heartbeat messages every 30 seconds
	heartbeat := func() error {
		logger.Debug("Sending heartbeat...")
		err := dm.Heartbeat()
		if err == nil {
			logger.Info("Heartbeat sent OK.")
		} else {
			logger.Error("Failed to send heartbeat: %v", err)
		}
		return err
	}

	// send initial heartbeat immediately
	err = heartbeat()
	if err != nil {
		return errs.NewError(errs.Heartbeat, err)
	}

	// create heartbeat timer
	heartBeatTimer := time.NewTicker(heartBeatInterval)
	defer func() { heartBeatTimer.Stop() }()

	logger.Info("Checking initial live status...")
	isLiving, err := AutoRetryWithConfig[bool](ctx, logger, &t, liveStatusChecker)
	if err != nil {
		return errs.NewError(errs.InitialLiveStatus, err)
	}
	if isLiving {
		logger.Info("The live is already started. Start recording immediately.")
		return nil
	} else {
		logger.Info("The live is not started yet. Waiting...")
	}

	hbCtx, hbCancel := context.WithCancel(ctx)
	defer hbCancel()
	go func() {
		for {
			select {
			case <-heartBeatTimer.C:
				err = heartbeat()
				if err != nil {
					logger.Error("heartbeat failed: %v", err)
				}
			case <-hbCtx.Done():
				logger.Debug("Heartbeat loop is stopped.")
				return
			}
		}
	}()

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
			var msg dmpkg.DanmakuExchange
			msg, err = dm.ReadExchange()
			if err != nil {
				return errs.NewError(errs.DanmakuExchangeRead, err)
			}
			// the exchange may be compressed
			msg, err = msg.Inflate()
			if err != nil {
				return errs.NewError(errs.MessageDecompression, err)
			}

			switch msg.Operation {
			case dmpkg.OpLayer7Data:
				//logger.Printf("server message: op %v, body %v", msg.Operation, string(msg.Body))
				var info liveInfo
				err := json.Unmarshal(msg.Body, &info)
				if err != nil {
					logger.Error("Invalid JSON: \"%v\", exchange: %v", string(msg.Body), msg)
					return errs.NewError(errs.JsonDecode, err)
				}
				switch info.Command {
				case CommandLiveStart:
					return nil
				case CommandStreamPreparing:
					break
				default:
					switch info.Command {
					case "ENTRY_EFFECT":
						fallthrough
					case "ONLINE_RANK_V2":
						fallthrough
					case "ONLINE_RANK_COUNT":
						fallthrough
					case "STOP_LIVE_ROOM_LIST":
						// useless message
						fallthrough
					case "HOT_RANK_CHANGED_V2":
						// useless message
						logger.Info("Ignore message: %v", info.Command)
					case "WATCHED_CHANGE":
						// number of watched people changed
						obj, exists := info.Data["num"]
						if !exists {
							continue
						}
						viewersNum, ok := obj.(float64)
						if !ok {
							logger.Error("Cannot parse watched people number: %v", obj)
							continue
						}
						logger.Info("The number of viewers (room: %v): %v", t.RoomId, viewersNum)
					case "INTERACT_WORD":
						var raw dmmsg.RawInteractWordMessage
						err = json.Unmarshal(msg.Body, &raw)
						if err != nil {
							logger.Error("Cannot parse RawInteractWordMessage JSON: %v", err)
							continue
						}
						logger.Info("Interact word message: user: %v medal: %v",
							raw.Data.UserName, raw.Data.FansMedal.Name)
					case "DANMU_MSG":
						var raw dmmsg.RawDanMuMessage
						err = json.Unmarshal(msg.Body, &raw)
						if err != nil {
							logger.Error("Cannot parse danmaku message as JSON: %v", err)
							continue
						}
						dmm, err := dmmsg.ParseDanmakuMessage(raw)
						if err != nil {
							logger.Error("Cannot parse danmaku message JSON: %v, raw data (base64 encoded): %v",
								err, base64.StdEncoding.EncodeToString(msg.Body))
							continue
						}
						logger.Info("Danmaku: %v", dmm.String())
					default:
						logger.Info("Ignore unhandled server message %v %v %v",
							info.Command, msg.Operation, string(msg.Body))
					}
				}
			default:
				logger.Info("Server message: %v", msg.String())
			}

		}
	}
}