summaryrefslogtreecommitdiff
path: root/src/remote/activitypub/act/create/note.ts
blob: 364fddfe0b136d451a472b0de8da30b09651d91b (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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';
import { IRemoteUser } from '../../../../models/user';
import resolvePerson from '../../resolve-person';
import createImage from './image';
import config from '../../../../config';

const log = debug('misskey:activitypub');

/**
 * 投稿作成アクティビティを捌きます
 */
export default async function createNote(resolver: Resolver, actor: IRemoteUser, note, silent = false): Promise<IPost> {
	if (typeof note.id !== 'string') {
		log(`invalid note: ${JSON.stringify(note, null, 2)}`);
		throw new Error('invalid note');
	}

	// 既に同じURIを持つものが登録されていないかチェックし、登録されていたらそれを返す
	const exist = await Post.findOne({ uri: note.id });
	if (exist) {
		return exist;
	}

	log(`Creating the Note: ${note.id}`);

	//#region Visibility
	let visibility = 'public';
	if (!note.to.includes('https://www.w3.org/ns/activitystreams#Public')) visibility = 'unlisted';
	if (note.cc.length == 0) visibility = 'private';
	// TODO
	if (visibility != 'public') throw new Error('unspported visibility');
	//#endergion

	//#region 添付メディア
	const media = [];
	if ('attachment' in note && note.attachment != null) {
		// TODO: attachmentは必ずしもImageではない
		// TODO: attachmentは必ずしも配列ではない
		// TODO: ループの中でawaitはすべきでない
		note.attachment.forEach(async media => {
			const created = await createImage(resolver, note.actor, media);
			media.push(created);
		});
	}
	//#endregion

	//#region リプライ
	let reply = null;
	if ('inReplyTo' in note && note.inReplyTo != null) {
		// リプライ先の投稿が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 });

		if (inReplyToPost) {
			reply = inReplyToPost;
		} else {
			// 無かったらフェッチ
			const inReplyTo = await resolver.resolve(note.inReplyTo) as any;

			// リプライ先の投稿の投稿者をフェッチ
			const actor = await resolvePerson(inReplyTo.attributedTo) as IRemoteUser;

			// TODO: silentを常にtrueにしてはならない
			reply = await createNote(resolver, actor, inReplyTo);
		}
	}
	//#endregion

	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,
		visibility,
		uri: note.id
	});
}