]>
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 if check_command_exists(["ffmpeg", "--help"]):
155 if check_command_exists(["avconv", "--help"]):
156 logging
.warn("Detected libav-tools! ffmpeg is recommended")
159 raise Exception("You must install ffmpeg or libav-tools")
162 if check_command_exists(["ffprobe", "--help"]):
165 if check_command_exists(["avprobe", "--help"]):
166 logging
.warn("Detected libav-tools! ffmpeg is recommended")
169 raise Exception("You must install ffmpeg or libav-tools")
171 def find_streamlink():
172 if check_command_exists(["streamlink", "--help"]):
175 if check_command_exists(["livestreamer", "--help"]):
176 logging
.warn("Detected livestreamer! streamlink is recommended")
177 return "livestreamer"
179 raise Exception("You must install streamlink or livestreamer")
181 def get_duration(filename
):
182 ffprobe
= find_ffprobe()
187 "-show_format_entry", "duration",
190 output
= subprocess
.check_output(cmd
).decode("utf-8")
191 for line
in output
.split("\n"):
192 m
= re
.search(R
"([0-9]+)", line
)
195 duration
= m
.group(1)
196 if duration
.isdigit():
200 logging
.debug("Falling back to full decode to find duration: %s % filename")
202 ffmpeg
= find_ffmpeg()
209 output
= subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
).decode("utf-8")
211 for line
in re
.split(R
"[\r\n]", output
):
212 m
= re
.search(R
"time=([0-9:]*)\.", line
)
215 [h
, m
, s
] = m
.group(1).split(":")
216 # ffmpeg prints the duration as it reads the file, we want the last one
217 duration
= int(h
) * 3600 + int(m
) * 60 + int(s
)
222 raise Exception("Unable to determine video duration of " + filename
)
224 def check_video_durations(flv_filename
, mp4_filename
):
225 flv_duration
= get_duration(flv_filename
)
226 mp4_duration
= get_duration(mp4_filename
)
228 if abs(flv_duration
- mp4_duration
) > 1:
230 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
231 mp4_filename
, flv_duration
, mp4_duration
237 def remux(infile
, outfile
):
238 logging
.info("Converting %s to mp4", infile
)
240 ffmpeg
= find_ffmpeg()
244 "-bsf:a", "aac_adtstoasc",
250 if not exec_subprocess(cmd
):
253 if not check_video_durations(infile
, outfile
):
259 def convert_to_mp4(filename
):
260 with
open(filename
, "rb") as f
:
262 basename
, ext
= os
.path
.splitext(filename
)
264 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
265 os
.rename(filename
, basename
+ ".flv")
267 filename
= basename
+ ext
269 if ext
in (".flv", ".ts"):
270 filename_mp4
= basename
+ ".mp4"
271 return remux(filename
, filename_mp4
)
276 def download_hds(filename
, video_url
, pvswf
=None):
277 streamlink
= find_streamlink()
279 filename
= sanify_filename(filename
)
280 logging
.info("Downloading: %s", filename
)
282 video_url
= "hds://" + video_url
284 param
= "%s pvswf=%s" % (video_url
, pvswf
)
295 if exec_subprocess(cmd
):
296 return convert_to_mp4(filename
)
300 def download_hls(filename
, video_url
):
301 streamlink
= find_streamlink()
303 filename
= sanify_filename(filename
)
304 video_url
= "hlsvariant://" + video_url
305 logging
.info("Downloading: %s", filename
)
314 if exec_subprocess(cmd
):
315 return convert_to_mp4(filename
)
319 def download_mpd(filename
, video_url
):
320 streamlink
= find_streamlink()
322 filename
= sanify_filename(filename
)
323 video_url
= "dash://" + video_url
324 logging
.info("Downloading: %s", filename
)
333 if exec_subprocess(cmd
):
334 return convert_to_mp4(filename
)
338 def download_http(filename
, video_url
):
339 filename
= sanify_filename(filename
)
340 logging
.info("Downloading: %s", filename
)
344 "--fail", "--retry", "3",
348 if exec_subprocess(cmd
):
349 return convert_to_mp4(filename
)
353 def natural_sort(l
, key
=None):
354 ignore_list
= ["a", "the"]
360 for c
in re
.split("([0-9]+)", k
):
363 newk
.append(c
.zfill(5))
365 for subc
in c
.split():
366 if subc
not in ignore_list
:
370 return sorted(l
, key
=key_func
)
372 def append_to_qs(url
, params
):
373 r
= list(urllib
.parse
.urlsplit(url
))
374 qs
= urllib
.parse
.parse_qs(r
[3])
375 for k
, v
in params
.items():
380 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
381 url
= urllib
.parse
.urlunsplit(r
)