]>
code.delx.au - webdl/blob - common.py
cabfd936c30f65e8fb11df8758888f455ac14222
21 autosocks
.try_autosocks()
27 format
= "%(levelname)s %(message)s",
28 level
= logging
.INFO
if os
.environ
.get("DEBUG", None) is None else logging
.DEBUG
,
31 CACHE_DIR
= os
.path
.join(
32 os
.environ
.get("XDG_CACHE_HOME", os
.path
.expanduser("~/.cache")),
36 USER_AGENT
= "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:21.0) Gecko/20100101 Firefox/21.0"
40 def __init__(self
, title
, parent
=None):
43 parent
.children
.append(self
)
46 self
.can_download
= False
48 def get_children(self
):
53 def fill_children(self
):
61 root_node
= Node("Root")
64 iview
.fill_nodes(root_node
)
67 sbs
.fill_nodes(root_node
)
70 brightcove
.fill_nodes(root_node
)
74 valid_chars
= frozenset("-_.()!@#%^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
75 def sanify_filename(filename
):
76 filename
= "".join(c
for c
in filename
if c
in valid_chars
)
77 assert len(filename
) > 0
80 cookiejar
= http
.cookiejar
.CookieJar()
81 urlopener
= urllib
.request
.build_opener(urllib
.request
.HTTPCookieProcessor(cookiejar
))
82 def _urlopen(url
, referrer
=None):
83 req
= urllib
.request
.Request(url
)
84 req
.add_header("User-Agent", USER_AGENT
)
86 req
.add_header("Referer", referrer
)
87 return urlopener
.open(req
)
89 def urlopen(url
, max_age
):
90 logging
.debug("urlopen(%r, %r)", url
, max_age
)
92 if not os
.path
.isdir(CACHE_DIR
):
93 os
.makedirs(CACHE_DIR
)
98 filename
= hashlib
.md5(url
.encode("utf-8")).hexdigest()
99 filename
= os
.path
.join(CACHE_DIR
, filename
)
100 if os
.path
.exists(filename
):
101 file_age
= int(time
.time()) - os
.path
.getmtime(filename
)
102 if file_age
< max_age
:
103 logging
.debug("loading from cache: %s", filename
)
104 return open(filename
, "rb")
106 logging
.debug("downloading: %s -> %s", url
, filename
)
108 dst
= open(filename
, "wb")
110 shutil
.copyfileobj(src
, dst
)
111 except Exception as e
:
120 return open(filename
, "rb")
122 def grab_text(url
, max_age
):
123 f
= urlopen(url
, max_age
)
124 text
= f
.read().decode("utf-8")
128 def grab_html(url
, max_age
):
129 f
= urlopen(url
, max_age
)
130 doc
= lxml
.html
.parse(f
, lxml
.html
.HTMLParser(encoding
="utf-8", recover
=True))
134 def grab_xml(url
, max_age
):
135 f
= urlopen(url
, max_age
)
136 doc
= lxml
.etree
.parse(f
, lxml
.etree
.XMLParser(encoding
="utf-8", recover
=True))
140 def grab_json(url
, max_age
, skip_assignment
=False, skip_function
=False):
141 f
= urlopen(url
, max_age
)
142 text
= f
.read().decode("utf-8")
150 rpos
= text
.rfind(")")
151 text
= text
[pos
+1:rpos
]
153 doc
= json
.loads(text
)
157 def exec_subprocess(cmd
):
158 logging
.debug("Executing: %s", cmd
)
160 p
= subprocess
.Popen(cmd
)
163 logging
.error("%s exited with error code: %s", cmd
[0], ret
)
168 logging
.error("Failed to run: %s -- %s", cmd
[0], e
)
169 except KeyboardInterrupt:
170 logging
.info("Cancelled: %s", cmd
)
174 except KeyboardInterrupt:
175 p
.send_signal(signal
.SIGKILL
)
180 def check_command_exists(cmd
):
182 subprocess
.check_output(cmd
)
187 def generate_remux_cmd(infile
, outfile
):
188 if check_command_exists(["avconv", "--help"]):
192 "-bsf:a", "aac_adtstoasc",
198 if check_command_exists(["ffmpeg", "--help"]):
202 "-bsf:a", "aac_adtstoasc",
208 raise Exception("You must install ffmpeg or libav-tools")
210 def remux(infile
, outfile
):
211 logging
.info("Converting %s to mp4", infile
)
212 cmd
= generate_remux_cmd(infile
, outfile
)
213 if not exec_subprocess(cmd
):
214 # failed, error has already been logged
217 flv_size
= os
.stat(infile
).st_size
218 mp4_size
= os
.stat(outfile
).st_size
219 if abs(flv_size
- mp4_size
) < 0.1 * flv_size
:
223 logging
.error("The size of %s is suspicious, did the remux fail?", outfile
)
225 except Exception as e
:
226 logging
.error("Conversion failed! %s", e
)
229 def convert_to_mp4(filename
):
230 with
open(filename
, "rb") as f
:
232 basename
, ext
= os
.path
.splitext(filename
)
234 if ext
== ".mp4" and fourcc
== b
"FLV\x01":
235 os
.rename(filename
, basename
+ ".flv")
237 filename
= basename
+ ext
239 if ext
in (".flv", ".ts"):
240 filename_mp4
= basename
+ ".mp4"
241 return remux(filename
, filename_mp4
)
246 def download_hds(filename
, video_url
, pvswf
=None):
247 filename
= sanify_filename(filename
)
248 logging
.info("Downloading: %s", filename
)
250 video_url
= video_url
.replace("http://", "hds://")
252 param
= "%s pvswf=%s" % (video_url
, pvswf
)
262 if exec_subprocess(cmd
):
263 return convert_to_mp4(filename
)
267 def download_hls(filename
, video_url
):
268 filename
= sanify_filename(filename
)
269 video_url
= video_url
.replace("http://", "hlsvariant://")
270 logging
.info("Downloading: %s", filename
)
278 if exec_subprocess(cmd
):
279 return convert_to_mp4(filename
)
283 def download_http(filename
, video_url
):
284 filename
= sanify_filename(filename
)
285 logging
.info("Downloading: %s", filename
)
289 "--fail", "--retry", "3",
293 if exec_subprocess(cmd
):
294 return convert_to_mp4(filename
)
298 def natural_sort(l
, key
=None):
299 ignore_list
= ["a", "the"]
305 for c
in re
.split("([0-9]+)", k
):
308 newk
.append(c
.zfill(5))
310 for subc
in c
.split():
311 if subc
not in ignore_list
:
315 return sorted(l
, key
=key_func
)
317 def append_to_qs(url
, params
):
318 r
= list(urllib
.parse
.urlsplit(url
))
319 qs
= urllib
.parse
.parse_qs(r
[3])
320 for k
, v
in params
.items():
325 r
[3] = urllib
.parse
.urlencode(sorted(qs
.items()), True)
326 url
= urllib
.parse
.urlunsplit(r
)