aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/Mangadex.cpp
blob: 848471fe51de12972422a84676ee35156013d82b (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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#include "../../plugins/Mangadex.hpp"
#include "../../include/Utils.hpp"
#include "../../include/Theme.hpp"
#include <json/writer.h>

namespace QuickMedia {
    PluginResult legacy_mangadex_id_to_new_manga_id(Page *page, const std::vector<int> &manga_ids, std::vector<std::pair<int, std::string>> &new_manga_ids) {
        Json::Value request_json(Json::objectValue);
        request_json["type"] = "manga";
        Json::Value manga_ids_json(Json::arrayValue);
        for(int manga_id : manga_ids) {
            manga_ids_json.append(manga_id);
        }
        request_json["ids"] = std::move(manga_ids_json);

        Json::StreamWriterBuilder json_builder;
        json_builder["commentStyle"] = "None";
        json_builder["indentation"] = "";

        std::vector<CommandArg> additional_args = {
            { "-X", "POST" },
            { "-H", "content-type: application/json" },
            { "--data-binary", Json::writeString(json_builder, request_json) }
        };

        Json::Value json_root;
        if(page->download_json(json_root, "https://api.mangadex.org/legacy/mapping", std::move(additional_args), true) != DownloadResult::OK)
            return PluginResult::NET_ERR;

        if(!json_root.isArray())
            return PluginResult::OK;

        for(const Json::Value &result_item_json : json_root) {
            if(!result_item_json.isObject())
                continue;

            const Json::Value &result_json = result_item_json["result"];
            if(!result_json.isString() || strcmp(result_json.asCString(), "ok") != 0)
                continue;

            const Json::Value &data_json = result_item_json["data"];
            if(!data_json.isObject())
                continue;

            const Json::Value &attributes_json = data_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &legacy_id_json = attributes_json["legacyId"];
            if(!legacy_id_json.isInt())
                continue;

            const Json::Value &new_id_json = attributes_json["newId"];
            if(!new_id_json.isString())
                continue;

            new_manga_ids.push_back(std::make_pair<int, std::string>(legacy_id_json.asInt(), new_id_json.asString()));
        }

        return PluginResult::OK;
    }
    
    static std::string relationships_get_cover_art_filename(const Json::Value &relationships_json) {
        std::string result;
        if(!relationships_json.isArray())
            return result;

        for(const Json::Value &relationship_json : relationships_json) {
            if(!relationship_json.isObject())
                continue;

            const Json::Value &relationship_type_json = relationship_json["type"];
            if(!relationship_type_json.isString() || strcmp(relationship_type_json.asCString(), "cover_art") != 0)
                continue;

            const Json::Value &attributes_json = relationship_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &file_name_json = attributes_json["fileName"];
            if(!file_name_json.isString())
                continue;

            result = file_name_json.asString();
            break;
        }

        return result;
    }

    static void add_tags(const Json::Value &tags_json, BodyItem *body_item) {
        if(!tags_json.isArray())
            return;

        for(const Json::Value &tag_json : tags_json) {
            if(!tag_json.isObject())
                continue;

            const Json::Value &attributes_json = tag_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &name_json = attributes_json["name"];
            if(!name_json.isObject())
                continue;

            const Json::Value &en_name_json = name_json["en"];
            if(!en_name_json.isString())
                continue;

            body_item->add_reaction(en_name_json.asString(), nullptr);
        }
    }

    enum class SearchType {
        TITLE,
        AUTHOR
    };

    static PluginResult search_manga(Page *plugin_page, SearchType search_type, const std::string &query, int page, BodyItems &result_items) {
        std::string url = "https://api.mangadex.org/manga?limit=20&order[relevance]=desc&includes[]=cover_art&offset=" + std::to_string(page * 20);
        const std::string query_encoded = url_param_encode(query);
        switch(search_type) {
            case SearchType::TITLE:
                url += "&title=" + query_encoded;
                break;
            case SearchType::AUTHOR:
                url += "&authors[]=" + query_encoded;
                url += "&artists[]=" + query_encoded;
                break;
        }

        Json::Value json_root;
        if(plugin_page->download_json(json_root, url, {}, true) != DownloadResult::OK)
            return PluginResult::NET_ERR;

        if(!json_root.isObject())
            return PluginResult::OK;

        const Json::Value &result_json = json_root["result"];
        if(!result_json.isString() || strcmp(result_json.asCString(), "ok") != 0)
            return PluginResult::ERR;

        const Json::Value &data_list_json = json_root["data"];
        if(!data_list_json.isArray())
            return PluginResult::ERR;

        for(const Json::Value &data_json : data_list_json) {
            if(!data_json.isObject())
                continue;
            
            const Json::Value &id_json = data_json["id"];
            if(!id_json.isString())
                continue;

            const Json::Value &attributes_json = data_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &title_json = attributes_json["title"];
            if(!title_json.isObject())
                continue;

            std::string title;
            const Json::Value &title_en_json = title_json["en"];
            if(title_en_json.isString())
                title = title_en_json.asString();
            else
                title = "No title"; // TODO: Verify if this happens. If it happens, get the title in any available language

            auto body_item = BodyItem::create(std::move(title));
            body_item->url = id_json.asString();

            std::string description;

            const Json::Value &status_json = attributes_json["status"];
            if(status_json.isString()) {
                if(!description.empty())
                    description += '\n';
                description += "Status: " + status_json.asString();
            }

            const Json::Value &description_json = attributes_json["description"];
            if(description_json.isObject()) {
                const Json::Value &en_json = description_json["en"];
                if(en_json.isString()) {
                    if(!description.empty())
                        description += '\n';
                    description += en_json.asString();
                }
            }

            if(!description.empty()) {
                body_item->set_description(std::move(description));
                body_item->set_description_color(get_theme().faded_text_color);
            }

            add_tags(attributes_json["tags"], body_item.get());

            std::string cover_art_filename = relationships_get_cover_art_filename(data_json["relationships"]);
            if(!cover_art_filename.empty())
                body_item->thumbnail_url = "https://uploads.mangadex.org/covers/" + body_item->url + "/" + std::move(cover_art_filename) + ".256.jpg";
            body_item->thumbnail_size = {101, 141};
            result_items.push_back(std::move(body_item));
        }

        return PluginResult::OK;
    }

    SearchResult MangadexSearchPage::search(const std::string &str, BodyItems &result_items) {
        return plugin_result_to_search_result(search_manga(this, SearchType::TITLE, str, 0, result_items));
    }

    PluginResult MangadexSearchPage::get_page(const std::string &str, int page, BodyItems &result_items) {
        return search_manga(this, SearchType::TITLE, str, page, result_items);
    }

    static PluginResult get_chapters_for_manga(Page *page, const std::string &manga_id, int page_num, BodyItems &result_items, ChapterImageUrls &chapter_image_urls) {
        std::string request_url = "https://api.mangadex.org/manga/" + manga_id + "/feed?order[chapter]=desc&limit=100&translatedLanguage[]=en&offset=" + std::to_string(page_num * 100);

        Json::Value json_root;
        if(page->download_json(json_root, request_url, {}, true) != DownloadResult::OK)
            return PluginResult::NET_ERR;

        if(!json_root.isObject())
            return PluginResult::OK;

        const Json::Value &result_json = json_root["result"];
        if(!result_json.isString() || strcmp(result_json.asCString(), "ok") != 0)
            return PluginResult::ERR;

        const Json::Value &data_list_json = json_root["data"];
        if(!data_list_json.isArray())
            return PluginResult::ERR;

        std::string prev_chapter;
        std::string chapter;
        for(const Json::Value &data_json : data_list_json) {
            if(!data_json.isObject())
                continue;

            const Json::Value &id_json = data_json["id"];
            if(!id_json.isString())
                continue;

            const Json::Value &attributes_json = data_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &translated_language_json = attributes_json["translatedLanguage"];
            if(!translated_language_json.isString() || strcmp(translated_language_json.asCString(), "en") != 0)
                continue;

            const Json::Value &chapter_json = attributes_json["chapter"];
            if(chapter_json.isString())
                chapter = chapter_json.asString();
            else
                chapter = "0";

            if(strcmp(prev_chapter.c_str(), chapter.c_str()) == 0)
                continue;

            const Json::Value &hash_json = attributes_json["hash"];
            if(!hash_json.isString())
                continue;

            std::string title = "Ch. " + chapter;
            prev_chapter = std::move(chapter);
            const Json::Value &title_json = attributes_json["title"];
            if(title_json.isString() && title_json.asCString()[0] != '\0')
                title += " - " + title_json.asString();

            const Json::Value &attributes_data_json = attributes_json["data"];
            if(!attributes_data_json.isArray())
                continue;

            auto body_item = BodyItem::create(std::move(title));
            body_item->url = id_json.asString();

            const Json::Value &publish_at_json = attributes_json["publishAt"];
            if(publish_at_json.isString()) {
                time_t unix_time = iso_utc_to_unix_time(publish_at_json.asCString());
                if(unix_time != 0) {
                    body_item->set_description("Uploaded: " + unix_time_to_local_time_str(unix_time));
                    body_item->set_description_color(get_theme().faded_text_color);
                }
            }

            std::vector<std::string> image_urls;
            image_urls.reserve(attributes_data_json.size());
            for(const Json::Value &data_item_json : attributes_data_json) {
                if(!data_item_json.isString())
                    continue;

                std::string url = hash_json.asString() + "/" + data_item_json.asString();
                image_urls.push_back(std::move(url));
            }
            chapter_image_urls[body_item->url] = std::move(image_urls);

            result_items.push_back(std::move(body_item));
        }

        return PluginResult::OK;
    }

    static void get_creators(const Json::Value &relationships_json, std::vector<Creator> &creators) {
        if(!relationships_json.isArray())
            return;

        for(const Json::Value &relationship_json : relationships_json) {
            if(!relationship_json.isObject())
                continue;

            const Json::Value &id_json = relationship_json["id"];
            if(!id_json.isString())
                continue;

            const Json::Value &type_json = relationship_json["type"];
            if(!type_json.isString() || (strcmp(type_json.asCString(), "author") != 0 && strcmp(type_json.asCString(), "artist") != 0))
                continue;

            const Json::Value &attributes_json = relationship_json["attributes"];
            if(!attributes_json.isObject())
                continue;

            const Json::Value &name_json = attributes_json["name"];
            if(!name_json.isString())
                continue;

            Creator creator;
            creator.name = name_json.asString();
            creator.url = id_json.asString();
            creator.creator_type = strcmp(type_json.asCString(), "author") == 0 ? CreatorType::AUTHOR : CreatorType::ARTIST;
            creators.push_back(std::move(creator));
        }
    }

    static PluginResult get_creators_for_manga(Page *page, const std::string &manga_id, std::vector<Creator> &creators) {
        std::string request_url = "https://api.mangadex.org/manga/" + manga_id + "?includes[]=artist&includes[]=author";

        Json::Value json_root;
        if(page->download_json(json_root, request_url, {}, true) != DownloadResult::OK)
            return PluginResult::NET_ERR;

        if(!json_root.isObject())
            return PluginResult::OK;

        const Json::Value &result_json = json_root["result"];
        if(!result_json.isString() || strcmp(result_json.asCString(), "ok") != 0)
            return PluginResult::ERR;

        const Json::Value &data_json = json_root["data"];
        if(!data_json.isObject())
            return PluginResult::ERR;

        get_creators(data_json["relationships"], creators);
        return PluginResult::OK;
    }

    static void remove_duplicate_creators(std::vector<Creator> &creators) {
        std::sort(creators.begin(), creators.end(), [](const Creator &creator1, const Creator &creator2) {
            return creator1.name < creator2.name;
        });
        creators.erase(
            std::unique(creators.begin(), creators.end(), [](const Creator &creator1, const Creator &creator2) {
                return creator1.name == creator2.name;
            }),
            creators.end());
    }

    // TODO: Do requests in parallel
    PluginResult MangadexSearchPage::submit(const std::string &title, const std::string &url, std::vector<Tab> &result_tabs) {
        PluginResult result;

        BodyItems body_items;
        ChapterImageUrls chapter_image_urls;
        result = get_chapters_for_manga(this, url, 0, body_items, chapter_image_urls);
        if(result != PluginResult::OK)
            return result;
        auto body = create_body();
        body->set_items(std::move(body_items));
        result_tabs.push_back(Tab{std::move(body), std::make_unique<MangadexChaptersPage>(program, this, title, url, std::move(chapter_image_urls)), create_search_bar("Search...", SEARCH_DELAY_FILTER)});

        std::vector<Creator> creators;
        result = get_creators_for_manga(this, url, creators);
        if(result != PluginResult::OK)
            return result;

        remove_duplicate_creators(creators);
        for(Creator &creator : creators) {
            result_tabs.push_back(Tab{create_body(), std::make_unique<MangadexCreatorPage>(program, this, std::move(creator)), create_search_bar("Search...", SEARCH_DELAY_FILTER)});
        }

        return PluginResult::OK;
    }

    PluginResult MangadexChaptersPage::submit(const std::string &title, const std::string &url, std::vector<Tab> &result_tabs) {
        result_tabs.push_back(Tab{nullptr, std::make_unique<MangadexImagesPage>(program, search_page, content_title, url, title, &chapter_image_urls), nullptr});
        return PluginResult::OK;
    }

    PluginResult MangadexChaptersPage::get_page(const std::string&, int page, BodyItems &result_items) {
        return get_chapters_for_manga(this, content_url, page, result_items, chapter_image_urls);
    }

    PluginResult MangadexCreatorPage::submit(const std::string &title, const std::string &url, std::vector<Tab> &result_tabs) {
        return search_page->submit(title, url, result_tabs);
    }

    PluginResult MangadexCreatorPage::get_page(const std::string&, int page, BodyItems &result_items) {
        return search_manga(this, SearchType::AUTHOR, creator.url, page, result_items);
    }

    PluginResult MangadexCreatorPage::lazy_fetch(BodyItems &result_items) {
        return search_manga(this, SearchType::AUTHOR, creator.url, 0, result_items);
    }

    bool MangadexChaptersPage::extract_id_from_url(const std::string &url, std::string &manga_id) const {
        size_t start_index = url.find("manga=");
        if(start_index == std::string::npos) {
            manga_id = url;
            return true;
        }

        start_index += 6;
        size_t end_index = url.find('&', start_index);
        if(end_index == std::string::npos) {
            manga_id = url.substr(start_index);
            return true;
        }
        
        manga_id = url.substr(start_index, end_index - start_index);
        return true;
    }

    ImageResult MangadexImagesPage::get_number_of_images(int &num_images) {
        num_images = 0;
        ImageResult image_result = get_image_urls_for_chapter(url);
        if(image_result != ImageResult::OK) return image_result;
        num_images = chapter_image_urls.size();
        return ImageResult::OK;
    }

    ImageResult MangadexImagesPage::for_each_page_in_chapter(PageCallback callback) {
        ImageResult image_result = get_image_urls_for_chapter(url);
        if(image_result != ImageResult::OK) return image_result;
        for(const std::string &url : chapter_image_urls) {
            if(!callback(url))
                break;
        }
        return ImageResult::OK;
    }

    ImageResult MangadexImagesPage::get_image_urls_for_chapter(const std::string &url) {
        if(!chapter_image_urls.empty())
            return ImageResult::OK;

        Json::Value json_root;
        if(download_json(json_root, "https://api.mangadex.org/at-home/server/" + url, {}, true) != DownloadResult::OK)
            return ImageResult::NET_ERR;

        if(!json_root.isObject())
            return ImageResult::ERR;

        const Json::Value &base_url_json = json_root["baseUrl"];
        if(!base_url_json.isString())
            return ImageResult::ERR;

        std::string base_url = base_url_json.asString();
        if(!base_url.empty() && base_url.back() != '/')
            base_url += '/';

        auto it = chapter_image_url_templates->find(url);
        if(it == chapter_image_url_templates->end())
            return ImageResult::ERR;

        chapter_image_urls.resize(it->second.size());
        for(size_t i = 0; i < it->second.size(); ++i) {
            chapter_image_urls[i] = base_url + "data/" + it->second[i];
        }

        return ImageResult::OK;
    }
}