summaryrefslogtreecommitdiff
path: root/recording/runner.go
blob: 98d443234dbf97d9d47fa52a0b84f087229d0920 (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
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
/*
This file contains task runner.
Task runner composes status monitor and stream downloader   concrete task config.
The config can be load from a config file.
*/
package recording

import (
	"bilibili-livestream-archiver/bilibili"
	"bilibili-livestream-archiver/common"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"path"
	"time"
)

// TaskResult represents an execution result of a task.
type TaskResult struct {
	Task  *TaskConfig
	Error error
}

const kReadChunkSize = 128 * 1024

// runTaskWithAutoRestart
// start a monitor&download task.
// The task will be restarted infinitely until the context is closed,
// which means it will survive when the live is ended. (It always waits for the next start)
// During the process, its status may change.
// Note: this method is blocking.
func (t *RunningTask) runTaskWithAutoRestart() error {
	for {
		t.status = StRunning
		err := tryRunTask(t)
		if errors.Is(err, bilibili.ErrRoomIsClosed) {
			t.status = StRestarting
			t.logger.Info("Restarting task...")
			continue
		} else if err != nil && !errors.Is(err, context.Canceled) {
			t.logger.Error("Task stopped with an error: %v", err)
			return fmt.Errorf("task stopped: %v", err)
		} else {
			t.logger.Info("Task stopped: %v", t.String())
			return nil
		}
	}
}

// tryRunTask does the actual work. It will return when in the following cases:
//   - the task context is cancelled
//   - the task is restarting (e.g. because of the end of live)
//   - some unrecoverable error happens (e.g. a protocol error caused by a bilibili protocol update)
func tryRunTask(t *RunningTask) error {
	netTypes := t.Transport.AllowedNetworkTypes
	t.logger.Info("Network types: %v", netTypes)
	bi := bilibili.NewBilibiliWithNetType(netTypes)
	t.logger.Info("Start task: room %v", t.RoomId)

	t.logger.Info("Getting notification server info...")
	authKey, dmUrl, err := getDanmakuServer(&t.TaskConfig, bi)
	if err != nil {
		return err
	}
	t.logger.Info("Success.")

	// run live status watcher asynchronously
	t.logger.Info("Starting watcher...")
	chWatcherEvent := make(chan WatcherEvent)
	chWatcherDown := make(chan struct{})

	// start and recover watcher asynchronously
	// the watcher may also be stopped by the downloader goroutine
	watcherCtx, stopWatcher := context.WithCancel(t.ctx)
	defer stopWatcher()
	go watcherRecoverableLoop(
		watcherCtx,
		dmUrl,
		authKey,
		t,
		bi,
		chWatcherEvent,
		chWatcherDown,
	)

	// The stream download goroutine may fail due to wrong watcher state.
	// But this is likely temporarily, so we should restart the downloader
	// until the state turns to closed.

	recorderCtx, stopRecorder := context.WithCancel(t.ctx)
	defer stopRecorder()
	for {
		select {
		case <-t.ctx.Done():
			t.logger.Info("Task is stopped.")
			return nil
		case <-chWatcherDown:
			// watcher is down and unrecoverable, stop this task
			return fmt.Errorf("task (room %v) stopped: watcher is down and unrecoverable", t.RoomId)
		case ev := <-chWatcherEvent:
			switch ev {
			case WatcherLiveStart:
				cancelled := false
				var err2 error
				// restart recorder if interrupted by I/O errors
				for !cancelled {
					cancelled, err2 = record(recorderCtx, bi, t)
					// live is closed normally, do not restart in current function
					// the watcher will wait for the next start
					if errors.Is(err2, bilibili.ErrRoomIsClosed) {
						t.logger.Info("Live is ended. Stop recording.")
						return bilibili.ErrRoomIsClosed
					}
					if err2 != nil {
						// some other unrecoverable error
						return err2
					}
				}
				t.logger.Info("Task is cancelled. Stop recording.")
			case WatcherLiveStop:
				// once the live is ended, the watcher will no longer receive live start event
				// we have to restart the watcher
				return bilibili.ErrRoomIsClosed
			}
		}
	}
}

// record. When cancelled, the caller should clean up immediately and stop the task.
func record(
	ctx context.Context,
	bi bilibili.Bilibili,
	task *RunningTask,
) (cancelled bool, err error) {
	logger := log.Default()
	logger.Printf("INFO: Getting room profile...")

	profile, err := common.AutoRetry(
		ctx,
		func() (bilibili.RoomProfileResponse, error) {
			return bi.GetRoomProfile(task.RoomId)
		},
		task.Transport.MaxRetryTimes,
		time.Duration(task.Transport.RetryIntervalSeconds)*time.Second,
		logger,
	)
	if errors.Is(err, context.Canceled) {
		cancelled = true
		return
	}
	if err != nil {
		// still error, abort
		logger.Printf("ERROR: Cannot get room information: %v. Stopping current task.", err)
		cancelled = true
		return
	}

	logger.Printf("INFO: Getting stream url...")
	urlInfo, err := common.AutoRetry(
		ctx,
		func() (bilibili.RoomUrlInfoResponse, error) {
			return bi.GetStreamingInfo(task.RoomId)
		},
		task.Transport.MaxRetryTimes,
		time.Duration(task.Transport.RetryIntervalSeconds)*time.Second,
		logger,
	)
	if errors.Is(err, context.Canceled) {
		cancelled = true
		return
	}
	if err != nil {
		logger.Printf("ERROR: Cannot get streaming info: %v", err)
		cancelled = true
		return
	}
	if len(urlInfo.Data.URLs) == 0 {
		j, err2 := json.Marshal(urlInfo)
		if err2 != nil {
			j = []byte("(not available)")
		}
		logger.Printf("ERROR: No stream returned from API. Response: %v", string(j))
		cancelled = true
		return
	}
	streamSource := urlInfo.Data.URLs[0]

	fileName := fmt.Sprintf(
		"%s.%s",
		GenerateFileName(profile.Data.Title, time.Now()),
		common.Errorable[string](common.GetFileExtensionFromUrl(streamSource.URL)).OrElse("flv"),
	)
	filePath := path.Join(task.Download.SaveDirectory, fileName)
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		logger.Printf("ERROR: Cannot open file for writing: %v", err)
		cancelled = true
		return
	}
	defer func() { _ = file.Close() }()

	writeBufferSize := task.Download.DiskWriteBufferBytes
	if writeBufferSize < kReadChunkSize {
		writeBufferSize = kReadChunkSize
	}
	if mod := writeBufferSize % kReadChunkSize; mod != 0 {
		writeBufferSize += kReadChunkSize - mod
	}
	writeBuffer := make([]byte, writeBufferSize)
	logger.Printf("Write buffer size: %v byte", writeBufferSize)
	logger.Printf("Recording live stream to file \"%v\"...", filePath)
	err = bi.CopyLiveStream(ctx, task.RoomId, streamSource, file, writeBuffer, kReadChunkSize)
	cancelled = err == nil || errors.Is(err, context.Canceled)
	if !cancelled {
		// real error happens
		logger.Printf("Error when copying live stream: %v", err)
	}
	return
}

// watcherRecoverableLoop run watcher forever until the context is cancelled.
func watcherRecoverableLoop(
	ctx context.Context,
	url string,
	authKey string,
	task *RunningTask,
	bi bilibili.Bilibili,
	chWatcherEvent chan<- WatcherEvent,
	chWatcherDown chan<- struct{},
) {
	for {
		err, errReason := watch(
			ctx,
			url,
			authKey,
			task.RoomId,
			func() (bool, error) {
				resp, err := bi.GetRoomPlayInfo(task.RoomId)
				if err != nil {
					return false, err
				}
				if resp.Code != 0 {
					return false, fmt.Errorf("bilibili API error: %v", resp.Message)
				}
				return resp.Data.LiveStatus.IsStreaming(), nil
			},
			chWatcherEvent,
		)

		// the context is cancelled, stop watching
		if errors.Is(err, context.Canceled) {
			return
		}

		switch errReason {
		case ErrSuccess:
			// stop normally, the context is closed
			return
		case ErrProtocol:
			task.logger.Fatal("Watcher stopped due to an unrecoverable error: %v", err)
			// shutdown the whole task
			chWatcherDown <- struct{}{}
			return
		case ErrTransport:
			task.logger.Error("ERROR: Watcher stopped due to an I/O error: %v", err)
			waitSeconds := task.Transport.RetryIntervalSeconds
			task.logger.Warning(
				"WARNING: Sleep for %v second(s) before restarting watcher.\n",
				waitSeconds,
			)
			time.Sleep(time.Duration(waitSeconds) * time.Second)
			task.logger.Info("Retrying...")
		}
	}
}

func getDanmakuServer(
	task *TaskConfig,
	bi bilibili.Bilibili,
) (string, string, error) {
	dmInfo, err := bi.GetDanmakuServerInfo(task.RoomId)
	if err != nil {
		return "", "", fmt.Errorf("failed to read stream server info: %w", err)
	}
	if len(dmInfo.Data.HostList) == 0 {
		return "", "", fmt.Errorf("no available stream server")
	}

	// get authkey and ws url
	authKey := dmInfo.Data.Token
	host := dmInfo.Data.HostList[0]
	url := fmt.Sprintf("wss://%s:%d/sub", host.Host, host.WssPort)
	return authKey, url, nil
}

func GenerateFileName(roomName string, t time.Time) string {
	ts := fmt.Sprintf(
		"%d-%02d-%02d-%02d-%02d-%02d",
		t.Year(),
		t.Month(),
		t.Day(),
		t.Hour(),
		t.Minute(),
		t.Second(),
	)
	return fmt.Sprintf("%s_%s", roomName, ts)
}