-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserviceLib.py
1255 lines (1048 loc) · 51 KB
/
serviceLib.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 python
# -*- coding: utf-8 -*-
# GNU General Public License
# m-TVGuide KODI Addon
# Copyright (C) 2018 Mariusz89B
# Copyright (C) 2016 Andrzej Mleczko
# 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 https://www.gnu.org/licenses.
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import unicode_literals
import sys
if sys.version_info[0] > 2:
PY3 = True
else:
PY3 = False
if PY3:
import urllib.request, urllib.error, urllib.parse, http.client, http.cookiejar
else:
import urllib, urllib2, httplib
import cookielib
import os, sys, io, re, socket, copy, threading
import time, datetime
import xbmc, xbmcgui, xbmcvfs
from unidecode import unidecode
from xml.etree import ElementTree
from collections import OrderedDict
from strings import *
from groups import *
import simplejson as json
import strings as strings2
import zlib
import json
import codecs
try:
import ssl
except:
pass
if PY3:
urllibURLError = urllib.error.URLError
urllibHTTPError = urllib.error.HTTPError
httplibBadStatusLine = http.client.BadStatusLine
httplibIncompleteRead = http.client.IncompleteRead
else:
urllibURLError = urllib2.URLError
urllibHTTPError = urllib2.HTTPError
httplibBadStatusLine = httplib.BadStatusLine
httplibIncompleteRead = httplib.IncompleteRead
HOST = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.50'
pathAddons = os.path.join(ADDON.getAddonInfo('path'), 'resources', 'addons.ini')
pathMapBase = os.path.join(ADDON.getAddonInfo('path'), 'resources')
if PY3:
try:
PROFILE_PATH = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))
except:
PROFILE_PATH = xbmcvfs.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
else:
try:
PROFILE_PATH = xbmc.translatePath(ADDON.getAddonInfo('profile'))
except:
PROFILE_PATH = xbmc.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
if PY3:
try:
pathMapExtraBase = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))
except:
pathMapExtraBase = xbmcvfs.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
else:
try:
pathMapExtraBase = xbmc.translatePath(ADDON.getAddonInfo('profile'))
except:
pathMapExtraBase = xbmc.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
onlineMapPathBase = M_TVGUIDE_SUPPORT + 'maps/'
try:
MAX_CONNECTION_TIME = int(ADDON.getSetting('max_connection_time'))
except:
MAX_CONNECTION_TIME = 30
HTTP_ConnectionTimeout = 10
PREDEFINED_CATEGORIES = []
BASE_LIST = []
CC_DICT = ccDict()
for k, v in CC_DICT.items():
cc = ADDON.getSetting('country_code_{}'.format(k.lower()))
if cc == 'true' and cc != '':
BASE_LIST.append(k)
if k == 'all':
all_channels = strings(30325)
PREDEFINED_CATEGORIES.append(all_channels)
else:
if cc == 'true' and cc != '':
PREDEFINED_CATEGORIES.append(k.upper())
XXX = ADDON.getSetting('XXX_EPG')
if XXX != '' and XXX != 'false':
XXX_EPG = True
else:
XXX_EPG = False
VOD = ADDON.getSetting('VOD_EPG')
if VOD != '' and XXX != 'false':
VOD_EPG = True
else:
VOD_EPG = False
def unidecodeStr(s):
if PY3:
return s
else:
return unidecode(s)
class ShowList:
def __init__(self, logCall=deb):
self.logCall = logCall
def decode(self, string):
json_ustr = json.dumps(string, ensure_ascii=False)
return json_ustr
def JsonToSortedTab(self, json):
strTab = []
outTab = []
for v,k in json.items():
strTab.append(int(v))
strTab.append(k)
outTab.append(strTab)
strTab = []
outTab.sort(key=lambda x: x[0])
return outTab
def getJsonFromAPI(self, url, post={}):
result_json = None
raw_json = None
try:
if PY3:
data = urllib.parse.urlencode(post).encode("utf-8")
reqUrl = urllib.request.Request(url, data)
else:
data = urllib.urlencode(post)
reqUrl = urllib2.Request(url, data)
reqUrl.add_header('User-Agent', HOST)
reqUrl.add_header('Keep-Alive', 'timeout=60')
reqUrl.add_header('Connection', 'Keep-Alive')
reqUrl.add_header('authority', 'raw.githubusercontent.com')
reqUrl.add_header('upgrade-insecure-requests', '1')
startTime = datetime.datetime.now()
while (datetime.datetime.now() - startTime).seconds < MAX_CONNECTION_TIME and strings2.M_TVGUIDE_CLOSING == False:
try:
if PY3:
raw_json = urllib.request.urlopen(reqUrl, timeout = HTTP_ConnectionTimeout)
else:
raw_json = urllib2.urlopen(reqUrl, timeout = HTTP_ConnectionTimeout)
content_json = raw_json.read()
if raw_json.headers.get("Content-Encoding", "") == "gzip":
content_json = zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(content_json)
result_json = json.loads(content_json)
raw_json.close()
break
except (httplibIncompleteRead, socket.timeout) as ex:
self.logCall('ShowList getJsonFromAPI exception: %s - retrying seconds = %s' % (str(ex), (datetime.datetime.now() - startTime).seconds))
except urllibHTTPError as ex:
if ex.code in [500, 408]:
self.logCall('ShowList getJsonFromAPI exception: %s - retrying seconds = %s' % (str(ex), (datetime.datetime.now() - startTime).seconds))
else:
raise
except urllibURLError as ex:
if 'timed out' in str(ex) or 'Timeout' in str(ex):
self.logCall('ShowList getJsonFromAPI exception: %s - retrying seconds = %s' % (str(ex), (datetime.datetime.now() - startTime).seconds))
else:
raise
try:
if raw_json:
raw_json.close()
raw_json = None
except:
pass
if strings2.M_TVGUIDE_CLOSING:
self.logCall('ShowList getJsonFromAPI M_TVGUIDE_CLOSING - aborting!')
break
xbmc.sleep(150)
except (urllibURLError, NameError, ValueError, httplibBadStatusLine) as ex:
self.logCall('ShowList getJsonFromAPI exception: %s - aborting!' % str(ex))
return None
return result_json
def getJsonFromExtendedAPI(self, url, post_data = None, save_cookie = False, load_cookie = False, cookieFile = None, jsonLoadsResult = False, jsonLoadResult = False, customHeaders = None, max_conn_time = MAX_CONNECTION_TIME, getResponseUrl=False, skipSslCertificate=False, json_dumps_post=False, http_timeout=HTTP_ConnectionTimeout, verbose=True):
result_json = None
raw_json = None
customOpeners = []
if PY3:
cj = http.cookiejar.LWPCookieJar()
else:
cj = cookielib.LWPCookieJar()
url = url.replace(' ','%20')
def urlOpen(req, customOpeners):
if skipSslCertificate and sys.version_info >= (2, 7, 9):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
if PY3:
customOpeners += [urllib.request.HTTPSHandler(context=ctx)]
else:
customOpeners += [urllib2.HTTPSHandler(context=ctx)]
if len(customOpeners) > 0:
if PY3:
opener = urllib.request.build_opener( *customOpeners )
else:
opener = urllib2.build_opener( *customOpeners )
response = opener.open(req, timeout = http_timeout)
else:
try:
if PY3:
response = urllib.request.urlopen(req, timeout = http_timeout)
else:
response = urllib2.urlopen(req, timeout = http_timeout)
except:
response = None
return response
try:
if cookieFile is not None:
if PY3:
customOpeners.append( urllib.request.HTTPCookieProcessor(cj) )
else:
customOpeners.append( urllib2.HTTPCookieProcessor(cj) )
if load_cookie == True and cookieFile is not None and os.path.isfile(cookieFile):
cj.load(cookieFile, ignore_discard = True)
if customHeaders is not None:
headers = customHeaders
else:
headers = { 'User-Agent' : HOST }
headers['Keep-Alive'] = 'timeout=60'
headers['Connection'] = 'Keep-Alive'
headers['authority'] = 'raw.githubusercontent.com'
headers['upgrade-insecure-requests'] = '1'
if json_dumps_post:
if PY3:
data = json.dumps(post_data).encode("utf-8")
else:
data = json.dumps(post_data)
elif post_data:
if PY3:
data = urllib.parse.urlencode(post_data).encode("utf-8")
else:
data = urllib.urlencode(post_data)
else:
data = None
if PY3:
reqUrl = urllib.request.Request(url=url, data=data, headers=headers)
else:
reqUrl = urllib2.Request(url=url, data=data, headers=headers)
startTime = datetime.datetime.now()
while (datetime.datetime.now() - startTime).seconds < max_conn_time and strings2.M_TVGUIDE_CLOSING == False:
try:
raw_json = urlOpen(reqUrl, customOpeners)
if raw_json:
if getResponseUrl:
result = raw_json.geturl()
raw_json.close()
return result
result_json = raw_json.read()
if raw_json.headers.get("Content-Encoding", "") == "gzip":
result_json = zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(result_json)
if jsonLoadsResult == True:
result_json = json.loads(result_json)
raw_json.close()
break
else:
result_json = None
return result_json
except (httplibIncompleteRead, socket.timeout) as ex:
if verbose:
self.logCall('ShowList getJsonFromExtendedAPI exception: %s, url: %s - retrying seconds = %s' % (str(ex), url, (datetime.datetime.now() - startTime).seconds))
except urllibHTTPError as ex:
if ex.code in [500, 408]:
if verbose:
self.logCall('ShowList getJsonFromExtendedAPI exception: %s, url: %s - retrying seconds = %s' % (str(ex), url, (datetime.datetime.now() - startTime).seconds))
else:
raise
except urllibURLError as ex:
if 'timed out' in str(ex) or 'Timeout' in str(ex):
if verbose:
self.logCall('ShowList getJsonFromExtendedAPI exception: %s, url: %s - retrying seconds = %s' % (str(ex), url, (datetime.datetime.now() - startTime).seconds))
else:
raise
try:
if raw_json:
raw_json.close()
raw_json = None
except:
pass
if strings2.M_TVGUIDE_CLOSING:
self.logCall('ShowList getJsonFromExtendedAPI M_TVGUIDE_CLOSING - aborting!')
break
xbmc.sleep(150)
if cookieFile is not None and save_cookie == True:
cj.save(cookieFile, ignore_discard = True)
except (urllibURLError, NameError, ValueError, httplibBadStatusLine) as ex:
if verbose:
self.logCall('ShowList getJsonFromExtendedAPI exception: %s - aborting!' % str(ex))
return None
return result_json
def getCookieItem(self, cookiefile, item = None):
ret = ''
if os.path.isfile(cookiefile):
if PY3:
cj = http.cookiejar.LWPCookieJar()
else:
cj = cookielib.LWPCookieJar()
cj.load(cookiefile, ignore_discard = True)
for cookie in cj:
if not item:
ret += '%s=%s;' % (cookie.name, cookie.value)
elif cookie.name == item:
ret = cookie.value
return ret
def downloadUrl(self, url, retryFailed = True):
fileContent = None
try:
if PY3:
reqUrl = urllib.request.Request(url)
else:
reqUrl = urllib2.Request(url)
reqUrl.add_header('User-Agent', HOST)
reqUrl.add_header('Keep-Alive', 'timeout=25')
reqUrl.add_header('authority', 'raw.githubusercontent.com')
reqUrl.add_header('upgrade-insecure-requests', '1')
reqUrl.add_header('Connection', 'Keep-Alive')
if PY3:
urlFile = urllib.request.urlopen(reqUrl, timeout=HTTP_ConnectionTimeout)
else:
urlFile = urllib2.urlopen(reqUrl, timeout=HTTP_ConnectionTimeout)
fileContent = urlFile.read()
urlFile.close()
except Exception as ex:
self.logCall('File download error, exception: %s, url: %s' % (str(ex), url))
fileContent = None
if not strings2.M_TVGUIDE_CLOSING and retryFailed == True and ('HTTP Error 500' in str(ex) or 'HTTP Error 408' in str(ex) or 'timeout' in str(ex) or 'IncompleteRead' in str(ex)):
return self.downloadUrl(url, retryFailed=False)
return fileContent
def parseDOM(self, html, name="", attrs={}, ret=False):
# Copyright (C) 2010-2011 Tobias Ussing And Henrik Mosgaard Jensen
if isinstance(html, str):
try:
html = [html] # Replace with chardet thingy
except:
html = [html]
elif isinstance(html, str):
html = [html]
elif not isinstance(html, list):
return ""
if not name.strip():
return ""
ret_lst = []
for item in html:
temp_item = re.compile('(<[^>]*?\n[^>]*?>)').findall(item)
for match in temp_item:
item = item.replace(match, match.replace("\n", " "))
lst = []
for key in attrs:
lst2 = re.compile('(<' + name + '[^>]*?(?:' + key + '=[\'"]' + attrs[key] + '[\'"].*?>))', re.M | re.S).findall(item)
if len(lst2) == 0 and attrs[key].find(" ") == -1: # Try matching without quotation marks
lst2 = re.compile('(<' + name + '[^>]*?(?:' + key + '=' + attrs[key] + '.*?>))', re.M | re.S).findall(item)
if len(lst) == 0:
lst = lst2
lst2 = []
else:
test = list(range(len(lst)))
test.reverse()
for i in test: # Delete anything missing from the next list.
if not lst[i] in lst2:
del(lst[i])
if len(lst) == 0 and attrs == {}:
lst = re.compile('(<' + name + '>)', re.M | re.S).findall(item)
if len(lst) == 0:
lst = re.compile('(<' + name + ' .*?>)', re.M | re.S).findall(item)
if isinstance(ret, str):
lst2 = []
for match in lst:
attr_lst = re.compile('<' + name + '.*?' + ret + '=([\'"].[^>]*?[\'"])>', re.M | re.S).findall(match)
if len(attr_lst) == 0:
attr_lst = re.compile('<' + name + '.*?' + ret + '=(.[^>]*?)>', re.M | re.S).findall(match)
for tmp in attr_lst:
cont_char = tmp[0]
if cont_char in "'\"":
# Limit down to next variable.
if tmp.find('=' + cont_char, tmp.find(cont_char, 1)) > -1:
tmp = tmp[:tmp.find('=' + cont_char, tmp.find(cont_char, 1))]
# Limit to the last quotation mark
if tmp.rfind(cont_char, 1) > -1:
tmp = tmp[1:tmp.rfind(cont_char)]
else:
if tmp.find(" ") > 0:
tmp = tmp[:tmp.find(" ")]
elif tmp.find("/") > 0:
tmp = tmp[:tmp.find("/")]
elif tmp.find(">") > 0:
tmp = tmp[:tmp.find(">")]
lst2.append(tmp.strip())
lst = lst2
else:
lst2 = []
for match in lst:
endstr = "</" + name
start = item.find(match)
end = item.find(endstr, start)
pos = item.find("<" + name, start + 1 )
while pos < end and pos != -1:
tend = item.find(endstr, end + len(endstr))
if tend != -1:
end = tend
pos = item.find("<" + name, pos + 1)
if start == -1 and end == -1:
temp = ""
elif start > -1 and end > -1:
temp = item[start + len(match):end]
elif end > -1:
temp = item[:end]
elif start > -1:
temp = item[start + len(match):]
if ret:
endstr = item[end:item.find(">", item.find(endstr)) + 1]
temp = match + temp + endstr
item = item[item.find(temp, item.find(match)) + len(temp):]
lst2.append(temp)
lst = lst2
ret_lst += lst
return ret_lst
class TvCid:
def __init__(self, cid, name, title, strm='', catchup='', lic='', dashjs='', beartoken='', tv_client_boot_id='', src='', img=''):
self.cid = cid
self.name = unidecodeStr(name)
self.title = unidecodeStr(title)
self.strm = strm
self.catchup = catchup
self.lic = lic
self.dashjs = dashjs
self.beartoken = beartoken
self.tv_client_boot_id = tv_client_boot_id
self.src = src
self.img = img
self.rtmpdumpLink = None
self.ffmpegdumpLink = None
class MapString:
def __init__(self, channelid, titleRegex, strm, src, displayName=None):
self.channelid = channelid
self.titleRegex = titleRegex
self.strm = strm
self.src = src
self.displayName = displayName
@staticmethod
def FastParse(xmlstr, epg_channels=None, logCall=deb):
rstrm = ''
categories = {}
if logCall:
logCall('\n\n')
logCall('[UPD] Parsing basemap file')
logCall('-------------------------------------------------------------------------------------')
if PY3:
xmlstr = xmlstr.decode('utf-8')
else:
xmlstr = xmlstr if isinstance(xmlstr, unicode) else xmlstr.decode('utf-8')
if logCall:
logCall('[UPD] %-35s %-50s %-35s' % ('-TITLE-', '-REGEX-', '-STRM-'))
result = list()
if epg_channels is not None:
for title, titles in epg_channels:
string_xml = '\n<channel id="{}" title="" strm=""/>'.format(title)
xmlstr += string_xml
if titles:
string_xml = '\n<channel id="{0}" title="" titles="{1}" strm=""/>'.format(title, titles)
xmlstr += string_xml
channelRe = re.compile('(<channel.*?/>)', re.DOTALL)
channelIdRe = re.compile('<channel\sid="(.*?)"', re.DOTALL)
channelTitleRe = re.compile('title="(.*?)"', re.DOTALL)
channelTitlesRe = re.compile('titles="(.*?)"', re.DOTALL)
channelStrmRe = re.compile('strm="(.*?)"/>', re.DOTALL)
channels = channelRe.findall(xmlstr)
for channel in channels:
r = channelIdRe.search(channel)
aid = r.group(1) if r else ''
for achannel in aid.split(', '):
r = channelTitleRe.search(channel)
atitle = r.group(1) if r else ''
r = channelTitlesRe.search(channel)
atitles = r.group(1) if r else ''
r = channelStrmRe.search(channel)
astrm = r.group(1) if r else ''
if logCall:
try:
logCall('[UPD] %-35s %-50s %-35s' % (achannel, atitle, astrm))
except:
logCall('[UPD] %-35s %-50s %-35s' % (achannel.decode('utf-8'), atitle, astrm))
if atitles == '':
result.append(MapString(channelid=achannel, titleRegex=atitle, strm=astrm, src='', displayName=''))
else:
for dtitle in atitles.split(', '):
result.append(MapString(channelid=achannel, titleRegex=atitle, strm=astrm, src='', displayName=dtitle))
rstrm = astrm
categoriesRe = re.compile('(<category name=".*?".*tags=".*?"/>)')
categoryRe = re.compile('<category name="(.*?)"', re.DOTALL)
tagsRe = re.compile('tags="(.*?)"/>', re.DOTALL)
category = categoriesRe.findall(xmlstr)
for cat in category:
category_tags_set = set()
category_name = categoryRe.search(cat).group(1)
category_tags = tagsRe.search(cat).group(1).split('|')
for tag in category_tags:
category_tags_set.add(('' + tag.lower()))
categories[category_name] = category_tags_set
if logCall:
logCall('-------------------------------------------------------------------------------------')
return [result, rstrm, categories]
@staticmethod
def loadFile(path, logCall=deb):
try:
logCall('[UPD] Loading basemap => mtvguide: %s' % path)
logCall('\n')
with open(path, 'rb') as content_file:
content = content_file.read()
except Exception as ex:
logCall('loadFile exception: %s' % getExceptionString())
content = ""
return content
class SleepSupervisor(object):
def __init__(self, stopCallback):
self.stopPlaybackCall = stopCallback
self.sleepEnabled = ADDON.getSetting('sleep__enabled')
self.sleepAction = ADDON.getSetting('sleep__action')
self.sleepTimer = int(ADDON.getSetting('sleep_timer')) * 60 #time in secs
self.timer = None
self.actions = {
'0': 'PlayerControl(Stop)',
'1': 'Quit',
'2': 'Powerdown',
'3': 'Suspend'
}
try:
self.action = self.actions[self.sleepAction]
except KeyError:
self.action = 'PlayerControl(Stop)'
deb('SleepSupervisor timer init: sleepEnabled %s, sleepAction: %s, sleepTimer: %s' % (self.sleepEnabled, self.action, self.sleepTimer))
def Start(self):
if self.sleepEnabled == 'true' and self.sleepTimer > 0:
self.Stop()
debug('SleepSupervisor timer Start, action = %s' % self.action)
self.timer = threading.Timer(self.sleepTimer, self.sleepTimeout)
self.timer.start()
def Stop(self):
if self.timer:
self.timer.cancel()
self.timer = None
debug('SleepSupervisor timer Stop')
def sleepTimeout(self):
deb('SleepSupervisor sleepTimeout, executing action: %s' % self.action)
self.timer = None
self.stopPlaybackCall()
xbmc.executebuiltin('%s' % self.action)
class baseServiceUpdater:
locker = threading.Lock()
logLocker = threading.Lock()
baseMapContent = None
categories = None
def __init__(self):
self.sl = ShowList(self.log)
self.login = ''
self.password = ''
self.highQuality = 'true'
self.url = ''
self.thread = None
self.serviceRegex = ''
self.servicePriority = int(0)
self.traceList = list()
self.rstrm = ''
self.forcePrintintingLog = False
self.printLogTimer = None
self.useOnlineMap = True
self.maxAllowedStreams = 1
self.addDuplicatesToList = False
self.addDuplicatesAtBeginningOfList = False
self.serviceEnabled = 'false'
self.baseMapFile = 'basemap.xml'
self.adultMapFile = 'adultmap.xml'
self.vodMapFile = 'vodmap.xml'
self.extraMapFile = 'basemap_extra.xml'
self.automap = list()
self.mapsLoaded = False
self.channelList = None
self.channels = None
self.refreshingStreams = False
self.cache = False
try:
self.onlineMapFile = onlineMapPathBase + self.localMapFile
except:
self.log('baseServiceUpdater self.localMapFile is not defined!!!')
self.onlineMapFile = ''
self.localMapFile = ''
try:
self.serviceRegex = "service=" + self.serviceName + "&cid=%"
self.rstrm = self.serviceRegex + 's'
except:
self.log('baseServiceUpdater self.serviceName is not defined!!!')
self.serviceName = 'baseService'
self.serviceRegex = ''
self.rstrm = ''
def waitUntilDone(self):
if self.thread is not None:
return self.thread.join()
def log(self, message):
if self.thread is not None and self.thread.is_alive() and self.forcePrintintingLog == False:
self.traceList.append(self.__class__.__name__ + ' ' + message)
else:
deb(self.__class__.__name__ + ' ' + message)
def printLog(self):
baseServiceUpdater.logLocker.acquire()
for trace in self.traceList:
deb(trace)
baseServiceUpdater.logLocker.release()
del self.traceList[:]
self.traceList = list()
def wrongService(self):
self.log('wrong service selected: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_WRONG), xbmcgui.NOTIFICATION_WARNING, time=15000, sound=True)
def connErrorMessage(self):
self.log('connection error for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_ERROR), xbmcgui.NOTIFICATION_WARNING, time=15000, sound=True)
def loginErrorMessage(self):
self.log('login error for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_LOGIN_INCORRECT), xbmcgui.NOTIFICATION_WARNING, time=15000, sound=True)
def maxDeviceIdMessage(self):
self.log('max amount of devices added: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_MAX_DEVICE_ID), xbmcgui.NOTIFICATION_WARNING, time=15000, sound=True)
def proxyErrorMessage(self):
self.log('proxy error for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_PROXY_BLOCK), sound=False)
def geoBlockErrorMessage(self):
self.log('geoblock error for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_GEO_BLOCK), sound=False)
def noPremiumMessage(self):
self.log('no premium for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_NO_PREMIUM), sound=False)
def noContentMessage(self):
self.log('no content for service: {}'.format(self.serviceName))
xbmcgui.Dialog().notification(self.serviceName, strings(SERVICE_NO_CONTENT), sound=False)
def startLoadingChannelList(self, automap, cache):
self.cache = cache
if self.thread is None or not self.thread.is_alive():
self.traceList.append('\n')
self.traceList.append('##############################################################################################################')
self.traceList.append('\n')
if cache:
self.thread = threading.Thread(name='cachedChannelList thread', target = self.cachedChannelList, args=(automap,))
else:
self.thread = threading.Thread(name='loadChannelList thread', target = self.loadChannelList, args=(automap,))
self.thread.start()
self.printLogTimer = threading.Timer(15, self.printLogTimeout)
self.printLogTimer.start()
def printLogTimeout(self):
self.printLogTimer = None
self.forcePrintintingLog = True
self.printLog()
def close(self):
if self.printLogTimer is not None:
self.printLogTimer.cancel()
self.printLog()
self.forcePrintintingLog = True
self.refreshingStreams = False
def unlockService(self):
pass
def resetService(self):
self.automap = list()
self.channelList = None
self.mapsLoaded = False
self.refreshingStreams = True
self.forcePrintintingLog = False
def getCategoriesFromMap(self):
if not baseServiceUpdater.categories:
self.getBaseMap()
return baseServiceUpdater.categories
def getBaseMap(self, epg_channels=None):
baseServiceUpdater.locker.acquire()
self.log('\n')
if not baseServiceUpdater.baseMapContent:
baseServiceUpdater.baseMapContent = list()
baseServiceUpdater.categories = {}
self.loadSingleBaseMap('base', self.baseMapFile, epg_channels)
if XXX_EPG:
self.loadSingleBaseMap('adult', self.adultMapFile)
if VOD_EPG:
self.loadSingleBaseMap('vod', self.vodMapFile)
for k in BASE_LIST:
self.loadSingleBaseMap('base_' + k.lower(), 'basemap_{}.xml'.format(k.lower()))
self.loadExtraBaseMap('base_extra', self.extraMapFile)
else:
self.log('loading cached base map')
baseServiceUpdater.locker.release()
return copy.deepcopy(baseServiceUpdater.baseMapContent)
def loadSingleBaseMap(self, lang, mapFilePath, epg_channels=None):
self.log('Loading {} channel map'.format(lang))
entries = None
map = ""
localMapFilename = os.path.join(pathMapBase, mapFilePath)
onlineMapFilename = onlineMapPathBase + mapFilePath
map = self.sl.getJsonFromExtendedAPI(onlineMapFilename, max_conn_time=9, http_timeout=5, verbose=False)
if map:
self.log('successfully downloaded online {} map file: {}'.format(lang, onlineMapFilename))
if xbmcvfs.exists(localMapFilename):
map += MapString.loadFile(localMapFilename, self.log)
else:
map += MapString.loadFile(os.path.join(pathMapBase, 'basemap.xml'), self.log)
self.log('{} file download failed - using local map: {}'.format(lang, localMapFilename))
entries, _, seCat = MapString.FastParse(map, epg_channels, False)
if entries is not None:
baseServiceUpdater.baseMapContent.extend(entries)
for id in seCat:
if id in baseServiceUpdater.categories:
baseServiceUpdater.categories[id].update(seCat[id])
else:
baseServiceUpdater.categories[id] = seCat[id]
def loadExtraBaseMap(self, lang, mapFilePath):
self.log('Loading {} channel map'.format(lang))
if not xbmcvfs.exists(os.path.join(pathMapExtraBase, mapFilePath)):
xbmcvfs.copy(os.path.join(pathMapBase, mapFilePath), os.path.join(pathMapExtraBase, mapFilePath))
localMapFilename = os.path.join(pathMapExtraBase, mapFilePath)
map = MapString.loadFile(localMapFilename, self.log)
entries, _, seCat = MapString.FastParse(map, None, False)
baseServiceUpdater.baseMapContent.extend(entries)
for id in seCat:
if id in baseServiceUpdater.categories:
baseServiceUpdater.categories[id].update(seCat[id])
else:
baseServiceUpdater.categories[id] = seCat[id]
def loadMapFile(self, epg_channels=None):
try:
if not self.mapsLoaded:
self.automap = self.getBaseMap(epg_channels)
if self.useOnlineMap:
dedicatedMapfile = self.sl.getJsonFromExtendedAPI(self.onlineMapFile, max_conn_time=6, verbose=False)
else:
dedicatedMapfile = None
if dedicatedMapfile is None:
dedicatedMapFilename = os.path.join(pathMapBase, self.localMapFile)
if os.path.isfile(dedicatedMapFilename):
if self.useOnlineMap:
self.log('loadMapFile: dedicated map download failed - using local map')
dedicatedMapfile = MapString.loadFile(dedicatedMapFilename, self.log)
else:
dedicatedMapfile = None
self.log('loadMapFile: dedicated map doesnt exist - using just base map')
else:
self.log('loadMapFile: success downloading online map file: %s' % self.onlineMapFile)
if dedicatedMapfile:
if not self.refreshingStreams:
dedicatedMap, rstrm, _ = MapString.FastParse(dedicatedMapfile, None, False) #self.log)
else:
#Avoid printing content of map to log on every refresh
dedicatedMap, rstrm, _ = MapString.FastParse(dedicatedMapfile, None, False)
for dedicatedEntry in dedicatedMap:
for baseEntry in self.automap:
if dedicatedEntry.channelid == baseEntry.channelid:
self.automap.remove(baseEntry)
break
self.automap.extend(dedicatedMap)
if not self.rstrm or self.rstrm == '':
self.rstrm = rstrm
self.mapsLoaded = True
except Exception as ex:
self.log('loadMapFile: Error %s' % getExceptionString())
def isChannelListStillValid(self):
return True
def getDisplayName(self):
try:
return self.serviceDisplayName
except:
pass
return self.serviceName
def getBaseChannelList(self, silent=False, returnCopy=True, cache=False):
result = list()
try:
if 'playlist_' in self.serviceName:
cachefile = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.m3u'.format(playlist=self.serviceName))
cachepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.cache'.format(playlist=self.serviceName))
if cache:
if os.path.exists(cachepath) and os.path.exists(cachefile):
if PY3:
with open(cachepath, 'r', encoding='utf-8') as f:
data = json.load(f)
else:
with codecs.open(cachepath, 'r', encoding='utf-8') as f:
data = json.load(f)
cachedList = list()
for k, v in data.items():
cachedList.append(TvCid(cid=k, name=v['name'], title=v['title'], strm=v['strm'], catchup=v['catchup']))
self.channelList = cachedList
return self.channelList
else:
if os.path.exists(cachepath) and 'playlist_' in self.serviceName:
os.remove(cachepath)
if self.channelList and self.isChannelListStillValid():
self.log('getBaseChannelList return cached channel list')
if returnCopy:
return copy.deepcopy(self.channelList)
else:
return self.channelList
tmpresult = self.getChannelList(silent)
if len(tmpresult) > 0:
result = tmpresult
self.channelList = copy.deepcopy(result)
except:
self.log('getBaseChannelList exception: %s' % getExceptionString())
if 'playlist_' in self.serviceName:
cachepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.cache'.format(playlist=self.serviceName))
if not os.path.exists(cachepath) and cache:
self.saveCache = threading.Thread(name='saveCacheList thread', target = self.saveCacheList, args=(self.channelList, self.serviceName,))
self.saveCache.start()
return result
def saveCacheList(self, result, serviceName):
cachedDict = {y.cid: {'name': y.name, 'title': y.title, 'strm': y.strm, 'catchup': y.catchup} for y in result}
cachepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.cache'.format(playlist=serviceName))
if not os.path.exists(cachepath):
if PY3: