aboutsummaryrefslogtreecommitdiff
path: root/plugins/mangaplus.py
blob: 7106903404d049904bee77fd0ca3ae2030cfb36e (plain)
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3

# The page decryption in this file is based on komikku/servers/mangaplus/__init__.py
# available at https://gitlab.com/valos/Komikku/-/blob/master/komikku/servers/mangaplus/__init__.py
# which is licensed under GPL 3.0

import os
import time
import sys
import re
import requests
import json

RE_ENCRYPTION_KEY = re.compile('.{1,2}')

api_url = 'https://jumpg-webapi.tokyo-cdn.com/api'
api_manga_url = api_url + '/title_detailV3?title_id={0}&format=json'
api_chapter_url = api_url + '/manga_viewer?chapter_id={0}&split=yes&img_quality=high&format=json'

class Chapter:
    id = ""
    title = ""

class MangaPage:
    url = ""
    encryption_key = None

def usage():
    print("mangaplus.py command")
    print("commands:")
    print("  download")
    print("  list")
    exit(1)

def usage_list():
    print("mangaplus.py list <url>")
    print("examples:")
    print("  mangaplus.py list \"https://mangaplus.shueisha.co.jp/titles/100056\"")
    exit(1)

def usage_download():
    print("mangaplus.py download <url> <download_dir>")
    print("examples:")
    print("  mangaplus.py download \"https://mangaplus.shueisha.co.jp/viewer/1006611\" /home/user/Manga/MangaName")
    print("")
    print("Note: The manga directory has to exist.")
    exit(1)

if len(sys.argv) < 2:
    usage()

# Encryption is done with symetric key and the key is provided in the json response....
def download_file(url, encryption_key, save_path):
    if encryption_key is not None:
        # Decryption
        key_stream = [int(v, 16) for v in RE_ENCRYPTION_KEY.findall(encryption_key)]
        block_size_in_bytes = len(key_stream)

        index = 0
        with requests.get(url, stream=True, timeout=30) as response:
            if not response.ok:
                return False
            with open(save_path, "wb") as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        content = bytes([int(v) ^ key_stream[(index + i) % block_size_in_bytes] for i, v in enumerate(chunk)])
                        file.write(content)
                    index += len(chunk)
    else:
        with requests.get(url, stream=True, timeout=30) as response:
            if not response.ok:
                return False
            with open(save_path, "wb") as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        file.write(chunk)
    return True

def title_url_extract_manga_id(url):
    result = re.search("mangaplus.shueisha.co.jp/titles/([0-9]+)", url)
    if result and len(result.groups()) > 0:
        return result.groups()[0]

def parse_chapters(chapters_json):
    result = []

    if not chapters_json:
        return result

    for chapter_json in chapters_json:
        chapter = Chapter()
        chapter.id = chapter_json["chapterId"]
        chapter.title = chapter_json["subTitle"]
        result.append(chapter)

    return result

def list_chapters(url, chapter_list_input):
    manga_id = title_url_extract_manga_id(url)
    if not manga_id:
        print("Failed to extract manga id from url: %s. Note: url is expected to be in this format: mangaplus.shueisha.co.jp/titles/<number>" % url)
        exit(2)

    url = api_manga_url.format(manga_id)

    response = requests.get(url, timeout=30)
    response.raise_for_status()

    resp_json = response.json()

    all_chapters = []
    chapter_list_groups = resp_json["success"]["titleDetailView"]["chapterListGroup"]
    for chapter_list_group in chapter_list_groups:
        first_chapter_list = chapter_list_group.get("firstChapterList")
        mid_chapter_list = chapter_list_group.get("midChapterList")
        last_chapter_list = chapter_list_group.get("lastChapterList")

        all_chapters.extend(parse_chapters(first_chapter_list))
        all_chapters.extend(parse_chapters(mid_chapter_list))
        all_chapters.extend(parse_chapters(last_chapter_list))

    seen_titles = set()
    for item in chapter_list_input:
        title = item.get("title")
        if len(title) > 0:
            seen_titles.add(title.lower().replace(" ", "").replace("/", "_"))

    seen_urls = set()
    for item in chapter_list_input:
        chapter_url = item.get("url")
        if chapter_url and len(chapter_url) > 0:
            seen_urls.add(chapter_url)

    chapters = []
    for chapter in reversed(all_chapters):
        title = chapter.title.replace("/", "_")
        url = "https://mangaplus.shueisha.co.jp/viewer/{0}".format(chapter.id)
        if title.lower().replace(" ", "") in seen_titles or url in seen_urls:
            break
        chapters.append({ "name": title, "url": url })
    print(json.dumps(chapters))

def viewer_url_extract_manga_id(url):
    result = re.search("mangaplus.shueisha.co.jp/viewer/([0-9]+)", url)
    if result and len(result.groups()) > 0:
        return result.groups()[0]

def download_chapter(url, download_dir):
    request_url = url
    manga_id = viewer_url_extract_manga_id(url)
    if not manga_id:
        print("Failed to extract manga id from url: %s. Note: url is expected to be in this format: mangaplus.shueisha.co.jp/viewer/<number>" % url)
        exit(2)
    
    url = api_chapter_url.format(manga_id)

    response = requests.get(url, timeout=30)
    response.raise_for_status()

    resp_json = response.json()

    manga_pages = []
    pages = resp_json["success"]["mangaViewer"]["pages"]
    for page in pages:
        manga_page_json = page.get("mangaPage")
        if manga_page_json:
            manga_page = MangaPage()
            manga_page.url = manga_page_json["imageUrl"]
            manga_page.encryption_key = manga_page_json.get("encryptionKey")
            manga_pages.append(manga_page)

    in_progress_filepath = os.path.join(download_dir, ".in_progress")
    with open(in_progress_filepath, "w") as file:
        file.write(request_url)

    img_number = 1
    for manga_page in manga_pages:
        image_name = manga_page.url.split('?')[0].split('/')[-1]
        ext = image_name[image_name.rfind("."):]
        image_name = str(img_number) + ext
        image_path = os.path.join(download_dir, image_name)
        print("Downloading {} to {}".format(manga_page.url, image_path))
        if not download_file(manga_page.url, manga_page.encryption_key, image_path):
            print("Failed to download image: %s" % manga_page.url)
            os.remove(in_progress_filepath)
            exit(2)
        img_number += 1

    if img_number == 1:
        print("Failed to find images for chapter")
        os.remove(in_progress_filepath)
        exit(2)

    with open(os.path.join(download_dir, ".finished"), "w") as file:
        file.write("1")

    os.remove(in_progress_filepath)

command = sys.argv[1]
if command == "list":
    if len(sys.argv) < 3:
        usage_list()
    
    url = sys.argv[2]
    chapter_list_input = sys.stdin.read()
    if len(chapter_list_input) == 0:
        chapter_list_input = []
    else:
        chapter_list_input = json.loads(chapter_list_input)
    list_chapters(url, chapter_list_input)
elif command == "download":
    if len(sys.argv) < 4:
        usage_download()
    url = sys.argv[2]
    download_dir = sys.argv[3]
    download_chapter(url, download_dir)
else:
    usage()