summaryrefslogtreecommitdiff
path: root/src/server/api/endpoints/posts/create.ts
blob: 42901ebcbfe848e95a47fb60f8600817595a43e0 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/**
 * Module dependencies
 */
import $ from 'cafy';
import deepEqual = require('deep-equal');
import html from '../../../../common/text/html';
import parse from '../../../../common/text/parse';
import { default as Post, IPost, isValidText, isValidCw } from '../../../../models/post';
import { default as User, ILocalAccount, IUser } from '../../../../models/user';
import { default as Channel, IChannel } from '../../../../models/channel';
import Following from '../../../../models/following';
import Mute from '../../../../models/mute';
import DriveFile from '../../../../models/drive-file';
import Watching from '../../../../models/post-watching';
import ChannelWatching from '../../../../models/channel-watching';
import { pack } from '../../../../models/post';
import notify from '../../common/notify';
import watch from '../../common/watch-post';
import event, { pushSw, publishChannelStream } from '../../../../common/event';
import getAcct from '../../../../common/user/get-acct';
import parseAcct from '../../../../common/user/parse-acct';
import config from '../../../../conf';

/**
 * Create a post
 *
 * @param {any} params
 * @param {any} user
 * @param {any} app
 * @return {Promise<any>}
 */
module.exports = (params, user: IUser, app) => new Promise(async (res, rej) => {
	// Get 'text' parameter
	const [text, textErr] = $(params.text).optional.string().pipe(isValidText).$;
	if (textErr) return rej('invalid text');

	// Get 'cw' parameter
	const [cw, cwErr] = $(params.cw).optional.string().pipe(isValidCw).$;
	if (cwErr) return rej('invalid cw');

	// Get 'viaMobile' parameter
	const [viaMobile = false, viaMobileErr] = $(params.viaMobile).optional.boolean().$;
	if (viaMobileErr) return rej('invalid viaMobile');

	// Get 'tags' parameter
	const [tags = [], tagsErr] = $(params.tags).optional.array('string').unique().eachQ(t => t.range(1, 32)).$;
	if (tagsErr) return rej('invalid tags');

	// Get 'geo' parameter
	const [geo, geoErr] = $(params.geo).optional.nullable.strict.object()
		.have('coordinates', $().array().length(2)
			.item(0, $().number().range(-180, 180))
			.item(1, $().number().range(-90, 90)))
		.have('altitude', $().nullable.number())
		.have('accuracy', $().nullable.number())
		.have('altitudeAccuracy', $().nullable.number())
		.have('heading', $().nullable.number().range(0, 360))
		.have('speed', $().nullable.number())
		.$;
	if (geoErr) return rej('invalid geo');

	// Get 'mediaIds' parameter
	const [mediaIds, mediaIdsErr] = $(params.mediaIds).optional.array('id').unique().range(1, 4).$;
	if (mediaIdsErr) return rej('invalid mediaIds');

	let files = [];
	if (mediaIds !== undefined) {
		// Fetch files
		// forEach だと途中でエラーなどがあっても return できないので
		// 敢えて for を使っています。
		for (const mediaId of mediaIds) {
			// Fetch file
			// SELECT _id
			const entity = await DriveFile.findOne({
				_id: mediaId,
				'metadata.userId': user._id
			});

			if (entity === null) {
				return rej('file not found');
			} else {
				files.push(entity);
			}
		}
	} else {
		files = null;
	}

	// Get 'repostId' parameter
	const [repostId, repostIdErr] = $(params.repostId).optional.id().$;
	if (repostIdErr) return rej('invalid repostId');

	let repost: IPost = null;
	let isQuote = false;
	if (repostId !== undefined) {
		// Fetch repost to post
		repost = await Post.findOne({
			_id: repostId
		});

		if (repost == null) {
			return rej('repostee is not found');
		} else if (repost.repostId && !repost.text && !repost.mediaIds) {
			return rej('cannot repost to repost');
		}

		// Fetch recently post
		const latestPost = await Post.findOne({
			userId: user._id
		}, {
			sort: {
				_id: -1
			}
		});

		isQuote = text != null || files != null;

		// 直近と同じRepost対象かつ引用じゃなかったらエラー
		if (latestPost &&
			latestPost.repostId &&
			latestPost.repostId.equals(repost._id) &&
			!isQuote) {
			return rej('cannot repost same post that already reposted in your latest post');
		}

		// 直近がRepost対象かつ引用じゃなかったらエラー
		if (latestPost &&
			latestPost._id.equals(repost._id) &&
			!isQuote) {
			return rej('cannot repost your latest post');
		}
	}

	// Get 'replyId' parameter
	const [replyId, replyIdErr] = $(params.replyId).optional.id().$;
	if (replyIdErr) return rej('invalid replyId');

	let reply: IPost = null;
	if (replyId !== undefined) {
		// Fetch reply
		reply = await Post.findOne({
			_id: replyId
		});

		if (reply === null) {
			return rej('in reply to post is not found');
		}

		// 返信対象が引用でないRepostだったらエラー
		if (reply.repostId && !reply.text && !reply.mediaIds) {
			return rej('cannot reply to repost');
		}
	}

	// Get 'channelId' parameter
	const [channelId, channelIdErr] = $(params.channelId).optional.id().$;
	if (channelIdErr) return rej('invalid channelId');

	let channel: IChannel = null;
	if (channelId !== undefined) {
		// Fetch channel
		channel = await Channel.findOne({
			_id: channelId
		});

		if (channel === null) {
			return rej('channel not found');
		}

		// 返信対象の投稿がこのチャンネルじゃなかったらダメ
		if (reply && !channelId.equals(reply.channelId)) {
			return rej('チャンネル内部からチャンネル外部の投稿に返信することはできません');
		}

		// Repost対象の投稿がこのチャンネルじゃなかったらダメ
		if (repost && !channelId.equals(repost.channelId)) {
			return rej('チャンネル内部からチャンネル外部の投稿をRepostすることはできません');
		}

		// 引用ではないRepostはダメ
		if (repost && !isQuote) {
			return rej('チャンネル内部では引用ではないRepostをすることはできません');
		}
	} else {
		// 返信対象の投稿がチャンネルへの投稿だったらダメ
		if (reply && reply.channelId != null) {
			return rej('チャンネル外部からチャンネル内部の投稿に返信することはできません');
		}

		// Repost対象の投稿がチャンネルへの投稿だったらダメ
		if (repost && repost.channelId != null) {
			return rej('チャンネル外部からチャンネル内部の投稿をRepostすることはできません');
		}
	}

	// Get 'poll' parameter
	const [poll, pollErr] = $(params.poll).optional.strict.object()
		.have('choices', $().array('string')
			.unique()
			.range(2, 10)
			.each(c => c.length > 0 && c.length < 50))
		.$;
	if (pollErr) return rej('invalid poll');

	if (poll) {
		(poll as any).choices = (poll as any).choices.map((choice, i) => ({
			id: i, // IDを付与
			text: choice.trim(),
			votes: 0
		}));
	}

	// テキストが無いかつ添付ファイルが無いかつRepostも無いかつ投票も無かったらエラー
	if (text === undefined && files === null && repost === null && poll === undefined) {
		return rej('text, mediaIds, repostId or poll is required');
	}

	// 直近の投稿と重複してたらエラー
	// TODO: 直近の投稿が一日前くらいなら重複とは見なさない
	if (user.latestPost) {
		if (deepEqual({
			text: user.latestPost.text,
			reply: user.latestPost.replyId ? user.latestPost.replyId.toString() : null,
			repost: user.latestPost.repostId ? user.latestPost.repostId.toString() : null,
			mediaIds: (user.latestPost.mediaIds || []).map(id => id.toString())
		}, {
			text: text,
			reply: reply ? reply._id.toString() : null,
			repost: repost ? repost._id.toString() : null,
			mediaIds: (files || []).map(file => file._id.toString())
		})) {
			return rej('duplicate');
		}
	}

	let tokens = null;
	if (text) {
		// Analyze
		tokens = parse(text);

		// Extract hashtags
		const hashtags = tokens
			.filter(t => t.type == 'hashtag')
			.map(t => t.hashtag);

		hashtags.forEach(tag => {
			if (tags.indexOf(tag) == -1) {
				tags.push(tag);
			}
		});
	}

	// 投稿を作成
	const post = await Post.insert({
		createdAt: new Date(),
		channelId: channel ? channel._id : undefined,
		index: channel ? channel.index + 1 : undefined,
		mediaIds: files ? files.map(file => file._id) : [],
		replyId: reply ? reply._id : undefined,
		repostId: repost ? repost._id : undefined,
		poll: poll,
		text: text,
		textHtml: tokens === null ? null : html(tokens),
		cw: cw,
		tags: tags,
		userId: user._id,
		appId: app ? app._id : null,
		viaMobile: viaMobile,
		geo,

		// 以下非正規化データ
		_reply: reply ? { userId: reply.userId } : undefined,
		_repost: repost ? { userId: repost.userId } : undefined,
	});

	// Serialize
	const postObj = await pack(post);

	// Reponse
	res({
		createdPost: postObj
	});

	//#region Post processes

	User.update({ _id: user._id }, {
		$set: {
			latestPost: post
		}
	});

	const mentions = [];

	async function addMention(mentionee, reason) {
		// Reject if already added
		if (mentions.some(x => x.equals(mentionee))) return;

		// Add mention
		mentions.push(mentionee);

		// Publish event
		if (!user._id.equals(mentionee)) {
			const mentioneeMutes = await Mute.find({
				muterId: mentionee,
				deletedAt: { $exists: false }
			});
			const mentioneesMutedUserIds = mentioneeMutes.map(m => m.muteeId.toString());
			if (mentioneesMutedUserIds.indexOf(user._id.toString()) == -1) {
				event(mentionee, reason, postObj);
				pushSw(mentionee, reason, postObj);
			}
		}
	}

	// タイムラインへの投稿
	if (!channel) {
		// Publish event to myself's stream
		event(user._id, 'post', postObj);

		// Fetch all followers
		const followers = await Following
			.find({
				followeeId: user._id,
				// 削除されたドキュメントは除く
				deletedAt: { $exists: false }
			}, {
				followerId: true,
				_id: false
			});

		// Publish event to followers stream
		followers.forEach(following =>
			event(following.followerId, 'post', postObj));
	}

	// チャンネルへの投稿
	if (channel) {
		// Increment channel index(posts count)
		Channel.update({ _id: channel._id }, {
			$inc: {
				index: 1
			}
		});

		// Publish event to channel
		publishChannelStream(channel._id, 'post', postObj);

		// Get channel watchers
		const watches = await ChannelWatching.find({
			channelId: channel._id,
			// 削除されたドキュメントは除く
			deletedAt: { $exists: false }
		});

		// チャンネルの視聴者(のタイムライン)に配信
		watches.forEach(w => {
			event(w.userId, 'post', postObj);
		});
	}

	// Increment my posts count
	User.update({ _id: user._id }, {
		$inc: {
			postsCount: 1
		}
	});

	// If has in reply to post
	if (reply) {
		// Increment replies count
		Post.update({ _id: reply._id }, {
			$inc: {
				repliesCount: 1
			}
		});

		// 自分自身へのリプライでない限りは通知を作成
		notify(reply.userId, user._id, 'reply', {
			postId: post._id
		});

		// Fetch watchers
		Watching
			.find({
				postId: reply._id,
				userId: { $ne: user._id },
				// 削除されたドキュメントは除く
				deletedAt: { $exists: false }
			}, {
				fields: {
					userId: true
				}
			})
			.then(watchers => {
				watchers.forEach(watcher => {
					notify(watcher.userId, user._id, 'reply', {
						postId: post._id
					});
				});
			});

		// この投稿をWatchする
		if ((user.account as ILocalAccount).settings.autoWatch !== false) {
			watch(user._id, reply);
		}

		// Add mention
		addMention(reply.userId, 'reply');
	}

	// If it is repost
	if (repost) {
		// Notify
		const type = text ? 'quote' : 'repost';
		notify(repost.userId, user._id, type, {
			postId: post._id
		});

		// Fetch watchers
		Watching
			.find({
				postId: repost._id,
				userId: { $ne: user._id },
				// 削除されたドキュメントは除く
				deletedAt: { $exists: false }
			}, {
				fields: {
					userId: true
				}
			})
			.then(watchers => {
				watchers.forEach(watcher => {
					notify(watcher.userId, user._id, type, {
						postId: post._id
					});
				});
			});

		// この投稿をWatchする
		// TODO: ユーザーが「Repostしたときに自動でWatchする」設定を
		//       オフにしていた場合はしない
		watch(user._id, repost);

		// If it is quote repost
		if (text) {
			// Add mention
			addMention(repost.userId, 'quote');
		} else {
			// Publish event
			if (!user._id.equals(repost.userId)) {
				event(repost.userId, 'repost', postObj);
			}
		}

		// 今までで同じ投稿をRepostしているか
		const existRepost = await Post.findOne({
			userId: user._id,
			repostId: repost._id,
			_id: {
				$ne: post._id
			}
		});

		if (!existRepost) {
			// Update repostee status
			Post.update({ _id: repost._id }, {
				$inc: {
					repostCount: 1
				}
			});
		}
	}

	// If has text content
	if (text) {
		/*
				// Extract a hashtags
				const hashtags = tokens
					.filter(t => t.type == 'hashtag')
					.map(t => t.hashtag)
					// Drop dupulicates
					.filter((v, i, s) => s.indexOf(v) == i);

				// ハッシュタグをデータベースに登録
				registerHashtags(user, hashtags);
		*/
		// Extract an '@' mentions
		const atMentions = tokens
			.filter(t => t.type == 'mention')
			.map(getAcct)
			// Drop dupulicates
			.filter((v, i, s) => s.indexOf(v) == i);

		// Resolve all mentions
		await Promise.all(atMentions.map(async (mention) => {
			// Fetch mentioned user
			// SELECT _id
			const mentionee = await User
				.findOne(parseAcct(mention), { _id: true });

			// When mentioned user not found
			if (mentionee == null) return;

			// 既に言及されたユーザーに対する返信や引用repostの場合も無視
			if (reply && reply.userId.equals(mentionee._id)) return;
			if (repost && repost.userId.equals(mentionee._id)) return;

			// Add mention
			addMention(mentionee._id, 'mention');

			// Create notification
			notify(mentionee._id, user._id, 'mention', {
				postId: post._id
			});

			return;
		}));
	}

	// Register to search database
	if (text && config.elasticsearch.enable) {
		const es = require('../../../db/elasticsearch');

		es.index({
			index: 'misskey',
			type: 'post',
			id: post._id.toString(),
			body: {
				text: post.text
			}
		});
	}

	// Append mentions data
	if (mentions.length > 0) {
		Post.update({ _id: post._id }, {
			$set: {
				mentions: mentions
			}
		});
	}

	//#endregion
});