forked from Hakkin/twitchpipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
292 lines (246 loc) · 6.3 KB
/
main.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
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strings"
"time"
"golang.org/x/crypto/ssh/terminal"
"rsc.io/getopt"
)
var stdErr = log.New(os.Stderr, "", 0)
var (
forceOutput bool
usernameURL bool
archiveMode bool
hideConsole bool
groupSelect string
groupList bool
)
func init() {
flag.BoolVar(&forceOutput, "f", false, "Force output to standard output even if TTY is detected")
flag.BoolVar(&usernameURL, "u", false, "Treat USERNAME as a URL")
flag.BoolVar(&archiveMode, "a", false, "Start downloading from the oldest segment rather than the newest")
flag.StringVar(&groupSelect, "g", "best", "Select specified playlist group\n\t\"best\" will select the best available group")
flag.BoolVar(&groupList, "G", false, "List available playlist groups and exit")
getopt.Aliases(
"f", "force-output",
"u", "url",
"a", "archive",
"g", "group",
"G", "list-groups",
)
}
func findBest(playlists []playlistInfo) playlistInfo {
var best playlistInfo
var highBitrate int
for _, p := range playlists {
if p.Group == "chunked" {
return p
}
if p.Bandwidth > highBitrate {
highBitrate = p.Bandwidth
best = p
}
}
return best
}
func printGroups(playlists []playlistInfo) {
columns := []*struct {
title string
length int
content []string
fn func(p playlistInfo) string
}{
{"Group", 0, nil, func(p playlistInfo) string { return p.Group }},
{"Name", 0, nil, func(p playlistInfo) string { return p.Name }},
{"Resolution", 0, nil, func(p playlistInfo) string { return fmt.Sprintf("%dx%d", p.Width, p.Height) }},
{"Bitrate", 0, nil, func(p playlistInfo) string { return fmt.Sprintf("%dk", p.Bandwidth/1024) }},
}
for _, c := range columns {
c.length = len(c.title)
}
for _, p := range playlists {
for _, c := range columns {
content := c.fn(p)
c.content = append(c.content, content)
if len(content) > c.length {
c.length = len(content)
}
}
}
for _, c := range columns {
fmt.Fprint(os.Stderr, c.title)
if c.length-len(c.title) > 0 {
fmt.Fprint(os.Stderr, strings.Repeat(" ", c.length-len(c.title)))
}
fmt.Fprint(os.Stderr, " ")
}
fmt.Fprintln(os.Stderr)
best := findBest(playlists)
for i := range playlists {
for _, c := range columns {
content := c.content[i]
fmt.Fprint(os.Stderr, content)
if c.length-len(content) > 0 {
fmt.Fprint(os.Stderr, strings.Repeat(" ", c.length-len(content)))
}
fmt.Fprint(os.Stderr, " ")
}
if playlists[i].Group == best.Group {
fmt.Fprint(os.Stderr, "(best)")
}
fmt.Fprintln(os.Stderr)
}
}
func printUsage() {
stdErr.Println("Usage: twitchpipe [OPTIONS...] <USERNAME> [COMMAND...]")
stdErr.Println()
stdErr.Println("If COMMAND is specified, it will be executed and stream data will be \nwritten to its standard input.")
stdErr.Println("Otherwise, stream data will be written to standard output.")
stdErr.Println()
stdErr.Println("Options:")
getopt.PrintDefaults()
}
func main() {
getopt.Parse()
if len(flag.Args()) < 1 {
printUsage()
os.Exit(1)
}
if hideConsole {
hideWindow()
}
externalCommand, externalArgs := len(flag.Args()) > 1, len(flag.Args()) > 2
username := flag.Arg(0)
if usernameURL {
u, err := url.Parse(username)
if err != nil {
stdErr.Fatalf("could not parse username as URL: %v\n", err)
}
path := u.Path
path = strings.TrimPrefix(path, "/")
username = strings.Split(path, "/")[0]
}
if username == "" {
printUsage()
os.Exit(1)
}
username = strings.ToLower(username)
if terminal.IsTerminal(int(os.Stdout.Fd())) && !forceOutput && !externalCommand && !groupList {
stdErr.Println("[WARNING] You have not piped the output anywhere.")
stdErr.Println(" Outputting binary data to a terminal can be dangerous.")
stdErr.Println(" To bypass this safety feature, use the '--force-output' option.")
os.Exit(1)
}
client := &http.Client{
Timeout: time.Second * 10,
}
token, err := getAcessToken(client, username)
if err != nil {
stdErr.Printf("could not acquire access token: %v\n", err)
os.Exit(1)
}
playlists, err := getPlaylists(client, username, token)
if err != nil {
stdErr.Printf("could not extract playlist: %v\n", err)
os.Exit(1)
}
if groupList {
printGroups(playlists)
os.Exit(0)
}
var playlistURL string
switch groupSelect {
case "best":
best := findBest(playlists)
playlistURL = best.URL
default:
for _, p := range playlists {
if p.Group == groupSelect {
playlistURL = p.URL
break
}
}
}
if playlistURL == "" {
stdErr.Printf("could not find desired playlist quality")
os.Exit(2)
}
var output io.Writer = os.Stdout
if len(flag.Args()) > 1 {
var args []string
if externalArgs {
args = flag.Args()[2:]
}
cmd := exec.Command(flag.Arg(1), args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if output, err = cmd.StdinPipe(); err != nil {
stdErr.Fatalf("could not acquire external command input: %v\n", err)
}
if err = cmd.Start(); err != nil {
stdErr.Fatalf("could not start external command: %v\n", err)
}
defer cmd.Wait()
}
tsURLs := make(chan string, 2)
done := make(chan error, 1)
go streamTs(client, tsURLs, output, done)
var seenURLs []string
seenURLsIndex := make(map[string]bool)
urls, urlsErr := getURLs(client, playlistURL)
if !archiveMode {
if len(urls) > 1 {
for _, url := range urls[0 : len(urls)-1] {
seenURLsIndex[url] = true
seenURLs = append(seenURLs, url)
}
}
}
for {
select {
case err := <-done:
close(tsURLs)
stdErr.Printf("error while streaming: %v\n", err)
os.Exit(2)
default:
}
if urlsErr != nil {
if urlsErr == errStreamOver {
close(tsURLs)
err := <-done
if err != nil {
stdErr.Printf("stream over with error: %v\n", err)
os.Exit(2)
}
stdErr.Println("stream over")
os.Exit(0)
}
stdErr.Printf("could not get prefetch URLs: %v\n", urlsErr)
}
for _, url := range urls {
if seenURLsIndex[url] {
continue
}
seenURLsIndex[url] = true
seenURLs = append(seenURLs, url)
tsURLs <- url
}
if len(seenURLs) > maxSeenURLs {
var removed []string
delta := len(seenURLs) - maxSeenURLs
removed, seenURLs = seenURLs[0:delta-1], seenURLs[delta:]
for _, url := range removed {
delete(seenURLsIndex, url)
}
}
time.Sleep(time.Second * 2)
urls, urlsErr = getURLs(client, playlistURL)
}
}