summaryrefslogtreecommitdiff
path: root/src/models/user.ts
blob: 31d09bc8f829231cf52eaaa2653137e363c5bcd0 (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
import * as mongo from 'mongodb';
const deepcopy = require('deepcopy');
const sequential = require('promise-sequential');
import rap from '@prezzemolo/rap';
import db from '../db/mongodb';
import Note, { pack as packNote, deleteNote } from './note';
import Following, { deleteFollowing } from './following';
import Mute, { deleteMute } from './mute';
import { getFriendIds } from '../server/api/common/get-friends';
import config from '../config';
import AccessToken, { deleteAccessToken } from './access-token';
import NoteWatching, { deleteNoteWatching } from './note-watching';
import Favorite, { deleteFavorite } from './favorite';
import NoteReaction, { deleteNoteReaction } from './note-reaction';
import MessagingMessage, { deleteMessagingMessage } from './messaging-message';
import MessagingHistory, { deleteMessagingHistory } from './messaging-history';
import DriveFile, { deleteDriveFile } from './drive-file';
import DriveFolder, { deleteDriveFolder } from './drive-folder';
import PollVote, { deletePollVote } from './poll-vote';
import FollowingLog, { deleteFollowingLog } from './following-log';
import FollowedLog, { deleteFollowedLog } from './followed-log';
import SwSubscription, { deleteSwSubscription } from './sw-subscription';
import Notification, { deleteNotification } from './notification';
import UserList, { deleteUserList } from './user-list';
import FollowRequest, { deleteFollowRequest } from './follow-request';

const User = db.get<IUser>('users');

User.createIndex('username');
User.createIndex('usernameLower');
User.createIndex(['username', 'host'], { unique: true });
User.createIndex(['usernameLower', 'host'], { unique: true });
User.createIndex('token', { sparse: true, unique: true });
User.createIndex('uri', { sparse: true, unique: true });

export default User;

type IUserBase = {
	_id: mongo.ObjectID;
	createdAt: Date;
	deletedAt?: Date;
	followersCount: number;
	followingCount: number;
	name?: string;
	notesCount: number;
	username: string;
	usernameLower: string;
	avatarId: mongo.ObjectID;
	bannerId: mongo.ObjectID;
	avatarUrl?: string;
	bannerUrl?: string;
	wallpaperId: mongo.ObjectID;
	wallpaperUrl?: string;
	data: any;
	description: string;
	pinnedNoteId: mongo.ObjectID;

	/**
	 * 凍結されているか否か
	 */
	isSuspended: boolean;

	/**
	 * 鍵アカウントか否か
	 */
	isLocked: boolean;

	/**
	 * このアカウントに届いているフォローリクエストの数
	 */
	pendingReceivedFollowRequestsCount: number;

	host: string;
};

export interface ILocalUser extends IUserBase {
	host: null;
	keypair: string;
	email: string;
	password: string;
	token: string;
	twitter: {
		accessToken: string;
		accessTokenSecret: string;
		userId: string;
		screenName: string;
	};
	line: {
		userId: string;
	};
	profile: {
		location: string;
		birthday: string; // 'YYYY-MM-DD'
		tags: string[];
	};
	lastUsedAt: Date;
	isBot: boolean;
	isCat: boolean;
	isAdmin?: boolean;
	isVerified?: boolean;
	twoFactorSecret: string;
	twoFactorEnabled: boolean;
	twoFactorTempSecret?: string;
	clientSettings: any;
	settings: any;
	hasUnreadNotification: boolean;
	hasUnreadMessagingMessage: boolean;
}

export interface IRemoteUser extends IUserBase {
	inbox: string;
	sharedInbox?: string;
	endpoints: string[];
	uri: string;
	url?: string;
	publicKey: {
		id: string;
		publicKeyPem: string;
	};
	updatedAt: Date;
	isAdmin: false;
}

export type IUser = ILocalUser | IRemoteUser;

export const isLocalUser = (user: any): user is ILocalUser =>
	user.host === null;

export const isRemoteUser = (user: any): user is IRemoteUser =>
	!isLocalUser(user);

//#region Validators
export function validateUsername(username: string): boolean {
	return typeof username == 'string' && /^[a-zA-Z0-9_]{1,20}$/.test(username);
}

export function validatePassword(password: string): boolean {
	return typeof password == 'string' && password != '';
}

export function isValidName(name?: string): boolean {
	return name === null || (typeof name == 'string' && name.length < 50 && name.trim() != '');
}

export function isValidDescription(description: string): boolean {
	return typeof description == 'string' && description.length < 500 && description.trim() != '';
}

export function isValidLocation(location: string): boolean {
	return typeof location == 'string' && location.length < 50 && location.trim() != '';
}

export function isValidBirthday(birthday: string): boolean {
	return typeof birthday == 'string' && /^([0-9]{4})\-([0-9]{2})-([0-9]{2})$/.test(birthday);
}
//#endregion

/**
 * Userを物理削除します
 */
export async function deleteUser(user: string | mongo.ObjectID | IUser) {
	let u: IUser;

	// Populate
	if (mongo.ObjectID.prototype.isPrototypeOf(user)) {
		u = await User.findOne({
			_id: user
		});
	} else if (typeof user === 'string') {
		u = await User.findOne({
			_id: new mongo.ObjectID(user)
		});
	} else {
		u = user as IUser;
	}

	console.log(u == null ? `User: delete skipped ${user}` : `User: deleting ${u._id}`);

	if (u == null) return;

	// このユーザーのAccessTokenをすべて削除
	await Promise.all((
		await AccessToken.find({ userId: u._id })
	).map(x => deleteAccessToken(x)));

	// このユーザーのNoteをすべて削除
	await sequential((
		await Note.find({ userId: u._id })
	).map(x => () => deleteNote(x)));

	// このユーザーのNoteReactionをすべて削除
	await Promise.all((
		await NoteReaction.find({ userId: u._id })
	).map(x => deleteNoteReaction(x)));

	// このユーザーのNoteWatchingをすべて削除
	await Promise.all((
		await NoteWatching.find({ userId: u._id })
	).map(x => deleteNoteWatching(x)));

	// このユーザーのPollVoteをすべて削除
	await Promise.all((
		await PollVote.find({ userId: u._id })
	).map(x => deletePollVote(x)));

	// このユーザーのFavoriteをすべて削除
	await Promise.all((
		await Favorite.find({ userId: u._id })
	).map(x => deleteFavorite(x)));

	// このユーザーのMessageをすべて削除
	await Promise.all((
		await MessagingMessage.find({ userId: u._id })
	).map(x => deleteMessagingMessage(x)));

	// このユーザーへのMessageをすべて削除
	await Promise.all((
		await MessagingMessage.find({ recipientId: u._id })
	).map(x => deleteMessagingMessage(x)));

	// このユーザーの関わるMessagingHistoryをすべて削除
	await Promise.all((
		await MessagingHistory.find({ $or: [{ partnerId: u._id }, { userId: u._id }] })
	).map(x => deleteMessagingHistory(x)));

	// このユーザーのDriveFileをすべて削除
	await Promise.all((
		await DriveFile.find({ 'metadata.userId': u._id })
	).map(x => deleteDriveFile(x)));

	// このユーザーのDriveFolderをすべて削除
	await Promise.all((
		await DriveFolder.find({ userId: u._id })
	).map(x => deleteDriveFolder(x)));

	// このユーザーのMuteをすべて削除
	await Promise.all((
		await Mute.find({ muterId: u._id })
	).map(x => deleteMute(x)));

	// このユーザーへのMuteをすべて削除
	await Promise.all((
		await Mute.find({ muteeId: u._id })
	).map(x => deleteMute(x)));

	// このユーザーのFollowingをすべて削除
	await Promise.all((
		await Following.find({ followerId: u._id })
	).map(x => deleteFollowing(x)));

	// このユーザーへのFollowingをすべて削除
	await Promise.all((
		await Following.find({ followeeId: u._id })
	).map(x => deleteFollowing(x)));

	// このユーザーのFollowRequestをすべて削除
	await Promise.all((
		await FollowRequest.find({ followerId: u._id })
	).map(x => deleteFollowRequest(x)));

	// このユーザーへのFollowRequestをすべて削除
	await Promise.all((
		await FollowRequest.find({ followeeId: u._id })
	).map(x => deleteFollowRequest(x)));

	// このユーザーのFollowingLogをすべて削除
	await Promise.all((
		await FollowingLog.find({ userId: u._id })
	).map(x => deleteFollowingLog(x)));

	// このユーザーのFollowedLogをすべて削除
	await Promise.all((
		await FollowedLog.find({ userId: u._id })
	).map(x => deleteFollowedLog(x)));

	// このユーザーのSwSubscriptionをすべて削除
	await Promise.all((
		await SwSubscription.find({ userId: u._id })
	).map(x => deleteSwSubscription(x)));

	// このユーザーのNotificationをすべて削除
	await Promise.all((
		await Notification.find({ notifieeId: u._id })
	).map(x => deleteNotification(x)));

	// このユーザーが原因となったNotificationをすべて削除
	await Promise.all((
		await Notification.find({ notifierId: u._id })
	).map(x => deleteNotification(x)));

	// このユーザーのUserListをすべて削除
	await Promise.all((
		await UserList.find({ userId: u._id })
	).map(x => deleteUserList(x)));

	// このユーザーが入っているすべてのUserListからこのユーザーを削除
	await Promise.all((
		await UserList.find({ userIds: u._id })
	).map(x =>
		UserList.update({ _id: x._id }, {
			$pull: { userIds: u._id }
		})
	));

	// このユーザーを削除
	await User.remove({
		_id: u._id
	});

	console.log(`User: deleted ${u._id}`);
}

/**
 * Pack a user for API response
 *
 * @param user target
 * @param me? serializee
 * @param options? serialize options
 * @return Packed user
 */
export const pack = (
	user: string | mongo.ObjectID | IUser,
	me?: string | mongo.ObjectID | IUser,
	options?: {
		detail?: boolean,
		includeSecrets?: boolean
	}
) => new Promise<any>(async (resolve, reject) => {

	const opts = Object.assign({
		detail: false,
		includeSecrets: false
	}, options);

	let _user: any;

	const fields = opts.detail ? {
	} : {
		settings: false,
		clientSettings: false,
		profile: false,
		keywords: false,
		domains: false
	};

	// Populate the user if 'user' is ID
	if (mongo.ObjectID.prototype.isPrototypeOf(user)) {
		_user = await User.findOne({
			_id: user
		}, { fields });
	} else if (typeof user === 'string') {
		_user = await User.findOne({
			_id: new mongo.ObjectID(user)
		}, { fields });
	} else {
		_user = deepcopy(user);
	}

	// TODO: ここでエラーにするのではなくダミーのユーザーデータを返す
	// SEE: https://github.com/syuilo/misskey/issues/1432
	if (!_user) return reject('invalid user arg.');

	// Me
	const meId: mongo.ObjectID = me
		? mongo.ObjectID.prototype.isPrototypeOf(me)
			? me as mongo.ObjectID
			: typeof me === 'string'
				? new mongo.ObjectID(me)
				: (me as IUser)._id
		: null;

	// Rename _id to id
	_user.id = _user._id;
	delete _user._id;

	if (_user.host == null) {
		// Remove private properties
		delete _user.keypair;
		delete _user.password;
		delete _user.token;
		delete _user.twoFactorTempSecret;
		delete _user.twoFactorSecret;
		delete _user.usernameLower;
		if (_user.twitter) {
			delete _user.twitter.accessToken;
			delete _user.twitter.accessTokenSecret;
		}
		delete _user.line;

		// Visible via only the official client
		if (!opts.includeSecrets) {
			delete _user.email;
			delete _user.settings;
			delete _user.clientSettings;
		}

		if (!opts.detail) {
			delete _user.twoFactorEnabled;
		}
	} else {
		delete _user.publicKey;
	}

	if (_user.avatarUrl == null) {
		_user.avatarUrl = `${config.drive_url}/default-avatar.jpg`;

		// 互換性のため
		if (_user.avatarId) {
			_user.avatarUrl = `${config.drive_url}/${_user.avatarId}`;
		}
	}

	// 互換性のため
	if (_user.bannerId && _user.bannerUrl == null) {
		_user.bannerUrl = `${config.drive_url}/${_user.bannerId}`;
	}

	if (!meId || !meId.equals(_user.id) || !opts.detail) {
		delete _user.avatarId;
		delete _user.bannerId;
		delete _user.hasUnreadMessagingMessage;
		delete _user.hasUnreadNotification;
	}

	if (meId && !meId.equals(_user.id)) {
		const [following1, following2, followReq1, followReq2, mute] = await Promise.all([
			Following.findOne({
				followerId: meId,
				followeeId: _user.id
			}),
			Following.findOne({
				followerId: _user.id,
				followeeId: meId
			}),
			_user.isLocked ? FollowRequest.findOne({
				followerId: meId,
				followeeId: _user.id
			}) : Promise.resolve(null),
			FollowRequest.findOne({
				followerId: _user.id,
				followeeId: meId
			}),
			Mute.findOne({
				muterId: meId,
				muteeId: _user.id
			})
		]);

		// Whether the user is following
		_user.isFollowing = following1 !== null;
		_user.isStalking = following1 && following1.stalk;

		_user.hasPendingFollowRequestFromYou = followReq1 !== null;
		_user.hasPendingFollowRequestToYou = followReq2 !== null;

		// Whether the user is followed
		_user.isFollowed = following2 !== null;

		// Whether the user is muted
		_user.isMuted = mute !== null;
	}

	if (opts.detail) {
		if (_user.pinnedNoteId) {
			// Populate pinned note
			_user.pinnedNote = packNote(_user.pinnedNoteId, meId, {
				detail: true
			});
		}

		if (meId && !meId.equals(_user.id)) {
			const myFollowingIds = await getFriendIds(meId);

			// Get following you know count
			_user.followingYouKnowCount = Following.count({
				followeeId: { $in: myFollowingIds },
				followerId: _user.id
			});

			// Get followers you know count
			_user.followersYouKnowCount = Following.count({
				followeeId: _user.id,
				followerId: { $in: myFollowingIds }
			});
		}
	}

	// resolve promises in _user object
	_user = await rap(_user);

	resolve(_user);
});

/*
function img(url) {
	return {
		thumbnail: {
			large: `${url}`,
			medium: '',
			small: ''
		}
	};
}
*/

export function getGhost(): Promise<ILocalUser> {
	return User.findOne({ _id: new mongo.ObjectId(config.ghost) });
}