-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmanga_tupi.py
117 lines (99 loc) · 4.21 KB
/
manga_tupi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import requests
import threading
import subprocess
import json
import os
from tqdm import tqdm
from sys import exit
from menu import menu
from pathlib import Path
from collections import defaultdict
base_url = "https://api.mangadex.org"
def run(dir_path):
subprocess.run(["feh", dir_path, "-R 1", "--fullscreen", "--scale-down"])
def main():
res = requests.get(
f"{base_url}/manga",
params={"title": input("Pesquise mangá: ")}).json()["data"]
titles = []
for manga in res:
if "pt-br" not in manga["attributes"]["altTitles"]:
try:
titles.append(manga["attributes"]["title"]["en"])
except:
try:
titles.append(manga["attributes"]["title"]["ja"])
except:
continue
else:
titles.append(manga["attributes"]["altTitles"]["pt-br"])
title_ids = [manga["id"] for manga in res]
selected_title = menu(titles)
offset = 0
get = lambda query: requests.get(f"{base_url}/manga/{title_ids[titles.index(selected_title)]}/feed?{query}").json()["data"]
current, chapters = [], []
while not current or len(current) == 500:
query = "&".join(["limit=500",
"translatedLanguage[]=pt-br",
"translatedLanguage[]=en",
"order[chapter]=asc",
"includeEmptyPages=0",
"includeFuturePublishAt=0",
f"offset={offset}"])
current = get(query)
chapters.extend(current)
offset += 500
#with open("chaps.json", "w") as f:
# json.dump(current, f)
chapter_sources = defaultdict(list)
for chap in chapters:
if chap["attributes"]["chapter"] is None:
continue
chapter_sources[chap["attributes"]["chapter"]].append(chap)
chapters_num = [f"{chap:.0f}" if chap == int(chap) else f"{chap:.2f}" for chap in sorted(list(map(float, chapter_sources.keys())))]
def chapter_selection(selected_chapter = None):
nonlocal chapters_num, chapter_sources
if not selected_chapter:
selected_chapter = menu(chapters_num)
else:
try:
selected_chapter = chapters_num[chapters_num.index(selected_chapter) + 1]
except IndexError:
print("Sem mais capítulos.")
exit()
def select_language():
nonlocal selected_chapter
chapter_translates = [chap["attributes"]["translatedLanguage"] + " " + str(i + 1) for i, chap in enumerate(chapter_sources[selected_chapter])]
chapter_ids = [chap["id"] for chap in chapter_sources[selected_chapter]]
selected_opt = menu(chapter_translates)
pages = requests.get(f"{base_url}/at-home/server/{chapter_ids[chapter_translates.index(selected_opt)]}").json()
home = Path.home().as_posix() if os.name != 'nt' else home.as_uri()
dirs = [home, 'Downloads', selected_title, selected_chapter]
dir_path = Path("/".join(dirs) if os.name != 'nt' else "\\".join(dirs))
dir_path.mkdir(parents=True, exist_ok=True)
first = True
thread = threading.Thread(target=run, args=(dir_path,))
print("Baixando páginas enquanto vc vê o mangá, pode ser que precise esperar um pouco...")
for i in tqdm(range(len(pages["chapter"]["data"]))):
url = pages["baseUrl"] + "/data/" + pages["chapter"]["hash"] + "/" + pages["chapter"]["data"][i]
img_path = Path(str(dir_path) + f"/{i}.png")
if not img_path.is_file():
img_data = requests.get(url).content
with open(img_path, "wb") as img:
img.write(img_data)
if first:
thread.start()
first = False
if not first:
thread.join()
select_language()
return selected_chapter
prev = chapter_selection()
while True:
opt = menu(["Próximo"])
if opt == "Próximo":
prev = chapter_selection(prev)
else:
break
if __name__=="__main__":
main()