forked from mk-fg/fgtk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradio
executable file
·171 lines (145 loc) · 5.69 KB
/
radio
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import itertools as it, operator as op, functools as ft
from tempfile import NamedTemporaryFile
import os, sys, io, re, requests, yaml, subprocess, signal, logging
player_wrap = 'media.mpv_icy_track_history' # should be in the sampe repo
tracks_global = os.path.expanduser('~/tracks.txt')
# --no-cache to prevent any audio/meta de-sync, so mute would work nicely
# Alternative: '--cache=1024', '--cache-initial=0'
mpv_args_base = ['--shuffle', '--loop=inf', '--no-cache', '--vo=null']
# radios_conf example (yaml):
# rmnrelax:
# url_pls: 'http://www.rmnrelax.de/aacplus/rmnrelax.m3u'
# args_wrapper: ['--mute-regexp=^\[RMN\]', '--recode-from=latin-1']
# etnfm:
# url_pls: 'http://ch1relay1.etn.fm:8100/listen.pls?sid=1'
# soma:
# template: true
# url_pls: 'http://somafm.com/{}.pls'
# difm:
# # use as e.g. "difm.vocaltrance" (to template "vocaltrance" into urls)
# template: true
# #url_pls: 'http://listen.di.fm/public3/{}.pls?3e4c569'
# url: 'http://pub5.di.fm:80/di_{}?3e4c569'
# args_wrapper:
# - >
# --mute-regexp=^(There|More of the show after these messages|Choose
# premium for the best audio experience|Digitally Imported TSTAG_60 ADWTAG|Job
# Opportunity at DI!.*|There's more to Digitally Imported!)$
# - --mute-title-prefix
radios_conf_default = '~/.radio.yaml'
_notify_init = False
def notify(title, body, critical=False, timeout=None, icon=None, fork=True):
global _notify_init
if fork and os.fork(): return
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
if not _notify_init:
Notify.init('radio')
_notify_init = True
note = Notify.Notification.new(summary=title, body=body, icon=icon)
if critical: note.set_urgency(Notify.Urgency.CRITICAL)
if timeout is not None: note.set_timeout(timeout)
note.show()
except: pass
if fork: os._exit(0)
def no_such_chan(err, chans):
p = ft.partial(print, file=sys.stderr)
p(err)
p('\nPossible matches:')
for chan in chans: p(' ' + chan)
sys.exit(1)
def get_url(chan, pls=False):
url = chan.get('url' if not pls else 'url_pls')
if url and chan.get('template'):
assert re.search(r'\{(\d+(:.*)?)?\}', url), url
name = chan['name'].split('.', 1)[-1]
url = url.format(name)
return url
def main(args=None):
import argparse
parser = argparse.ArgumentParser(description='Start radio playback.')
parser.add_argument('chan',
help='Radio channel (exact name or unique part of it) to tune into.')
parser.add_argument('-c', '--conf',
metavar='path', default=radios_conf_default,
help='Path to the configuration file with a list of radios.'
' See head of this script for an example. Default: %(default)s')
parser.add_argument('--desktop-notification-props',
default='{fork: false, icon: amarok, critical: true}', metavar='yaml_data',
help='Desktop notification properties (keywords) to pass to notify() function (see code).'
' "false" (bool value) can be passed here to disable desktop notifications entirely.'
' Default: %(default)s')
parser.add_argument('--debug', action='store_true', help='Verbose operation mode.')
opts = parser.parse_args(sys.argv[1:] if args is None else args)
logging.basicConfig(level=logging.DEBUG if opts.debug else logging.WARNING)
log = logging.getLogger('radio')
files_cleanup = set()
radios = os.path.expanduser(opts.conf)
with io.open(radios) as src: radios = yaml.safe_load(src)
chan = chan_name = opts.chan
if chan not in radios:
match = list(k for k in radios if k.startswith(chan))
if not match:
chan_tpl_base = chan.split('.', 1)[0]
match = radios.get(chan_tpl_base)
if match: match = match.get('template') and [chan_tpl_base]
if not match: match = list(k for k in radios if chan in k)
if not match: no_such_chan('Unable to match {!r}'.format(chan), radios.keys())
if len(match) > 1: no_such_chan('Unable to uniquely match {!r}'.format(chan), match)
chan, = match
log.debug('Using chan: %s', chan)
chan = radios[chan]
chan.update(name=chan_name)
url = get_url(chan, pls=True)
if url:
r = requests.get(url)
r.raise_for_status()
pls = NamedTemporaryFile(prefix='radio.pls.') # will be cleaned-up by child pid
files_cleanup.add(pls.name)
pls.write(r.text)
pls.flush()
url = '--playlist={}'.format(pls.name)
else:
url = get_url(chan)
assert url, chan
tracks = tracks_global
if 'tracks' in chan: tracks = chan['tracks']
if not os.path.exists(tracks):
with open(tracks, 'ab'): pass
notify_kws = yaml.safe_load(opts.desktop_notification_props)
if notify_kws is not False: notify_kws = notify_kws or dict()
pid_player = os.getpid()
pid = os.fork()
if not pid: ### child
os.setsid()
tail = subprocess.Popen(['tail', '-n1', '-f', tracks], stdout=subprocess.PIPE)
def player_check(sig=None, frm=None):
try: os.kill(pid_player, 0)
except OSError:
tail.terminate()
sys.exit(0)
signal.signal(signal.SIGALRM, player_check)
signal.alarm(5 *60)
for line in iter(tail.stdout.readline, ''):
player_check()
line = line.strip()
if notify_kws is not False:
notify('mpv: radio {}'.format(chan['name']), line, **notify_kws)
print(line)
sys.exit(0)
else: ### parent (player)
args_wrapper, args = chan.get('args_wrapper', list()), chan.get('args', list())
args = mpv_args_base + args
if opts.debug: args_wrapper.extend(['--debug', '--passthrough'])
if tracks: args_wrapper.extend([ '-d', tracks, '-t',
'--line-format', '{{ts}}{{mute}}{{}} [{}]\n'.format(chan['name']) ])
args.append(url)
args = [player_wrap] + args_wrapper + ['--'] + args
log.debug('Running: %s', ' '.join(args))
os.execvp(player_wrap, args)
if __name__ == '__main__': sys.exit(main())