-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
553 lines (489 loc) · 12.5 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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Console player for rockradio.com online radio station.
// Made just for fun and personal comfort (avoid registration and advertising).
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/keybind"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/PuerkitoBio/goquery"
"github.com/fsnotify/fsnotify"
"github.com/koykov/vlc"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"os/signal"
"os/user"
"path"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
const (
PLAY = 0x100
PAUSE = 0x200
STOP = 0x300
)
// JSON types
type Hotkey struct {
Key string `json:"key"`
Desc string `json:"desc"`
}
type ChannelChunk struct {
Id uint64 `json:"channel_id"`
Expiry string `json:"expires_on"`
Length float64
Tracks []ChannelChunkTracks `json:"tracks"`
}
type ChannelChunkTracks struct {
Id uint64 `json:"id"`
Artist string `json:"display_artist"`
Title string `json:"display_title"`
Album string `json:"release"`
AlbumDate string `json:"release_date"`
Content ChannelChunkTracksContent `json:"content"`
}
type ChannelChunkTracksContent struct {
Length float64 `json:"length"`
Assets []ChannelChunkTracksContentAssets `json:"assets"`
}
type ChannelChunkTracksContentAssets struct {
Url string `json:"url"`
}
// General types
type RockRadioPlayer struct {
Channels map[uint64]RockRadioPlayerChannel
CurrentChunk ChannelChunk
CurrentTrack ChannelChunkTracksContentAssets
CurrentChannel uint64
AudioToken string
Status uint64
NextFetch uint64
vlcPlayer *vlc.Vlc
waitGroup *sync.WaitGroup
}
type RockRadioPlayerChannel struct {
Id uint64 `json:"Id"`
Title string `json:"Title"`
}
var rr RockRadioPlayer
var verbose bool
func init() {
// Check (and create if needed) configuration directory.
configDir := GetConfigDir()
_, err := os.Stat(configDir)
if os.IsNotExist(err) {
if err := os.MkdirAll(configDir, 0755); err != nil {
log.Fatal("Cannot create configuration diectory.")
}
}
// Check (and create) hotkeys configuration file.
hotkeyConfig := GetHotkeyConfig()
_, err = os.Stat(hotkeyConfig)
if os.IsNotExist(err) {
// For possible keys see https://github.com/BurntSushi/xgbutil/blob/master/keybind/keysymdef.go
// Unfortunately, there isn't possibility to specify a key combination, only one key may be used.
PutToFile(hotkeyConfig, `[
{
"key": "Pause",
"desc": "Play/pause."
}
]`)
Debug("create default config file - %s", hotkeyConfig)
}
// Check (and create if needed) cache directory.
cacheDir := GetCacheDir()
_, err = os.Stat(cacheDir)
if os.IsNotExist(err) {
if err := os.MkdirAll(cacheDir, 0755); err != nil {
log.Fatal("Cannot create cache diectory.")
}
}
// Initialize player.
rr.Init()
}
func main() {
var wg sync.WaitGroup
// Parse CLI options.
channelPtr := flag.Int("c", 0, "Channel ID.")
verbosePtr := flag.Bool("verbose", false, "Display debug messages.")
flag.Parse()
verbose = *verbosePtr
rr.waitGroup = &wg
// First fetch unique AudioToken. It have no sense to continue without it.
wg.Add(1)
rr.FetchAudioToken()
defer rr.ReleasePlayer()
// Make goroutine for final cleanup callback.
wg.Add(1)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
defer wg.Done()
<-c
Cleanup()
os.Exit(1)
}()
// Initialize keybinding.
X, err := xgbutil.NewConn()
if err != nil {
log.Fatal(err)
}
keybind.Initialize(X)
hotkeyConfig := GetHotkeyConfig()
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
err = watcher.Add(hotkeyConfig)
if err != nil {
log.Println(err)
}
// Keybinding goroutine.
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case ev := <-watcher.Events:
log.Println(ev)
err := bindall(hotkeyConfig, X)
if err != nil {
log.Println(err)
continue
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
err = bindall(hotkeyConfig, X)
if err != nil {
log.Panicln(err)
}
// Event handling goroutine.
wg.Add(1)
go func() {
defer wg.Done()
xevent.Main(X)
}()
// Cache check.
cacheFile := GetCacheDir() + string(os.PathSeparator) + "data.json"
needRegenerate := false
fi, err := os.Stat(cacheFile)
if err != nil {
if os.IsNotExist(err) {
needRegenerate = true
Debug("Cache file %s doesn't exists, need generate.", cacheFile)
} else {
log.Fatalf("Error when reading cache file: %s", err.Error())
}
}
if !needRegenerate {
now := time.Now()
mtime := fi.ModTime()
diff := now.Sub(mtime)
needRegenerate = diff.Seconds() > 7*24*3600
if needRegenerate {
Debug("Cache file %s is deprecated, need regenerate.", cacheFile)
}
}
if !needRegenerate {
// Read channels and groups from the cache.
raw, err := ioutil.ReadFile(cacheFile)
if err != nil {
log.Fatalf("Error reading cache file: %s", err.Error())
}
rr.Channels = make(map[uint64]RockRadioPlayerChannel)
_ = json.Unmarshal(raw, &rr.Channels)
Debug("Cache hit, reading file %s", cacheFile)
} else {
// Fetch channels and groups from 101.ru
rr.FetchChannels()
b, err := json.Marshal(rr.Channels)
if err != nil {
log.Fatal(err.Error())
}
PutToFile(cacheFile, string(b))
Debug("Write channels data to cache file %s", cacheFile)
}
// Choose channel.
if *channelPtr == 0 {
reader := bufio.NewReader(os.Stdin)
cls := make([]string, len(rr.Channels))
for _, c := range rr.Channels {
cls = append(cls, fmt.Sprintf("%d - %s\n", c.Id, c.Title))
}
sort.Strings(cls)
fmt.Println("Choose channel:")
for _, g := range cls {
fmt.Print(g)
}
fmt.Print("\nChannel: ")
channelIndex, _ := reader.ReadString('\n')
rr.CurrentChannel, _ = strconv.ParseUint(strings.Trim(channelIndex, "\n"), 10, 64)
} else {
rr.CurrentChannel = uint64(*channelPtr)
}
channel := rr.Channels[rr.CurrentChannel]
// Playing loop.
var heartbeat, tickToken, tickTrack <-chan time.Time
fmt.Printf("\nPlayng: %s\n", channel.Title)
for {
rr.FetchChannelInfo()
Debug("Fetch remote data %#v", rr.CurrentChunk)
Debug("Next fetch after %s", FormatTime(uint64(rr.CurrentChunk.Length)))
heartbeat = time.Tick(time.Second)
tickToken = time.After(time.Duration(math.Floor(rr.CurrentChunk.Length)) * time.Second)
for _, track := range rr.CurrentChunk.Tracks {
tickTrack = time.After(time.Duration(math.Floor(track.Content.Length)) * time.Second)
// Play current song.
rr.Stop()
fmt.Printf("%s - %s [%s] - %s\n", track.Artist, track.Title, track.Album, FormatTime(uint64(track.Content.Length)))
rr.CurrentTrack = track.Content.Assets[0] // @todo check next assets
wg.Add(1)
go rr.Play()
goOut := false
for {
select {
case <-heartbeat:
// Well, just waste the time while player works.
time.Sleep(time.Second)
case <-tickTrack:
// Need to break the infinite loop.
goOut = true
case <-tickToken:
// We need fresh audio token.
wg.Add(1)
go rr.FetchAudioToken()
}
if goOut {
break
}
}
}
}
// Waiting for finishing all goroutines.
wg.Wait()
}
// Process finish callback.
func Cleanup() {
rr.Stop()
Debug("Cleanup sig.")
}
// Returns full path to the config directory.
func GetConfigDir() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
ps := string(os.PathSeparator)
return usr.HomeDir + ps + ".config" + ps + "rrply"
}
// Returns full path to the hotkey configuration file.
func GetHotkeyConfig() string {
ps := string(os.PathSeparator)
return GetConfigDir() + ps + "hotkey.json"
}
// Returns full path to the cache directory.
func GetCacheDir() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
ps := string(os.PathSeparator)
return usr.HomeDir + ps + ".cache" + ps + "rrply"
}
// Create file (if needed) and write contents to him.
func PutToFile(filename string, contents string) {
if _, err := os.Create(filename); err != nil {
log.Fatal("Error when file is created: ", err.Error())
}
file, err := os.OpenFile(filename, os.O_RDWR, 0644)
if err != nil {
log.Fatal("Error when file is created: ", err.Error())
}
defer func() {
_ = file.Close()
}()
_, _ = file.WriteString(contents)
if err = file.Sync(); err != nil {
log.Fatal("Error when saving file: ", err.Error())
}
}
// Parses config file and binds keys to events.
func bindall(hotkeyConfig string, X *xgbutil.XUtil) (err error) {
config, err := ioutil.ReadFile(hotkeyConfig)
if err != nil {
log.Fatal("Could not find config file: ", err.Error())
return
}
var hotkeys []Hotkey
err = json.Unmarshal(config, &hotkeys)
if err != nil {
log.Fatal("Could not parse config file: ", err.Error())
return
}
keybind.Detach(X, X.RootWin())
for _, hotkey := range hotkeys {
hotkey.attach(X)
}
return
}
// Attach callback to the hotkey.
func (hotkey Hotkey) attach(X *xgbutil.XUtil) {
err := keybind.KeyPressFun(
func(X *xgbutil.XUtil, e xevent.KeyPressEvent) {
if rr.Status == STOP || rr.Status == PAUSE {
go rr.Resume()
} else {
go rr.Pause()
}
}).Connect(X, X.RootWin(), hotkey.Key, true)
if err != nil {
log.Fatalf("Could not bind %s: %s", hotkey.Key, err.Error())
}
}
// Convert seconds to "mm:ss" time format.
func FormatTime(s uint64) string {
min := s / 60
sec := s % 60
format := "%d:%d"
if sec < 10 {
format = "%d:0%d"
}
return fmt.Sprintf(format, min, sec)
}
// Print formatted debug message.
func Debug(message string, a ...interface{}) {
if verbose {
fmt.Println(fmt.Sprintf("Debug: "+message, a))
}
}
// Initialize player instance.
func (p *RockRadioPlayer) Init() {
var err error
p.vlcPlayer, err = vlc.NewVlc([]string{})
if err != nil {
log.Fatal(err)
}
}
// Release player instance.
func (p *RockRadioPlayer) ReleasePlayer() {
_ = p.vlcPlayer.Stop()
_ = p.vlcPlayer.Release()
_ = p.vlcPlayer.Release()
}
// Fetch unique audio token from rockradio.com
func (p *RockRadioPlayer) FetchAudioToken() {
defer p.waitGroup.Done()
response, err := http.Get("https://www.rockradio.com")
if err != nil {
log.Fatal(err)
return
}
defer func() {
_ = response.Body.Close()
}()
source, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
return
}
re := regexp.MustCompile(`"audio_token":"([a-z0-9]+)"`)
res := re.FindStringSubmatch(string(source))
if res == nil {
log.Fatal("Couldn't fetch AudioToken. Exiting.")
}
p.AudioToken = res[1]
Debug("Fetch AudioToken: %s", p.AudioToken)
}
// Fetch channels from rockradio.com
func (p *RockRadioPlayer) FetchChannels() {
doc, err := goquery.NewDocument("https://www.rockradio.com/")
if err != nil {
log.Fatal("Couldn't fetch channels: ", err.Error())
}
p.Channels = make(map[uint64]RockRadioPlayerChannel, 0)
doc.Find("div.submenu.channels li").Each(func(i int, selection *goquery.Selection) {
id, exists := selection.Attr("data-channel-id")
title := selection.Find("a").Find("span").Text()
if exists {
cid, _ := strconv.ParseUint(path.Base(id), 0, 64)
p.Channels[cid] = RockRadioPlayerChannel{
cid, title,
}
}
})
}
// Fetch channel info.
func (p *RockRadioPlayer) FetchChannelInfo() {
if len(p.AudioToken) == 0 {
log.Fatal("Unknown AudioToken. Call self.FetchAudioToken() first.")
}
ts := time.Now().UnixNano() / 1000000
channelUrl := fmt.Sprintf("https://www.rockradio.com/_papi/v1/rockradio/routines/channel/%d?audio_token=%s&_=%d", p.CurrentChannel, p.AudioToken, ts)
response, err := http.Get(channelUrl)
if err != nil {
log.Fatal(err)
return
}
defer func() {
_ = response.Body.Close()
}()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
var cc ChannelChunk
err = json.Unmarshal(b, &cc)
if err != nil {
log.Fatal(err)
}
p.CurrentChunk = cc
for _, track := range p.CurrentChunk.Tracks {
p.CurrentChunk.Length += track.Content.Length
}
}
// Play channel.
func (p *RockRadioPlayer) Play() {
defer p.waitGroup.Done()
playUrl := "https:" + p.CurrentTrack.Url
err := p.vlcPlayer.PlayURL(playUrl)
if err != nil {
log.Fatal(err)
}
if p.Status == PAUSE {
p.Pause()
} else {
p.Status = PLAY
Debug("Play sig.")
}
}
// Pause playing.
func (p *RockRadioPlayer) Pause() {
_ = p.vlcPlayer.Pause()
p.Status = PAUSE
Debug("Pause sig.")
}
// Resume playing.
func (p *RockRadioPlayer) Resume() {
_ = p.vlcPlayer.Resume()
p.Status = PLAY
Debug("Resume sig.")
}
// Stop playing.
func (p *RockRadioPlayer) Stop() {
_ = p.vlcPlayer.Stop()
p.Status = STOP
Debug("Stop sig.")
}