chore: preliminary cleanup

This commit is contained in:
Benex254
2024-08-05 09:47:06 +03:00
parent 8d7fc81781
commit b738998b05
13 changed files with 23 additions and 284 deletions

View File

@@ -3,35 +3,33 @@ default_language_version:
repos:
- repo: https://github.com/pycqa/isort
rev: 5.12.0 # You can replace this with the latest version
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
args: ["--profile", "black"] # Ensure compatibility with Black
args: ["--profile", "black"] # Ensure compatibility with Black
- repo: https://github.com/PyCQA/autoflake
rev: v2.2.1
hooks:
- id: autoflake
args: ["--in-place","--remove-unused-variables", "--remove-all-unused-imports"]
args:
[
"--in-place",
"--remove-unused-variables",
"--remove-all-unused-imports",
]
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.4.10
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
args: [--fix]
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.4.2
hooks:
- id: black
name: black
language_version: python3.10
# ------ TODO: re-add this -----
# - repo: https://github.com/PyCQA/bandit
# rev: 1.7.9 # Update me!
# hooks:
# - id: bandit
# args: ["-c", "pyproject.toml"]
# additional_dependencies: ["bandit[toml]"]
language_version: python3.10 # to ensure compatibilty

View File

@@ -2,6 +2,7 @@
Just contains some useful data used across the codebase
"""
# useful incases where the anilist title is too different from the provider title
anime_normalizer = {
"1P": "one piece",
"Magia Record: Mahou Shoujo Madoka☆Magica Gaiden (TV)": "Mahou Shoujo Madoka☆Magica",
@@ -11,153 +12,3 @@ anime_normalizer = {
anilist_sort_normalizer = {"search match": "SEARCH_MATCH"}
themes_available = [
"Aliceblue",
"Antiquewhite",
"Aqua",
"Aquamarine",
"Azure",
"Beige",
"Bisque",
"Black",
"Blanchedalmond",
"Blue",
"Blueviolet",
"Brown",
"Burlywood",
"Cadetblue",
"Chartreuse",
"Chocolate",
"Coral",
"Cornflowerblue",
"Cornsilk",
"Crimson",
"Cyan",
"Darkblue",
"Darkcyan",
"Darkgoldenrod",
"Darkgray",
"Darkgrey",
"Darkgreen",
"Darkkhaki",
"Darkmagenta",
"Darkolivegreen",
"Darkorange",
"Darkorchid",
"Darkred",
"Darksalmon",
"Darkseagreen",
"Darkslateblue",
"Darkslategray",
"Darkslategrey",
"Darkturquoise",
"Darkviolet",
"Deeppink",
"Deepskyblue",
"Dimgray",
"Dimgrey",
"Dodgerblue",
"Firebrick",
"Floralwhite",
"Forestgreen",
"Fuchsia",
"Gainsboro",
"Ghostwhite",
"Gold",
"Goldenrod",
"Gray",
"Grey",
"Green",
"Greenyellow",
"Honeydew",
"Hotpink",
"Indianred",
"Indigo",
"Ivory",
"Khaki",
"Lavender",
"Lavenderblush",
"Lawngreen",
"Lemonchiffon",
"Lightblue",
"Lightcoral",
"Lightcyan",
"Lightgoldenrodyellow",
"Lightgreen",
"Lightgray",
"Lightgrey",
"Lightpink",
"Lightsalmon",
"Lightseagreen",
"Lightskyblue",
"Lightslategray",
"Lightslategrey",
"Lightsteelblue",
"Lightyellow",
"Lime",
"Limegreen",
"Linen",
"Magenta",
"Maroon",
"Mediumaquamarine",
"Mediumblue",
"Mediumorchid",
"Mediumpurple",
"Mediumseagreen",
"Mediumslateblue",
"Mediumspringgreen",
"Mediumturquoise",
"Mediumvioletred",
"Midnightblue",
"Mintcream",
"Mistyrose",
"Moccasin",
"Navajowhite",
"Navy",
"Oldlace",
"Olive",
"Olivedrab",
"Orange",
"Orangered",
"Orchid",
"Palegoldenrod",
"Palegreen",
"Paleturquoise",
"Palevioletred",
"Papayawhip",
"Peachpuff",
"Peru",
"Pink",
"Plum",
"Powderblue",
"Purple",
"Red",
"Rosybrown",
"Royalblue",
"Saddlebrown",
"Salmon",
"Sandybrown",
"Seagreen",
"Seashell",
"Sienna",
"Silver",
"Skyblue",
"Slateblue",
"Slategray",
"Slategrey",
"Snow",
"Springgreen",
"Steelblue",
"Tan",
"Teal",
"Thistle",
"Tomato",
"Turquoise",
"Violet",
"Wheat",
"White",
"Whitesmoke",
"Yellow",
"Yellowgreen",
]

View File

@@ -9,28 +9,6 @@ from ..utils import sanitize_filename
logger = logging.getLogger(__name__)
class MyLogger:
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self, msg):
pass
def main_progress_hook(data):
match data["status"]:
case "error":
logger.error("sth went wrong")
case "finished":
logger.info("download complete")
# Options for yt-dlp
class YtDLPDownloader:
downloads_queue = Queue()
@@ -49,15 +27,13 @@ class YtDLPDownloader:
self._thread.start()
# Function to download the file
# TODO: untpack the title to its actual values episode_title and anime_title
def _download_file(self, url: str, download_dir, title, silent, vid_format="best"):
anime_title = sanitize_filename(title[0])
episode_title = sanitize_filename(title[1])
ydl_opts = {
# Specify the output path and template
"outtmpl": f"{download_dir}/{anime_title}/{episode_title}.%(ext)s",
"progress_hooks": [
main_progress_hook,
], # Progress hook
"silent": silent,
"verbose": False,
"format": vid_format,

View File

@@ -7,6 +7,7 @@ from ..constants import USER_DATA_PATH
logger = logging.getLogger(__name__)
# TODO: merger this functionality with the config object
class UserData:
user_data = {"watch_history": {}, "animelist": [], "user": {}}

View File

@@ -1,8 +1,6 @@
import logging
import os
import re
import shutil
from datetime import datetime
from functools import lru_cache
from thefuzz import fuzz
@@ -12,8 +10,6 @@ from fastanime.libs.anilist.anilist_data_schema import AnilistBaseMediaDataSchem
from .data import anime_normalizer
logger = logging.getLogger(__name__)
# TODO: make it use color_text instead of fixed vals
# from .kivy_markup_helper import color_text
@lru_cache()
@@ -22,36 +18,6 @@ def remove_html_tags(text: str):
return re.sub(clean, "", text)
# utility functions
def write_crash(e: Exception):
index = datetime.today()
error = f"[b][color=#fa0000][ {index} ]:[/color][/b]\n(\n\n{e}\n\n)\n"
try:
with open("crashdump.txt", "a") as file:
file.write(error)
except Exception:
with open("crashdump.txt", "w") as file:
file.write(error)
return index
def read_crash_file():
crash_file_path = "./crashfile.txt"
if not os.path.exists(crash_file_path):
return None
else:
with open(crash_file_path, "r") as file:
return file.read()
def move_file(source_path, dest_path):
try:
path = shutil.move(source_path, dest_path)
return (1, path)
except Exception as e:
return (0, e)
@lru_cache()
def sanitize_filename(filename: str):
"""

View File

@@ -5,20 +5,7 @@ if sys.version_info < (3, 10):
"You are using an unsupported version of Python. Only Python versions 3.8 and above are supported by yt-dlp"
) # noqa: F541
import logging
import os
from dotenv import load_dotenv
load_dotenv()
if os.environ.get("FA_RICH_TRACEBACK", False):
from rich.traceback import install
install(show_locals=True)
# initiate constants
__version__ = "v0.50.0"
APP_NAME = "FastAnime"
@@ -28,40 +15,6 @@ REPO = f"{GIT_REPO}/{AUTHOR}/{APP_NAME}"
def FastAnime():
if "--update" in sys.argv:
from .Utility.app_updater import update_app
update_app()
sys.argv.remove("--update")
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 "--log-file" in sys.argv:
# Configure logging
from rich.logging import RichHandler
from .constants import NOTIFIER_LOG_FILE_PATH
logging.getLogger(__name__)
logging.basicConfig(
level=logging.DEBUG, # Set the logging level to DEBUG
# Use a simple message format
format="%(asctime)s%(levelname)s: %(message)s",
datefmt="[%d/%m/%Y@%H:%M:%S]", # Use a custom date format
filename=NOTIFIER_LOG_FILE_PATH,
filemode="a", # Use RichHandler to format the logs
)
sys.argv.remove("--log-file")
from .cli import run_cli
run_cli()

View File

@@ -14,8 +14,6 @@ APP_DIR = os.path.abspath(os.path.dirname(__file__))
CONFIGS_DIR = os.path.join(APP_DIR, "configs")
ASSETS_DIR = os.path.join(APP_DIR, "assets")
# --- notification bell ---
NOTIFICATION_BELL = os.path.join(ASSETS_DIR, "tut_turu.mp3")
# --- icon stuff ---
if PLATFORM == "Windows":

View File

@@ -2,6 +2,8 @@
This module defines the shape of the anilist data that can be received in order to enhance dev experience
"""
# TODO: rename this module to types
from typing import TypedDict
@@ -90,10 +92,6 @@ class AnilistCharacter(TypedDict):
description: str
# class AnilistCharacterNode(TypedDict):
# node
class AnilistVoiceActor(TypedDict):
name: AnilistName
image: AnilistImage

View File

@@ -110,6 +110,7 @@ class AniListApi:
variables = {"id": id}
return self._make_authenticated_request(delete_list_entry_query, variables)
# TODO: unify the _make_authenticated_request with original since sessions are now in use
def _make_authenticated_request(self, query: str, variables: dict = {}):
"""
The core abstraction for getting authenticated data from the anilist api
@@ -121,9 +122,7 @@ class AniListApi:
variables:dict
variables to pass to the anilist api
"""
# req=UrlRequestRequests(url, self.got_data,)
try:
# TODO: check if data is as expected
response = self.session.post(
ANILIST_ENDPOINT,
json={"query": query, "variables": variables},
@@ -184,9 +183,7 @@ class AniListApi:
variables:dict
variables to pass to the anilist api
"""
# req=UrlRequestRequests(url, self.got_data,)
try:
# TODO: check if data is as expected
response = self.session.post(
ANILIST_ENDPOINT,
json={"query": query, "variables": variables},

View File

@@ -3,6 +3,7 @@ This module contains all the preset queries for the sake of neatness and convini
Mostly for internal usage
"""
# TODO: Format the queries
mark_as_read_mutation = """
mutation{
UpdateUser{
@@ -627,10 +628,10 @@ query {
medium
large
}
mediaListEntry{
id
progress
}
mediaListEntry{
id
progress
}
description
episodes
trailer{
@@ -976,5 +977,3 @@ query($id:Int){
}
}
"""
# print(search_query)

View File

@@ -3,6 +3,7 @@ import requests
from .constants import ANIMEPAHE_BASE, ANIMEPAHE_ENDPOINT, REQUEST_HEADERS
# TODO: hack this to completion
class AnimePaheApi:
def search_for_anime(self, user_query, *args):
try:

View File

@@ -19,6 +19,7 @@ episode info = https://hianime.to/ajax/v2/episode/list/27
"""
# TODO: complete this
class AniWatchApi(AnimeProvider):
def search_for_anime(
self, anilist_selected_anime: AnilistBaseMediaDataSchema, *args