62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
|
import re
|
||
|
from os import path
|
||
|
from time import time
|
||
|
|
||
|
from discord import Interaction
|
||
|
|
||
|
from entity import Entry
|
||
|
from framework import Downloader, Youtube
|
||
|
|
||
|
|
||
|
class FileManager:
|
||
|
def __init__(
|
||
|
self, youtube: Youtube, downloader: Downloader, downloadDirectory: str
|
||
|
) -> None:
|
||
|
self.youtube = youtube
|
||
|
self.downloader = downloader
|
||
|
self.downloadDirectory = downloadDirectory
|
||
|
self.youtubeVideoRegex = re.compile(
|
||
|
r"(https:\/\/)?(www|music)\.youtube\.com\/(watch\?v=|shorts\/)\w*"
|
||
|
)
|
||
|
self.progressLastUpdate = 0
|
||
|
|
||
|
def getFileName(self, entryId: str) -> str:
|
||
|
return path.join(self.downloadDirectory, entryId)
|
||
|
|
||
|
async def downloadProgress(
|
||
|
self,
|
||
|
interaction: Interaction,
|
||
|
entry: Entry,
|
||
|
current_size: int,
|
||
|
total_size: int,
|
||
|
):
|
||
|
if time() - self.progressLastUpdate > 1:
|
||
|
self.progressLastUpdate = time()
|
||
|
await interaction.edit_original_response(
|
||
|
content=f"Downloading {entry.title.name} [%.2f/%.2f Mo]"
|
||
|
% (current_size / 1024 / 1024, total_size / 1024 / 1024)
|
||
|
)
|
||
|
|
||
|
async def download(self, interaction: Interaction, entries: list[Entry]):
|
||
|
for entry in entries:
|
||
|
entryId = self.youtube.getId(entry.title.url)
|
||
|
|
||
|
fileName = self.getFileName(entryId)
|
||
|
if not path.isfile(fileName) and isinstance(entry.source, str):
|
||
|
if self.youtubeVideoRegex.match(entry.source) is not None:
|
||
|
entry.source = await self.youtube.download(
|
||
|
entry.source,
|
||
|
fileName,
|
||
|
lambda current_size, total_size: self.downloadProgress(
|
||
|
interaction, entry, current_size, total_size
|
||
|
),
|
||
|
)
|
||
|
else:
|
||
|
entry.source = await self.downloader.download(
|
||
|
entry.source,
|
||
|
fileName,
|
||
|
lambda current_size, total_size: self.downloadProgress(
|
||
|
interaction, entry, current_size, total_size
|
||
|
),
|
||
|
)
|