umbot
Version:
Universal bot(vk, telegram, viber) or skills for Yandex.Alisa, Маруся and sber
270 lines (269 loc) • 10.9 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bot = void 0;
const mmApp_1 = require("../mmApp");
const util_1 = require("../utils/standard/util");
const platforms_1 = require("../platforms");
const UsersData_1 = require("../models/UsersData");
const http_1 = require("http");
__exportStar(require("./interfaces/IBot"), exports);
class Bot {
_serverInst;
_userData;
_content = null;
_botController;
_auth;
constructor(type, botController) {
this._auth = null;
this._botController = botController;
mmApp_1.mmApp.appType = !type ? mmApp_1.T_ALISA : type;
}
initTypeInGet() {
if (util_1.GET && util_1.GET.type) {
if ([mmApp_1.T_TELEGRAM, mmApp_1.T_ALISA, mmApp_1.T_VIBER, mmApp_1.T_VK, mmApp_1.T_USER_APP, mmApp_1.T_MARUSIA, mmApp_1.T_SMARTAPP].indexOf(util_1.GET.type)) {
mmApp_1.mmApp.appType = util_1.GET.type;
return true;
}
}
return false;
}
initConfig(config) {
if (config) {
mmApp_1.mmApp.setConfig(config);
}
}
initParams(params) {
if (params) {
mmApp_1.mmApp.setParams(params);
}
}
initBotController(fn) {
if (fn) {
this._botController = fn;
}
}
static _getBotClassAndType(userBotClass = null) {
let botClass = null;
let type = null;
switch (mmApp_1.mmApp.appType) {
case mmApp_1.T_ALISA:
botClass = new platforms_1.Alisa();
type = UsersData_1.UsersData.T_ALISA;
break;
case mmApp_1.T_VK:
botClass = new platforms_1.Vk();
type = UsersData_1.UsersData.T_VK;
break;
case mmApp_1.T_TELEGRAM:
botClass = new platforms_1.Telegram();
type = UsersData_1.UsersData.T_TELEGRAM;
break;
case mmApp_1.T_VIBER:
botClass = new platforms_1.Viber();
type = UsersData_1.UsersData.T_VIBER;
break;
case mmApp_1.T_MARUSIA:
botClass = new platforms_1.Marusia();
type = UsersData_1.UsersData.T_MARUSIA;
break;
case mmApp_1.T_SMARTAPP:
botClass = new platforms_1.SmartApp();
type = UsersData_1.UsersData.T_SMART_APP;
break;
case mmApp_1.T_USER_APP:
if (userBotClass) {
botClass = userBotClass;
type = UsersData_1.UsersData.T_USER_APP;
}
break;
}
return { botClass, type };
}
setContent(content) {
this._content = content;
}
_getUserData() {
if (this._userData) {
return this._userData;
}
this._userData = new UsersData_1.UsersData();
return this._userData;
}
_clearState() {
if (this._botController) {
this._botController.clearStoreData();
}
}
async run(userBotClass = null) {
if (!this._botController) {
const errMsg = 'Не определен класс с логикой приложения. Укажите класс с логикой, передав его в метод initBotController';
mmApp_1.mmApp.saveLog('bot.log', errMsg);
throw new Error(errMsg);
}
const { botClass, type } = Bot._getBotClassAndType(userBotClass);
if (botClass) {
if (this._botController.userToken === null) {
this._botController.userToken = this._auth;
}
if (await botClass.init(this._content, this._botController)) {
if (botClass.sendInInit) {
return await botClass.sendInInit;
}
const userData = this._getUserData();
userData.escapeString('');
this._botController.userId = userData.escapeString(this._botController.userId);
if (type) {
userData.type = type;
}
const isLocalStorage = !!(mmApp_1.mmApp.config.isLocalStorage && botClass.isLocalStorage());
let isNewUser = true;
if (isLocalStorage) {
botClass.isUsedLocalStorage = isLocalStorage;
this._botController.userData = (await botClass.getLocalStorage());
}
else {
const query = {
userId: userData.escapeString(this._botController.userId),
};
if (this._auth) {
query.userId = userData.escapeString(this._botController.userToken);
}
if (await userData.whereOne(query)) {
this._botController.userData = userData.data;
isNewUser = false;
}
else {
this._botController.userData = {};
userData.userId = this._botController.userId;
userData.meta = this._botController.userMeta;
}
}
if (!this._botController.oldIntentName &&
this._botController.userData &&
this._botController.userData.oldIntentName) {
this._botController.oldIntentName = this._botController.userData.oldIntentName;
}
this._botController.run();
if (this._botController.thisIntentName !== null && this._botController.userData) {
this._botController.userData.oldIntentName = this._botController.thisIntentName;
}
else {
delete this._botController.userData?.oldIntentName;
}
let content;
if (this._botController.isSendRating) {
content = await botClass.getRatingContext();
}
else {
content = await botClass.getContext();
}
if (!isLocalStorage) {
userData.data = this._botController.userData;
if (isNewUser) {
userData.save(true).then((res) => {
if (!res) {
mmApp_1.mmApp.saveLog('bot.log', `Bot:run(): Не удалось сохранить данные для пользователя: ${this._botController.userId}.`);
}
});
}
else {
userData.update().then((res) => {
if (!res) {
mmApp_1.mmApp.saveLog('bot.log', `Bot:run(): Не удалось обновить данные для пользователя: ${this._botController.userId}.`);
}
});
}
}
else {
await botClass.setLocalStorage(this._botController.userData);
}
if (botClass.getError()) {
mmApp_1.mmApp.saveLog('bot.log', botClass.getError());
}
userData.destroy();
this._clearState();
return content;
}
else {
mmApp_1.mmApp.saveLog('bot.log', botClass.getError());
throw new Error(botClass.getError() || '');
}
}
else {
const msg = 'Не удалось определить тип приложения!';
mmApp_1.mmApp.saveLog('bot.log', msg);
throw new Error(msg);
}
}
start(hostname = 'localhost', port = 3000, userBotClass = null) {
const send = (res, statusCode, result) => {
res.statusCode = statusCode;
res.setHeader('Content-Type', typeof result === 'object' ? 'application/json' : 'text/plain');
res.end(typeof result === 'string' ? result : JSON.stringify(result));
};
this.close();
this._serverInst = (0, http_1.createServer)(async (req, res) => {
if (req.method !== 'POST') {
send(res, 400, 'Bad Request');
return;
}
try {
const data = await this.readRequestData(req);
const query = JSON.parse(data);
if (query) {
if (req.headers && req.headers.authorization) {
this._auth = req.headers.authorization.replace('Bearer', '');
}
this.setContent(query);
const result = await this.run(userBotClass);
send(res, result === 'notFound' ? 404 : 200, result);
}
}
catch (error) {
if (error instanceof SyntaxError) {
mmApp_1.mmApp.saveLog('bot.log', `Bot:start(): Syntax Error: ${error}`);
send(res, 400, 'Invalid JSON');
}
else {
mmApp_1.mmApp.saveLog('bot.log', `Bot:start(): Server error: ${error}`);
send(res, 500, 'Internal Server Error');
}
}
});
this._serverInst.listen(port, hostname, () => {
console.log(`Server running at //${hostname}:${port}/`);
});
return this._serverInst;
}
readRequestData(req) {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk.toString();
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
}
close() {
if (this._serverInst) {
this._serverInst.close();
this._serverInst = undefined;
}
}
}
exports.Bot = Bot;