-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (84 loc) · 1.99 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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
)
func usage() {
fmt.Printf("Usage: %s <twitch-username>\n", os.Args[0])
os.Exit(1)
}
func formats(name string) []string {
cmd := exec.Command("youtube-dl", "-F", "https://twitch.tv/"+name)
output, err := cmd.CombinedOutput()
if err != nil {
offline := fmt.Sprintf("%s is offline", name)
if strings.Contains(string(output), offline) {
fmt.Printf("Stream '%s' is offline.\n", name)
return []string{}
}
log.Fatalf("Error occurred: %v", err)
}
formatCodes := []string{}
lines := strings.Split(string(output), "\n")
regex := regexp.MustCompile(`^\d+p(\S+)?`)
for _, line := range lines {
if matches := regex.FindStringSubmatch(line); matches != nil {
formatCodes = append(formatCodes, matches[0])
}
}
return formatCodes
}
func pickOne(lst []string) string {
for i, v := range lst {
fmt.Printf("%d. %s\n", i+1, v)
}
var answer string
for {
fmt.Print("? ")
_, err := fmt.Scanln(&answer)
if err != nil {
log.Fatalf("[ERROR] %v: ", err)
}
if index, err := strconv.Atoi(answer); err == nil && index >= 1 && index <= len(lst) {
return lst[index-1]
}
fmt.Println("Invalid input. Please enter a number between 1 and", len(lst))
}
}
func getFmt(name string) string {
fmts := formats(name)
if len(fmts) == 0 {
log.Fatal("No available format found for the stream.")
}
fmt.Println("Pick a format:")
return pickOne(fmts)
}
func playStream(fmt, name string) {
url := "https://twitch.tv/" + name
cmd := exec.Command("mpv", "--really-quiet", "--title=Twitch", "--ytdl-format="+fmt, url)
// stderr to /dev/null
cmd.Stderr = nil
// run asynchronously
err := cmd.Start()
if err != nil {
log.Fatalf("[ERROR] %v: ", err)
}
// choto-mate ne! ... give me back my terminal
err = cmd.Process.Release()
if err != nil {
log.Fatalf("[ERROR] %v: ", err)
}
}
func main() {
if len(os.Args) < 2 {
usage()
}
name := os.Args[1]
fmtStr := getFmt(name)
playStream(fmtStr, name)
}