forked from PretendoNetwork/juxtaposition
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.ts
More file actions
447 lines (381 loc) · 12.1 KB
/
Copy pathposts.ts
File metadata and controls
447 lines (381 loc) · 12.1 KB
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
import express from 'express';
import multer from 'multer';
import xmlbuilder from 'xmlbuilder';
import * as z from 'zod';
import {
getValueFromQueryString,
getInvalidPostRegex
} from '@/util';
import {
getPostByID,
getUserContent,
getPostReplies,
getUserSettings,
getCommunityByID,
getCommunityByTitleID,
getDuplicatePosts
} from '@/database';
import { Post } from '@/models/post';
import { Community } from '@/models/community';
import { config } from '@/config';
import { ApiErrorCode, badRequest, serverError } from '@/errors';
import { uploadPainting, uploadScreenshot } from '@/images';
import type { GetUserDataResponse } from '@pretendonetwork/grpc/account/get_user_data_rpc';
import type { PostRepliesResult } from '@/types/miiverse/post';
import type { HydratedPostDocument, IPostInput } from '@/types/mongoose/post';
import type { HydratedCommunityDocument } from '@/types/mongoose/community';
import type { HydratedSettingsDocument } from '@/types/mongoose/settings';
const newPostSchema = z.object({
community_id: z.string().optional(),
app_data: z.string().optional(),
painting: z.string().optional(),
screenshot: z.string().optional(),
body: z.string().optional(),
feeling_id: z.string(),
search_key: z.string().array().or(z.string()).optional(),
topic_tag: z.string().optional(),
is_autopost: z.string(),
is_spoiler: z.string().optional(),
is_app_jumpable: z.string().optional(),
language_id: z.string()
});
const router = express.Router();
const upload = multer();
/* GET post titles. */
router.post('/', upload.none(), newPost);
router.post('/:post_id/replies', upload.none(), newPost);
router.post('/:post_id.delete', async function (request: express.Request, response: express.Response): Promise<void> {
response.type('application/xml');
const post = await getPostByID(request.params.post_id);
const userContent = await getUserContent(request.pid);
if (!post || !userContent) {
return badRequest(response, ApiErrorCode.FAIL_NOT_FOUND_POST, 404);
}
if (post.pid !== userContent.pid) {
return badRequest(response, ApiErrorCode.NOT_ALLOWED, 403);
}
await post.del('User requested removal', request.pid);
response.sendStatus(200);
});
router.post('/:post_id/empathies', upload.none(), async function (request: express.Request, response: express.Response): Promise<void> {
response.type('application/xml');
const post = await getPostByID(request.params.post_id);
if (!post) {
return badRequest(response, ApiErrorCode.FAIL_NOT_FOUND_POST, 404);
}
if (post.yeahs?.indexOf(request.pid) === -1) {
await Post.updateOne({
id: post.id,
yeahs: {
$ne: request.pid
}
},
{
$inc: {
empathy_count: 1
},
$push: {
yeahs: request.pid
}
});
} else if (post.yeahs?.indexOf(request.pid) !== -1) {
await Post.updateOne({
id: post.id,
yeahs: {
$eq: request.pid
}
},
{
$inc: {
empathy_count: -1
},
$pull: {
yeahs: request.pid
}
});
}
response.sendStatus(200);
});
router.get('/:post_id/replies', async function (request: express.Request, response: express.Response): Promise<void> {
response.type('application/xml');
const limitString = getValueFromQueryString(request.query, 'limit')[0];
let limit = 10; // TODO - Is there a real limit?
if (limitString) {
limit = parseInt(limitString);
}
if (isNaN(limit)) {
limit = 10;
}
const post = await getPostByID(request.params.post_id);
if (!post) {
return badRequest(response, ApiErrorCode.FAIL_NOT_FOUND_POST, 404);
}
const posts = await getPostReplies(post.id, limit);
if (posts.length === 0) {
request.log.warn('Post has no replies');
return badRequest(response, ApiErrorCode.FAIL_NOT_FOUND_POST, 404);
}
const result: PostRepliesResult = {
has_error: 0,
version: 1,
request_name: 'replies',
posts: []
};
for (const post of posts) {
result.posts.push({
post: post.json({
with_mii: request.query.with_mii as string === '1',
topic_tag: true
})
});
}
response.send(xmlbuilder.create({
result
}, {
separateArrayItems: true
}).end({
pretty: true,
allowEmpty: true
}));
});
router.get('/', async function (request: express.Request, response: express.Response): Promise<void> {
response.type('application/xml');
const postID = getValueFromQueryString(request.query, 'post_id')[0];
if (!postID) {
request.log.warn('Post ID wasn\'t provided');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
const post = await getPostByID(postID);
if (!post) {
return badRequest(response, ApiErrorCode.FAIL_NOT_FOUND_POST, 404);
}
response.send(xmlbuilder.create({
result: {
has_error: '0',
version: '1',
request_name: 'posts.search',
posts: {
post: post.json({ with_mii: true })
}
}
}).end({ pretty: true, allowEmpty: true }));
});
function canPost(community: HydratedCommunityDocument, userSettings: HydratedSettingsDocument, parentPost: HydratedPostDocument | null, user: GetUserDataResponse): boolean {
const isReply = !!parentPost;
const isPublicPostableCommunity = community.type >= 0 && community.type < 2;
const isOpenCommunity = community.permissions.open;
const isCommunityAdmin = (community.admins ?? []).includes(user.pid);
const isUserLimitedFromPosting = userSettings.account_status !== 0;
const hasAccessLevelRequirement = isReply
? user.accessLevel >= community.permissions.minimum_new_comment_access_level
: user.accessLevel >= community.permissions.minimum_new_post_access_level;
if (isUserLimitedFromPosting) {
return false;
}
if (isCommunityAdmin) {
return true; // admins can always post (if not limited)
}
if (!hasAccessLevelRequirement) {
return false;
}
return isReply ? isOpenCommunity : isPublicPostableCommunity;
}
async function newPost(request: express.Request, response: express.Response): Promise<void> {
response.type('application/xml');
if (!request.user) {
return serverError(response, ApiErrorCode.ACCOUNT_SERVER_ERROR);
}
if (!request.user.mii) {
// * This should never happen, but TypeScript complains so check anyway
// TODO - Better errors
request.log.warn('Mii does not exist or is invalid');
return serverError(response, ApiErrorCode.ACCOUNT_SERVER_ERROR);
}
const userSettings = await getUserSettings(request.pid);
const bodyCheck = newPostSchema.safeParse(request.body);
if (!userSettings || !bodyCheck.success) {
request.log.warn('Body check failed');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
const communityID = bodyCheck.data.community_id || '';
const messageBody = bodyCheck.data.body?.trim();
const painting = bodyCheck.data.painting?.replace(/\0/g, '').trim() || '';
const screenshot = bodyCheck.data.screenshot?.replace(/\0/g, '').trim() || '';
const appData = bodyCheck.data.app_data?.replace(/[^A-Za-z0-9+/=\s]/g, '').trim() || '';
const feelingID = parseInt(bodyCheck.data.feeling_id);
let searchKey = bodyCheck.data.search_key || [];
const topicTag = bodyCheck.data.topic_tag || '';
const autopost = bodyCheck.data.is_autopost;
const spoiler = bodyCheck.data.is_spoiler;
const jumpable = bodyCheck.data.is_app_jumpable;
const languageID = parseInt(bodyCheck.data.language_id);
const countryID = parseInt(request.paramPack.country_id);
const platformID = parseInt(request.paramPack.platform_id);
const regionID = parseInt(request.paramPack.region_id);
if (
isNaN(feelingID) ||
isNaN(languageID) ||
isNaN(countryID) ||
isNaN(platformID) ||
isNaN(regionID)
) {
request.log.warn('Parameters are NaN');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
let community = await getCommunityByID(communityID);
if (!community) {
community = await Community.findOne({
olive_community_id: communityID
});
}
if (!community) {
community = await getCommunityByTitleID(request.paramPack.title_id);
}
let parentPost: HydratedPostDocument | null = null;
if (request.params.post_id) {
parentPost = await getPostByID(request.params.post_id.toString());
if (!parentPost) {
request.log.warn('Request missing parent post');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
} else {
community = await getCommunityByID(parentPost.community_id);
if (!community) {
community = await Community.findOne({
olive_community_id: parentPost.community_id
});
}
if (parentPost.removed) {
request.log.warn('Request wants to reply to parent post, but parent post has been removed');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
}
}
if (!community || userSettings.account_status !== 0 || community.community_id === 'announcements') {
return badRequest(response, ApiErrorCode.NOT_FOUND_COMMUNITY, 404);
}
if (!canPost(community, userSettings, parentPost, request.user)) {
return badRequest(response, ApiErrorCode.NOT_ALLOWED, 403);
}
let miiFace = 'normal_face.png';
switch (parseInt(request.body.feeling_id)) {
case 1:
miiFace = 'smile_open_mouth.png';
break;
case 2:
miiFace = 'wink_left.png';
break;
case 3:
miiFace = 'surprise_open_mouth.png';
break;
case 4:
miiFace = 'frustrated.png';
break;
case 5:
miiFace = 'sorrow.png';
break;
}
if (messageBody && getInvalidPostRegex().test(messageBody)) {
request.log.warn('Message body failed regex');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
if (messageBody && messageBody.length > 280) {
request.log.warn('Message body too long');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
if (!messageBody && !painting && !screenshot) {
request.log.warn('Message content is empty');
return badRequest(response, ApiErrorCode.BAD_PARAMS);
}
if (!Array.isArray(searchKey)) {
searchKey = [searchKey];
}
const document: IPostInput = {
id: '', // * This gets changed when saving the document for the first time
title_id: request.paramPack.title_id,
community_id: community.olive_community_id,
screen_name: userSettings.screen_name,
body: messageBody ? messageBody : '',
app_data: appData,
painting: '',
painting_img: '',
painting_big: '',
screenshot: '',
screenshot_big: '',
screenshot_thumb: '',
screenshot_aspect: '',
screenshot_length: 0,
country_id: countryID,
created_at: new Date(),
feeling_id: feelingID,
search_key: searchKey,
topic_tag: topicTag,
is_autopost: (autopost) ? 1 : 0,
is_spoiler: (spoiler === '1') ? 1 : 0,
is_app_jumpable: (jumpable) ? 1 : 0,
language_id: languageID,
mii: request.user.mii.data,
mii_face_url: `${config.cdnUrl}/mii/${request.user.pid}/${miiFace}`,
pid: request.pid,
platform_id: platformID,
region_id: regionID,
verified: (request.user.accessLevel === 2 || request.user.accessLevel === 3),
parent: parentPost ? parentPost.id : null,
removed: false
};
const duplicatePost = await getDuplicatePosts(request.pid, document);
if (duplicatePost) {
return badRequest(response, ApiErrorCode.NOT_ALLOWED_SPAM, 403);
}
const post = await Post.create(document);
if (painting) {
const paintings = await uploadPainting({
blob: painting,
autodetectFormat: true,
isBmp: false,
pid: post.pid,
postId: post.id
});
if (paintings === null) {
// The document we already submitted to the db is invalid, so drop it.
post.deleteOne();
return serverError(response, ApiErrorCode.DATABASE_ERROR);
}
post.painting = paintings.blob;
post.painting_img = paintings.img;
post.painting_big = paintings.big;
}
if (screenshot) {
const screenshotUrls = await uploadScreenshot({
blob: screenshot,
pid: post.pid,
postId: post.id
});
if (screenshotUrls === null) {
// The document we already submitted to the db is invalid, so drop it.
post.deleteOne();
return serverError(response, ApiErrorCode.DATABASE_ERROR);
}
post.screenshot = screenshotUrls.full;
post.screenshot_big = screenshotUrls.big ?? '';
post.screenshot_length = screenshotUrls.fullLength;
post.screenshot_thumb = screenshotUrls.thumb;
post.screenshot_aspect = screenshotUrls.aspect;
}
if (post.isModified()) {
await post.save();
}
if (parentPost) {
parentPost.reply_count = (parentPost.reply_count || 0) + 1;
parentPost.save();
}
response.send(xmlbuilder.create({
result: {
has_error: '0',
version: '1',
post: {
post: post.json({ with_mii: true })
}
}
}).end({ pretty: true, allowEmpty: true }));
}
export default router;