iceshrimp-legacy/src/api/bot/interfaces/line.ts

154 lines
3.2 KiB
TypeScript
Raw Normal View History

2017-10-06 20:36:46 +02:00
import * as EventEmitter from 'events';
import * as express from 'express';
2017-10-06 21:30:57 +02:00
import * as request from 'request';
2017-10-06 20:36:46 +02:00
import * as crypto from 'crypto';
2017-10-06 21:48:56 +02:00
import User from '../../models/user';
2017-10-06 20:36:46 +02:00
import config from '../../../conf';
2017-10-06 21:30:57 +02:00
import BotCore from '../core';
2017-10-06 22:50:01 +02:00
import _redis from '../../../db/redis';
import prominence = require('prominence');
2017-10-06 20:36:46 +02:00
2017-10-06 22:50:01 +02:00
const redis = prominence(_redis);
2017-10-06 21:30:57 +02:00
2017-10-07 11:30:04 +02:00
class LineBot extends BotCore {
private replyToken: string;
private reply(messages: any[]) {
request.post({
url: 'https://api.line.me/v2/bot/message/reply',
headers: {
'Authorization': `Bearer ${config.line_bot.channel_access_token}`
},
json: {
replyToken: this.replyToken,
messages: messages
}
}, (err, res, body) => {
if (err) {
console.error(err);
return;
}
});
}
public async react(ev: any): Promise<void> {
// テキスト以外(スタンプなど)は無視
if (ev.message.type !== 'text') return;
const res = await this.q(ev.message.text);
if (res == null) return;
// 返信
this.reply([{
type: 'text',
text: res
}]);
}
public static import(data) {
const bot = new LineBot();
bot._import(data);
return bot;
}
public async showUserCommand(q: string) {
const user = await require('../endpoints/users/show')({
username: q.substr(1)
}, this.user);
this.reply([{
type: 'template',
altText: await super.showUserCommand(q),
template: {
type: 'buttons',
thumbnailImageUrl: `${user.avatar_url}?thumbnail&size=1024`,
title: `${user.name} (@${user.username})`,
text: user.description || '(no description)',
actions: [{
type: 'uri',
label: 'Webで見る',
uri: `${config.url}/${user.username}`
}]
}
}]);
}
}
2017-10-06 20:36:46 +02:00
module.exports = async (app: express.Application) => {
if (config.line_bot == null) return;
const handler = new EventEmitter();
2017-10-06 21:30:57 +02:00
handler.on('message', async (ev) => {
const sourceId = ev.source.userId;
2017-10-06 22:50:01 +02:00
const sessionId = `line-bot-sessions:${sourceId}`;
2017-10-06 21:30:57 +02:00
2017-10-06 22:50:01 +02:00
const _session = await redis.get(sessionId);
2017-10-07 11:30:04 +02:00
let bot: LineBot;
2017-10-06 22:50:01 +02:00
if (_session == null) {
2017-10-06 21:48:56 +02:00
const user = await User.findOne({
line: {
user_id: sourceId
}
});
2017-10-07 11:30:04 +02:00
bot = new LineBot(user);
2017-10-06 23:43:36 +02:00
2017-10-07 11:30:04 +02:00
bot.on('signin', user => {
2017-10-06 23:03:16 +02:00
User.update(user._id, {
$set: {
line: {
user_id: sourceId
2017-10-06 21:48:56 +02:00
}
2017-10-06 23:03:16 +02:00
}
2017-10-06 21:48:56 +02:00
});
2017-10-06 23:03:16 +02:00
});
2017-10-06 21:48:56 +02:00
2017-10-07 11:30:04 +02:00
bot.on('signout', user => {
2017-10-06 23:43:36 +02:00
User.update(user._id, {
$set: {
line: {
user_id: null
}
}
});
});
2017-10-07 11:30:04 +02:00
redis.set(sessionId, JSON.stringify(bot.export()));
2017-10-06 22:50:01 +02:00
} else {
2017-10-07 11:30:04 +02:00
bot = LineBot.import(JSON.parse(_session));
2017-10-06 21:30:57 +02:00
}
2017-10-07 11:30:04 +02:00
bot.on('updated', () => {
redis.set(sessionId, JSON.stringify(bot.export()));
2017-10-06 22:50:01 +02:00
});
2017-10-07 11:30:04 +02:00
bot.react(ev);
2017-10-06 21:30:57 +02:00
});
2017-10-06 20:36:46 +02:00
app.post('/hooks/line', (req, res, next) => {
2017-10-06 21:30:57 +02:00
// req.headers['x-line-signature'] は常に string ですが、型定義の都合上
2017-10-06 20:36:46 +02:00
// string | string[] になっているので string を明示しています
2017-10-06 21:30:57 +02:00
const sig1 = req.headers['x-line-signature'] as string;
2017-10-06 20:36:46 +02:00
2017-10-06 21:30:57 +02:00
const hash = crypto.createHmac('SHA256', config.line_bot.channel_secret)
.update((req as any).rawBody);
2017-10-06 20:36:46 +02:00
const sig2 = hash.digest('base64');
// シグネチャ比較
if (sig1 === sig2) {
2017-10-06 21:30:57 +02:00
req.body.events.forEach(ev => {
handler.emit(ev.type, ev);
});
2017-10-06 20:36:46 +02:00
res.sendStatus(200);
} else {
res.sendStatus(400);
}
});
};