forked from vorghahn/sstvProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsstvProxy.py
3810 lines (3371 loc) · 153 KB
/
sstvProxy.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
#!/usr/bin/env python3
###
###Copyright (c) 2016 by Joel Kaaberg and contributors. See AUTHORS
###for more details.
###
###Some rights reserved.
###
###Redistribution and use in source and binary forms of the software as well
###as documentation, with or without modification, are permitted provided
###that the following conditions are met:
###
###* Redistributions of source code must retain the above copyright
### notice, this list of conditions and the following disclaimer.
###
###* Redistributions in binary form must reproduce the above
### copyright notice, this list of conditions and the following
### disclaimer in the documentation and/or other materials provided
### with the distribution.
###
###* The names of the contributors may not be used to endorse or
### promote products derived from this software without specific
### prior written permission.
###
###THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND
###CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
###NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
###A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
###OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
###EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
###PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
###PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
###LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
###NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
###SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
###DAMAGE.
###
import logging, os, sys, time, argparse, json, gzip, base64, platform, threading, subprocess, urllib, glob, sqlite3, \
array, socket, struct, ntpath, timeit, re
from datetime import datetime, timedelta
from json import load, dump
from logging.handlers import RotatingFileHandler
from xml.etree import ElementTree as ET
from socket import timeout
from io import StringIO
from xml.sax.saxutils import escape
import requests
import datetime as dt
import xml.sax.saxutils as saxutils
HEADLESS = False
try:
from urlparse import urljoin
import thread
except ImportError:
from urllib.parse import urljoin
import _thread
from flask import Flask, redirect, abort, request, Response, send_from_directory, jsonify, render_template, \
stream_with_context, url_for
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", action='store_true', help="Console Debugging Enable")
parser.add_argument("-hl", "--headless", action='store_true', help="Force Headless mode")
parser.add_argument("-t", "--tvh", action='store_true', help="Force TVH scanning mode")
parser.add_argument("-i", "--install", action='store_true', help="Force install again")
args = parser.parse_args()
try:
import tkinter
except:
HEADLESS = True
if args.headless or 'headless' in sys.argv:
HEADLESS = True
app = Flask(__name__, static_url_path='')
__version__ = 1.837
# Changelog
# 1.837 - Web work
# 1.836 - Addition of sports.m3u8 which includes groups for current sports
# 1.8354 - Removal of trailing '==' from URLs.
# 1.8353 - Fallback fix
# 1.8352 - Small refactor for sstvLauncher
# 1.8351 - XML tag fix, xml path fix
# 1.835 - Emby fix for categories
# 1.834 - Dynamic mpegts added
# 1.833 - EPG category tinkering
# 1.832 - Escape characters for Emby EPG scanning
# 1.831 - Added translation of plex dvr transcode settings to SSTV quality settings.
# 1.83 - Rewrote create url to use chan api, added strm arg to playlist.m3u8 and static.m3u8 and dynamic playlists can be called using streamtype.m3u8 ie /sstv/hls.m3u8
# 1.8251 - Make pipe an option still and other small fixes
# 1.825 - Added support for enigma by adding in blank subtitle and desc fields to the EPG
# 1.8241 - Added user agent to log, Added new servers
# 1.824 - Backup server prompt added for headless
# 1.823 - Added -i for install trigger
# 1.822 - Added Auto server selection to Gui.
# 1.821 - Added CHECK_CHANNEL to adv settings
# 1.82 - Advanced settings added to web page, channel scanning work
# 1.815 - Restart option fix
# 1.814 - EPG Hotfix
# 1.813 - EPG Hotfix
# 1.812 - FixUrl Fix, readded EPG override (was inadvertantly removed in a commit revert), change of epg refresh to 4hrs
# 1.811 - Dev disable
# 1.81 - Improvement to Series Category detection.
# 1.8 - Added .gz support for EXTRA XML file/url.
# 1.731 - Correction of channel return type that had been removed
# 1.73 - HTML write exception fixed for settigns page, Vaders update
# 1.72 - Auto server selection based off of ping
# 1.71 - Channel parsing catch added for missing channels
# 1.7 - Static and dynamic xspf options added ip:port/sstv/static.xspf or ip:port/sstv/playlist.xspf, changed tkinter menu
# 1.691 - Updated FOG Urls
# 1.69 - Added more info to website, removed network discovery(isn't useful).
# 1.68 - Updated for MyStreams changes
# 1.672 - Changed mpegts output default quality from 1 to what user has set.
# 1.671 - Correction of MMATV url
# 1.67 - Finished JSON to XML, fixed quality setting and settings menu form posting
# 1.66 - Added extra m3u8 to the standard Plex Live output, make sure to use combined.xml in this scenario instead too.
# 1.65 - Addition of strmtype 'mpegts' utilises ffmpeg pipe prev used only by TVH/Plex Live. Enhancement of Webpage incl update and restart buttons.
# 1.64 - Bugfixes
# 1.63 - Added catch for clients with no user agent at all
# 1.62 - xmltv merger bugfix and speedup, kodi settings overwrite disabled
# 1.61 - Addition of test.m3u8 to help identify client requirements
# 1.60 - Addition of XMLTV merger /combined.xml, TVH CHNUM addition, Addition of MMA tv auth, change of returns based on detected client
# 1.59 - Removed need for TVH redirect, added a new path IP:PORT/tvh can be used in plex instead!
# 1.58 - A single dynamic channel can be requested with /ch##.m3u8 strm/qual options are still optional is /ch1.m3u8?strm=rtmp&qual=2
# 1.57 - Index.html enhancements
# 1.56 - Addition of TVH proxy core role to this proxy, will disable SSTV to plex live though
# 1.55 - Addition of Static m3u8
# 1.54 - Adjustment to kodi dynamic url links and fix to external hls usage.
# 1.53 - Sports only epg available at /sports.xml
# 1.52 - Addition of External Port
# 1.51 - Inclusion of an m3u8 merger to add another m3u8 files contents to the end of the kodi.m3u8 playlist result is called combined.m3u8 refer advanced settings.
# 1.50 - GUI Redesign
# 1.47 - TVH scanning fixed.
# 1.46 - REmoved startup gui from mac and linux exes, fixed linux url
# 1.45 - Added restart required message, Change of piping checks, manual trigger now for easy mux detection (forcing channel 1), use 'python sstvproxy install'
# 1.44 - Change of initial launch to use the gui, if not desired launch with 'python sstvproxy.py headless'. Added adv settings parsing see advancedsettings.json for example
# 1.43 - Bugfix settings menu
# 1.42 - External Playlist added, version check and download added
# 1.41 - Bug fix and switch put on network discovery
# 1.40 - Settings menu added to /index.html
# 1.37 - Network Discovery fixed hopefully
# 1.36 - Two path bug fixes
# 1.35 - Mac addon path fix and check
# 1.34 - Fixed Plex Discovery, TVH file creation fix and addition of writing of genres and template files
# 1.33 - Typo
# 1.32 - Change server name dots to hyphens.
# 1.31 - Tidying
# 1.3 - EPG - Changed zap2it references to the channel number for better readability in clients that use that field as the channel name. As a result the epgs from both sources share the same convention. Playlist generators adjusted to suit.
# 1.2 - TVH Completion and install
# 1.1 - Refactoring and TVH inclusion
# 1.0 - Initial post testing release
############################################################
# Logging
############################################################
# Setup logging
log_formatter = logging.Formatter(
'%(asctime)s - %(levelname)-10s - %(name)-10s - %(funcName)-25s- %(message)s')
logger = logging.getLogger('SmoothStreamsProxy v' + str(__version__))
logger.setLevel(logging.DEBUG)
logging.getLogger('werkzeug').setLevel(logging.ERROR)
# Console logging
console_handler = logging.StreamHandler()
if args.debug:
console_handler.setLevel(logging.DEBUG)
else:
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(log_formatter)
logger.addHandler(console_handler)
# Rotating Log Files
if not os.path.isdir(os.path.join(os.path.dirname(sys.argv[0]), 'cache')):
os.mkdir(os.path.join(os.path.dirname(sys.argv[0]), 'cache'))
file_handler = RotatingFileHandler(os.path.join(os.path.dirname(sys.argv[0]), 'cache', 'status.log'),
maxBytes=1024 * 1024 * 2,
backupCount=5)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)
USERAGENT = 'YAP - %s - %s - %s' % (sys.argv[0], platform.system(), str(__version__))
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USERAGENT)]
urllib.request.install_opener(opener)
type = ""
latestfile = "https://raw.githubusercontent.com/vorghahn/sstvProxy/master/sstvProxy.py"
if not sys.argv[0].endswith('.py'):
if platform.system() == 'Linux':
type = "Linux/"
latestfile = "https://raw.githubusercontent.com/vorghahn/sstvProxy/master/Linux/sstvProxy"
elif platform.system() == 'Windows':
type = "Windows/"
latestfile = "https://raw.githubusercontent.com/vorghahn/sstvProxy/master/Windows/sstvproxy.exe"
elif platform.system() == 'Darwin':
type = "Macintosh/"
latestfile = "https://raw.githubusercontent.com/vorghahn/sstvProxy/master/Macintosh/sstvproxy"
url = "https://raw.githubusercontent.com/vorghahn/sstvProxy/master/%sversion.txt" % type
try:
latest_ver = float(json.loads(urllib.request.urlopen(url).read().decode('utf-8'))['Version'])
except:
latest_ver = float(0.0)
logger.info("Latest version check failed, check internet.")
token = {
'hash': '',
'expires': ''
}
playlist = ""
class channelinfo:
epg = ""
description = ""
channum = 0
channame = ""
class programinfo:
description = ""
channel = 0
channelname = ""
height = 0
startTime = 0
endTime = 0
timeRange = ""
_title = ""
_category = ""
_quality = ""
_language = ""
def get_title(self):
if len(self._title) == 0:
return ("none " + self.timeRange).strip()
else:
return (self._title + " " + self.quality + " " + self.timeRange).replace(" ", " ").strip()
def set_title(self, title):
self._title = title
if len(self._category) == 0 or self._category == "TVShows":
if title.startswith("NHL") or "hockey" in title.lower():
self._category = "Ice Hockey"
elif title.startswith("UEFA") or title.startswith("EPL") or title.startswith(
"Premier League") or title.startswith("La Liga") or title.startswith(
"Bundesliga") or title.startswith(
"Serie A") or "soccer" in title.lower():
self._category = "World Football"
elif title.startswith("MLB") or "baseball" in title.lower():
self._category = "Baseball"
elif title.startswith("MMA") or title.startswith("UFC") or "boxing" in title.lower():
self._category = "Boxing + MMA"
elif title.startswith("NCAAF") or title.startswith("CFB"):
self._category = "NCAAF"
elif title.startswith("ATP") or "tennis" in title.lower():
self._category = "Tennis"
elif title.startswith("WWE"):
self._category = "Wrestling"
elif title.startswith("NFL") or title.startswith("NBA"):
self._category = title.split(" ")[0].replace(":", "").strip()
elif 'nba' in title.lower() or 'nbl' in title.lower() or 'ncaam' in title.lower() or 'basketball' in title.lower():
self._category = "Basketball"
elif 'nfl' in title.lower() or 'football' in title.lower() or 'american football' in title.lower() or 'ncaaf' in title.lower() or 'cfb' in title.lower():
self._category = "Football"
elif 'EPL' in title or 'efl' in title.lower() or 'soccer' in title.lower() or 'ucl' in title.lower() or 'mls' in title.lower() or 'uefa' in title.lower() or 'fifa' in title.lower() or 'fc' in title.lower() or 'la liga' in title.lower() or 'serie a' in title.lower() or 'wcq' in title.lower():
self._category = "Soccer"
elif 'rugby' in title.lower() or 'nrl' in title.lower() or 'afl' in title.lower():
self._category = "Rugby"
elif 'cricket' in title.lower() or 't20' in title.lower():
self._category = "Cricket"
elif 'tennis' in title.lower() or 'squash' in title.lower() or 'atp' in title.lower():
self._category = "Tennis/Squash"
elif 'f1' in title.lower() or 'nascar' in title.lower() or 'motogp' in title.lower() or 'racing' in title.lower():
self._category = "Motor Sport"
elif 'golf' in title.lower() or 'pga' in title.lower():
self._category = "Golf"
elif 'boxing' in title.lower() or 'mma' in title.lower() or 'ufc' in title.lower() or 'wrestling' in title.lower() or 'wwe' in title.lower():
self._category = "Martial Sports"
elif 'hockey' in title.lower() or 'nhl' in title.lower() or 'ice hockey' in title.lower():
self._category = "Ice Hockey"
elif 'baseball' in title.lower() or 'mlb' in title.lower() or 'beisbol' in title.lower() or 'minor league' in title.lower():
self._category = "Baseball"
elif 'news' in title.lower():
self._category = "News"
title = property(get_title, set_title)
def get_category(self):
if (len(self._category) == 0 or self._category == "none") and (
self.title.lower().find("news") or self.description.lower().find("news")) > -1:
return "News"
else:
return self._category
def set_category(self, category):
if category == "tv":
self._category = ""
else:
self._category = category
category = property(get_category, set_category)
def get_language(self):
return self._language
def set_language(self, language):
if language.upper() == "US" or language.upper() == "EN":
self._language = ""
else:
self._language = language.upper()
language = property(get_language, set_language)
def get_quality(self):
return self._quality
def set_quality(self, quality):
if quality.endswith("x1080"):
self._quality = "1080i"
self.height = 1080
elif quality.endswith("x720") or quality.lower() == "720p":
self._quality = "720p"
self.height = 720
elif quality.endswith("x540") or quality.lower() == "hqlq":
self._quality = "540p"
self.height = 540
elif quality.find("x") > 2:
self._quality = quality
self.height = int(quality.split("x")[1])
else:
self._quality = quality
self.height = 0
quality = property(get_quality, set_quality)
def get_album(self):
if self._quality.upper() == "HQLQ" and self.channelname.upper().find(" 720P") > -1:
self._quality = "720p"
return (self._category + " " + self.quality + " " + self._language).strip().replace(" ", " ")
album = property(get_album)
class EST5EDT(dt.tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-5) + self.dst(dt)
def utc_seconds(self):
return self.utcoffset(datetime.now()).total_seconds()
def dst(self, dt):
d = datetime(dt.year, 3, 8) # 2nd Sunday in March
self.dston = d + timedelta(days=6 - d.weekday())
d = datetime(dt.year, 11, 1) # 1st Sunday in Nov
self.dstoff = d + timedelta(days=6 - d.weekday())
if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
return timedelta(hours=1)
else:
return timedelta(0)
def tzname(self, dt):
return 'EST5EDT'
############################################################
# CONFIG
############################################################
# These are just defaults, place your settings in a file called proxysettings.json in the same directory
USER = ""
PASS = ""
SITE = "viewstvn"
SRVR = "dnaw1"
SRVR_SPARE = "dnaw1"
AUTO_SERVER = False
CHECK_CHANNEL = True
STRM = "hls"
QUAL = "1"
QUALLIMIT = 70
LISTEN_IP = "127.0.0.1"
LISTEN_PORT = 6969
SERVER_HOST = "http://" + LISTEN_IP + ":" + str(LISTEN_PORT)
SERVER_PATH = "sstv"
KODIPORT = 8080
EXTIP = "127.0.0.1"
EXTPORT = 80
EXT_HOST = "http://" + EXTIP + ":" + str(EXTPORT)
KODIUSER = "kodi"
KODIPASS = ""
EXTM3URL = ''
EXTM3UNAME = ''
EXTM3UFILE = ''
EXTXMLURL = ''
TVHREDIRECT = False
TVHURL = '127.0.0.1'
TVHUSER = ''
TVHPASS = ''
OVRXML = ''
tvhWeight = 300 # subscription priority
tvhstreamProfile = 'pass' # specifiy a stream profile that you want to use for adhoc transcoding in tvh, e.g. mp4
GUIDELOOKAHEAD = 5 # minutes
PIPE = False
CHANAPI = None
FALLBACK = False
# LINUX/WINDOWS
if platform.system() == 'Linux':
FFMPEGLOC = '/usr/bin/ffmpeg'
if os.path.isdir(os.path.join(os.path.expanduser("~"), '.kodi', 'userdata', 'addon_data', 'pvr.iptvsimple')):
ADDONPATH = os.path.join(os.path.expanduser("~"), '.kodi', 'userdata', 'addon_data', 'pvr.iptvsimple')
else:
ADDONPATH = False
elif platform.system() == 'Windows':
FFMPEGLOC = os.path.join('C:\FFMPEG', 'bin', 'ffmpeg.exe')
if os.path.isdir(os.path.join(os.path.expanduser("~"), 'AppData', 'Roaming', 'Kodi', 'userdata', 'addon_data',
'pvr.iptvsimple')):
ADDONPATH = os.path.join(os.path.expanduser("~"), 'AppData', 'Roaming', 'Kodi', 'userdata', 'addon_data',
'pvr.iptvsimple')
else:
ADDONPATH = False
elif platform.system() == 'Darwin':
FFMPEGLOC = '/usr/local/bin/ffmpeg'
if os.path.isdir(
os.path.join(os.path.expanduser("~"), "Library", "Application Support", 'Kodi', 'userdata', 'addon_data',
'pvr.iptvsimple')):
ADDONPATH = os.path.join(os.path.expanduser("~"), "Library", "Application Support", 'Kodi', 'userdata',
'addon_data', 'pvr.iptvsimple')
else:
ADDONPATH = False
else:
print("Unknown OS detected... proxy may not function correctly")
############################################################
# INIT
############################################################
serverList = [
[' EU-Mix', 'deu'],
[' DE-Frankfurt', 'deu-de'],
[' FR-Paris', 'deu-fr1'],
[' NL-Mix', 'deu-nl'],
[' NL-1', 'deu-nl1'],
[' NL-2', 'deu-nl2'],
[' NL-3 Ams', 'deu-nl3'],
[' NL-4 Breda', 'deu-nl4'],
[' NL-5 Enschede', 'deu-nl5'],
[' UK-Mix', 'deu-uk'],
[' UK-London1', 'deu-uk1'],
[' UK-London2', 'deu-uk2'],
[' US-Mix', 'dna'],
[' East-Mix', 'dnae'],
[' West-Mix', 'dnaw'],
[' East-NJ', 'dnae1'],
[' East-VA', 'dnae2'],
# [' East-Mtl', 'dnae3'],
# [' East-Tor', 'dnae4'],
[' East-ATL', 'dnae5'],
[' East-NY', 'dnae6'],
[' West-Phx', 'dnaw1'],
[' West-LA', 'dnaw2'],
[' West-SJ', 'dnaw3'],
[' West-Chi', 'dnaw4'],
['Asia', 'dap'],
[' Asia1', 'dap1'],
[' Asia2', 'dap2'],
[' Asia3', 'dap3'],
[' Asia-Old', 'dsg']
]
vaders_channels = {"1": "2499", "2": "2500", "3": "2501", "4": "2502", "5": "2503", "6": "2504", "7": "2505",
"8": "2506", "9": "2507", "10": "2508", "11": "2509", "12": "2510", "13": "2511", "14": "2512",
"15": "2513", "16": "2514", "17": "2515", "18": "2516", "19": "2517", "20": "2518", "21": "2519",
"22": "2520", "23": "2521", "24": "2522", "25": "2523", "26": "2524", "27": "2525", "28": "2526",
"29": "2527", "30": "2528", "31": "2529", "32": "2530", "33": "2531", "34": "2532", "35": "2533",
"36": "2534", "37": "2535", "38": "2536", "39": "2537", "40": "2538", "41": "2541", "42": "2542",
"43": "2543", "44": "2544", "45": "2545", "46": "2546", "47": "2547", "48": "2548", "49": "2549",
"50": "2550", "51": "2551", "52": "2552", "53": "2553", "54": "2554", "55": "2555", "56": "2556",
"57": "2557", "58": "2606", "59": "2607", "60": "2608", "61": "2609", "62": "2610", "63": "2611",
"64": "2612", "65": "2613", "66": "2614", "67": "2615", "68": "2616", "69": "2617", "70": "2618",
"71": "2619", "72": "2620", "73": "2622", "74": "2621", "75": "2623", "76": "2624", "77": "2625",
"78": "2626", "79": "2627", "80": "2628", "81": "2629", "82": "2630", "83": "2631", "84": "2632",
"85": "2633", "86": "2634", "87": "2635", "88": "2636", "89": "2637", "90": "2638", "91": "2639",
"92": "2640", "93": "2641", "94": "2642", "95": "2643", "96": "2644", "97": "2645", "98": "2646",
"99": "2647", "100": "2648", "101": "2649", "102": "2650", "103": "2651", "104": "2652",
"105": "2653", "106": "2654", "107": "2655", "108": "2656", "109": "2657", "110": "2658",
"111": "2659", "112": "2660", "113": "2661", "114": "2662", "115": "2663", "116": "2664",
"117": "2665", "118": "2666", "119": "2667", "120": "2668", "121": "47381", "122": "2679",
"123": "2680", "124": "2681", "125": "2682", "126": "47376", "127": "47377", "128": "47378",
"129": "47379", "130": "47380", "131": "47718", "132": "47719", "133": "49217", "134": "50314",
"135": "50315", "136": "50319", "137": "50320", "138": "50321", "139": "50322", "141": "49215",
"140": "50394", "142": "49216", "143": "50395", "144": "50396", "145": "50397", "146": "50398",
"147": "50399", "148": "47707", "149": "47670", "150": "47716"}
providerList = [
['Live247', 'view247'],
['Mystreams', 'vaders'],
['StarStreams', 'viewss'],
['StreamTVnow', 'viewstvn'],
['MMA-TV/MyShout', 'viewmmasr']
]
streamtype = ['hls', 'hlsa', 'rtmp', 'mpegts', 'rtsp', 'dash', 'wss']
qualityList = [
['HD', '1'],
['HQ', '2'],
['LQ', '3']
]
STREAM_INFO = {'hls': {'domain': 'https', 'port': '443', 'playlist': '.stream/playlist.m3u8', 'quality': 'standard'},
'hlsa': {'domain': 'https', 'port': '443', 'playlist': '/playlist.m3u8', 'quality': '.smil'},
'rtmp': {'domain': 'rtmp', 'port': '3625', 'playlist': '.stream', 'quality': 'standard'},
'mpegts': {'domain': 'https', 'port': '443', 'playlist': '.stream/mpeg.2ts', 'quality': 'standard'},
'rtsp': {'domain': 'rtsp', 'port': '2935', 'playlist': '.stream', 'quality': 'standard'},
'dash': {'domain': 'https', 'port': '443', 'playlist': '/manifest.mpd', 'quality': '.smil'},
'wss': {'domain': 'wss', 'port': '443', 'playlist': '.stream', 'quality': 'standard'},
'wssa': {'domain': 'wss', 'port': '443', 'playlist': '', 'quality': '.smil'}
}
def adv_settings():
if os.path.isfile(os.path.join(os.path.dirname(sys.argv[0]), 'advancedsettings.json')):
logger.debug("Parsing advanced settings")
with open(os.path.join(os.path.dirname(sys.argv[0]), 'advancedsettings.json')) as advset:
advconfig = load(advset)
if "kodiuser" in advconfig:
logger.debug("Overriding kodi username")
global KODIUSER
KODIUSER = advconfig["kodiuser"]
if "kodipass" in advconfig:
logger.debug("Overriding kodi password")
global KODIPASS
KODIPASS = advconfig["kodipass"]
if "ffmpegloc" in advconfig:
logger.debug("Overriding ffmpeg location")
global FFMPEGLOC
FFMPEGLOC = advconfig["ffmpegloc"]
if "kodiport" in advconfig:
logger.debug("Overriding kodi port")
global KODIPORT
KODIPORT = advconfig["kodiport"]
if "extram3u8url" in advconfig:
logger.debug("Overriding EXTM3URL")
global EXTM3URL
EXTM3URL = advconfig["extram3u8url"]
if "extram3u8name" in advconfig:
logger.debug("Overriding EXTM3UNAME")
global EXTM3UNAME
EXTM3UNAME = advconfig["extram3u8name"]
if "extram3u8file" in advconfig:
logger.debug("Overriding EXTM3UFILE")
global EXTM3UFILE
EXTM3UFILE = advconfig["extram3u8file"]
if "extraxmlurl" in advconfig:
logger.debug("Overriding EXTXMLURL")
global EXTXMLURL
EXTXMLURL = advconfig["extraxmlurl"]
if "tvhredirect" in advconfig:
logger.debug("Overriding tvhredirect")
global TVHREDIRECT
TVHREDIRECT = advconfig["tvhredirect"]
if "tvhaddress" in advconfig:
logger.debug("Overriding tvhaddress")
global TVHURL
TVHURL = advconfig["tvhaddress"]
if "tvhuser" in advconfig:
logger.debug("Overriding tvhuser")
global TVHUSER
TVHUSER = advconfig["tvhuser"]
if "tvhpass" in advconfig:
logger.debug("Overriding tvhpass")
global TVHPASS
TVHPASS = advconfig["tvhpass"]
if "overridexml" in advconfig:
logger.debug("Overriding XML")
global OVRXML
OVRXML = advconfig["overridexml"]
if "checkchannel" in advconfig:
logger.debug("Overriding CheckChannel")
global CHECK_CHANNEL
CHECK_CHANNEL = advconfig["checkchannel"] == "True"
if "pipe" in advconfig:
logger.debug("Overriding Pipe")
global PIPE
PIPE = advconfig["pipe"] == "True"
def load_settings():
global QUAL, QUALLIMIT, USER, PASS, SRVR, SRVR_SPARE, SITE, STRM, KODIPORT, LISTEN_IP, LISTEN_PORT, SERVER_HOST, EXTIP, EXT_HOST, EXTPORT
if not os.path.isfile(os.path.join(os.path.dirname(sys.argv[0]), 'proxysettings.json')):
logger.debug("No config file found.")
try:
logger.debug("Parsing settings")
with open(os.path.join(os.path.dirname(sys.argv[0]), 'proxysettings.json')) as jsonConfig:
config = {}
config = load(jsonConfig)
if "quality" in config:
QUAL = config["quality"]
if "username" in config:
USER = config["username"]
if "password" in config:
PASS = config["password"]
if "server" in config:
SRVR = config["server"]
if "server_spare" in config:
SRVR_SPARE = config["server_spare"]
if "service" in config:
SITE = config["service"]
if SITE == "mmatv":
SITE = "viewmmasr"
if "stream" in config:
STRM = config["stream"]
if "kodiport" in config:
KODIPORT = config["kodiport"]
if "externalip" in config:
EXTIP = config["externalip"]
if "externalport" in config:
EXTPORT = config["externalport"]
if "ip" in config and "port" in config:
LISTEN_IP = config["ip"]
LISTEN_PORT = config["port"]
SERVER_HOST = "http://" + LISTEN_IP + ":" + str(LISTEN_PORT)
EXT_HOST = "http://" + EXTIP + ":" + str(EXTPORT)
logger.debug("Using config file.")
except:
if HEADLESS:
config = {}
config["username"] = input("Username?")
USER = config["username"]
config["password"] = input("Password?")
PASS = config["password"]
os.system('cls' if os.name == 'nt' else 'clear')
print("Type the number of the item you wish to select:")
for i in providerList:
print(providerList.index(i), providerList[providerList.index(i)][0])
config["service"] = providerList[int(input("Provider name?"))][1]
os.system('cls' if os.name == 'nt' else 'clear')
SITE = config["service"]
print("Type the number of the item you wish to select:")
for i in serverList:
print(serverList.index(i), serverList[serverList.index(i)][0])
result = input("Regional Server name? (or type 'auto')")
if result.lower() == 'auto':
testServers()
config["server"] = SRVR
config["server_spare"] = SRVR_SPARE
else:
config["server"] = serverList[int(result)][1]
os.system('cls' if os.name == 'nt' else 'clear')
for i in serverList:
print(serverList.index(i), serverList[serverList.index(i)][0])
result = input("Backup Regional Server name?")
config["server_spare"] = serverList[int(result)][1]
os.system('cls' if os.name == 'nt' else 'clear')
print("Type the number of the item you wish to select:")
for i in streamtype:
print(streamtype.index(i), i)
config["stream"] = streamtype[int(input("Dynamic Stream Type? (HLS/RTMP)"))]
os.system('cls' if os.name == 'nt' else 'clear')
for i in qualityList:
print(qualityList.index(i), qualityList[qualityList.index(i)][0])
config["quality"] = qualityList[int(input("Stream quality?"))][1]
os.system('cls' if os.name == 'nt' else 'clear')
config["ip"] = input("Listening IP address?(ie recommend 127.0.0.1 for beginners)")
config["port"] = int(input("and port?(ie 99, do not use 8080)"))
os.system('cls' if os.name == 'nt' else 'clear')
config["externalip"] = input("External IP?")
config["externalport"] = int(input("and ext port?(ie 99, do not use 8080)"))
os.system('cls' if os.name == 'nt' else 'clear')
QUAL = config["quality"]
SRVR = config["server"]
STRM = config["stream"]
LISTEN_IP = config["ip"]
LISTEN_PORT = config["port"]
EXTIP = config["externalip"]
EXTPORT = config["externalport"]
SERVER_HOST = "http://" + LISTEN_IP + ":" + str(LISTEN_PORT)
EXT_HOST = "http://" + EXTIP + ":" + str(EXTPORT)
with open(os.path.join(os.path.dirname(sys.argv[0]), 'proxysettings.json'), 'w') as fp:
dump(config, fp)
else:
root = tkinter.Tk()
root.title("YAP Setup")
# root.geometry('750x600')
app = GUI(root) # calling the class to run
root.mainloop()
installer()
adv_settings()
if args.install:
installer()
############################################################
# INSTALL
############################################################
def installer():
if os.path.isfile(os.path.join('/usr', 'bin', 'tv_find_grabbers')):
writetvGrabFile()
os.chmod('/usr/bin/tv_grab_sstv', 0o777)
proc = subprocess.Popen("/usr/bin/tv_find_grabbers")
if os.path.isdir(ADDONPATH):
writesettings()
writegenres()
if not os.path.isdir(os.path.join(os.path.dirname(sys.argv[0]), 'Templates')):
os.mkdir(os.path.join(os.path.dirname(sys.argv[0]), 'Templates'))
writetemplate()
def writetvGrabFile():
f = open(os.path.join('/usr', 'bin', 'tv_grab_sstv'), 'w')
tvGrabFile = '''#!/bin/sh
dflag=
vflag=
cflag=
#Save this file into /usr/bin ensure HTS user has read/write and the file is executable
URL="%s/%s/epg.xml"
DESCRIPTION="SmoothStreamsTV"
VERSION="1.1"
if [ $# -lt 1 ]; then
wget -q -O - $URL
exit 0
fi
for a in "$@"; do
[ "$a" = "-d" -o "$a" = "--description" ] && dflag=1
[ "$a" = "-v" -o "$a" = "--version" ] && vflag=1
[ "$a" = "-c" -o "$a" = "--capabilities" ] && cflag=1
done
if [ -n "$dflag" ]; then
echo $DESCRIPTION
fi
if [ -n "$vflag" ]; then
echo $VERSION
fi
if [ -n "$cflag" ]; then
echo "baseline"
fi''' % (SERVER_HOST, SERVER_PATH)
f.write(tvGrabFile)
f.close()
# lazy install, low priority
def writesettings():
f = open(os.path.join(ADDONPATH, 'settings.xml'), 'w')
xmldata = """<settings>
<setting id="epgCache" value="false" />
<setting id="epgPath" value="" />
<setting id="epgPathType" value="1" />
<setting id="epgTSOverride" value="true" />
<setting id="epgTimeShift" value="0.0" />
<setting id="epgUrl" value="%s/%s/epg.xml" />
<setting id="logoBaseUrl" value="" />
<setting id="logoFromEpg" value="1" />
<setting id="logoPath" value="" />
<setting id="logoPathType" value="1" />
<setting id="m3uCache" value="true" />
<setting id="m3uPath" value="" />
<setting id="m3uPathType" value="1" />
<setting id="m3uUrl" value="%s/%s/kodi.m3u8" />
<setting id="sep1" value="" />
<setting id="sep2" value="" />
<setting id="sep3" value="" />
<setting id="startNum" value="1" />
</settings>""" % (SERVER_HOST, SERVER_PATH, SERVER_HOST, SERVER_PATH)
f.write(xmldata)
f.close()
def writegenres():
f = open(os.path.join(ADDONPATH, 'genres.xml'), 'w')
xmldata = """<genres>
<!---UNDEFINED--->
<genre type="00">Undefined</genre>
<!---MOVIE/DRAMA--->
<genre type="16">Movie/Drama</genre>
<genre type="16" subtype="01">Detective/Thriller</genre>
<genre type="16" subtype="02">Adventure/Western/War</genre>
<genre type="16" subtype="03">Science Fiction/Fantasy/Horror</genre>
<genre type="16" subtype="04">Comedy</genre>
<genre type="16" subtype="05">Soap/Melodrama/Folkloric</genre>
<genre type="16" subtype="06">Romance</genre>
<genre type="16" subtype="07">Serious/Classical/Religious/Historical Movie/Drama</genre>
<genre type="16" subtype="08">Adult Movie/Drama</genre>
<!---NEWS/CURRENT AFFAIRS--->
<genre type="32">News/Current Affairs</genre>
<genre type="32" subtype="01">News/Weather Report</genre>
<genre type="32" subtype="02">News Magazine</genre>
<genre type="32" subtype="03">Documentary</genre>
<genre type="32" subtype="04">Discussion/Interview/Debate</genre>
<!---SHOW--->
<genre type="48">Show/Game Show</genre>
<genre type="48" subtype="01">Game Show/Quiz/Contest</genre>
<genre type="48" subtype="02">Variety Show</genre>
<genre type="48" subtype="03">Talk Show</genre>
<!---SPORTS--->
<genre type="64">Sports</genre>
<genre type="64" subtype="01">Special Event</genre>
<genre type="64" subtype="02">Sport Magazine</genre>
<genre type="96" subtype="03">Football</genre>
<genre type="144">Tennis/Squash</genre>
<genre type="64" subtype="05">Team Sports</genre>
<genre type="64" subtype="06">Athletics</genre>
<genre type="160">Motor Sport</genre>
<genre type="64" subtype="08">Water Sport</genre>
<genre type="64" subtype="09">Winter Sports</genre>
<genre type="64" subtype="10">Equestrian</genre>
<genre type="176">Martial Sports</genre>
<genre type="16">Basketball</genre>
<genre type="32">Baseball</genre>
<genre type="48">Soccer</genre>
<genre type="80">Ice Hockey</genre>
<genre type="112">Golf</genre>
<genre type="128">Cricket</genre>
<!---CHILDREN/YOUTH--->
<genre type="80">Children's/Youth Programmes</genre>
<genre type="80" subtype="01">Pre-school Children's Programmes</genre>
<genre type="80" subtype="02">Entertainment Programmes for 6 to 14</genre>
<genre type="80" subtype="03">Entertainment Programmes for 16 to 16</genre>
<genre type="80" subtype="04">Informational/Educational/School Programme</genre>
<genre type="80" subtype="05">Cartoons/Puppets</genre>
<!---MUSIC/BALLET/DANCE--->
<genre type="96">Music/Ballet/Dance</genre>
<genre type="96" subtype="01">Rock/Pop</genre>
<genre type="96" subtype="02">Serious/Classical Music</genre>
<genre type="96" subtype="03">Folk/Traditional Music</genre>
<genre type="96" subtype="04">Musical/Opera</genre>
<genre type="96" subtype="05">Ballet</genre>
<!---ARTS/CULTURE--->
<genre type="112">Arts/Culture</genre>
<genre type="112" subtype="01">Performing Arts</genre>
<genre type="112" subtype="02">Fine Arts</genre>
<genre type="112" subtype="03">Religion</genre>
<genre type="112" subtype="04">Popular Culture/Traditional Arts</genre>
<genre type="112" subtype="05">Literature</genre>
<genre type="112" subtype="06">Film/Cinema</genre>
<genre type="112" subtype="07">Experimental Film/Video</genre>
<genre type="112" subtype="08">Broadcasting/Press</genre>
<genre type="112" subtype="09">New Media</genre>
<genre type="112" subtype="10">Arts/Culture Magazines</genre>
<genre type="112" subtype="11">Fashion</genre>
<!---SOCIAL/POLITICAL/ECONOMICS--->
<genre type="128">Social/Political/Economics</genre>
<genre type="128" subtype="01">Magazines/Reports/Documentary</genre>
<genre type="128" subtype="02">Economics/Social Advisory</genre>
<genre type="128" subtype="03">Remarkable People</genre>
<!---EDUCATIONAL/SCIENCE--->
<genre type="144">Education/Science/Factual</genre>
<genre type="144" subtype="01">Nature/Animals/Environment</genre>
<genre type="144" subtype="02">Technology/Natural Sciences</genre>
<genre type="144" subtype="03">Medicine/Physiology/Psychology</genre>
<genre type="144" subtype="04">Foreign Countries/Expeditions</genre>
<genre type="144" subtype="05">Social/Spiritual Sciences</genre>
<genre type="144" subtype="06">Further Education</genre>
<genre type="144" subtype="07">Languages</genre>
<!---LEISURE/HOBBIES--->
<genre type="160">Leisure/Hobbies</genre>
<genre type="160" subtype="01">Tourism/Travel</genre>
<genre type="160" subtype="02">Handicraft</genre>
<genre type="160" subtype="03">Motoring</genre>
<genre type="160" subtype="04">Fitness & Health</genre>
<genre type="160" subtype="05">Cooking</genre>
<genre type="160" subtype="06">Advertisement/Shopping</genre>
<genre type="160" subtype="07">Gardening</genre>
<!---SPECIAL--->
<genre type="176">Special Characteristics</genre>
<genre type="176" subtype="01">Original Language</genre>
<genre type="176" subtype="02">Black & White</genre>
<genre type="176" subtype="03">Unpublished</genre>
<genre type="176" subtype="04">Live Broadcast</genre>
</genres>"""
f.write(xmldata)
f.close()
def writetemplate():
f = open(os.path.join(os.path.dirname(sys.argv[0]), 'Templates', 'device.xml'), 'w')
xmldata = """<root xmlns="urn:schemas-upnp-org:device-1-0">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<URLBase>{{ data.BaseURL }}</URLBase>
<device>
<deviceType>urn:schemas-upnp-org:device:MediaServer:1</deviceType>
<friendlyName>{{ data.FriendlyName }}</friendlyName>
<manufacturer>{{ data.Manufacturer }}</manufacturer>
<modelName>{{ data.ModelNumber }}</modelName>
<modelNumber>{{ data.ModelNumber }}</modelNumber>
<serialNumber></serialNumber>
<UDN>uuid:{{ data.DeviceID }}</UDN>
</device>
</root>"""
f.write(xmldata)
f.close()
############################################################
# INSTALL GUI
############################################################
if not HEADLESS:
class ToggledFrame(tkinter.Frame):
def __init__(self, parent, text="", *args, **options):
tkinter.Frame.__init__(self, parent, *args, **options)
self.show = tkinter.IntVar()
self.show.set(0)
self.title_frame = tkinter.Frame(self)
self.title_frame.pack(fill="x", expand=1)
tkinter.Label(self.title_frame, text=text).pack(side="left", fill="x", expand=1)
self.toggle_button = tkinter.Checkbutton(self.title_frame, width=2, text='+', command=self.toggle,
variable=self.show)
self.toggle_button.pack(side="left")
self.sub_frame = tkinter.Frame(self, relief="sunken", borderwidth=1)
def toggle(self):
if bool(self.show.get()):
self.sub_frame.pack(fill="x", expand=1)
self.toggle_button.configure(text='-')
else:
self.sub_frame.forget()
self.toggle_button.configure(text='+')
class GUI(tkinter.Frame):
def client_exit(self, root):
root.destroy()
def __init__(self, master):
tkinter.Frame.__init__(self, master)
self.t1 = tkinter.StringVar()
self.t1.set("Minimum Settings")
t1 = tkinter.Label(master, textvariable=self.t1, height=2)
t1.grid(row=1, column=2)
self.labelUsername = tkinter.StringVar()
self.labelUsername.set("Username")
labelUsername = tkinter.Label(master, textvariable=self.labelUsername, height=2)
labelUsername.grid(row=2, column=1)
#
userUsername = tkinter.StringVar()
userUsername.set("[email protected]")
self.username = tkinter.Entry(master, textvariable=userUsername, width=30)
self.username.grid(row=2, column=2)
#
self.noteUsername = tkinter.StringVar()
self.noteUsername.set("mystreams will not be an email address")
noteUsername = tkinter.Label(master, textvariable=self.noteUsername, height=2)
noteUsername.grid(row=2, column=3)