delarte/src/delarte/download.py

62 lines
1.5 KiB
Python

# License: GNU AGPL v3: http://www.gnu.org/licenses/
# This file is part of `delarte` (https://git.afpy.org/fcode/delarte.git)
"""Provide download utilities."""
import os
from . import subtitles
from .error import HTTPError
_CHUNK = 64 * 1024
def download_mp4_media(url, file_name, http, on_progress):
"""Download a MP4 (video or audio) to given file."""
on_progress(file_name, 0, 0)
if os.path.isfile(file_name):
on_progress(file_name, 1, 1)
return
temp_file = f"{file_name}.tmp"
with open(temp_file, "ab") as f:
r = http.request(
"GET",
url,
headers={"Range": f"bytes={f.tell()}-"},
preload_content=False,
)
HTTPError.raise_for_status(r)
_, total = r.getheader("content-range").split("/")
total = int(total)
for content in r.stream(_CHUNK, True):
f.write(content)
on_progress(file_name, f.tell(), total)
r.release_conn()
os.rename(temp_file, file_name)
def download_vtt_media(url, file_name, http, on_progress):
"""Download a VTT and SRT-convert it to to given file."""
on_progress(file_name, 0, 0)
if os.path.isfile(file_name):
on_progress(file_name, 1, 1)
return
temp_file = f"{file_name}.tmp"
with open(temp_file, "w", encoding="utf-8") as f:
r = http.request("GET", url)
HTTPError.raise_for_status(r)
subtitles.convert(r.data.decode("utf-8"), f)
on_progress(file_name, f.tell(), f.tell())
os.rename(temp_file, file_name)