]> code.delx.au - webdl/blob - common.py
Prefer ffmpeg if it is installed
[webdl] / common.py
1 import hashlib
2 import io
3 import json
4 import logging
5 import lxml.etree
6 import lxml.html
7 import os
8 import re
9 import requests
10 import requests_cache
11 import shutil
12 import signal
13 import subprocess
14 import time
15 import urllib.parse
16
17
18 try:
19 import autosocks
20 autosocks.try_autosocks()
21 except ImportError:
22 pass
23
24
25 logging.basicConfig(
26 format = "%(levelname)s %(message)s",
27 level = logging.INFO if os.environ.get("DEBUG", None) is None else logging.DEBUG,
28 )
29
30 CACHE_FILE = os.path.join(
31 os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache")),
32 "webdl",
33 "requests_cache"
34 )
35 if not os.path.isdir(os.path.dirname(CACHE_FILE)):
36 os.makedirs(os.path.dirname(CACHE_FILE))
37
38 requests_cache.install_cache(CACHE_FILE, backend='sqlite', expire_after=3600)
39
40
41 class Node(object):
42 def __init__(self, title, parent=None):
43 self.title = title
44 if parent:
45 parent.children.append(self)
46 self.parent = parent
47 self.children = []
48 self.can_download = False
49
50 def get_children(self):
51 if not self.children:
52 self.fill_children()
53 return self.children
54
55 def fill_children(self):
56 pass
57
58 def download(self):
59 raise NotImplemented
60
61
62 def load_root_node():
63 root_node = Node("Root")
64
65 import iview
66 iview.fill_nodes(root_node)
67
68 import sbs
69 sbs.fill_nodes(root_node)
70
71 import ten
72 ten.fill_nodes(root_node)
73
74 return root_node
75
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
80 return filename
81
82 def ensure_scheme(url):
83 parts = urllib.parse.urlparse(url)
84 if parts.scheme:
85 return url
86 parts = list(parts)
87 parts[0] = "http"
88 return urllib.parse.urlunparse(parts)
89
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"
92
93 def grab_text(url):
94 logging.debug("grab_text(%r)", url)
95 request = http_session.prepare_request(requests.Request("GET", url))
96 response = http_session.send(request)
97 return response.text
98
99 def grab_html(url):
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))
104 response.close()
105 return doc
106
107 def grab_xml(url):
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))
112 response.close()
113 return doc
114
115 def grab_json(url):
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()
120
121 def exec_subprocess(cmd):
122 logging.debug("Executing: %s", cmd)
123 try:
124 p = subprocess.Popen(cmd)
125 ret = p.wait()
126 if ret != 0:
127 logging.error("%s exited with error code: %s", cmd[0], ret)
128 return False
129 else:
130 return True
131 except OSError as e:
132 logging.error("Failed to run: %s -- %s", cmd[0], e)
133 except KeyboardInterrupt:
134 logging.info("Cancelled: %s", cmd)
135 try:
136 p.terminate()
137 p.wait()
138 except KeyboardInterrupt:
139 p.send_signal(signal.SIGKILL)
140 p.wait()
141 return False
142
143
144 def check_command_exists(cmd):
145 try:
146 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
147 return True
148 except Exception:
149 return False
150
151 def find_ffmpeg():
152 for ffmpeg in ["ffmpeg", "avconv"]:
153 if check_command_exists([ffmpeg, "--help"]):
154 return ffmpeg
155
156 raise Exception("You must install ffmpeg or libav-tools")
157
158 def find_ffprobe():
159 for ffprobe in ["ffprobe", "avprobe"]:
160 if check_command_exists([ffprobe, "--help"]):
161 return ffprobe
162
163 raise Exception("You must install ffmpeg or libav-tools")
164
165 def find_streamlink():
166 for streamlink in ["streamlink", "livestreamer"]:
167 if check_command_exists([streamlink, "--help"]):
168 return streamlink
169
170 raise Exception("You must install streamlink or livestreamer")
171
172 def get_duration(filename):
173 ffprobe = find_ffprobe()
174
175 cmd = [
176 ffprobe,
177 filename,
178 "-show_format_entry", "duration",
179 "-v", "quiet",
180 ]
181 output = subprocess.check_output(cmd).decode("utf-8")
182 for line in output.split("\n"):
183 m = re.search(R"([0-9]+)", line)
184 if not m:
185 continue
186 duration = m.group(1)
187 if duration.isdigit():
188 return int(duration)
189
190
191 logging.debug("Falling back to full decode to find duration: %s % filename")
192
193 ffmpeg = find_ffmpeg()
194 cmd = [
195 ffmpeg,
196 "-i", filename,
197 "-vn",
198 "-f", "null", "-",
199 ]
200 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
201 duration = None
202 for line in re.split(R"[\r\n]", output):
203 m = re.search(R"time=([0-9:]*)\.", line)
204 if not m:
205 continue
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)
209
210 if duration:
211 return duration
212 else:
213 raise Exception("Unable to determine video duration of " + filename)
214
215 def check_video_durations(flv_filename, mp4_filename):
216 flv_duration = get_duration(flv_filename)
217 mp4_duration = get_duration(mp4_filename)
218
219 if abs(flv_duration - mp4_duration) > 1:
220 logging.error(
221 "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
222 mp4_filename, flv_duration, mp4_duration
223 )
224 return False
225
226 return True
227
228 def remux(infile, outfile):
229 logging.info("Converting %s to mp4", infile)
230
231 ffmpeg = find_ffmpeg()
232 cmd = [
233 ffmpeg,
234 "-i", infile,
235 "-bsf:a", "aac_adtstoasc",
236 "-acodec", "copy",
237 "-vcodec", "copy",
238 "-y",
239 outfile,
240 ]
241 if not exec_subprocess(cmd):
242 return False
243
244 if not check_video_durations(infile, outfile):
245 return False
246
247 os.unlink(infile)
248 return True
249
250 def convert_to_mp4(filename):
251 with open(filename, "rb") as f:
252 fourcc = f.read(4)
253 basename, ext = os.path.splitext(filename)
254
255 if ext == ".mp4" and fourcc == b"FLV\x01":
256 os.rename(filename, basename + ".flv")
257 ext = ".flv"
258 filename = basename + ext
259
260 if ext in (".flv", ".ts"):
261 filename_mp4 = basename + ".mp4"
262 return remux(filename, filename_mp4)
263
264 return ext == ".mp4"
265
266
267 def download_hds(filename, video_url, pvswf=None):
268 streamlink = find_streamlink()
269
270 filename = sanify_filename(filename)
271 logging.info("Downloading: %s", filename)
272
273 video_url = "hds://" + video_url
274 if pvswf:
275 param = "%s pvswf=%s" % (video_url, pvswf)
276 else:
277 param = video_url
278
279 cmd = [
280 streamlink,
281 "-f",
282 "-o", filename,
283 param,
284 "best",
285 ]
286 if exec_subprocess(cmd):
287 return convert_to_mp4(filename)
288 else:
289 return False
290
291 def download_hls(filename, video_url):
292 streamlink = find_streamlink()
293
294 filename = sanify_filename(filename)
295 video_url = "hlsvariant://" + video_url
296 logging.info("Downloading: %s", filename)
297
298 cmd = [
299 streamlink,
300 "-f",
301 "-o", filename,
302 video_url,
303 "best",
304 ]
305 if exec_subprocess(cmd):
306 return convert_to_mp4(filename)
307 else:
308 return False
309
310 def download_mpd(filename, video_url):
311 streamlink = find_streamlink()
312
313 filename = sanify_filename(filename)
314 video_url = "dash://" + video_url
315 logging.info("Downloading: %s", filename)
316
317 cmd = [
318 streamlink,
319 "-f",
320 "-o", filename,
321 video_url,
322 "best",
323 ]
324 if exec_subprocess(cmd):
325 return convert_to_mp4(filename)
326 else:
327 return False
328
329 def download_http(filename, video_url):
330 filename = sanify_filename(filename)
331 logging.info("Downloading: %s", filename)
332
333 cmd = [
334 "curl",
335 "--fail", "--retry", "3",
336 "-o", filename,
337 video_url,
338 ]
339 if exec_subprocess(cmd):
340 return convert_to_mp4(filename)
341 else:
342 return False
343
344 def natural_sort(l, key=None):
345 ignore_list = ["a", "the"]
346 def key_func(k):
347 if key is not None:
348 k = key(k)
349 k = k.lower()
350 newk = []
351 for c in re.split("([0-9]+)", k):
352 c = c.strip()
353 if c.isdigit():
354 newk.append(c.zfill(5))
355 else:
356 for subc in c.split():
357 if subc not in ignore_list:
358 newk.append(subc)
359 return newk
360
361 return sorted(l, key=key_func)
362
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():
367 if v is not None:
368 qs[k] = v
369 elif k in qs:
370 del qs[k]
371 r[3] = urllib.parse.urlencode(sorted(qs.items()), True)
372 url = urllib.parse.urlunsplit(r)
373 return url
374