jormungandr-bite/src/models/user.ts

518 lines
13 KiB
TypeScript
Raw Normal View History

2017-09-07 13:13:01 -06:00
import * as mongo from 'mongodb';
2018-06-17 18:54:53 -06:00
const deepcopy = require('deepcopy');
2018-06-17 23:28:43 -06:00
const sequential = require('promise-sequential');
2018-02-01 16:06:01 -07:00
import rap from '@prezzemolo/rap';
2018-03-29 05:32:18 -06:00
import db from '../db/mongodb';
2018-04-17 07:33:27 -06:00
import Note, { pack as packNote, deleteNote } from './note';
2018-04-11 16:13:15 -06:00
import Following, { deleteFollowing } from './following';
2018-04-11 14:50:45 -06:00
import Mute, { deleteMute } from './mute';
2018-04-18 21:43:25 -06:00
import { getFriendIds } from '../server/api/common/get-friends';
2018-04-01 22:15:53 -06:00
import config from '../config';
2018-04-11 12:46:32 -06:00
import AccessToken, { deleteAccessToken } from './access-token';
import NoteWatching, { deleteNoteWatching } from './note-watching';
import Favorite, { deleteFavorite } from './favorite';
import NoteReaction, { deleteNoteReaction } from './note-reaction';
2018-04-11 13:05:03 -06:00
import MessagingMessage, { deleteMessagingMessage } from './messaging-message';
import MessagingHistory, { deleteMessagingHistory } from './messaging-history';
2018-04-11 13:22:06 -06:00
import DriveFile, { deleteDriveFile } from './drive-file';
import DriveFolder, { deleteDriveFolder } from './drive-folder';
2018-04-11 16:19:28 -06:00
import PollVote, { deletePollVote } from './poll-vote';
2018-04-11 16:25:46 -06:00
import FollowingLog, { deleteFollowingLog } from './following-log';
import FollowedLog, { deleteFollowedLog } from './followed-log';
2018-04-11 16:32:35 -06:00
import SwSubscription, { deleteSwSubscription } from './sw-subscription';
2018-04-14 15:34:55 -06:00
import Notification, { deleteNotification } from './notification';
2018-04-23 19:08:15 -06:00
import UserList, { deleteUserList } from './user-list';
2018-05-31 03:11:28 -06:00
import FollowRequest, { deleteFollowRequest } from './follow-request';
2017-01-16 17:12:33 -07:00
2018-02-01 16:06:01 -07:00
const User = db.get<IUser>('users');
2016-12-28 15:49:51 -07:00
2018-04-13 23:42:18 -06:00
User.createIndex('username');
User.createIndex('usernameLower');
2018-04-13 23:29:18 -06:00
User.createIndex(['username', 'host'], { unique: true });
User.createIndex(['usernameLower', 'host'], { unique: true });
2018-04-14 21:40:48 -06:00
User.createIndex('token', { sparse: true, unique: true });
2018-04-08 08:29:27 -06:00
User.createIndex('uri', { sparse: true, unique: true });
2016-12-28 15:49:51 -07:00
2018-02-01 16:06:01 -07:00
export default User;
2016-12-28 15:49:51 -07:00
2018-04-01 13:01:34 -06:00
type IUserBase = {
2017-09-07 13:13:01 -06:00
_id: mongo.ObjectID;
2018-03-28 23:48:47 -06:00
createdAt: Date;
2018-04-26 05:22:51 -06:00
deletedAt?: Date;
2018-03-28 23:48:47 -06:00
followersCount: number;
followingCount: number;
2018-04-05 10:36:34 -06:00
name?: string;
2018-04-07 11:30:37 -06:00
notesCount: number;
2017-09-07 13:13:01 -06:00
username: string;
2018-03-28 23:48:47 -06:00
usernameLower: string;
avatarId: mongo.ObjectID;
bannerId: mongo.ObjectID;
2018-06-09 17:41:57 -06:00
avatarUrl?: string;
bannerUrl?: string;
2018-06-06 14:14:37 -06:00
wallpaperId: mongo.ObjectID;
2018-07-27 16:52:48 -06:00
wallpaperUrl?: string;
2017-09-07 13:13:01 -06:00
data: any;
description: string;
2018-09-17 15:29:47 -06:00
pinnedNoteIds: mongo.ObjectID[];
2018-05-31 03:08:47 -06:00
/**
*
*/
2018-03-28 23:48:47 -06:00
isSuspended: boolean;
2018-05-31 03:08:47 -06:00
/**
*
*/
isLocked: boolean;
2018-05-31 10:12:02 -06:00
/**
*
*/
pendingReceivedFollowRequestsCount: number;
2018-04-01 20:14:45 -06:00
host: string;
2017-09-07 13:13:01 -06:00
};
2017-10-06 16:23:00 -06:00
2018-04-01 13:48:38 -06:00
export interface ILocalUser extends IUserBase {
host: null;
2018-04-07 12:58:11 -06:00
keypair: string;
email: string;
password: string;
token: string;
twitter: {
accessToken: string;
accessTokenSecret: string;
userId: string;
screenName: string;
2018-04-01 13:48:38 -06:00
};
2018-04-07 12:58:11 -06:00
line: {
userId: string;
};
profile: {
location: string;
birthday: string; // 'YYYY-MM-DD'
tags: string[];
};
lastUsedAt: Date;
isBot: boolean;
2018-05-20 20:08:08 -06:00
isCat: boolean;
2018-07-24 10:14:38 -06:00
isAdmin?: boolean;
isVerified?: boolean;
2018-04-07 12:58:11 -06:00
twoFactorSecret: string;
twoFactorEnabled: boolean;
2018-04-26 05:22:51 -06:00
twoFactorTempSecret?: string;
2018-04-07 12:58:11 -06:00
clientSettings: any;
settings: {
autoWatch: boolean;
alwaysMarkNsfw?: boolean;
};
2018-05-28 10:25:54 -06:00
hasUnreadNotification: boolean;
hasUnreadMessagingMessage: boolean;
2018-04-01 13:48:38 -06:00
}
export interface IRemoteUser extends IUserBase {
2018-04-07 12:58:11 -06:00
inbox: string;
2018-07-19 07:40:44 -06:00
sharedInbox?: string;
2018-05-16 02:06:12 -06:00
endpoints: string[];
2018-04-07 12:58:11 -06:00
uri: string;
2018-04-15 03:38:40 -06:00
url?: string;
2018-04-07 12:58:11 -06:00
publicKey: {
id: string;
publicKeyPem: string;
2018-04-01 13:48:38 -06:00
};
2018-04-17 00:37:18 -06:00
updatedAt: Date;
2018-08-20 10:03:58 -06:00
isAdmin: false;
2018-04-01 13:48:38 -06:00
}
2018-04-01 13:01:34 -06:00
2018-04-01 13:52:11 -06:00
export type IUser = ILocalUser | IRemoteUser;
2018-04-01 13:01:34 -06:00
export const isLocalUser = (user: any): user is ILocalUser =>
user.host === null;
export const isRemoteUser = (user: any): user is IRemoteUser =>
!isLocalUser(user);
2018-03-31 04:55:00 -06:00
2018-04-01 20:14:45 -06:00
//#region Validators
2018-04-01 13:52:11 -06:00
export function validateUsername(username: string): boolean {
return typeof username == 'string' && /^[a-zA-Z0-9_]{1,20}$/.test(username);
2018-04-01 13:52:11 -06:00
}
export function validatePassword(password: string): boolean {
return typeof password == 'string' && password != '';
}
2018-04-05 10:36:34 -06:00
export function isValidName(name?: string): boolean {
2018-05-16 02:04:39 -06:00
return name === null || (typeof name == 'string' && name.length < 50 && name.trim() != '');
2018-04-01 13:52:11 -06:00
}
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);
}
2018-04-01 20:14:45 -06:00
//#endregion
2018-04-01 13:52:11 -06:00
2018-04-11 12:46:32 -06:00
/**
* Userを物理削除します
*/
export async function deleteUser(user: string | mongo.ObjectID | IUser) {
2018-04-11 03:24:42 -06:00
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;
}
2018-04-14 20:57:33 -06:00
console.log(u == null ? `User: delete skipped ${user}` : `User: deleting ${u._id}`);
2018-04-11 03:24:42 -06:00
if (u == null) return;
2018-04-11 12:46:32 -06:00
// このユーザーのAccessTokenをすべて削除
await Promise.all((
await AccessToken.find({ userId: u._id })
).map(x => deleteAccessToken(x)));
// このユーザーのNoteをすべて削除
2018-05-25 22:25:10 -06:00
await sequential((
await Note.find({ userId: u._id })
).map(x => () => deleteNote(x)));
2018-04-11 12:46:32 -06:00
// このユーザーの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)));
2018-04-11 16:19:28 -06:00
// このユーザーのPollVoteをすべて削除
await Promise.all((
await PollVote.find({ userId: u._id })
).map(x => deletePollVote(x)));
2018-04-11 12:46:32 -06:00
// このユーザーのFavoriteをすべて削除
await Promise.all((
await Favorite.find({ userId: u._id })
).map(x => deleteFavorite(x)));
// このユーザーのMessageをすべて削除
2018-04-11 13:05:03 -06:00
await Promise.all((
await MessagingMessage.find({ userId: u._id })
).map(x => deleteMessagingMessage(x)));
2018-04-11 03:24:42 -06:00
2018-04-11 12:46:32 -06:00
// このユーザーへのMessageをすべて削除
2018-04-11 13:05:03 -06:00
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)));
2018-04-11 03:24:42 -06:00
2018-04-11 12:46:32 -06:00
// このユーザーのDriveFileをすべて削除
2018-04-11 13:22:06 -06:00
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)));
2018-04-11 03:24:42 -06:00
2018-04-11 14:50:45 -06:00
// このユーザーの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)));
2018-04-11 12:46:32 -06:00
// このユーザーのFollowingをすべて削除
2018-04-11 16:13:15 -06:00
await Promise.all((
await Following.find({ followerId: u._id })
).map(x => deleteFollowing(x)));
2018-04-11 03:24:42 -06:00
2018-04-11 12:46:32 -06:00
// このユーザーへのFollowingをすべて削除
2018-04-11 16:13:15 -06:00
await Promise.all((
await Following.find({ followeeId: u._id })
).map(x => deleteFollowing(x)));
2018-04-11 03:24:42 -06:00
2018-05-31 03:08:47 -06:00
// このユーザーの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)));
2018-04-11 14:50:45 -06:00
// このユーザーのFollowingLogをすべて削除
2018-04-11 16:25:46 -06:00
await Promise.all((
await FollowingLog.find({ userId: u._id })
).map(x => deleteFollowingLog(x)));
2018-04-11 14:50:45 -06:00
// このユーザーのFollowedLogをすべて削除
2018-04-11 16:25:46 -06:00
await Promise.all((
await FollowedLog.find({ userId: u._id })
).map(x => deleteFollowedLog(x)));
2018-04-11 14:50:45 -06:00
2018-04-11 16:32:35 -06:00
// このユーザーのSwSubscriptionをすべて削除
await Promise.all((
await SwSubscription.find({ userId: u._id })
).map(x => deleteSwSubscription(x)));
2018-04-14 15:34:55 -06:00
// このユーザーの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)));
2018-04-23 19:08:15 -06:00
// このユーザーのUserListをすべて削除
await Promise.all((
await UserList.find({ userId: u._id })
).map(x => deleteUserList(x)));
2018-04-23 23:12:19 -06:00
// このユーザーが入っているすべてのUserListからこのユーザーを削除
2018-04-23 19:08:15 -06:00
await Promise.all((
await UserList.find({ userIds: u._id })
).map(x =>
UserList.update({ _id: x._id }, {
$pull: { userIds: u._id }
})
));
2018-04-11 03:24:42 -06:00
// このユーザーを削除
2018-04-14 15:37:55 -06:00
await User.remove({
_id: u._id
});
2018-04-14 20:57:33 -06:00
console.log(`User: deleted ${u._id}`);
2018-04-11 03:24:42 -06:00
}
2018-02-01 16:06:01 -07:00
/**
* 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,
2018-09-18 23:18:34 -06:00
includeSecrets?: boolean,
includeHasUnreadNotes?: boolean
2018-02-01 16:06:01 -07:00
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false,
includeSecrets: false
}, options);
let _user: any;
const fields = opts.detail ? {
} : {
2018-04-07 12:58:11 -06:00
settings: false,
clientSettings: false,
profile: false,
keywords: false,
domains: false
2018-02-01 16:06:01 -07:00
};
// 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);
}
2018-04-09 14:02:44 -06:00
// TODO: ここでエラーにするのではなくダミーのユーザーデータを返す
// SEE: https://github.com/syuilo/misskey/issues/1432
2018-02-01 16:06:01 -07:00
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;
2018-04-07 12:58:11 -06:00
if (_user.host == null) {
2018-03-27 01:51:12 -06:00
// Remove private properties
2018-04-07 12:58:11 -06:00
delete _user.keypair;
delete _user.password;
delete _user.token;
delete _user.twoFactorTempSecret;
delete _user.twoFactorSecret;
2018-03-28 23:48:47 -06:00
delete _user.usernameLower;
2018-04-07 12:58:11 -06:00
if (_user.twitter) {
delete _user.twitter.accessToken;
delete _user.twitter.accessTokenSecret;
2018-03-27 01:51:12 -06:00
}
2018-04-07 12:58:11 -06:00
delete _user.line;
2018-03-27 01:51:12 -06:00
// Visible via only the official client
if (!opts.includeSecrets) {
2018-04-07 12:58:11 -06:00
delete _user.email;
delete _user.settings;
delete _user.clientSettings;
2018-03-27 01:51:12 -06:00
}
if (!opts.detail) {
2018-04-07 12:58:11 -06:00
delete _user.twoFactorEnabled;
2018-03-27 01:51:12 -06:00
}
2018-04-17 04:43:49 -06:00
} else {
delete _user.publicKey;
2018-02-01 16:06:01 -07:00
}
2018-06-09 17:34:46 -06:00
if (_user.avatarUrl == null) {
2018-07-27 16:52:48 -06:00
_user.avatarUrl = `${config.drive_url}/default-avatar.jpg`;
2018-02-01 16:06:01 -07:00
2018-07-27 16:52:48 -06:00
// 互換性のため
if (_user.avatarId) {
_user.avatarUrl = `${config.drive_url}/${_user.avatarId}`;
}
2018-06-09 17:34:46 -06:00
}
2018-02-01 16:06:01 -07:00
2018-07-27 16:52:48 -06:00
// 互換性のため
if (_user.bannerId && _user.bannerUrl == null) {
_user.bannerUrl = `${config.drive_url}/${_user.bannerId}`;
}
2018-06-06 14:14:37 -06:00
2018-02-01 16:06:01 -07:00
if (!meId || !meId.equals(_user.id) || !opts.detail) {
2018-03-28 23:48:47 -06:00
delete _user.avatarId;
delete _user.bannerId;
2018-05-28 10:25:54 -06:00
delete _user.hasUnreadMessagingMessage;
delete _user.hasUnreadNotification;
2018-02-01 16:06:01 -07:00
}
if (meId && !meId.equals(_user.id)) {
2018-05-31 09:42:37 -06:00
const [following1, following2, followReq1, followReq2, mute] = await Promise.all([
2018-04-18 21:43:25 -06:00
Following.findOne({
2018-03-28 23:48:47 -06:00
followerId: meId,
followeeId: _user.id
2018-04-18 21:43:25 -06:00
}),
Following.findOne({
2018-03-28 23:48:47 -06:00
followerId: _user.id,
followeeId: meId
2018-04-18 21:43:25 -06:00
}),
2018-09-04 03:33:16 -06:00
FollowRequest.findOne({
2018-05-31 09:42:37 -06:00
followerId: meId,
followeeId: _user.id
2018-09-04 03:33:16 -06:00
}),
2018-05-31 09:42:37 -06:00
FollowRequest.findOne({
followerId: _user.id,
followeeId: meId
}),
2018-04-18 21:43:25 -06:00
Mute.findOne({
muterId: meId,
muteeId: _user.id
})
]);
// Whether the user is following
_user.isFollowing = following1 !== null;
_user.isStalking = following1 && following1.stalk;
2018-05-31 09:42:37 -06:00
_user.hasPendingFollowRequestFromYou = followReq1 !== null;
_user.hasPendingFollowRequestToYou = followReq2 !== null;
2018-04-18 21:43:25 -06:00
// Whether the user is followed
_user.isFollowed = following2 !== null;
2018-02-01 16:06:01 -07:00
// Whether the user is muted
2018-04-18 21:43:25 -06:00
_user.isMuted = mute !== null;
2018-02-01 16:06:01 -07:00
}
if (opts.detail) {
2018-09-17 15:29:47 -06:00
if (_user.pinnedNoteIds) {
// Populate pinned notes
_user.pinnedNotes = Promise.all(_user.pinnedNoteIds.map((id: mongo.ObjectId) => packNote(id, meId, {
2018-02-01 16:06:01 -07:00
detail: true
2018-09-17 15:29:47 -06:00
})));
2018-02-01 16:06:01 -07:00
}
if (meId && !meId.equals(_user.id)) {
2018-04-18 21:43:25 -06:00
const myFollowingIds = await getFriendIds(meId);
2018-02-01 16:06:01 -07:00
// Get following you know count
2018-03-28 23:48:47 -06:00
_user.followingYouKnowCount = Following.count({
followeeId: { $in: myFollowingIds },
followerId: _user.id
2018-02-01 16:06:01 -07:00
});
// Get followers you know count
2018-03-28 23:48:47 -06:00
_user.followersYouKnowCount = Following.count({
followeeId: _user.id,
followerId: { $in: myFollowingIds }
2018-02-01 16:06:01 -07:00
});
}
}
2018-09-18 23:18:34 -06:00
if (!opts.includeHasUnreadNotes) {
delete _user.hasUnreadSpecifiedNotes;
delete _user.hasUnreadMentions;
}
2018-02-01 16:06:01 -07:00
// resolve promises in _user object
_user = await rap(_user);
resolve(_user);
});
/*
function img(url) {
return {
thumbnail: {
large: `${url}`,
medium: '',
small: ''
}
};
}
*/
2018-04-26 05:30:49 -06:00
export function getGhost(): Promise<ILocalUser> {
return User.findOne({ _id: new mongo.ObjectId(config.ghost) });
}