hippofish/src/remote/activitypub/resolve-person.ts

75 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-03-31 12:55:00 +02:00
import { JSDOM } from 'jsdom';
import { toUnicode } from 'punycode';
2018-04-01 21:15:27 +02:00
import User, { validateUsername, isValidName, isValidDescription } from '../../models/user';
2018-03-31 12:55:00 +02:00
import webFinger from '../webfinger';
import Resolver from './resolver';
2018-04-04 18:07:07 +02:00
import uploadFromUrl from '../../api/drive/upload-from-url';
2018-03-31 12:55:00 +02:00
2018-04-02 11:36:47 +02:00
export default async (value, verifier?: string) => {
2018-04-04 18:07:07 +02:00
const resolver = new Resolver();
const object = await resolver.resolve(value) as any;
2018-03-31 12:55:00 +02:00
if (
object === null ||
object.type !== 'Person' ||
typeof object.preferredUsername !== 'string' ||
2018-04-02 11:36:47 +02:00
!validateUsername(object.preferredUsername) ||
2018-03-31 12:55:00 +02:00
!isValidName(object.name) ||
!isValidDescription(object.summary)
) {
2018-04-04 18:07:07 +02:00
throw new Error('invalid person');
2018-03-31 12:55:00 +02:00
}
2018-04-04 18:07:07 +02:00
const finger = await webFinger(object.id, verifier);
2018-03-31 12:55:00 +02:00
2018-04-02 11:36:47 +02:00
const host = toUnicode(finger.subject.replace(/^.*?@/, ''));
const hostLower = host.replace(/[A-Z]+/, matched => matched.toLowerCase());
2018-03-31 12:55:00 +02:00
const summaryDOM = JSDOM.fragment(object.summary);
// Create user
const user = await User.insert({
avatarId: null,
bannerId: null,
2018-04-05 11:08:51 +02:00
createdAt: Date.parse(object.published) || null,
2018-03-31 12:55:00 +02:00
description: summaryDOM.textContent,
2018-04-04 18:07:07 +02:00
followersCount: 0,
followingCount: 0,
2018-03-31 12:55:00 +02:00
name: object.name,
2018-04-04 18:07:07 +02:00
postsCount: 0,
2018-03-31 12:55:00 +02:00
driveCapacity: 1024 * 1024 * 8, // 8MiB
username: object.preferredUsername,
2018-04-02 11:36:47 +02:00
usernameLower: object.preferredUsername.toLowerCase(),
host,
2018-03-31 12:55:00 +02:00
hostLower,
account: {
2018-04-01 08:58:49 +02:00
publicKey: {
id: object.publicKey.id,
publicKeyPem: object.publicKey.publicKeyPem
},
2018-04-01 12:43:26 +02:00
inbox: object.inbox,
2018-03-31 12:55:00 +02:00
uri: object.id,
},
});
const [avatarId, bannerId] = await Promise.all([
object.icon,
object.image
2018-04-05 11:08:51 +02:00
].map(async img => {
if (img === undefined) {
2018-03-31 12:55:00 +02:00
return null;
}
2018-04-05 11:08:51 +02:00
const file = await uploadFromUrl(img.url, user);
2018-03-31 12:55:00 +02:00
2018-04-05 11:08:51 +02:00
return file._id;
2018-03-31 12:55:00 +02:00
}));
User.update({ _id: user._id }, { $set: { avatarId, bannerId } });
user.avatarId = avatarId;
user.bannerId = bannerId;
return user;
};