]>
code.delx.au - webdl/blob - common.py
19 autosocks
.try_autosocks()
25 format
= "%(levelname)s %(message)s",
26 level
= logging
.INFO
if os
.environ
.get("DEBUG", None) is None else logging
.DEBUG
,
29 CACHE_FILE
= os
.path
.join(
30 os
.environ
.get("XDG_CACHE_HOME", os
.path
.expanduser("~/.cache")),
34 requests_cache
.install_cache(CACHE_FILE
, backend
='sqlite', expire_after
=3600)
38 def __init__(self
, title
, parent
=None):
41 parent
.children
.append(self
)
44 self
.can_download
= False
46 def get_children(self
):
51 def fill_children(self
):
59 root_node
= Node("Root")
62 iview
.fill_nodes(root_node
)
65 sbs
.fill_nodes(root_node
)
68 brightcove
.fill_nodes(root_node
)
72 valid_chars
= frozenset("-_.()!@#%^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
73 def sanify_filename(filename
):
74 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
75 assert len(filename
) > 0
78 def ensure_scheme(url
):
79 parts
= urllib
.parse
.urlparse(url
)
84 return urllib
.parse
.urlunparse(parts
)
86 http_session
= requests
.Session()
87 http_session
.headers
["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:21.0) Gecko/20100101 Firefox/21.0"
90 logging
.debug("grab_text(%r)", url
)
91 request
= http_session
.prepare_request(requests
.Request("GET", url
))
92 response
= http_session
.send(request
)
96 logging
.debug("grab_html(%r)", url
)
97 request
= http_session
.prepare_request(requests
.Request("GET", url
))
98 response
= http_session
.send(request
, stream
=True)
99 doc
= lxml
.html
.parse(response
.raw
, lxml
.html
.HTMLParser(encoding
="utf-8", recover
=True))
104 logging
.debug("grab_xml(%r)", url
)
105 request
= http_session
.prepare_request(requests
.Request("GET", url
))
106 response
= http_session
.send(request
, stream
=True)
107 doc
= lxml
.etree
.parse(response
.raw
, lxml
.etree
.XMLParser(encoding
="utf-8", recover
=True))
112 logging
.debug("grab_json(%r)", url
)
113 request
= http_session
.prepare_request(requests
.Request("GET", url
))
114 response
= http_session
.send(request
)
115 return response
.json()
117 def exec_subprocess(cmd
):
118 logging
.debug("Executing: %s", cmd
)
120 p
= subprocess
.Popen(cmd
)
123 logging
.error("%s exited with error code: %s", cmd
[0], ret
)
128 logging
.error("Failed to run: %s -- %s", cmd
[0], e
)
129 except KeyboardInterrupt:
130 logging
.info("Cancelled: %s", cmd
)
134 except KeyboardInterrupt:
135 p
.send_signal(signal
.SIGKILL
)
140 def check_command_exists(cmd
):
142 subprocess
.check_output(cmd
, stderr
=subprocess
.STDOUT
)
148 for ffmpeg
in ["avconv", "ffmpeg"]:
149 if check_command_exists([ffmpeg
, "--help"]):
152 raise Exception("You must install ffmpeg or libav-tools")
155 for ffprobe
in ["avprobe", "ffprobe"]:
156 if check_command_exists([ffprobe
, "--help"]):
159 raise Exception("You must install ffmpeg or libav-tools")
161 def get_duration(filename
):
162 ffprobe
= find_ffprobe()
167 "-show_format_entry", "duration",
170 output
= subprocess
.check_output(cmd
).decode("utf-8")
171 for line
in output
.split("\n"):
172 if line
.startswith("duration="):
173 return float(line
.split("=")[1]) # ffprobe
174 if re
.match(R
'^[0-9.]*$', line
):
175 return float(line
) # avprobe
177 raise Exception("Unable to determine video duration of " + filename
)
179 def check_video_durations(flv_filename
, mp4_filename
):
180 flv_duration
= get_duration(flv_filename
)
181 mp4_duration
= get_duration(mp4_filename
)
183 if abs(flv_duration
- mp4_duration
) > 1:
185 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
186 mp4_filename
, flv_duration
, mp4_duration
192 def remux(infile
, outfile
):
193 logging
.info("Converting %s to mp4", infile
)
195 ffmpeg
= find_ffmpeg()
199 "-bsf:a", "aac_adtstoasc",
204 if not exec_subprocess(cmd
):
207 if not check_video_durations(infile
, outfile
):
213 def convert_to_mp4(filename
):
214 with
open(filename
, "rb") as f
:
216 basename
, ext
= os
.path
.splitext(filename
)
218 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
219 os
.rename(filename
, basename
+ ".flv")
221 filename
= basename
+ ext
223 if ext
in (".flv", ".ts"):
224 filename_mp4
= basename
+ ".mp4"
225 return remux(filename
, filename_mp4
)
230 def download_hds(filename
, video_url
, pvswf
=None):
231 filename
= sanify_filename(filename
)
232 logging
.info("Downloading: %s", filename
)
234 video_url
= "hds://" + video_url
236 param
= "%s pvswf=%s" % (video_url
, pvswf
)
246 if exec_subprocess(cmd
):
247 return convert_to_mp4(filename
)
251 def download_hls(filename
, video_url
):
252 filename
= sanify_filename(filename
)
253 video_url
= "hlsvariant://" + video_url
254 logging
.info("Downloading: %s", filename
)
262 if exec_subprocess(cmd
):
263 return convert_to_mp4(filename
)
267 def download_http(filename
, video_url
):
268 filename
= sanify_filename(filename
)
269 logging
.info("Downloading: %s", filename
)
273 "--fail", "--retry", "3",
277 if exec_subprocess(cmd
):
278 return convert_to_mp4(filename
)
282 def natural_sort(l
, key
=None):
283 ignore_list
= ["a", "the"]
289 for c
in re
.split("([0-9]+)", k
):
292 newk
.append(c
.zfill(5))
294 for subc
in c
.split():
295 if subc
not in ignore_list
:
299 return sorted(l
, key
=key_func
)
301 def append_to_qs(url
, params
):
302 r
= list(urllib
.parse
.urlsplit(url
))
303 qs
= urllib
.parse
.parse_qs(r
[3])
304 for k
, v
in params
.items():
309 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
310 url
= urllib
.parse
.urlunsplit(r
)