summaryrefslogtreecommitdiff
path: root/recording/runner.go
blob: 487cab8f140d43ff12c1ad469ee3bca9c1f81d56 (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
/*
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"
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"path"
	"sync"
	"time"
)

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

// RunTask start a monitor&download task and
// put its execution result into a channel.
func RunTask(ctx context.Context, wg *sync.WaitGroup, task *TaskConfig) {
	defer wg.Done()
	err := doTask(ctx, task)
	logger := log.Default()
	if err != nil && !errors.Is(err, context.Canceled) {
		logger.Printf("A task stopped with an error (room %v): %v\n", task.RoomId, err)
	} else {
		logger.Printf("Task stopped (room %v): %v\n", task.RoomId, task.String())
	}
}

// doTask do the actual work, but returns synchronously.
func doTask(ctx context.Context, task *TaskConfig) error {
	logger := log.Default()
	bi := bilibili.NewBilibili()
	logger.Printf("Start task: room %v\n", task.RoomId)

	authKey, url, err := getStreamingServer(task, logger, bi)
	if err != nil {
		return err
	}

	// run live status watcher asynchronously
	logger.Println("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(ctx)
	defer stopWatcher()
	go watcherRecoverableLoop(watcherCtx, url, authKey, task, 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.

	// We store the last modified live status
	// in case there is a false-positive duplicate.
	lastStatusIsLiving := false
	recorderCtx, stopRecorder := context.WithCancel(ctx)
	defer stopRecorder()
	for {
		select {
		case <-ctx.Done():
			logger.Printf("Task (room %v) is stopped.\n", task.RoomId)
			return nil
		case <-chWatcherDown:
			// watcher is down and unrecoverable, stop this task
			return fmt.Errorf("task (room %v) stopped: watcher is down and unrecoverable", task.RoomId)
		case ev := <-chWatcherEvent:
			switch ev {
			case WatcherLiveStart:
				if lastStatusIsLiving {
					logger.Println("Duplicate adjacent WatcherLiveStart event. Ignoring.")
					continue
				}
				go func() {
					cancelled := false
					var err2 error
					// restart recorder if interrupted by I/O errors
					for !cancelled {
						cancelled, err2 = record(recorderCtx, bi, task)
						if err2 == bilibili.ErrRoomIsClosed {
							sec := task.Watch.LiveInterruptedRestartSleepSeconds
							if sec == 0 {
								// default: 3s
								// TODO move this to default config value (not easily supported by viper)
								time.Sleep(3 * time.Second)
							}
							if sec > 0 {
								logger.Printf("Sleep for %vs before restart recording.\n", sec)
								time.Sleep(time.Duration(sec) * time.Second)
							}
						}
					}
					logger.Printf("Task is cancelled. Stop recording. (room %v)\n", task.RoomId)
				}()
				lastStatusIsLiving = true
			case WatcherLiveStop:
				lastStatusIsLiving = false
			}
		}
	}
}

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

	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.\n", err)
		cancelled = true
		return
	}

	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() }()

	// buffered writer
	fWriter := bufio.NewWriterSize(file, task.Download.DiskWriteBufferBytes)
	defer func() {
		err := fWriter.Flush()
		if err != nil {
			logger := log.Default()
			logger.Printf("Failed to flush buffered file write data: %v\n", err)
		}
	}()
	logger.Printf("Write buffer size: %v byte\n", fWriter.Size())

	logger.Printf("Recording live stream to file \"%v\"...", filePath)
	err = bi.CopyLiveStream(ctx, task.RoomId, streamSource, fWriter)
	cancelled = err == nil || errors.Is(err, context.Canceled)
	if !cancelled {
		// real error happens
		logger.Printf("Error when copying live stream: %v\n", err)
	}
	return
}

// watcherRecoverableLoop run watcher forever until the context is cancelled.
func watcherRecoverableLoop(
	ctx context.Context,
	url string,
	authKey string,
	task *TaskConfig,
	bi bilibili.Bilibili,
	chWatcherEvent chan WatcherEvent,
	chWatcherDown chan<- struct{},
) {
	logger := log.Default()

	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:
			logger.Printf("FATAL: Watcher stopped due to an unrecoverable error: %v\n", err)
			// shutdown the whole task
			chWatcherDown <- struct{}{}
			return
		case ErrTransport:
			logger.Printf("ERROR: Watcher stopped due to an I/O error: %v\n", err)
			waitSeconds := task.Transport.RetryIntervalSeconds
			logger.Printf(
				"WARNING: Sleep for %v second(s) before restarting watcher.\n",
				waitSeconds,
			)
			time.Sleep(time.Duration(waitSeconds) * time.Second)
			logger.Printf("Retrying...")
		}
	}
}

func getStreamingServer(
	task *TaskConfig,
	logger *log.Logger,
	bi bilibili.Bilibili,
) (string, string, error) {
	logger.Println("Getting stream server info...")
	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")
	}
	logger.Println("Success.")

	// 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)
}