-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsource.py
More file actions
4039 lines (3293 loc) · 173 KB
/
source.py
File metadata and controls
4039 lines (3293 loc) · 173 KB
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) 2022 Mariusz89B
# Copyright (C) 2022 rysson
# Copyright (C) 2018 primaeval
# Copyright (C) 2016 Andrzej Mleczko
# Copyright (C) 2014 Krzysztof Cebulski
# Copyright (C) 2013 Szakalit
# Copyright (C) 2013 Tommy Winther
# 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
import configparser
else:
import urllib
import ConfigParser
from collections import Counter
import threading
import requests
import urllib3
import os, re, time, io, zipfile
from datetime import datetime, timedelta
try:
from datetime import timezone
except ImportError:
pass
import xbmc, xbmcgui, xbmcvfs
import shutil
import playService
import serviceLib
import sqlite3
import codecs
from xml.etree import ElementTree
from strings import *
import strings as strings2
from itertools import chain
from skins import Skin
from random import uniform
from unidecode import unidecode
from groups import *
UA = xbmc.getUserAgent()
CACHELIST = {}
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')
PREDEFINED_CATEGORIES = []
EPG_LIST = []
EPG_DICT = {}
CC_DICT = ccDict()
for k, v in CC_DICT.items():
epg = ADDON.getSetting('epg_{cc}'.format(cc=k)).strip()
cc = ADDON.getSetting('country_code_{}'.format(k.lower()))
if cc == 'true' and cc != '':
EPG_DICT.update({k: v})
if epg and epg != '':
EPG_LIST.append(epg)
if k == 'all':
all_channels = strings(30325)
PREDEFINED_CATEGORIES.append(all_channels)
else:
if cc == 'true' and cc != '':
PREDEFINED_CATEGORIES.append(k.upper())
# ADDON settings
SOURCE = ADDON.getSetting('source')
if SOURCE == '0':
GET_SOURCE = '0'
else:
GET_SOURCE = '1'
PARSER = ADDON.getSetting('useCustomParser')
if PARSER == 'true':
CUSTOM_PARSER = True
else:
CUSTOM_PARSER = False
AUTO_CID = ADDON.getSetting('AutoUpdateCid')
if AUTO_CID == 'true':
UPDATE_CID = True
else:
UPDATE_CID = False
DATABASE_CLEARED = ADDON.getSetting("database_cleared")
if DATABASE_CLEARED == 'true':
GET_DATABASE_CLEARED = True
else:
GET_DATABASE_CLEARED = False
PRAGMA_MODE = ADDON.getSetting("pragma_mode")
if PRAGMA_MODE == 'true':
GET_PRAGMA_MODE = True
else:
GET_PRAGMA_MODE = False
ALT_CHANN = ADDON.getSetting('epg_display_name')
if ALT_CHANN == 'true':
CH_DISP_NAME = True
else:
CH_DISP_NAME = False
EPG_INTERVAL = ADDON.getSetting('epg_interval')
if EPG_INTERVAL == '0':
GET_EPG_INTERVAL = 0
elif EPG_INTERVAL == '1':
GET_EPG_INTERVAL = 1
elif EPG_INTERVAL == '2':
GET_EPG_INTERVAL = 2
elif EPG_INTERVAL == '3':
GET_EPG_INTERVAL = 3
elif EPG_INTERVAL == '4':
GET_EPG_INTERVAL = 4
elif EPG_INTERVAL == '5':
GET_EPG_INTERVAL = 5
else:
GET_EPG_INTERVAL = 6
CHANNEL_FILTER = ADDON.getSetting('channel_filter_sort')
if CHANNEL_FILTER == '0':
GET_CHANNEL_FILTER = '0'
elif CHANNEL_FILTER == '1':
GET_CHANNEL_FILTER = '1'
else:
GET_CHANNEL_FILTER = '2'
ADJUST_LOCAL_TIME = ADDON.getSetting('auto_time_zone')
NUMBER_OF_SERVICE_PRIORITIES = 12
SETTINGS_TO_CHECK = ['source', 'xmltv_file', 'xmltv_logo_folder', 'useCustomParser',
'm-TVGuide', 'm-TVGuide2', 'm-TVGuide3',
'XXX_EPG', 'VOD_EPG', 'time_zone', 'auto_time_zone']
for k, v in EPG_DICT.items():
SETTINGS_TO_CHECK.append('epg_{0}'.format(k))
def unidecodeStr(s):
if PY3:
return s
else:
return unidecode(s)
class proxydt(datetime):
@staticmethod
def strptime(date_string, format):
import time
try:
res = datetime.strptime(date_string, format)
except:
res = datetime(*(time.strptime(date_string, format)[0:6]))
return res
proxydt = proxydt
class Progress(object):
"""Simple class to keep progrees."""
def __init__(self, total, callback=None):
self.n = 0
self.total = total
self.callback = callback
class Channel(object):
def __init__(self, id, title, logo = None, titles = None, streamUrl = None, visible = True, weight = -1):
self.id = id
self.title = title
self.logo = logo
self.titles = titles
self.streamUrl = streamUrl
self.visible = visible
self.weight = weight
self.channelList = list()
self.channelListAll = list()
def isPlayable(self):
return hasattr(self, 'streamUrl') and self.streamUrl
def __eq__(self, other):
return self.id == other.id
def __repr__(self):
return 'Channel(id={}, title={}, logo={}, titles={}, streamUrl={})' \
.format(self.id, self.title, self.logo, self.titles, self.streamUrl)
class Program(object):
def __init__(self, channel, title, startDate, endDate, description, productionDate = None, director = None, actor = None, episode = None, rating = None, imageLarge = None, imageSmall = None, categoryA = None, categoryB = None, notificationScheduled = None, recordingScheduled = None, fileName = None):
"""
@param channel:
@type channel: source.Channel
@param title:
@param startDate:
@param endDate:
@param description:
@param imageLarge:
@param imageSmall:
"""
self.channel = channel
self.title = title
self.startDate = startDate
self.endDate = endDate
self.description = description
self.productionDate = productionDate
self.director = director
self.actor = actor
self.episode = episode
self.rating = rating
self.imageLarge = imageLarge
self.imageSmall = imageSmall
self.categoryA = categoryA
self.categoryB = categoryB
self.notificationScheduled = notificationScheduled
self.recordingScheduled = recordingScheduled
self.fileName = fileName
def __repr__(self):
return 'Program(channel={}, title={}, startDate={}, endDate={}, description={}, productionDate={}, director={}, actor={}, episode{}, rating{}, imageLarge={}, imageSmall={}, categoryA={}, categoryB={})' \
.format(self.channel, self.title, self.startDate, self.endDate, self.description, self.productionDate, self.director, self.actor, self.episode, self.rating, self.imageLarge, self.imageSmall, self.categoryA, self.categoryB)
class ProgramDescriptionParser(object):
DECORATE_REGEX = re.compile(r'\[COLOR\s*\w*\]|\[/COLOR\]|\[B\]|\[/B\]|\[I\]|\[/I\]', re.IGNORECASE)
CATEGORY_REGEX = re.compile(r'((G:|Kategoria:|Genre:|Genere:|Category:|Kategori:|Cat.?gorie:|Kategorie:|Kategorija:|Sjanger:)(.*?\[\/B\]|.*?[^\.]*)(\.)?)', re.IGNORECASE)
def __init__(self, description):
self.description = description
def extractCategory(self):
try:
category = ProgramDescriptionParser.CATEGORY_REGEX.search(self.description).group(1)
category = ProgramDescriptionParser.DECORATE_REGEX.sub("", category)
category = re.sub('G:|Kategoria:|Genre:|Category:|Kategori:|Cat.?gorie:|Kategorie:|Kategorija:|Sjanger:|Genere:', '', category).strip()
self.description = ProgramDescriptionParser.CATEGORY_REGEX.sub("", self.description).strip()
except:
category = ''
return category
def extractProductionDate(self):
try:
productionDate = re.search(r'((R:|Rok produkcji:|Producerat .?r:|Production date:|Produktions dato:|Date de production:|Produktionsdatum:|Godina proizvodnje:|Datum proizvodnje:|Produksjonsdato:|Productie datum:|Datum v.?roby:|Anno prodotto:)\s*(\[B\])?(\d{2,4}|live)(\[\/B\])?(\.)?)', self.description).group(4)
productionDate = ProgramDescriptionParser.DECORATE_REGEX.sub("", productionDate)
productionDate = re.sub('R:|Rok produkcji:|Producerat .?r:|Production date:|Produktions dato:|Date de production:|Produktionsdatum:|Godina proizvodnje:|Datum proizvodnje:|Produksjonsdato:|Productie datum:|Datum v.?roby:|Anno prodotto:', '', productionDate).strip()
self.description = re.sub(r'((R:|Rok produkcji:|Producerat .?r:|Production date:|Produktions dato:|Date de production:|Produktionsdatum:|Godina proizvodnje:|Datum proizvodnje:|Produksjonsdato:|Productie datum:|Datum v.?roby:|Anno prodotto:)\s*(\[B\])?(\d{2,4}|live)(\[\/B\])?(\.)?)', '', self.description).strip()
except:
productionDate = ''
return productionDate
def extractDirector(self):
try:
director = re.search(r'.*((Re.?yser:|Regiss.?r:|Director:|Instrukt.?r:|R.?alisateur:|Regisseur:|Direktor:|Re.?is.?r:|Direttore:)(.*?\[\/B\]|.*?[^\.]*)).*', self.description).group(1)
director = ProgramDescriptionParser.DECORATE_REGEX.sub("", director)
director = re.sub(r'Re.?yser:|Regiss.?r:|Director:|Instrukt.?r:|R.?alisateur:|Regisseur:|Direktor:|Re.?is.?r:|Direttore:', '', director).strip()
self.description = re.sub(r'(Re.?yser:|Regiss.?r:|Director:|Instrukt.?r:|R.?alisateur:|Regisseur:|Direktor:|Re.?is.?r:|Direttore:)(.*?\[\/B\]|.*?[^\.]*)(\.)?', '', self.description).strip()
except:
director = ''
return director
def extractEpisode(self):
try:
episode = re.search(r'.*((Odcinek:|Avsnitt:|Episode:|Episode:|.?pisode:|Folge:|Odjeljak:|Epizoda:|Aflevering:|Sezione:)\s*(\[B\])?(.*?\/B\]|.*?[^\.]*)(\.)?).*', self.description).group(1)
episode = ProgramDescriptionParser.DECORATE_REGEX.sub("", episode)
episode = re.sub('Odcinek:|Avsnitt:|Episode:|.?pisode:|Folge:|Odjeljak:|Epizoda:|Aflevering:|Sezione:', '', episode).strip()
self.description = re.sub(r'(Odcinek:|Avsnitt:|Episode:|.?pisode:|Folge:|Odjeljak:|Epizoda:|Aflevering:|Sezione:)\s*(\[B\])?(.*?\/B\]|.*?[^\.]*)(\.)?', '', self.description).strip()
p = re.compile(r'([*S|E]((S)?(\d{1,3})?\s*((E)?\d{1,5}(\/\d{1,5})?)))')
episode = p.search(self.description).group(1)
except:
episode = ''
return episode
def extractAllowedAge(self):
if PY3:
addonPath = xbmcvfs.translatePath(ADDON.getAddonInfo('path'))
else:
addonPath = xbmc.translatePath(ADDON.getAddonInfo('path'))
try:
icon = ''
age = ''
try:
age = re.search(r'(W:|Od lat:|.?r:|Rating:|Pendant des ann.?es:|.?ber die Jahre:|Godinama:|Jaar:|Rok:|Anni:).*?(\[B\])?(\d+)(\[\/B\])?(\.)?', self.description).group(3)
if age == '3':
age = '0'
icon = os.path.join(addonPath, 'icons', 'age_rating', 'icon_{}.png'.format(age))
except:
age = re.search(r'(W:|Od lat:|.?r:|Rating:|Pendant des ann.?es:|.?ber die Jahre:|Godinama:|Jaar:|Rok:|Anni:).*?(\[B\])?(\w+)(\[\/B\])?(\.)?', self.description).group(3)
age = ProgramDescriptionParser.DECORATE_REGEX.sub("", age)
self.description = re.sub(r'(W:|Od lat:|.?r:|Rating:|Pendant des ann.?es:|.?ber die Jahre:|Godinama:|Jaar:|Rok:|Anni:).*?(\[B\])?({Age}|.*)\s*(\+)?(\[\/B\])?(\.)?'.format(Age=age), '', self.description).strip()
except:
icon = ''
age = ''
return icon, age
def extractRating(self):
try:
rating = re.search(r'((O:|Ocena:|Betyg:|Starrating:|Bewertung:|Bed.?mmelse:|Bewertung:|Ocjena:|Notation:|Valutazione:|Hodnocen.?:)\s*(\[B\])?(\d+/\d+)(\[\/B\])?(\.)?)', self.description).group(4)
rating = ProgramDescriptionParser.DECORATE_REGEX.sub("", rating)
rating = re.sub('O:|Ocena:|Betyg:|Starrating:|Bewertung:|Bed.?mmelse:|Bewertung:|Ocjena:|Notation:|Valutazione:|Hodnocen.?:', '', rating).strip()
self.description = re.sub(r'((O:|Ocena:|Betyg:|Bewertung:|Bed.?mmelse:|Ocjena:|Bewertung:|Ocjena:|Notation:|Valutazione:|Hodnocen.?:)\s*(\[B\])?(\d+/\d+)(\[\/B\])?(\.)?)', '', self.description).strip()
except:
rating = ''
return rating
def extractActors(self):
try:
actors = re.search(r'.*((Aktorzy:|Sk.?despelare:|Actors:|Skuespillere:|Acteurs:|Schauspiel:|Glumci:|Herec:|Attori:)(.*?\[\/B\]|.*?[^\.]*)).*', self.description).group(1)
actors = ProgramDescriptionParser.DECORATE_REGEX.sub("", actors)
actors = re.sub('Aktorzy:|Sk.?despelare:|Actors:|Skuespillere:|Acteurs:|Schauspiel:|Glumci:|Herec:|Attori:', '', actors).strip()
self.description = re.sub(r'(Aktorzy:|Sk.?despelare:|Actors:|Skuespillere:|Acteurs:|Schauspiel:|Glumci:|Herec:|Attori:)(.*?\[\/B\]|.*?[^\.]*)(\.)?', '', self.description).strip()
except:
actors = ''
return actors
class SourceException(Exception):
pass
class SourceUpdateCanceledException(SourceException):
pass
class SourceNotConfiguredException(SourceException):
pass
class RestartRequired(SourceException):
pass
class SourceFaultyEPGException(SourceException):
def __init__(self, epg):
self.epg = epg
class DatabaseSchemaException(sqlite3.DatabaseError):
pass
class Database(object):
SOURCE_DB = 'source.db'
if PY3:
config = configparser.RawConfigParser()
else:
config = ConfigParser.RawConfigParser()
try:
config.read(os.path.join(Skin.getSkinPath(), 'settings.ini'))
ini_chan = config.getint("Skin", "CHANNELS_PER_PAGE")
CHANNELS_PER_PAGE = ini_chan
except:
CHANNELS_PER_PAGE = 10
def __init__(self):
self.conn = None
self.eventQueue = []
self.event = threading.Event()
self.eventResults = dict()
self.source = instantiateSource()
self.updateInProgress = False
self.updateFailed = False
self.skipUpdateRetries = False
self.settingsChanged = None
self.channelList = list()
self.channelListAll = list()
self.servicePlaylist = dict()
self.category = None
if PY3:
try:
self.profilePath = xbmcvfs.translatePath(ADDON.getAddonInfo('profile'))
except:
self.profilePath = xbmcvfs.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
else:
try:
self.profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
except:
self.profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile')).decode('utf-8')
if not os.path.exists(self.profilePath):
os.makedirs(self.profilePath)
self.databasePath = os.path.join(self.profilePath, Database.SOURCE_DB)
self.ChannelsWithStream = ADDON.getSetting('OnlyChannelsWithStream')
self.epgBasedOnLastModDate = ADDON.getSetting('UpdateEPGOnModifiedDate')
self.lock = threading.Lock()
self.services_updated = False
self.number_of_service_priorites = NUMBER_OF_SERVICE_PRIORITIES
self.close_callback = None
self.unlockDbTimer = None
threading.Thread(name='Database Event Loop', target = self.eventLoop).start()
def eventLoop(self):
deb('Database.eventLoop() >>>>>>>>>> starting...')
while True:
self.event.wait()
self.event.clear()
event = self.eventQueue.pop(0)
command = event[0]
callback = event[1]
deb('Database.eventLoop() >>>>>>>>>> processing command: {}'.format(command.__name__ ))
try:
result = command(*event[2:])
self.eventResults[command.__name__] = result
if callback:
if self._initialize == command:
self.close_callback = callback
threading.Thread(name='Database callback', target=callback, args=[result]).start()
else:
threading.Thread(name='Database callback', target=callback).start()
if self._close == command:
del self.eventQueue[:]
break
except Exception as ex:
deb('Database.eventLoop() >>>>>>>>>> exception: {}!'.format(getExceptionString() ))
if self.close_callback:
self.close_callback(False)
deb('Database.eventLoop() >>>>>>>>>> exiting...')
def _invokeAndBlockForResult(self, method, *args):
self.lock.acquire()
event = [method, None]
event.extend(args)
self.eventQueue.append(event)
self.event.set()
while method.__name__ not in self.eventResults:
time.sleep(0.03)
result = self.eventResults.get(method.__name__)
del self.eventResults[method.__name__]
self.lock.release()
return result
def initialize(self, callback, cancel_requested_callback=None):
self.eventQueue.append([self._initialize, callback, cancel_requested_callback])
self.event.set()
def _initialize(self, cancel_requested_callback):
deb('_initialize')
sqlite3.register_adapter(datetime, self.adapt_datetime)
sqlite3.register_converter(str('timestamp'), self.convert_datetime)
self.alreadyTriedUnlinking = False
while True:
if cancel_requested_callback is not None and cancel_requested_callback():
break
try:
self.unlockDbTimer = threading.Timer(120, self.delayedUnlockDb)
self.unlockDbTimer.start()
time.sleep(uniform(0, 0.2))
self.conn = sqlite3.connect(self.databasePath, detect_types=sqlite3.PARSE_DECLTYPES, cached_statements=2000)
self.conn.execute("PRAGMA foreign_keys = ON");
self.conn.execute("PRAGMA locking_mode = EXCLUSIVE");
self.conn.execute("PRAGMA encoding = 'UTF-8'");
self.conn.execute("PRAGMA temp_store = 0");
self.conn.execute("PRAGMA cache_size = -32000");
if GET_PRAGMA_MODE:
self.conn.execute("PRAGMA journal_mode = WAL");
self.conn.execute("PRAGMA temp_store = 2");
self.conn.execute("PRAGMA synchronous = NORMAL");
self.conn.row_factory = sqlite3.Row
# create and drop dummy table to check if database is locked
c = self.conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS database_lock_check(id TEXT PRIMARY KEY)')
c.execute('DROP TABLE database_lock_check')
c.execute('pragma integrity_check')
for row in c:
deb('Database is {}'.format(row[str('integrity_check')]))
c.close()
self._createTables()
self.settingsChanged = self._wasSettingsChanged(ADDON)
break
except RestartRequired:
strings2.M_TVGUIDE_CLOSING = True
xbmcgui.Dialog().ok(strings(30978), strings(30979))
return False
except sqlite3.OperationalError:
#if cancel_requested_callback is None or strings2.M_TVGUIDE_CLOSING:
deb('[{}] Database is locked, bailing out...'.format(ADDON_ID))
#break
#else: # ignore 'database is locked'
#deb('[{}] Database is locked, retrying...'.format(ADDON_ID))
xbmcgui.Dialog().notification(strings(57051), strings(57052), time=8000, sound=True)
return False
except sqlite3.DatabaseError:
self.conn = None
if self.alreadyTriedUnlinking:
deb('[{}] Database is broken and unlink() failed'.format(ADDON_ID))
break
else:
try:
os.unlink(self.databasePath)
except OSError:
pass
self.alreadyTriedUnlinking = True
xbmcgui.Dialog().ok(ADDON.getAddonInfo('name'), strings(DATABASE_SCHEMA_ERROR_1) + '\n' + strings(DATABASE_SCHEMA_ERROR_2) + ' ' + strings(DATABASE_SCHEMA_ERROR_3))
return self.conn is not None
def delayedUnlockDb(self):
try:
self.eventQueue.append([self.unlockDb, None])
self.event.set()
except:
pass
def unlockDb(self):
try:
if self.conn:
deb('Unlocking DB')
self.conn.execute("PRAGMA locking_mode = NORMAL");
c = self.conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS database_lock_check(id TEXT PRIMARY KEY)')
c.execute('DROP TABLE database_lock_check')
self.conn.commit()
c.close()
except:
pass
def close(self, callback=None):
self.close_callback = None
if self.unlockDbTimer and self.unlockDbTimer.is_alive():
self.unlockDbTimer.cancel()
self.source.close()
self.eventQueue.append([self._close, callback])
self.event.set()
def _close(self):
try:
# rollback any non-commit'ed changes to avoid database lock
if self.conn:
self.conn.execute("PRAGMA analysis_limit = 400");
self.conn.execute("PRAGMA optimize");
self.conn.rollback()
except sqlite3.OperationalError:
pass # no transaction is active
if self.conn:
self.conn.close()
def _wasSettingsChanged(self, addon):
settingsChanged = False
noRows = True
count = 0
c = self.conn.cursor()
c.execute('SELECT * FROM settings')
for row in c:
noRows = False
key = row[str('key')]
regex_epg = re.compile(r'epg_\w{2,3}')
if regex_epg.match(key) and key not in ['epg_{0}'.format(x) for x in list(EPG_DICT.keys())]:
c.execute('DELETE FROM settings WHERE key=?', [key])
if SETTINGS_TO_CHECK.count(key):
count += 1
setting = addon.getSetting(key)
if row[str('value')] != setting:
deb('Settings changed for key: {}, value id DB: {}, in settings.xml: {}'.format(key, row[str('value')], setting) )
settingsChanged = True
if count != len(SETTINGS_TO_CHECK):
deb('Settings changed - number of keys is different')
settingsChanged = True
if settingsChanged or noRows:
for key in SETTINGS_TO_CHECK:
value = addon.getSetting(key)
c.execute('INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)', [key, value])
if not c.rowcount:
c.execute('UPDATE settings SET value=? WHERE key=?', [value, key])
try:
c.execute('UPDATE UPDATES SET epg_size=? WHERE source=?', [0, self.source.KEY])
except:
pass
self.conn.commit()
c.close()
deb('Settings changed: {}'.format(str(settingsChanged) ))
return settingsChanged
def _isCacheExpired(self, date, initializing, startup, force):
try:
if force:
return True
if startup:
return False
if GET_EPG_INTERVAL == 1 and initializing:
return True
if self.settingsChanged:
return True
# check if channel data is up-to-date in database
try:
c = self.conn.cursor()
c.execute('SELECT channels_updated FROM sources WHERE id=?', [self.source.KEY])
row = c.fetchone()
if not row:
return True
channelsLastUpdated = row[str('channels_updated')]
c.close()
except TypeError:
return True
# check if program data is up-to-date in database
c = self.conn.cursor()
if self.epgBasedOnLastModDate == 'false':
dateStr = date.strftime('%Y-%m-%d')
c.execute('SELECT programs_updated FROM updates WHERE source=? AND date=?', [self.source.KEY, dateStr])
else:
c.execute('SELECT programs_updated FROM updates WHERE source=?', [self.source.KEY])
row = c.fetchone()
if row:
programsLastUpdated = row[str('programs_updated')]
else:
programsLastUpdated = None
c.execute('SELECT epg_size FROM updates WHERE source=?', [self.source.KEY])
row = c.fetchone()
epgSize = 0
if row:
epgSize = row[str('epg_size')]
ADDON.setSetting('epg_size', str(epgSize))
c.close()
set_time = 'auto'
if programsLastUpdated is not None:
interval = GET_EPG_INTERVAL
if interval == 0:
set_time = 'auto'
elif interval == 1:
set_time = 0
elif interval == 2:
set_time = 43200
elif interval == 3:
set_time = 86400
elif interval == 4:
set_time = 172800
elif interval == 5:
set_time = 604800
elif interval == 6:
set_time = 1209600
if set_time != 'auto':
try:
epg_interval = datetime.timestamp(datetime.now()) - set_time
except:
epg_interval = time.mktime(datetime.now().timetuple()) - set_time
try:
last_update = datetime.timestamp(programsLastUpdated)
except:
last_update = time.mktime(programsLastUpdated.timetuple())
if int(epg_interval) > int(last_update):
self.source.isUpdated(channelsLastUpdated, programsLastUpdated, epgSize)
else:
return False
return self.source.isUpdated(channelsLastUpdated, programsLastUpdated, epgSize)
except:
self.updateFailed = True
return
def cachePlaylist(self, serviceHandler):
playlist_cache = os.path.join(PROFILE_PATH, 'playlist_cache.list')
serviceName = serviceHandler.serviceName
src = ADDON.getSetting('{playlist}_source'.format(playlist=serviceName))
refr = ADDON.getSetting('{playlist}_refr'.format(playlist=serviceName))
if refr == 'true':
refr_c = serviceName
else:
refr_c = None
n = datetime.now()
d = timedelta(days=int(ADDON.getSetting('{playlist}_refr_days'.format(playlist=serviceName))))
if PY3:
tnow = datetime.timestamp(n)
else:
from time import time
tnow = str(time()).split('.')[0]
tdel = d.total_seconds()
path = os.path.join(PROFILE_PATH, 'playlists')
filepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.m3u'.format(playlist=serviceName))
try:
filename = os.path.basename(filepath)
timestamp = str(os.path.getmtime(filepath)).split('.')[0]
except:
timestamp = tnow
if not os.path.exists(path):
os.makedirs(path)
url_setting = ADDON.getSetting('{playlist}_url'.format(playlist=serviceName))
urlpath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.url'.format(playlist=serviceName))
if os.path.exists(urlpath):
if PY3:
with open(urlpath, 'r', encoding='utf-8') as f:
url = [line.strip() for line in f][0]
else:
with codecs.open(urlpath, 'r', encoding='utf-8') as f:
url = [line.strip() for line in f][0]
else:
url = url_setting
cachedate = int(timestamp) + int(tdel)
if int(tnow) >= int(cachedate) or (not os.path.exists(filepath) or os.stat(filepath).st_size <= 0 or url != url_setting):
deb('[UPD] Cache playlist: Write, expiration date: {}'.format(datetime.fromtimestamp(int(cachedate))))
cache = False
else:
if refr == 'true' and src == '0':
deb('[UPD] Cache playlist: Read')
cache = True
else:
cache = False
if not cache:
if PY3:
if os.path.exists(playlist_cache):
with open(playlist_cache, 'r', encoding='utf-8') as r:
services = r.read().splitlines()
with open(playlist_cache, 'w', encoding='utf-8') as f:
for service in services:
if service != serviceName:
f.write(service+'\n')
else:
if os.path.exists(playlist_cache):
with codecs.open(playlist_cache, 'r', encoding='utf-8') as r:
services = r.read().splitlines()
with codecs.open(playlist_cache, 'w', encoding='utf-8') as f:
for service in services:
if service != serviceName:
f.write(service+'\n')
else:
if (os.path.exists(filepath) or os.stat(filepath).st_size > 0 or url == url_setting):
if PY3:
try:
with open(playlist_cache, 'r', encoding='utf-8') as r:
services = r.read().splitlines()
except:
services = []
with open(playlist_cache, 'a', encoding='utf-8') as f:
if serviceName not in services:
f.write(serviceName+'\n')
else:
try:
with codecs.open(playlist_cache, 'r', encoding='utf-8') as r:
services = r.read().splitlines()
except:
services = []
with codecs.open(playlist_cache, 'a', encoding='utf-8') as f:
if serviceName not in services:
f.write(serviceName+'\n')
return cache, refr_c
def updateChannelAndProgramListCaches(self, callback, date = datetime.now(), progress_callback = None, initializing=False, startup=False, force=False, clearExistingProgramList = True):
self.eventQueue.append([self._updateChannelAndProgramListCaches, callback, date, progress_callback, initializing, startup, force, clearExistingProgramList])
self.event.set()
def _updateChannelAndProgramListCaches(self, date, progress_callback, initializing, startup, force, clearExistingProgramList):
deb('_updateChannelAndProgramListCache')
import sys
refr_lst = []
# todo workaround service.py 'forgets' the adapter and convert set in _initialize.. wtf?!
sqlite3.register_adapter(datetime, self.adapt_datetime)
sqlite3.register_converter(str('timestamp'), self.convert_datetime)
# Start service threads
updateServices = self.services_updated == False and UPDATE_CID
if updateServices:
deb('[UPD] Starting updating STRM')
playlist_cache = os.path.join(PROFILE_PATH, 'playlist_cache.list')
cache = False
serviceList = list()
services = list()
for serviceName in playService.LIST:
serviceHandler = playService.LIST[serviceName]
services.append(serviceHandler)
if serviceHandler.serviceEnabled == 'true':
serviceList.append(serviceHandler)
if 'playlist_' in serviceName:
cache, refr_c = self.cachePlaylist(serviceHandler)
refr_lst.append(refr_c)
if GET_DATABASE_CLEARED:
cache = False
CACHELIST.update({serviceName: {'cache': cache}})
if (not cache and not 'playlist_' in serviceName) or serviceHandler.serviceEnabled == 'false':
self.removePredefinedCategoriesDb(serviceName)
for k, v in CACHELIST.items():
if not v['cache']:
self.deleteAllCustomStreams()
if os.path.exists(playlist_cache):
os.remove(playlist_cache)
filepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.m3u'.format(playlist=k))
urlpath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.url'.format(playlist=k))
cachepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.cache'.format(playlist=k))
if os.path.exists(filepath):
os.remove(filepath)
if os.path.exists(urlpath):
os.remove(urlpath)
if os.path.exists(cachepath):
os.remove(cachepath)
for s in services:
if s not in serviceList:
self.deleteCustomStreams(s.serviceName, s.serviceRegex)
if 'playlist_' in s.serviceName:
filepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.m3u'.format(playlist=s.serviceName))
urlpath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.url'.format(playlist=s.serviceName))
cachepath = os.path.join(PROFILE_PATH, 'playlists', '{playlist}.cache'.format(playlist=s.serviceName))
if os.path.exists(filepath):
os.remove(filepath)
if os.path.exists(urlpath):
os.remove(urlpath)
if os.path.exists(cachepath):
os.remove(cachepath)
if PY3:
if os.path.exists(playlist_cache):
with open(playlist_cache, 'r', encoding='utf-8') as r:
r_services = r.read().splitlines()
with open(playlist_cache, 'w', encoding='utf-8') as f:
for service in r_services:
if service != s.serviceName:
f.write(service+'\n')
else:
if os.path.exists(playlist_cache):
with codecs.open(playlist_cache, 'r', encoding='utf-8') as r:
r_services = r.read().splitlines()
with codecs.open(playlist_cache, 'w', encoding='utf-8') as f:
for service in r_services:
if service != s.serviceName:
f.write(service+'\n')
cacheExpired = self._isCacheExpired(date, initializing, startup, force)
ADDON.setSetting('database_cleared', 'false')
if cacheExpired and not self.skipUpdateRetries or force:
deb('_isCacheExpired')
self.updateInProgress = True
self.updateFailed = False
dateStr = date.strftime('%Y-%m-%d')
self._removeOldRecordings()
self._removeOldNotifications()
c = self.conn.cursor()
dbChannelsUpdated = False
try:
deb('[{}] Updating caches...'.format(ADDON_ID))
profilePath = self.profilePath
if progress_callback:
progress_callback(0)
imported = 0
nrOfFailures = 0
startTime = datetime.now()
for item in self.source.getDataFromExternal(date, progress_callback):
imported += 1
xbmcvfs.delete(os.path.join(profilePath, 'custom_channels.list'))
channelList = []
if not xbmcvfs.exists(os.path.join(profilePath, 'basemap_extra.xml')):
try:
shutil.copyfile(os.path.join(ADDON.getAddonInfo('path'), 'resources', 'basemap_extra.xml'), os.path.join(profilePath, 'basemap_extra.xml'))
except:
pass
p = re.compile(r'\s<channel id="(.*?)"', re.DOTALL)
with open(os.path.join(profilePath, 'basemap_extra.xml'), 'rb') as f:
if PY3:
base = str(f.read(), 'utf-8')
else:
base = f.read().decode('utf-8')