├── plugins ├── __init__.py ├── utils.py ├── animefire.py └── animesonlinecc.py ├── todo.txt ├── video_player.py ├── requirements.txt ├── loader.py ├── README.md ├── menu.py ├── main.py ├── manga_tupi.py ├── repository.py └── LICENSE /plugins/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /todo.txt: -------------------------------------------------------------------------------- 1 | add watch lists 2 | study pytermgui 3 | study python-mpv 4 | gemini or llama for recommendation system 5 | add manga-tupi 6 | improve model with Cython 7 | 8 | 9 | user <-> TUI (view) <- controler (main) <- model (repository) <-> plugins (scrapers or api) 10 | (MVCP) 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /plugins/utils.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | 4 | def is_firefox_installed_as_snap(): 5 | try: 6 | result = subprocess.run( 7 | ["snap", "list", "firefox"], 8 | stdout=subprocess.PIPE, 9 | stderr=subprocess.PIPE, 10 | text=True 11 | ) 12 | return result.returncode == 0 # Return code 0 means Firefox is installed as a snap 13 | except FileNotFoundError: 14 | return False 15 | -------------------------------------------------------------------------------- /video_player.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | from sys import exit 3 | 4 | 5 | def play_video(url: str, debug=False) -> None: 6 | try: 7 | if not debug: 8 | process = subprocess.run(["mpv", url, "--fullscreen", "--cursor-autohide-fs-only", "--log-file=log.txt"] 9 | , stdout=subprocess.PIPE 10 | , stdin=subprocess.PIPE) 11 | except FileNotFoundError: 12 | # Handle the case where mpv is not installed or not in PATH 13 | raise EnvironmentError("Error: 'mpv' is not installed or not found in the system PATH.") 14 | except Exception as e: 15 | raise e 16 | 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | altgraph==0.17.4 2 | appdirs==1.4.4 3 | attrs==24.2.0 4 | beautifulsoup4==4.12.3 5 | bs4==0.0.2 6 | certifi==2024.8.30 7 | charset-normalizer==3.4.0 8 | cssselect==1.2.0 9 | fake-useragent==1.5.1 10 | h11==0.14.0 11 | idna==3.10 12 | importlib_metadata==8.5.0 13 | lxml==5.3.0 14 | lxml_html_clean==0.3.1 15 | outcome==1.3.0.post0 16 | packaging==24.2 17 | parse==1.20.2 18 | pyee==11.1.1 19 | pyinstaller==6.11.1 20 | pyinstaller-hooks-contrib==2024.10 21 | pyppeteer==2.0.0 22 | pyquery==2.0.1 23 | PySocks==1.7.1 24 | requests==2.32.3 25 | requests-html==0.10.0 26 | selenium==4.26.1 27 | setuptools==75.5.0 28 | sniffio==1.3.1 29 | sortedcontainers==2.4.0 30 | soupsieve==2.6 31 | tqdm==4.67.0 32 | trio==0.27.0 33 | trio-websocket==0.11.1 34 | typing_extensions==4.12.2 35 | urllib3==1.26.20 36 | w3lib==2.2.1 37 | websocket-client==1.8.0 38 | websockets==10.4 39 | wsproto==1.2.0 40 | zipp==3.21.0 41 | fuzzywuzzy==0.18.0 42 | Levenshtein==0.26.1 43 | python-Levenshtein==0.26.1 44 | -------------------------------------------------------------------------------- /loader.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import sys 3 | from abc import ABC, abstractstaticmethod 4 | from os.path import isfile, join, abspath 5 | from os import listdir 6 | 7 | 8 | class PluginInterface(ABC): 9 | @abstractstaticmethod 10 | def search_anime(): 11 | raise NotImplementedError 12 | 13 | @abstractstaticmethod 14 | def search_episodes(): 15 | raise NotImplementedError 16 | 17 | @abstractstaticmethod 18 | def search_player_src(): 19 | raise NotImplementedError 20 | 21 | 22 | def get_resource_path(relative_path): 23 | """Get the path to resources, whether running as script or executable.""" 24 | if hasattr(sys, '_MEIPASS'): 25 | return join(sys._MEIPASS, relative_path) 26 | return join(abspath("."), relative_path) 27 | 28 | def load_plugins(languages: dict, plugins = None) -> None: 29 | path = get_resource_path("plugins/") 30 | system = {"__init__.py", "utils.py"} 31 | plugins = plugins if plugins is not None else [file[:-3] for file in listdir(path) if isfile(join(path, file)) and file not in system] 32 | for plugin in plugins: 33 | plugin = importlib.import_module("plugins." + plugin) 34 | plugin.load(languages) 35 | 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sobre 2 | Estava cansado de anúncios e o ani-cli não tinha conteúdo em portuguẽs brasileiro então fiz essa ferramenta de CLI. 3 | Para ver mangás veja ![manga-tupi](https://github.com/manga-tupi) 4 | 5 | # Youtube Demo 6 | [![Demo](https://img.youtube.com/vi/eug6gKLTD3I/maxresdefault.jpg)](https://youtu.be/eug6gKLTD3I) 7 | 8 | # Requisitos 9 | mpv, firefox, python, venv, git 10 | 11 | ## Dependências no windows 12 | Recomendamos o uso do gerenciador de pacotes para windows [Cholatey](https://chocolatey.org/install). 13 | Para instalar o mpv no windows, execute o comando abaixo no powershell como administrador após instalar chocolatey. 14 | ```powershell 15 | choco install mpvio.install 16 | ``` 17 | 18 | # Release 19 | Basta dar direito de execução a release mais atual e usar. 20 | ```bash 21 | chmod +x ./ani-tupi 22 | ``` 23 | 24 | # Buildar do código-fonte 25 | Clone o repositório e execute os seguintes comandos. 26 | 27 | ## Instalando python, pip e venv (Ubuntu) 28 | ``` 29 | sudo apt install python-is-python3 pip python3.12-venv 30 | ``` 31 | 32 | ## Linux 33 | ```bash 34 | git clone https://github.com/eduardonery1/ani-tupi 35 | cd ani-tupi 36 | python3 -m venv venv 37 | source ./venv/bin/activate 38 | pip3 install -r requirements.txt 39 | ./build.sh 40 | ``` 41 | 42 | ## Windows (Powershell) 43 | ```powershell 44 | git clone https://github.com/eduardonery1/ani-tupi 45 | cd ani-tupi 46 | python -m venv venv 47 | venv/Scripts/activate.ps1 48 | pip install -r requirements.txt 49 | pip install windows-curses 50 | pyinstaller --onefile main.py -n ani-tupi --hidden-import plugins/animefire.py 51 | ``` 52 | Depois, adicione o diretório dist que foi gerado pelo pyinstaller a variável de sistema PATH. Reinicie seu terminal. 53 | 54 | # Usar 55 | Basta usar agora. 56 | ```bash 57 | ani-tupi 58 | ``` 59 | -------------------------------------------------------------------------------- /menu.py: -------------------------------------------------------------------------------- 1 | import curses 2 | from sys import exit 3 | 4 | 5 | def __menu(stdscr, menu, msg, result) -> str: 6 | menu.append("Sair") 7 | stdscr.clear() 8 | curses.curs_set(0) 9 | 10 | screen_height, screen_width = stdscr.getmaxyx() 11 | display_height = screen_height - 2 # Leave space for padding at the top and bottom 12 | 13 | curses.start_color() 14 | 15 | curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_YELLOW) # Black text on yellow background 16 | curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) 17 | 18 | current_option = 0 19 | start_index = 0 # Index of the first displayed option 20 | 21 | while True: 22 | stdscr.clear() 23 | 24 | stdscr.attron(curses.color_pair(2)) 25 | stdscr.addstr(1, screen_width//5 - len(msg)//2, msg.upper()) 26 | stdscr.attroff(curses.color_pair(2)) 27 | 28 | end_index = start_index + display_height 29 | visible_options = menu[start_index:min(len(menu), end_index)] 30 | # Display menu 31 | for idx, row in enumerate(visible_options): 32 | if start_index + idx == current_option: 33 | stdscr.attron(curses.color_pair(1)) # Highlight current option 34 | stdscr.addstr(idx + 2, 2, row) 35 | stdscr.attroff(curses.color_pair(1)) 36 | else: 37 | stdscr.addstr(idx + 2, 2, row) 38 | key = stdscr.getch() 39 | 40 | # Arrow key navigation 41 | if key == curses.KEY_UP: 42 | current_option = (current_option - 1) % len(menu) 43 | if current_option < start_index: 44 | start_index = current_option 45 | elif current_option == len(menu) - 1 and display_height < len(menu): 46 | start_index = current_option - display_height + 1 47 | 48 | elif key == curses.KEY_DOWN: 49 | current_option = (current_option + 1) % len(menu) 50 | if current_option >= end_index or current_option == 0: 51 | start_index = current_option 52 | elif key == curses.KEY_ENTER or key in [10, 13]: 53 | result.append(menu[current_option]) 54 | break 55 | 56 | def menu(opts: list[str], msg="") -> str: 57 | selected = [] 58 | curses.wrapper(lambda stdscr: __menu(stdscr, opts, msg, result=selected)) 59 | if selected[0] == "Sair": 60 | exit() 61 | opts.pop() 62 | return selected[0] 63 | 64 | if __name__ == "__main__": 65 | main() 66 | 67 | -------------------------------------------------------------------------------- /plugins/animefire.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import subprocess 3 | from bs4 import BeautifulSoup 4 | from repository import rep 5 | from loader import PluginInterface 6 | from selenium import webdriver 7 | from selenium.webdriver.common.by import By 8 | from selenium.webdriver.support.wait import WebDriverWait 9 | from selenium.webdriver.support import expected_conditions as EC 10 | from .utils import is_firefox_installed_as_snap 11 | 12 | 13 | class AnimeFire(PluginInterface): 14 | languages = ["pt-br"] 15 | name = "animefire" 16 | 17 | @staticmethod 18 | def search_anime(query): 19 | url = "https://animefire.plus/pesquisar/" + "-".join(query.split()) 20 | html_content = requests.get(url) 21 | soup = BeautifulSoup(html_content.text, 'html.parser') 22 | target_class = 'col-6 col-sm-4 col-md-3 col-lg-2 mb-1 minWDanime divCardUltimosEps' 23 | titles_urls = [div.article.a["href"] for div in soup.find_all('div', class_=target_class) if 'title' in div.attrs] 24 | titles = [h3.get_text() for h3 in soup.find_all("h3", class_="animeTitle")] 25 | for title, url in zip(titles, titles_urls): 26 | rep.add_anime(title, url, AnimeFire.name) 27 | 28 | @staticmethod 29 | def search_episodes(anime, url, params): 30 | html_episodes_page = requests.get(url) 31 | soup = BeautifulSoup(html_episodes_page.text, "html.parser") 32 | episode_links = [a["href"] for a in soup.find_all('a', class_="lEp epT divNumEp smallbox px-2 mx-1 text-left d-flex")] 33 | opts = [a.get_text() for a in soup.find_all('a', class_="lEp epT divNumEp smallbox px-2 mx-1 text-left d-flex")] 34 | rep.add_episode_list(anime, opts, episode_links, AnimeFire.name) 35 | 36 | @staticmethod 37 | def search_player_src(url_episode, container, event): 38 | options = webdriver.FirefoxOptions() 39 | options.add_argument("--headless") 40 | 41 | try: 42 | if is_firefox_installed_as_snap(): 43 | service = webdriver.FirefoxService(executable_path="/snap/bin/geckodriver") 44 | driver = webdriver.Firefox(options=options, service = service) 45 | else: 46 | driver = webdriver.Firefox(options=options) 47 | except: 48 | raise Exception("Firefox not installed.") 49 | 50 | driver.get(url_episode) 51 | try: 52 | params = (By.ID, "my-video_html5_api") 53 | element = WebDriverWait(driver, 7).until( 54 | EC.visibility_of_all_elements_located(params) 55 | ) 56 | except: 57 | try: 58 | xpath = "/html/body/div[2]/div[2]/div/div[1]/div[1]/div/div/div[2]/div[4]/iframe" 59 | params = (By.XPATH, xpath) 60 | element = WebDriverWait(driver, 7).until( 61 | EC.visibility_of_all_elements_located(params) 62 | ) 63 | except: 64 | driver.quit() 65 | raise Exception("nor iframe nor video tags were found in animefire.") 66 | 67 | product = driver.find_element(params[0], params[1]) 68 | link = product.get_property("src") 69 | driver.quit() 70 | 71 | if not event.is_set(): 72 | container.append(link) 73 | event.set() 74 | 75 | 76 | def load(languages_dict): 77 | can_load = False 78 | for language in AnimeFire.languages: 79 | if language in languages_dict: 80 | can_load = True 81 | break 82 | if not can_load: 83 | return 84 | rep.register(AnimeFire) 85 | 86 | 87 | -------------------------------------------------------------------------------- /plugins/animesonlinecc.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import subprocess 3 | from bs4 import BeautifulSoup 4 | from repository import rep 5 | from loader import PluginInterface 6 | from selenium import webdriver 7 | from selenium.webdriver.common.by import By 8 | from selenium.webdriver.support.wait import WebDriverWait 9 | from selenium.webdriver.support import expected_conditions as EC 10 | from multiprocessing.pool import ThreadPool 11 | from os import cpu_count 12 | from .utils import is_firefox_installed_as_snap 13 | 14 | 15 | class AnimesOnlineCC(PluginInterface): 16 | languages = ["pt-br"] 17 | name = "animesonlinecc" 18 | 19 | @staticmethod 20 | def search_anime(query): 21 | url = "https://animesonlinecc.to/search/" + "+".join(query.split()) 22 | html_content = requests.get(url) 23 | soup = BeautifulSoup(html_content.text, 'html.parser') 24 | divs = soup.find_all('div', class_='data') 25 | titles_urls = [div.h3.a["href"] for div in divs] 26 | titles = [div.h3.a.get_text() for div in divs] 27 | for title, url in zip(titles, titles_urls): 28 | rep.add_anime(title, url, AnimesOnlineCC.name) 29 | 30 | def parse_seasons(title, url): 31 | html = requests.get(url) 32 | soup = BeautifulSoup(html.text, 'html.parser') 33 | num_seasons = len([div for div in soup.find_all('div', class_='se-c')]) 34 | if num_seasons > 1: 35 | for n in range(2, num_seasons + 1): 36 | rep.add_anime(title + " Season " + str(n), url, AnimesOnlineCC.name, n) 37 | 38 | with ThreadPool(cpu_count()) as pool: 39 | for title, url in zip(titles, titles_urls): 40 | pool.apply(parse_seasons, args=(title, url)) 41 | 42 | @staticmethod 43 | def search_episodes(anime, url, season): 44 | html_episodes_page = requests.get(url) 45 | soup = BeautifulSoup(html_episodes_page.text, "html.parser") 46 | seasons = [ season for season in soup.find_all('ul', class_="episodios") ] 47 | season = seasons[ season - 1 if season is not None else 0] 48 | urls, titles = [], [] 49 | for div in season.find_all('div', class_="episodiotitle"): 50 | urls.append(div.a["href"]) 51 | titles.append(div.a.get_text()) 52 | rep.add_episode_list(anime, titles, urls, AnimesOnlineCC.name) 53 | 54 | @staticmethod 55 | def search_player_src(url_episode, container, event): 56 | options = webdriver.FirefoxOptions() 57 | options.add_argument("--headless") 58 | 59 | try: 60 | if is_firefox_installed_as_snap(): 61 | service = webdriver.FirefoxService(executable_path="/snap/bin/geckodriver") 62 | driver = webdriver.Firefox(options=options, service = service) 63 | else: 64 | driver = webdriver.Firefox(options=options) 65 | except: 66 | raise Exception("Firefox not installed.") 67 | 68 | driver.get(url_episode) 69 | 70 | try: 71 | class_ = "/html/body/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/iframe" 72 | params = (By.XPATH, class_) 73 | element = WebDriverWait(driver, 7).until( 74 | EC.visibility_of_all_elements_located(params) 75 | ) 76 | except: 77 | driver.quit() 78 | raise Exception("nor iframe nor video tags were found in animesonlinecc.") 79 | 80 | product = driver.find_element(params[0], params[1]) 81 | link = product.get_property("src") 82 | driver.quit() 83 | 84 | if not event.is_set(): 85 | container.append(link) 86 | event.set() 87 | 88 | 89 | def load(languages_dict): 90 | can_load = False 91 | for language in AnimesOnlineCC.languages: 92 | if language in languages_dict: 93 | can_load = True 94 | break 95 | if not can_load: 96 | return 97 | rep.register(AnimesOnlineCC) 98 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import loader 2 | import argparse 3 | from menu import menu 4 | from repository import rep 5 | from loader import PluginInterface 6 | from sys import exit 7 | from video_player import play_video 8 | from json import load, dump 9 | from manga_tupi import main as manga_tupi 10 | from os import name 11 | from pathlib import Path 12 | 13 | 14 | HISTORY_PATH = Path.home().as_posix() + "/.local/state/ani-tupi/" if name != 'nt' else "C:\\Program Files\\ani-tupi\\" 15 | 16 | def main(args): 17 | loader.load_plugins({"pt-br"}, None if not args.debug else ["animesonlinecc"]) 18 | 19 | if not args.continue_watching: 20 | query = (input("Pesquise anime: ") if not args.query else args.query) if not args.debug else "eva" 21 | rep.search_anime(query) 22 | titles = rep.get_anime_titles() 23 | selected_anime = menu(titles, msg="Escolha o Anime.") 24 | 25 | rep.search_episodes(selected_anime) 26 | episode_list = rep.get_episode_list(selected_anime) 27 | selected_episode = menu(episode_list, msg="Escolha o episódio.") 28 | 29 | episode_idx = episode_list.index(selected_episode) 30 | else: 31 | selected_anime, episode_idx = load_history() 32 | 33 | num_episodes = len(rep.anime_episodes_urls[selected_anime][0][0]) 34 | while True: 35 | episode = episode_idx + 1 36 | player_url = rep.search_player(selected_anime, episode) 37 | if args.debug: print(player_url) 38 | play_video(player_url, args.debug) 39 | save_history(selected_anime, episode_idx) 40 | 41 | opts = [] 42 | if episode_idx < num_episodes - 1: 43 | opts.append("Próximo") 44 | if episode_idx > 0: 45 | opts.append("Anterior") 46 | 47 | selected_opt = menu(opts, msg="O que quer fazer agora?") 48 | 49 | if selected_opt == "Próximo": 50 | episode_idx += 1 51 | elif selected_opt == "Anterior": 52 | episode_idx -= 1 53 | 54 | def load_history(): 55 | file_path = HISTORY_PATH + "history.json" 56 | try: 57 | with open(file_path, "r") as f: 58 | data = load(f) 59 | titles = dict() 60 | for entry, info in data.items(): 61 | ep_info = f" (Ultimo episódio assistido {info[1] + 1})" 62 | titles[entry + ep_info] = len(ep_info) 63 | selected = menu(list(titles.keys()), msg="Continue assistindo.") 64 | anime = selected[:-titles[selected]] 65 | episode_idx = data[anime][1] 66 | rep.anime_episodes_urls[anime] = data[anime][0] 67 | return anime, episode_idx 68 | except FileNotFoundError: 69 | print("Sem histórico de animes") 70 | exit() 71 | except PermissionError: 72 | print("Sem permissão para ler arquivos.") 73 | return 74 | 75 | def save_history(anime, episode): 76 | file_path = HISTORY_PATH + "history.json" 77 | try: 78 | with open(file_path, "r+") as f: 79 | data = load(f) 80 | data[anime] = [rep.anime_episodes_urls[anime], 81 | episode] 82 | with open(file_path , "w") as f: 83 | dump(data, f) 84 | 85 | except FileNotFoundError: 86 | Path(file_path).mkdir(parents=True, exist_ok=True) 87 | 88 | with open(file_path, "w") as f: 89 | data = dict() 90 | data[anime] = [rep.anime_episodes_urls[anime], 91 | episode] 92 | dump(data, f) 93 | 94 | except PermissionError: 95 | print("Não há permissão para criar arquivos.") 96 | return 97 | 98 | if __name__=="__main__": 99 | parser = argparse.ArgumentParser( 100 | prog = "ani-tupi", 101 | description="Veja anime sem sair do terminal.", 102 | ) 103 | parser.add_argument("--query", "-q",) 104 | parser.add_argument("--debug", "-d", action="store_true") 105 | parser.add_argument("--continue_watching", "-c", action="store_true") 106 | parser.add_argument("--manga", "-m", action="store_true") 107 | args = parser.parse_args() 108 | 109 | if args.manga: 110 | manga_tupi() 111 | else: 112 | main(args) 113 | 114 | 115 | -------------------------------------------------------------------------------- /manga_tupi.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import threading 3 | import subprocess 4 | import json 5 | import os 6 | from tqdm import tqdm 7 | from sys import exit 8 | from menu import menu 9 | from pathlib import Path 10 | from collections import defaultdict 11 | 12 | 13 | base_url = "https://api.mangadex.org" 14 | 15 | def run(dir_path): 16 | subprocess.run(["feh", dir_path, "-R 1", "--fullscreen", "--scale-down"]) 17 | 18 | def main(): 19 | res = requests.get( 20 | f"{base_url}/manga", 21 | params={"title": input("Pesquise mangá: ")}).json()["data"] 22 | 23 | titles = [] 24 | for manga in res: 25 | if "pt-br" not in manga["attributes"]["altTitles"]: 26 | try: 27 | titles.append(manga["attributes"]["title"]["en"]) 28 | except: 29 | try: 30 | titles.append(manga["attributes"]["title"]["ja"]) 31 | except: 32 | continue 33 | else: 34 | titles.append(manga["attributes"]["altTitles"]["pt-br"]) 35 | 36 | title_ids = [manga["id"] for manga in res] 37 | selected_title = menu(titles) 38 | 39 | offset = 0 40 | get = lambda query: requests.get(f"{base_url}/manga/{title_ids[titles.index(selected_title)]}/feed?{query}").json()["data"] 41 | current, chapters = [], [] 42 | while not current or len(current) == 500: 43 | query = "&".join(["limit=500", 44 | "translatedLanguage[]=pt-br", 45 | "translatedLanguage[]=en", 46 | "order[chapter]=asc", 47 | "includeEmptyPages=0", 48 | "includeFuturePublishAt=0", 49 | f"offset={offset}"]) 50 | current = get(query) 51 | chapters.extend(current) 52 | offset += 500 53 | #with open("chaps.json", "w") as f: 54 | # json.dump(current, f) 55 | chapter_sources = defaultdict(list) 56 | for chap in chapters: 57 | if chap["attributes"]["chapter"] is None: 58 | continue 59 | chapter_sources[chap["attributes"]["chapter"]].append(chap) 60 | chapters_num = [f"{chap:.0f}" if chap == int(chap) else f"{chap:.2f}" for chap in sorted(list(map(float, chapter_sources.keys())))] 61 | 62 | def chapter_selection(selected_chapter = None): 63 | nonlocal chapters_num, chapter_sources 64 | if not selected_chapter: 65 | selected_chapter = menu(chapters_num) 66 | else: 67 | try: 68 | selected_chapter = chapters_num[chapters_num.index(selected_chapter) + 1] 69 | except IndexError: 70 | print("Sem mais capítulos.") 71 | exit() 72 | 73 | def select_language(): 74 | nonlocal selected_chapter 75 | chapter_translates = [chap["attributes"]["translatedLanguage"] + " " + str(i + 1) for i, chap in enumerate(chapter_sources[selected_chapter])] 76 | chapter_ids = [chap["id"] for chap in chapter_sources[selected_chapter]] 77 | selected_opt = menu(chapter_translates) 78 | 79 | pages = requests.get(f"{base_url}/at-home/server/{chapter_ids[chapter_translates.index(selected_opt)]}").json() 80 | home = Path.home().as_posix() if os.name != 'nt' else home.as_uri() 81 | dirs = [home, 'Downloads', selected_title, selected_chapter] 82 | dir_path = Path("/".join(dirs) if os.name != 'nt' else "\\".join(dirs)) 83 | dir_path.mkdir(parents=True, exist_ok=True) 84 | first = True 85 | thread = threading.Thread(target=run, args=(dir_path,)) 86 | 87 | print("Baixando páginas enquanto vc vê o mangá, pode ser que precise esperar um pouco...") 88 | for i in tqdm(range(len(pages["chapter"]["data"]))): 89 | url = pages["baseUrl"] + "/data/" + pages["chapter"]["hash"] + "/" + pages["chapter"]["data"][i] 90 | img_path = Path(str(dir_path) + f"/{i}.png") 91 | if not img_path.is_file(): 92 | img_data = requests.get(url).content 93 | with open(img_path, "wb") as img: 94 | img.write(img_data) 95 | if first: 96 | thread.start() 97 | first = False 98 | if not first: 99 | thread.join() 100 | select_language() 101 | 102 | return selected_chapter 103 | 104 | prev = chapter_selection() 105 | while True: 106 | opt = menu(["Próximo"]) 107 | if opt == "Próximo": 108 | prev = chapter_selection(prev) 109 | else: 110 | break 111 | 112 | 113 | 114 | if __name__=="__main__": 115 | main() 116 | 117 | 118 | -------------------------------------------------------------------------------- /repository.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from os import cpu_count 3 | from loader import PluginInterface 4 | from typing import Callable 5 | from collections import defaultdict 6 | from threading import Thread, Condition 7 | from concurrent.futures import ThreadPoolExecutor 8 | from multiprocessing.pool import ThreadPool 9 | from fuzzywuzzy import fuzz 10 | 11 | 12 | class Repository: 13 | """ SingletonRepository 14 | get for methods called by main that return some value 15 | search for methods called by main that don't return but affects state 16 | add for methods called by any plugin that affects state 17 | register should be called by a loader function 18 | """ 19 | 20 | _instance = None 21 | 22 | def __init__(self) -> None: 23 | self.sources = dict() 24 | self.anime_to_urls = defaultdict(list) 25 | self.anime_episodes_titles = defaultdict(list) 26 | self.anime_episodes_urls = defaultdict(list) 27 | self.norm_titles = dict() 28 | 29 | def __new__(cls): 30 | if not Repository._instance: 31 | Repository._instance = super(Repository, cls).__new__(cls) 32 | return Repository._instance 33 | 34 | def register(self, plugin: PluginInterface) -> None: 35 | self.sources[plugin.name] = plugin 36 | 37 | def search_anime(self, query: str) -> None: 38 | with ThreadPool(min(len(self.sources), cpu_count())) as pool: 39 | for source in self.sources: 40 | pool.apply(self.sources[source].search_anime, args=(query,)) 41 | 42 | def add_anime(self, title: str, url: str, source:str, params=None) -> None: 43 | """ 44 | This method assumes that different seasons are different anime, like MAL, so plugin devs should take scrape that way. 45 | """ 46 | title_ = title.lower() 47 | table = {"clássico": "", 48 | "classico": "", 49 | ":":"", 50 | "part":"season", 51 | "temporada":"season", 52 | "(":"", 53 | ")":"", 54 | " ": ""} 55 | 56 | for key, val in table.items(): 57 | title_ = title_.replace(key, val) 58 | 59 | self.norm_titles[title] = title_ 60 | 61 | threshold = 95 62 | for key in self.anime_to_urls.keys(): 63 | if fuzz.ratio(title_, self.norm_titles[key]) >= threshold: 64 | self.anime_to_urls[key].append((url, source, params)) 65 | return 66 | self.anime_to_urls[title].append((url, source, params)) 67 | 68 | def get_anime_titles(self) -> list[str]: 69 | return sorted(list(self.anime_to_urls.keys())) 70 | 71 | def search_episodes(self, anime: str) -> None: 72 | if anime in self.anime_episodes_titles: 73 | return self.anime_episode_titles[anime] 74 | 75 | urls_and_scrapers = rep.anime_to_urls[anime] 76 | threads = [Thread(target=self.sources[source].search_episodes, args=(anime, url, params, )) for url, source, params in urls_and_scrapers] 77 | 78 | for th in threads: 79 | th.start() 80 | 81 | for th in threads: 82 | th.join() 83 | 84 | def add_episode_list(self, anime: str, title_list: list[str], url_list: list[str], source: str) -> None: 85 | self.anime_episodes_titles[anime].append(title_list) 86 | self.anime_episodes_urls[anime].append((url_list, source)) 87 | 88 | def get_episode_list(self, anime: str): 89 | return sorted(self.anime_episodes_titles[anime], key=lambda title_list: len(title_list))[0] 90 | 91 | def search_player(self, anime: str, episode_num: int) -> None: 92 | """ 93 | This method assumes all episode lists to be the same size, plugin devs should guarantee that OVA's are not considered. 94 | """ 95 | selected_urls = [] 96 | for urls, source in self.anime_episodes_urls[anime]: 97 | if len(urls) >= episode_num: 98 | selected_urls.append((urls[episode_num - 1], source)) 99 | 100 | async def search_all_sources(): 101 | nonlocal selected_urls, self 102 | event = asyncio.Event() 103 | container = [] 104 | loop = asyncio.get_running_loop() 105 | with ThreadPoolExecutor(max_workers=cpu_count()) as executor: 106 | tasks = [loop.run_in_executor(executor, self.sources[source].search_player_src, url, container, event) for url, source in selected_urls] 107 | done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) 108 | 109 | #for task in pending: 110 | # task.cancel() 111 | return container[0] 112 | 113 | return asyncio.run(search_all_sources()) 114 | 115 | rep = Repository() 116 | 117 | if __name__=="__main__": 118 | rep3, rep2 = Repository(), Repository() 119 | print(rep3 is rep2) 120 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------