const express = require("express"); const router = express.Router(); const pool = require("../../db"); const { strictInput } = require("../../middleware/strict_input"); const { authenticateToken } = require("../../middleware/authenticate_token"); const { uploadDirectory } = require("../../middleware/post_upload"); const { getFriendIdsAmong, areFriends } = require("../relations/friend_graph"); const { likeDataForPosts } = require("./post_graph"); const path = require("path"); function parsePagination(req) { const { limit: limitRaw, offset: offsetRaw } = req.query; if (limitRaw === undefined && offsetRaw === undefined) { return { limit: 20, offset: 0 }; } const limit = limitRaw === undefined ? 20 : Number(limitRaw); const offset = offsetRaw === undefined ? 0 : Number(offsetRaw); if (!Number.isInteger(limit) || limit < 1 || limit > 100) { return { error: "limit must be an integer between 1 and 100" }; } if (!Number.isInteger(offset) || offset < 0) { return { error: "offset must be a non-negative integer" }; } return { limit, offset }; } async function getPosts(req, res, ownOnly) { const pagination = parsePagination(req); if (pagination.error) return res.status(400).send(pagination.error); try { const values = []; const conditions = ["p.active = true"]; if (ownOnly) { conditions.push(`p.author_id = $${values.length + 1}`); values.push(req.user.id); } else { const visible = [`people.private = false`, `p.author_id = $${values.length + 1}`]; values.push(req.user.id); const { rows } = await pool.query( `SELECT DISTINCT p.author_id FROM posts p JOIN people ON people.id = p.author_id WHERE p.active = true AND people.private = true`, ); const privateAuthorIds = rows.map((row) => Number(row.author_id)); if (privateAuthorIds.length > 0) { const friendIds = await getFriendIdsAmong(req.user.id, privateAuthorIds); if (friendIds.size > 0) { visible.push(`p.author_id = ANY($${values.length + 1})`); values.push([...friendIds]); } } conditions.push(`(${visible.join(" OR ")})`); } const where = conditions.join(" AND "); const query = `SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at FROM posts p LEFT JOIN people ON people.id = p.author_id WHERE ${where} ORDER BY p.created_at DESC LIMIT $${values.length + 1} OFFSET $${values.length + 2}`; values.push(pagination.limit, pagination.offset); const { rows } = await pool.query(query, values); const likeData = await likeDataForPosts( req.user.id, rows.map((row) => row.id), ); const posts = rows.map((row) => ({ ...row, like_count: likeData.get(Number(row.id))?.like_count ?? 0, liked_by_me: likeData.get(Number(row.id))?.liked_by_me ?? false, })); res.status(200).json(posts); } catch (err) { console.error("database query failed", { message: err.message, code: err.code, detail: err.detail, hint: err.hint, stack: err.stack, }); res.status(500).send("Posts could not be retrieved, request failed"); } } router.get( "/image/:filename", authenticateToken, strictInput(), async (req, res) => { const filename = path.basename(req.params.filename); if (filename !== req.params.filename) return res.status(404).end(); try { const { rows } = await pool.query( `SELECT p.author_id, people.private AS author_private FROM posts p LEFT JOIN people ON people.id = p.author_id WHERE p.image_link = $1 AND p.active = true`, [`/posts/image/${filename}`], ); if (rows.length === 0) return res.status(404).send("Image not found"); const post = rows[0]; if ( post.author_private && Number(post.author_id) !== req.user.id && !(await areFriends(req.user.id, post.author_id)) ) { return res.status(404).send("Image not found"); } res.set("Cache-Control", "private, no-store"); res.sendFile(filename, { root: uploadDirectory }, (err) => { if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end(); }); } catch (err) { console.error("post image query failed", { message: err.message, code: err.code, detail: err.detail, hint: err.hint, }); return res.status(500).send("Image could not be retrieved, request failed"); } }, ); router.get( "/me", authenticateToken, strictInput({ query: ["limit", "offset"] }), (req, res) => getPosts(req, res, true), ); router.get( "/", authenticateToken, strictInput({ query: ["limit", "offset"] }), (req, res) => getPosts(req, res, false), ); module.exports = router;