]>
code.delx.au - webdl/blob - common.py
20 autosocks
.try_autosocks()
26 format
= "%(levelname)s %(message)s",
27 level
= logging
.INFO
if os
.environ
.get("DEBUG", None) is None else logging
.DEBUG
,
30 CACHE_FILE
= os
.path
.join(
31 os
.environ
.get("XDG_CACHE_HOME", os
.path
.expanduser("~/.cache")),
35 if not os
.path
.isdir(os
.path
.dirname(CACHE_FILE
)):
36 os
.makedirs(os
.path
.dirname(CACHE_FILE
))
38 requests_cache
.install_cache(CACHE_FILE
, backend
='sqlite', expire_after
=3600)
42 def __init__(self
, title
, parent
=None):
45 parent
.children
.append(self
)
48 self
.can_download
= False
50 def get_children(self
):
55 def fill_children(self
):
63 root_node
= Node("Root")
66 iview
.fill_nodes(root_node
)
69 sbs
.fill_nodes(root_node
)
72 ten
.fill_nodes(root_node
)
76 valid_chars
= frozenset("-_.()!@#%^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
77 def sanify_filename(filename
):
78 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
79 assert len(filename
) > 0
82 def ensure_scheme(url
):
83 parts
= urllib
.parse
.urlparse(url
)
88 return urllib
.parse
.urlunparse(parts
)
90 http_session
= requests
.Session()
91 http_session
.headers
["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:21.0) Gecko/20100101 Firefox/21.0"
94 logging
.debug("grab_text(%r)", url
)
95 request
= http_session
.prepare_request(requests
.Request("GET", url
))
96 response
= http_session
.send(request
)
100 logging
.debug("grab_html(%r)", url
)
101 request
= http_session
.prepare_request(requests
.Request("GET", url
))
102 response
= http_session
.send(request
, stream
=True)
103 doc
= lxml
.html
.parse(io
.BytesIO(response
.content
), lxml
.html
.HTMLParser(encoding
="utf-8", recover
=True))
108 logging
.debug("grab_xml(%r)", url
)
109 request
= http_session
.prepare_request(requests
.Request("GET", url
))
110 response
= http_session
.send(request
, stream
=True)
111 doc
= lxml
.etree
.parse(io
.BytesIO(response
.content
), lxml
.etree
.XMLParser(encoding
="utf-8", recover
=True))
116 logging
.debug("grab_json(%r)", url
)
117 request
= http_session
.prepare_request(requests
.Request("GET", url
))
118 response
= http_session
.send(request
)
119 return response
.json()
121 def exec_subprocess(cmd
):
122 logging
.debug("Executing: %s", cmd
)
124 p
= subprocess
.Popen(cmd
)
127 logging
.error("%s exited with error code: %s", cmd
[0], ret
)
132 logging
.error("Failed to run: %s -- %s", cmd
[0], e
)
133 except KeyboardInterrupt:
134 logging
.info("Cancelled: %s", cmd
)
138 except KeyboardInterrupt:
139 p
.send_signal(signal
.SIGKILL
)
144 def check_command_exists(cmd
):
146 subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
)
152 for ffmpeg
in ["ffmpeg", "avconv"]:
153 if check_command_exists([ffmpeg
, "--help"]):
156 raise Exception("You must install ffmpeg or libav-tools")
159 for ffprobe
in ["ffprobe", "avprobe"]:
160 if check_command_exists([ffprobe
, "--help"]):
163 raise Exception("You must install ffmpeg or libav-tools")
165 def find_streamlink():
166 for streamlink
in ["streamlink", "livestreamer"]:
167 if check_command_exists([streamlink
, "--help"]):
170 raise Exception("You must install streamlink or livestreamer")
172 def get_duration(filename
):
173 ffprobe
= find_ffprobe()
178 "-show_format_entry", "duration",
181 output
= subprocess
.check_output(cmd
).decode("utf-8")
182 for line
in output
.split("\n"):
183 m
= re
.search(R
"([0-9]+)", line
)
186 duration
= m
.group(1)
187 if duration
.isdigit():
191 logging
.debug("Falling back to full decode to find duration: %s % filename")
193 ffmpeg
= find_ffmpeg()
200 output
= subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
).decode("utf-8")
202 for line
in re
.split(R
"[\r\n]", output
):
203 m
= re
.search(R
"time=([0-9:]*)\.", line
)
206 [h
, m
, s
] = m
.group(1).split(":")
207 # ffmpeg prints the duration as it reads the file, we want the last one
208 duration
= int(h
) * 3600 + int(m
) * 60 + int(s
)
213 raise Exception("Unable to determine video duration of " + filename
)
215 def check_video_durations(flv_filename
, mp4_filename
):
216 flv_duration
= get_duration(flv_filename
)
217 mp4_duration
= get_duration(mp4_filename
)
219 if abs(flv_duration
- mp4_duration
) > 1:
221 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
222 mp4_filename
, flv_duration
, mp4_duration
228 def remux(infile
, outfile
):
229 logging
.info("Converting %s to mp4", infile
)
231 ffmpeg
= find_ffmpeg()
235 "-bsf:a", "aac_adtstoasc",
241 if not exec_subprocess(cmd
):
244 if not check_video_durations(infile
, outfile
):
250 def convert_to_mp4(filename
):
251 with
open(filename
, "rb") as f
:
253 basename
, ext
= os
.path
.splitext(filename
)
255 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
256 os
.rename(filename
, basename
+ ".flv")
258 filename
= basename
+ ext
260 if ext
in (".flv", ".ts"):
261 filename_mp4
= basename
+ ".mp4"
262 return remux(filename
, filename_mp4
)
267 def download_hds(filename
, video_url
, pvswf
=None):
268 streamlink
= find_streamlink()
270 filename
= sanify_filename(filename
)
271 logging
.info("Downloading: %s", filename
)
273 video_url
= "hds://" + video_url
275 param
= "%s pvswf=%s" % (video_url
, pvswf
)
286 if exec_subprocess(cmd
):
287 return convert_to_mp4(filename
)
291 def download_hls(filename
, video_url
):
292 streamlink
= find_streamlink()
294 filename
= sanify_filename(filename
)
295 video_url
= "hlsvariant://" + video_url
296 logging
.info("Downloading: %s", filename
)
305 if exec_subprocess(cmd
):
306 return convert_to_mp4(filename
)
310 def download_mpd(filename
, video_url
):
311 streamlink
= find_streamlink()
313 filename
= sanify_filename(filename
)
314 video_url
= "dash://" + video_url
315 logging
.info("Downloading: %s", filename
)
324 if exec_subprocess(cmd
):
325 return convert_to_mp4(filename
)
329 def download_http(filename
, video_url
):
330 filename
= sanify_filename(filename
)
331 logging
.info("Downloading: %s", filename
)
335 "--fail", "--retry", "3",
339 if exec_subprocess(cmd
):
340 return convert_to_mp4(filename
)
344 def natural_sort(l
, key
=None):
345 ignore_list
= ["a", "the"]
351 for c
in re
.split("([0-9]+)", k
):
354 newk
.append(c
.zfill(5))
356 for subc
in c
.split():
357 if subc
not in ignore_list
:
361 return sorted(l
, key
=key_func
)
363 def append_to_qs(url
, params
):
364 r
= list(urllib
.parse
.urlsplit(url
))
365 qs
= urllib
.parse
.parse_qs(r
[3])
366 for k
, v
in params
.items():
371 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
372 url
= urllib
.parse
.urlunsplit(r
)