sharkey/src/server/api/endpoints/users/show.ts
syuilo 246cead2b1
Improve user operations
Resolve #2197
Resolve #3367
2018-11-23 08:01:14 +09:00

89 lines
1.9 KiB
TypeScript

import $ from 'cafy'; import ID, { transform, transformMany } from '../../../../misc/cafy-id';
import User, { pack, isRemoteUser } from '../../../../models/user';
import resolveRemoteUser from '../../../../remote/resolve-user';
import define from '../../define';
const cursorOption = { fields: { data: false } };
export const meta = {
desc: {
'ja-JP': '指定したユーザーの情報を取得します。'
},
requireCredential: false,
params: {
userId: {
validator: $.type(ID).optional,
transform: transform,
desc: {
'ja-JP': '対象のユーザーのID',
'en-US': 'Target user ID'
}
},
userIds: {
validator: $.arr($.type(ID)).optional.unique(),
transform: transformMany,
desc: {
'ja-JP': 'ユーザーID (配列)'
}
},
username: {
validator: $.str.optional
},
host: {
validator: $.str.optional.nullable
}
}
};
export default define(meta, (ps, me) => new Promise(async (res, rej) => {
let user;
if (ps.userIds) {
const users = await User.find({
_id: {
$in: ps.userIds
}
});
res(await Promise.all(users.map(u => pack(u, me, {
detail: true
}))));
} else {
// Lookup user
if (typeof ps.host === 'string') {
try {
user = await resolveRemoteUser(ps.username, ps.host, cursorOption);
} catch (e) {
console.warn(`failed to resolve remote user: ${e}`);
return rej('failed to resolve remote user');
}
} else {
const q: any = ps.userId != null
? { _id: ps.userId }
: { usernameLower: ps.username.toLowerCase(), host: null };
user = await User.findOne(q, cursorOption);
if (user === null) {
return rej('user not found');
}
}
// Send response
res(await pack(user, me, {
detail: true
}));
if (isRemoteUser(user)) {
if (user.lastFetchedAt == null || Date.now() - user.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24) {
resolveRemoteUser(ps.username, ps.host, { }, true);
}
}
}
}));