Get actual subject host in mfm fromHtml

This commit is contained in:
Laura Hausmann 2023-09-11 22:25:29 +02:00
parent 552041726b
commit fb091488d8
No known key found for this signature in database
GPG Key ID: D044E84C5BE01605
3 changed files with 23 additions and 2 deletions

View File

@ -1,11 +1,12 @@
import { URL } from "node:url";
import * as parse5 from "parse5";
import { defaultTreeAdapter as treeAdapter } from "parse5";
import { getSubjectHostFromUriAndUsernameCached } from "@/remote/resolve-user.js";
const urlRegex = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+/;
const urlRegexFull = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+$/;
export async function fromHtml(html: string, hashtagNames?: string[]): Promise<string> {
export async function fromHtml(html: string, hashtagNames?: string[], basicMentionResolve: boolean = false): Promise<string> {
// some AP servers like Pixelfed use br tags as well as newlines
html = html.replace(/<br\s?\/?>\r?\n/gi, "\n");
@ -72,7 +73,9 @@ export async function fromHtml(html: string, hashtagNames?: string[]): Promise<s
if (part.length === 2 && href) {
//#region ホスト名部分が省略されているので復元する
const acct = `${txt}@${new URL(href.value).hostname}`;
const acct = basicMentionResolve
? `${txt}@${new URL(href.value).hostname}`
: `${txt}@${await getSubjectHostFromUriAndUsernameCached(href.value, txt)}`;
text += acct;
//#endregion
} else if (part.length === 3) {

View File

@ -187,6 +187,22 @@ export async function getSubjectHostFromUri(uri: string): Promise<string | null>
}
}
export async function getSubjectHostFromUriAndUsernameCached(uri: string, username: string): Promise<string | null> {
const hostname = new URL(uri).hostname;
username = username.substring(1); // remove leading @ from username
const user = await Users.findOneBy({
usernameLower: username.toLowerCase(),
host: hostname
});
if (user) {
return user.host;
}
return await getSubjectHostFromUri(uri) ?? hostname;
}
export async function getSubjectHostFromAcct(acct: string): Promise<string | null> {
try {
const res = await resolveUserWebFinger(acct.toLowerCase());

View File

@ -111,6 +111,8 @@ describe("fromHtml", () => {
assert.deepStrictEqual(
await fromHtml(
'<p>a <a href="https://joiniceshrimp.org/@user" class="u-url mention">@user</a> d</p>',
undefined,
false
),
"a @user@joiniceshrimp.org d",
);