From 3db379b069720b2cf3387a3d1b7e24a0c541082a Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Thu, 5 Sep 2024 10:20:36 +0700 Subject: [PATCH] Added `liked` flag to objects in inbox refs https://linear.app/tryghost/issue/AP-293 In order to render the feed and inbox we need to know which objects have been liked, this is a naive implementation which doesn't scale to multiple users and should be replaced as party of the database restructure work. --- src/handlers.ts | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/handlers.ts b/src/handlers.ts index f96ad3c3..12f652f3 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -24,9 +24,13 @@ import { Temporal } from '@js-temporal/polyfill'; import { createHash } from 'node:crypto'; type StoredThing = { + id: string; object: string | { + id: string; content: string; - } + [key: string]: any; + }; + [key: string]: any; } import z from 'zod'; @@ -352,22 +356,30 @@ export async function inboxHandler( ctx: Context<{ Variables: HonoContextVariables }>, next: Next, ) { + const liked = (await ctx.get('db').get(['liked'])) || []; const results = (await ctx.get('db').get(['inbox'])) || []; + const apCtx = fedify.createContext(ctx.req.raw as Request, { + db: ctx.get('db'), + globaldb: ctx.get('globaldb'), + }); let items: unknown[] = []; for (const result of results) { try { const db = ctx.get('globaldb'); const thing = await db.get([result]); + if (!thing) { + continue; + } // If the object is a string, it's probably a URI, so we should // look it up the db. If it's not in the db, we should just leave // it as is - if (thing && typeof thing.object === 'string') { + if (typeof thing.object === 'string') { thing.object = await db.get([thing.object]) ?? thing.object; } // Sanitize HTML content - if (thing?.object && typeof thing.object !== 'string') { + if (thing.object && typeof thing.object !== 'string') { thing.object.content = sanitizeHtml(thing.object.content, { allowedTags: ['a', 'p', 'img', 'br', 'strong', 'em', 'span'], allowedAttributes: { @@ -377,6 +389,24 @@ export async function inboxHandler( }); } + let objectId: string = ''; + if (typeof thing.object === 'string') { + objectId = thing.object; + } else if (typeof thing.object.id === 'string') { + objectId = thing.object.id; + } + + if (objectId) { + const likeId = apCtx.getObjectUri(Like, { + id: createHash('sha256').update(objectId).digest('hex'), + }); + if (liked.includes(likeId.href)) { + if (typeof thing.object !== 'string') { + thing.object.liked = true; + } + } + } + items.push(thing); } catch (err) { console.log(err);