forked from grudolf/m3u2hts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
m3u2hts.py
278 lines (250 loc) · 9.06 KB
/
m3u2hts.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# m3u2hts.py - Generate TVHeadend 3.x channel/tag configuration files from
# IPTV M3U playlist
#
# (c) 2012 Gregor Rudolf
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
#===============================================================================
from optparse import OptionParser
import codecs
import re
import os
try:
import json
except ImportError:
# old python? easy_install simplejson
import simplejson as json
PROGNUM = re.compile(r"(\d+) - (.*)") # #EXTINF:0,1 - SLO 1 -> #1 - num, 2 - ime
CHAN_NUMBERING_GENERATE = 0
CHAN_NUMBERING_DURATION = 1
CHAN_NUMBERING_NAMES = 2
channels = dict()
tags = dict()
def readm3u(infile, removenum, channumbering, inputcodec):
"""
Read IPTV channels from .M3U file
@param infile: input file
@param removenum: try to remove channel numbers from names
@param channumbering: how to get channel number
@param inputcodec: encoding of input file
"""
instream = codecs.open(infile, "Ur", encoding=inputcodec)
chancnt = 0
tagcnt = 0
chname = ''
chtags = None
chlanguage = None
chnumber = None
chxmltv = None
chicon = None
for line in instream.readlines():
line = line.strip()
if line.startswith("#EXTINF:"):
#EXTINF:duration,channel number - channel name
buff = line[8:].split(',')
m = PROGNUM.search(buff[1])
if removenum and m:
chname = m.group(2)
else:
chname = buff[1]
if m and channumbering == CHAN_NUMBERING_NAMES:
chnumber = m.group(1)
elif channumbering == CHAN_NUMBERING_DURATION:
chnumber = buff[0]
elif line.startswith('#EXTTV:'):
#EXTTV:tag[,tag,tag...];language;XMLTV id[;icon URL]
buff = line[7:].split(';')
chtags = buff[0].split(',')
for t in chtags:
if not t in tags:
tagcnt += 1
tags[t] = {'num': tagcnt, 'name': t}
chlanguage = buff[1]
if chlanguage:
if not chlanguage in tags:
tagcnt += 1
tags[chlanguage] = {'num': tagcnt, 'name': chlanguage}
chtags.append(chlanguage)
chxmltv = buff[2]
chicon = buff[3] if len(buff) > 3 else None
elif line.startswith('udp://@'):
chancnt += 1
if channumbering == CHAN_NUMBERING_GENERATE: chnumber = chancnt
chip, chport = line[7:].rsplit(':', 1)
if chname in channels:
print "%s already exists" % chname
chname = chname + '.'
channels[chname] = {'num': chancnt, 'number': chnumber, 'name': chname, 'tags': chtags, 'lang': chlanguage,
'ip': chip, 'port': chport, 'xmltv': chxmltv, 'icon': chicon}
chname = ''
chtags = None
chlanguage = None
chnumber = None
chxmltv = None
chicon = None
else:
continue
def writechannels():
svcpath = 'iptvservices'
chnpath = 'channels'
if not os.path.exists(svcpath):
os.mkdir(svcpath)
if not os.path.exists(chnpath):
os.mkdir(chnpath)
for channel in channels.values():
#iptvservices/iptv_?
jssvc = {'pmt': 0,
'channelname': channel['name'],
'port': channel['port'],
'interface': 'eth1',
'group': channel['ip'],
'mapped': 1,
'pcr': 0,
'disabled': 0}
writejson(os.path.join(svcpath, "iptv_" + str(channel['num'])), jssvc)
#channels/?
jschan = {'name': channel['name'],
'dvr_extra_time_pre': 0,
'dvr_extra_time_post': 0}
if channel['number'] is not None:
jschan['channel_number'] = channel['number']
if channel['xmltv'] is not None:
jschan['xmltv-channel'] = channel['xmltv']
if channel['tags'] is not None:
jschan['tags'] = list(tags[x]['num'] for x in channel['tags'])
if channel['icon'] is not None:
jschan['icon'] = channel['icon']
writejson(os.path.join(chnpath, str(channel['num'])), jschan)
def uuid():
import uuid
return uuid.uuid4().hex
def writechannels39():
xmltvpath = "epggrab/xmltv/channels"
if not os.path.exists(xmltvpath):
os.makedirs(xmltvpath)
chnpath = 'channel'
if not os.path.exists(chnpath):
os.makedirs(chnpath)
#input/iptv
path = os.path.join('input', 'iptv')
if not os.path.exists(path):
os.makedirs(path)
#input/iptv/config
writejson(os.path.join(path, 'config'), {
'uuid': uuid(),
'skipinitscan': 1,
'autodiscovery': 0
})
#input/iptv/networks/uuid()
path = os.path.join(path, 'networks', uuid())
if not os.path.exists(path):
os.makedirs(path)
writejson(os.path.join(path, 'config'), {
'networkname': 'IPTV network',
'skipinitscan': 1,
'autodiscovery': 0
})
#input/iptv/networks/uuid()/muxes
path = os.path.join(path, 'muxes')
if not os.path.exists(path):
os.mkdir(path)
#one mux and service for each channel
for channel in channels.values():
muxid = uuid()
muxpath = os.path.join(path, muxid)
if not os.path.exists(muxpath):
os.mkdir(muxpath)
jsmux = {
'iptv_url': "udp://@%s:%s" % (channel['ip'], channel['port']),
'iptv_interface': 'eth1',
'iptv_atsc': 0,
'iptv_svcname': channel['name'],
'enabled': 1,
'initscan': 1 # mark mux as scanned
}
#input/iptv/networks/uuid()/muxes/uuid()/config file
writejson(os.path.join(muxpath, 'config'), jsmux)
#input/iptv/networks/uuid()/muxes/uuid()/services/uuid()
svcpath = os.path.join(muxpath, 'services')
if not os.path.exists(svcpath):
os.mkdir(svcpath)
svcid = uuid()
jssvc = {
'sid': 1, # guess service id
'svcname': channel['name'],
'name': channel['name'],
'dvb_servicetype': 1,
'enabled': 1
}
writejson(os.path.join(svcpath, svcid), jssvc)
#channel
chanid = uuid()
jschan = {
'name': channel['name'],
'dvr_pre_time': 0,
'dvr_pst_time': 0,
'services': [svcid]
}
if channel['number'] is not None:
jschan['number'] = int(channel['number'])
if channel['tags'] is not None:
jschan['tags'] = list(tags[x]['num'] for x in channel['tags'])
if channel['icon'] is not None:
jschan['icon'] = channel['icon']
writejson(os.path.join(chnpath, chanid), jschan)
#epg
#epggrab/xmltv/channels/#
if channel['xmltv'] is not None:
xmlid = channel['xmltv']
else:
xmlid = channel['name']
jsepg = {
'name': xmlid,
'channels': [chanid]
}
writejson(os.path.join(xmltvpath, chanid), jsepg)
def writetags():
path = 'channeltags'
if not os.path.exists(path):
os.mkdir(path)
for tag in tags.values():
#channeltags/?
jstag = {'enabled': 1,
'internal': 0,
'titledIcon': 0,
'name': tag['name'],
'comment': '', 'icon': '',
'id': tag['num']}
writejson(os.path.join(path, str(tag['num'])), jstag)
def writejson(filename, obj):
"""
Export obj to filename in JSON format
@param filename: output file
@param obj: object to export
"""
outstream = codecs.open(filename, "w", encoding='utf-8')
json.dump(obj, outstream, indent=4, ensure_ascii=False)
outstream.close()
def main():
par = OptionParser(usage="%prog [options] inputfile",
description="Generate TVHeadend 3.x channel/tag configuration files from IPTV M3U playlist")
par.add_option('-r', '--removenum', action='store_true', help=u'remove program numbers from names')
par.add_option('-n', '--numbering', type='int', default=0,
help=u'program numbers are generated(0), determined from duration(1) or extracted from program names(2)')
par.add_option('-c', '--codec', action='store', dest='codec', default='cp1250',
help=u'input file encoding [default: %default]')
par.add_option('--newformat', action='store_true',
help=u'generate TVHeadend 3.9+ compatible configuration files (experimental)')
opt, args = par.parse_args()
if len(args) == 1:
readm3u(args[0], opt.removenum, opt.numbering, opt.codec)
writechannels39() if opt.newformat else writechannels()
writetags()
print("OK")
else:
par.print_help()
if __name__ == '__main__':
main()