badl/manager/__init__.py

62 lines
1.8 KiB
Python
Raw Normal View History

2023-02-21 17:50:53 +08:00
from video import Video
from threading import Thread
2023-03-04 13:53:05 +08:00
from queue import SimpleQueue
2023-02-21 17:50:53 +08:00
from sanitize_filename import sanitize
from pathlib import Path
2023-03-04 13:53:05 +08:00
from time import sleep
2023-02-21 17:50:53 +08:00
class Manager:
def __init__(self):
self.video_list: list[Video] = []
2023-02-21 19:56:22 +08:00
self.bvid_set = set()
2023-03-04 13:53:05 +08:00
self.queue = SimpleQueue()
2023-03-04 18:18:39 +08:00
self.path = ""
2023-03-04 13:53:05 +08:00
def get_info_worker(self):
while not self.queue.empty():
video: Video = self.queue.get()
video.get_info()
2023-03-04 18:18:39 +08:00
sleep(1)
2023-02-21 17:50:53 +08:00
2023-02-21 19:56:22 +08:00
def add_videos_by_number(self, video_numbers: list[str]):
for video_number in video_numbers:
2023-02-21 17:50:53 +08:00
try:
video = Video(video_number)
except:
continue
2023-02-21 19:56:22 +08:00
if (bvid := video.v.get_bvid()) not in self.bvid_set:
self.bvid_set.add(bvid)
self.video_list.append(video)
2023-03-04 13:53:05 +08:00
self.queue.put(video)
Thread(target=self.get_info_worker).start()
def download_worker(self, parent_dir: Path):
while not self.queue.empty():
video: Video = self.queue.get()
filename = sanitize(video.title) + ".m4a"
2023-03-04 18:18:39 +08:00
while True:
try:
video.download(parent_dir / filename)
break
except:
sleep(1)
sleep(1)
2023-02-21 17:50:53 +08:00
2023-03-04 18:18:39 +08:00
def download(self):
parent_dir = Path(self.path)
2023-03-04 13:53:05 +08:00
for video in self.video_list:
self.queue.put(video)
Thread(target=self.download_worker, args=(parent_dir,)).start()
2023-02-21 17:50:53 +08:00
def get_progress(self):
return [
{
"number": v.number,
"title": v.title,
"received": v.received_bytes,
"total": v.length,
}
for v in self.video_list
]