coyote/routes/status.cpp

72 lines
2.1 KiB
C++

#include "routes.h"
#include "../lxb_wrapper.h"
#include "../servehelper.h"
#include "../client.h"
#include "../models.h"
static inline std::string make_title(const Post& post);
void status_route(const httplib::Request& req, httplib::Response& res) {
std::string server = req.matches.str(1);
std::string id = req.matches.str(2);
std::optional<Post> post;
PostContext context;
try {
post = mastodon_client.get_post(server, id);
if (post) {
context = mastodon_client.get_post_context(server, id);
}
} catch (const std::exception& e) {
res.status = 500;
serve_error(req, res, "500: Internal server error", "Failed to fetch post information", e.what());
return;
}
if (!post) {
res.status = 404;
serve_error(req, res, "404: Post not found");
return;
}
if (post->reblog) {
serve_redirect(req, res, get_origin(req) + '/' + server + "/@" + post->reblog->account.acct(false) + '/' + post->reblog->id, true);
return;
}
Element body("body");
body.nodes.reserve(context.ancestors.size() * 2 + 1 + context.descendants.size() * 2);
for (const Post& i : context.ancestors) {
body.nodes.push_back(serialize_post(req, server, i));
body.nodes.push_back(Element("hr"));
}
body.nodes.push_back(serialize_post(req, server, *post, false, true));
for (const Post& i : context.descendants) {
body.nodes.push_back(Element("hr"));
body.nodes.push_back(serialize_post(req, server, i));
}
serve(req, res, make_title(*post), std::move(body));
}
static inline std::string make_title(const Post& post) {
LXB::HTML::Document document(post.content.str);
size_t content_len;
const char* content = reinterpret_cast<const char*>(lxb_dom_node_text_content(document.body(), &content_len));
std::string title = post.account.display_name + " (@" + post.account.acct() + "): ";
if (content_len) {
title.append(content, content_len > 50 ? 50 : content_len);
if (content_len > 50) {
title += "";
}
} else {
title += "Post";
}
return title;
}