-
Notifications
You must be signed in to change notification settings - Fork 1
/
oceaneyes.py
executable file
·2147 lines (1789 loc) · 61.4 KB
/
oceaneyes.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
#!../bin/python3
import sys, os, subprocess, time, logging, socket, requests, urllib, urllib.parse, json, xmltodict
from threading import Thread
#try:
# from tinydb import TinyDB, Query
#except ModuleNotFoundError:
# os.system('pip install tinydb')
from tinydb import TinyDB, Query
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
global headers, url_placeholder, name_placeholder, country_placeholder, genre_placeholder
url_placeholder = "https://streaming.radio.co/s5c5da6a36/listen"
name_placeholder = "Bird Song radio"
country_placeholder = "United Kingdom"
genre_placeholder = "Nature Sounds & Spa Music"
headers = {
"User-Agent": "Mozilla/5.0 (Linux; Android 12; Pixel 6 Build/SD1A.210817.023; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/94.0.4606.71 Mobile Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip,deflate",
"Upgrade-Insecure-Requests": "1",
"Connection": "keep-alive"
}
def import_safe(m, v = "0.0.0"):
if m.isnumeric():
logging.error("Module parameters incorrect")
sys.exit()
try:
__import__(m)
result = True
except ModuleNotFoundError:
logging.error(f"Module not found: {m} ({v})")
os.system(f"pip install {m}=={v}")
result = True
except:
os.system(f"pip install {m}=={v}")
result = True
if result:
return True
else:
sys.exit()
if import_safe("asyncio", "3.4.3"):
import asyncio
def background(f):
def wrapped(*args, **kwargs):
return asyncio.new_event_loop().run_in_executor(None, f, *args, **kwargs)
return wrapped
def main():
return
def switch(device = 1):
global url, ip, settings
try:
dbc = TinyDB("settings.db")
dip = dict((dbc.get(doc_id=int(device))))
ip = str(dip["ipaddress"])
url = str("http://" + ip)
dbc.close()
settings = {
"ipaddress" : ip,
"url" : url,
"language" : "English"
}
return settings, url, ip
except:
settings = {
"ipaddress" : "0.0.0.0",
"url" : "http://0.0.0.0",
"language" : "English"
}
return settings, settings["url"], settings["ip"]
def get_serverip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
s.connect(('1.1.1.1', 1))
sip = s.getsockname()[0]
except Exception:
sip = '127.0.0.1'
finally:
s.close()
return sip
def init_yt():
# Store previously played YouTube Radio stations
if os.path.isfile("stations_yt.db"):
dby = TinyDB("stations_yt.db")
if os.path.getsize('stations_yt.db') == 0:
for i in range(0,100):
dby.insert({'vid': '00000000000', 'aid': '00', 'sid': 'YouTube Stream Name'})
else:
dby = TinyDB("stations_yt.db")
# Create 99 radio stations in YouTube storage with id 100 = last played
for i in range(0,100):
dby.insert({'vid': '00000000000', 'aid': '00', 'sid': 'YouTube Stream Name'})
def init(device = 1):
global url, ip, sip, settings, pid_fm, pid_hd
sip = get_serverip()
# Attempt to find or set an ipaddress
if os.path.isfile("settings.db"):
dbc = TinyDB("settings.db")
if os.path.getsize('settings.db') == 0:
for i in range(0,10):
dbc.insert({'ipaddress': '0.0.0.0', 'language': 'English'})
hosts, devices = scan()
code = oe.cache("RadioBrowser")
else:
conf = dict((dbc.get(doc_id=int(device))))
conf = dict((dbc.get(doc_id=int(device))))
else:
dbc = TinyDB("settings.db")
# Create 20 radio devices in setting storage
for i in range(0,20):
dbc.insert({'ipaddress': '0.0.0.0', 'language': 'English'})
# Fallback on init to detect radio devices on network
try:
ip = str(conf['ipaddress'])
except:
init()
# Setup YouTube Radio storage
init_yt()
settings, url, ip = switch(int(device))
settings = {
"ipaddress" : ip,
"url" : url,
"language" : "English"
}
stations = {
"100": {
"name" : "BBC World Service",
"url" : "http://stream.live.vc.bbcmedia.co.uk/bbc_world_service",
"country" : "United Kingdom",
"genre" : "Public Radio"
}
}
dbc.close()
return settings, url, ip
def scan():
home = os.path.expanduser("~/")
os.system(f"rm {home}/.oceaneyes")
if os.path.isfile("settings.db"):
dbc = TinyDB("settings.db")
else:
dbc = TinyDB("settings.db")
dbc.insert({'ipaddress': '0.0.0.0', 'language': 'English'})
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1", 80))
h = s.getsockname()[0].split(".")
h = str(h[0] + "." + h[1] + "." + h[2])
s.close()
hosts = []
dev_radios = []
dev_tuners = []
d = 0
e = 99
logging.info("[i] Auto detecting Skytune radios on the LAN, this may take some time ...")
print("[i] Auto detecting Skytune radios on the LAN ...\n\n")
print("--- Tip: Take note of these numbers and then set")
print("--- static routes on the router for these devices\n\n")
#os.system('export DISPLAY=:0')
#os.system('env DBUS_SESSION_BUS_ADDRESS=unix:path=/run/lee/$(id -u)/bus')
#os.system('notify-send --urgency=normal "OceanEyes: Auto detecting Skytune radios" "Please wait for the scan to complete before attempting to use the API"')
for i in range(2,256):
host = h + "." + str(i)
try:
try:
r = requests.get("http://" + str(host) + ":80", timeout=1)
if r.status_code == 200:
p = 80
except:
p = 0
logging.info(f"[i] Looking for a radio at this address ({str(h)}.{str(i)})")
if p == 80:
logging.info(f"[i] Looking for a radio at this address ({str(h)}.{str(i)}) [P:80]")
# test that the radio can be pinged
result = str(os.popen("ping " + str(host) + " -w 5 -W 5").read())
else:
p = 0
result = "0 received"
except:
p = 0
result = "0 received"
if "5 received" in result:
try:
# Detect Skytune Radio
r = requests.get("http://" + str(host) + "/php/favList.php?PG=0")
if r.status_code == 200 and 'favListInfo' in r.text:
d+=1
#http://deviceip/device.xml
logging.info(f"\n[+] Found a skytune radio @{str(host)}:80\n")
dev_xml = "http://" + str(host) + "/device.xml"
dev_inf = requests.get(dev_xml)
dev_dat = xmltodict.parse(dev_inf.content)
dev_radios.append(host)
dbc.update({'ipaddress': str(host)}, doc_ids=[int(d)])
dbc.update({'name': str(dev_dat["root"]["device"]["friendlyName"])}, doc_ids=[int(d)])
dbc.update({'make': str(dev_dat["root"]["device"]["modelName"])}, doc_ids=[int(d)])
dbc.update({'uuid': str(dev_dat["root"]["device"]["UDN"]).replace("uuid:", "")}, doc_ids=[int(d)])
except:
x=1
try:
# Detect HDHomeRun
g = requests.get("http://" + str(host) + "/lineup.html")
if g.status_code == 200 and '<title>HDHomeRun Lineup</title>' in g.text:
e+=1
dev_tuners.append(host)
dbc.update({'ipaddress': str(host)}, doc_ids=[int(e)])
logging.info(f"\n[+] Found a hdhomerun @{str(host)}:80\n")
except:
x=1
hosts.append(host)
radios = len(dev_radios)
if radios > 0:
if radios > 1:
logging.info(f"\n[i] Found {str(radios)} radios on the network")
else:
logging.info(f"\n[i] Found {str(radios)} radio on the network")
for i in range(0,int(radios)):
logging.info(f"--- Radio {str(i+1)} @ {str(dev_radios[i])}")
os.system(f'notify-send --urgency=normal "OceanEyes: Found Radio" "A SkyTune radio was found at IP address: {str(dev_radios[i])}"')
tuners = len(dev_tuners)
if tuners > 0:
if tuners > 1:
logging.info(f"\n[i] Found {str(tuners)} tuners on the network")
else:
logging.info(f"\n[i] Found {str(tuners)} tuner on the network")
for i in range(0,int(tuners)):
logging.info(f"--- Tuner {str(i+1)} @ {str(dev_tuners[i])}")
sip = get_serverip()
#os.system(f'notify-send --urgency=normal "OceanEyes: Scanning complete" "You can now use the API at http://{sip}:1929"')
os.system(f"touch {home}/.oceaneyes")
return hosts, dev_radios
def convert_l2d(lst):
# Converts a list to a dictionary
res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res_dct
def isfloat(sin):
if sin.replace(".", "").isnumeric():
return True
else:
return False
def is_online(ip = "0.0.0.0"):
args = socket.getaddrinfo(ip, 80, socket.AF_INET, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in args:
s = socket.socket(family, socktype, proto)
try:
s.connect(sockaddr)
except socket.error:
return False
else:
s.close()
r = requests.get(url + "/php/favList.php?PG=0", headers=headers)
if r.status_code == 404:
return False
else:
return True
def is_streamable(churl = url_placeholder, chpreview = False):
if "fm://" in churl or "dab://" in churl:
return True
else:
try:
import vlc
vlc_ins = vlc.Instance('--input-repeat=-1', '-q')
vlc_pla = vlc_ins.media_player_new()
vlc_med = vlc_ins.media_new(str(churl))
vlc_pla.set_media(vlc_med); vlc_pla.play()
if chpreview == False:
vlc_pla.audio_set_mute(True); time.sleep(5)
time.sleep(10)
did_play = str(vlc_pla.is_playing()); time.sleep(1); vlc_pla.stop()
result = False
if str(vlc_pla.get_state()) == "State.Stopped":
if did_play == "1":
result = True
else:
vlc_pla.stop()
except ModuleNotFoundError:
return True
return result
def listen(device = 1, chid = "1", chduration = 21600):
if int(chid) > 99 or chduration > 21600:
code = 500
message = "Duration or channel preset out of range, must be below 100 and less than 1 hour playback"
else:
try:
import vlc
if is_online(settings_ip):
chid, chname, churl, country_str, genre_str = info_get(int(device), str(int(chid)))
else:
chid, chname, churl, country_str, genre_str = info_cached(int(device), str(int(chid)))
print("[i] Playing " + str(chname) + " locally ...")
vlc_ins = vlc.Instance('--input-repeat=-1', '-q')
vlc_pla = vlc_ins.media_player_new()
vlc_med = vlc_ins.media_new(str(churl))
vlc_pla.set_media(vlc_med); vlc_pla.play()
vlc_pla.audio_set_mute(False);
time.sleep(chduration)
did_play = str(vlc_pla.is_playing()); time.sleep(1); vlc_pla.stop()
code = 400
message = ""
if str(vlc_pla.get_state()) == "State.Stopped":
if did_play == "1":
code = 200
message = "Now listening to " + str(chname) + " on local device"
else:
vlc_pla.stop()
except ModuleNotFoundError:
os.system('pip install python-vlc')
code = 500
message = "Module python-vlc was installed with pip, pleaase try the request again"
return code, message
return code, message
def search(keyword = "BBC Radio 1", source = "radiobrowser", match_exact = True):
station_data = []
station_name = "not set"
station_url = "not set"
station_codec = "not set"
station_bitrate = "not set"
station_genre = "not set"
station_country = "not set"
station_language= "not set"
l = []
code = 0
# SEARCH RadioBrowser
if str(source.lower()) == "radiobrowser":
try:
from pyradios import RadioBrowser
source = RadioBrowser()
result = source.search(name=str(keyword), name_exact=match_exact)
i = 0; l = []
for item in result:
for key, value in item.items():
if str(key).lower() == "hls":
station_hls = str(value)
if str(key).lower() == "codec":
station_codec = str(value)
if str(key).lower() == "bitrate":
station_bitrate = str(value)
if str(key).lower() == "name":
station_name = str(value)
if str(key).lower() == "url":
station_url = str(value)
if str(key).lower() == "countrycode":
station_country = str(value)
if str(key).lower() == "state":
station_country = station_country + ";" + str(value)
if str(key).lower() == "language":
station_language = str(value)
if str(key).lower() == "tags":
station_genre = str(value)
station_data = {'chindex': int(i), 'chname': str(station_name), 'churl': str(station_url), 'chcodec': str(station_codec), 'chbitrate': str(station_bitrate), 'chhls': int(str(station_hls)), 'chgenre': str(station_genre), 'chcountry': str(station_country), 'chlanguage': str(station_language)}
l.append(station_data)
i+=1
if i > 1:
code = 200
else:
code = 404
except ModuleNotFoundError:
os.system('pip install pyradios')
station_data = {'chindex': 0, 'source': 'radiobrowser', 'chname': 'not found', 'churl': 'not found', 'chcodec': 'MP3', 'chbitrate': '320', 'chhls': 0, 'chgenre': 'notfound', 'chcountry': 'not found', 'chlanguage': 'not found'}
l = []
l.append(station_data)
code = 404
return code, l
# SEARCH : TuneIn
elif str(source.lower()) == "tunein":
try:
import opml
data = opml.parse("http://opml.radiotime.com/Search.ashx?event=lit&query=" + str(keyword))
i = 0
c = 0
for d in data:
try:
if str(data[i].type).lower() == "audio" and str(data[i].item).lower() == "station" and i <= int(len(data)):
c+=1
try:
station_name = str(data[i].text)
station_url = str(data[i].URL)
f = urllib.request.urlopen(str(station_url))
station_url = str(f.read())
station_url = station_url.replace("b'http", "http").replace("\\n'", "")
f.close()
except:
station_name = str(url_placeholder)
station_url = str(name_placeholder)
try:
station_codec = str(data[i].formats)
station_bitrate = str(data[i].bitrate)
except:
station_code = "not"
station_bitrate = "0"
try:
data[i].genre_id
station_genre = str(data[i].genre_id)
except:
station_genre = "g0"
try:
station_country = str(data[i].guide_id)
except:
station_country = str(data[i].guide_id)
try:
station_language = str(data[i].subtext)
except:
station_language = "s0"
station_data = {'chindex': int(c), 'chname': str(station_name), 'churl': str(station_url), 'chcodec': str(station_codec), 'chbitrate': str(station_bitrate), 'chhls': 0, 'chgenre': str(station_genre), 'chcountry': str(station_country), 'chlanguage': str(station_language)}
l.append(station_data)
i+=1
except:
station_data = {'chindex': 0, 'chname': 'not found', 'source': 'none', 'churl': 'not found', 'chcodec': 'MP3', 'chbitrate': '320', 'chhls': 0, 'chgenre': 'notfound', 'chcountry': 'not found', 'chlanguage': 'not found'}
if len(data) > 2:
code = 200
else:
code = 404
except ModuleNotFoundError:
os.system('pip install opml')
station_data = {'chindex': 0, 'source': 'tunein', 'chname': 'not found', 'churl': 'not found', 'chcodec': 'MP3', 'chbitrate': '320', 'chhls': 0, 'chgenre': 'notfound', 'chcountry': 'not found', 'chlanguage': 'not found'}
l = []
l.append(station_data)
code = 404
else:
station_data = {'chindex': 0, 'chname': 'not found', 'source': 'none', 'churl': 'not found', 'chcodec': 'MP3', 'chbitrate': '320', 'chhls': 0, 'chgenre': 'notfound', 'chcountry': 'not found', 'chlanguage': 'not found'}
l = []
l.append(station_data)
code = 404
return code, l
def cache(source = "RadioBrowser"):
code = 400
if str(source).lower() == "radiobrowser":
dest_file = "cache_radiobrowser.sql.gz"
source_url = "https://backups.radio-browser.info"
source_file = str(source_url) + "/latest.sql.gz"
r = requests.get(source_url)
code = r.status_code
if int(code) == 200 and os.path.isfile(dest_file) == False:
print("[i] Downloading entire Radio Browser database, please wait (this may take up 20 minutes) ...")
d = requests.get(source_file, allow_redirects=True)
code = d.status_code
open(dest_file, 'wb').write(d.content)
else:
print("[i] Radio Browser already cached, delete latest.sql.gz to force a download")
return code
def enrich_url(chname = "BBC Radio 1"):
code, result = search(str(chname).lower(), "RadioBrowser", False)
chplays = False
if code == 200:
i = 0
# Return a list of URL's matching station name, attempt to play with vlc, return the first playable URL
while i < len(result):
print("[i] Atempting to enrich URL for " + str(chname))
if is_streamable(result[i]["churl"], False):
chplays = True
churl = result[i]["churl"]
print("[i] Found a working URL!")
break
# found a playable url, break
else:
chplays = False
i+=1
if chplays:
return churl
else:
return url_placeholder
def get_total(device = 1, thing = "fav"):
t = 0
settings, settings_url, settings_ip = switch(device)
if thing == "fav":
r = requests.get(settings_url + "/php/favList.php?PG=0")
s = str(r.text).split("\n")
i = len(s)
c = s[i-2].split(":")
f = c[2].split(",")
t = int(f[0])
return t
def get_remaining(device = 1, thing = "fav"):
t = 0
settings, settings_url, settings_ip = switch(device)
if thing == "fav":
f = int(get_total(int(device), "fav"))
t = 99 - f
return int(t)
def get_status(sip):
status = "Unknown"
try:
r = requests.get("http://" + str(sip) + "/php/playing.php")
d = json.loads(str(r.text).replace("'", '"'))
if d["result"] == "success":
status = "playing"
playing = str(d["name"])
code = 200
else:
status = "stopped"
playing = "None"
code = 400
except Exception as e:
status = "unknown"
playing= "None"
code = 404
#logging.info(f"[i] Status of radio@{ip}: {playing} [{code}]")
return code, status, playing
def info_get(device = 1, chid = "1"):
chid = str(int(chid)-1)
settings, settings_url, settings_ip = switch(device)
t = get_total(device, "fav")
if int(chid) > t:
chname = str(name_placeholder)
churl = str(url_placeholder)
chcountry = "United Kingdom"
chgenre = "Nature Sounds & Spa Music"
return chid, chname, churl, chcountry, chgenre
else:
station_ids, station_names, station_urls, station_countries, station_genres = list_get()
chid = station_ids[int(chid)]
chname = station_names[int(chid)]
churl = station_urls[int(chid)]
chcountry = station_countries[int(chid)]
chgenre = station_genres[int(chid)]
country_bit = chcountry.split(",")
country_str = decode_country(int(country_bit[0]), int(country_bit[1]), int(country_bit[2]))
genre_bit = chgenre.split(",")
genre_str = decode_genre(int(genre_bit[0]), int(genre_bit[1])).replace("and", "&")
return chid, chname, churl, country_str, genre_str
def info_cached(chid = "1"):
t = 99
if int(chid) > t:
chid = "100"
chname = str(name_placeholder)
churl = str(url_placeholder)
chcountry = str(country_placeholder)
chgenre = str(genre_placeholder)
return chid, chname, churl, chcountry, chgenre
else:
dbs = TinyDB("stations.db")
chl = dict((dbs.get(doc_id=int(chid))))
dbs.close()
chid = str(chl['channel'])
chname = str(chl['name'])
churl = str(chl['url'])
chcountry = str(chl['country'])
chgenre = str(chl['genre'])
return chid, chname, churl, chcountry, chgenre
def edit(chid = "0", newchname = name_placeholder, newchurl = url_placeholder, forcechcountry = "3;17;-1", forcechgenre = "1;45", forceskytune = "0"):
if str(chid).isnumeric():
t = get_total(device, "fav")
if int(chid) <= t:
data = info_get(str(chid))
chid = str(int(chid) - 1)
chname = data[1]
churl = data[2]
chcountry = data[3]
chgenre = data[4]
code, newchgenre = encode_genre(str(chgenre))
newchcountry = str(chcountry).replace(",", ";")
newchskytune = "0"
#newchname = urllib.parse.quote_plus(str(newchname))
f = {'chName': str(newchname), 'chUrl': str(newchurl), 'chCountry': str(newchcountry), 'chGenre': str(newchgenre), 'chSkytune': str(newchskytune)}
r = requests.post(url + "/updateCh.cgi?CI=" + str(int(chid)), data=f)
code = int(r.status_code)
return code, str(chid), str(newchname), str(newchurl), str(newchcountry), str(newchgenre), str(newchskytune)
else:
code = 500
skyt = 0
print("Error: Preset Out Of Range")
return code, str("Null"), str("Null"), str("Null"), str("Null"), str("Null"), str(skyt)
else:
code = 500
skyt = 0
print("Error: Preset Out Of Range")
return code, str("Null"), str("Null"), str("Null"), str("Null"), str("Null"), str(skyt)
def play(device = 1, ch = "0"):
t = get_total(device, "fav")
settings, settings_url, settings_ip = switch(device)
if int(ch) <= t:
r = requests.get(settings_url + "/doApi.cgi", params = {"AI":"16", "CI": str(int(ch) - 1)})
if r.status_code == 200:
code, status, playing = get_status(ip)
message = "Changing channel"
return code, message, playing
else:
code = 500
message = "Failed to change channel"
playing = "None"
else:
code = 404
message = "Failed to change channel"
playing = "None"
return code, message, playing
def add(device = 1, chname = "Local Streaming", churl = "http://192.168.1.200:1234/stream.mp3", chcountry = "-1", chgenre = "-1", chplay = False):
settings, settings_url, settings_ip = switch(device)
t = 0
c = get_total(device, "fav")
if c > 99:
code = 403
station = "Presets Full"
return code, station
else:
f = {'EX': '0', 'chName': str(chname), 'chUrl': str(churl), 'chCountry': str(chcountry), 'chGenre': str(chgenre)}
if chplay:
if is_streamable(churl, False):
r = requests.post(url + "/addCh.cgi", data=f)
if r.status_code == 200:
print("[i] Added station " + str(chname) + " to radio @" + str(ip))
else:
r = requests.post(url + "/addCh.cgi", data=f)
if r.status_code == 200:
print("[i] Added station " + str(chname) + " to radio @" + str(ip))
time.sleep(8)
t = get_total("fav")
if t > c:
code = 200
station = str(chname)
else:
code = 500
station = str(chname)
return code, station
def add_import(device = 1, filename = "./import.pls", encode = False, chpreview = False):
c=0
s=0
added = ""
settings, settings_url, settings_ip = switch(device)
if ".pls" in filename:
print("[i] Importing station presets from " + str(filename))
lines = [i.split("=") for i in open(filename).readlines()]
t = int(len(lines)-1)
while c < t:
if "file" in str(lines[c][0]).lower() and "://" in str(lines[c][1]).lower():
s+=1
if encode:
churl = str(urllib.parse.quote_plus(str(lines[c][1]).replace("\n", "")))
chname = str(urllib.parse.quote_plus(str(lines[c+1][1]).replace("\n", "")))
else:
churl = str(lines[c][1]).replace("\n", "")
chname = str(lines[c+1][1]).replace("\n", "")
chcountry = "3;17;-1"
chgenre = "2;14"
chplays = False
if is_streamable(churl, chpreview):
chplays = True
code, station = add(device, chname, churl, chcountry, chgenre, False)
else:
code = 404
station = chname
churl = url_placeholder
chplays = False
if code == 200 and chplays:
added += str(str(code) + "," + str(station) + "," + str(churl) + "\n")
print("[+] " + str(s) + " of " + str(int((t/3))) + " ... [C-" + str(code) + ":P-" + str(chplays) + ":" + str(chname) + ":" + str(churl) + "]")
elif code == 404 or chplays == False:
print("[!] " + str(s) + " of " + str(int((t/3))) + " ... [C-" + str(code) + ":P-" + str(chplays) + ":" + str(chname) + " Cannot be contacted, double check the url or your internet connection]")
else:
print("[!] " + str(s) + " of " + str(int((t/3))) + " ... [C-" + str(code) + ":P-" + str(chplays) + ":" + str(chname) + "]")
added += str(str(code) + "," + str(station) + "," + str(churl) + "\n")
c+=1
elif ".json" in filename:
# Get genres and locations into global scope
decode_genre(1, 11)
decode_country(1,1,75)
print("[i] Importing station presets from " + str(filename))
with open(filename) as json_file:
data = json.load(json_file)
for q in data['stations']:
t = int(len(data['stations']))
for i in data['stations']:
s+=1
chname = str(i['name'])
churl = str(i['url'])
chcountry = str(i['country'])
chgenre = str(i['genre'])
gcode, chgenre = encode_genre(str(i['genre']))
ccode, chcountry = encode_country(str(i['country']))
chplays = False
if is_streamable(churl, chpreview):
chplays = True
code, station = add(device, chname, churl, chcountry, chgenre, False)
else:
code = 404
station = chname
churl = url_placeholder
chplays = False
if code == 200 and chplays:
added += str(str(code) + "," + str(station) + "," + str(churl) + "\n")
print("[+] " + str(s) + " of " + str(int((t))) + " ... [C-" + str(ccode) + ":G-" + str(gcode) + ":L-" + str(ccode) + ":P-" + str(chplays) + ":" + str(chname) + ":" + str(churl) + "]")
elif code == 404 or chplays == False:
print("[!] " + str(s) + " of " + str(int((t))) + " ... [C-" + str(ccode) + ":G-" + str(gcode) + ":L-" + str(ccode) + ":P-" + str(chplays) + ":" + str(chname) + " Cannot be contacted, double check the url or your internet connection]")
else:
print("[!] " + str(s) + " of " + str(int((t))) + " ... [C-" + str(ccode) + ":G-" + str(gcode) + ":L-" + str(ccode) + ":P-" + str(chplays) + ":" + str(chname) + "]")
added += str(str(code) + "," + str(station) + "," + str(churl) + "," + str(chgenre) + "," + str(chcountry) + "\n")
c+=1
else:
added = "None"
return added
def add_current(device = 1):
# Get current number of favs first
settings, settings_url, settings_ip = switch(device)
t = 0
c = get_total(int(device), "fav")
code, status, playing = get_status(ip)
if "stopped" in status.lower():
station = "None"
else:
# Set new fav
r = requests.get(settings_url + "/doApi.cgi", params = {"AI":"8"})
t = get_total(int(device), "fav")
# Read currently playing
code, status, playing = get_status(settings_ip)
station = playing
if t > c:
code = 200
else:
code = 500
return code, station
def del_current(device = 1):
# Get current number of favs first
settings, settings_url, settings_ip = switch(device)
t = 0
c = get_total(device, "fav")
code, status, playing = get_status(ip)
if "stopped" in status.lower():
station = "None"
else:
# Del currently playing
r = requests.get(settings_url + "/doApi.cgi", params = {"AI":"4"})
t = get_total("fav")
# Read currently playing
code, status, playing = get_status(settings_ip)
station = playing
if t < c:
code = 200
else:
code = 500
return code, station
def move(device = 1, f = "2", t = "1"):
#/moveCh.cgi?CI=49&DI=48&EX=0
# offset by 1 so -1 off values supplied in method
f = int(int(f)-1)
t = int(int(t)-1)
settings, settings_url, settings_ip = switch(device)
c = get_total(int(device), "fav")
if f > 99 or t > 99 or t > c or f > c or f < 0 or t < 0:
code = 400
string = "Cannot move - presets out of range"
return code, string
else:
r = requests.post(settings_url + "/moveCh.cgi?EX=0&CI="+ str(int(f)) +"&DI="+ str(int(t)))
code = 200
string = "Moved preset " + str(int(f)+1) + " to " + str(int(t)+1)
return code, string
def volume(device = 1, dir = "down"):
# volume down VL=-1
# volume up VL=1
# mute VL=128
# unmute VL=0
inc = "1"
if dir.isnumeric() == False:
settings, settings_url, settings_ip = switch(device)
if dir == "down":
inc = "-" + str(inc)
elif dir == "up":
inc = str(inc)
elif dir == "mute":
inc = "128"
elif dir == "unmute":
inc = "0"
elif dir == "toggle":
r = requests.get(settings_url + "/php/doVol.php", params = {"VL":str(inc)})
d = json.loads(str(r.text).replace("'", '"'))
data_level = d["level"]
data_muted = d["muted"]
if "false" in str(data_muted):
r = requests.get(settings_url + "/php/doVol.php", params = {"VL":"128"})
d = json.loads(str(r.text).replace("'", '"'))
data_level = d["level"]
return data_level
elif "true" in str(data_muted):
r = requests.get(settings_url + "/php/doVol.php", params = {"VL":"0"})
d = json.loads(str(r.text).replace("'", '"'))
data_level = d["level"]
return data_level
else:
inc = "-1"
r = requests.get(settings_url + "/php/doVol.php", params = {"VL":str(inc)})
d = json.loads(str(r.text).replace("'", '"'))
data_level = d["level"]
data_muted = d["muted"]
else: