aboutsummaryrefslogtreecommitdiff
path: root/plugins/mangakatana.py
blob: e7e0604935d63caff5caef66fe448209a3181fd1 (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
#!/usr/bin/env python3

import os
import time
import sys
import requests
import json

from lxml import etree

headers = {
    'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
}

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

def usage_list():
    print("mangakatana.py list <url>")
    exit(1)

def usage_download():
    print("mangakatana.py download <url> <download_dir>")
    print("examples:")
    print("  mangakatana.py download \"http://mangakatana.com/manga/useless-ponko.22679\" /home/user/Manga/MangaName")
    print("")
    print("Note: The manga directory has to exist.")
    exit(1)

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

def download_file(url, save_path):
    file_size = 0
    try:
        with requests.get(url, headers=headers, stream=True, timeout=30) as response:
            if not response.ok:
                return 0
            with open(save_path, "wb") as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        file.write(chunk)
                        file_size += len(chunk)
        return file_size
    except requests.exceptions.ChunkedEncodingError as e:
        print("Warning: error while downloading %s: %s" % (url, str(e)))
        return 0

def list_chapters(url, chapter_list_input):
    response = requests.get(url, headers=headers, timeout=30)
    response.raise_for_status()

    seen_titles = set()
    for item in chapter_list_input:
        title = item.get("title")
        if title and 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)

    tree = etree.HTML(response.text)
    chapters = []
    for element in tree.xpath('//div[@class="chapters"]//div[@class="chapter"]//a[1]'):
        element_text = element.text.strip().replace("/", "_")
        url = element.attrib.get("href").strip()
        if element_text.lower().replace(" ", "") in seen_titles or url in seen_urls:
            break
        chapters.append({ "name": element_text, "url": url })
    
    print(json.dumps(chapters))

def extract_javascript_sections(html_source):
    sections = []
    start = 0

    while True:
        start = html_source.find("<script", start)
        if start == -1:
            return sections

        start += 7
        start = html_source.find(">", start)
        if start == -1:
            return sections

        start += 1
        end = html_source.find("</script>", start)
        if end == -1:
            return sections

        sections.append(html_source[start:end])
        start = end + 9

def get_javascript_string_arrays(js_source):
    arrays = []
    start = 0

    while True:
        start = js_source.find("=['", start)
        if start == -1:
            return arrays

        start += 3
        end = js_source.find("]", start)
        if end == -1:
            return arrays

        arr = js_source[start:end].replace("'", "").split(",")
        arrays.extend(list(filter(None, arr)))
        start = end + 1

def uniq_str_arr(arr):
    res = []
    prev = ""
    for d in arr:
        if d != prev:
            res.append(d)
        prev = d
    return res

def download_chapter(url, download_dir):
    response = requests.get(url, timeout=30)
    response.raise_for_status()

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

    response_text = response.text
    js_sections = extract_javascript_sections(response_text)
    js_string_arrays = []
    for js_section in js_sections:
        js_string_arrays.extend(uniq_str_arr(get_javascript_string_arrays(js_section)))

    image_sources = js_string_arrays

    img_number = 1
    for image_source in image_sources:
        image_source = image_source.strip()
        if not image_source:
            continue
        ext = image_source[image_source.rfind("."):]
        image_name = str(img_number) + ext
        image_path = os.path.join(download_dir, image_name)
        image_source = image_source.replace("://i1", "://i3")
        print("Downloading {} to {}".format(image_source, image_path))
        if not download_file(image_source, image_path):
            if not download_file(image_source, image_path):
                print("Failed to download image: %s" % image_source)
                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()