pixwhile/routes/users/illustrations.cpp

80 lines
2.7 KiB
C++

#include <utility>
#include "../routes.h"
#include "../../numberhelper.h"
#include "../../servehelper.h"
#include "../../pixivclient.h"
#include "common.h"
static Element generate_pager(const Illusts& illusts, size_t page);
static inline Element generate_content(const Illusts& illusts);
void user_illustrations_route(const httplib::Request& req, httplib::Response& res, const Config& config, PixivClient& pixiv_client) {
uint64_t user_id = to_ull(req.matches[1].str());
uint64_t page = req.has_param("p") ? to_ull(req.get_param_value("p")) - 1 : 0;
User user;
Illusts illusts;
try {
user = pixiv_client.get_user(user_id);
illusts = pixiv_client.get_illusts(user_id, page);
} catch (const PixivException& e) {
if (e.status == 404) {
res.status = 404;
serve_error(req, res, config, "404: User not found", e.what());
} else {
res.status = 500;
serve_error(req, res, config, "500: Internal server error", "Failed to fetch user information", e.what());
}
return;
} catch (const std::exception& e) {
res.status = 500;
serve_error(req, res, config, "500: Internal server error", "Failed to fetch user information", e.what());
return;
}
Element body("body", {
generate_user_header(std::move(user), config),
generate_pager(illusts, page),
Element("br"),
generate_content(illusts),
generate_pager(illusts, page)
});
serve(req, res, config, user.display_name + " illustrations", std::move(body));
}
static Element generate_pager(const Illusts& illusts, size_t page) {
using namespace std::string_literals;
auto link = [](std::string href, const char* text, bool add_link) {
Element b("b");
if (add_link) {
b.nodes.push_back(Element("a", {{"href", std::move(href)}}, {text}));
} else {
b.nodes.push_back(text);
}
return b;
};
return Element("div", {{"class", "center"}}, {
link("?p=1", "First", page != 0), " ",
link("?p="s + std::to_string(page), "Prev", page != 0), " ",
std::to_string(page + 1), "/", std::to_string(illusts.total_pages), " ",
link("?p="s + std::to_string(page + 2), "Next", page + 1 < illusts.total_pages), " ",
link("?p="s + std::to_string(illusts.total_pages), "Last", page + 1 < illusts.total_pages)
});
}
static inline Element generate_content(const Illusts& illusts) {
// TODO be real
Element ul("ul");
ul.nodes.reserve(illusts.illusts.size());
for (const Illust& i : illusts.illusts) {
ul.nodes.push_back(Element("li", {
std::to_string(i.illust_id)
}));
}
return ul;
}