-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.py
More file actions
1455 lines (1344 loc) · 51.1 KB
/
default.py
File metadata and controls
1455 lines (1344 loc) · 51.1 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/python #
# -*- coding: utf-8 -*- #
############################################################################
# /T /I #
# / |/ | .-~/ #
# T\ Y I |/ / _ #
# /T | \I | I Y.-~/ #
# I l /I T\ | | l | T / #
# T\ | \ Y l /T | \I l \ ` l Y #
# __ | \l \l \I l __l l \ ` _. | #
# \ ~-l `\ `\ \ \ ~\ \ `. .-~ | #
# \ ~-. "-. ` \ ^._ ^. "-. / \ | #
#.--~-._ ~- ` _ ~-_.-"-." ._ /._ ." ./ #
# >--. ~-. ._ ~>-" "\ 7 7 ] #
#^.___~"--._ ~-{ .-~ . `\ Y . / | #
# <__ ~"-. ~ /_/ \ \I Y : | #
# ^-.__ ~(_/ \ >._: | l______ #
# ^--.,___.-~" /_/ ! `-.~"--l_ / ~"-. #
# (_/ . ~( /' "~"--,Y -=b-. _) #
# (_/ . \ Fire TV Guru/ l c"~o \ #
# \ / `. . .^ \_.-~"~--. ) #
# (_/ . ` / / ! )/ #
# / / _. '. .': / ' #
# ~(_/ . / _ ` .-<_ #
# /_/ . ' .-~" `. / \ \ ,z=. #
# ~( / ' : | K "-.~-.______// #
# "-,. l I/ \_ __{--->._(==. #
# //( \ < ~"~" // #
# /' /\ \ \ ,v=. (( #
# .^. / /\ " }__ //===- ` #
# / / ' ' "-.,__ {---(==- #
# .^ ' : T ~" ll #
# / . . . : | :! \ #
# (_/ / | | j-" ~^ #
# ~-<_(_.^-~" #
# #
############################################################################
#############################=IMPORTS=######################################
#Kodi Specific
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,xbmcvfs
import sys
# Select available log level constant to use for notice-level logging
if hasattr(xbmc, 'LOGNOTICE'):
LOG_NOTICE = xbmc.LOGNOTICE
elif hasattr(xbmc, 'LOGINFO'):
LOG_NOTICE = xbmc.LOGINFO
elif hasattr(xbmc, 'LOGWARNING'):
LOG_NOTICE = xbmc.LOGWARNING
elif hasattr(xbmc, 'LOGNONE'):
LOG_NOTICE = xbmc.LOGNONE
else:
LOG_NOTICE = 0
# Log that the module has been loaded (helps confirm installed copy)
try:
xbmc.log(f'IPTVXC: default.py loaded (LOG_NOTICE={LOG_NOTICE})', LOG_NOTICE)
except Exception:
pass
#Python Specific
import base64,os,re,unicodedata,time,string,sys,urllib.request
import urllib.parse,urllib.error,json,datetime,zipfile,shutil
import xml.etree.ElementTree as ET
from datetime import date
#Addon Specific
from resources.modules import control,tools,popup,speedtest,epg
##########################=VARIABLES=#######################################
ADDON = xbmcaddon.Addon()
ADDONPATH = ADDON.getAddonInfo("path")
ADDON_NAME = ADDON.getAddonInfo("name")
ADDON_ID = ADDON.getAddonInfo('id')
DIALOG = xbmcgui.Dialog()
DP = xbmcgui.DialogProgress()
HOME = xbmcvfs.translatePath('special://home/')
ADDONS = os.path.join(HOME, 'addons')
USERDATA = os.path.join(HOME, 'userdata')
PLUGIN = os.path.join(ADDONS, ADDON_ID)
PACKAGES = os.path.join(ADDONS, 'packages')
ADDONDATA = os.path.join(USERDATA, 'addon_data', ADDON_ID)
ADVANCED = os.path.join(USERDATA, 'advancedsettings.xml')
advanced_settings = os.path.join(PLUGIN,'resources', 'advanced_settings')
MEDIA = os.path.join(ADDONS, PLUGIN , 'resources', 'media')
KODIV = float(xbmc.getInfoLabel("System.BuildVersion")[:4])
M3U_PATH = os.path.join(ADDONDATA, 'm3u.m3u')
##########################=ART PATHS=#######################################
icon = os.path.join(PLUGIN, 'icon.png')
# fallback for Extras if no specific icon is provided
iconextras = os.path.join(MEDIA, 'icon_EXTRAS.png')
fanart = os.path.join(PLUGIN, 'fanart.jpg')
background = os.path.join(MEDIA, 'background.jpg')
live = os.path.join(MEDIA, 'live.jpg')
catch = os.path.join(MEDIA, 'cu.jpg')
Moviesod = os.path.join(MEDIA, 'movie.jpg')
Tvseries = os.path.join(MEDIA, 'tv.jpg')
# new menu icons placed in resources/media (files starting with icon_)
iconfavorites = os.path.join(MEDIA, 'icon_FAVORITES.png')
iconrecent = os.path.join(MEDIA, 'icon_RECENTLY_WATCHED.png')
icon_lastplayed = os.path.join(MEDIA, 'icon_LAST_PLAYED.png')
iconaccount = os.path.join(MEDIA, 'icon_ACCOUNT_INFO.png')
iconlive = os.path.join(MEDIA, 'icon_LIVE_TV.png')
iconMoviesod = os.path.join(MEDIA, 'icon_MOVIES_VOD.png')
iconTvseries = os.path.join(MEDIA, 'icon_SERIES.png')
icontvguide = os.path.join(MEDIA, 'icon_TV_GUIDE.png')
iconcatchup = os.path.join(MEDIA, 'icon_CATCHUP_TV.png')
iconsearch = os.path.join(MEDIA, 'icon_SEARCH.png')
iconsettings = os.path.join(MEDIA, 'icon_SETTINGS.png')
#########################=XC VARIABLES=#####################################
dns = control.setting('DNS')
username = control.setting('Username')
password = control.setting('Password')
live_url = '{0}/enigma2.php?username={1}&password={2}&type=get_live_categories'.format(dns,username,password)
vod_url = '{0}/enigma2.php?username={1}&password={2}&type=get_vod_categories'.format(dns,username,password)
series_url = '{0}/enigma2.php?username={1}&password={2}&type=get_series_categories'.format(dns,username,password)
panel_api = '{0}/panel_api.php?username={1}&password={2}'.format(dns,username,password)
player_api = '{0}/player_api.php?username={1}&password={2}'.format(dns,username,password)
play_url = '{0}/live/{1}/{2}/'.format(dns,username,password)
play_live = '{0}/{1}/{2}/'.format(dns,username,password)
play_movies = '{0}/movie/{1}/{2}/'.format(dns,username,password)
play_series = '{0}/series/{1}/{2}/'.format(dns,username,password)
#############################################################################
adult_tags = ['xxx','xXx','XXX','adult','Adult','ADULT','adults','Adults','ADULTS','porn','Porn','PORN']
def buildcleanurl(url):
url = str(url).replace('USERNAME',username).replace('PASSWORD',password)
return url
def home():
# Last Played quick access
last = tools.load_last_played()
if last and last.get('url'):
ts = last.get('timestamp', 0)
ago = ''
if ts:
delta = int(time.time() - ts)
if delta < 60:
ago = 'just now'
elif delta < 3600:
ago = '%dm ago' % (delta // 60)
elif delta < 86400:
ago = '%dh ago' % (delta // 3600)
else:
ago = '%dd ago' % (delta // 86400)
channel_name = last.get('name', 'Last Channel')
label = '[B][COLOR lime]\u25b6 Last Played: %s[/COLOR][/B]' % channel_name
if ago:
label = '[B][COLOR lime]\u25b6 Last Played (%s): %s[/COLOR][/B]' % (ago, channel_name)
# Always use the provided local icon for Last Played so it displays
tools.addDir(label, last['url'], 35, icon_lastplayed, background, '')
tools.addDir('Favorites','url',30,iconfavorites,background,'')
tools.addDir('Recently Watched','url',32,iconrecent,background,'')
tools.addDir('Account Information','url',6,iconaccount,background,'')
tools.addDir('Live TV','live',1,iconlive,background,'')
tools.addDir('Movies/VOD','vod',3,iconMoviesod,background,'')
tools.addDir('Series','live',18,iconTvseries,background,'')
tools.addDir('[COLOR FF42A5F5][B]TV Guide[/B][/COLOR]','epg',37,icontvguide,background,'')
tools.addDir('Catchup TV','url',12,iconcatchup,background,'')
tools.addDir('Search','url',5,iconsearch,background,'')
# Trakt.tv integration removed
tools.addDir('Settings','url',8,iconsettings,background,'')
tools.addDir('Extras','url',16,iconextras,background,'')
def livecategory():
data = tools.OPEN_URL_CACHED(live_url, ttl_minutes=tools.CONTENT_CACHE_TTL_TV)
if not data:
return
hidexxx = xbmcaddon.Addon().getSetting('hidexxx')=='true'
try:
root = ET.fromstring(data)
except Exception:
return
for ch in root.findall('.//channel'):
t = ch.findtext('title', default='')
name = tools.b64(t) if t else ''
p = ch.findtext('playlist_url', default='')
url2 = tools.check_protocol(p).replace('<![CDATA[','').replace(']]>','')
if not hidexxx or (hidexxx and not any(s in name for s in adult_tags)):
tools.addDir('%s' % name, url2, 2, icon, background if hidexxx else live, '')
def Livelist(url):
url = buildcleanurl(url)
data = tools.OPEN_URL_CACHED(url, ttl_minutes=tools.CONTENT_CACHE_TTL_TV)
if not data:
return
hidexxx = xbmcaddon.Addon().getSetting('hidexxx')=='true'
try:
root = ET.fromstring(data)
except Exception:
return
for ch in root.findall('.//channel'):
t = ch.findtext('title', default='')
ch_name = re.sub(r'\[.*?min ', '-', tools.b64(t)) if t else ''
s = ch.findtext('stream_url', default='')
url1 = tools.check_protocol(s).replace('<![CDATA[','').replace(']]>','')
thumb = ch.findtext('desc_image', default='')
if thumb:
thumb = thumb.replace('<![CDATA[ ','').replace(' ]]>','')
else:
thumb = live
d = ch.findtext('description', default='')
desc = tools.b64(d) if d else 'No Info Available'
if not hidexxx or (hidexxx and not any(tag in ch_name for tag in adult_tags)):
tools.addDir(ch_name, url1, 4, thumb, background, desc)
def series_cats(url):
raw = tools.OPEN_URL_CACHED(player_api+'&action=get_series_categories', ttl_minutes=tools.CONTENT_CACHE_TTL_SERIES)
if not raw:
return
try:
vod_cat = json.loads(raw)
except Exception:
return
hidexxx = xbmcaddon.Addon().getSetting('hidexxx')=='true'
for cat in vod_cat:
name = cat.get('category_name','')
cid = cat.get('category_id','')
if not hidexxx or (hidexxx and not any(s in name for s in adult_tags)):
tools.addDir(name, player_api+'&action=get_series&category_id='+str(cid), 25, icon, background, '')
def serieslist(url):
raw = tools.OPEN_URL_CACHED(url, ttl_minutes=tools.CONTENT_CACHE_TTL_SERIES)
if not raw:
return
try:
ser_cat = json.loads(raw)
except Exception:
return
meta_on = xbmcaddon.Addon().getSetting('meta')=='true'
for ser in ser_cat:
if meta_on:
tools.addDirMeta(ser.get('name',''), player_api+'&action=get_series_info&series_id='+str(ser.get('series_id','')), 19, ser.get('cover',''), (ser.get('backdrop_path') or [''])[0] if ser.get('backdrop_path') else '', ser.get('plot',''), ser.get('releaseDate',''), str(ser.get('cast','')).split(), ser.get('rating_5based',''), ser.get('episode_run_time',''), ser.get('genre',''))
else:
tools.addDir(ser.get('name',''), player_api+'&action=get_series_info&series_id='+str(ser.get('series_id','')), 19, ser.get('cover',''), background, '')
def series_seasons(url):
raw = tools.OPEN_URL_CACHED(url, ttl_minutes=tools.CONTENT_CACHE_TTL_SERIES)
if not raw:
return
try:
ser_cat = json.loads(raw)
except Exception:
return
info = ser_cat.get('info', {})
for season in ser_cat.get('episodes', {}):
tools.addDir('Season - '+str(season), url+'&season_number='+str(season), 20, info.get('cover',''), (info.get('backdrop_path') or [''])[0] if info.get('backdrop_path') else '', '')
def season_list(url):
raw = tools.OPEN_URL_CACHED(url, ttl_minutes=tools.CONTENT_CACHE_TTL_SERIES)
if not raw:
return
try:
ser = json.loads(raw)
except Exception:
return
info = ser.get('info', {})
episodes_map = ser.get('episodes', {})
from urllib.parse import urlparse, parse_qs
parsed_url = urlparse(url)
season_qs = parse_qs(parsed_url.query).get('season_number', [])
season_number = season_qs[0] if season_qs else None
episodes = []
try:
if isinstance(episodes_map, dict):
key = season_number
alt_key = None
try:
alt_key = int(season_number) if season_number is not None else None
except:
alt_key = None
if key in episodes_map and episodes_map[key]:
episodes = episodes_map[key]
elif alt_key is not None and alt_key in episodes_map and episodes_map[alt_key]:
episodes = episodes_map[alt_key]
else:
for k in episodes_map:
try:
for e in episodes_map[k]:
episodes.append(e)
except:
pass
elif isinstance(episodes_map, list):
episodes = episodes_map
except:
episodes = []
meta_on = xbmcaddon.Addon().getSetting('meta')=='true'
for ep in episodes:
title = ep.get('title') or ep.get('name') or 'Episode'
ser_info = ep.get('info')
if isinstance(ser_info, list):
ser_info = ser_info[0] if ser_info else {}
if not isinstance(ser_info, dict):
ser_info = {}
cover = ser_info.get('movie_image') or ser_info.get('cover') or ''
plot = ser_info.get('plot') or ''
releasedate = ser_info.get('releasedate') or ser_info.get('releaseDate') or ''
duration = ser_info.get('duration') or ''
container_extension = ep.get('container_extension') or 'mp4'
play = play_series+str(ep.get('id'))+'.'+container_extension
if meta_on:
tools.addDirMeta(title, play, 4, cover, cover, plot, releasedate, str(info.get('cast','')).split(), info.get('rating_5based',''), str(duration), info.get('genre',''))
else:
tools.addDir(title, play, 4, cover, cover, '')
def vod(url):
data = tools.OPEN_URL_CACHED(vod_url if url == 'vod' else buildcleanurl(url), ttl_minutes=tools.CONTENT_CACHE_TTL_MOVIES)
if not data:
return
hidexxx = xbmcaddon.Addon().getSetting('hidexxx')=='true'
meta_on = xbmcaddon.Addon().getSetting('meta')=='true'
try:
root = ET.fromstring(data)
except Exception:
return
for ch in root.findall('.//channel'):
t = ch.findtext('title', default='')
name = str(tools.b64(t)).replace('?', '') if t else ''
playlist = ch.findtext('playlist_url')
if playlist:
url1 = tools.check_protocol(playlist.replace('<![CDATA[','').replace(']]>',''))
if not hidexxx or (hidexxx and not any(s in name for s in adult_tags)):
tools.addDir(name, url1, 3, icon, background, '')
else:
thumb = ch.findtext('desc_image', default='')
if thumb:
thumb = thumb.replace('<![CDATA[','').replace(']]>','')
stream = ch.findtext('stream_url', default='')
url1 = tools.check_protocol(stream.replace('<![CDATA[','').replace(']]>',''))
desc_raw = ch.findtext('description', default='')
desc = tools.b64(desc_raw) if desc_raw else ''
if meta_on:
try:
plot = tools.regex_from_to(desc,'PLOT:','\n')
cast = tools.regex_from_to(desc,'CAST:','\n')
ratin= tools.regex_from_to(desc,'RATING:','\n')
year = tools.regex_from_to(desc,'RELEASEDATE:','\n').replace(' ','-')
year = re.compile('-.*?-.*?-(.*?)-',re.DOTALL).findall(year)
runt = tools.regex_from_to(desc,'DURATION_SECS:','\n')
genre= tools.regex_from_to(desc,'GENRE:','\n')
# Pass full desc (contains TMDB_ID) instead of just plot
tools.addDirMeta(str(name).replace('[/COLOR][/B].','.[/COLOR][/B]'),url1,4,thumb or background,background,desc,str(year).replace("['","" ).replace("']",""),str(cast).split(),ratin,runt,genre)
except:
pass
xbmcplugin.setContent(int(sys.argv[1]), 'vod')
else:
tools.addDir(name,url1,4,thumb or background,background,desc)
def search():
if mode==3:
return False
# Let user choose a scope
scope_items = ['Live TV & Catchup','Movies/VOD','Series','All sections']
choice = DIALOG.select('Search in', scope_items)
if choice == -1:
return
scope = ['live','vod','series','all'][choice]
text = searchdialog()
if not text:
return
q = (text or '').lower()
hidexxx = xbmcaddon.Addon().getSetting('hidexxx')=='true'
results = []
# Search Live TV (available_channels)
# Try quick network fetch with retries; fall back to a short-lived cached copy
raw = tools.OPEN_URL(panel_api)
if not raw:
raw = tools.OPEN_URL_CACHED(panel_api, ttl_minutes=1)
if raw:
try:
parse = json.loads(raw)
except Exception:
parse = {}
channels = parse.get('available_channels', {})
for key in channels:
a = channels[key]
name = a.get('name','')
lower = name.lower()
if q in lower or (q not in lower and q in name):
stream_id = str(a.get('stream_id',''))
thumb = (a.get('stream_icon','') or '').replace(r'\/', '/')
stream_type = (a.get('stream_type','') or '').replace(r'\/', '/')
container_extension = a.get('container_extension','mp4')
if not hidexxx or (hidexxx and not any(s in name for s in adult_tags)):
if scope in ('all','vod') and 'movie' in stream_type:
results.append(('movie', name, play_movies+stream_id+'.'+container_extension, 4, thumb, background, ''))
if scope in ('all','live') and 'live' in stream_type:
results.append(('live', name, play_live+stream_id, 4, thumb, background, ''))
if scope in ('all','vod'):
# Search VOD (Movies)
# Prefer cached VOD catalog to avoid blocking UI; try network if cache miss
vod_data = tools.OPEN_URL_CACHED(vod_url, ttl_minutes=tools.CONTENT_CACHE_TTL_MOVIES)
if not vod_data:
vod_data = tools.OPEN_URL(vod_url)
if vod_data:
try:
root = ET.fromstring(vod_data)
for ch in root.findall('.//channel'):
t = ch.findtext('title', default='')
name = str(tools.b64(t)).replace('?', '') if t else ''
if q in name.lower() or (q not in name.lower() and q in name):
playlist = ch.findtext('playlist_url')
thumb = ch.findtext('desc_image', default='')
if thumb:
thumb = thumb.replace('<![CDATA[','').replace(']]>','')
stream = ch.findtext('stream_url', default='')
url1 = tools.check_protocol((playlist or stream).replace('<![CDATA[','').replace(']]>',''))
desc_raw = ch.findtext('description', default='')
desc = tools.b64(desc_raw) if desc_raw else ''
if not hidexxx or (hidexxx and not any(s in name for s in adult_tags)):
results.append(('vod', name, url1, 4, thumb or background, background, desc))
except Exception:
pass
if scope in ('all','series'):
# Search Series
series_endpoint = player_api + '&action=get_series'
series_data = tools.OPEN_URL_CACHED(series_endpoint, ttl_minutes=tools.CONTENT_CACHE_TTL_SERIES)
if not series_data:
series_data = tools.OPEN_URL(series_endpoint)
if series_data:
try:
ser_cat = json.loads(series_data)
for ser in ser_cat:
name = ser.get('name','')
if q in name.lower() or (q not in name.lower() and q in name):
series_id = str(ser.get('series_id',''))
cover = ser.get('cover','')
results.append(('series', name, player_api+'&action=get_series_info&series_id='+series_id, 19, cover, background, ''))
except Exception:
pass
if scope in ('all','live'):
# Search Catch-up (if available)
catchup_raw = tools.OPEN_URL(panel_api)
if not catchup_raw:
catchup_raw = tools.OPEN_URL_CACHED(panel_api, ttl_minutes=1)
if catchup_raw:
try:
parse = json.loads(catchup_raw)
channels = parse.get('available_channels', {})
for key in channels:
a = channels[key]
if int(a.get('tv_archive', 0)) == 1:
name = (a.get('epg_channel_id','') or '').replace(r'\/', '/')
if q in name.lower() or (q not in name.lower() and q in name):
thumb = (a.get('stream_icon','') or '').replace(r'\/', '/')
sid = str(a.get('stream_id',''))
results.append(('catchup', name, 'url', 13, thumb, background, sid))
except Exception:
pass
# Display all results
section_labels = {
'live': '[B][COLOR lime]LIVE[/COLOR][/B] ',
'movie': '[B][COLOR orange]MOVIE[/COLOR][/B] ',
'vod': '[B][COLOR yellow]VOD[/COLOR][/B] ',
'series': '[B][COLOR aqua]SERIES[/COLOR][/B] ',
'catchup': '[B][COLOR orange]CATCH-UP[/COLOR][/B] '
}
# Log query and results counts, then normalize, de-duplicate and sort
try:
xbmc.log('IPTVXC: search requested q=%s' % q, LOG_NOTICE)
# raw count before de-duplication
raw_count = len(results)
seen = set()
unique_results = []
for r in results:
key = (r[0], (r[1] or '').strip().lower())
if key not in seen:
seen.add(key)
unique_results.append(r)
results = unique_results
type_priority = {'live': 0, 'movie': 1, 'vod': 2, 'series': 3, 'catchup': 4}
results.sort(key=lambda x: (type_priority.get(x[0], 99), (x[1] or '').lower()))
final_count = len(results)
xbmc.log('IPTVXC: search raw=%d final=%d q=%s' % (raw_count, final_count, q), LOG_NOTICE)
except Exception:
# If dedupe/sort/logging fails for any reason, fall back to the original order
pass
for r in results:
# r = (type, name, url, mode, thumb, background, desc/sid)
label = section_labels.get(r[0], '') + r[1]
# Playable items: mode==4, isFolder=False
if r[0] in ('movie', 'live', 'vod'):
tools.addDir(label, r[2], 4, r[4], r[5], r[6])
# Non-playable: keep original mode (series/catchup)
else:
tools.addDir(label, r[2], r[3], r[4], r[5], r[6])
######
######
def catchup():
listcatchup()
def listcatchup():
raw = tools.OPEN_URL_CACHED(panel_api, ttl_minutes=tools.CONTENT_CACHE_TTL_TV)
if not raw:
return
try:
parse = json.loads(raw)
except Exception:
return
channels = parse.get('available_channels', {})
for key in channels:
a = channels[key]
if int(a.get('tv_archive', 0)) == 1:
name = (a.get('epg_channel_id','') or '').replace(r'\/', '/')
thumb = (a.get('stream_icon','') or '').replace(r'\/', '/')
sid = str(a.get('stream_id',''))
if name:
tools.addDir(name, 'url', 13, thumb, background, sid)
def tvarchive(name,description):
days = 7
now = str(datetime.datetime.now()).replace('-','').replace(':','').replace(' ','')
date3 = datetime.datetime.now() - datetime.timedelta(days)
date = str(date3)
date = str(date).replace('-','').replace(':','').replace(' ','')
APIv2 = "{0}/player_api.php?username={1}&password={2}&action=get_simple_data_table&stream_id={3}".format(dns,username,password,description)
link = tools.OPEN_URL(APIv2)
match = re.compile('"title":"(.+?)".+?"start":"(.+?)","end":"(.+?)","description":"(.+?)"').findall(link)
for ShowTitle,start,end,DesC in match:
ShowTitle = tools.b64(ShowTitle)
DesC = tools.b64(DesC)
format = '%Y-%m-%d %H:%M:%S'
try:
modend = datetime.datetime.strptime(end, format)
modstart = datetime.datetime.strptime(start, format)
except Exception:
modend = datetime.datetime(*(time.strptime(end, format)[0:6]))
modstart = datetime.datetime(*(time.strptime(start, format)[0:6]))
StreamDuration = modend - modstart
modend_ts = time.mktime(modend.timetuple())
modstart_ts = time.mktime(modstart.timetuple())
FinalDuration = int(modend_ts-modstart_ts) / 60
strstart = start
Realstart = str(strstart).replace('-','').replace(':','').replace(' ','')
start2 = start[:-3]
editstart = start2
start2 = str(start2).replace(' ',' - ')
start = str(editstart).replace(' ',':')
Editstart = start[:13] + '-' + start[13:]
Finalstart = Editstart.replace('-:','-')
if Realstart > date:
if Realstart < now:
catchupURL = "{0}/streaming/timeshift.php?username={1}&password={2}&stream={3}&start=".format(dns,username,password,description)
ResultURL = catchupURL + str(Finalstart) + "&duration={0}".format(FinalDuration)
kanalinimi = "[B][COLOR white]{0}[/COLOR][/B] - {1}".format(start2,ShowTitle)
tools.addDir(kanalinimi,ResultURL,4,icon,background,DesC)
#############################
def tvguide():
xbmc.executebuiltin('ActivateWindow(TVGuide)')
def _playback_watchdog():
"""Background thread: dismiss busy dialogs when playback stops.
When the user presses X on a live IPTV stream, Kodi's FFmpeg demuxer
can block for 10-30 s trying to close the TCP connection. During that
time Kodi shows a 'busydialog' that nothing ever closes, making the UI
appear frozen. This watchdog detects the playing→stopped transition
and aggressively hammers Dialog.Close until the UI is responsive again.
"""
import threading
player = xbmc.Player()
monitor = xbmc.Monitor()
# 1. Wait for playback to actually start (max 30 s)
started = False
for _ in range(60):
if monitor.abortRequested():
return
if player.isPlaying():
started = True
break
xbmc.sleep(500)
if not started:
# Playback never began — clean up and leave
xbmc.executebuiltin('Dialog.Close(busydialog)')
xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
xbmc.log(f'{ADDON_ID}: watchdog – playback never started, exiting', LOG_NOTICE)
return
xbmc.log(f'{ADDON_ID}: watchdog – playback started, monitoring', LOG_NOTICE)
# 2. Wait until the player stops
while not monitor.abortRequested():
if not player.isPlaying():
break
xbmc.sleep(500)
xbmc.log(f'{ADDON_ID}: watchdog – playback stopped, dismissing busy dialogs', LOG_NOTICE)
# 3. Aggressively close busy dialogs for up to 10 s so the UI never
# appears stuck while FFmpeg tears down the connection.
for _ in range(20):
if monitor.abortRequested():
return
xbmc.executebuiltin('Dialog.Close(busydialog)')
xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
xbmc.sleep(500)
def _start_playback_watchdog():
"""Launch the playback watchdog in a daemon thread."""
import threading
t = threading.Thread(target=_playback_watchdog,
name='IPTVXC-PlayWatchdog', daemon=True)
t.start()
def apply_subtitles_for_playback(player_obj, url_arg, name_arg='', desc_arg=''):
"""
Spawn a short-lived thread that waits for playback to start and then
sets subtitle visibility according to addon settings per content type.
"""
try:
import threading
except Exception:
threading = None
def _worker():
startt = time.time()
while time.time() - startt < 30:
try:
if player_obj.isPlaying():
try:
cat = tools.classify_favorite(mode, url_arg, desc_arg or '', name_arg or '')
except Exception:
cat = 'live'
try:
if cat == 'series':
enabled = ADDON.getSetting('subtitles_series') == 'true'
elif cat == 'vod':
enabled = ADDON.getSetting('subtitles_vod') == 'true'
else:
enabled = ADDON.getSetting('subtitles_live') == 'true'
except Exception:
enabled = False
try:
player_obj.showSubtitles(bool(enabled))
except Exception as e:
try:
xbmc.log(f'{ADDON_ID}: apply_subtitles failed: {e}', LOG_NOTICE)
except Exception:
pass
break
except Exception:
pass
xbmc.sleep(500)
try:
if threading:
t = threading.Thread(target=_worker, daemon=True)
t.start()
else:
_worker()
except Exception:
try:
_worker()
except Exception:
pass
def stream_video(url):
url = buildcleanurl(url)
# Log to history and save as last played
tools.add_to_history(url, name or '', iconimage or icon, description or '')
tools.save_last_played(url, name or '', iconimage or icon, description or '')
xbmc.log(f'{ADDON_ID}: stream_video() resolving URL: {url[:120]}', LOG_NOTICE)
# Try to get current programme info for the info overlay
now_title, now_desc = '', ''
try:
# Extract stream_id from URL (last path segment)
sid = url.rstrip('/').split('/')[-1].split('.')[0]
if sid.isdigit():
now_title, now_desc = epg.get_now_playing(player_api, sid)
except Exception:
pass
liz = xbmcgui.ListItem(path=str(url), offscreen=True)
liz.setArt({'icon': icon, 'thumb': icon})
display_title = now_title if now_title else (name or '')
display_desc = now_desc if now_desc else (description or '')
liz.setInfo(type='Video', infoLabels={'Title': display_title, 'Plot': display_desc, 'TVShowTitle': name or ''})
liz.setContentLookup(False)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz)
xbmc.log(f'{ADDON_ID}: stream_video() resolved OK', LOG_NOTICE)
# Force-close Kodi's busy dialog in case it lingers while the player
# buffers or while a remote thumbnail download is blocking the main
# thread. A short sleep lets setResolvedUrl propagate first.
xbmc.sleep(200)
xbmc.executebuiltin('Dialog.Close(busydialog)')
xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
# Start background watchdog (best-effort) and also keep this script
# alive for a short while. By spinning in the main thread we can
# repeatedly close dialogs even if the addon process is terminated
# by Kodi shortly after resolving the URL.
_start_playback_watchdog()
# call the EPG updater
epg.start_epg_updater(player_api, url, name or '')
player = xbmc.Player()
# Ensure subtitles follow addon settings once playback actually starts
try:
apply_subtitles_for_playback(player, url, name or '', description or '')
except Exception:
pass
# Wait for playback to actually start (up to 10 s), then exit as soon
# as it stops. This prevents the invoker staying alive for the full
# 30-second guard window after the user presses X to stop.
start = time.time()
playback_started = False
while time.time() - start < 30:
if player.isPlaying():
playback_started = True
elif playback_started:
# Playback started and has now stopped — clean up and exit
xbmc.executebuiltin('Dialog.Close(busydialog)')
xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
break
elif time.time() - start > 10:
# Playback never started within 10 s — give up
break
# small delay prevents hogging CPU
xbmc.sleep(500)
def searchdialog():
search = control.inputDialog(heading='Search '+ADDON_NAME+':')
if search=="":
return
else:
return search
def settingsmenu():
if xbmcaddon.Addon().getSetting('meta')=='true':
META = '[B][COLOR lime]ON[/COLOR][/B]'
else:
META = '[B][COLOR red]OFF[/COLOR][/B]'
if xbmcaddon.Addon().getSetting('hidexxx')=='true':
xxx = '[B][COLOR lime]ON[/COLOR][/B]'
else:
xxx = '[B][COLOR red]OFF[/COLOR][/B]'
tools.addDir('Switch Server','url',34,icon,background,'')
tools.addDir('Edit Advanced Settings','ADS',10,icon,background,'')
tools.addDir('META is %s'%META,'META',10,icon,background,META)
tools.addDir('Hide Adult Content is %s'%xxx,'XXX',10,icon,background,xxx)
tools.addDir('Log Out','LO',10,icon,background,'')
def addonsettings(url,description):
url = buildcleanurl(url)
if url =="clearcache":
tools.clear_cache()
elif url =="AS":
xbmc.executebuiltin('Addon.OpenSettings(%s)'% ADDON_ID)
elif url =="ADS":
dialog = xbmcgui.Dialog().select('Edit Advanced Settings', ['Open AutoConfig','Enable Fire TV Stick AS','Enable Fire TV AS','Enable 1GB Ram or Lower AS','Enable 2GB Ram or Higher AS','Enable Nvidia Shield AS','Disable AS'])
if dialog==0:
advancedsettings('auto')
elif dialog==1:
advancedsettings('stick')
tools.ASln()
elif dialog==2:
advancedsettings('firetv')
tools.ASln()
elif dialog==3:
advancedsettings('lessthan')
tools.ASln()
elif dialog==4:
advancedsettings('morethan')
tools.ASln()
elif dialog==5:
advancedsettings('shield')
tools.ASln()
elif dialog==6:
advancedsettings('remove')
xbmcgui.Dialog().ok(ADDON_NAME, 'Advanced Settings Removed')
elif url =="ADS2":
dialog = xbmcgui.Dialog().select('Select Your Device Or Closest To', ['Open AutoConfig','Fire TV Stick ','Fire TV','1GB Ram or Lower','2GB Ram or Higher','Nvidia Shield'])
if dialog==0:
advancedsettings('auto')
tools.ASln()
elif dialog==1:
advancedsettings('stick')
tools.ASln()
elif dialog==2:
advancedsettings('firetv')
tools.ASln()
elif dialog==3:
advancedsettings('lessthan')
tools.ASln()
elif dialog==4:
advancedsettings('morethan')
tools.ASln()
elif dialog==5:
advancedsettings('shield')
tools.ASln()
elif url =="tv":
dialog = xbmcgui.Dialog().yesno(ADDON_NAME,'Would You like us to Setup the TV Guide for You?')
if dialog:
pvrsetup()
xbmcgui.Dialog().ok(ADDON_NAME, 'PVR Integration Complete, Restart Kodi For Changes To Take Effect')
elif url =="Itv":
xbmc.executebuiltin('InstallAddon(pvr.iptvsimple)')
elif url =="ST":
# Only run the speed test, do not prompt for M3U or provider
speedtest.speedtest()
return
elif url =="META":
if 'ON' in description:
xbmcaddon.Addon().setSetting('meta','false')
xbmc.executebuiltin('Container.Refresh')
else:
xbmcaddon.Addon().setSetting('meta','true')
xbmc.executebuiltin('Container.Refresh')
elif url =="XXX":
if 'ON' in description:
pas = tools.keypopup('Enter Adult Password:')
if pas ==control.setting('xxx_pw'):
xbmcaddon.Addon().setSetting('hidexxx','false')
xbmc.executebuiltin('Container.Refresh')
else:
xbmcaddon.Addon().setSetting('hidexxx','true')
xbmc.executebuiltin('Container.Refresh')
elif url =="LO":
xbmcaddon.Addon().setSetting('DNS','')
xbmcaddon.Addon().setSetting('Username','')
xbmcaddon.Addon().setSetting('Password','')
xbmc.executebuiltin('XBMC.ActivateWindow(Videos,addons://sources/video/)')
xbmc.executebuiltin('Container.Refresh')
elif url =="UPDATE":
if 'ON' in description:
xbmcaddon.Addon().setSetting('update','false')
xbmc.executebuiltin('Container.Refresh')
else:
xbmcaddon.Addon().setSetting('update','true')
xbmc.executebuiltin('Container.Refresh')
elif url == "RefM3U":
DP.create(ADDON_NAME, "Please Wait")
tools.gen_m3u(panel_api, M3U_PATH)
def adult_set():
dialog = DIALOG.yesno(ADDON_NAME,'Would you like to hide the Adult Menu? \nYou can always change this in settings later on.')
if dialog:
control.setSetting('xxx_pwset','true')
pass
else:
control.setSetting('xxx_pwset','false')
pass
dialog = DIALOG.yesno(ADDON_NAME,'Would you like to Password Protect Adult Content? \nYou can always change this in settings later on.')
if dialog:
control.setSetting('xxx_pwset','true')
adultpw = tools.keypopup('Enter Password')
control.setSetting('xxx_pw',adultpw)
else:
control.setSetting('xxx_pwset','false')
pass
def advancedsettings(device):
if device == 'stick':
file = open(os.path.join(advanced_settings, 'stick.xml'))
elif device =='auto':
popup.autoConfigQ()
elif device == 'firetv':
file = open(os.path.join(advanced_settings, 'firetv.xml'))
elif device == 'lessthan':
file = open(os.path.join(advanced_settings, 'lessthan1GB.xml'))
elif device == 'morethan':
file = open(os.path.join(advanced_settings, 'morethan1GB.xml'))
elif device == 'shield':
file = open(os.path.join(advanced_settings, 'shield.xml'))
elif device == 'remove':
os.remove(ADVANCED)
try:
read = file.read()
f = open(ADVANCED, mode='w+')
f.write(read)
f.close()
except:
pass
def accountinfo():
response = tools.OPEN_URL(panel_api)
if not response:
tools.addDir('[B][COLOR white]Account Information:[/COLOR][/B] Unable to fetch account details (no response)', '', '', icon, background, '')
return
try:
parse = json.loads(response)
except Exception as e:
try:
xbmc.log(f'{ADDON_ID}: accountinfo() JSON parse error: {e}', LOG_NOTICE)
except Exception:
pass
tools.addDir('[B][COLOR white]Account Information:[/COLOR][/B] Unable to parse server response', '', '', icon, background, '')
return
user_info = parse.get('user_info', {}) or {}
expiry_raw = user_info.get('exp_date', '')
expiry = 'Unlimited'
if expiry_raw not in (None, '', '0'):
try:
expiry_ts = int(expiry_raw)
expiry = datetime.datetime.fromtimestamp(expiry_ts).strftime('%d/%m/%Y - %H:%M')
expreg = re.compile('^(.*?)/(.*?)/(.*?)$', re.DOTALL).findall(expiry)
if expreg:
day, month, year = expreg[0]
month = tools.MonthNumToName(month)
year = re.sub(' -.*?$', '', year)
expiry = month + ' ' + day + ' - ' + year
except Exception:
expiry = 'Unlimited'
username = str(user_info.get('username', ''))
password = str(user_info.get('password', ''))
status = str(user_info.get('status', ''))
active_cons = str(user_info.get('active_cons', ''))
max_connections = str(user_info.get('max_connections', ''))
local_ip = str(tools.getlocalip() or '')
external_ip = str(tools.getexternalip() or '')
tools.addDir('[B][COLOR white]Username :[/COLOR][/B] ' + username, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Password :[/COLOR][/B] ' + password, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Expiry Date:[/COLOR][/B] ' + expiry, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Account Status :[/COLOR][/B] %s' % status, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Current Connections:[/COLOR][/B] ' + active_cons, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Allowed Connections:[/COLOR][/B] ' + max_connections, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Local IP Address:[/COLOR][/B] ' + local_ip, '', '', icon, background, '')
tools.addDir('[B][COLOR white]External IP Address:[/COLOR][/B] ' + external_ip, '', '', icon, background, '')
tools.addDir('[B][COLOR white]Kodi Version:[/COLOR][/B] ' + str(KODIV), '', '', icon, background, '')
def waitasec(time_to_wait,title,text):
FTGcd = xbmcgui.DialogProgress()
ret = FTGcd.create(' '+title)
secs=0
percent=0
increment = int(100 / time_to_wait)
cancelled = False
while secs < time_to_wait:
secs += 1
percent = increment*secs
secs_left = str((time_to_wait - secs))
remaining_display = "Still " + str(secs_left) + "seconds left"
FTGcd.update(percent,text+'\n'+remaining_display)
xbmc.sleep(1000)
if (FTGcd.iscanceled()):
cancelled = True
break
if cancelled == True:
return False
else:
FTGcd.close()
return False
def tester():
try:
xbmc.log('[IPTVXC] tester() called', LOG_NOTICE)
addon = xbmcaddon.Addon()
dns = addon.getSetting(id='DNS')
user = addon.getSetting(id='Username')
pw = addon.getSetting(id='Password')
if not dns or not user or not pw:
DIALOG.ok(ADDON_NAME, 'Please enter DNS, Username and Password in Settings')
return
auth_url = '{0}/player_api.php?username={1}&password={2}'.format(dns, user, pw)
response = tools.OPEN_URL(auth_url)
if not response:
DIALOG.ok(ADDON_NAME, 'No response from server when testing credentials')
return
try:
parse = json.loads(response)
except Exception:
DIALOG.ok(ADDON_NAME, 'Invalid response from server')
return
login_data = None
try:
login_data = parse.get('user_info', {}).get('auth')
except:
login_data = None
if login_data in (None, 0, '0'):
DIALOG.ok(ADDON_NAME, 'Test Failed\nIncorrect Login Details')
else:
DIALOG.ok(ADDON_NAME, 'Test Successful\nCredentials appear valid')
return
except Exception as e:
DIALOG.ok(ADDON_NAME, 'Test Error\n%s' % str(e))
return
def pvrsetup():
correctPVR()
return
def correctPVR():
DIALOG.ok(ADDON_NAME, 'This will generate a local M3U playlist and configure PVR IPTV Simple Client with your EPG.\n\nThis may take a minute depending on your channel count.')
try:
addon = xbmcaddon.Addon(ADDON_ID)
dns_text = addon.getSetting(id='DNS').rstrip('/')
username_text = addon.getSetting(id='Username')
password_text = addon.getSetting(id='Password')
EPGurl = dns_text + "/xmltv.php?username=" + username_text + "&password=" + password_text