misskey-tools/src/services/worker.ts

54 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-08-04 16:43:13 +09:00
import cron from 'node-cron';
2020-08-12 13:31:09 +09:00
import delay from 'delay';
2020-09-08 20:05:22 +09:00
import { Users } from '../models';
2020-08-04 16:43:13 +09:00
import { api } from './misskey';
2020-09-08 20:05:22 +09:00
import { format } from '../functions/format';
import { deleteUser } from '../functions/users';
import { updateScore } from '../functions/update-score';
import { getScores } from '../functions/get-scores';
2020-08-04 16:43:13 +09:00
export default (): void => {
2020-09-09 00:53:50 +09:00
cron.schedule('0 0 0 * * *', async () => {
2020-08-04 16:43:13 +09:00
const users = await Users.createQueryBuilder()
.select()
.getMany();
for (const user of users) {
try {
const text = format(await getScores(user));
await updateScore(user);
2020-08-12 13:31:09 +09:00
if (user.alertMode === 'note') {
const res = await api<Record<string, unknown>>(user.host, 'notes/create', {
text,
visibility: 'specified'
}, user.token);
if (res.error) {
throw res.error;
}
break;
} else if (user.alertMode === 'notification') {
const res = await api(user.host, 'notifications/create', {
header: 'みす廃あらーと',
icon: 'https://i.imgur.com/B991yTl.png',
body: text,
}, user.token);
if (res.error) {
throw res.error;
}
}
2020-08-04 16:43:13 +09:00
} catch (e) {
if (e.code === 'NO_SUCH_USER' || e.code === 'AUTHENTICATION_FAILED') {
// ユーザーが削除されている場合、レコードからも消してとりやめ
console.info(`${user.username}@${user.host} is deleted, so delete this user from the system`);
await deleteUser(user.username, user.host);
} else {
console.error(e);
}
2020-08-12 13:31:09 +09:00
} finally {
if (user.alertMode === 'note')
await delay(3000);
2020-08-04 16:43:13 +09:00
}
}
});
};