summaryrefslogtreecommitdiff
path: root/src/api/endpoints/posts/search.ts
blob: a3c44d09cee196225c9e03bb97def27c2d549a9d (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
/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import $ from 'cafy';
const escapeRegexp = require('escape-regexp');
import Post from '../../models/post';
import User from '../../models/user';
import getFriends from '../../common/get-friends';
import serialize from '../../serializers/post';
import config from '../../../conf';

/**
 * Search a post
 *
 * @param {any} params
 * @param {any} me
 * @return {Promise<any>}
 */
module.exports = (params, me) => new Promise(async (res, rej) => {
	// Get 'text' parameter
	const [text, textError] = $(params.text).optional.string().$;
	if (textError) return rej('invalid text param');

	// Get 'user_id' parameter
	const [userId, userIdErr] = $(params.user_id).optional.id().$;
	if (userIdErr) return rej('invalid user_id param');

	// Get 'username' parameter
	const [username, usernameErr] = $(params.username).optional.string().$;
	if (usernameErr) return rej('invalid username param');

	// Get 'following' parameter
	const [following = null, followingErr] = $(params.following).optional.nullable.boolean().$;
	if (followingErr) return rej('invalid following param');

	// Get 'reply' parameter
	const [reply = null, replyErr] = $(params.reply).optional.nullable.boolean().$;
	if (replyErr) return rej('invalid reply param');

	// Get 'repost' parameter
	const [repost = null, repostErr] = $(params.repost).optional.nullable.boolean().$;
	if (repostErr) return rej('invalid repost param');

	// Get 'media' parameter
	const [media = null, mediaErr] = $(params.media).optional.nullable.boolean().$;
	if (mediaErr) return rej('invalid media param');

	// Get 'since_date' parameter
	const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$;
	if (sinceDateErr) throw 'invalid since_date param';

	// Get 'until_date' parameter
	const [untilDate, untilDateErr] = $(params.until_date).optional.number().$;
	if (untilDateErr) throw 'invalid until_date param';

	// Get 'offset' parameter
	const [offset = 0, offsetErr] = $(params.offset).optional.number().min(0).$;
	if (offsetErr) return rej('invalid offset param');

	// Get 'limit' parameter
	const [limit = 10, limitErr] = $(params.limit).optional.number().range(1, 30).$;
	if (limitErr) return rej('invalid limit param');

	let user = userId;

	if (user == null && username != null) {
		const _user = await User.findOne({
			username_lower: username.toLowerCase()
		});
		if (_user) {
			user = _user._id;
		}
	}

	// If Elasticsearch is available, search by it
	// If not, search by MongoDB
	(config.elasticsearch.enable ? byElasticsearch : byNative)
		(res, rej, me, text, user, following, reply, repost, media, sinceDate, untilDate, offset, limit);
});

// Search by MongoDB
async function byNative(res, rej, me, text, userId, following, reply, repost, media, sinceDate, untilDate, offset, max) {
	const q: any = {
		$and: []
	};

	const push = x => q.$and.push(x);

	if (text) {
		push({
			$and: text.split(' ').map(x => ({
				text: new RegExp(escapeRegexp(x))
			}))
		});
	}

	if (userId) {
		push({
			user_id: userId
		});
	}

	if (following != null) {
		const ids = await getFriends(me._id, false);
		push({
			user_id: following ? {
				$in: ids
			} : {
				$nin: ids
			}
		});
	}

	if (reply != null) {
		if (reply) {
			push({
				reply_id: {
					$exists: true,
					$ne: null
				}
			});
		} else {
			push({
				$or: [{
					reply_id: {
						$exists: false
					}
				}, {
					reply_id: null
				}]
			});
		}
	}

	if (repost != null) {
		if (repost) {
			push({
				repost_id: {
					$exists: true,
					$ne: null
				}
			});
		} else {
			push({
				$or: [{
					repost_id: {
						$exists: false
					}
				}, {
					repost_id: null
				}]
			});
		}
	}

	if (media != null) {
		if (media) {
			push({
				media_ids: {
					$exists: true,
					$ne: null
				}
			});
		} else {
			push({
				$or: [{
					media_ids: {
						$exists: false
					}
				}, {
					media_ids: null
				}]
			});
		}
	}

	if (sinceDate) {
		push({
			created_at: {
				$gt: new Date(sinceDate)
			}
		});
	}

	if (untilDate) {
		push({
			created_at: {
				$lt: new Date(untilDate)
			}
		});
	}

	// Search posts
	const posts = await Post
		.find(q, {
			sort: {
				_id: -1
			},
			limit: max,
			skip: offset
		});

	// Serialize
	res(await Promise.all(posts.map(async post =>
		await serialize(post, me))));
}

// Search by Elasticsearch
async function byElasticsearch(res, rej, me, text, userId, following, reply, repost, media, sinceDate, untilDate, offset, max) {
	const es = require('../../db/elasticsearch');

	es.search({
		index: 'misskey',
		type: 'post',
		body: {
			size: max,
			from: offset,
			query: {
				simple_query_string: {
					fields: ['text'],
					query: text,
					default_operator: 'and'
				}
			},
			sort: [
				{ _doc: 'desc' }
			],
			highlight: {
				pre_tags: ['<mark>'],
				post_tags: ['</mark>'],
				encoder: 'html',
				fields: {
					text: {}
				}
			}
		}
	}, async (error, response) => {
		if (error) {
			console.error(error);
			return res(500);
		}

		if (response.hits.total === 0) {
			return res([]);
		}

		const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id));

		// Fetch found posts
		const posts = await Post
			.find({
				_id: {
					$in: hits
				}
			}, {
				sort: {
					_id: -1
				}
			});

		posts.map(post => {
			post._highlight = response.hits.hits.filter(hit => post._id.equals(hit._id))[0].highlight.text[0];
		});

		// Serialize
		res(await Promise.all(posts.map(async post =>
			await serialize(post, me))));
	});
}