summaryrefslogtreecommitdiff
path: root/main.go
blob: 7d3fc378c038082ad5c587612e86a252fb41ed99 (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
package main

/*
In this file we implement config file and command line arguments parsing.
Task lifecycle management are implemented in recording package.
*/

import (
	"context"
	"fmt"
	"github.com/akamensky/argparse"
	"github.com/keuin/slbr/bilibili"
	"github.com/keuin/slbr/logging"
	"github.com/keuin/slbr/recording"
	"github.com/mitchellh/mapstructure"
	"github.com/samber/mo"
	"github.com/spf13/viper"
	"log"
	"os"
	"os/signal"
	"reflect"
	"sync"
	"syscall"
)

const defaultDiskBufSize = uint64(1024 * 1024) // 1MiB

var globalConfig *GlobalConfig

func getTasks() (tasks []recording.TaskConfig) {
	var err error
	parser := argparse.NewParser(
		"slbr",
		"Record bilibili live streams",
	)
	defer func() {
		if err != nil {
			fmt.Printf("ERROR: %v.\n", err)
			fmt.Print(parser.Usage(""))
			os.Exit(0)
		}
	}()
	configFilePtr := parser.String(
		"c", "config",
		&argparse.Options{
			Required: false,
			Help:     "Specify which configuration file to use. JSON, TOML and YAML are all supported",
		},
	)
	rooms := parser.IntList(
		"s", "room",
		&argparse.Options{
			Required: false,
			Help: "Specify which room to record. " +
				"The ID is included in bilibili live webpage url. " +
				"Set this to run without config file",
		},
	)
	saveToPtr := parser.String(
		"o", "save-to",
		&argparse.Options{
			Required: false,
			Help: "Specify the directory where to save records. " +
				"If not set, process working directory is used",
		},
	)
	diskBufSizePtr := parser.Int(
		"b", "disk-write-buffer",
		&argparse.Options{
			Required: false,
			Help: "Specify disk write buffer size (bytes). " +
				"The real minimum buffer size is determined by OS. " +
				"Setting this to a large value may make stopping take a long time",
			Default: 4194304,
		},
	)

	err = parser.Parse(os.Args)
	if err != nil {
		return
	}

	fromCli := len(*rooms) > 0
	fromFile := *configFilePtr != ""

	if fromCli && fromFile {
		err = fmt.Errorf("cannot specify room id argument and config file at the same time")
		return
	}

	if !fromCli && !fromFile {
		err = fmt.Errorf("no task specified")
		return
	}

	if fromFile {
		configFile := *configFilePtr
		fmt.Printf("Config file: %v\n", configFile)

		viper.SetConfigFile(configFile)

		err = viper.ReadInConfig()
		if err != nil {
			err = fmt.Errorf("cannot open config file \"%v\": %w", configFile, err)
			return
		}

		if err != nil {
			err = fmt.Errorf("cannot read config file \"%v\": %w", configFile, err)
			return
		}
		var gc GlobalConfig
		netType := reflect.TypeOf(bilibili.IP64)
		err = viper.Unmarshal(&gc, func(conf *mapstructure.DecoderConfig) {
			conf.DecodeHook = func(from reflect.Value, to reflect.Value) (interface{}, error) {
				if to.Type() == netType &&
					bilibili.IpNetType(from.String()).GetDialNetString() == "" {
					return nil, fmt.Errorf("invalid IpNetType: %v", from.String())
				}
				return from.Interface(), nil
			}
		})
		if err != nil {
			err = fmt.Errorf("cannot parse config file \"%v\": %w", configFile, err)
			return
		}
		globalConfig = &gc
		return globalConfig.Tasks
	}

	// generate task list from cli
	taskCount := len(*rooms)
	tasks = make([]recording.TaskConfig, taskCount)
	saveTo := mo.EmptyableToOption(*saveToPtr).OrElse(".")
	diskBufSize := uint64(*diskBufSizePtr)
	if *diskBufSizePtr <= 0 {
		diskBufSize = defaultDiskBufSize
	}
	for i := 0; i < taskCount; i++ {
		tasks[i] = recording.TaskConfig{
			RoomId:    bilibili.RoomId((*rooms)[i]),
			Transport: recording.DefaultTransportConfig(),
			Download: recording.DownloadConfig{
				DiskWriteBufferBytes: int64(diskBufSize),
				SaveDirectory:        saveTo,
			},
		}
	}

	return
}

func main() {
	logger := log.Default()
	taskConfigs := getTasks()
	tasks := make([]recording.RunningTask, len(taskConfigs))

	wg := sync.WaitGroup{}
	ctxTasks, cancelTasks := context.WithCancel(context.Background())
	fmt.Println("Record tasks:")
	for i, task := range taskConfigs {
		tasks[i] = recording.NewRunningTask(
			taskConfigs[i],
			ctxTasks,
			func() {},
			func() { wg.Done() },
			logging.NewWrappedLogger(logger, fmt.Sprintf("room %v", task.RoomId)),
		)
		fmt.Printf("[%2d] %s\n", i+1, task)
	}
	fmt.Println("")

	logger.Printf("Starting tasks...")

	for i := range tasks {
		wg.Add(1)
		err := tasks[i].StartTask()
		if err != nil {
			logger.Printf("Cannot start task %v (room %v): %v. Skip.", i, tasks[i].RoomId, err)
			wg.Done()
		}
	}

	// listen on stop signals
	chSigStop := make(chan os.Signal)
	signal.Notify(chSigStop,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM)

	chSigQuit := make(chan os.Signal)
	signal.Notify(chSigQuit, syscall.SIGQUIT)
	go func() {
		select {
		case <-chSigStop:
			logger.Println("Stopping all tasks...")
			cancelTasks()
		case <-chSigQuit:
			logger.Println("Aborted.")
			os.Exit(0)
		}
	}()

	// block main goroutine on task goroutines
	defer func() {
		wg.Wait()
		logger.Println("YABR is stopped.")
	}()
}