]>
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 brightcove
.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 ["avconv", "ffmpeg"]:
153 if check_command_exists([ffmpeg
, "--help"]):
156 raise Exception("You must install ffmpeg or libav-tools")
159 for ffprobe
in ["avprobe", "ffprobe"]:
160 if check_command_exists([ffprobe
, "--help"]):
163 raise Exception("You must install ffmpeg or libav-tools")
165 def get_duration(filename
):
166 ffprobe
= find_ffprobe()
171 "-show_format_entry", "duration",
174 output
= subprocess
.check_output(cmd
).decode("utf-8")
175 for line
in output
.split("\n"):
176 if line
.startswith("duration="):
177 return float(line
.split("=")[1]) # ffprobe
178 if re
.match(R
'^[0-9.]*$', line
):
179 return float(line
) # avprobe
181 raise Exception("Unable to determine video duration of " + filename
)
183 def check_video_durations(flv_filename
, mp4_filename
):
184 flv_duration
= get_duration(flv_filename
)
185 mp4_duration
= get_duration(mp4_filename
)
187 if abs(flv_duration
- mp4_duration
) > 1:
189 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
190 mp4_filename
, flv_duration
, mp4_duration
196 def remux(infile
, outfile
):
197 logging
.info("Converting %s to mp4", infile
)
199 ffmpeg
= find_ffmpeg()
203 "-bsf:a", "aac_adtstoasc",
209 if not exec_subprocess(cmd
):
212 if not check_video_durations(infile
, outfile
):
218 def convert_to_mp4(filename
):
219 with
open(filename
, "rb") as f
:
221 basename
, ext
= os
.path
.splitext(filename
)
223 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
224 os
.rename(filename
, basename
+ ".flv")
226 filename
= basename
+ ext
228 if ext
in (".flv", ".ts"):
229 filename_mp4
= basename
+ ".mp4"
230 return remux(filename
, filename_mp4
)
235 def download_hds(filename
, video_url
, pvswf
=None):
236 filename
= sanify_filename(filename
)
237 logging
.info("Downloading: %s", filename
)
239 video_url
= "hds://" + video_url
241 param
= "%s pvswf=%s" % (video_url
, pvswf
)
252 if exec_subprocess(cmd
):
253 return convert_to_mp4(filename
)
257 def download_hls(filename
, video_url
):
258 filename
= sanify_filename(filename
)
259 video_url
= "hlsvariant://" + video_url
260 logging
.info("Downloading: %s", filename
)
269 if exec_subprocess(cmd
):
270 return convert_to_mp4(filename
)
274 def download_http(filename
, video_url
):
275 filename
= sanify_filename(filename
)
276 logging
.info("Downloading: %s", filename
)
280 "--fail", "--retry", "3",
284 if exec_subprocess(cmd
):
285 return convert_to_mp4(filename
)
289 def natural_sort(l
, key
=None):
290 ignore_list
= ["a", "the"]
296 for c
in re
.split("([0-9]+)", k
):
299 newk
.append(c
.zfill(5))
301 for subc
in c
.split():
302 if subc
not in ignore_list
:
306 return sorted(l
, key
=key_func
)
308 def append_to_qs(url
, params
):
309 r
= list(urllib
.parse
.urlsplit(url
))
310 qs
= urllib
.parse
.parse_qs(r
[3])
311 for k
, v
in params
.items():
316 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
317 url
= urllib
.parse
.urlunsplit(r
)