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
|
# encoding: UTF-8
# api: streamtuner2
# type: functions
# title: play/record actions
# description: Starts audio applications, guesses MIME types for URLs
# version: 0.9
#
# Multimedia interface for starting audio players, recording app,
# or web browser (listed as "url/http" association in players).
#
# Each channel plugin has a .listtype which describes the linked
# audio playlist format. It's audio/x-scpls mostly, seldomly m3u,
# but sometimes url/direct if the entry[url] directly leads to the
# streaming server.
#
# 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
| <
>
>
>
>
|
|
>
|
<
|
<
>
>
>
>
>
>
>
>
|
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 |
# encoding: UTF-8
# api: streamtuner2
# type: functions
# cagtegory: io
# title: play/record actions
# description: Starts audio applications, guesses MIME types for URLs
# version: 0.9
# priority: core
#
# Multimedia interface for starting audio players, recording app,
# or web browser (listed as "url/http" association in players).
# It maps audio MIME types, and extracts/converts playlist types
# (PLS, M3U, XSPF, SMIL, JSPF, ASX, raw urls).
#
# Each channel plugin has a .listtype which defines the linked
# audio playlist format. It's "pls", seldomly "m3u", or "xspf".
# Some channels list raw "srv" addresses, while Youtube "href"
# entries to Flash videos.
#
# As fallback the playlist URL is retrieved and its MIME type
# checked, and its content regexped to guess the link format.
# Lastly a playlist type suitable for audio players recreated.
# Which is somewhat of a security feature, playlists get cleaned
# up this way. The conversion is not strictly necessary for all
# players, as basic PLS is supported by most.
#
# And finally this module is also used by exporting and (perhaps
# in the future) playlist importing features.
import re
import os
from ahttp import fix_url as http_fix_url, session
from config import conf, __print__ as debug, dbg
import platform |
|
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 |
# Streamlink/listformat mapping
listfmt_t = {
"audio/x-scpls": "pls",
"audio/x-mpegurl": "m3u",
"video/x-ms-asf": "asx",
"application/xspf+xml": "xspf",
"*/*": "href", # "href" for unknown responses
"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
"application/x-shockwave-flash": "href", # fallback
}
# Audio type MIME map
mediafmt_t = {
"audio/mpeg": "mp3", |
>
>
>
| 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 |
# Streamlink/listformat mapping
listfmt_t = {
"audio/x-scpls": "pls",
"audio/x-mpegurl": "m3u",
"audio/mpegurl": "m3u",
"video/x-ms-asf": "asx",
"application/xspf+xml": "xspf",
"*/*": "href", # "href" for unknown responses
"url/direct": "srv",
"url/youtube": "href",
"url/http": "href",
"audio/x-pn-realaudio": "ram",
"application/smil": "smil",
"application/vnd.ms-wpl":"smil",
"audio/x-ms-wax": "asx",
"video/x-ms-asf": "asx",
"x-urn/st2-script": "script", # unused
"application/x-shockwave-flash": "href", # fallback
}
# Audio type MIME map
mediafmt_t = {
"audio/mpeg": "mp3", |
|
81
82
83
84
85
86
87
88
89
90
91
92
93
94 | ("m3u", r""" ^ \s* #(EXT)?M3U """),
("asx" , r""" <asx\b """),
("smil", r""" <smil[^>]*> .* <seq> """),
("html", r""" <(audio|video)\b[^>]+\bsrc\s*=\s*["']?https?:// """),
("wpl", r""" <\?wpl \s+ version="1\.0" \s* \?> """),
("b4s", r""" <WinampXML> """), # http://gonze.com/playlists/playlist-format-survey.html
("jspf", r""" ^ \s* \{ \s* "playlist": \s* \{ """),
("json", r""" "url": \s* "\w+:// """),
("href", r""" .* """),
]
# Exec wrapper |
>
| 94
95
96
97
98
99
100
101
102
103
104
105
106
107
108 | ("m3u", r""" ^ \s* #(EXT)?M3U """),
("asx" , r""" <asx\b """),
("smil", r""" <smil[^>]*> .* <seq> """),
("html", r""" <(audio|video)\b[^>]+\bsrc\s*=\s*["']?https?:// """),
("wpl", r""" <\?wpl \s+ version="1\.0" \s* \?> """),
("b4s", r""" <WinampXML> """), # http://gonze.com/playlists/playlist-format-survey.html
("jspf", r""" ^ \s* \{ \s* "playlist": \s* \{ """),
("asf", r""" ^ \[Reference\] .*? ^Ref\d+= """),
("json", r""" "url": \s* "\w+:// """),
("href", r""" .* """),
]
# Exec wrapper |
|
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 | run("yelp /usr/share/doc/streamtuner2/help/")
# Calls player for stream url and format
#
def play(url, audioformat="audio/mpeg", source="pls", row={}):
cmd = mime_app(audioformat, conf.play)
cmd = interpol(cmd, url, listformat, row)
run(cmd)
# Call streamripper
#
def record(url, audioformat="audio/mpeg", source="href", row={}):
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: |
|
|
| 126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 | run("yelp /usr/share/doc/streamtuner2/help/")
# Calls player for stream url and format
#
def play(url, audioformat="audio/mpeg", source="pls", row={}):
cmd = mime_app(audioformat, conf.play)
cmd = interpol(cmd, url, source, row)
run(cmd)
# Call streamripper
#
def record(url, audioformat="audio/mpeg", source="href", row={}):
cmd = mime_app(audioformat, conf.record)
cmd = interpol(cmd, url, source, row)
run(cmd)
# OS shell command escaping
#
def quote(ins):
if type(ins) is str: |
|
181
182
183
184
185
186
187
188
189
190
191
192
193
194 | return "false"
# Substitute .pls URL with local .m3u, or direct srv addresses, or leaves URL asis.
# · Takes a single input `url`.
# · But returns a list of [urls] after playlist extraction.
# · If repackaging as .m3u/.pls/.xspf, returns the local [fn].
#
def convert_playlist(url, source, dest, local_file=True, title=""):
urls = []
debug(dbg.PROC, "convert_playlist(", url, source, dest, ")")
# Leave alone if format matches, or if "srv" URL class, or if not http (local path, mms:/rtsp:)
if source == dest or source in ("srv", "href") or not re.match("(https?|spdy)://", url): |
>
>
>
| 195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 | return "false"
# Substitute .pls URL with local .m3u, or direct srv addresses, or leaves URL asis.
# · Takes a single input `url`.
# · But returns a list of [urls] after playlist extraction.
# · If repackaging as .m3u/.pls/.xspf, returns the local [fn].
#
# TODO: This still needs some rewrite to reuse the incoming row={},
# and keep station titles for converted playlists.
#
def convert_playlist(url, source, dest, local_file=True, title=""):
urls = []
debug(dbg.PROC, "convert_playlist(", url, source, dest, ")")
# Leave alone if format matches, or if "srv" URL class, or if not http (local path, mms:/rtsp:)
if source == dest or source in ("srv", "href") or not re.match("(https?|spdy)://", url): |
|
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 | break # with `probe` set
# Check ambiguity (except pseudo extension)
if len(set([source, mime, probe])) > 1:
debug(dbg.ERR, "Possible playlist format mismatch:", (source, mime, probe, ext))
# Extract URLs from content
for fmt in [ "pls", "xspf", "asx", "smil", "jspf", "m3u", "json", "raw" ]:
if not urls and fmt in (source, mime, probe, ext, "raw"):
urls = extract_playlist(source).format(fmt)
debug(dbg.DATA, "conversion from:", source, " to dest:", fmt, "got URLs=", urls)
# Return original, or asis for srv targets
if not urls:
return [url]
elif dest in ("srv", "href"):
return urls
debug( urls )
# Otherwise convert to local file
if local_file:
fn = tmp_fn(cnt)
save_playlist(source="srv", multiply=True).export(urls=urls, fn=fn, dest=dest, title=title)
return [fn]
else:
return urls
# Tries to fetch a resource, aborts on ICY responses. |
|
|
|
|
>
>
|
| 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 | break # with `probe` set
# Check ambiguity (except pseudo extension)
if len(set([source, mime, probe])) > 1:
debug(dbg.ERR, "Possible playlist format mismatch:", (source, mime, probe, ext))
# Extract URLs from content
for fmt in ["pls", "xspf", "asx", "smil", "jspf", "m3u", "json", "asf", "raw"]:
if not urls and fmt in (source, mime, probe, ext, "raw"):
urls = extract_playlist(cnt).format(fmt)
debug(dbg.DATA, "conversion from:", source, " with extractor:", fmt, "got URLs=", urls)
# Return original, or asis for srv targets
if not urls:
return [url]
elif dest in ("srv", "href"):
return urls
debug( urls )
# Otherwise convert to local file
if local_file:
fn, is_unique = tmp_fn(cnt)
with open(fn, "wb") as f:
debug(dbg.DATA, "exporting with format:", dest, " into filename:", fn)
f.write( save_playlist(source="srv", multiply=True).export(urls=urls, dest=dest, title=title) )
return [fn]
else:
return urls
# Tries to fetch a resource, aborts on ICY responses. |
|
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 |
# Extract payload
mime = r.headers.get("content-type", "href")
# Map MIME to abbr type (pls, m3u, xspf)
if listfmt_t.get(mime):
mime = listfmt_t.get(mime)
# Raw content (mp3, flv)
elif mimefmt_t.get(mime):
mime = mimefmt_t.get(mime)
return (mime, url)
# Rejoin body
content = "\n".join(r.iter_lines())
return (mime, content)
# Extract URLs from playlist formats:
#
class extract_playlist(object):
# Content of playlist file
src = ""
def __init__(self, text):
self.src = text
# Extract only URLs from given source type
def format(self, fmt):
debug(dbg.DATA, fmt)
return re.findall(self.extr_urls[fmt], self.src, re.X);
# Only look out for URLs, not local file paths
extr_urls = {
"pls": r" (?i) ^ \s*File\d* \s*=\s* (\w+://[^\s]+) ",
"m3u": r" (?m) ^( \w+:// [^#\n]+ )",
"xspf": r" (?x) <location> (\w+://[^<>\s]+) </location> ",
"asx": r" (?x) <ref \b[^>]+\b href \s*=\s* [\'\"] (\w+://[^\s\"\']+) [\'\"] ",
"smil": r" (?x) <(?:audio|video)\b [^>]+ \b src \s*=\s* [^\"\']? \s* (\w+://[^\"\'\s]+) ",
"jspf": r" (?x) \"location\" \s*:\s* \"(\w+://[^\"\s]+)\" ",
"json": r" (?x) \"url\" \s*:\s* \"(\w+://[^\"\s]+)\" ",
"raw": r" (?i) ( [\w+]+:// [^\s\"\'\>\#]+ ) ",
}
# Save rows in one of the export formats.
# Takes a few combinations of parameters (either rows[], or urls[]+title),
# because it's used by playlist_convert() as well as the station saving.
#
class save_playlist(object):
# if converting
source = "pls"
# expand multiple server URLs into duplicate entries in target playlist
multiply = True
# constructor
def __init__(self, source, multiply):
self.source = source
self.multiply = multiply
# Used by playlist_convert(), to transform a list of extracted URLs
# into a local .pls/.m3u collection again. Therefore injects the
# `title` back into each of the URL rows.
def export(self, urls=None, title=None, dest="pls"):
rows = [ { "url": url, "title": title } for url in urls ]
return self.store(rows, None, dest)
# Export a playlist
def store(self, rows=None, fn=None, dest="pls"):
# can be just a single entry
rows = copy.deepcopy(rows)
if type(rows) is dict:
rows = [row]
# Expand contained stream urls |
|
>
|
|
|
|
>
>
|
>
>
>
|
|
<
|
|
| 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 |
# Extract payload
mime = r.headers.get("content-type", "href")
# Map MIME to abbr type (pls, m3u, xspf)
if listfmt_t.get(mime):
mime = listfmt_t.get(mime)
# Raw content (mp3, flv)
elif mediafmt_t.get(mime):
debug(dbg.ERR, "Got media MIME type for expected playlist", mime, " on url=", url)
mime = mediafmt_t.get(mime)
return (mime, url)
# Rejoin body
content = "\n".join(r.iter_lines())
return (mime, content)
# Extract URLs from playlist formats:
#
class extract_playlist(object):
# Content of playlist file
src = ""
def __init__(self, text):
self.src = text
# Extract only URLs from given source type
def format(self, fmt):
debug(dbg.DATA, "input regex:", fmt, len(self.src))
return re.findall(self.extr_urls[fmt], self.src, re.X);
# Only look out for URLs, not local file paths
extr_urls = {
"pls": r"(?im) ^ \s*File\d* \s*=\s* (\w+://[^\s]+) ",
"m3u": r" (?m) ^( \w+:// [^#\n]+ )",
"xspf": r" (?x) <location> (\w+://[^<>\s]+) </location> ",
"asx": r" (?x) <ref \b[^>]+\b href \s*=\s* [\'\"] (\w+://[^\s\"\']+) [\'\"] ",
"smil": r" (?x) <(?:audio|video|media)\b [^>]+ \b src \s*=\s* [^\"\']? \s* (\w+://[^\"\'\s]+) ",
"jspf": r" (?x) \"location\" \s*:\s* \"(\w+://[^\"\s]+)\" ",
"json": r" (?x) \"url\" \s*:\s* \"(\w+://[^\"\s]+)\" ",
"asf": r" (?m) ^ \s*Ref\d+ = (\w+://[^\s]+) ",
"raw": r" (?i) ( [\w+]+:// [^\s\"\'\>\#]+ ) ",
}
# Save rows in one of the export formats.
#
# The export() version uses urls[]+title= as input, converts it into a
# list of rows{} beforehand.
#
# While store() requires rows{} to begin with, to perform a full
# conversion. Can save directly to a file name.
#
class save_playlist(object):
# if converting
source = "pls"
# expand multiple server URLs into duplicate entries in target playlist
multiply = True
# constructor
def __init__(self, source, multiply):
self.source = source
self.multiply = multiply
# Used by playlist_convert(), to transform a list of extracted URLs
# into a local .pls/.m3u collection again. Therefore injects the
# `title` back into each of the URL rows.
def export(self, urls=None, title=None, dest="pls"):
rows = [ { "url": url, "title": title } for url in urls ]
return self.store(rows, dest)
# Export a playlist from rows{}
def store(self, rows=None, dest="pls"):
# can be just a single entry
rows = copy.deepcopy(rows)
if type(rows) is dict:
rows = [row]
# Expand contained stream urls |
|
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361 | break
rows = new_rows
debug(dbg.DATA, "conversion to:", dest, " from:", self.source, "with rows=", rows)
# call conversion schemes
converter = getattr(self, dest) or self.pls
txt = converter(rows)
# save directly?
if fn:
with open(fn, "wb") as f:
f.write(txt)
else:
return txt
# M3U
def m3u(self, rows):
txt = "#EXTM3U\n"
for r in rows:
txt += "#EXTINF:-1,%s\n" % r["title"]
txt += "%s\n" % http_fix_url(r["url"]) |
|
|
|
|
|
|
|
<
|
| 363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384 | break
rows = new_rows
debug(dbg.DATA, "conversion to:", dest, " from:", self.source, "with rows=", rows)
# call conversion schemes
converter = getattr(self, dest) or self.pls
return converter(rows)
# save directly
def file(self, rows, dest, fn):
with open(fn, "wb") as f:
f.write(self.store(rows, dest))
# M3U
def m3u(self, rows):
txt = "#EXTM3U\n"
for r in rows:
txt += "#EXTINF:-1,%s\n" % r["title"]
txt += "%s\n" % http_fix_url(r["url"]) |
|