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 | #
# As fallback there is a regex which just looks for URLs in the
# given resource (works for m3u/pls/xspf/asx/...).
import re
import os
from ahttp import fix_url as http_fix_url, get as http_get
from config import conf, __print__ as debug, dbg
import platform
# Coupling to main window
#
main = None
# Streamlink/listformat mapping
#
lt = dict(
pls = "audio/x-scpls",
m3u = "audio/x-mpegurl",
asx = "video/x-ms-asf",
xspf = "application/xspf+xml",
href = "url/http",
srv = "url/direct",
ram = "audio/x-pn-realaudio",
smil = "application/smil",
script = "text/x-urn-streamtuner2-script", # unused
)
# Audio type MIME map
#
mf = dict(
mp3 = "audio/mpeg",
ogg = "audio/ogg",
aac = "audio/aac",
midi = "audio/midi",
mod = "audio/mod",
)
# Player command placeholders for playlist formats
placeholder_map = dict(
pls = "%url | %pls | %u | %l | %r",
m3u = "%m3u | %f | %g | %m",
pls = "%srv | %d | %s",
)
# Exec wrapper
#
def run(cmd):
if cmd: debug(dbg.PROC, "Exec:", cmd) |
|
<
|
|
|
|
|
|
|
>
>
|
|
>
|
<
|
<
|
|
|
|
>
|
|
<
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
| 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 | #
# As fallback there is a regex which just looks for URLs in the
# given resource (works for m3u/pls/xspf/asx/...).
import re
import os
from ahttp import fix_url as http_fix_url, session
from config import conf, __print__ as debug, dbg
import platform
# Coupling to main window
#
main = None
# Streamlink/listformat mapping
listfmt_t = {
"audio/x-scpls": "pls",
"audio/x-mpegurl": "m3u",
"video/x-ms-asf": "asx",
"application/xspf+xml": "xspf",
"*/*": "href",
"url/direct": "srv",
"url/youtube": "href",
"url/http": "href",
"audio/x-pn-realaudio": "ram",
"application/smil": "smil",
"application/vnd.ms-wpl":"smil",
"x-urn/st2-script": "script", # unused
}
# Audio type MIME map
mediafmt_t = {
"audio/mpeg": "mp3",
"audio/ogg": "ogg",
"audio/aac" : "aac",
"audio/aacp" : "aac",
"audio/midi": "midi",
"audio/mod": "mod",
"audio/it+zip": "mod",
"audio/s3+zip": "mod",
"audio/xm+zip": "mod",
}
# Player command placeholders for playlist formats
placeholder_map = dict(
pls = "%url | %pls | %u | %l | %r",
m3u = "%m3u | %f | %g | %m",
srv = "%srv | %d | %s",
)
# Playlist format content probing (assert type)
playlist_content_map = {
"pls": r""" (?i)\[playlist\].*numberofentries""",
"xspf": r""" <\?xml .* <playlist .* http://xspf\.org/ns/0/""",
"m3u": r""" #M3U""",
"asx" : r""" <ASX\b""",
"smil": r""" <smil[^>]*> .* <seq>""",
"wpl": r""" <\?wpl \s+ version="1\.0" \s* \?>""",
"jspf": r""" \{ \s* "playlist": \s* \{ """,
"json": r""" "url": \s* "\w+:// """,
"href": r""" .* """,
}
# Exec wrapper
#
def run(cmd):
if cmd: debug(dbg.PROC, "Exec:", cmd) |
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 | cmd = mime_app(audioformat, conf.record)
cmd = interpol(cmd, url, listformat, row)
run(cmd)
# OS shell command escaping
#
def quote(s):
return "%r" % str(s)
# Convert e.g. "text/x-scpls" MIME types to just "pls" monikers
#
def listfmt(t = "pls"):
if t in lf.values():
for short,mime in lf.items():
if mime == t:
return short
return t # "pls"
# Convert MIME type into list of ["audio/xyz", "audio/*", "*/*"]
# for comparison against configured record/play association.
def mime_app(fmt, cmd_list):
for match in [ fmt, fmt[:fmt.find("/")] + "/*", "*/*" ]:
if cmd_list.get(match):
return cmd_list[match]
# Replaces instances of %m3u, %pls, %srv in a command string.
# · Also understands short aliases %l, %f, %d. |
|
>
|
>
>
|
|
|
>
| 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 | cmd = mime_app(audioformat, conf.record)
cmd = interpol(cmd, url, listformat, row)
run(cmd)
# OS shell command escaping
#
def quote(ins):
if type(ins) is str:
return "%r" % str(ins)
else:
return " ".join(["%r" % str(s) for s in ins])
# Convert e.g. "text/x-scpls" MIME types to just "pls" monikers
#
def listfmt(t = "pls"):
if t in listfmt_t.values():
for short,mime in listfmt_t.items():
if mime == t:
return short
return t # "pls"
# Convert MIME type into list of ["audio/xyz", "audio/*", "*/*"]
# for comparison against configured record/play association.
def mime_app(fmt, cmd_list):
major = fmt[:fmt.find("/")]
for match in [ fmt, major + "/*", "*/*" ]:
if cmd_list.get(match):
return cmd_list[match]
# Replaces instances of %m3u, %pls, %srv in a command string.
# · Also understands short aliases %l, %f, %d. |
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 | if cmd.find("%") < 0:
cmd = cmd + " %m3u"
# standard placeholders
for dest, rx in placeholder_map.items():
if re.search(rx, cmd, re.X):
# from .pls to .m3u
url = convert_playlist(url, listfmt(source), listfmt(dest))
# insert quoted URL/filepath
return re.sub(rx, cmd, quote(url), 2, re.X)
return "false"
# Substitute .pls URL with local .m3u,
# or direct srv address, or leave as-is.
#
def convert_playlist(url, source, dest):
# Leave alone
if source == dest or source in ("srv", "href"):
return url
# Else
return url
# Save row(s) in one of the export formats,
# depending on file extension:
#
# · m3u
# · pls |
|
|
>
|
>
>
>
|
|
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
| 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 | if cmd.find("%") < 0:
cmd = cmd + " %m3u"
# standard placeholders
for dest, rx in placeholder_map.items():
if re.search(rx, cmd, re.X):
# from .pls to .m3u
urls = convert_playlist(url, listfmt(source), listfmt(dest))
# insert quoted URL/filepath
return re.sub(rx, cmd, quote(urls), 2, re.X)
return "false"
# Substitute .pls URL with local .m3u,
# or direct srv address, or leave as-is.
#
def convert_playlist(url, source, dest):
urls = []
print(dbg.PROC, "convert_playlist(", url, source, dest, ")")
# Leave alone
is_url = re.search("\w+://", url)
if source == dest or source in ("srv", "href") or not is_url:
return [url]
# Retrieve from URL
(mime, cnt) = http_probe_get(url)
# Leave streaming server as is
if mime == "srv":
cnt = ""
return [url]
# Test URL path "extension" for ".pls" / ".m3u" etc.
ext = re.findall("\.(\w)$|($)", url)[0]
# Probe MIME type and content per regex
probe = None
for probe,rx in playlist_content_map.items():
if re.search(rx, cnt, re.X|re.S):
break # with `probe` set
# Check ambiguity (except pseudo extension)
if len(set([source, mime, probe])) > 1:
print(dbg.ERR, "Possible playlist format mismatch:", (source, mime, probe, ext))
# Extract URLs from content
for fmt,extractor in [ ("pls",extract_playlist.pls), ("asx",extract_playlist.asx), ("raw",extract_playlist.raw) ]:
if not urls and fmt in (source, mime, probe, ext):
urls = extractor(cnt)
# Return asis for srv targets
if dest in ("srv", "href", "any"):
return urls
print urls
# Otherwise convert to local file
fn = tmp_fn(cnt)
save(urls[0], fn, dest)
return [fn]
# Tries to fetch a resource, aborts on ICY responses.
#
def http_probe_get(url):
# possible streaming request
r = session.get(url, stream=True)
if not len(r.headers):
return ("srv", r)
# extract payload
mime = r.headers.get("content-type", "any")
if mediafmt_t.get(mime):
mime = mediafmt_t.get(mime)
content = "".join(r.iter_lines())
return (mime, content)
# Extract URLs from playlist formats:
#
class extract_playlist(object):
@staticmethod
def pls(text):
return re.findall("\s*File\d*\s*=\s*(\w+://[^\s]+)", text, re.I)
@staticmethod
def asx(text):
return re.findall("<Ref\s+href=\"(http://.+?)\"", text)
@staticmethod
def raw(text):
print(dbg.WARN, "Raw playlist extraction")
return re.findall("(https?://[^\s]+)", content, re.I)
# Save row(s) in one of the export formats,
# depending on file extension:
#
# · m3u
# · pls |
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 |
# unknown
else:
return
# write
if txt:
f = open(fn, "wb")
f.write(txt)
f.close()
pass
# retrieve real stream urls from .pls or .m3u links
def extract_urls(pls, listformat="__not_used_yet__"):
# extract stream address from .pls URL
if (re.search("\.pls", pls)): #audio/x-scpls
return pls(pls)
elif (re.search("\.asx", pls)): #video/x-ms-asf
return re.findall("<Ref\s+href=\"(http://.+?)\"", http_get(pls))
elif (re.search("\.m3u|\.ram|\.smil", pls)): #audio/x-mpegurl
return re.findall("(http://[^\s]+)", http_get(pls), re.I)
else: # just assume it was a direct mpeg/ogg streamserver link
return [ (pls if pls.startswith("/") else http_fix_url(pls)) ]
pass
# generate filename for temporary .m3u, if possible with unique id
def tmp_fn(pls):
# use shoutcast unique stream id if available
stream_id = re.search("http://.+?/.*?(\d+)", pls, re.M)
stream_id = stream_id and stream_id.group(1) or "XXXXXX"
try:
channelname = main.current_channel
except:
channelname = "unknown"
return (str(conf.tmp) + os.sep + "streamtuner2."+channelname+"."+stream_id+".m3u", len(stream_id) > 3 and stream_id != "XXXXXX")
# check if there are any urls in a given file
def has_urls(tmp_fn):
if os.path.exists(tmp_fn):
return open(tmp_fn, "r").read().find("http://") > 0
# create a local .m3u file from it
def m3u(pls):
# temp filename
(tmp_fn, unique) = tmp_fn(pls)
# does it already exist?
if tmp_fn and unique and conf.reuse_m3u and has_urls(tmp_fn):
return tmp_fn
# download PLS
debug( dbg.DATA, "pls=",pls )
url_list = extract_urls(pls)
debug( dbg.DATA, "urls=", url_list )
# output URL list to temporary .m3u file
if (len(url_list)):
#tmp_fn =
f = open(tmp_fn, "w")
f.write("#M3U\n")
f.write("\n".join(url_list) + "\n")
f.close()
# return path/name of temporary file
return tmp_fn
else:
debug( dbg.ERR, "error, there were no URLs in ", pls )
raise "Empty PLS"
# Download a .pls resource and extract urls
def extract_from_pls(url):
text = http_get(url)
debug(dbg.DATA, "pls_text=", text)
return re.findall("\s*File\d*\s*=\s*(\w+://[^\s]+)", text, re.I)
# currently misses out on the titles
# get a single direct ICY stream url (extract either from PLS or M3U)
def srv(url):
return extract_urls(url)[0]
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
< | 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
|
# unknown
else:
return
# write
if txt:
with open(fn, "wb") as f:
f.write(txt)
pass
# generate filename for temporary .m3u, if possible with unique id
def tmp_fn(pls):
# use shoutcast unique stream id if available
stream_id = re.search("http://.+?/.*?(\d+)", pls, re.M)
stream_id = stream_id and stream_id.group(1) or "XXXXXX"
try:
channelname = main.current_channel
except:
channelname = "unknown"
return (str(conf.tmp) + os.sep + "streamtuner2."+channelname+"."+stream_id+".m3u", len(stream_id) > 3 and stream_id != "XXXXXX")
# check if there are any urls in a given file
def has_urls(tmp_fn):
if os.path.exists(tmp_fn):
return open(tmp_fn, "r").read().find("http://") > 0
|