-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsomafm
executable file
·712 lines (593 loc) · 23.6 KB
/
somafm
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
#!/usr/bin/env python3
# Python frontend for playing SomaFM with MPlayer
# Written by Tom Nardi (MS3FGX@gmail.com)
# Licensed under the GPLv3, see "COPYING"
version = "1.72-dev"
import re
import os
import sys
import pickle
import shutil
import signal
import requests
import argparse
import colorama
import platform
import tempfile
import subprocess
from random import randrange, choice
from datetime import datetime
from colorama import Fore, Style
from collections import OrderedDict
# Optional Chromecast support, don't error if can't import
try:
import pychromecast
chromecast_support = True
except ImportError:
chromecast_support = False
# Basic config options:
#-----------------------------------------------------------------------
# Default quality (0 is highest available)
quality_num = 0
# Default channel to play
default_chan = "Groove Salad"
# Name of Chromecast device
chromecast_name = "The Office"
# Show track names in terminal while casting
cast_sync = True
# Highlight station IDs in yellow
station_highlights = True
# Enable/Disable experimental desktop notifications
desktop_notifications = False
# Show which player is being used in header
show_player = False
# Experimental Options:
#-----------------------------------------------------------------------
# Run a custom command on each new track (BE CAREFUL)
custom_notifications = False
# Custom notification command, track title will be given as argument
notification_cmd = ""
# Log tracks to file
log_tracks = False
# File to store track listing
track_file = "/tmp/somafm_tracks.txt"
# Following variables should probably be left alone
#-----------------------------------------------------------------------
# SomaFM channel list
url = "somafm.com/channels.json"
# Generate safe temporary directory on each OS
tmp_dir = tempfile.gettempdir()
# Directory for cache
cache_dir = tmp_dir + "/soma_cache"
# Directory for channel icons
icon_dir = cache_dir + "/icons"
# Default image size for icons
image_size = "xlimage"
# File name for channel cache
channel_file = cache_dir + "/channel_list"
# PID file
pid_file = tmp_dir + "/soma.pid"
# Known station IDs
station_ids = ["SomaFM", "Big Url", "Nerd Show"]
# Supported players
players = ['mplayer','mpg123','mpv']
# Define functions
#-----------------------------------------------------------------------#
# Catch ctrl-c
def signal_handler(sig, frame):
# Re-enable cursor if it was turned off
print('\033[?25h')
print(Fore.RED + "Force closing...")
# Kill any sneaky players
for player_name in players:
subprocess.call(['killall', '-q', player_name])
clean_exit()
# Do necessary cleanup when closing on good terms
def clean_exit():
# Delete PID file
os.unlink(pid_file)
sys.exit(0)
# Check for supported players and config variables
def configPlayer():
# Make player definition global, init name
global player
player = {'name': ''}
# Loop through list of players
for player_name in players:
# Match found
if shutil.which(player_name):
if player_name == 'mplayer':
player = {
'name': 'mplayer',
'arg': '-playlist',
'sarg1': '-ao',
'sarg2': 'null',
'stream': 'PLS'
}
break
elif player_name == 'mpg123':
player = {
'name': 'mpg123',
'arg': '-@',
'sarg1': '-a',
'sarg2': 'null',
'stream': 'MP3'
}
break
elif player_name == 'mpv':
player = {
'name': 'mpv',
'arg': '',
'stream': 'PLS'
}
break
# If dict hasn't been populated, then no player was found
if not player['name']:
print(Fore.RED + "No supported player found!")
print(Fore.WHITE + "Please check documentation for a list of supported players.")
clean_exit()
# Download master list of channels
def downloadChannels():
# Make global so other functions can acess it
global channel_list
# Let user know we're downloading
if args.ssl:
print("Downloading channel list via HTTPS...", end='')
protocol = "https://"
else:
print("Downloading channel list...", end='')
protocol = "http://"
# Let user know we're downloading
sys.stdout.flush()
# Pull down JSON file
try:
channel_raw = requests.get(protocol + url, timeout=15)
except requests.exceptions.Timeout:
print("Timeout!")
clean_exit()
except requests.exceptions.ConnectionError:
print("Network Error!")
clean_exit()
except requests.exceptions.RequestException as e:
print("Unknown Error!")
clean_exit()
# Put channels in list
channel_list = channel_raw.json()['channels']
# Write to file
with open(channel_file, 'wb') as fp:
pickle.dump(channel_list, fp)
print("OK")
# Download channel icons
def downloadIcons():
# Create icon directory if don't exist
if not os.path.exists(icon_dir):
os.mkdir(icon_dir)
# If there are already icons, return
if os.listdir(icon_dir):
return
# Let user know we're downloading
print("Downloading channel icons", end='')
sys.stdout.flush()
for channel in channel_list:
# Download current icon
current_icon = requests.get(channel[image_size])
# Construct path
icon_path = icon_dir + "/" + os.path.basename(channel[image_size])
# Save it to file
with open(icon_path, 'wb') as saved_icon:
saved_icon.write(current_icon.content)
# Print a dot so user knows we're moving
print(".", end='')
sys.stdout.flush()
# If we get here, all done
print("OK")
# Loop through channels and print their descriptions
def listChannels():
# Find longest channel name
channel_length = max(len(channel['title']) for channel in channel_list)
# Loop through channels
print(Fore.RED + "------------------------------")
for channel in channel_list:
# Adjust spacing to fit longest channel name
print(Fore.BLUE + '{cname:>{cwidth}}'.format(cwidth=channel_length, cname=channel['title']) + Fore.WHITE, end=' : ')
print(Fore.GREEN + channel['description'] + Fore.RESET)
# Show sorted list of listeners
def showStats():
# To count total listeners
listeners = 0
# Dictionary for sorting
channel_dict = {}
# Put channels and listener counts into dictionary
for channel in channel_list:
channel_dict[channel['title']] = int(channel['listeners'])
# Sort and print results
sorted_list = OrderedDict(sorted(channel_dict.items(), key=lambda x: x[1], reverse=True))
print(Fore.RED + "------------------------------")
for key, val in sorted_list.items():
# Total up listeners
listeners = listeners + val
print(Fore.GREEN + '{:>4}'.format(val) + Fore.BLUE, end=' : ')
print(Fore.BLUE + key + Fore.RESET)
# Print total line
print(Fore.YELLOW + '{:>4}'.format(listeners) + Fore.BLUE, end=' : ')
print(Fore.CYAN + "Total Listeners" + Fore.RESET)
# Return information for given channel
def channelGet(request, channel_name):
for channel in channel_list:
if channel_name.capitalize() in channel['title'].capitalize():
# Channel exists, now what?
if request == "VERIFY":
return()
elif request == "PLS":
return(channel['playlists'][quality_num]['url'])
elif request == "NAME":
return(channel['title'])
elif request == "DESC":
return(channel['description'])
elif request == "ICON":
return(icon_dir + "/" + os.path.basename(channel[image_size]))
elif request == "ICON_URL":
return(channel[image_size])
elif request == "URL":
# Download PLS
pls_file = requests.get(channel['playlists'][quality_num]['url'])
# Split out file URL
for line in pls_file.text.splitlines():
if "File1" in line:
return(line.split('=')[1])
elif request == "MP3":
for stream in channel['playlists']:
if stream['format'] == 'mp3':
return(stream['url'])
else:
print(Fore.RED + "Unknown channel operation!")
clean_exit()
# If we get here, no match
print(Fore.RED + "Channel not found!")
print(Fore.WHITE + "Double check the name of the channel and try again.")
clean_exit()
# Stream channel with media player
def startStream(channel_name):
# Verify stream exists before starting stream
stream_link = channelGet(player['stream'], args.channel)
# Show HTTPS notification
if "https" in stream_link:
print("Loading stream (HTTPS)...", end='')
else:
print("Loading stream...", end='')
# Open stream
try:
playstream = subprocess.Popen([player['name'], player['arg'], stream_link],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
except:
print(Fore.RED + "FAILED")
print("")
print(Fore.WHITE + "Playback encountered an unknown error.")
clean_exit()
print("OK")
# Hand off to info display
streamInfo(playstream)
# Stream channel on Chromecast
def startCast(channel_name):
# Populate stream variables
stream_name = channelGet('NAME', channel_name)
stream_url = channelGet('URL', channel_name)
# Now try to communicate with CC
print("Connecting to", chromecast_name, end='...')
sys.stdout.flush()
try:
chromecasts = pychromecast.get_chromecasts()
cast = next(cc for cc in chromecasts if cc.device.friendly_name == chromecast_name)
except:
print(Fore.RED + "FAILED")
print("")
print(Fore.WHITE + "Double check the device name and try again.")
clean_exit()
# Attempt to start stream
try:
cast.wait()
stream = cast.media_controller
stream.play_media(stream_url, 'audio/mp3', stream_name, channelGet('ICON_URL', channel_name))
stream.block_until_active()
except:
print(Fore.RED + "FAILED")
print("")
print(Fore.WHITE + "Stream failed to start on Chromecast.")
clean_exit()
print("OK")
# Start player with no audio to get track info
if cast_sync:
# Some player specific tweaks
if player['name'] == 'mpg123':
# mpg123 needs @ added to stream name
stream_url = '-@'+channelGet('MP3', args.channel)
elif player['name'] == 'mpv':
# Playing without audio doesn't seem to work in mpv, so bail out for now
print(Fore.RED + "Cast sync not supported on mpv.")
clean_exit()
try:
playstream = subprocess.Popen([player['name'], player['sarg1'], player['sarg2'], stream_url],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
except:
print(Fore.RED + "Track Sync Failed!")
clean_exit()
# Hand off to info display
streamInfo(playstream)
# If we get here, then player has stopped and so should Cast
cast.quit_app()
else:
print(Fore.RED + "--------------------------")
print(Fore.WHITE + "Now playing: " + Fore.CYAN + stream_name)
clean_exit()
# Determine if track is a Station ID
def stationID(track):
# Loop through known IDs, return on match
for station in station_ids:
if station.upper() in track.upper():
return(True)
# If we get here, no match was found
return(False)
# Print stream and track information
def streamInfo(playstream):
# Hide cursor
print('\033[?25l', end="")
InfoPrinted = False
print(Fore.RED + "--------------------------")
# Parse output
for line in playstream.stdout:
# Print debug information
if args.verbose:
print(line)
if InfoPrinted is False:
# mpv
if line.startswith(b'File tags:'):
if show_player:
print(Fore.CYAN + "Player: " + Fore.WHITE + "mpv")
# mpv doesn't give us much info, so have to pull channel name from args
print(Fore.CYAN + "Channel: " + Fore.WHITE + channelGet('NAME', args.channel))
print(Fore.RED + "--------------------------")
print(Fore.WHITE + "Press Crtl+C to Quit", end="")
InfoPrinted = True
# mpg123
if line.startswith(b'ICY-NAME'):
if show_player:
print(Fore.CYAN + "Player: " + Fore.WHITE + "mpg123")
print(Fore.CYAN + "Channel: " + Fore.WHITE + line.decode().split(':', 2)[1].strip())
if line.startswith(b'MPEG'):
print(Fore.CYAN + "Bitrate: " + Fore.WHITE + line.decode().strip())
print(Fore.RED + "--------------------------", end="")
InfoPrinted = True
# Mplayer
if line.startswith(b'Name'):
if show_player:
print(Fore.CYAN + "Player: " + Fore.WHITE + "MPlayer")
print(Fore.CYAN + "Channel: " + Fore.WHITE + line.decode().split(':', 2)[1].strip())
if line.startswith(b'Genre'):
print(Fore.CYAN + "Genre: " + Fore.WHITE + line.decode().split(':', 1)[1].strip())
if line.startswith(b'Bitrate'):
print(Fore.CYAN + "Bitrate: " + Fore.WHITE + line.decode().split(':', 1)[1].strip())
print(Fore.RED + "--------------------------", end="")
InfoPrinted = True
# Save track to file
if line.startswith(b'Capturing') and CaptureEnable:
# Print save icon next to track, flush output
print(" " + u"\U0001F4BE", end="")
sys.stdout.flush()
# Open favorites file for append
fav = open("favorites.txt", 'a')
# Write out current track
fav.write(track + "\n")
# Close file
fav.close()
# Set flag to false so this only runs once
CaptureEnable = False
# Updates on every new track
if line.startswith(b'ICY Info:') or line.startswith(b'ICY-META:') or line.startswith(b' icy-title:'):
# Reset capture flag
CaptureEnable = True
# mpv format is different
if line.startswith(b' icy-title:'):
track = line.decode().split(':', 1)[1].strip()
else:
# Break out artist - track data
info = line.decode().split(':', 1)[1].strip()
match = re.search(r"StreamTitle='(.*)';StreamUrl=", info)
track = match.group(1)
# Print date before track
print("")
print(Fore.BLUE + datetime.now().strftime("%H:%M:%S"), end=' | ')
# Check if track is a station ID once, save value to variable
IDStatus = stationID(track)
# Highlight station IDs in yellow
if station_highlights and IDStatus:
print(Fore.YELLOW + track, end="")
else:
print(Fore.GREEN + track, end="")
# Flush line so far
sys.stdout.flush()
# Before doing anything further, make sure it's not a Station ID
if not IDStatus:
# Log track to file if enabled
if log_tracks:
track_log.write(track + "\n")
# Send desktop notification if enabled
if desktop_notifications:
subprocess.Popen(['notify-send', '-i', channelGet('ICON', args.channel), track])
# Run custom notification command if enabled
if custom_notifications:
subprocess.run([notification_cmd, track], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
# Execution below this line
#-----------------------------------------------------------------------#
# Load signal handler
signal.signal(signal.SIGINT, signal_handler)
# Handle arguments
parser = argparse.ArgumentParser(description='Simple Python 3 player for SomaFM, version ' + version)
parser.add_argument('-l', '--list', action='store_true', help='Download and display list of channels')
parser.add_argument('-s', '--stats', action='store_true', help='Display current listener stats')
parser.add_argument('-a', '--about', action='store_true', help='Show information about SomaFM')
parser.add_argument('-c', '--cast', nargs='?', default=False, help='Start playback on Chromecast')
parser.add_argument('-f', '--file', action='store_true', help='Enable experimental track logging for this session')
parser.add_argument('-n', '--notify', action='store_true', help='Enable experimental desktop notifications for this session')
parser.add_argument('-p', '--player', action='store_true', help='Show which player is being used for this session')
parser.add_argument('-v', '--verbose', action='store_true', help='For debug use, prints all output of media player.')
parser.add_argument('-d', '--delete', action='store_true', help='Delete cache files')
parser.add_argument('-r', '--random', action='store_true', help='Choose a random channel at startup')
parser.add_argument('-S', '--ssl', action='store_true', help='Enable HTTPS, not supported on all platforms')
parser.add_argument("channel", nargs='?', const=1, default=None, help="Channel to stream. Default is Groove Salad (unless the --random flag is passed)")
args = parser.parse_args()
# None means user gave -c option, but no device name
if args.cast is None:
args.cast = True
else:
# If there is string after -c, use it as device name
chromecast_name = args.cast
# Check if the process is still running
def is_process_running(pid):
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
# Check for existing PID file
if os.path.isfile(pid_file):
with open(pid_file, 'r') as f:
pid = int(f.read().strip())
if is_process_running(pid):
print("SomaFM is already running!")
print("If you think this message is a mistake, delete the file: " + pid_file)
sys.exit()
else:
# PID file exists, but the process is not running
os.remove(pid_file)
# If we get here, create one
with open(pid_file, 'w') as pidfile:
pidfile.write(str(os.getpid()))
# Enable log file
if args.file:
log_tracks = True
# Enable desktop notifications
if args.player:
show_player = True
# Enable player display
if args.notify:
desktop_notifications = True
# Delete cache directory, exit
if args.delete:
try:
shutil.rmtree(cache_dir)
except:
print("Error while clearing cache!")
clean_exit()
# If we get here, sucess
print("Cache cleared.")
clean_exit()
# Get screen ready
colorama.init()
if platform.system() == "Windows":
os.system('cls')
else:
os.system('clear')
print(Style.BRIGHT, end='')
if args.about:
# I can't decide which one I like best, so let's use them all!
randlogo = randrange(3)
if randlogo == 0:
print(Fore.BLUE + " _____ " + Fore.GREEN + " ________ ___")
print(Fore.BLUE + " / ___/____ ____ ___ ____ _" + Fore.GREEN + "/ ____/ |/ /")
print(Fore.BLUE + " \__ \/ __ \/ __ `__ \/ __ `" + Fore.GREEN + "/ /_ / /|_/ / ")
print(Fore.BLUE + " ___/ / /_/ / / / / / / /_/ " + Fore.GREEN + "/ __/ / / / / ")
print(Fore.BLUE + "/____/\____/_/ /_/ /_/\__,_" + Fore.GREEN + "/_/ /_/ /_/ ")
elif randlogo == 1:
print(Fore.BLUE + " __" + Fore.GREEN + " ___")
print(Fore.BLUE + "/ _\ ___ _ __ ___ __ _ " + Fore.GREEN + "/ __\/\/\ ")
print(Fore.BLUE + "\ \ / _ \| '_ ` _ \ / _` |" + Fore.GREEN + "/ _\ / \ ")
print(Fore.BLUE + "_\ \ (_) | | | | | | (_| " + Fore.GREEN + "/ / / /\/\ \ ")
print(Fore.BLUE + "\__/\___/|_| |_| |_|\__,_" + Fore.GREEN + "\/ \/ \/ ")
elif randlogo == 2:
print(Fore.BLUE + " ______ ______ __ __ ______ " + Fore.GREEN + " ______ __ __ ")
print(Fore.BLUE + "/\ ___\ /\ __ \ /\ '-./ \ /\ __ \ " + Fore.GREEN + " /\ ___\ /\ '-./ \ ")
print(Fore.BLUE + "\ \___ \ \ \ \/\ \ \ \ \-./\ \ \ \ __ \ " + Fore.GREEN + " \ \ __\ \ \ \-./\ \ ")
print(Fore.BLUE + " \/\_____\ \ \_____\ \ \_\ \ \_\ \ \_\ \_\ " + Fore.GREEN + " \ \_\ \ \_\ \ \_\ ")
print(Fore.BLUE + " \/_____/ \/_____/ \/_/ \/_/ \/_/\/_/ " + Fore.GREEN + " \/_/ \/_/ \/_/ ")
print(Fore.WHITE + "")
print("SomaFM is a listener-supported Internet-only radio station.")
print("")
print("That means no advertising or annoying commercial interruptions. SomaFM's")
print("mission is to search for and expose great new music which people may")
print("otherwise never encounter.")
print("")
print("If you like what you hear on SomaFM and want to help, please consider")
print("visiting their site and making a donation.")
print("")
print(Fore.BLUE + "https://somafm.com/support/")
print("")
clean_exit()
# Create cache directory if doesn't exist
if not os.path.exists(cache_dir):
os.mkdir(cache_dir)
if args.list:
# Always download, this allows manual update
downloadChannels()
listChannels()
clean_exit()
if args.stats:
downloadChannels()
showStats()
clean_exit()
# If we get here, we are playing
# Check for player binaries before we get too comfortable
configPlayer()
# If SSL enabled, force reloading channels
if args.ssl:
downloadChannels()
# See if we already have a channel list
if os.path.isfile(channel_file) == False:
downloadChannels()
# Load local channel list
with open (channel_file, 'rb') as fp:
channel_list = pickle.load(fp)
# Open file for track logging (enable line buffering)
if log_tracks:
track_log = open(track_file, 'a', 1)
# Sanity check for desktop notifications
if desktop_notifications:
# See if we have notify-send
if shutil.which("notify-send") == None:
# If we don't, turn off notifications and warn user
desktop_notifications = False
print(Fore.RED + "Desktop notifications not supported on this system!" + Fore.WHITE)
else:
# Otherwise, get icons
downloadIcons()
# If -r option given and no channel provided, pick random channel from list
if args.random and args.channel == None:
args.channel = choice([chan['title'] for chan in channel_list])
elif args.channel == None:
args.channel = default_chan
# Record the start time
start_time = datetime.now()
# If Chromecast support is enabled, break off here
if args.cast:
if chromecast_support:
startCast(args.channel)
else:
print(Fore.RED + "Chromecast Support Disabled!")
print(Fore.WHITE + "Please install the pychromecast library.")
clean_exit()
else:
# Else, start stream
startStream(args.channel)
# Calculate how long we were playing
time_elapsed = datetime.now() - start_time
hours, remainder = divmod(int(time_elapsed.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
# Close log file
if log_tracks:
track_log.close()
# Print exit message
print('\033[?25h')
print(Fore.RESET + "Playback stopped after {:02}:{:02}:{:02}".format(int(hours), int(minutes), int(seconds)))
# Delete PID file
os.unlink(pid_file)
# EOF