-
Notifications
You must be signed in to change notification settings - Fork 24
/
ytcast.go
523 lines (476 loc) · 14.3 KB
/
ytcast.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// See license file for copyright and license details.
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/user"
"path/filepath"
"sort"
"strings"
"time"
"github.com/MarcoLucidi01/ytcast/dial"
"github.com/MarcoLucidi01/ytcast/youtube"
)
const (
progName = "ytcast"
progRepo = "https://github.com/MarcoLucidi01/ytcast"
xdgCache = "XDG_CACHE_HOME"
fallbackCacheDir = ".cache" // used if xdgCache is not set, stored in $HOME
cacheFileName = progName + ".json"
launchTimeout = 1 * time.Minute
launchCheckInterval = 3 * time.Second
fallbackIdFormat = "0405.0000.2006010215" // poor man's UUID.
)
var (
progVersion = "vX.Y.Z-dev" // set with -ldflags at build time
errNoAddr = errors.New("no valid address for interface")
errNoDevFound = errors.New("no device found")
errNoDevLastUsed = errors.New("no device last used")
errNoDevMatch = errors.New("no device matches")
errMoreDevMatch = errors.New("more than one device matches")
errNoDevSelected = errors.New("no device selected")
errNoLaunch = errors.New("unable to launch app and get screenId")
errNoVideo = errors.New("no video to play")
errUnknownAppState = errors.New("unknown app state")
errInvalidCode = errors.New("invalid pairing code")
flagAdd = flag.Bool("a", false, "add video(s) to queue, don't change what's currently playing")
flagClearCache = flag.Bool("c", false, "clear cache")
flagDevName = flag.String("d", "", "select device by substring of name, hostname (ip) or unique service name")
flagNetInterface = flag.String("i", "", "specify network interface (or ip or hostname) to use for network operations")
flagLastUsed = flag.Bool("p", false, "select last used device")
flagList = flag.Bool("l", false, "list cached devices")
flagPairCode = flag.String("pair", "", "manual pair using TV code, skip device discovery")
flagSearch = flag.Bool("s", false, "search (discover) devices on the network and update cache")
flagTimeout = flag.Duration("t", dial.MSearchMinTimeout, fmt.Sprintf("search timeout (max %s)", dial.MSearchMaxTimeout))
flagVerbose = flag.Bool("verbose", false, "enable verbose logging")
flagVersion = flag.Bool("v", false, "print program version")
)
// cast contains a dial.Device and the youtube.Remote connected to that Device.
// Device will be nil if Remote was manually paired using a TV code.
// It's stored in the cache.
type cast struct {
Device *dial.Device
Remote *youtube.Remote
LastUsed bool // true if Device is the last successfully used Device.
cached bool // true if Device was fetched from the cache and not just discovered/updated.
}
func main() {
flag.StringVar(flagDevName, "n", "", "deprecated, same as -d")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "usage: %s [-a|-c|-d|-i|-l|-p|-s|-t|-v|-pair|-verbose] [video...]\n\n", progName)
fmt.Fprintf(flag.CommandLine.Output(), "cast YouTube videos to your smart TV.\n\n")
flag.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "\n%s %s\n%s\n", progName, progVersion, progRepo)
}
flag.Parse()
if *flagVersion {
fmt.Printf("%s %s\n", progName, progVersion)
return
}
log.SetFlags(log.Ltime | log.Lshortfile)
if !*flagVerbose {
log.SetOutput(io.Discard)
}
log.Printf("%s %s\n", progName, progVersion)
if err := run(); err != nil {
log.Println(err)
fmt.Fprintf(os.Stderr, "%s: %s\n", progName, err)
os.Exit(1)
}
}
func run() error {
cacheFilePath := filepath.Join(mkCacheDir(), cacheFileName)
cache := make(map[string]*cast)
if !*flagClearCache {
cache = loadCache(cacheFilePath)
}
defer saveCache(cacheFilePath, cache)
var err error
localAddr := ""
if *flagNetInterface != "" {
localAddr, err = addrFromInterface(*flagNetInterface)
if err != nil {
if errors.Is(err, errNoAddr) {
return fmt.Errorf("%s: addrFromInterface: %s", *flagNetInterface, err)
}
log.Printf("%s: addrFromInterface: %s", *flagNetInterface, err)
localAddr = *flagNetInterface // -i is not a valid interface, maybe it's an ip or hostname
}
log.Printf("using local address %s for network operations", localAddr)
localAddr += ":0" // use a random port
}
if *flagPairCode != "" {
return manualPair(cache, localAddr, *flagPairCode)
}
if len(cache) == 0 || *flagSearch {
if err := discoverDevices(cache, localAddr, *flagTimeout); err != nil {
return err
}
}
var selected *cast
switch {
case *flagDevName != "":
if selected, err = matchOneDevice(cache, *flagDevName); err == nil {
break
}
if !errors.Is(err, errNoDevMatch) {
return err
}
if err = discoverDevices(cache, localAddr, *flagTimeout); err != nil {
return err
}
if len(cache) == 0 {
return errNoDevFound
}
if selected, err = matchOneDevice(cache, *flagDevName); err != nil {
return err
}
case *flagLastUsed:
if selected = findLastUsedDevice(cache); selected == nil {
return errNoDevLastUsed
}
case len(cache) == 0:
// this check is done here and NOT immediately after the first
// discoverDevices() to give a chance to rediscover in -d case.
return errNoDevFound
case *flagList, *flagSearch:
listDevices(cache)
return nil
default:
listDevices(cache)
return errNoDevSelected
}
videos := flag.Args()
if len(videos) == 0 || (len(videos) == 1 && videos[0] == "-") {
if videos, err = readVideosFromStdin(); err != nil {
return err
}
if len(videos) == 0 {
return errNoVideo
}
}
// Device and (or) Remote could come from the cache, we need to make sure
// they use localAddr for network operations
if selected.Device != nil {
if err := selected.Device.SetLocalAddr(localAddr); err != nil {
return fmt.Errorf("%q: SetLocalAddr: %w", selected.name(), err)
}
}
if selected.Remote != nil {
if err := selected.Remote.SetLocalAddr(localAddr); err != nil {
return fmt.Errorf("%q: SetLocalAddr: %w", selected.name(), err)
}
}
screenId := ""
if selected.wasManuallyPaired() {
// try to reuse the screenId since we can't know if it changed.
screenId = selected.Remote.ScreenId
} else {
if !selected.Device.Ping() {
log.Printf("%q is not awake, trying waking it up...", selected.name())
if err := selected.Device.TryWakeup(); err != nil {
return fmt.Errorf("%q: TryWakeup: %w", selected.name(), err)
}
}
if screenId, err = launchYouTubeApp(selected.Device); err != nil {
return err
}
}
for _, entry := range cache {
entry.LastUsed = entry == selected
}
if needsToConnect(selected.Remote, screenId) {
log.Printf("connecting to %q via YouTube Lounge", selected.name())
remote, err := youtube.Connect(localAddr, screenId, getConnectName())
if err != nil {
return fmt.Errorf("Connect: %w", err)
}
if selected.wasManuallyPaired() {
// these fields must be maintained because they are not
// returned by Connect(), but only by ConnectWithCode().
remote.DeviceId = selected.Remote.DeviceId
remote.ScreenName = selected.Remote.ScreenName
}
selected.Remote = remote
}
if *flagAdd {
log.Printf("requesting YouTube Lounge to add %v to %q's playing queue", videos, selected.name())
if err := selected.Remote.Add(videos); err != nil {
return fmt.Errorf("Add: %w", err)
}
return nil
}
log.Printf("requesting YouTube Lounge to play %v on %q", videos, selected.name())
if err := selected.Remote.Play(videos); err != nil {
return fmt.Errorf("Play: %w", err)
}
return nil
}
func mkCacheDir() string {
cacheDir := os.Getenv(xdgCache)
if cacheDir == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Println(err)
return "." // current directory
}
cacheDir = filepath.Join(homeDir, fallbackCacheDir)
}
cacheDir = filepath.Join(cacheDir, progName)
log.Printf("mkdir -p %s", cacheDir)
if err := os.MkdirAll(cacheDir, 0755); err != nil {
log.Println(err)
return "."
}
return cacheDir
}
func loadCache(fpath string) map[string]*cast {
log.Printf("loading cache %s", fpath)
cache := make(map[string]*cast)
data, err := os.ReadFile(fpath)
if err != nil {
log.Println(err)
return cache
}
var cacheValues []*cast
if err = json.Unmarshal(data, &cacheValues); err != nil {
log.Printf("unmarshal cache: %s", err)
return cache
}
for _, entry := range cacheValues {
entry.cached = true
cache[entry.uuid()] = entry
}
return cache
}
func saveCache(fpath string, cache map[string]*cast) {
log.Printf("saving cache %s", fpath)
var cacheValues []*cast
for _, entry := range cache {
cacheValues = append(cacheValues, entry)
}
data, err := json.Marshal(cacheValues)
if err != nil {
log.Printf("marshal cache: %s", err)
return
}
if err := os.WriteFile(fpath, data, 0600); err != nil {
log.Println(err)
}
}
func addrFromInterface(name string) (string, error) {
iface, err := net.InterfaceByName(name)
if err != nil {
return "", err
}
addrs, err := iface.Addrs()
if err != nil {
return "", fmt.Errorf("%w: Addrs: %w", errNoAddr, err)
}
for _, addr := range addrs {
if a, ok := addr.(*net.IPNet); ok {
return a.IP.String(), nil
}
}
return "", errNoAddr
}
func manualPair(cache map[string]*cast, localAddr, code string) error {
if code = strings.TrimSpace(code); code == "" {
return errInvalidCode
}
log.Println("connecting to device via YouTube Lounge and pairing code")
remote, err := youtube.ConnectWithCode(localAddr, code, getConnectName())
if err != nil {
return fmt.Errorf("ConnectWithCode: %w", err)
}
if remote.DeviceId == "" {
remote.DeviceId = strings.ReplaceAll(time.Now().Format(fallbackIdFormat), ".", "")
}
if remote.ScreenName == "" {
remote.ScreenName = remote.DeviceId
}
if entry, ok := cache[remote.DeviceId]; ok {
entry.Remote = remote
entry.cached = false
} else {
cache[remote.DeviceId] = &cast{Remote: remote}
}
fmt.Println(cache[remote.DeviceId])
return nil
}
func discoverDevices(cache map[string]*cast, localAddr string, timeout time.Duration) error {
devCh, err := dial.Discover(nil, localAddr, timeout)
if err != nil {
return fmt.Errorf("Discover: %w", err)
}
for dev := range devCh {
if entry, ok := cache[dev.UniqueServiceName]; ok {
entry.Device = dev
entry.cached = false
} else {
cache[dev.UniqueServiceName] = &cast{Device: dev}
}
}
return nil
}
func matchOneDevice(cache map[string]*cast, name string) (*cast, error) {
nameLow := strings.ToLower(strings.TrimSpace(name))
var matched []*cast
for _, entry := range cache {
matches := strings.Contains(strings.ToLower(entry.name()), nameLow) ||
strings.Contains(strings.ToLower(entry.hostname()), nameLow) ||
strings.Contains(strings.ToLower(entry.uuid()), nameLow)
if matches {
matched = append(matched, entry)
}
}
if len(matched) == 1 {
return matched[0], nil
}
if len(matched) == 0 {
return nil, fmt.Errorf("%w %q", errNoDevMatch, name)
}
var matchedStr strings.Builder
for _, m := range matched {
matchedStr.WriteRune('\n')
matchedStr.WriteString(m.String())
}
return nil, fmt.Errorf("%w %q:%s", errMoreDevMatch, name, matchedStr.String())
}
func findLastUsedDevice(cache map[string]*cast) *cast {
for _, entry := range cache {
if entry.LastUsed {
return entry
}
}
return nil
}
func listDevices(cache map[string]*cast) {
var entries []*cast
for _, entry := range cache {
entries = append(entries, entry)
}
sort.Slice(entries, func(i, j int) bool {
switch {
case !entries[i].cached && entries[j].cached:
return true
case entries[i].cached && !entries[j].cached:
return false
case entries[i].LastUsed:
return true
case entries[j].LastUsed:
return false
}
return entries[i].name() < entries[j].name()
})
for _, entry := range entries {
fmt.Println(entry)
}
}
func (c *cast) wasManuallyPaired() bool {
return c.Device == nil // implies c.Remote != nil
}
func (c *cast) uuid() string {
if c.wasManuallyPaired() {
return c.Remote.DeviceId
}
return c.Device.UniqueServiceName
}
func (c *cast) name() string {
if c.wasManuallyPaired() {
return c.Remote.ScreenName
}
return c.Device.FriendlyName
}
func (c *cast) hostname() string {
if c.wasManuallyPaired() {
return "unknown"
}
return c.Device.Hostname()
}
func (c *cast) String() string {
var info []string
if c.cached {
info = append(info, "cached")
}
if c.LastUsed {
info = append(info, "lastused")
}
return fmt.Sprintf("%.8s %-15s %-30q %s",
strings.TrimPrefix(c.uuid(), "uuid:"), c.hostname(), c.name(), strings.Join(info, " "))
}
func launchYouTubeApp(dev *dial.Device) (string, error) {
for start := time.Now(); time.Since(start) < launchTimeout; time.Sleep(launchCheckInterval) {
app, err := dev.GetAppInfo(youtube.DialAppName, youtube.Origin)
if err != nil {
return "", fmt.Errorf("%q: GetAppInfo: %q: %w", dev.FriendlyName, youtube.DialAppName, err)
}
log.Printf("%q is %s on %q", youtube.DialAppName, app.State, dev.FriendlyName)
switch app.State {
case "running":
screenId, err := youtube.ExtractScreenId(app.Additional.Data)
if err != nil {
return "", err
}
if screenId != "" {
return screenId, nil
}
log.Println("screenId not available")
case "stopped", "hidden":
log.Printf("launching %q on %q", youtube.DialAppName, dev.FriendlyName)
if _, err := dev.Launch(youtube.DialAppName, youtube.Origin, ""); err != nil {
return "", fmt.Errorf("%q: Launch: %q: %w", dev.FriendlyName, youtube.DialAppName, err)
}
default:
return "", fmt.Errorf("%q: %q: %q: %w", dev.FriendlyName, youtube.DialAppName, app.State, errUnknownAppState)
}
}
return "", fmt.Errorf("%q: %q: %w", dev.FriendlyName, youtube.DialAppName, errNoLaunch)
}
func readVideosFromStdin() ([]string, error) {
log.Println("reading videos from stdin")
scanner := bufio.NewScanner(os.Stdin)
var videos []string
for scanner.Scan() {
if v := strings.TrimSpace(scanner.Text()); v != "" {
videos = append(videos, v)
}
}
return videos, scanner.Err()
}
func needsToConnect(remote *youtube.Remote, screenId string) bool {
switch {
case remote == nil:
return true
case remote.ScreenId != screenId:
log.Println("screenId changed")
return true
case remote.Expired():
log.Println("LoungeToken expired, trying refreshing it")
if err := remote.RefreshToken(); err != nil {
log.Printf("RefreshToken: %s", err)
return true
}
}
return false
}
func getConnectName() string {
u, err := user.Current()
if err != nil {
log.Println(err)
return progName
}
h, err := os.Hostname()
if err != nil {
log.Println(err)
return progName
}
return fmt.Sprintf("%s@%s", u.Username, h)
}