- f = urlopen(url, max_age)
- doc = etree.parse(f)
- f.close()
- return doc
-
-def grab_json(url, max_age):
- f = urlopen(url, max_age)
- doc = json.load(f)
- f.close()
- return doc
-
-def download_rtmp(filename, vbase, vpath, hash_url=None):
- if vpath.endswith(".flv"):
- vpath = vpath[:-4]
- cmd = [
- "rtmpdump",
- "-o", filename,
- "-r", vbase,
- "-y", vpath,
- ]
- if hash_url is not None:
- cmd += ["--swfVfy", hash_url]
- try:
- p = subprocess.Popen(cmd)
- ret = p.wait()
- if ret != 0:
- print >>sys.stderr, "rtmpdump exited with error code:", ret
- return False
- except OSError, e:
- print >>sys.stderr, "Failed to run rtmpdump!", e
- return False
- except KeyboardInterrupt:
- print "Cancelled", cmd
- try:
- p.terminate()
- p.wait()
- except KeyboardInterrupt:
- p.send_signal(signal.SIGKILL)
- p.wait()
-
-def download_urllib(filename, url):
- print "Downloading: %s -> %s" % (url, filename)
- try:
- src = urllib.urlopen(url)
- dst = open(filename, "w")
- shutil.copyfileobj(src, dst)
- return True
- except KeyboardInterrupt:
- print "\nCancelled", url
- finally:
- src.close()
- dst.close()
- return False
+ f = urlopen(url, max_age)
+ doc = lxml.etree.parse(f, lxml.etree.XMLParser(encoding="utf-8", recover=True))
+ f.close()
+ return doc
+
+def grab_json(url, max_age, skip_assignment=False, skip_function=False):
+ f = urlopen(url, max_age)
+ text = f.read().decode("utf-8")
+
+ if skip_assignment:
+ pos = text.find("=")
+ text = text[pos+1:]
+
+ elif skip_function:
+ pos = text.find("(")
+ rpos = text.rfind(")")
+ text = text[pos+1:rpos]
+
+ doc = json.loads(text)
+ f.close()
+ return doc
+
+def exec_subprocess(cmd):
+ logging.debug("Executing: %s", cmd)
+ try:
+ p = subprocess.Popen(cmd)
+ ret = p.wait()
+ if ret != 0:
+ logging.error("%s exited with error code: %s", cmd[0], ret)
+ return False
+ else:
+ return True
+ except OSError as e:
+ logging.error("Failed to run: %s -- %s", cmd[0], e)
+ except KeyboardInterrupt:
+ logging.info("Cancelled: %s", cmd)
+ try:
+ p.terminate()
+ p.wait()
+ except KeyboardInterrupt:
+ p.send_signal(signal.SIGKILL)
+ p.wait()
+ return False
+
+
+def check_command_exists(cmd):
+ try:
+ subprocess.check_output(cmd, stderr=subprocess.STDOUT)
+ return True
+ except Exception:
+ return False
+
+def find_ffmpeg():
+ for ffmpeg in ["avconv", "ffmpeg"]:
+ if check_command_exists([ffmpeg, "--help"]):
+ return ffmpeg
+
+ raise Exception("You must install ffmpeg or libav-tools")
+
+def find_ffprobe():
+ for ffprobe in ["avprobe", "ffprobe"]:
+ if check_command_exists([ffprobe, "--help"]):
+ return ffprobe
+
+ raise Exception("You must install ffmpeg or libav-tools")
+
+def get_duration(filename):
+ ffprobe = find_ffprobe()
+
+ cmd = [
+ ffprobe,
+ filename,
+ "-show_format_entry", "duration",
+ "-v", "quiet",
+ ]
+ output = subprocess.check_output(cmd).decode("utf-8")
+ for line in output.split("\n"):
+ if line.startswith("duration="):
+ return float(line.split("=")[1])
+
+ raise Exception("Unable to determine video duration of " + filename)
+
+def check_video_durations(flv_filename, mp4_filename):
+ flv_duration = get_duration(flv_filename)
+ mp4_duration = get_duration(mp4_filename)
+
+ if abs(flv_duration - mp4_duration) > 1:
+ logging.error(
+ "The duration of %s is suspicious, did the remux fail? Expected %s == %s",
+ mp4_filename, flv_duration, mp4_duration
+ )
+ return False
+
+ return True
+
+def remux(infile, outfile):
+ logging.info("Converting %s to mp4", infile)
+
+ ffmpeg = find_ffmpeg()
+ cmd = [
+ ffmpeg,
+ "-i", infile,
+ "-bsf:a", "aac_adtstoasc",
+ "-acodec", "copy",
+ "-vcodec", "copy",
+ outfile,
+ ]
+ if not exec_subprocess(cmd):
+ return False
+
+ if not check_video_durations(infile, outfile):
+ return False
+
+ os.unlink(infile)
+ return True
+
+def convert_to_mp4(filename):
+ with open(filename, "rb") as f:
+ fourcc = f.read(4)
+ basename, ext = os.path.splitext(filename)
+
+ if ext == ".mp4" and fourcc == b"FLV\x01":
+ os.rename(filename, basename + ".flv")
+ ext = ".flv"
+ filename = basename + ext
+
+ if ext in (".flv", ".ts"):
+ filename_mp4 = basename + ".mp4"
+ return remux(filename, filename_mp4)
+
+ return ext == ".mp4"
+
+
+def download_hds(filename, video_url, pvswf=None):
+ filename = sanify_filename(filename)
+ logging.info("Downloading: %s", filename)
+
+ video_url = "hds://" + video_url
+ if pvswf:
+ param = "%s pvswf=%s" % (video_url, pvswf)
+ else:
+ param = video_url
+
+ cmd = [
+ "livestreamer",
+ "-o", filename,
+ param,
+ "best",
+ ]
+ if exec_subprocess(cmd):
+ return convert_to_mp4(filename)
+ else:
+ return False
+
+def download_hls(filename, video_url):
+ filename = sanify_filename(filename)
+ video_url = "hlsvariant://" + video_url
+ logging.info("Downloading: %s", filename)
+
+ cmd = [
+ "livestreamer",
+ "-o", filename,
+ video_url,
+ "best",
+ ]
+ if exec_subprocess(cmd):
+ return convert_to_mp4(filename)
+ else:
+ return False
+
+def download_http(filename, video_url):
+ filename = sanify_filename(filename)
+ logging.info("Downloading: %s", filename)
+
+ cmd = [
+ "curl",
+ "--fail", "--retry", "3",
+ "-o", filename,
+ video_url,
+ ]
+ if exec_subprocess(cmd):
+ return convert_to_mp4(filename)
+ else:
+ return False
+
+def natural_sort(l, key=None):
+ ignore_list = ["a", "the"]
+ def key_func(k):
+ if key is not None:
+ k = key(k)
+ k = k.lower()
+ newk = []
+ for c in re.split("([0-9]+)", k):
+ c = c.strip()
+ if c.isdigit():
+ newk.append(c.zfill(5))
+ else:
+ for subc in c.split():
+ if subc not in ignore_list:
+ newk.append(subc)
+ return newk
+
+ return sorted(l, key=key_func)
+
+def append_to_qs(url, params):
+ r = list(urllib.parse.urlsplit(url))
+ qs = urllib.parse.parse_qs(r[3])
+ for k, v in params.items():
+ if v is not None:
+ qs[k] = v
+ elif k in qs:
+ del qs[k]
+ r[3] = urllib.parse.urlencode(sorted(qs.items()), True)
+ url = urllib.parse.urlunsplit(r)
+ return url