Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions graphql/account.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { encodeGlobalID } from "@pothos/plugin-relay";
import * as vocab from "@fedify/vocab";
import { execute, parse } from "graphql";
import { updateAccountData } from "@hackerspub/models/account";
import type { UserContext } from "./builder.ts";
import { schema } from "./mod.ts";
import { putProfileOgImage } from "./og.ts";
import {
createFedCtx,
insertAccountWithActor,
Expand Down Expand Up @@ -34,6 +36,22 @@ const accountByUsernameQuery = parse(`
}
`);

const accountOgImageUrlQuery = parse(`
query AccountOgImageUrl($username: String!) {
accountByUsername(username: $username) {
ogImageUrl
}
}
`);

const accountsOgImageUrlQuery = parse(`
query AccountsOgImageUrl {
accounts {
ogImageUrl
}
}
`);

const invitationTreeQuery = parse(`
query InvitationTree {
invitationTree {
Expand Down Expand Up @@ -62,6 +80,52 @@ const updateAccountMutation = parse(`
}
`);

const smallPngDataUrl = "data:image/png;base64," +
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";

function createOgTestDisk(): {
disk: UserContext["disk"];
putKeys: string[];
deleteKeys: string[];
} {
const putKeys: string[] = [];
const deleteKeys: string[] = [];
return {
putKeys,
deleteKeys,
disk: {
getUrl(key: string) {
if (key === "avatar-og-test") return Promise.resolve(smallPngDataUrl);
return Promise.resolve(`http://localhost/media/${key}`);
},
put(key: string) {
putKeys.push(key);
return Promise.resolve(undefined);
},
delete(key: string) {
deleteKeys.push(key);
return Promise.resolve(undefined);
},
} as unknown as UserContext["disk"],
};
}

test("putProfileOgImage leaves existing cached images for the caller", async () => {
const disk = createOgTestDisk();

const key = await putProfileOgImage(disk.disk, "og/v2/stale-profile.png", {
avatarKey: "avatar-og-test",
avatarUrl: smallPngDataUrl,
bio: "Cached profile image should survive until metadata is updated.",
displayName: "Profile Cache Review",
handle: "@profilecache@localhost",
});

assert.match(key, /^og\/v2\/.+\.png$/);
assert.notEqual(key, "og/v2/stale-profile.png");
assert.deepEqual(disk.deleteKeys, []);
});

test("viewer returns the signed-in account and null for guests", async () => {
await withRollback(async (tx) => {
const account = await insertAccountWithActor(tx, {
Expand Down Expand Up @@ -101,6 +165,77 @@ test("viewer returns the signed-in account and null for guests", async () => {
});
});

test("Account.ogImageUrl renders and reuses a cached profile image", async () => {
await withRollback(async (tx) => {
const account = await insertAccountWithActor(tx, {
username: "profileoggraphql",
name: "Profile OG GraphQL",
email: "profileoggraphql@example.com",
});
const updated = await updateAccountData(tx, {
id: account.account.id,
avatarKey: "avatar-og-test",
bio: "Mixed script bio: Hello, 안녕하세요, こんにちは, 你好, 😀",
ogImageKey: "og/v2/stale-profile.png",
});
assert.ok(updated != null);

const disk = createOgTestDisk();
const firstResult = await execute({
schema,
document: accountOgImageUrlQuery,
variableValues: { username: account.account.username },
contextValue: makeGuestContext(tx, { disk: disk.disk }),
onError: "NO_PROPAGATE",
});

assert.equal(firstResult.errors, undefined);
const firstUrl = (toPlainJson(firstResult.data) as {
accountByUsername: { ogImageUrl: string };
}).accountByUsername.ogImageUrl;
assert.match(firstUrl, /^http:\/\/localhost\/media\/og\/v2\/.+\.png$/);
assert.equal(disk.putKeys.length, 1);
assert.deepEqual(disk.deleteKeys, ["og/v2/stale-profile.png"]);

const stored = await tx.query.accountTable.findFirst({
where: { id: account.account.id },
});
assert.ok(stored?.ogImageKey?.startsWith("og/v2/"));

const secondResult = await execute({
schema,
document: accountOgImageUrlQuery,
variableValues: { username: account.account.username },
contextValue: makeGuestContext(tx, { disk: disk.disk }),
onError: "NO_PROPAGATE",
});

assert.equal(secondResult.errors, undefined);
const secondUrl = (toPlainJson(secondResult.data) as {
accountByUsername: { ogImageUrl: string };
}).accountByUsername.ogImageUrl;
assert.equal(secondUrl, firstUrl);
assert.equal(disk.putKeys.length, 1);
assert.deepEqual(disk.deleteKeys, ["og/v2/stale-profile.png"]);
});
});

test("Account.ogImageUrl rejects bulk account list queries", async () => {
await withRollback(async (tx) => {
const disk = createOgTestDisk();
const result = await execute({
schema,
document: accountsOgImageUrlQuery,
contextValue: makeGuestContext(tx, { disk: disk.disk }),
onError: "NO_PROPAGATE",
});

assert.deepEqual(toPlainJson(result.data), { accounts: null });
assert.match(result.errors?.[0]?.message ?? "", /Query exceeds Complexity/);
assert.deepEqual(disk.putKeys, []);
});
});

test("accountByUsername returns a local account by username", async () => {
await withRollback(async (tx) => {
const account = await insertAccountWithActor(tx, {
Expand Down
49 changes: 49 additions & 0 deletions graphql/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
transformAvatar,
updateAccount,
} from "@hackerspub/models/account";
import { renderMarkup } from "@hackerspub/models/markup";
import { syncActorFromAccount } from "@hackerspub/models/actor";
import type { Locale } from "@hackerspub/models/i18n";
import {
Comment thread
dahlia marked this conversation as resolved.
Expand All @@ -21,13 +22,16 @@ import { Actor } from "./actor.ts";
import { builder } from "./builder.ts";
import { InvitationLink } from "./invitation-link.ts";
import { Notification } from "./notification.ts";
import { putProfileOgImage } from "./og.ts";
import { ArticleDraft } from "./post.ts";
import {
fromPostVisibility,
PostVisibility,
toPostVisibility,
} from "./postvisibility.ts";

const profileOgImageComplexity = 2_000;

export const Account = builder.drizzleNode("accountTable", {
name: "Account",
id: {
Expand Down Expand Up @@ -74,6 +78,51 @@ export const Account = builder.drizzleNode("accountTable", {
return new URL(url);
},
}),
ogImageUrl: t.field({
type: "URL",
complexity: profileOgImageComplexity,
select: {
columns: {
avatarKey: true,
bio: true,
id: true,
name: true,
ogImageKey: true,
username: true,
},
with: {
actor: {
columns: {
handleHost: true,
},
},
emails: true,
},
},
async resolve(account, _, ctx) {
const avatarUrl = await getAvatarUrl(ctx.disk, account);
const bio = await renderMarkup(ctx.fedCtx, account.bio, {
kv: ctx.kv,
});
const handle = `@${account.username}@${account.actor.handleHost}`;
const key = await putProfileOgImage(ctx.disk, account.ogImageKey, {
avatarKey: account.avatarKey ?? avatarUrl,
avatarUrl,
bio: bio.text,
displayName: account.name,
handle,
});
if (key !== account.ogImageKey) {
await ctx.db.update(accountTable)
.set({ ogImageKey: key })
.where(eq(accountTable.id, account.id));
if (account.ogImageKey != null) {
await ctx.disk.delete(account.ogImageKey);
}
}
Comment thread
dahlia marked this conversation as resolved.
Comment thread
dahlia marked this conversation as resolved.
return new URL(await ctx.disk.getUrl(key));
},
}),
locales: t.field({
type: ["Locale"],
nullable: true,
Expand Down
5 changes: 5 additions & 0 deletions graphql/assets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Hackers' Pub visual identity assets in this directory are from:
https://github.com/hackers-pub/visual-identity

Visual Identity of Hackers' Pub (c) 2025 Bak Eunji is licensed under Creative
Commons Attribution-ShareAlike 4.0 International.
Loading
Loading