Skip to content

Instantly share code, notes, and snippets.

@jaspervdj
Last active March 3, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaspervdj/1b1365baa19b4d787c9be788c5ea1ee0 to your computer and use it in GitHub Desktop.
Save jaspervdj/1b1365baa19b4d787c9be788c5ea1ee0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os.path
import sys
import time
import urllib.parse
import urllib.request
from typing import Iterable
def get_segment_urls(m3u8_url: str) -> Iterable[str]:
m3u8_text: str = urllib.request.urlopen(m3u8_url).read().decode('utf-8')
for line in m3u8_text.splitlines():
if line.startswith("#"):
continue
yield urllib.parse.urljoin(m3u8_url, line)
def download_segment(segment_url: str, destination: str) -> None:
if os.path.exists(destination):
print(f"Skip {destination}", file=sys.stderr)
else:
print(f"Download {segment_url}", file=sys.stderr)
content: bytes = urllib.request.urlopen(segment_url, timeout=30).read()
with open(destination, "wb") as f:
f.write(content)
def download_segments(m3u8_url: str, output_dir: str) -> None:
segment_urls = list(get_segment_urls(m3u8_url))
for i in range(len(segment_urls)):
segment_url = segment_urls[i]
_, ext = os.path.splitext(segment_url)
output_path = os.path.join(output_dir, "{:05d}{}".format(i, ext))
progress: float = 100 * i / len(segment_urls)
print("[{:04.2f}%] ".format(progress), file=sys.stderr, end="")
download_segment(segment_url, output_path)
def main(m3u8_url: str, output_dir: str) -> None:
success = False
while not success:
try:
download_segments(m3u8_url, output_dir)
success = True
except KeyboardInterrupt:
return
except Exception as e:
print(e, file=sys.stderr)
print("Waiting before retrying...", file=sys.stderr)
time.sleep(30)
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} M3U8_URL OUTPUT_DIR")
sys.exit(1)
else:
main(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment