-
Notifications
You must be signed in to change notification settings - Fork 31
/
station.py
957 lines (823 loc) · 36 KB
/
station.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2011 Guillaume Pellerin
# <yomguy@parisson.com>
# This file is part of deefuzzer
# This program 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.
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
import datetime
import string
import random
import shout
import urllib.request, urllib.parse, urllib.error
import mimetypes
import json
import hashlib
import MySQLdb as mdb
from threading import Thread
from .player import *
from .recorder import *
from .relay import *
from .streamer import *
from .tools import *
class Station(Thread):
"""a DeeFuzzer shouting station thread"""
id = 0
valid = False
counter = 0
delay = 0
start_time = time.time()
server_ping = False
playlist = []
media_source = None
lp = 1
player_mode = 1
osc_control_mode = 0
twitter_mode = 0
jingles_mode = 0
relay_mode = 0
record_mode = 0
run_mode = 1
appendtype = 0
feeds_json = 0
feeds_rss = 0
feeds_mode = 0
feeds_playlist = 0
feeds_showfilepath = 0
feeds_showfilename = 0
short_name = ''
channelIsOpen = False
starting_id = -1
jingles_frequency = 2
statusfile = ''
base_directory = ''
mdb_host = '127.0.0.1'
mdb_port = 3306
mdb_user = ''
mdb_password = ''
mdb_database = ''
mdb_table = ''
mdb_field = ''
feeds_dir = ''
is_alive = False
def __init__(self, station, q, logqueue, m3u):
Thread.__init__(self)
self.station = station
self.q = q
self.logqueue = logqueue
self.m3u = m3u
self.current_media_obj = MediaBase()
if 'station_statusfile' in self.station:
self.statusfile = station['station_statusfile']
try:
if os.path.exists(self.statusfile):
f = open(self.statusfile, 'r')
self.starting_id = int(f.read())
f.close()
except:
pass
if 'base_dir' in self.station:
self.base_directory = self.station['base_dir'].strip()
# Media
if 'm3u' in self.station['media']:
if not self.station['media']['m3u'].strip() == '':
self.media_source = self._path_add_base(self.station['media']['m3u'])
if 'dir' in self.station['media']:
if not self.station['media']['dir'].strip() == '':
self.media_source = self._path_add_base(self.station['media']['dir'])
if 'source' in self.station['media']:
if not self.station['media']['source'].strip() == '':
self.media_source = self._path_add_base(self.station['media']['source'])
assert os.path.exists(self.media_source), 'The source directory or file does not exist.'
# MySQL
if 'mysql' in self.station['media']:
if 'host' in self.station['media']['mysql']:
self.mdb_host = self.station['media']['mysql']['host']
if 'port' in self.station['media']['mysql']:
self.mdb_port = self.station['media']['mysql']['port']
if 'user' in self.station['media']['mysql']:
self.mdb_user = self.station['media']['mysql']['user']
if 'password' in self.station['media']['mysql']:
self.mdb_password = self.station['media']['mysql']['password']
if 'database' in self.station['media']['mysql']:
self.mdb_database = self.station['media']['mysql']['database']
if 'table' in self.station['media']['mysql']:
self.mdb_table = self.station['media']['mysql']['table']
if 'field' in self.station['media']['mysql']:
self.mdb_field = self.station['media']['mysql']['field']
self.media_format = self.station['media']['format']
self.shuffle_mode = int(self.station['media']['shuffle'])
self.bitrate = int(self.station['media']['bitrate'])
self.ogg_quality = int(self.station['media']['ogg_quality'])
self.samplerate = int(self.station['media']['samplerate'])
self.voices = int(self.station['media']['voices'])
# Server
if 'mountpoint' in self.station['server']:
self.mountpoint = self.station['server']['mountpoint']
elif 'short_name' in self.station['infos']:
self.mountpoint = self.station['infos']['short_name']
else:
self.mountpoint = 'default'
self.short_name = self.mountpoint
if 'appendtype' in self.station['server']:
self.appendtype = int(self.station['server']['appendtype'])
if 'type' in self.station['server']:
self.type = self.station['server']['type'] # 'icecast' | 'stream-m'
else:
self.type = 'icecast'
if 'stream-m' in self.type:
self.channel = HTTPStreamer()
self.channel.mount = '/publish/' + str(self.mountpoint)
elif 'icecast' in self.type:
self.channel = shout.Shout()
self.channel.mount = '/' + str(self.mountpoint)
if self.appendtype:
self.channel.mount = str(self.channel.mount) + '.' + str(self.media_format)
else:
self._err('Not a compatible server type. Choose "stream-m" or "icecast".')
return
# Shout requires non-unicode strings
self.channel.url = str(self.station['infos']['url'])
self.channel.name = str(self.station['infos']['name'])
self.channel.genre = str(self.station['infos']['genre'])
self.channel.description = str(self.station['infos']['description'])
self.channel.format = str(self.media_format)
self.channel.host = str(self.station['server']['host'])
self.channel.port = int(self.station['server']['port'])
self.channel.user = 'source'
self.channel.password = str(self.station['server']['sourcepassword'])
self.channel.public = int(self.station['server']['public'])
if self.channel.format == 'mp3':
self.channel.audio_info = {'bitrate': str(self.bitrate),
'samplerate': str(self.samplerate),
'channels': str(self.voices), }
else:
self.channel.audio_info = {'bitrate': str(self.bitrate),
'samplerate': str(self.samplerate),
'quality': str(self.ogg_quality),
'channels': str(self.voices), }
self.server_url = 'http://' + str(self.channel.host) + ':' + str(self.channel.port)
self.channel_url = self.server_url + self.channel.mount
# RSS
if 'feeds' in self.station:
self.station['rss'] = self.station['feeds']
if 'rss' in self.station:
if 'mode' in self.station['rss']:
self.feeds_mode = int(self.station['rss']['mode'])
if self.feeds_mode:
self.feeds_dir = self._path_add_base(self.station['rss']['dir'])
self.feeds_enclosure = int(self.station['rss']['enclosure'])
if 'json' in self.station['rss']:
self.feeds_json = int(self.station['rss']['json'])
if 'rss' in self.station['rss']:
self.feeds_rss = int(self.station['rss']['rss'])
if 'playlist' in self.station['rss']:
self.feeds_playlist = int(self.station['rss']['playlist'])
if 'showfilename' in self.station['rss']:
self.feeds_showfilename = int(self.station['rss']['showfilename'])
if 'showfilepath' in self.station['rss']:
self.feeds_showfilepath = int(self.station['rss']['showfilepath'])
self.feeds_media_url = self.channel.url + '/media/'
if 'media_url' in self.station['rss']:
if not self.station['rss']['media_url'] == '':
self.feeds_media_url = self.station['rss']['media_url']
if self.feeds_dir:
self.base_name = self.feeds_dir + os.sep + self.short_name + '_' + self.channel.format
else:
self.base_name = self.short_name + '_' + self.channel.format
self.feeds_current_file = self.base_name + '_current'
self.feeds_playlist_file = self.base_name + '_playlist'
# Logging
self._info('Opening ' + self.short_name + ' - ' + self.channel.name)
self.metadata_relative_dir = 'metadata'
self.metadata_url = self.channel.url + '/rss/' + self.metadata_relative_dir
self.metadata_dir = self.feeds_dir + os.sep + self.metadata_relative_dir
if self.feeds_mode and not os.path.exists(self.metadata_dir):
os.makedirs(self.metadata_dir)
# The station's player
self.player = Player(self.type)
# OSCing
# mode = 0 means Off, mode = 1 means On
if 'control' in self.station:
self.osc_control_mode = int(self.station['control']['mode'])
if self.osc_control_mode:
self.osc_port = int(self.station['control']['port'])
self.osc_controller = OSCController(self.osc_port)
# OSC paths and callbacks
self.osc_controller.add_method('/media/next', 'i', self.media_next_callback)
self.osc_controller.add_method('/media/relay', 'i', self.relay_callback)
self.osc_controller.add_method('/twitter', 'i', self.twitter_callback)
self.osc_controller.add_method('/jingles', 'i', self.jingles_callback)
self.osc_controller.add_method('/record', 'i', self.record_callback)
self.osc_controller.add_method('/player', 'i', self.player_callback)
self.osc_controller.add_method('/run', 'i', self.run_callback)
self.osc_controller.start()
# Jingling between each media.
if 'jingles' in self.station:
if 'mode' in self.station['jingles']:
self.jingles_mode = int(self.station['jingles']['mode'])
if 'shuffle' in self.station['jingles']:
self.jingles_shuffle = int(self.station['jingles']['shuffle'])
if 'frequency' in self.station['jingles']:
self.jingles_frequency = int(self.station['jingles']['frequency'])
if 'dir' in self.station['jingles']:
self.jingles_dir = self._path_add_base(self.station['jingles']['dir'])
if self.jingles_mode == 1:
self.jingles_callback('/jingles', [1])
# Relaying
if 'relay' in self.station:
self.relay_mode = int(self.station['relay']['mode'])
self.relay_url = self.station['relay']['url']
self.relay_author = self.station['relay']['author']
if self.relay_mode == 1:
self.relay_callback('/media/relay', [1])
# Twitting
if 'twitter' in self.station:
self.twitter_mode = int(self.station['twitter']['mode'])
self.twitter_key = self.station['twitter']['key']
self.twitter_secret = self.station['twitter']['secret']
self.twitter_tags = self.station['twitter']['tags'].split(' ')
try:
self.twitter_messages = self.station['twitter']['message']
if isinstance(self.twitter_messages, dict):
self.twitter_messages = list(self.twitter_messages)
except:
pass
if self.twitter_mode:
self.twitter_callback('/twitter', [1])
# Recording
if 'record' in self.station:
self.record_mode = int(self.station['record']['mode'])
self.record_dir = self._path_add_base(self.station['record']['dir'])
if self.record_mode:
self.record_callback('/record', [1])
self.valid = True
def _path_add_base(self, a):
return os.path.join(self.base_directory, a)
def _path_m3u_rel(self, a):
return os.path.join(os.path.dirname(self.media_source), a)
def _log(self, level, msg):
try:
obj = {'msg': 'Station ' + str(self.channel_url) + ': ' + str(msg), 'level': str(level)}
self.logqueue.put(obj)
except:
pass
def _info(self, msg):
self._log('info', msg)
def _err(self, msg):
self._log('err', msg)
def run_callback(self, path, value):
value = value[0]
self.run_mode = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
def media_next_callback(self, path, value):
value = value[0]
self.next_media = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
def relay_callback(self, path, value):
value = value[0]
if value:
self.relay_mode = 1
if self.type == 'icecast':
self.player.start_relay(self.relay_url)
else:
self.relay_mode = 0
if self.type == 'icecast':
self.player.stop_relay()
self.id = 0
self.next_media = 1
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
message = "relaying : %s" % self.relay_url
self._info(message)
def twitter_callback(self, path, value):
value = value[0]
self.twitter = Twitter(self.twitter_key, self.twitter_secret)
self.twitter_mode = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
# IMPROVEMENT: The URL paths should be configurable because they're
# server-implementation specific
self.m3u_url = self.channel.url + '/m3u/' + self.m3u.split(os.sep)[-1]
self.feeds_url = self.channel.url + '/rss/' + self.feeds_playlist_file.split(os.sep)[-1]
self._info(message)
def jingles_callback(self, path, value):
value = value[0]
if value:
self.jingles_list = self.get_jingles()
self.jingles_length = len(self.jingles_list)
self.jingle_id = 0
self.jingles_mode = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
def record_callback(self, path, value):
value = value[0]
if value:
if not os.path.exists(self.record_dir):
os.makedirs(self.record_dir)
self.rec_file = self.short_name.replace('/', '_') + '-'
self.rec_file += datetime.datetime.now().strftime("%x-%X").replace('/', '_')
self.rec_file += '.' + self.channel.format
self.recorder = Recorder(self.record_dir)
self.recorder.open(self.rec_file)
else:
try:
self.recorder.recording = False
self.recorder.close()
except:
pass
if self.type == 'icecast':
date = datetime.datetime.now().strftime("%Y")
media = None
if self.channel.format == 'mp3':
media = Mp3(self.record_dir + os.sep + self.rec_file)
if self.channel.format == 'ogg':
media = Ogg(self.record_dir + os.sep + self.rec_file)
if media:
media.metadata = {'artist': self.artist.encode('utf-8'),
'title': self.title.encode('utf-8'),
'album': self.short_name.encode('utf-8'),
'genre': self.channel.genre.encode('utf-8'),
'date': date.encode('utf-8'), }
media.write_tags()
self.record_mode = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
def player_callback(self, path, value):
value = value[0]
self.player_mode = value
message = "received OSC message '%s' with arguments '%d'" % (path, value)
self._info(message)
def get_playlist(self):
file_list = []
try:
# MySQLdb
if 'mysql' in self.station['media']:
try:
con = mdb.connect(host = self.mdb_host,
user = self.mdb_user,
passwd = self.mdb_password,
db = self.mdb_database,
port = self.mdb_port,
use_unicode = True)
cur = con.cursor()
cur.execute("SELECT %s FROM %s" % (self.mdb_field, self.mdb_table))
rows = cur.fetchall()
for row in rows:
file_list.append(row[0])
except mdb.Error as e:
self._err('Could not get playlist from MySQLdb, Error %d: %s' % (e.args[0], e.args[1]))
finally:
if con:
con.close()
# Directory
elif os.path.isdir(self.media_source):
self.q.get(1)
try:
for root, dirs, files in os.walk(self.media_source):
for file in files:
s = file.split('.')
ext = s[len(s) - 1]
if ext.lower() == self.channel.format and not os.sep + '.' in file:
file_list.append(root + os.sep + file)
file_list.sort()
except:
pass
self.q.task_done()
# File
elif os.path.isfile(self.media_source):
self.q.get(1)
try:
f = open(self.media_source, 'r')
try:
for path in f.readlines():
path = path.strip()
if '#' != path[0]:
fp = self._path_m3u_rel(path)
if os.path.isfile(fp):
file_list.append(fp)
except:
f.close()
except:
pass
self.q.task_done()
except:
pass
return file_list
def get_array_hash(self, s):
return hashlib.md5(str(s).encode('utf-8')).hexdigest()
def get_jingles(self):
file_list = []
for root, dirs, files in os.walk(self.jingles_dir):
for file in files:
s = file.split('.')
ext = s[len(s) - 1]
if ext.lower() == self.channel.format and not os.sep + '.' in file:
file_list.append(root + os.sep + file)
file_list.sort()
return file_list
def tweet(self):
if len(self.new_tracks):
new_tracks_objs = self.media_to_objs(self.new_tracks)
for media_obj in new_tracks_objs:
title, artist, song = self.get_songmeta(media_obj)
artist_names = artist.split(' ')
artist_tags = ' #'.join(list(set(artist_names) - {'&', '-'}))
message = '#NEWTRACK ! %s %s on #%s' % \
(song, artist_tags.strip(), self.short_name)
message = message[:113] + self.feeds_url
self.update_twitter(message)
def get_next_media(self):
# Init playlist
if self.lp:
playlist = self.playlist
new_playlist = self.get_playlist()
lp_new = len(new_playlist)
if not self.counter:
self.id = 0
if -1 < self.starting_id < lp_new:
self.id = self.starting_id
self.playlist = new_playlist
self.lp = lp_new
# Shake it, Fuzz it !
if self.shuffle_mode:
random.shuffle(self.playlist)
self._info('Generating new playlist (' + str(self.lp) + ' tracks)')
# use a hash check instead to detect when a filename changes as well as playlist length
# Also, recompute the hash every time for the built-in playlist so we can catch when that
# changes as well
elif self.get_array_hash(new_playlist) != self.get_array_hash(self.playlist):
self.id += 1
if self.id >= lp_new:
self.id = 0
else:
self.lp = lp_new
# Twitting new tracks
new_playlist_set = set(new_playlist)
playlist_set = set(playlist)
new_tracks = new_playlist_set - playlist_set
self.new_tracks = list(new_tracks.copy())
if self.twitter_mode == 1 and self.counter:
self.tweet()
# Shake it, Fuzz it !
if self.shuffle_mode:
random.shuffle(playlist)
# Play new tracks first
for track in self.new_tracks:
playlist.insert(0, track)
self.playlist = playlist
self._info('Generating new playlist (' + str(self.lp) + ' tracks)')
if self.jingles_mode and not (self.counter % self.jingles_frequency) and self.jingles_length:
media = self.jingles_list[self.jingle_id]
self.jingle_id = (self.jingle_id + 1) % self.jingles_length
else:
media = self.playlist[self.id]
self.id = (self.id + 1) % self.lp
self.q.get(1)
try:
f = open(self.statusfile, 'w')
f.write(str(self.id))
f.close()
if self.feeds_playlist:
self.update_feeds(self.media_to_objs(self.playlist), self.feeds_playlist_file, '(playlist)')
except:
pass
self.q.task_done()
return media
else:
mess = 'No media in source!'
self._err(mess)
self.run_mode = 0
def media_to_objs(self, media_list):
media_objs = []
for media in media_list:
file_meta = MediaBase()
file_name, file_title, file_ext = get_file_info(media)
self.q.get(1)
try:
if file_ext.lower() == 'mp3' or mimetypes.guess_type(media)[0] == 'audio/mpeg':
file_meta = Mp3(media)
elif file_ext.lower() == 'ogg' or mimetypes.guess_type(media)[0] == 'audio/ogg':
file_meta = Ogg(media)
elif file_ext.lower() == 'webm' or mimetypes.guess_type(media)[0] == 'video/webm':
file_meta = WebM(media)
except Exception as e:
self._err('Could not get specific media type class for %s' % (media))
self._err('Error: %s' % (str(e)))
pass
self.q.task_done()
media_objs.append(file_meta)
return media_objs
def update_feeds(self, media_list, rss_file, sub_title):
if not self.feeds_mode:
return
rss_item_list = []
if not os.path.exists(self.feeds_dir):
os.makedirs(self.feeds_dir)
channel_subtitle = self.channel.name + ' ' + sub_title
_date_now = datetime.datetime.now()
date_now = str(_date_now)
media_absolute_playtime = _date_now
json_data = []
for media in media_list:
json_item = {}
media_stats = os.stat(media.media)
media_date = time.localtime(media_stats[8])
media_date = time.strftime("%a, %d %b %Y %H:%M:%S +0200", media_date)
media.metadata['Duration'] = str(media.length).split('.')[0]
media.metadata['Bitrate'] = str(media.bitrate) + ' kbps'
media.metadata['StartTime'] = str(media_absolute_playtime).split('.')[0]
media.metadata['EndTime'] = str(media_absolute_playtime+media.length).split('.')[0]
media_description = '<table>'
media_description_item = '<tr><td>%s: </td><td><b>%s</b></td></tr>'
for key in list(media.metadata.keys()):
if media.metadata[key] != '':
if key == 'filepath' and not self.feeds_showfilepath:
continue
if key == 'filename' and not self.feeds_showfilename:
continue
media_description += media_description_item % (key.capitalize(),
media.metadata[key])
json_item[key] = media.metadata[key]
if self.feeds_showfilepath:
media_description += media_description_item % ('Filepath', media.media)
json_item['filepath'] = media.media
if self.feeds_showfilename:
media_description += media_description_item % ('Filename', media.file_name)
json_item['filename'] = media.file_name
media_description += '</table>'
title, artist, song = self.get_songmeta(media)
media_absolute_playtime += media.length
if self.feeds_enclosure == '1':
media_link = self.feeds_media_url + media.file_name
media_link = media_link.decode('utf-8')
rss_item_list.append(RSSItem(
title=song,
link=media_link,
description=media_description,
enclosure=Enclosure(media_link, str(media.size), 'audio/mpeg'),
guid=Guid(media_link),
pubDate=media_date, )
)
else:
media_link = self.metadata_url + '/' + media.file_name + '.xml'
try:
media_link = media_link.decode('utf-8')
except:
continue
rss_item_list.append(RSSItem(
title=song,
link=media_link,
description=media_description,
guid=Guid(media_link),
pubDate=media_date, )
)
json_data.append(json_item)
rss = RSS2(title=channel_subtitle,
link=self.channel.url,
description=self.channel.description.decode('utf-8'),
lastBuildDate=date_now,
items=rss_item_list, )
self.q.get(1)
try:
if self.feeds_rss:
f = open(rss_file + '.xml', 'w')
rss.write_xml(f, 'utf-8')
f.close()
except:
pass
try:
if self.feeds_json:
f = open(rss_file + '.json', 'w')
f.write(json.dumps(json_data, separators=(',', ':')))
f.close()
except:
pass
self.q.task_done()
def update_twitter(self, message):
try:
self.twitter.post(message.decode('utf8'))
self._info('Twitting : "' + message + '"')
except:
self._err('Twitting : "' + message + '"')
def set_relay_mode(self):
self.prefix = '#nowplaying #LIVE'
self.title = ""
self.artist = ""
self.song = ""
if self.type == 'stream-m':
relay = URLReader(self.relay_url)
self.channel.set_callback(relay.read_callback)
if self.record_mode:
relay.set_recorder(self.recorder)
else:
self.stream = self.player.relay_read()
def get_songmeta(self, mediaobj):
title = ""
artist = ""
song = ""
try:
title = mediaobj.get_title()
artist = mediaobj.get_artist()
song = mediaobj.get_song(True)
except:
pass
# print(title, artist, song)
return title, artist, song
def get_currentsongmeta(self):
self.title = ""
self.artist = ""
self.song = ""
self.current_media_obj = MediaBase()
try:
m = self.media_to_objs([self.media])
self.current_media_obj = m[0]
except:
self._info("Failed to get media object for %s" % (self.media))
pass
self.title, self.artist, self.song = self.get_songmeta(self.current_media_obj)
def set_read_mode(self):
self.prefix = '#nowplaying'
try:
self.get_currentsongmeta()
fn = self.current_media_obj.file_name
if fn:
self.metadata_file = self.metadata_dir + os.sep + fn + '.xml'
self.update_feeds([self.current_media_obj], self.feeds_current_file, '(currently playing)')
if fn:
self._info('DeeFuzzing: id = %s, name = %s' % (self.id, fn))
except:
pass
self.player.set_media(self.media)
self.q.get(1)
try:
if self.player_mode:
self.stream = self.player.file_read_slow()
else:
self.stream = self.player.file_read_fast()
except:
pass
self.q.task_done()
def set_webm_read_mode(self):
self.channel.set_callback(FileReader(self.media).read_callback)
def update_twitter_current(self):
if not self.__twitter_should_update():
return
message = '%s %s on #%s' % (self.prefix, self.song, self.short_name)
tags = '#' + ' #'.join(self.twitter_tags)
message = message + ' ' + tags
message = message[:108] + ' > ' + self.m3u_url
self.update_twitter(message)
def channel_open(self):
if self.channelIsOpen:
return True
try:
self.channel.open()
self.channel_delay = self.channel.delay()
self._info('channel connected')
self.channelIsOpen = True
return True
except:
self._err('channel could not be opened')
return False
def channel_close(self):
self.channelIsOpen = False
try:
self.channel.close()
self._info('channel closed')
except:
self._err('channel could not be closed')
def ping_server(self):
log = True
while not self.server_ping:
try:
server = urllib.request.urlopen(self.server_url)
self.server_ping = True
self._info('Channel available.')
except:
time.sleep(1)
if log:
self._err('Could not connect the channel. Waiting for channel to become available.')
log = False
def icecastloop_nextmedia(self):
try:
self.next_media = 0
self.media = self.get_next_media()
self.counter += 1
self.counter = (self.counter % self.jingles_frequency) + self.jingles_frequency
if self.relay_mode:
self.set_relay_mode()
elif os.path.exists(self.media) and not os.sep + '.' in self.media:
if self.lp == 0:
self._err('has no media to stream !')
return False
self.set_read_mode()
return True
except Exception as e:
self._err('icecastloop_nextmedia: Error: ' + str(e))
return False
def __twitter_should_update(self):
"""Returns whether or not an update should be sent to Twitter"""
if not self.twitter_mode:
# Twitter posting disabled. Return false.
return False
if self.relay_mode:
# We are in relay mode. Return true.
return True
if self.jingles_mode and (self.counter % self.jingles_frequency):
# We should be playing a jingle, and we don't send jingles to Twiitter.
return False
return True
def icecastloop_metadata(self):
try:
self.update_twitter_current()
if self.song:
self.channel.set_metadata({'song': str(self.song), 'charset': 'utf-8'})
return True
except Exception as e:
self._err('icecastloop_metadata: Error: ' + str(e))
return False
def run(self):
self.ping_server()
if self.type == 'stream-m':
if self.relay_mode:
self.set_relay_mode()
else:
self.media = self.get_next_media()
self.set_webm_read_mode()
if not self.channel_open():
return
self.channel.start()
if self.type == 'icecast':
while True: # Do this so that the handlers will still restart the stream
while self.run_mode:
if not self.channel_open():
return
if not self.icecastloop_nextmedia():
self._info('Something wrong happened in icecastloop_nextmedia. Ending.')
self.channel_close()
return
self.icecastloop_metadata()
# TEST MODE: Jump thru only the first chunk of each file
# first = True
for self.chunk in self.stream:
# if first:
# first = False
# else:
# break
if self.next_media or not self.run_mode:
self.is_alive = False
break
if self.record_mode:
try:
# Record the chunk
self.recorder.write(self.chunk)
except:
self._err('could not write the buffer to the file')
try:
# Send the chunk to the stream
self.channel.send(self.chunk)
self.channel.sync()
self.is_alive = True
except:
self._err('could not send the buffer')
self.channel_close()
if not self.channel_open():
self._err('could not restart the channel')
self.is_alive = False
if self.record_mode:
self.recorder.close()
return
try:
self.channel.set_metadata({'song': self.song, 'charset': 'utf8', })
self._info('channel restarted')
self.channel.send(self.chunk)
self.channel.sync()
self.is_alive = True
except:
self._err('could not send data after restarting the channel')
self.channel_close()
if self.record_mode:
self.recorder.close()
self.is_alive = False
return
# send chunk loop end
# while run_mode loop end
self._info("Play mode ended. Stopping stream.")
if self.record_mode:
self.recorder.close()
self.channel_close()
time.sleep(1)