-
Notifications
You must be signed in to change notification settings - Fork 2
/
awr.py
349 lines (308 loc) · 10.6 KB
/
awr.py
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
#! /usr/bin/python
"""
AWR (abidibo's Web Radio software)
This software provides an interface to control the mplayer software.
The web raidios configured in the conf/radios.json json file are displayed
in a GtkNotebook by genre.
@author abidibo (Stefano Contini) <dev@abidibo.net>
@license MIT License (http://opensource.org/licenses/MIT)
@copyright 2013-2014 abidibo
"""
import os
import tempfile
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
import subprocess
from threading import Thread, Timer
import re
import json
from xml.sax.saxutils import escape
from time import sleep
from os import path
from agtk import MainWindow
def project_path(relative_path):
return path.abspath(path.join(path.dirname(__file__), relative_path))
# without this line threads are executed after the main loop
GObject.threads_init()
"""
@brief AWR Graphic User Interface
"""
class AWRGUI:
"""
@brief Constructor
@param AWR app the main application instance
"""
def __init__(self, app):
self._app = app
self._active_radio = None
self._style = 'dark';
# main window
self._win = MainWindow('main_window', 'AWR', self._app.kill_proc)
self._win.set_resizable(True)
# geometry = Gdk.Geometry()
# geometry.min_height = 100
# self._win.set_geometry_hints(None, geometry, Gdk.WindowHints.MIN_SIZE)
# main container
self.create_container()
# track and controllers
self.create_controlbar()
# notebook
self.create_notebook()
# footer
self.create_footer()
# style
self.style_provider = Gtk.CssProvider()
self.style_provider.load_from_path(project_path('css/style-%s.css' % self._style))
screen = Gdk.Screen.get_default()
styleContext = Gtk.StyleContext()
styleContext.add_provider_for_screen(screen, self.style_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
self._win.show_all()
"""
Main window widget getter
"""
def get_win(self):
return self._win
"""
@brief Creates the external container
"""
def create_container(self):
self._container = Gtk.Box(name='main_container', spacing=5, orientation=Gtk.Orientation.VERTICAL, homogeneous=False, margin=10)
self._win.add(self._container)
"""
@brief Creates the controller top bar
@description displays current track and stop, play, pause controllers
"""
def create_controlbar(self):
controlbar_box = Gtk.Box(spacing=5)
controlbar_box.get_style_context().add_class("ctrlbar");
self._container.pack_start(controlbar_box, False, False, 0)
# stop button
self._stop_button = Gtk.Button(stock=Gtk.STOCK_MEDIA_STOP)
self._stop_button.connect('clicked', self._app.stop_stream)
controlbar_box.pack_start(self._stop_button, False, False, 0)
# playpause button
self._playpause_button = Gtk.Button(stock=Gtk.STOCK_MEDIA_PAUSE)
self._playpause_button.connect('clicked', self._app.playpause_stream)
controlbar_box.pack_start(self._playpause_button, False, False, 0)
# onair label
onair_label = Gtk.Label('On Air')
controlbar_box.pack_start(onair_label, False, False, 0)
# track label (changes dynamically)
self._track_label = Gtk.Label('--')
self._track_label.get_style_context().add_class("evidence");
controlbar_box.pack_start(self._track_label, False, False, 0)
self.update()
"""
@brief Updates the controllers
"""
def update(self, track_title=None):
status = self._app.get_status()
self.update_stop_button(status)
self.update_playpause_button(status)
self.update_track_label(status, track_title)
if status == 'stopped':
self.unset_active_radio()
"""
@brief Updates the stop button
"""
def update_stop_button(self, status):
if status == 'stopped' or status == 'init':
self._stop_button.set_sensitive(False)
self._stop_button.get_style_context().add_class("button-disabled");
else:
self._stop_button.set_sensitive(True)
self._stop_button.get_style_context().remove_class("button-disabled");
"""
@brief Updates the play and pause buttons
"""
def update_playpause_button(self, status):
if status == 'stopped' or status == 'init':
self._playpause_button.set_sensitive(False)
self._playpause_button.set_label(Gtk.STOCK_MEDIA_PAUSE)
self._playpause_button.get_style_context().add_class("button-disabled");
elif status == 'playing':
self._playpause_button.set_sensitive(True)
self._playpause_button.set_label(Gtk.STOCK_MEDIA_PAUSE)
self._playpause_button.get_style_context().remove_class("button-disabled");
else:
self._playpause_button.set_label(Gtk.STOCK_MEDIA_PLAY)
def update_track_label(self, status, track_title):
if status == 'stopped':
self.update_track('--')
elif track_title:
self.update_track(track_title)
"""
@brief Creates the genres notebook
"""
def create_notebook(self):
json_data = open(project_path('conf/radios.json'))
data = json.load(json_data)
notebook = Gtk.Notebook()
self._container.pack_start(notebook, False, False, 0)
for genre in data['genres']:
genre_label = Gtk.Label(genre['name']);
genre_table = self.construct_genre_page(genre);
notebook.append_page(genre_table, genre_label);
"""
@brief Creates a genre page
"""
def construct_genre_page(self, genre):
grid = Gtk.Grid(row_spacing=10, margin=10)
i = 0
for radio in genre['radios']:
img_button = Gtk.Button(image=Gtk.Image.new_from_file(project_path(radio['img'])))
img_button.get_style_context().add_class("button-img");
img_button.set_vexpand(False)
img_button.connect('clicked', self._app.stream_radio, radio)
label = Gtk.Label(use_markup=True, xalign=0, margin_left=5)
label.set_line_wrap(True)
label.set_markup('<b>%s</b>\n%s' % (radio['name'], radio['description']))
grid.attach(img_button, 0, i, 1, 1)
grid.attach_next_to(label, img_button, Gtk.PositionType.RIGHT, 1, 1)
i = i + 1
return grid
"""
Creates the application footer
"""
def create_footer(self):
abidibo_container = Gtk.EventBox()
abidibo = Gtk.Image.new_from_file(project_path('abidibo.png'))
abidibo.set_property('xalign', 1)
abidibo_container.add(abidibo)
abidibo_container.connect('button_press_event', self.toggle_style)
self._container.pack_start(abidibo_container, False, False, 0)
"""
Sets the active radio widget
"""
def set_active_radio(self, widget):
self.unset_active_radio()
self._active_radio = widget
self._active_radio.get_style_context().add_class("button-selected");
"""
Unsets the active radio widget
"""
def unset_active_radio(self):
if self._active_radio:
self._active_radio.get_style_context().remove_class("button-selected");
self._active_radio = None
"""
@brief Updates the current track
"""
def update_track(self, title):
self._track_label.set_markup(title)
"""
@brief Toggles between light and dark styles
"""
def toggle_style(self, widget, event):
self._style = 'dark' if self._style == 'light' else 'light'
self.style_provider.load_from_path(project_path('css/style-%s.css' % self._style))
"""
Main app class
"""
class AWR:
"""
@brief Constructor
"""
def __init__(self):
self._proc = None
self._status = 'stopped'
self._gui = AWRGUI(self)
self._fifo_path = os.path.join(tempfile.mkdtemp(), 'fifo')
os.mkfifo(self._fifo_path)
"""
@brief Gets the player status
"""
def get_status(self):
return self._status
"""
@brief Starts the stream of a web radio
@param GtkWidget widget the widget which was clicked
@param Object radio the radio json object
"""
def stream_radio(self, widget, radio):
self.kill_proc()
if radio['playlist']:
self._proc = subprocess.Popen(["mplayer", "-slave", "-input", "file=%s" % self._fifo_path, "-playlist", radio['url']], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
self._proc = subprocess.Popen(["mplayer", "-slave", "-input", "file=%s" % self._fifo_path, radio['url']], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self._status = 'init'
thread = Thread(target = self.parse_stdout, )
thread.start()
self._gui.set_active_radio(widget)
"""
Parses mplayer stdout to catch the track title
"""
def parse_stdout(self):
error = True
for line in iter(self._proc.stdout.readline, ''):
str_line = str(line.decode('utf-8')).rstrip()
print(str_line)
if self._status == 'stopped':
error = False
break
if str_line.startswith('Starting playback'):
self._status = 'playing'
GObject.timeout_add(50, self._gui.update)
if str_line.startswith('ICY Info:'):
info = str_line.split(':', 1)[1].strip()
attrs = dict(re.findall("(\w+)='([^']*)'", info))
title = attrs.get('StreamTitle', '(unknown)')
self._status = 'playing'
# fixes seg fault when updating gui from inside another thread
GObject.timeout_add(100, self._gui.update, '<b>%s</b>' % escape(title))
# if stdout stops without pressing the stop button then an error occurred
if error:
GObject.idle_add(self.display_info)
"""
@brief Stops the stream
@param GtkWidget widget the widget which was clicked
"""
def stop_stream(self, widget):
if self._proc:
self._proc.communicate(b'stop\n')
self._status = 'stopped'
self._gui.update()
"""
@brief Toggles the play/pause mode
@param GtkWidget widget the widget which was clicked
"""
def playpause_stream(self, widget):
if self._proc:
try:
fifo = os.open(self._fifo_path, os.O_WRONLY)
os.write(fifo, 'pause\n'.encode('utf-8'))
# self._proc.communicate(b'pause\n')
self._status = 'playing' if self._status == 'paused' else 'paused'
self._gui.update()
except:
pass
"""
@brief Kills the current mplayer process
"""
def kill_proc(self):
self._status = 'stopped'
self._gui.update()
if self._proc:
timer = Timer(3, self._proc.kill)
try:
timer.start()
stdout, stderr = self._proc.communicate(b'quit\n')
timer.cancel()
except:
pass
"""
Displays a check internet connection message
"""
def display_info(self):
dialog = Gtk.MessageDialog(self._gui.get_win(), Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "Application streaming error")
dialog.format_secondary_text(
"An error occured while streaming audio data. Check your internet connection.")
dialog.run()
dialog.destroy()
def main(self):
Gtk.main()
if __name__ == "__main__":
awr = AWR()
awr.main()