rudeshark.net/src/remote/activitypub/act/create/note.ts

80 lines
2.4 KiB
TypeScript
Raw Normal View History

2018-04-06 12:35:23 +02:00
import { JSDOM } from 'jsdom';
import * as debug from 'debug';
import Resolver from '../../resolver';
import Post, { IPost } from '../../../../models/post';
import createPost from '../../../../services/post/create';
2018-04-06 23:13:40 +02:00
import { IRemoteUser } from '../../../../models/user';
2018-04-06 12:35:23 +02:00
import resolvePerson from '../../resolve-person';
import createImage from './image';
2018-04-06 23:13:40 +02:00
import config from '../../../../config';
2018-04-06 12:35:23 +02:00
const log = debug('misskey:activitypub');
2018-04-06 23:13:40 +02:00
/**
* 稿
*/
export default async function createNote(resolver: Resolver, actor: IRemoteUser, note, silent = false): Promise<IPost> {
2018-04-06 23:13:40 +02:00
if (typeof note.id !== 'string') {
2018-04-06 12:35:23 +02:00
log(`invalid note: ${JSON.stringify(note, null, 2)}`);
throw new Error('invalid note');
}
2018-04-06 23:13:40 +02:00
// 既に同じURIを持つものが登録されていないかチェックし、登録されていたらそれを返す
const exist = await Post.findOne({ uri: note.id });
if (exist) {
return exist;
}
2018-04-06 12:35:23 +02:00
log(`Creating the Note: ${note.id}`);
2018-04-06 23:13:40 +02:00
//#region 添付メディア
2018-04-06 12:35:23 +02:00
const media = [];
if ('attachment' in note && note.attachment != null) {
// TODO: attachmentは必ずしもImageではない
// TODO: ループの中でawaitはすべきでない
note.attachment.forEach(async media => {
const created = await createImage(resolver, note.actor, media);
media.push(created);
});
}
2018-04-06 23:13:40 +02:00
//#endregion
2018-04-06 12:35:23 +02:00
2018-04-06 23:13:40 +02:00
//#region リプライ
2018-04-06 12:35:23 +02:00
let reply = null;
if ('inReplyTo' in note && note.inReplyTo != null) {
2018-04-06 23:13:40 +02:00
// リプライ先の投稿がMisskeyに登録されているか調べる
const uri: string = note.inReplyTo.id || note.inReplyTo;
const inReplyToPost = uri.startsWith(config.url + '/')
? await Post.findOne({ _id: uri.split('/').pop() })
: await Post.findOne({ uri });
2018-04-06 12:35:23 +02:00
if (inReplyToPost) {
reply = inReplyToPost;
} else {
2018-04-06 23:13:40 +02:00
// 無かったらフェッチ
2018-04-06 12:35:23 +02:00
const inReplyTo = await resolver.resolve(note.inReplyTo) as any;
2018-04-06 23:13:40 +02:00
// リプライ先の投稿の投稿者をフェッチ
const actor = await resolvePerson(inReplyTo.attributedTo) as IRemoteUser;
// TODO: silentを常にtrueにしてはならない
reply = await createNote(resolver, actor, inReplyTo);
2018-04-06 12:35:23 +02:00
}
}
2018-04-06 23:13:40 +02:00
//#endregion
2018-04-06 12:35:23 +02:00
const { window } = new JSDOM(note.content);
return await createPost(actor, {
createdAt: new Date(note.published),
media,
reply,
repost: undefined,
text: window.document.body.textContent,
viaMobile: false,
geo: undefined,
uri: note.id
});
}