iptv/app/m3u.py
2025-07-16 15:07:06 +08:00

88 lines
1.4 KiB
Python

import codecs
def tvgParser(txt):
d = {}
buf = ''
k = ''
inbrace = False
for c in txt:
if c == '"':
if inbrace:
inbrace = False
d[k] = buf
buf = ''
k = ''
else:
inbrace = True
continue
if c == '=':
k = buf
buf = ''
continue
if c == ' ':
if inbrace:
buf = '%s%s' % (buf,c)
continue
buf = '%s%s' % (buf,c)
if k != '':
v = buf
d[k] = v
return d
def channelInfo(l):
g = {}
e = l.split(',')
info = e[-2]
fo=info.split(' ',1)
if len(fo) == 2:
_,tvginfo=info.split(' ',1)
g = tvgParser(tvginfo)
g['name'] = e[-1]
return g
def name_url_m3u(text):
ret = []
for i, line in enumerate(text.split('\n')):
llist = line.split(',')
if len(llist) != 2:
return ret
ret.append({'url':llist[1], 'name':llist[0]})
return ret
def m3uParser(text):
text = ''.join(text.split('\r'))
newchannel = False
channels = []
for i,line in enumerate(text.split('\n')):
if i==0 and not line.startswith('#EXTM3U'):
return name_url_m3u(text)
if i == 0:
continue
if line == '':
continue
if line.startswith('#EXTINF'):
channel = channelInfo(line)
status = 'url'
continue
if line.startswith('http://') or line.startswith('https://'):
channel['url'] = line
channels.append(channel)
continue
return channels
def testfile(filename):
with codecs.open(filename,'r','utf-8') as f:
text = f.read()
m3uParser(text)
if __name__ == '__main__':
import sys
testfile(sys.argv[1])