UNPKG

koishi-plugin-adapter-matrix

Version:

Matrix Adapter for koishi

81 lines 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpAdapter = void 0; const satori_1 = require("@satorijs/satori"); const bot_1 = require("./bot"); const utils_1 = require("./utils"); const logger = new satori_1.Logger('matrix'); class HttpAdapter extends satori_1.Adapter.Server { constructor(ctx) { super(); this.txnId = null; const put = (path, callback) => { ctx.router.put(path, this.hook(callback).bind(this)); ctx.router.put('/_matrix/app/v1' + path, this.hook(callback).bind(this)); }; const get = (path, callback) => { ctx.router.get(path, this.hook(callback).bind(this)); ctx.router.get('/_matrix/app/v1' + path, this.hook(callback).bind(this)); }; put('/transactions/:txnId', this.transactions); get('/users/:userId', this.users); get('/room/:roomAlias', this.rooms); } hook(callback) { return (ctx) => { const bots = this.bots.filter(bot => (bot instanceof bot_1.MatrixBot) && (bot.config.hsToken === ctx.query.access_token)); if (!bots.length) { ctx.status = 403; ctx.body = { errcode: 'M_FORBIDDEN' }; return; } ctx.bots = bots; callback.call(this, ctx); }; } async start(bot) { try { await bot.initialize(); bot.online(); } catch (e) { logger.error('failed to initialize', e); throw e; } } transactions(ctx) { const { txnId } = ctx.params; const events = ctx.request.body.events; ctx.body = {}; if (txnId === this.txnId) return; this.txnId = txnId; for (const event of events) { const bots = ctx.bots .filter(bot => bot.userId !== event.sender && bot.rooms.includes(event.room_id)); let bot; if (event.type === 'm.room.member' && event.content.membership === 'invite' && (bot = ctx.bots.find(bot => bot.userId === event.state_key)) && !bots.includes(bot)) { bots.push(bot); } bots.forEach(bot => (0, utils_1.dispatchSession)(bot, event)); } } users(ctx) { const { userId } = ctx.params; if (!ctx.bots.find(bot => bot.userId === userId)) { ctx.status = 404; ctx.body = { 'errcode': 'CHAT.SATORI.NOT_FOUND' }; return; } ctx.body = {}; } rooms(ctx) { ctx.status = 404; ctx.body = { 'errcode': 'CHAT.SATORI.NOT_FOUND' }; } } exports.HttpAdapter = HttpAdapter; //# sourceMappingURL=http.js.map