-
Notifications
You must be signed in to change notification settings - Fork 13
/
radio_browser_source.py
1447 lines (1214 loc) · 56.8 KB
/
radio_browser_source.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
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Radio-Browser-Plugin for Rhythmbox.
# Copyright (C) 2012 <[email protected]>
# This is a derivative of software originally created by <[email protected]> 2009
#
# Radio-Browser-Plugin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Radio-Browser-Plugin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radio-Browser-Plugin. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import RB
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository.GdkPixbuf import Pixbuf
from gi.repository import GLib
import rb
import http.client
import os
import subprocess
from threading import Thread
import threading
import hashlib
import urllib.request, urllib.parse, urllib.error
import webbrowser
import queue
import pickle
import datetime
import math
import urllib.request, urllib.error, urllib.parse
import xml.sax.saxutils
from radio_station import RadioStation
from record_process import RecordProcess
from feed import Feed
from icecast_handler import FeedIcecast
from shoutcast_handler import FeedShoutcast
from shoutcast_handler import ShoutcastRadioStation
from board_handler import FeedBoard
from board_handler import BoardHandler
from radiotime_handler import FeedRadioTime
from radiotime_handler import FeedRadioTimeLocal
from constants import _Const
CONST = _Const()
RECENTLY_USED_FILENAME = "recently2.bin"
BOOKMARKS_FILENAME = "bookmarks2.bin"
GLib.threads_init()
class RadioBrowserSource(RB.StreamingSource):
def __init__(self):
self.hasActivated = False
self.feeds = []
RB.StreamingSource.__init__(self, name="RadioBrowserPlugin")
def do_get_status(self, *args):
'''
Method called by Rhythmbox to figure out what to show on this source
statusbar.
'''
if self.updating:
return (self.load_status, '', 1)
else:
return ('', '', 1)
def do_set_property(self, property, value):
if property.name == 'plugin':
self.plugin = value
""" return list of actions that should be displayed in toolbar """
def do_get_ui_actions(self):
print("do_get_ui_actions")
return self.do_impl_get_ui_actions()
def do_impl_get_ui_actions(self):
print("do_impl_get_ui_actions")
return ["UpdateList", "ClearIconCache"]
def do_impl_get_status(self):
print("do_impl_get_status")
if self.updating:
progress = -1.0
if self.load_total_size > 0:
progress = min(float(self.load_current_size) / self.load_total_size, 1.0)
return (self.load_status, None, progress)
else:
return (_("Nothing to do"), None, 2.0)
def update_download_status(self, filename, current, total):
#print "update_download_status"
self.load_current_size = current
self.load_total_size = total
self.load_status = _("Loading %(url)s") % {'url': filename}
Gdk.threads_enter()
self.notify_status_changed()
Gdk.threads_leave()
def do_selected(self):
print("do_selected")
self.do_impl_activate()
""" on source actiavation, e.g. double click on source or playing something in this source """
def do_impl_activate(self):
print("do_impl_activate")
# first time of activation -> add graphical stuff
if not self.hasActivated:
self.plugin = self.props.plugin
self.shell = self.props.shell
self.db = self.shell.props.db;
self.entry_type = self.props.entry_type
self.hasActivated = True
# add listener for stream infos
sp = self.shell.props.shell_player
sp.props.player.connect("info", self.info_available)
# create cache dir
self.cache_dir = RB.find_user_cache_file("radio-browser")
if os.path.exists(self.cache_dir) is False:
os.makedirs(self.cache_dir, 0o700)
self.icon_cache_dir = os.path.join(self.cache_dir, "icons")
if os.path.exists(self.icon_cache_dir) is False:
os.makedirs(self.icon_cache_dir, 0o700)
self.updating = False
self.load_current_size = 0
self.load_total_size = 0
self.load_status = ""
# create the model for the view
ui = Gtk.Builder()
ui.add_from_file(rb.find_plugin_file(self.plugin,
'radio_station.ui'))
self.filter_entry = ui.get_object('filter_entry')
self.filter_entry_bitrate = ui.get_object('filter_entry_bitrate')
self.filter_entry_genre = ui.get_object('filter_entry_genre')
self.tree_store = Gtk.TreeStore(str, object)
self.sorted_list_store = Gtk.TreeModelSort(model=self.tree_store) #Gtk.TreeModelSort(self.tree_store)
self.filtered_list_store = self.sorted_list_store.filter_new()
self.filtered_list_store.set_visible_func(self.list_store_visible_func)
self.filtered_icon_view_store = None
#self.tree_view = Gtk.TreeView(self.sorted_list_store)
self.tree_view = ui.get_object('tree_view')
self.tree_view.set_model(self.sorted_list_store)
# create the view
column_title = Gtk.TreeViewColumn() #"Title",Gtk.CellRendererText(),text=0)
column_title.set_title(_("Title"))
renderer = Gtk.CellRendererPixbuf()
column_title.pack_start(renderer, expand=False)
column_title.set_cell_data_func(renderer, self.model_data_func, "image")
renderer = Gtk.CellRendererText()
column_title.pack_start(renderer, expand=True)
column_title.add_attribute(renderer, 'text', 0)
column_title.set_resizable(True)
column_title.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
column_title.set_fixed_width(100)
column_title.set_expand(True)
self.tree_view.append_column(column_title)
self.info_box_tree = ui.get_object('info_box_tree')
# - selection change
self.tree_view.connect("cursor-changed", self.treeview_cursor_changed_handler, self.info_box_tree)
# create icon view
self.icon_view = ui.get_object('icon_view')
self.icon_view.set_text_column(0)
self.icon_view.set_pixbuf_column(2)
self.tree_view_container = ui.get_object('tree_view_container')
self.icon_view_container = ui.get_object('icon_view_container')
self.view = ui.get_object('view')
filterbox = ui.get_object('filterbox')
self.start_box = ui.get_object('start_box')
# prepare search tab
print("prepare search tab")
self.info_box_search = ui.get_object('info_box_search')
self.search_box = ui.get_object('search_box')
self.search_entry = ui.get_object('search_entry')
def searchButtonClick(widget):
self.doSearch(self.search_entry.get_text())
self.search_entry.connect("activate", searchButtonClick)
searchbutton = ui.get_object('searchbutton')
searchbutton.connect("clicked", searchButtonClick)
search_input_box = ui.get_object('search_input_box')
self.result_box = ui.get_object('result_box')
self.result_box.connect("cursor-changed", self.treeview_cursor_changed_handler, self.info_box_search)
self.result_box_container = ui.get_object('result_box_container')
self.result_box.append_column(Gtk.TreeViewColumn(_("Title"), Gtk.CellRendererText(), text=0))
stations_box = ui.get_object('stations_box')
self.notebook = ui.get_object('notebook')
ui.connect_signals(self)
self.pack_start(self.notebook, True, True, 0)
self.notebook.show_all()
self.icon_view_container.hide()
# initialize lists for recording streams and icon cache
self.recording_streams = {}
self.icon_cache = {}
# start icon downloader thread
# use queue for communication with thread
# enqueued addresses will get downloaded
self.icon_download_queue = queue.Queue()
self.icon_download_thread = threading.Thread(target=self.icon_download_worker)
self.icon_download_thread.setDaemon(True)
self.icon_download_thread.start()
# first time filling of the model
self.main_list_filled = False
# enable images on buttons
settings = Gtk.Settings.get_default()
settings.set_property("gtk_button_images", True)
#Gtk.Settings.gtk_button_images(True)
for feed in self.searchEngines():
self.feeds.append(feed)
self.event_page_switch(_, _, 0)
# rhythmbox 0.13.3 does not have the following method
try:
rb.BrowserSource.do_impl_activate(self)
except:
print("ignored error")
def searchEngines(self):
print("searchEngines")
yield FeedIcecast(self.cache_dir,self.update_download_status)
yield FeedBoard(self.cache_dir, self.update_download_status)
#yield FeedShoutcast(self.cache_dir,self.update_download_status)
#yield FeedRadioTime(self.cache_dir,self.update_download_status)
def doSearch(self, term):
print("doSearch")
search_model = Gtk.ListStore(str)
search_model.append((_("Searching for : '%s'") % term,))
# unset model
self.result_box.set_model(search_model)
# start thread
search_thread = threading.Thread(target=self.doSearchThread, args=(term,))
search_thread.start()
def doSearchThread(self, term):
print("doSearchThread")
results = {}
self.station_actions = {}
# check each engine for search method
for feed in self.feeds:
try:
feed.search
except:
print("no search support in : " + feed.name())
continue
# call search method
try:
self.station_actions[feed.name()] = feed.get_station_actions()
result = feed.search(term)
results[feed.name()] = result
except Exception as e:
print("error with source:" + feed.name())
print("error:" + str(e))
Gdk.threads_enter()
# create new model
new_model = Gtk.TreeStore(str, object)
# add entries to model
for name in list(results.keys()):
result = results[name]
source_parent = new_model.append(None, (name + " (" + str(len(result)) + ")", None))
for entry in result:
new_model.append(source_parent, (entry.server_name, entry))
# set model of result_box
new_model.set_sort_column_id(0, Gtk.SortType.ASCENDING)
self.result_box.set_model(new_model)
Gdk.threads_leave()
def download_click_statistic(self):
print("download_click_statistic")
# download statistics
statisticsStr = ""
try:
remotefile = urllib.request.urlopen(urllib.request.Request(CONST.BOARD_ROOT + "xml/stations/topclick/25", headers={'User-Agent': CONST.USER_AGENT}))
statisticsStr = remotefile.read()
except Exception as e:
print("download failed exception")
print(e)
return
# parse statistics
self.statistics_handler = BoardHandler()
xml.sax.parseString(statisticsStr, self.statistics_handler)
# fill statistics box
self.refill_statistics(thread=True)
def shortStr(self, longstring, maxlen):
if len(longstring) > maxlen:
short_value = longstring[0:maxlen - 3] + "..."
else:
short_value = longstring
return short_value
def refill_statistics(self, thread=False):
print("refill_statistics")
# check if already downloaded
try:
self.statistics_handler
except:
transmit_thread = threading.Thread(target=self.download_click_statistic)
transmit_thread.start()
return
def button_click(widget, name, station):
self.play_uri(station)
def button_add_click(widget, name, station):
print ("button_add_click")
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
if data is None:
data = {}
if station.server_name not in data:
data[station.server_name] = station
self.save_to_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME), data)
self.refill_favourites()
if thread:
Gdk.threads_enter()
for entry in self.statistics_handler.entries:
button = Gtk.Button(self.shortStr(entry.server_name, 30) + " (" + entry.clickcount + ")")
button.connect("clicked", button_click, entry.server_name, entry)
button_add = Gtk.Button()
img = Gtk.Image()
img.set_from_stock(Gtk.STOCK_GO_FORWARD, Gtk.IconSize.BUTTON)
button_add.set_image(img)
button_add.connect("clicked", button_add_click, entry.server_name, entry)
line = Gtk.HBox()
line.pack_start(button, True, True, 0) #dm
line.pack_start(button_add, False, False, 0)
self.statistics_box.pack_start(line, False, False, 0)
line.show_all()
self.statistics_box_parent.show_all()
if thread:
Gdk.threads_leave()
def refill_favourites(self):
print("refill favourites")
(hasfound, width, height) = Gtk.icon_size_lookup(Gtk.IconSize.BUTTON)
# remove all old information in infobox
for widget in self.start_box.get_children():
self.start_box.remove(widget)
def button_click(widget, name, station):
self.play_uri(station)
print ("2")
def button_record_click(widget, name, station):
self.record_uri(station)
print ("1")
def button_add_click(widget, name, station):
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
print (data)
if data is None:
data = {}
if station.server_name not in data:
data[station.server_name] = station
self.save_to_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME), data)
self.refill_favourites()
print ("3")
def button_delete_click(widget, name, station):
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
if data is None:
data = {}
if station.server_name in data:
del data[station.server_name]
self.save_to_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME), data)
self.refill_favourites()
left_box = Gtk.VBox()
left_box.show()
# add click statistics list
self.statistics_box = Gtk.VBox()
scrolled_box = Gtk.ScrolledWindow()
scrolled_box.add_with_viewport(self.statistics_box)
scrolled_box.set_property("hscrollbar-policy", Gtk.PolicyType.AUTOMATIC)
decorated_box = Gtk.Frame()
decorated_box.set_label("Click statistics (Last 30 days)")
decorated_box.add(scrolled_box)
self.statistics_box_parent = decorated_box
left_box.pack_start(decorated_box, True, True, 0) #dm
self.refill_statistics()
# add recently played list
recently_box = Gtk.VBox()
scrolled_box = Gtk.ScrolledWindow()
scrolled_box.add_with_viewport(recently_box)
scrolled_box.set_property("hscrollbar-policy", Gtk.PolicyType.AUTOMATIC)
decorated_box = Gtk.Frame()
decorated_box.set_label("Recently played")
decorated_box.add(scrolled_box)
left_box.pack_start(decorated_box, True, True, 0) #dm
self.start_box.pack1(left_box)
data = self.load_from_file(os.path.join(self.cache_dir, RECENTLY_USED_FILENAME))
if data is None:
data = {}
dataNew = {}
sortedkeys = sorted(data.keys())
for name in sortedkeys:
station = data[name]
if datetime.datetime.now() - station.PlayTime <= datetime.timedelta(
days=float(self.plugin.recently_played_purge_days)):
if len(name) > 53:
short_value = name[0:50] + "..."
else:
short_value = name
button = Gtk.Button(short_value)
button.connect("clicked", button_click, name, station)
button_add = Gtk.Button()
img = Gtk.Image()
img.set_from_stock(Gtk.STOCK_GO_FORWARD, Gtk.IconSize.BUTTON)
button_add.set_image(img)
button_add.connect("clicked", button_add_click, name, station)
line = Gtk.HBox()
line.pack_start(button, True, True, 0) #dm
line.pack_start(button_add, False, False, 0) #expand
recently_box.pack_start(line, False, False, 0) #expand
dataNew[name] = station
try:
if station.icon_src != "":
hash_src = hashlib.md5(station.icon_src.encode('utf-8')).hexdigest()
filepath = os.path.join(self.icon_cache_dir, hash_src)
if os.path.exists(filepath):
buffer = Pixbuf.new_from_file_at_size(filepath, width, height)
img = Gtk.Image()
img.set_from_pixbuf(buffer)
img.show()
button.set_image(img)
except:
print("could not set image for station:" + str(station.server_name))
if len(sortedkeys) > 0:
decorated_box.show_all()
self.save_to_file(os.path.join(self.cache_dir, RECENTLY_USED_FILENAME), dataNew)
# add bookmarks
favourites_box = Gtk.VBox()
scrolled_box = Gtk.ScrolledWindow()
scrolled_box.add_with_viewport(favourites_box)
scrolled_box.set_property("hscrollbar-policy", Gtk.PolicyType.AUTOMATIC)
decorated_box = Gtk.Frame()
decorated_box.set_label("Favourites")
decorated_box.add(scrolled_box)
self.start_box.pack2(decorated_box)
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
if data is None:
data = {}
sortedkeys = sorted(data.keys())
print (sortedkeys)
for name in sortedkeys:
print (name)
line = Gtk.HBox()
station = data[name]
if len(name) > 53:
short_value = name[0:50] + "..."
else:
short_value = name
button = Gtk.Button(short_value)
button.connect("clicked", button_click, name, station)
button_delete = Gtk.Button()
img = Gtk.Image()
img.set_from_stock(Gtk.STOCK_DELETE, Gtk.IconSize.BUTTON)
button_delete.set_image(img)
button_delete.connect("clicked", button_delete_click, name, station)
button_record = Gtk.Button()
img = Gtk.Image()
img.set_from_stock(Gtk.STOCK_MEDIA_RECORD, Gtk.IconSize.BUTTON)
button_record.set_image(img)
button_record.connect("clicked", button_record_click, name, station)
line.pack_start(button, True, True, 0) #dm
line.pack_start(button_record, False, False, 0) #dm expand
line.pack_start(button_delete, False, False, 0) #dm expand
favourites_box.pack_start(line, False, False, 0) #dm expand
try:
if station.icon_src != "":
hash_src = hashlib.md5(station.icon_src.encode('utf-8')).hexdigest()
filepath = os.path.join(self.icon_cache_dir, hash_src)
if os.path.exists(filepath):
buffer = Pixbuf.new_from_file_at_size(filepath, width, height)
img = Gtk.Image()
img.set_from_pixbuf(buffer)
img.show()
button.set_image(img)
except:
print("could not set image for station:" + str(station.server_name))
if (len(sortedkeys) > 0):
decorated_box.show_all()
""" handler for page switches in the main notebook """
def event_page_switch(self, notebook, page, page_num):
print("event_page_switch")
if page_num == 0:
# update favourites each time user selects it
self.refill_favourites()
if page_num == 1:
pass
if page_num == 2:
if not self.main_list_filled:
# fill the list only the first time, the user selects the main tab
self.main_list_filled = True
self.refill_list()
""" listener on double click in search view """
def on_item_activated_icon_view(self, widget, item):
print("on_item_activated_icon_view")
model = widget.get_model()
station = model[item][1]
self.play_uri(station)
""" listener on selection change in search view """
def on_selection_changed_icon_view(self, widget):
print("on_selection_changed_icon_view")
#model = widget.get_model()
#items = widget.get_selected_items()
model = self.icon_view.get_model()
items = self.icon_view.get_selected_items()
if len(items) == 1:
print("time to update with the info box")
obj = model[items[0]][1]
self.update_info_box(obj, self.info_box_tree) #dm2
""" listener for selection changes """
def treeview_cursor_changed_handler(self, treeview, info_box):
# get selected item
print("treeview_cursor_changed_handler")
selection = treeview.get_selection()
model,tree_iter = selection.get_selected()
# if some item is selected
if not tree_iter == None:
text = model.get_value(tree_iter, 0)
obj = model.get_value(tree_iter,1)
if not obj:
for feed in self.feeds:
if feed.name() in text:
obj = feed
break
self.update_info_box(obj,info_box)
def update_info_box(self, obj, info_box):
print("update_info_box")
# remove all old information in infobox
for widget in info_box.get_children():
info_box.remove(widget)
# create new infobox
info_container = Gtk.Table(12, 2)
info_container.set_col_spacing(0, 10)
self.info_box_added_rows = 0
# convenience method for adding new labels to infobox
def add_label(title, value, shorten=True):
if value == None:
return
if not value == "":
if shorten:
if len(value) > 53:
short_value = value[0:50] + "..."
else:
short_value = value
else:
short_value = value
label = Gtk.Label()
label.set_line_wrap(True)
if value.startswith("http://") or value.startswith("mms:") or value.startswith("mailto:"):
label.set_markup("<a href='" + xml.sax.saxutils.escape(value) + "'>" + xml.sax.saxutils.escape(
short_value) + "</a>")
else:
label.set_markup(xml.sax.saxutils.escape(short_value))
label.set_selectable(True)
label.set_alignment(0, 0)
title_label = Gtk.Label(title)
title_label.set_alignment(1, 0)
title_label.set_markup("<b>" + xml.sax.saxutils.escape(title) + "</b>")
info_container.attach(title_label, 0, 1, self.info_box_added_rows, self.info_box_added_rows + 1)
info_container.attach(label, 1, 2, self.info_box_added_rows, self.info_box_added_rows + 1)
self.info_box_added_rows = self.info_box_added_rows + 1
if isinstance(obj, Feed):
feed = obj
add_label(_("Entry type"), _("Feed"))
add_label(_("Description"), feed.getDescription(), False)
add_label(_("Feed homepage"), feed.getHomepage())
add_label(_("Feed source"), feed.getSource())
try:
t = os.path.getmtime(feed.filename)
timestr = datetime.datetime.fromtimestamp(t).strftime("%x %X")
except:
timestr = _("No local copy")
add_label(_("Last update"), timestr)
if isinstance(obj, RadioStation):
station = obj
add_label(_("Source feed"), station.type)
add_label(_("Name"), station.server_name)
add_label(_("Tags"), station.genre)
add_label(_("Bitrate"), station.bitrate)
add_label(_("Server type"), station.server_type)
add_label(_("Homepage"), station.homepage)
add_label(_("Current song (on last refresh)"), station.current_song)
add_label(_("Current listeners"), station.listeners)
add_label(_("Language"), station.language)
add_label(_("Country"), station.country)
add_label(_("Votes"), station.votes)
add_label(_("Negative votes"), station.negativevotes)
add_label(_("Stream URL"), station.listen_url)
try:
PlayTime = station.PlayTime.strftime("%x %X")
add_label(_("Added to recently played at"), PlayTime)
except:
pass
button_box = Gtk.VBox()
def button_play_handler(widget, station):
self.play_uri(station)
def button_bookmark_handler(widget, station):
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
if data is None:
data = {}
if station.server_name not in data:
self.tree_store.append(self.bookmarks_iter, (station.server_name, station))
data[station.server_name] = station
widget.set_label(_("Unbookmark"))
else:
tree_iter = self.tree_store.iter_children(self.bookmarks_iter)
while True:
title = self.tree_store.get_value(tree_iter,0)
if title == station.server_name:
self.tree_store.remove(tree_iter)
break
tree_iter = self.tree_store.iter_next(tree_iter)
if tree_iter == None:
break
del data[station.server_name]
widget.set_label(_("Bookmark"))
self.save_to_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME), data)
def button_record_handler(widget, station):
self.record_uri(station)
def button_download_handler(widget, feed):
transmit_thread = threading.Thread(target=self.download_feed, args=(feed,))
transmit_thread.setDaemon(True)
transmit_thread.start()
def button_action_handler(widget, action):
action.call(self)
def button_station_action_handler(widget, action, station):
action.call(self, station)
print ("1", obj)
if isinstance(obj, Feed):
print ("2")
feed = obj
if os.path.isfile(feed.filename):
button = Gtk.Button(_("Redownload"))
button.connect("clicked", button_download_handler, feed)
else:
button = Gtk.Button(_("Download"))
button.connect("clicked", button_download_handler, feed)
button_box.pack_start(button, False, False, 0)
for action in feed.get_feed_actions():
print ("3")
button = Gtk.Button(action.name)
button.connect("clicked", button_action_handler, action)
button_box.pack_start(button, False, False, 0)
if isinstance(obj, RadioStation):
button = Gtk.Button(_("Play"))
button.connect("clicked", button_play_handler, obj)
button_box.pack_start(button, False, False, 0)
# check for streamripper, before displaying record button
try:
process = subprocess.Popen("streamripper", stdout=subprocess.PIPE)
process.communicate()
process.wait()
except(OSError):
print("streamripper not found")
else:
button = Gtk.Button(_("Record"))
button.connect("clicked", button_record_handler, obj)
button_box.pack_start(button, False, False, 0)
data = self.load_from_file(os.path.join(self.cache_dir, BOOKMARKS_FILENAME))
if data is None:
data = {}
if station.server_name not in data:
button = Gtk.Button(_("Bookmark"))
else:
button = Gtk.Button(_("Unbookmark"))
button.connect("clicked", button_bookmark_handler, obj)
button_box.pack_start(button, False, False, 0)
if station.type in list(self.station_actions.keys()):
actions = self.station_actions[station.type]
for action in actions:
button = Gtk.Button(action.name)
button.connect("clicked", button_station_action_handler, action, obj)
button_box.pack_start(button, False, False, 0)
sub_info_box = Gtk.HBox()
sub_info_box.pack_start(info_container, True, True, 0) #dm
sub_info_box.pack_start(button_box, False, False, 0)
decorated_info_box = Gtk.Frame()
decorated_info_box.set_label("Info box")
decorated_info_box.add(sub_info_box)
info_box.pack_start(decorated_info_box, True, True, 0) #dm
print(decorated_info_box)
info_box.show_all()
print("finished info box routine")
""" icon download worker thread function """
def icon_download_worker(self):
print("icon_download_worker")
while True:
filepath, src = self.icon_download_queue.get()
if os.path.exists(filepath) is False:
if src.lower().startswith("http://"):
try:
urllib.request.urlretrieve(src, filepath)
except:
pass
self.icon_download_queue.task_done()
""" tries to load icon from disk and if found it saves it in cache returns it """
def get_icon_pixbuf(self, filepath, return_value_not_found=None):
if os.path.exists(filepath):
icon = None
if filepath in self.icon_cache:
return self.icon_cache[filepath]
else:
try:
what, width, height = Gtk.icon_size_lookup(Gtk.IconSize.BUTTON)
icon = Pixbuf.new_from_file_at_size(filepath, width, height)
except:
icon = return_value_not_found
self.icon_cache[filepath] = icon
return icon
return return_value_not_found
""" data display function for tree view """
def model_data_func(self,column,cell,model,iter2,infostr):
print ("model_data_func")
obj = model.get_value(iter2,1)
self.clef_icon = self.get_icon_pixbuf(rb.find_plugin_file(self.plugin, "note.png"))
if infostr == "image":
icon = None
if isinstance(obj, RadioStation):
station = obj
# default icon
icon = self.clef_icon
# icons for special feeds
if station.type == "Shoutcast":
icon = self.get_icon_pixbuf(rb.find_plugin_file(self.plugin, "shoutcast-logo.png"))
if station.type == "Icecast":
icon = self.get_icon_pixbuf(rb.find_plugin_file(self.plugin, "xiph-logo.png"))
if station.type == "Board":
icon = self.get_icon_pixbuf(rb.find_plugin_file(self.plugin, "local-logo.png"))
# most special icons, if the station has one for itsself
if station.icon_src != "":
hash_src = hashlib.md5(station.icon_src.encode('utf-8')).hexdigest()
filepath = os.path.join(self.icon_cache_dir, hash_src)
if os.path.exists(filepath):
icon = self.get_icon_pixbuf(filepath, icon)
else:
# load icon
self.icon_download_queue.put([filepath, station.icon_src])
if icon is None:
cell.set_property("stock-id", Gtk.STOCK_DIRECTORY)
else:
cell.set_property("pixbuf", icon)
""" transmits station information to board """
def transmit_station(self, station):
print("transmit_station")
if station.type == "Board":
""" this gets the decoded url, and also does register the click for statistics """
f = urllib.request.urlopen(urllib.request.Request(CONST.BOARD_ROOT + "xml/url/"+ station.id, headers={'User-Agent': CONST.USER_AGENT}))
f.read()
print("Transmit station '" + str(station.server_name) + "' OK")
""" transmits title information to board """
"""def transmit_title(self,title):
params = urllib.urlencode({'action':'streaming','name': self.station.server_name,'url': self.station.getRealURL(),'source':self.station.type,'title':title})
f = urllib.urlopen(BOARD_ROOT+"?%s" % params)
f.read()
print "Transmit title '"+str(title)+"' OK"
"""
""" stream information listener """
def info_available(self, player, uri, field, value):
print("info_available")
if field == RB.MetaDataField.TITLE:
self.title = value
self.set_streaming_title(self.title)
#transmit_thread = threading.Thread(target = self.transmit_title,args = (value,))
#transmit_thread.setDaemon(True)
#transmit_thread.start()
#print "setting title to:"+value
elif field == RB.MetaDataField.GENRE:
self.genre = value
## causes warning: RhythmDB-WARNING **: trying to sync properties of non-editable file
#self.shell.props.db.set(self.entry, rhythmdb.PROP_GENRE, value)
#self.shell.props.db.commit()
#print "setting genre to:"+value
elif field == RB.MetaDataField.BITRATE:
## causes warning: RhythmDB-WARNING **: trying to sync properties of non-editable file
#self.shell.props.db.set(self.entry, rhythmdb.PROP_BITRATE, value/1000)
#self.shell.props.db.commit()
#print "setting bitrate to:"+str(value/1000)
pass
else:
print("Server sent unknown info '" + str(field) + "':'" + str(value) + "'")
def record_uri(self,station):
play_thread = threading.Thread(target = self.play_uri_,args = (station,True))
play_thread.setDaemon(True)
play_thread.start()
""" listener for filter entry change """
def filter_entry_changed(self,Gtk_entry):
if self.filter_entry.get_text() == "" and self.filter_entry_genre.get_text() == "":
print ("entry and genre are empty")
self.tree_view_container.show()
self.icon_view_container.hide()
else:
print ("entry or genre has a value")
self.tree_view_container.hide()
self.icon_view_container.show()
self.icon_view.set_model(None)
if not self.filtered_icon_view_store == None:
self.filtered_icon_view_store.refilter()
self.icon_view.set_model(self.filtered_icon_view_store)
self.notify_status_changed()
""" callback for item filtering """
def list_store_visible_func(self,model,tree_iter,destroy):
#print "list_store_visible_func"
# returns true if the row should be visible
if len(model) == 0:
return True
obj = model.get_value(tree_iter,1)
if isinstance(obj,RadioStation):
station = obj
try:
bitrate = int(station.bitrate)
min_bitrate = int(float(self.filter_entry_bitrate.get_value()))
if bitrate < min_bitrate:
return False
except:
pass
filter_string = self.filter_entry.get_text().lower()
if filter_string != "":
if station.server_name.lower().find(filter_string) < 0:
return False
filter_string = self.filter_entry_genre.get_text().lower()
if filter_string != "":
genre = station.genre
if genre is None:
genre = ""
if genre.lower().find(filter_string) < 0:
return False
return True
else:
return True
""" handler for update toolbar button """
def update_button_clicked(self, widget):
print("update_button_clicked")
if not self.updating:
# delete cache files
files = os.listdir(self.cache_dir)
for filename in files:
if filename.endswith("xml"):
filepath = os.path.join(self.cache_dir, filename)
os.unlink(filepath)
# start filling again
self.refill_list()
def clear_iconcache_button_clicked(self, widget):
print("clear_iconcache_button_clicked")
if not self.updating:
# delete cache files
files = os.listdir(self.icon_cache_dir)
for filename in files:
filepath = os.path.join(self.icon_cache_dir, filename)
os.unlink(filepath)
# delete internal cache
self.icon_cache = {}
# start filling again
self.refill_list()
pass
""" starts playback of the station """
def play_uri(self, station):