[backend] Actually try to resolve unknown mentions in mfm-to-html

This commit is contained in:
Laura Hausmann 2023-10-14 16:26:45 +02:00
parent 72f048a24d
commit 349f770166
Signed by: zotan
GPG key ID: D044E84C5BE01605
6 changed files with 49 additions and 40 deletions

View file

@ -3,8 +3,9 @@ import type * as mfm from "mfm-js";
import config from "@/config/index.js"; import config from "@/config/index.js";
import { intersperse } from "@/prelude/array.js"; import { intersperse } from "@/prelude/array.js";
import type { IMentionedRemoteUsers } from "@/models/entities/note.js"; import type { IMentionedRemoteUsers } from "@/models/entities/note.js";
import { resolveMentionWithFallback } from "@/remote/resolve-user.js";
export function toHtml( export async function toHtml(
nodes: mfm.MfmNode[] | null, nodes: mfm.MfmNode[] | null,
mentionedRemoteUsers: IMentionedRemoteUsers = [], mentionedRemoteUsers: IMentionedRemoteUsers = [],
) { ) {
@ -16,9 +17,9 @@ export function toHtml(
const doc = window.document; const doc = window.document;
function appendChildren(children: mfm.MfmNode[], targetElement: any): void { async function appendChildren(children: mfm.MfmNode[], targetElement: any): Promise<void> {
if (children) { if (children) {
for (const child of children.map((x) => (handlers as any)[x.type](x))) for (const child of await Promise.all(children.map(async (x) => await (handlers as any)[x.type](x))))
targetElement.appendChild(child); targetElement.appendChild(child);
} }
} }
@ -26,33 +27,33 @@ export function toHtml(
const handlers: { const handlers: {
[K in mfm.MfmNode["type"]]: (node: mfm.NodeType<K>) => any; [K in mfm.MfmNode["type"]]: (node: mfm.NodeType<K>) => any;
} = { } = {
bold(node) { async bold(node) {
const el = doc.createElement("b"); const el = doc.createElement("b");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
small(node) { async small(node) {
const el = doc.createElement("small"); const el = doc.createElement("small");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
strike(node) { async strike(node) {
const el = doc.createElement("del"); const el = doc.createElement("del");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
italic(node) { async italic(node) {
const el = doc.createElement("i"); const el = doc.createElement("i");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
fn(node) { async fn(node) {
const el = doc.createElement("i"); const el = doc.createElement("i");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
@ -64,9 +65,9 @@ export function toHtml(
return pre; return pre;
}, },
center(node) { async center(node) {
const el = doc.createElement("div"); const el = doc.createElement("div");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
@ -104,28 +105,20 @@ export function toHtml(
return el; return el;
}, },
link(node) { async link(node) {
const a = doc.createElement("a"); const a = doc.createElement("a");
a.href = node.props.url; a.href = node.props.url;
appendChildren(node.children, a); await appendChildren(node.children, a);
return a; return a;
}, },
mention(node) { async mention(node) {
const el = doc.createElement("span"); const el = doc.createElement("span");
el.setAttribute("class", "h-card"); el.setAttribute("class", "h-card");
el.setAttribute("translate", "no"); el.setAttribute("translate", "no");
const a = doc.createElement("a"); const a = doc.createElement("a");
const { username, host, acct } = node.props; const { username, host, acct } = node.props;
const remoteUserInfo = mentionedRemoteUsers.find( a.href = await resolveMentionWithFallback(username, host, acct, mentionedRemoteUsers);
(remoteUser) =>
remoteUser.username.toLowerCase() === username.toLowerCase() && remoteUser.host === host,
);
a.href = remoteUserInfo
? remoteUserInfo.url
? remoteUserInfo.url
: remoteUserInfo.uri
: `${config.url}/${acct}`;
a.className = "u-url mention"; a.className = "u-url mention";
const span = doc.createElement("span"); const span = doc.createElement("span");
span.textContent = username; span.textContent = username;
@ -135,9 +128,9 @@ export function toHtml(
return el; return el;
}, },
quote(node) { async quote(node) {
const el = doc.createElement("blockquote"); const el = doc.createElement("blockquote");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
@ -168,14 +161,14 @@ export function toHtml(
return a; return a;
}, },
plain(node) { async plain(node) {
const el = doc.createElement("span"); const el = doc.createElement("span");
appendChildren(node.children, el); await appendChildren(node.children, el);
return el; return el;
}, },
}; };
appendChildren(nodes, doc.body); await appendChildren(nodes, doc.body);
return `<p>${doc.body.innerHTML}</p>`; return `<p>${doc.body.innerHTML}</p>`;
} }

View file

@ -2,7 +2,7 @@ import * as mfm from "mfm-js";
import type { Note } from "@/models/entities/note.js"; import type { Note } from "@/models/entities/note.js";
import { toHtml } from "../../../mfm/to-html.js"; import { toHtml } from "../../../mfm/to-html.js";
export default function (note: Note) { export default async function (note: Note) {
if (!note.text) return ""; if (!note.text) return "";
return toHtml(mfm.parse(note.text), JSON.parse(note.mentionedRemoteUsers)); return toHtml(mfm.parse(note.text), JSON.parse(note.mentionedRemoteUsers));
} }

View file

@ -108,7 +108,7 @@ export default async function renderNote(
const summary = note.cw === "" ? String.fromCharCode(0x200b) : note.cw; const summary = note.cw === "" ? String.fromCharCode(0x200b) : note.cw;
const content = toHtml( const content = await toHtml(
Object.assign({}, note, { Object.assign({}, note, {
text: apText, text: apText,
}), }),

View file

@ -73,7 +73,7 @@ export async function renderPerson(user: ILocalUser) {
preferredUsername: user.username, preferredUsername: user.username,
name: user.name, name: user.name,
summary: profile.description summary: profile.description
? toHtml(mfm.parse(profile.description)) ? await toHtml(mfm.parse(profile.description))
: null, : null,
icon: avatar ? renderImage(avatar) : null, icon: avatar ? renderImage(avatar) : null,
image: banner ? renderImage(banner) : null, image: banner ? renderImage(banner) : null,

View file

@ -3,12 +3,13 @@ import chalk from "chalk";
import { IsNull } from "typeorm"; import { IsNull } from "typeorm";
import config from "@/config/index.js"; import config from "@/config/index.js";
import type { User, IRemoteUser } from "@/models/entities/user.js"; import type { User, IRemoteUser } from "@/models/entities/user.js";
import { Users } from "@/models/index.js"; import { UserProfiles, Users } from "@/models/index.js";
import { toPuny } from "@/misc/convert-host.js"; import { toPuny } from "@/misc/convert-host.js";
import webFinger from "./webfinger.js"; import webFinger from "./webfinger.js";
import { createPerson, updatePerson } from "./activitypub/models/person.js"; import { createPerson, updatePerson } from "./activitypub/models/person.js";
import { remoteLogger } from "./logger.js"; import { remoteLogger } from "./logger.js";
import { Cache } from "@/misc/cache.js"; import { Cache } from "@/misc/cache.js";
import { IMentionedRemoteUsers } from "@/models/entities/note.js";
const logger = remoteLogger.createSubLogger("resolve-user"); const logger = remoteLogger.createSubLogger("resolve-user");
const uriHostCache = new Cache<string>("resolveUserUriHost", 60 * 60 * 24); const uriHostCache = new Cache<string>("resolveUserUriHost", 60 * 60 * 24);
@ -173,6 +174,21 @@ export async function resolveUser(
return user; return user;
} }
export async function resolveMentionWithFallback(username: string, host: string | null, acct: string, cache: IMentionedRemoteUsers): Promise<string> {
const fallback = `${config.url}/${acct}`;
const cached = cache.find(r => r.username.toLowerCase() === username.toLowerCase() && r.host === host);
if (cached) return cached.url ?? cached.uri;
if (host === null) return fallback;
try {
const user = await resolveUser(username, host);
const profile = await UserProfiles.findOneBy({ userId: user.id });
return profile?.url ?? user.uri ?? fallback;
}
catch {
return fallback;
}
}
export async function getSubjectHostFromUri(uri: string): Promise<string | null> { export async function getSubjectHostFromUri(uri: string): Promise<string | null> {
try { try {
const acct = subjectToAcct((await webFinger(uri)).subject); const acct = subjectToAcct((await webFinger(uri)).subject);

View file

@ -5,16 +5,16 @@ import { toHtml } from "../src/mfm/to-html.js";
import { fromHtml } from "../src/mfm/from-html.js"; import { fromHtml } from "../src/mfm/from-html.js";
describe("toHtml", () => { describe("toHtml", () => {
it("br", () => { it("br", async () => {
const input = "foo\nbar\nbaz"; const input = "foo\nbar\nbaz";
const output = "<p><span>foo<br>bar<br>baz</span></p>"; const output = "<p><span>foo<br>bar<br>baz</span></p>";
assert.equal(toHtml(mfm.parse(input)), output); assert.equal(await toHtml(mfm.parse(input)), output);
}); });
it("br alt", () => { it("br alt", async () => {
const input = "foo\r\nbar\rbaz"; const input = "foo\r\nbar\rbaz";
const output = "<p><span>foo<br>bar<br>baz</span></p>"; const output = "<p><span>foo<br>bar<br>baz</span></p>";
assert.equal(toHtml(mfm.parse(input)), output); assert.equal(await toHtml(mfm.parse(input)), output);
}); });
}); });