Skip to content

Commit

Permalink
feat:standardize the user data helper to kork for both cli and gui
Browse files Browse the repository at this point in the history
  • Loading branch information
Benex254 committed Jul 7, 2024
1 parent 2aa02d6 commit f08062e
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 52 deletions.
1 change: 1 addition & 0 deletions fastanime/Utility/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"1P": "one piece",
"Magia Record: Mahou Shoujo Madoka☆Magica Gaiden (TV)": "Mahou Shoujo Madoka☆Magica",
"Dungeon ni Deai o Motomeru no wa Machigatte Iru Darouka": "Dungeon ni Deai wo Motomeru no wa Machigatteiru Darou ka",
'Hazurewaku no "Joutai Ijou Skill" de Saikyou ni Natta Ore ga Subete wo Juurin suru made': "Hazure Waku no [Joutai Ijou Skill] de Saikyou ni Natta Ore ga Subete wo Juurin Suru made",
}


Expand Down
26 changes: 14 additions & 12 deletions fastanime/Utility/downloader/downloader.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import logging
from queue import Queue
from threading import Thread

import yt_dlp

from ... import USER_DOWNLOADS_DIR
from ..show_notification import show_notification
from ..utils import sanitize_filename

logger = logging.getLogger(__name__)


class MyLogger:
def debug(self, msg):
print(msg)
pass

def warning(self, msg):
print(msg)
pass

def error(self, msg):
print(msg)
pass


def main_progress_hook(data):
match data["status"]:
case "error":
show_notification(
"Something went wrong while downloading the video", data["filename"]
)
logger.error("sth went wrong")
case "finished":
show_notification("Downloaded", data["filename"])
logger.info("download complete")


# Options for yt-dlp
Expand All @@ -41,7 +40,7 @@ def _worker(self):
try:
task(*args)
except Exception as e:
show_notification("Something went wrong", f"Reason: {e}")
logger.error(f"Something went wrong {e}")
self.downloads_queue.task_done()

def __init__(self):
Expand All @@ -50,15 +49,18 @@ def __init__(self):
self._thread.start()

# Function to download the file
def _download_file(self, url: str, title, custom_progress_hook, silent):
def _download_file(
self, url: str, download_dir, title, custom_progress_hook, silent
):
anime_title = sanitize_filename(title[0])
ydl_opts = {
"outtmpl": f"{USER_DOWNLOADS_DIR}/{anime_title}/{anime_title}-episode {title[1]}.%(ext)s", # Specify the output path and template
"outtmpl": f"{download_dir}/{anime_title}/{anime_title}-episode {title[1]}.%(ext)s", # Specify the output path and template
"progress_hooks": [
main_progress_hook,
custom_progress_hook,
], # Progress hook
"silent": silent,
"verbose": False,
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
Expand Down
36 changes: 36 additions & 0 deletions fastanime/Utility/user_data_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import json
import logging
import os

from .. import USER_DATA_PATH

logger = logging.getLogger(__name__)


class UserData:
user_data = {"watch_history": {}, "animelist": []}

def __init__(self):
try:
if os.path.isfile(USER_DATA_PATH):
with open(USER_DATA_PATH, "r") as f:
user_data = json.load(f)
self.user_data.update(user_data)
print(user_data, self.user_data)
except Exception as e:
logger.error(e)

def update_watch_history(self, watch_history: dict):
self.user_data["watch_history"] = watch_history
self._update_user_data()

def update_animelist(self, anime_list: list):
self.user_data["animelist"] = list(set(anime_list))
self._update_user_data()

def _update_user_data(self):
with open(USER_DATA_PATH, "w") as f:
json.dump(self.user_data, f)


user_data_helper = UserData()
10 changes: 7 additions & 3 deletions fastanime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

install(show_locals=True)
# Create a logger instance
logger = logging.getLogger(__name__)


# initiate constants
__version__ = "v0.30.0"
Expand Down Expand Up @@ -36,11 +36,12 @@

USER_DATA_PATH = os.path.join(APP_DATA_DIR, "user_data.json")
USER_CONFIG_PATH = os.path.join(APP_DATA_DIR, "config.ini")
USER_WATCH_HISTORY = os.path.join(APP_DATA_DIR, "watch_history.json")


# video dir
USER_DOWNLOADS_DIR = dirs.user_downloads_dir
USER_DOWNLOADS_DIR = dirs.user_videos_dir

print(f"USER_DOWNLOADS_DIR: {USER_DOWNLOADS_DIR}")


def FastAnime(gui=False):
Expand All @@ -52,15 +53,18 @@ def FastAnime(gui=False):
if "--gui" in sys.argv:
gui = True
sys.argv.remove("--gui")
if "--log" in sys.argv:
# Configure logging
from rich.logging import RichHandler

logging.getLogger(__name__)
logging.basicConfig(
level=logging.DEBUG, # Set the logging level to DEBUG
format="%(message)s", # Use a simple message format
datefmt="[%X]", # Use a custom date format
handlers=[RichHandler()], # Use RichHandler to format the logs
)
sys.argv.remove("--log")
if gui:
from .gui import run_gui

Expand Down
66 changes: 64 additions & 2 deletions fastanime/cli/commands/download.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,68 @@
import click

from ...libs.anime_provider.allanime.api import anime_provider
from ...Utility.downloader.downloader import downloader
from ..config import Config
from ..utils.utils import clear, fuzzy_inquirer


@click.command()
def download():
print("download")
@click.option("--anime-title", prompt="Enter the anime title", required=True)
@click.option("--episode-start", prompt="Enter the episode start", required=True)
@click.option("--episode-end", prompt="Enter the episode end", required=True)
@click.pass_obj
def download(config: Config, anime_title, episode_start, episode_end):
translation_type = config.translation_type
download_dir = config.downloads_dir
quality = config.quality
search_results = anime_provider.search_for_anime(
anime_title, translation_type=translation_type
)

episodes_to_download = range(int(episode_start), int(episode_end) + 1)
options = {show["name"]: show for show in search_results["shows"]["edges"]}
anime = fuzzy_inquirer("Please select the anime:", options.keys())

anime_data = options[anime]
availableEpisodesDetail = anime_data["availableEpisodes"]

episodes = availableEpisodesDetail[translation_type]

server = config.server
for episode_number in episodes_to_download:
if episode_number not in range(episodes):
print(f"Episode {episode_number} not available")
continue
print(f"Downloading episode {episode_number} of {anime_data['name']}")
episode = anime_provider.get_anime_episode(
anime_data["_id"], str(episode_number), translation_type
)

# get streams for episode from provider
episode_streams = anime_provider.get_episode_streams(episode)
episode_streams = {
episode_stream[0]: episode_stream[1] for episode_stream in episode_streams
}

# prompt for preferred server
if not server or server not in episode_streams.keys():
server = fuzzy_inquirer("Please select server:", episode_streams.keys())
print(episode)
print(episode_streams)
selected_server = episode_streams[server]

links = selected_server["links"]
if quality > len(links) - 1:
quality = config.quality = len(links) - 1
elif quality < 0:
quality = config.quality = 0
stream_link = links[quality]["link"]

downloader._download_file(
stream_link,
download_dir,
(anime_data["name"], str(episode_number)),
lambda *_: "",
silent=True,
)
clear()
26 changes: 13 additions & 13 deletions fastanime/cli/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
import os
from configparser import ConfigParser

from .. import USER_CONFIG_PATH, USER_DOWNLOADS_DIR, USER_WATCH_HISTORY
from .. import USER_CONFIG_PATH, USER_DOWNLOADS_DIR
from ..Utility import user_data_helper


class Config(object):
Expand Down Expand Up @@ -37,17 +37,17 @@ def __init__(self) -> None:
self.server = self.get_server()
self.preferred_language = self.get_preferred_language()

# ---- setup history ------
if not os.path.exists(USER_WATCH_HISTORY):
self.watch_history = {}
else:
with open(USER_WATCH_HISTORY, "r") as history:
self.watch_history = json.load(history)

def update_watch_history(self, title, episode):
with open(USER_WATCH_HISTORY, "w") as history:
self.watch_history[title] = episode
json.dump(self.watch_history, history)
# ---- setup user data ------
self.watch_history = user_data_helper.user_data.get("watch_history", {})
self.anime_list = user_data_helper.user_data.get("animelist", [])

def update_watch_history(self, anime_id: int, episode: str | None):
self.watch_history.update({str(anime_id): episode})
user_data_helper.update_watch_history(self.watch_history)

def update_anime_list(self, anime_id: int):
self.anime_list.append(anime_id)
user_data_helper.update_animelist(self.anime_list)

def get_downloads_dir(self):
return self.configparser.get("general", "downloads_dir")
Expand Down
Loading

0 comments on commit f08062e

Please sign in to comment.