aboutsummaryrefslogtreecommitdiff
path: root/src/due/html.py
blob: 27eb13ab2b6425bd7a8c68117c6dea5ce35a054f (plain) (blame)
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import requests
import joblib
from due.cache import cache
from flask import request
import math
import re
import os


def seen(element, manga=False):
    matches = re.findall(r"\d+\]|\[\d+", element)

    if manga:
        matches = re.search(r"\[<a.*?>(\d+)<\/a>\]", element)

        if matches:
            return int(matches.group(1))
        else:
            return 0

    if len(matches) > 1:
        return int(matches[1].strip("[]"))
    elif len(matches) == 1:
        return int(matches[0].strip("[]"))
    else:
        return 0


def anime_to_html(releasing_outdated_anime):
    current_html = []
    ids = []

    for media in releasing_outdated_anime:
        anime = media["media"]
        title = anime["title"]["english"]
        id = anime["id"]

        if id in ids:
            return
        else:
            ids.append(id)

        progress = anime["mediaListEntry"]["progress"]
        available = (
            {"episode": 0}
            if media["media"]["nextAiringEpisode"] is None
            else media["media"]["nextAiringEpisode"]
        )["episode"] - 1

        if available <= 0:
            available = "?"

        if title is None:
            title = anime["title"]["romaji"]

        if request.cookies.get("show_missing") is not None and str(available)[0] == "?":
            ids.pop()

            continue

        current_html.append(
            f'<li><a href="https://anilist.co/anime/{id}" target="_blank">{title}</a> {progress} [{available}]</li>'
        )

    current_html = sorted(current_html, key=seen, reverse=True)

    current_html.insert(0, "<ul>")
    current_html.append("</ul>")

    return ("".join(current_html), len(ids))


def manga_to_html(releasing_outdated_manga, show_missing):
    current_html = []
    ids = []

    def process(media):
        manga = media["media"]
        title = manga["title"]["native"]
        id = manga["id"]

        if id in ids:
            return
        else:
            ids.append(id)

        progress = manga["mediaListEntry"]["progress"]
        available = (
            {"episode": 0}
            if media["media"]["nextAiringEpisode"] is None
            else media["media"]["nextAiringEpisode"]
        )["episode"] - 1

        if available <= 0:
            available = "?"

        mangadex_data = cache.get(str(manga["id"]) + "id")
        mangadex_id = None

        if mangadex_data is None:
            mangadex_data = requests.get(
                "https://api.mangadex.org/manga",
                params={"title": title, "year": manga["startDate"]["year"]},
            ).json()["data"]

            # This is very stupid. It should never get this far, anyway.
            if len(mangadex_data) == 0:
                mangadex_data = requests.get(
                    "https://api.mangadex.org/manga",
                    params={
                        "title": manga["title"]["romaji"],
                        "year": manga["startDate"]["year"],
                    },
                ).json()["data"]

                if len(mangadex_data) == 0:
                    mangadex_data = requests.get(
                        "https://api.mangadex.org/manga",
                        params={
                            "title": manga["title"]["romaji"],
                            "year": manga["startDate"]["year"],
                        },
                    ).json()["data"]

            cache.set(str(manga["id"]) + "id", mangadex_data)

        if len(mangadex_data) == 0:
            available = "?"
        else:
            mangadex_id = mangadex_data[0]["id"]
            manga_chapter_aggregate = cache.get(str(manga["id"]) + "ag")

            if manga_chapter_aggregate is None:
                manga_chapter_aggregate = requests.get(
                    f"https://api.mangadex.org/manga/{mangadex_id}/aggregate",
                ).json()

                cache.set(str(manga["id"]) + "ag", manga_chapter_aggregate)

            if "none" in manga_chapter_aggregate["volumes"]:
                available = list(
                    manga_chapter_aggregate["volumes"]["none"]["chapters"]
                )[0]

                if str(available) == "none":
                    available = list(
                        manga_chapter_aggregate["volumes"]["none"]["chapters"]
                    )[1]
            else:
                try:
                    available = list(
                        manga_chapter_aggregate["volumes"][
                            str(len(list(manga_chapter_aggregate["volumes"])))
                        ]["chapters"]
                    )[0]
                except Exception:
                    available = "?"

                if not str(available)[0].isdigit():
                    if len(manga_chapter_aggregate["volumes"]) == 0:
                        ids.pop()

                        return

                    available = math.floor(
                        float(
                            list(manga_chapter_aggregate["volumes"]["1"]["chapters"])[0]
                        )
                    )

        if show_missing is not None and str(available)[0] == "?":
            ids.pop()

            return

        # Useful when debugging
        # if str(available)[0] != "?":
        #     ids.pop()

        #     return

        if str(available)[0] == "{":
            ids.pop()

            return

        if str(available)[0].isdigit():
            available = math.floor(float(available))

        if int(progress) >= int(available):
            ids.pop()

            return

        available_link = (
            available
            if mangadex_id is None
            else f'<a href="https://mangadex.org/title/{mangadex_id}">{available}</a>'
        )

        current_html.append(
            f'<li><a href="https://anilist.co/manga/{id}" target="_blank">{title}</a> {progress} [{available_link}]</li>'
        )

    joblib.Parallel(n_jobs=int(os.getenv("CONCURRENT_JOBS")) or 4, require="sharedmem")(
        joblib.delayed(process)(media) for media in releasing_outdated_manga
    )

    current_html = sorted(current_html, key=lambda x: seen(x, manga=True), reverse=True)

    current_html.insert(0, "<ul>")
    current_html.append("</ul>")

    return ("".join(current_html), len(ids))


def page(main_content, footer):
    message = '<blockquote>Slow loads? If your media hasn\'t been cached in a while, the first load will take a couple seconds longer than the rest. Subsequent requests on cached media should be faster. <a href="/?hide_message">Hide <i>forever</i></a></blockquote>'

    if request.cookies.get("hide_message") == "1":
        message = ""

    return f"""
<!DOCTYPE html>
<html>
    <head>
        <title>期限</title>

        <link rel="stylesheet" type="text/css" href="https://latex.now.sh/style.css">
        <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/palettes/base16-light.css">
        <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/risotto.css">
        <!-- <link rel="stylesheet" type="text/css" href="https://skybox.sh/css/custom.css"> -->
        <link rel="shortcut icon" type="image/x-icon" href="https://ps.fuwn.me/-tePaWtKW2y/angry-miku-nakano.ico">
    </head>

    <body>
        <style>text-align: center;</style>

        <h1><a href="/">期限</a></h1>

        {main_content}

        <p></p>

        <hr>

        <p>{footer}</p>

        {message}
    </body>
</html>
"""