Add a download progress hook to ytdl
All checks were successful
Build and Publish Jimmy.2 / build_and_publish (push) Successful in 6s

This commit is contained in:
Nexus 2024-05-31 03:03:22 +01:00
parent c400596861
commit fb4935e331
Signed by: nex
GPG key ID: 0FA334385D0B689F

View file

@ -2,6 +2,9 @@ import asyncio
import functools import functools
import hashlib import hashlib
import logging import logging
import math
import time
import httpx import httpx
import subprocess import subprocess
import tempfile import tempfile
@ -257,7 +260,32 @@ class YTDLCog(commands.Cog):
): ):
"""Runs yt-dlp and outputs into discord.""" """Runs yt-dlp and outputs into discord."""
await ctx.defer() await ctx.defer()
last_edit = time.time()
options = self.default_options.copy() options = self.default_options.copy()
async def _download_hook(_data: dict[str, typing.Any]):
n = time.time()
_total = _data.get("total_bytes", _data.get("total_bytes_estimate"))
if _total:
_percent = round(_data.get("downloaded_bytes", 0) / _total * 100, 2)
else:
_total = max(1, _data.get("fragment_count", 4096))
_percent = round(max(_data.get("fragment_index", 1), 1) / _total * 100, 2)
_speed_bytes_per_second = _data.get("speed", 1)
_speed_megabits_per_second = round((_speed_bytes_per_second * 8) / 1024 / 1024)
_eta = discord.utils.utcnow() + _data.get("eta") or discord.utils.utcnow()
blocks = "#" * math.floor(_percent / 10)
bar = f"{blocks}{'.' * (10 - len(blocks))}"
line = (f"{_percent}% [{bar}] | {_speed_megabits_per_second}Mbps | "
f"ETA {discord.utils.format_dt(_eta, 'R')}")
nonlocal last_edit
if (n - last_edit) >= 5:
embed.clear_fields()
embed.add_field(name="Progress", value=line)
await ctx.edit(embed=embed)
last_edit = time.time()
options["progress_hooks"] = [_download_hook]
description = "" description = ""
with tempfile.TemporaryDirectory(prefix="jimmy-ytdl-") as temp_dir: with tempfile.TemporaryDirectory(prefix="jimmy-ytdl-") as temp_dir:
@ -355,15 +383,20 @@ class YTDLCog(commands.Cog):
description += "\n".join(lines) description += "\n".join(lines)
domain = urlparse(webpage_url).netloc domain = urlparse(webpage_url).netloc
await ctx.edit( embed = discord.Embed(
embed=discord.Embed(
title=title, title=title,
description=description, description=description,
url=webpage_url, url=webpage_url,
colour=self.colours.get(domain, discord.Colour.og_blurple()), colour=self.colours.get(domain, discord.Colour.og_blurple()),
) )
.set_footer(text="Downloading (step 2/10)") embed.add_field(
.set_thumbnail(url=thumbnail_url) name="Progress",
value="0% [..........] <t:253402300800:R>"
)
embed.set_footer(text="Downloading (step 2/10)")
embed.set_thumbnail(url=thumbnail_url)
await ctx.edit(
embed=embed
) )
previous = await self.get_saved(webpage_url, chosen_format_id, snip or "*") previous = await self.get_saved(webpage_url, chosen_format_id, snip or "*")
if previous: if previous:
@ -379,6 +412,9 @@ class YTDLCog(commands.Cog):
).set_image(url=previous), ).set_image(url=previous),
) )
return return
last_edit = time.time()
try: try:
await asyncio.to_thread(functools.partial(downloader.download, [url])) await asyncio.to_thread(functools.partial(downloader.download, [url]))
except yt_dlp.DownloadError as e: except yt_dlp.DownloadError as e: