-
Notifications
You must be signed in to change notification settings - Fork 0
/
e2m3u2bouquet-name.py
1688 lines (1494 loc) · 84.8 KB
/
e2m3u2bouquet-name.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 python2
# encoding: utf-8
"""
e2m3u2bouquet.e2m3u2bouquet -- Enigma2 IPTV m3u to bouquet parser
@author: Dave Sully, Doug Mackay
@copyright: 2017 All rights reserved.
@license: GNU GENERAL PUBLIC LICENSE version 3
@deffield updated: Updated
"""
import time
import sys
import os
import errno
import re
import unicodedata
import datetime
import urllib
import urlparse
import imghdr
import tempfile
import glob
import ssl
import hashlib
import socket
from PIL import Image
from collections import OrderedDict
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
try:
from enigma import eDVBDB
except ImportError:
eDVBDB = None
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
__all__ = []
__version__ = '0.8.2'
__date__ = '2017-06-04'
__updated__ = '2018-12-26'
DEBUG = 0
TESTRUN = 0
ENIGMAPATH = '/etc/enigma2/'
EPGIMPORTPATH = '/etc/epgimport/'
CFGPATH = os.path.join(ENIGMAPATH, 'e2m3u2bouquet/')
PICONSPATH = '/usr/share/enigma2/picon/'
IMPORTED = False
PLACEHOLDER_SERVICE = '#SERVICE 1:832:d:0:0:0:0:0:0:0:'
class CLIError(Exception):
"""Generic exception to raise and log different fatal errors."""
def __init__(self, msg):
super(CLIError).__init__(type(self))
self.msg = "E: %s" % msg
def __str__(self):
return self.msg
def __unicode__(self):
return self.msg
class AppUrlOpener(urllib.FancyURLopener):
"""Set user agent for downloads
"""
version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
def display_welcome():
print('\n********************************')
print('Starting Enigma2 IPTV bouquets v{}'.format(__version__))
print(str(datetime.datetime.now()))
print("********************************\n")
def display_end_msg():
print("\n********************************")
print("Enigma2 IPTV bouquets created ! ")
print("********************************")
print("\nTo enable EPG data")
print("Please open EPG-Importer plugin.. ")
print("Select sources and enable the new IPTV source")
print("(will be listed as under 'IPTV Bouquet Maker - E2m3u2bouquet')")
print("Save the selected sources, press yellow button to start manual import")
print("You can then set EPG-Importer to automatically import the EPG every day")
def make_config_folder():
"""create config folder if it doesn't exist
"""
try:
os.makedirs(CFGPATH)
except OSError, e: # race condition guard
if e.errno != errno.EEXIST:
raise
def uninstaller():
"""Clean up routine to remove any previously made changes
"""
print('----Running uninstall----')
try:
# Bouquets
print('Removing old IPTV bouquets...')
for fname in os.listdir(ENIGMAPATH):
if 'userbouquet.suls_iptv_' in fname:
os.remove(os.path.join(ENIGMAPATH, fname))
elif 'bouquets.tv.bak' in fname:
os.remove(os.path.join(ENIGMAPATH, fname))
# Custom Channels and sources
print('Removing IPTV custom channels...')
if os.path.isdir(EPGIMPORTPATH):
for fname in os.listdir(EPGIMPORTPATH):
if 'suls_iptv_' in fname:
os.remove(os.path.join(EPGIMPORTPATH, fname))
# bouquets.tv
print('Removing IPTV bouquets from bouquets.tv...')
os.rename(os.path.join(ENIGMAPATH, 'bouquets.tv'), os.path.join(ENIGMAPATH, 'bouquets.tv.bak'))
tvfile = open(os.path.join(ENIGMAPATH, 'bouquets.tv'), 'w+')
bakfile = open(os.path.join(ENIGMAPATH, 'bouquets.tv.bak'))
for line in bakfile:
if '.suls_iptv_' not in line:
tvfile.write(line)
bakfile.close()
tvfile.close()
except Exception, e:
print('Unable to uninstall')
raise
print('----Uninstall complete----')
def get_category_title(cat, category_options):
"""Return the title override if set else the title
"""
if cat in category_options:
return category_options[cat]['nameOverride'] if category_options[cat].get('nameOverride', False) else cat
return cat
def get_service_title(channel):
"""Return the title override if set else the title
"""
return channel['nameOverride'] if channel.get('nameOverride', False) else channel['stream-name']
def reload_bouquets():
if not TESTRUN:
print("\n----Reloading bouquets----")
if eDVBDB:
eDVBDB.getInstance().reloadBouquets()
print("bouquets reloaded...")
else:
os.system("wget -qO - http://127.0.0.1/web/servicelistreload?mode=2 > /dev/null 2>&1 &")
print("bouquets reloaded...")
def xml_safe_comment(string):
"""Can't have -- in xml comments"""
return string.replace('--', '- - ')
def xml_escape(string):
return string.replace("&", "&") \
.replace("\"", """) \
.replace("'", "'") \
.replace("<", "<") \
.replace(">", ">")
def xml_unescape(string):
return string.replace('"', '"') \
.replace() \
.replace("'", "'") \
.replace("<", "<") \
.replace(">", ">") \
.replace("&", "&")
def get_safe_filename(filename):
"""Convert filename to safe filename
"""
name = filename.replace(" ", "_").replace("/", "_")
if type(name) is unicode:
name = name.encode('utf-8')
name = unicodedata.normalize('NFKD', unicode(name, 'utf_8')).encode('ASCII', 'ignore')
name = re.sub('[^a-z0-9-_]', '', name.lower())
return name
def get_parser_args(program_license, program_version_message):
parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
# URL Based Setup
urlgroup = parser.add_argument_group('URL Based Setup')
urlgroup.add_argument('-m', '--m3uurl', dest='m3uurl', action='store',
help='URL to download m3u data from (required)')
urlgroup.add_argument('-e', '--epgurl', dest='epgurl', action='store',
help='URL source for XML TV epg data sources')
# Provider based setup
providergroup = parser.add_argument_group('Provider Based Setup')
providergroup.add_argument('-n', '--providername', dest='providername', action='store',
help='Host IPTV provider name (e.g. FAB/EPIC) (required)')
providergroup.add_argument('-u', '--username', dest='username', action='store',
help='Your IPTV username (required)')
providergroup.add_argument('-p', '--password', dest='password', action='store',
help='Your IPTV password (required)')
# Options
parser.add_argument('-i', '--iptvtypes', dest='iptvtypes', action='store_true',
help='Treat all stream references as IPTV stream type. (required for some enigma boxes)')
parser.add_argument('-sttv', '--streamtype_tv', dest='sttv', action='store', type=int,
help='Stream type for TV (e.g. 1, 4097, 5001 or 5002) overrides iptvtypes')
parser.add_argument('-stvod', '--streamtype_vod', dest='stvod', action='store', type=int,
help='Stream type for VOD (e.g. 4097, 5001 or 5002) overrides iptvtypes')
parser.add_argument('-M', '--multivod', dest='multivod', action='store_true',
help='Create multiple VOD bouquets rather single VOD bouquet')
parser.add_argument('-a', '--allbouquet', dest='allbouquet', action='store_true',
help='Create all channels bouquet')
parser.add_argument('-P', '--picons', dest='picons', action='store_true',
help='Automatically download of Picons, this option will slow the execution')
parser.add_argument('-q', '--iconpath', dest='iconpath', action='store',
help='Option path to store picons, if not supplied defaults to /usr/share/enigma2/picon/')
parser.add_argument('-xs', '--xcludesref', dest='xcludesref', action='store_true',
help='Disable service ref overriding from override.xml file')
parser.add_argument('-b', '--bouqueturl', dest='bouqueturl', action='store',
help='URL to download providers bouquet - to map custom service references')
parser.add_argument('-bd', '--bouquetdownload', dest='bouquetdownload', action='store_true',
help='Download providers bouquet (use default url) - to map custom service references')
parser.add_argument('-bt', '--bouquettop', dest='bouquettop', action='store_true',
help='Place IPTV bouquets at top')
parser.add_argument('-U', '--uninstall', dest='uninstall', action='store_true',
help='Uninstall all changes made by this script')
parser.add_argument('-V', '--version', action='version', version=program_version_message)
return parser
class Status:
is_running = False
message = ''
class ProviderConfig:
def __init__(self):
self.name = ''
self.enabled = False
self.settings_level = ''
self.m3u_url = ''
self.epg_url = ''
self.username = ''
self.password = ''
self.provider_update_url = ''
self.iptv_types = False
self.streamtype_tv = ''
self.streamtype_vod = ''
self.multi_vod = False
self.all_bouquet = False
self.picons = False
self.icon_path = ''
self.sref_override = False
self.bouquet_url = ''
self.bouquet_download = False
self.bouquet_top = False
self.last_provider_update = 0
class Provider:
def __init__(self, config):
self._panel_bouquet_file = ''
self._panel_bouquet = None
self._m3u_file = None
self._category_order = []
self._category_options = {}
self._dictchannels = OrderedDict()
self._xmltv_sources_list = None
self.config = config
def _download_picon_file(self, logo_url, title):
if logo_url:
if not logo_url.startswith('http'):
logo_url = 'http://{}'.format(logo_url)
piconname = self._get_picon_name(title)
picon_file_path = os.path.join(self.config.icon_path, piconname)
existingpicon = filter(os.path.isfile, glob.glob(picon_file_path + '*'))
if not existingpicon:
if DEBUG:
print("Picon file doesn't exist downloading")
print('PiconURL: {}'.format(logo_url))
else:
# Output some kind of progress indicator
if not IMPORTED:
# don't output when called from the plugin
sys.stdout.write('.')
sys.stdout.flush()
try:
response = urllib.urlopen(logo_url)
info = response.info()
response.close()
if info.maintype == 'image':
urllib.urlretrieve(logo_url, picon_file_path)
else:
if DEBUG:
print('Download Picon - not an image, skipping')
self._picon_create_empty(picon_file_path)
return
except Exception, e:
if DEBUG:
print('Download picon urlopen error', e)
self._picon_create_empty(picon_file_path)
return
self._picon_post_processing(picon_file_path)
def _picon_create_empty(self, picon_file_path):
"""
create an empty picon so that we don't retry this picon
"""
open(picon_file_path + '.None', 'a').close()
def _picon_post_processing(self, picon_file_path):
"""Check type of image received and convert to png
if necessary
"""
ext = ""
# get image type
try:
ext = imghdr.what(picon_file_path)
except Exception, e:
if DEBUG:
print('Picon post processing - not an image or no file', e, picon_file_path)
self._picon_create_empty(picon_file_path)
return
# if image but not png convert to png
if (ext is not None) and (ext is not 'png'):
if DEBUG:
print('Converting Picon to png')
try:
Image.open(picon_file_path).save("{}.{}".format(picon_file_path, 'png'))
except Exception, e:
if DEBUG:
print('Picon post processing - unable to convert image', e)
self._picon_create_empty(picon_file_path)
return
try:
# remove non png file
os.remove(picon_file_path)
except Exception, e:
if DEBUG:
print('Picon post processing - unable to remove non png file', e)
return
else:
# rename to correct extension
try:
os.rename(picon_file_path, "{}.{}".format(picon_file_path, ext))
except Exception, e:
if DEBUG:
print('Picon post processing - unable to rename file ', e)
def _get_picon_name(self, service_name):
"""Convert the service name to a Picon Service Name
"""
name = service_name
if type(name) is unicode:
name = name.encode('utf-8')
name = unicodedata.normalize('NFKD', unicode(name, 'utf_8')).encode('ASCII', 'ignore')
name = re.sub('[\W]', '', name.replace('&', 'and')
.replace('+', 'plus')
.replace('*', 'star')
.lower())
return name
def _parse_panel_bouquet(self):
"""Check providers bouquet for custom service references
"""
self._panel_bouquet = {}
if os.path.isfile(self._panel_bouquet_file):
with open(self._panel_bouquet_file, "r") as f:
for line in f:
if '#SERVICE' in line:
# get service ref values we need (dict value) and stream file (dict key)
service = line.strip().split(':')
if len(service) == 11:
pos = service[10].rfind('/')
if pos != -1 and (pos + 1 != len(service[10])):
key = service[10][pos + 1:]
value = ':'.join((service[1], service[2], service[3], service[4], service[5],
service[6], service[7], service[8], service[9]))
if value != '0:1:0:0:0:0:0:0:0':
# only add to dict if a custom service id is present
self._panel_bouquet[key] = value
if not DEBUG:
# remove panel bouquet file
os.remove(self._panel_bouquet_file)
def _set_streamtypes_vodcats(self, service_dict):
"""Set the stream types and VOD categories
"""
parsed_stream_url = urlparse.urlparse(service_dict['stream-url'])
root, ext = os.path.splitext(parsed_stream_url.path)
# check for vod streams ending .*.m3u8 e.g. 2345.mp4.m3u8
is_m3u8_vod = re.search('\.[^/]+\.m3u8$', parsed_stream_url.path)
if (parsed_stream_url.path.endswith('.ts') or parsed_stream_url.path.endswith('.m3u8')) \
or not ext \
and not is_m3u8_vod \
and not service_dict['group-title'].startswith('VOD'):
service_dict['stream-type'] = '4097' if self.config.iptv_types else '1'
if self.config.streamtype_tv:
# Set custom TV stream type if supplied - this overrides all_iptv_stream_types
service_dict['stream-type'] = str(self.config.streamtype_tv)
else:
service_dict['group-title'] = u"VOD - {}".format(service_dict['group-title'])
service_dict['stream-type'] = '4097' if not self.config.streamtype_vod else str(self.config.streamtype_vod)
def _parse_map_bouquet_xml(self):
"""Check for bouquets within mapping override file and applies if found
"""
category_order = []
mapping_file = self._get_mapping_file()
if mapping_file:
self._update_status('----Parsing custom bouquet order----')
print('\n'.format(Status.message))
try:
tree = ET.ElementTree(file=mapping_file)
for node in tree.findall(".//category"):
dictoption = {}
category = node.attrib.get('name')
if not type(category) is unicode:
category = category.decode("utf-8")
cat_title_override = node.attrib.get('nameOverride', '')
if not type(cat_title_override) is unicode:
cat_title_override = cat_title_override.decode("utf-8")
dictoption['nameOverride'] = cat_title_override
dictoption['idStart'] = int(node.attrib.get('idStart', '0')) \
if node.attrib.get('idStart', '0').isdigit() else 0
dictoption['enabled'] = node.attrib.get('enabled', True) == 'true'
category_order.append(category)
# If this category is marked as custom and doesn't exist in self._dictchannels then add
is_custom_category = node.attrib.get('customCategory', False) == 'true'
if is_custom_category:
dictoption['customCategory'] = True
if category not in self._dictchannels:
self._dictchannels[category] = []
self._category_options[category] = dictoption
self._update_status('custom bouquet order applied...')
print(Status.message)
except Exception, e:
msg = 'Corrupt override.xml file'
print(msg)
if DEBUG:
raise msg
return category_order
def _parse_map_channels_xml(self):
"""Check for channels within mapping override file and apply if found
"""
mapping_file = self._get_mapping_file()
if mapping_file:
self._update_status('----Parsing custom channel order, please be patient----')
print('\n{}'.format(Status.message))
try:
tree = ET.ElementTree(file=mapping_file)
i = 0
for cat in self._dictchannels:
if not cat.startswith("VOD"):
# We don't override any individual VOD streams
sortedchannels = []
listchannels = []
# find channels that are to be moved to this category (categoryOverride)
for node in tree.findall(u'.//channel[@categoryOverride="{}"]'.format(cat)):
node_name = node.attrib.get('name')
category = node.attrib.get('category')
channel_index = None
# get index of channel in the current category
try:
channel_index = next((self._dictchannels[category].index(item) for item in self._dictchannels[category]
if item['stream-name'] == node_name), None)
except KeyError:
pass
if channel_index is not None:
# remove from existing category and add to new
self._dictchannels[cat].append(self._dictchannels[category].pop(channel_index))
for x in self._dictchannels[cat]:
listchannels.append(x['stream-name'])
for node in tree.findall(u'.//channel[@category="{}"]'.format(cat)):
# Check for placeholders, give unique name, insert into sorted channels and dictchannels[cat]
node_name = node.attrib.get('name')
if node_name == 'placeholder':
node_name = 'placeholder_' + str(i)
listchannels.append(node_name)
self._dictchannels[cat].append({'stream-name': node_name})
i += 1
sortedchannels.append(node_name)
sortedchannels.extend(listchannels)
# remove duplicates, keep order
listchannels = OrderedDict((x, True) for x in sortedchannels).keys()
# sort the channels by new order
channel_order_dict = {channel: index for index, channel in enumerate(listchannels)}
self._dictchannels[cat].sort(key=lambda x: channel_order_dict[x['stream-name']])
self._update_status('custom channel order applied...')
print(Status.message)
# apply overrides
channel_nodes = tree.iter('channel')
for override_channel in channel_nodes:
name = override_channel.attrib.get('name')
category = override_channel.attrib.get('category')
category_override = override_channel.attrib.get('categoryOverride')
channel_index = None
channels_list = None
if category_override:
# check if the channel has been moved to the new category
try:
channel_index = next((self._dictchannels[category_override].index(item) for item in self._dictchannels[category_override]
if item['stream-name'] == name), None)
except KeyError:
pass
if category_override and channel_index is not None:
channels_list = self._dictchannels.get(category_override)
else:
channels_list = self._dictchannels.get(category)
if channels_list is not None and name != 'placeholder':
for x in channels_list:
if x['stream-name'] == name:
if override_channel.attrib.get('enabled') == 'false':
x['enabled'] = False
x['nameOverride'] = override_channel.attrib.get('nameOverride', '')
x['categoryOverride'] = override_channel.attrib.get('categoryOverride', '')
# default to current values if attribute doesn't exist
x['tvg-id'] = override_channel.attrib.get('tvg-name', x['tvg-name'])
if override_channel.attrib.get('serviceRef', None) and self.config.sref_override:
x['serviceRef'] = override_channel.attrib.get('serviceRef', x['serviceRef'])
x['serviceRefOverride'] = True
# streamUrl no longer output to xml file but we still check and process it
x['stream-url'] = override_channel.attrib.get('streamUrl', x['stream-url'])
clear_stream_url = override_channel.attrib.get('clearStreamUrl') == 'true'
if clear_stream_url:
x['stream-url'] = ''
break
self._update_status('custom overrides applied...')
print(Status.message)
except Exception, e:
msg = 'Corrupt override.xml file'
print(msg)
if DEBUG:
raise msg
def _get_mapping_file(self):
mapping_file = None
search_path = [os.path.join(CFGPATH, get_safe_filename(self.config.name) + '-sort-override.xml'),
os.path.join(os.getcwd(), get_safe_filename(self.config.name) + '-sort-override.xml')]
for path in search_path:
if os.path.isfile(path):
mapping_file = path
break;
return mapping_file
def _save_bouquet_entry(self, f, channel):
"""Add service to bouquet file
"""
if not channel['stream-name'].startswith('placeholder_'):
f.write("#SERVICE {}:{}:{}\n"
.format(channel['serviceRef'], urllib.quote(channel['stream-url']),
get_service_title(channel).encode("utf-8")))
f.write("#DESCRIPTION {}\n".format(get_service_title(channel).encode("utf-8")))
else:
f.write('{}\n'.format(PLACEHOLDER_SERVICE))
def _get_bouquet_index_name(self, cat_filename, provider_filename):
return ('#SERVICE 1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.suls_iptv_{}_{}.tv" ORDER BY bouquet\n'
.format(provider_filename, cat_filename))
def _save_bouquet_index_entries(self, iptv_bouquets):
"""Add to the main bouquets.tv file
"""
# get current bouquets indexes
current_bouquet_indexes = self._get_current_bouquet_indexes()
if iptv_bouquets:
with open(os.path.join(ENIGMAPATH, 'bouquets.tv'), 'w') as f:
f.write('#NAME Bouquets (TV)\n')
if self.config.bouquet_top:
for bouquet in iptv_bouquets:
f.write(bouquet)
for bouquet in current_bouquet_indexes:
f.write(bouquet)
else:
for bouquet in current_bouquet_indexes:
f.write(bouquet)
for bouquet in iptv_bouquets:
f.write(bouquet)
def _get_current_bouquet_indexes(self):
"""Get all the bouquet indexes except this provider
"""
current_bouquets_indexes = []
with open(os.path.join(ENIGMAPATH, 'bouquets.tv'), 'r') as f:
for line in f:
if line.startswith('#NAME'):
continue
else:
if not '.suls_iptv_{}'.format(get_safe_filename(self.config.name)) in line:
current_bouquets_indexes.append(line)
return current_bouquets_indexes
def _create_all_channels_bouquet(self):
"""Create the Enigma2 all channels bouquet
"""
self._update_status('----Creating all channels bouquet----')
print('\n{}'.format(Status.message))
bouquet_indexes = []
vod_categories = list(cat for cat in self._category_order if cat.startswith('VOD -'))
bouquet_name = '{} All Channels'.format(self.config.name)
cat_filename = get_safe_filename(bouquet_name)
provider_filename = get_safe_filename(self.config.name)
# create file
bouquet_filepath = os.path.join(ENIGMAPATH, 'userbouquet.suls_iptv_{}_{}.tv'
.format(provider_filename, cat_filename))
if DEBUG:
print("Creating: {}".format(bouquet_filepath))
with open(bouquet_filepath, 'w+') as f:
f.write('#NAME {} - {}\n'.format(self.config.name.encode('utf-8'), bouquet_name.encode('utf-8')))
# write place holder channels (for channel numbering)
for i in xrange(100):
f.write('{}\n'.format(PLACEHOLDER_SERVICE))
channel_num = 1
for cat in self._category_order:
if cat in self._dictchannels:
if cat not in vod_categories:
cat_title = get_category_title(cat, self._category_options)
# Insert group description placeholder in bouquet
f.write("#SERVICE 1:64:0:0:0:0:0:0:0:0:\n")
f.write("#DESCRIPTION {}\n".format(cat_title.encode('utf-8')))
for x in self._dictchannels[cat]:
if x.get('enabled') or x['stream-name'].startswith('placeholder_'):
self._save_bouquet_entry(f, x)
channel_num += 1
while (channel_num % 100) is not 0:
f.write('{}\n'.format(PLACEHOLDER_SERVICE))
channel_num += 1
# Add to bouquet index list
bouquet_indexes.append(self._get_bouquet_index_name(cat_filename, provider_filename))
self._update_status('all channels bouquet created ...')
print(Status.message)
return bouquet_indexes
def _create_epgimport_source(self, sources, group=None):
"""Create epg-importer source file
"""
indent = " "
source_name = '{} - {}'.format(self.config.name, group) if group else self.config.name
channels_filename = os.path.join(EPGIMPORTPATH, 'suls_iptv_{}_channels.xml'.format(get_safe_filename(self.config.name)))
# write providers epg feed
source_filename = os.path.join(EPGIMPORTPATH, 'suls_iptv_{}.sources.xml'
.format(get_safe_filename(source_name)))
with open(os.path.join(EPGIMPORTPATH, source_filename), "w+") as f:
f.write('<sources>\n')
f.write('{}<sourcecat sourcecatname="IPTV Bouquet Maker - E2m3u2bouquet">\n'.format(indent))
f.write('{}<source type="gen_xmltv" nocheck="1" channels="{}">\n'
.format(2 * indent, channels_filename))
f.write('{}<description>{}</description>\n'.format(3 * indent, xml_escape(source_name)))
for source in sources:
f.write('{}<url><![CDATA[{}]]></url>\n'.format(3 * indent, source))
f.write('{}</source>\n'.format(2 * indent))
f.write('{}</sourcecat>\n'.format(indent))
f.write('</sources>\n')
def _get_category_id(self, cat):
"""Generate 32 bit category id to help make service refs unique"""
return hashlib.md5(self.config.name + cat.encode('utf-8')).hexdigest()[:8]
def _has_m3u_file(self):
return self._m3u_file is not None
def _update_status(self, message):
Status.message = '{}: {}'.format(self.config.name, message)
def _process_provider_update(self):
"""Download provider update file from url"""
downloaded = False
updated = False
path = tempfile.gettempdir()
filename = os.path.join(path, 'provider-{}-update.txt'.format(self.config.name))
self._update_status('----Downloading providers update file----')
print('\n{}'.format(Status.message))
print('provider update url = ', self.config.provider_update_url)
try:
context = ssl._create_unverified_context()
urllib.urlretrieve(self.config.provider_update_url, filename, context=context)
downloaded = True
except Exception:
pass # fallback to no ssl context
if not downloaded:
try:
urllib.urlretrieve(self.config.provider_update_url, filename)
except Exception, e:
print('[e2m3u2b] process_provider_update error. Type:', type(e))
print('[e2m3u2b] process_provider_update error: ', e)
if os.path.isfile(filename):
try:
with open(filename, 'r') as f:
line = f.readline().strip()
if line:
provider_tmp = {
'name': line.split(',')[0],
'm3u': line.split(',')[1],
'epg': line.split(',')[2],
}
# check we have name and m3u values
if provider_tmp.get('name') and provider_tmp.get('m3u'):
self.config.name = provider_tmp['name']
self.config.m3u_url = provider_tmp['m3u']
self.config.epg_url = provider_tmp.get('epg', self.config.epg_url)
self.config.last_provider_update = int(time.time())
updated = True
except IndexError, e:
print('[e2m3u2b] _process_provider_update error unable to read providers update file')
if not DEBUG:
os.remove(filename)
return updated
def process_provider(self):
Status.is_running = True
# Set epg to rytec if nothing else provided
if self.config.epg_url is None:
self.config.epg_url = "http://www.vuplus-community.net/rytec/rytecxmltv-UK.gz"
# Set picon path
if self.config.icon_path is None or TESTRUN == 1:
self.config.icon_path = PICONSPATH
if self.config.name is None:
self.config.name = "E2m3u2Bouquet"
# If no username or password supplied extract them from m3u_url
if (self.config.username is None) or (self.config.password is None):
# username, password = e2m3u_setup.extract_user_details_from_url(provider)
self.extract_user_details_from_url()
# Replace USERNAME & PASSWORD placeholders in urls
self.config.m3u_url = self.config.m3u_url.replace('USERNAME', urllib.quote_plus(self.config.username)).replace('PASSWORD', urllib.quote_plus(self.config.password))
self.config.epg_url = self.config.epg_url.replace('USERNAME', urllib.quote_plus(self.config.username)).replace('PASSWORD', urllib.quote_plus(self.config.password))
if self.config.bouquet_download and self.config.bouquet_url:
self.config.bouquet_url = self.config.bouquet_url.replace('USERNAME', urllib.quote_plus(self.config.username)).replace('PASSWORD', urllib.quote_plus(self.config.password))
# get default provider bouquet download url if bouquet download set and no bouquet url given
if self.config.bouquet_download and not self.config.bouquet_url:
# set bouquet_url to default url
pos = self.config.m3u_url.find('get.php')
if pos != -1:
self.config.bouquet_url = self.config.m3u_url[0:pos + 7] + '?username={}&password={}&type=dreambox&output=ts'.format(
urllib.quote_plus(self.config.username), urllib.quote_plus(self.config.password))
# Download panel bouquet
if self.config.bouquet_url:
self.download_panel_bouquet()
# Download m3u
self.download_m3u()
if self._has_m3u_file():
# parse m3u file
self.parse_m3u()
self.parse_map_xmltvsources_xml()
# save xml mapping - should be after m3u parsing
self.save_map_xml()
# Download picons
if self.config.picons:
self.download_picons()
# Create bouquet files
self.create_bouquets()
# Now create custom channels for each bouquet
self._update_status('----Creating EPG-Importer config ----')
print('\n{}'.format(Status.message))
self.create_epgimporter_config()
self._update_status('EPG-Importer config created...')
print(Status.message)
Status.is_running = False
def provider_update(self):
if self.config.provider_update_url and self.config.username and self.config.password:
return self._process_provider_update()
return False
def extract_user_details_from_url(self):
"""Extract username & password from m3u_url """
if self.config.m3u_url:
parsed = urlparse.urlparse(self.config.m3u_url)
username_param = urlparse.parse_qs(parsed.query).get('username')
if username_param:
self.config.username = username_param[0]
password_param = urlparse.parse_qs(parsed.query).get('password')
if password_param:
self.config.password = password_param[0]
def download_m3u(self):
"""Download m3u file from url"""
path = tempfile.gettempdir()
filename = os.path.join(path, 'e2m3u2bouquet.m3u')
self._update_status('----Downloading m3u file----')
print("\n{}".format(Status.message))
if DEBUG:
print("m3uurl = {}".format(self.config.m3u_url))
try:
urllib.urlretrieve(self.config.m3u_url, filename)
except Exception, e:
self._update_status('Unable to download m3u file from url')
print(Status.message)
filename = None
self._m3u_file = filename
def parse_m3u(self):
"""core parsing routine"""
# Extract and generate the following items from the m3u
# group-title
# tvg-name
# tvg-id
# tvg-logo
# stream-name
# stream-url
self._update_status('----Parsing m3u file----')
print('\n{}'.format(Status.message))
try:
if not os.path.getsize(self._m3u_file):
msg = 'M3U file is empty. Check username & password'
print(msg)
if DEBUG:
raise Exception(msg)
except Exception, e:
print(e)
if DEBUG:
raise
service_dict = {}
with open(self._m3u_file, "r") as f:
for line in f:
if 'EXTM3U' in line: # First line we are not interested
continue
elif 'EXTINF:' in line: # Info line - work out group and output the line
service_dict = {'tvg-id': '', 'tvg-name': '', 'tvg-logo': '', 'group-title': '', 'stream-name': '',
'stream-url': '', 'enabled': True, 'nameOverride': '', 'categoryOverride': '',
'serviceRef': '', 'serviceRefOverride': False
}
if line.find('tvg-') == -1:
msg = "No extended playlist info found. Check m3u url should be 'type=m3u_plus'"
print(msg)
if DEBUG:
raise Exception(msg)
channel = line.split('"')
# strip unwanted info at start of line
pos = channel[0].find(' ')
channel[0] = channel[0][pos:]
# loop through params and build dict
for i in xrange(0, len(channel) - 2, 2):
service_dict[channel[i].lower().strip(' =')] = channel[i + 1].decode('utf-8')
# Get the stream name from end of line (after comma)
stream_name_pos = line.rfind(',')
if stream_name_pos != -1:
service_dict['stream-name'] = line[stream_name_pos + 1:].strip().decode('utf-8')
# Set default name for any blank groups
if service_dict['group-title'] == '':
service_dict['group-title'] = u'None'
elif 'http:' in line or 'https:' in line or 'rtmp:' in line:
if 'tvg-id' not in service_dict:
# if this is true the playlist had a http line but not EXTINF
msg = "No extended playlist info found. Check m3u url should be 'type=m3u_plus'"
print(msg)
if DEBUG:
raise Exception(msg)
service_dict['stream-url'] = line.strip()
self._set_streamtypes_vodcats(service_dict)
if service_dict['group-title'] not in self._dictchannels:
self._dictchannels[service_dict['group-title']] = [service_dict]
else:
self._dictchannels[service_dict['group-title']].append(service_dict)
# sort categories by custom order (if exists)
sorted_categories = self._parse_map_bouquet_xml()
self._category_order = self._dictchannels.keys()
sorted_categories.extend(self._category_order)
# remove duplicates, keep order
self._category_order = OrderedDict((x, True) for x in sorted_categories).keys()
# Check for and parse override map
self._parse_map_channels_xml()
# Add Service references
# VOD won't have epg so use same service id for all VOD
vod_service_id = 65535
serviceid_start = 34000
category_offset = 150
catstartnum = serviceid_start
for cat in self._category_order:
num = catstartnum
if cat in self._dictchannels:
if not cat.startswith("VOD"):
if cat in self._category_options:
# check if we have cat idStart from override file
if self._category_options[cat]["idStart"] > 0:
num = self._category_options[cat]["idStart"]
else:
self._category_options[cat]["idStart"] = num
else:
self._category_options[cat] = {"idStart": num}
for x in self._dictchannels[cat]:
cat_id = self._get_category_id(cat)
service_ref = "{:x}:{}:{}:0".format(num, cat_id[:4], cat_id[4:])
if not x['stream-name'].startswith('placeholder_'):
if self._panel_bouquet and not x.get('serviceRefOverride'):
# check if we have the panels custom service ref
pos = x['stream-url'].rfind('/')
if pos != -1 and (pos + 1 != len(x['stream-url'])):
m3u_stream_file = x['stream-url'][pos + 1:]
if m3u_stream_file in self._panel_bouquet:
# have a match use the panels custom service ref
x['serviceRef'] = "{}:{}".format(x['stream-type'], self._panel_bouquet[m3u_stream_file])
continue
if not x.get('serviceRefOverride'):
# if service ref is not overridden in xml update
x['serviceRef'] = "{}:0:1:{}:0:0:0".format(x['stream-type'], service_ref)
num += 1
else:
x['serviceRef'] = PLACEHOLDER_SERVICE
else:
for x in self._dictchannels[cat]:
x['serviceRef'] = "{}:0:1:{:x}:0:0:0:0:0:0".format(x['stream-type'], vod_service_id)
while catstartnum < num:
catstartnum += category_offset
vod_index = None
if "VOD" in self._category_order:
# if we have the vod category placeholder from the override use it otherwise
# use the first found vod category position
vod_index = self._category_order.index("VOD")
else:
for key in self._category_order:
if key.startswith("VOD"):
vod_index = self._category_order.index(key)
break
if vod_index is not None:
# move all VOD categories to VOD placeholder position or group after first vod position
vodcategories = list((cat for cat in self._category_order if cat.startswith('VOD -')))
if len(vodcategories):
# remove the vod category(s) from current position
self._category_order = [x for x in self._category_order if x not in vodcategories]
# insert the vod category(s) at the placeholder / first pos
self._category_order[vod_index:vod_index] = vodcategories
try:
self._category_order.remove("VOD")
except ValueError:
pass # ignore exception