ваше сообщение коммита
This commit is contained in:
@@ -25,9 +25,10 @@
|
||||
"@langchain/community": "^0.3.34",
|
||||
"@langchain/core": "0.3.0",
|
||||
"@langchain/ollama": "^0.2.0",
|
||||
"@openzeppelin/contracts": "4.5.0",
|
||||
"axios": "^1.6.7",
|
||||
"@openzeppelin/contracts": "^5.2.0",
|
||||
"axios": "^1.8.4",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"cookie": "^1.0.2",
|
||||
"cors": "^2.8.5",
|
||||
"cron": "^4.1.0",
|
||||
"csurf": "^1.11.0",
|
||||
@@ -39,16 +40,20 @@
|
||||
"helmet": "^8.0.0",
|
||||
"hnswlib-node": "^3.0.0",
|
||||
"imap": "^0.8.19",
|
||||
"langchain": "0.0.200",
|
||||
"langchain": "^0.3.19",
|
||||
"mailparser": "^3.7.2",
|
||||
"node-cron": "^3.0.3",
|
||||
"node-telegram-bot-api": "^0.66.0",
|
||||
"nodemailer": "^6.10.0",
|
||||
"pg": "^8.10.0",
|
||||
"semver": "^7.7.1",
|
||||
"session-file-store": "^1.5.0",
|
||||
"siwe": "^2.1.4",
|
||||
"telegraf": "^4.16.3",
|
||||
"winston": "^3.17.0"
|
||||
"utf7": "^1.0.2",
|
||||
"viem": "^2.23.15",
|
||||
"winston": "^3.17.0",
|
||||
"ws": "^8.18.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nomicfoundation/hardhat-chai-matchers": "^2.0.0",
|
||||
@@ -68,12 +73,18 @@
|
||||
"eslint-config-prettier": "^10.0.2",
|
||||
"globals": "^16.0.0",
|
||||
"hardhat": "^2.22.19",
|
||||
"hardhat-gas-reporter": "^1.0.8",
|
||||
"hardhat-gas-reporter": "^2.2.2",
|
||||
"nodemon": "^3.1.9",
|
||||
"prettier": "^3.5.3",
|
||||
"solidity-coverage": "^0.8.1",
|
||||
"ts-node": ">=8.0.0",
|
||||
"typechain": "^8.3.0",
|
||||
"typescript": ">=4.5.0"
|
||||
},
|
||||
"resolutions": {
|
||||
"ws": "^8.18.1",
|
||||
"cookie": "^1.0.2",
|
||||
"semver": "^7.7.1",
|
||||
"**/utf7/semver": "^7.7.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const { ChatOllama } = require('@langchain/ollama');
|
||||
const { HNSWLib } = require('langchain/vectorstores/hnswlib');
|
||||
const { OpenAIEmbeddings } = require('langchain/embeddings/openai');
|
||||
const { HNSWLib } = require('@langchain/community/vectorstores/hnswlib');
|
||||
const { OpenAIEmbeddings } = require('@langchain/openai');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
class AIAssistant {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
const { pool } = require('../db');
|
||||
const nodemailer = require('nodemailer');
|
||||
const Imap = require('imap');
|
||||
const simpleParser = require('mailparser').simpleParser;
|
||||
const { processMessage } = require('./ai-assistant');
|
||||
const { inspect } = require('util');
|
||||
const logger = require('../utils/logger');
|
||||
const verificationService = require('./verification-service');
|
||||
@@ -18,11 +21,46 @@ const transporter = nodemailer.createTransport({
|
||||
}
|
||||
});
|
||||
|
||||
// Конфигурация для получения писем
|
||||
const imapConfig = {
|
||||
user: process.env.EMAIL_USER,
|
||||
password: process.env.EMAIL_PASSWORD,
|
||||
host: process.env.EMAIL_IMAP_HOST,
|
||||
port: process.env.EMAIL_IMAP_PORT,
|
||||
tls: true,
|
||||
tlsOptions: { rejectUnauthorized: false },
|
||||
keepalive: {
|
||||
interval: 10000, // Проверка соединения каждые 10 секунд
|
||||
idleInterval: 300000, // Сброс соединения через 5 минут простоя
|
||||
forceNoop: true // Принудительная отправка NOOP для поддержания соединения
|
||||
}
|
||||
};
|
||||
|
||||
class EmailBotService {
|
||||
constructor(user, password) {
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.transporter = transporter;
|
||||
this.imap = new Imap(imapConfig);
|
||||
this.initialize();
|
||||
this.listenForReplies();
|
||||
}
|
||||
|
||||
initialize() {
|
||||
this.imap.once('error', (err) => {
|
||||
logger.error(`IMAP connection error: ${err.message}`);
|
||||
// Пробуем переподключиться через 1 минуту при ошибке
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (this.imap.state !== 'connected') {
|
||||
this.imap = new Imap(imapConfig);
|
||||
this.initialize();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`Error reconnecting IMAP: ${e.message}`);
|
||||
}
|
||||
}, 60000);
|
||||
});
|
||||
}
|
||||
|
||||
async sendVerificationCode(toEmail, userId) {
|
||||
@@ -65,6 +103,157 @@ class EmailBotService {
|
||||
}
|
||||
}
|
||||
|
||||
listenForReplies() {
|
||||
// Запускаем проверку почты каждые 60 секунд
|
||||
setInterval(() => {
|
||||
this.checkEmails();
|
||||
}, 60000);
|
||||
}
|
||||
|
||||
checkEmails() {
|
||||
try {
|
||||
// Добавляем обработчики ошибок
|
||||
this.imap.once('error', (err) => {
|
||||
logger.error(`IMAP connection error during check: ${err.message}`);
|
||||
// Пытаемся закрыть соединение при ошибке
|
||||
try {
|
||||
this.imap.end();
|
||||
} catch (e) {
|
||||
// Игнорируем ошибки при закрытии
|
||||
}
|
||||
});
|
||||
|
||||
this.imap.once('ready', () => {
|
||||
this.imap.openBox('INBOX', false, (err, box) => {
|
||||
if (err) {
|
||||
logger.error(`Error opening inbox: ${err}`);
|
||||
this.imap.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Ищем непрочитанные письма
|
||||
this.imap.search(['UNSEEN'], (err, results) => {
|
||||
if (err) {
|
||||
logger.error(`Error searching messages: ${err}`);
|
||||
this.imap.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!results || results.length === 0) {
|
||||
logger.info('No new messages found');
|
||||
this.imap.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Защищаемся от пустых результатов
|
||||
try {
|
||||
const f = this.imap.fetch(results, { bodies: '' });
|
||||
|
||||
f.on('message', (msg, seqno) => {
|
||||
msg.on('body', (stream, info) => {
|
||||
simpleParser(stream, async (err, parsed) => {
|
||||
if (err) {
|
||||
logger.error(`Error parsing message: ${err}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка входящего письма для Ollama
|
||||
try {
|
||||
// Проверяем, что это действительно письмо (защита от ошибок)
|
||||
if (parsed && parsed.text && parsed.from && parsed.from.value &&
|
||||
parsed.from.value.length > 0 && parsed.from.value[0].address) {
|
||||
|
||||
const fromEmail = parsed.from.value[0].address.toLowerCase();
|
||||
const subject = parsed.subject || '';
|
||||
const text = parsed.text || '';
|
||||
|
||||
// Передаем письмо в Ollama для обработки
|
||||
await this.processOllamaEmail(fromEmail, subject, text);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(`Error processing email for Ollama: ${e.message}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
f.once('error', (err) => {
|
||||
logger.error(`Fetch error: ${err}`);
|
||||
});
|
||||
|
||||
f.once('end', () => {
|
||||
try {
|
||||
this.imap.end();
|
||||
} catch (e) {
|
||||
logger.error(`Error ending IMAP connection: ${e.message}`);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error(`Error fetching messages: ${e.message}`);
|
||||
try {
|
||||
this.imap.end();
|
||||
} catch (e) {
|
||||
// Игнорируем ошибки при закрытии
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
this.imap.connect();
|
||||
} catch (error) {
|
||||
logger.error(`Global error checking emails: ${error.message}`);
|
||||
// Обеспечиваем корректное завершение IMAP сессии
|
||||
try {
|
||||
this.imap.end();
|
||||
} catch (e) {
|
||||
// Игнорируем ошибки при закрытии
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для обработки письма с помощью Ollama
|
||||
async processOllamaEmail(fromEmail, subject, text) {
|
||||
try {
|
||||
// Проверяем, есть ли текст для обработки
|
||||
if (!text || text.trim() === '') {
|
||||
logger.info(`Empty message from ${fromEmail}, skipping Ollama processing`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`Processing message from ${fromEmail} for Ollama`);
|
||||
|
||||
// Получаем ответ от Ollama
|
||||
const response = await processMessage(text);
|
||||
|
||||
if (response) {
|
||||
// Отправляем ответ обратно пользователю
|
||||
await this.transporter.sendMail({
|
||||
from: this.user,
|
||||
to: fromEmail,
|
||||
subject: `Re: ${subject}`,
|
||||
text: response
|
||||
});
|
||||
|
||||
logger.info(`Ollama response sent to ${fromEmail}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Error in Ollama email processing: ${error}`);
|
||||
|
||||
// Отправляем сообщение об ошибке пользователю
|
||||
try {
|
||||
await this.transporter.sendMail({
|
||||
from: this.user,
|
||||
to: fromEmail,
|
||||
subject: 'Error processing your request',
|
||||
text: 'Sorry, we encountered an error processing your message. Please try again later.'
|
||||
});
|
||||
} catch (e) {
|
||||
logger.error(`Error sending error notification: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для проверки кода без IMAP
|
||||
async verifyCode(email, code) {
|
||||
return await verificationService.verifyCode(code, 'email', email.toLowerCase());
|
||||
|
||||
1085
backend/yarn.lock
1085
backend/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user