dj-embe/service/fileManager.py

70 lines
2.4 KiB
Python
Raw Normal View History

2023-05-06 01:16:26 +00:00
import re
2023-05-16 23:04:16 +00:00
from collections.abc import AsyncIterator
from os import path, stat
2023-05-06 01:16:26 +00:00
from time import time
from discord import Interaction
2023-05-16 23:04:16 +00:00
from entity import Entry, File
2023-05-06 01:16:26 +00:00
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*"
)
2023-05-16 23:04:16 +00:00
self.progressLastUpdate = 0.0
2023-05-06 01:16:26 +00:00
def getFileName(self, entryId: str) -> str:
return path.join(self.downloadDirectory, entryId)
async def downloadProgress(
self,
interaction: Interaction,
entry: Entry,
2023-05-16 23:04:16 +00:00
current_size: float,
total_size: float,
2023-05-06 01:16:26 +00:00
):
2023-05-16 23:04:16 +00:00
current_size = current_size / 1024 / 1024
total_size = total_size / 1024 / 1024
if time() - self.progressLastUpdate > 1 and total_size > 10:
2023-05-06 01:16:26 +00:00
self.progressLastUpdate = time()
await interaction.edit_original_response(
content=f"Downloading {entry.title.name} [%.2f/%.2f Mo]"
2023-05-16 23:04:16 +00:00
% (current_size, total_size)
2023-05-06 01:16:26 +00:00
)
2023-05-16 23:04:16 +00:00
async def download(
self, interaction: Interaction, entries: list[Entry]
) -> AsyncIterator[File]:
2023-05-06 01:16:26 +00:00
for entry in entries:
2023-05-16 23:04:16 +00:00
print("DOWNLOAD", entry.source)
entryId = self.youtube.getId(entry.source)
2023-05-06 01:16:26 +00:00
fileName = self.getFileName(entryId)
if not path.isfile(fileName) and isinstance(entry.source, str):
if self.youtubeVideoRegex.match(entry.source) is not None:
2023-05-16 23:04:16 +00:00
yield await self.youtube.download(
2023-05-06 01:16:26 +00:00
entry.source,
fileName,
lambda current_size, total_size: self.downloadProgress(
interaction, entry, current_size, total_size
),
)
else:
2023-05-16 23:04:16 +00:00
yield await self.downloader.download(
2023-05-06 01:16:26 +00:00
entry.source,
fileName,
lambda current_size, total_size: self.downloadProgress(
interaction, entry, current_size, total_size
),
)
2023-05-16 23:04:16 +00:00
yield File(fileName, stat(fileName).st_size)