Skip to content

Commit

Permalink
Merge pull request #147 from Arima57/master
Browse files Browse the repository at this point in the history
Minor Visual Tweaks 0.1 (Loading spinner)
  • Loading branch information
sdaqo authored Dec 26, 2023
2 parents 79c75e3 + 7c5c35e commit acc2537
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 44 deletions.
10 changes: 8 additions & 2 deletions anipy_cli/cli/menus/menu.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sys
import os
from typing import List

from anipy_cli.arg_parser import CliArgs
from anipy_cli.colors import colors, cprint
from anipy_cli.misc import Entry, error
from anipy_cli.misc import Entry, error, clear_console
from anipy_cli.player import PlayerBaseType
from anipy_cli.url_handler import videourl, epHandler
from anipy_cli.query import query
Expand Down Expand Up @@ -37,7 +38,11 @@ def menu_options(self) -> List[MenuOption]:
def print_header(self):
cprint(
colors.GREEN,
f"Playing: {self.entry.show_name} {self.entry.quality} | ",
"Playing: ",
colors.BLUE,
self.entry.show_name,
colors.GREEN,
f" | {self.entry.quality} | ",
colors.RED,
f"{self.entry.ep}/{self.entry.latest_ep}",
)
Expand Down Expand Up @@ -71,6 +76,7 @@ def selec_ep(self):
self.print_options()

def search(self):
clear_console()
query_class = query(input("Search: "), self.entry)
if query_class.get_links() == 0:
error("no search results")
Expand Down
7 changes: 5 additions & 2 deletions anipy_cli/cli/menus/seasonal_menu.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import sys
from typing import List
from yaspin import yaspin
from yaspin.spinners import Spinners


from anipy_cli.arg_parser import CliArgs
from anipy_cli.colors import colors, cprint, cinput
from anipy_cli.misc import Entry, print_names, error
from anipy_cli.misc import Entry, print_names, error, clear_console
from anipy_cli.player import get_player
from anipy_cli.url_handler import videourl, epHandler
from anipy_cli.query import query
Expand Down Expand Up @@ -59,7 +62,7 @@ def add_anime(self):
links = [search["category_url"]]

else:
print("\nCurrent: ", search)
clear_console()
query_class = query(search, show_entry)
query_class.get_pages()
links = query_class.get_links()
Expand Down
15 changes: 11 additions & 4 deletions anipy_cli/cli/util.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from yaspin import yaspin
from yaspin.spinners import Spinners
from anipy_cli.colors import cprint, colors, cinput
from anipy_cli.misc import Entry, search_in_season_on_gogo, print_names
from anipy_cli.url_handler import epHandler, videourl
Expand Down Expand Up @@ -75,11 +77,16 @@ def get_season_searches(gogo=True):
else:
cprint(colors.YELLOW, "Please enter a valid season name.\n")

if gogo:
anime_in_season = search_in_season_on_gogo(season_year, season_name)
with yaspin(
text="Fetching seasonals...", spinner=Spinners.dots, color="cyan"
) as spinner:
if gogo:
anime_in_season = search_in_season_on_gogo(season_year, season_name)

else:
anime_in_season = MAL().get_seasonal_anime(season_year, season_name)
else:
anime_in_season = MAL().get_seasonal_anime(season_year, season_name)

spinner.ok("✔")

cprint("Anime found in {} {} Season: ".format(season_year, season_name))
cprint(
Expand Down
3 changes: 3 additions & 0 deletions anipy_cli/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ class colors:
CYAN = "\u001b[36m"
RED = "\u001b[31m"
END = "\x1b[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
RESET = "\033[0m"


def color(*values, sep: str = "") -> str:
Expand Down
14 changes: 11 additions & 3 deletions anipy_cli/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ class download:
A entry with all fields is required.
"""

def __init__(self, entry, quality, ffmpeg=False, dl_path: Path = None, file_name_format="") -> None:
def __init__(
self, entry, quality, ffmpeg=False, dl_path: Path = None, file_name_format=""
) -> None:
try:
self.quality = int(quality)
except ValueError:
Expand Down Expand Up @@ -426,7 +428,11 @@ def _get_fname(self) -> str:

show_name = self._get_valid_pathname(self.entry.show_name)

file_format = self.file_name_format if self.file_name_format else Config().download_name_format
file_format = (
self.file_name_format
if self.file_name_format
else Config().download_name_format
)

return file_format.format(
show_name=show_name,
Expand All @@ -441,7 +447,9 @@ def _get_valid_pathname(name: str):
if sys.platform == "win32":
name = "".join(["" if x in WIN_INVALID_CHARS else x for x in name])

name = "".join([i for i in name if i.isascii()]) # Verify all chars are ascii (eject if not)
name = "".join(
[i for i in name if i.isascii()]
) # Verify all chars are ascii (eject if not)
name = "-".join(name.split()) # Clean all white spaces, including tabs and such

return name
Expand Down
22 changes: 14 additions & 8 deletions anipy_cli/mal.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,9 @@ def __init__(self, user=None, password=None):
def auto_map_all_without_map(self):
with Pool(processes=None) as pool:
mal_entries = self.local_mal_list_json["data"]
# apply the search function to each search value in parallel
# apply the search function to each search value in parallel
results = pool.map(self.auto_map_gogo_mal, mal_entries, True)


new_mal_entries = list()
for result in results:
if type(result) is dict:
Expand Down Expand Up @@ -562,7 +561,9 @@ def auto_map_gogo_mal(self, mal_entry, mp=False):
if "gogo_map" in mal_entry and len(mal_entry["gogo_map"]) > 0:
return {"failed_to_map": False, "mal_entry": mal_entry}
failed_to_map = True
cprint(colors.GREEN, "Auto mapping: ", colors.BLUE, mal_entry["node"]["title"])
cprint(
colors.GREEN, "Auto mapping: ", colors.BLUE, mal_entry["node"]["title"]
)

search_values = [
mal_entry["node"]["title"],
Expand All @@ -582,7 +583,10 @@ def auto_map_gogo_mal(self, mal_entry, mp=False):
mal_entry["gogo_map"] = []
for i, anime in enumerate(found["search"][1]):
if any(
anime.lower().rstrip("(dub)").rstrip("(japanese dub)").strip(" ")
anime.lower()
.rstrip("(dub)")
.rstrip("(japanese dub)")
.strip(" ")
in show.lower()
for show in [search_values[0], search_values[1]]
):
Expand All @@ -592,13 +596,15 @@ def auto_map_gogo_mal(self, mal_entry, mp=False):
self.update_gogo_map_list(gogo_map, current_map)
failed_to_map = False
if not mp:
self.shows_failed_automap.discard(mal_entry["node"]["title"])
self.shows_failed_automap.discard(
mal_entry["node"]["title"]
)
self.update_anime_list(
mal_entry["node"]["id"],
{
"num_watched_episodes": mal_entry["node"]["my_list_status"][
"num_episodes_watched"
],
"num_watched_episodes": mal_entry["node"][
"my_list_status"
]["num_episodes_watched"],
"tags": "anipy-cli",
},
)
Expand Down
14 changes: 5 additions & 9 deletions anipy_cli/player/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,18 @@ def get_player(rpc_client=None, player_override="") -> PlayerBaseType:

if not player_override:
player = cfg.player_path

player = Path(player)

if player.name == "mpv" and cfg.reuse_mpv_window:
from anipy_cli.player.players.mpv_contrl import MpvControllable

return MpvControllable(rpc_client=rpc_client)

player_dict = {
"mpv": Mpv,
"mpvnet": Mpv,
"vlc": Vlc,
"syncplay": Syncplay
}
player_dict = {"mpv": Mpv, "mpvnet": Mpv, "vlc": Vlc, "syncplay": Syncplay}

player_class = player_dict.get(player.name, None)

if player_class:
return player_class(str(player), rpc_client=rpc_client)
else:
Expand Down
18 changes: 13 additions & 5 deletions anipy_cli/query.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import requests
import re
from bs4 import BeautifulSoup
from yaspin import yaspin
from yaspin.spinners import Spinners


from anipy_cli.misc import loc_err, response_err, error, print_names
from anipy_cli.colors import colors, cinput
Expand All @@ -18,11 +21,16 @@ class query:
"""

def __init__(self, search_param, entry) -> None:
self.entry = entry
self.search_url = base_url + f"/search.html?keyword={search_param}"
r = requests.get(self.search_url)
response_err(r, self.search_url)
self.soup = BeautifulSoup(r.content, "html.parser")
with yaspin() as spinner:
spinner.text = f"Searching for {colors.BLUE}{search_param}{colors.END}"
spinner.spinner = Spinners.dots
spinner.color = "cyan"
self.entry = entry
self.search_url = base_url + f"/search.html?keyword={search_param}"
r = requests.get(self.search_url)
response_err(r, self.search_url)
self.soup = BeautifulSoup(r.content, "html.parser")
spinner.ok("✓")

def get_pages(self):
"""Get count of result pages of query"""
Expand Down
5 changes: 2 additions & 3 deletions anipy_cli/seasonal.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,13 @@ def latest_eps(self):
for i, e, n in zip(categ_urls, user_eps, names):
self.entry.category_url = i
ep_class = epHandler(self.entry)

eps_range = ep_class._load_eps_list()
for j in eps_range:
if parsenum(j["ep"]) == e:
eps_range = eps_range[eps_range.index(j) + 1:]
eps_range = eps_range[eps_range.index(j) + 1 :]
break


ep_urls = []
for j in eps_range:
self.entry.ep = parsenum(j["ep"])
Expand Down
44 changes: 36 additions & 8 deletions anipy_cli/url_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
import base64
import functools
import m3u8
from yaspin import yaspin
from yaspin.spinners import Spinners
from pathlib import Path
from urllib.parse import urlparse, parse_qsl, urlencode, urljoin
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter, Retry
from Cryptodome.Cipher import AES

from anipy_cli.misc import response_err, error, loc_err, parsenum, Entry
from anipy_cli.colors import cinput, color, colors
from anipy_cli.misc import response_err, error, loc_err, parsenum, Entry, clear_console
from anipy_cli.colors import cinput, color, colors, cprint
from anipy_cli.config import Config


Expand Down Expand Up @@ -119,15 +121,26 @@ def get_first(self):
else:
return ep_list[0]["ep"]

def _do_prompt(self, prompt="Episode"):
def _do_prompt(self, prompt="Select Episode"):
clear_console()
cprint(
colors.BLUE,
colors.BOLD,
colors.UNDERLINE,
(self.entry.show_name),
colors.END,
colors.RESET,
)
ep_range = f" [{self.get_first()}-{self.get_latest()}]"

specials = self.get_special_list()
if specials:
ep_range += " Special Eps: "
ep_range += ", ".join([x["ep"] for x in specials])

return cinput(prompt, colors.GREEN, ep_range, colors.END, "\n>> ", input_color=colors.CYAN)
return cinput(
prompt, colors.GREEN, ep_range, colors.END, "\n>> ", input_color=colors.CYAN
)

def _validate_ep(self, ep: str):
"""
Expand All @@ -147,8 +160,13 @@ def pick_ep(self):
Cli function to pick an episode from 1 to
the latest available.
"""

self.get_latest()
with yaspin(
text=f"Fetching episode list for {colors.BLUE}{self.entry.show_name}..."
) as spinner:
spinner.color = "cyan"
spinner.spinner = Spinners.dots
self.get_latest()
spinner.hide()

while True:
which_episode = self._do_prompt()
Expand All @@ -171,7 +189,13 @@ def pick_ep_seasonal(self):
the latest available.
"""

self.get_latest()
with yaspin(
text=f"Fetching episode list for {colors.BLUE}{self.entry.show_name}..."
) as spinner:
spinner.color = "cyan"
spinner.spinner = Spinners.dots
self.get_latest()
spinner.hide()

while True:
which_episode = self._do_prompt(
Expand Down Expand Up @@ -298,7 +322,11 @@ def embed_url(self):
soup = BeautifulSoup(r.content, "html.parser")
link = soup.find("a", {"class": "active", "rel": "1"})
loc_err(link, self.entry.ep_url, "embed-url")
self.entry.embed_url = f'https:{link["data-video"]}' if not link["data-video"].startswith("https:") else link["data-video"]
self.entry.embed_url = (
f'https:{link["data-video"]}'
if not link["data-video"].startswith("https:")
else link["data-video"]
)

@functools.lru_cache()
def get_enc_keys(self):
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def read_version():
"moviepy",
"pyyaml",
"python-mpv",
"yaspin"
],
entry_points="[console_scripts]\nanipy-cli=anipy_cli.run_anipy_cli:main",
)

0 comments on commit acc2537

Please sign in to comment.