summaryrefslogtreecommitdiff
path: root/src/remote/resolve-user.ts
blob: e199b6f1479ddbf03a0b23f62124eb9b2a2ce95c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { toUnicode, toASCII } from 'punycode';
import User, { IUser } from '../models/user';
import webFinger from './webfinger';
import config from '../config';
import { createPerson } from './activitypub/models/person';

export default async (username: string, _host: string, option?: any): Promise<IUser> => {
	const usernameLower = username.toLowerCase();

	if (_host == null) {
		return await User.findOne({ usernameLower });
	}

	const hostAscii = toASCII(_host).toLowerCase();
	const host = toUnicode(hostAscii);

	if (config.host == host) {
		return await User.findOne({ usernameLower, host: null });
	}

	let user = await User.findOne({ usernameLower, host }, option);

	if (user === null) {
		const acctLower = `${usernameLower}@${hostAscii}`;

		const finger = await webFinger(acctLower);
		const self = finger.links.find(link => link.rel && link.rel.toLowerCase() === 'self');
		if (!self) {
			throw new Error('self link not found');
		}

		user = await createPerson(self.href);
	}

	return user;
};