// Теперь получаем все сообщения этого гостя (по идентификатору И каналу)
constguestResult=awaitdb.getQuery()(
`SELECT
id,
decrypt_text(identifier_encrypted, $3) as user_id,
channel,
decrypt_text(content_encrypted, $3) as content,
content_type,
attachments,
media_metadata,
is_ai,
created_at
FROM unified_guest_messages
WHERE decrypt_text(identifier_encrypted, $3) = $1
AND channel = $2
ORDER BY created_at ASC`,
[guestIdentifier,guestChannel,encryptionKey]
);
// Преобразуем формат для совместимости с фронтендом
constmessages=guestResult.rows.map(msg=>({
id:msg.id,
user_id:`guest_${guestId}`,
sender_type:msg.is_ai?'bot':'user',
content:msg.content,
channel:msg.channel,
role:'guest',
direction:msg.is_ai?'incoming':'outgoing',
created_at:msg.created_at,
attachment_filename:null,
attachment_mimetype:null,
attachment_size:null,
attachment_data:null,
// Дополнительные поля для медиа
content_type:msg.content_type,
attachments:msg.attachments,
media_metadata:msg.media_metadata
}));
returnres.json(messages);
}
// Стандартная логика для зарегистрированных пользователей - ТОЛЬКО ПУБЛИЧНЫЕ СООБЩЕНИЯ
letresult;
if(conversationId){
result=awaitdb.getQuery()(
`SELECT id, user_id, decrypt_text(sender_type_encrypted, $2) as sender_type, decrypt_text(content_encrypted, $2) as content, decrypt_text(channel_encrypted, $2) as channel, decrypt_text(role_encrypted, $2) as role, decrypt_text(direction_encrypted, $2) as direction, created_at, decrypt_text(attachment_filename_encrypted, $2) as attachment_filename, decrypt_text(attachment_mimetype_encrypted, $2) as attachment_mimetype, attachment_size, attachment_data, message_type
FROM messages
WHERE conversation_id = $1 AND message_type = 'public'
ORDER BY created_at ASC`,
[conversationId,encryptionKey]
);
}elseif(userId){
result=awaitdb.getQuery()(
`SELECT id, user_id, decrypt_text(sender_type_encrypted, $2) as sender_type, decrypt_text(content_encrypted, $2) as content, decrypt_text(channel_encrypted, $2) as channel, decrypt_text(role_encrypted, $2) as role, decrypt_text(direction_encrypted, $2) as direction, created_at, decrypt_text(attachment_filename_encrypted, $2) as attachment_filename, decrypt_text(attachment_mimetype_encrypted, $2) as attachment_mimetype, attachment_size, attachment_data, message_type
FROM messages
WHERE user_id = $1 AND message_type = 'public'
ORDER BY created_at ASC`,
[userId,encryptionKey]
);
}else{
result=awaitdb.getQuery()(
`SELECT id, user_id, decrypt_text(sender_type_encrypted, $1) as sender_type, decrypt_text(content_encrypted, $1) as content, decrypt_text(channel_encrypted, $1) as channel, decrypt_text(role_encrypted, $1) as role, decrypt_text(direction_encrypted, $1) as direction, created_at, decrypt_text(attachment_filename_encrypted, $1) as attachment_filename, decrypt_text(attachment_mimetype_encrypted, $1) as attachment_mimetype, attachment_size, attachment_data, message_type
returnres.status(403).json({error:'Пользователь заблокирован. Сообщение не принимается.'});
}
// Проверка наличия идентификатора для выбранного канала
if(channel==='email'){
constemailIdentity=awaitdb.getQuery()(
'SELECT decrypt_text(provider_id_encrypted, $3) as provider_id FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $3) LIMIT 1',
[user_id,'email',encryptionKey]
);
if(emailIdentity.rows.length===0){
returnres.status(400).json({error:'У пользователя не указан email. Сообщение не отправлено.'});
}
}
if(channel==='telegram'){
consttgIdentity=awaitdb.getQuery()(
'SELECT decrypt_text(provider_id_encrypted, $3) as provider_id FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $3) LIMIT 1',
[user_id,'telegram',encryptionKey]
);
if(tgIdentity.rows.length===0){
returnres.status(400).json({error:'У пользователя не привязан Telegram. Сообщение не отправлено.'});
'SELECT decrypt_text(provider_id_encrypted, $3) as provider_id FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $3) LIMIT 1',
[user_id,'wallet',encryptionKey]
);
if(walletIdentity.rows.length===0){
returnres.status(400).json({error:'У пользователя не привязан кошелёк. Сообщение не отправлено.'});
}
}
// 1. Проверяем, есть ли беседа для user_id
letconversationResult=awaitdb.getQuery()(
'SELECT id, user_id, created_at, updated_at, decrypt_text(title_encrypted, $2) as title FROM conversations WHERE user_id = $1 ORDER BY updated_at DESC, created_at DESC LIMIT 1',
// 4. Если это исходящее сообщение для Telegram — отправляем через бота
if(channel==='telegram'&&direction==='out'){
try{
// console.log(`[messages.js] Попытка отправки сообщения в Telegram для user_id=${user_id}`);
// Получаем Telegram ID пользователя
consttgIdentity=awaitdb.getQuery()(
'SELECT decrypt_text(provider_id_encrypted, $3) as provider_id FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $3) LIMIT 1',
[user_id,'telegram',encryptionKey]
);
// console.log(`[messages.js] Результат поиска Telegram ID:`, tgIdentity.rows);
if(tgIdentity.rows.length>0){
consttelegramId=tgIdentity.rows[0].provider_id;
// console.log(`[messages.js] Отправка сообщения в Telegram ID: ${telegramId}, текст: ${content}`);
// console.log(`[messages.js] Результат отправки в Telegram:`, sendResult);
}else{
logger.warn('[messages.js] Telegram Bot не инициализирован');
}
}catch(sendErr){
// console.error(`[messages.js] Ошибка при отправке в Telegram:`, sendErr);
}
}else{
// console.warn(`[messages.js] Не найден Telegram ID для user_id=${user_id}`);
}
}catch(err){
// console.error('[messages.js] Ошибка отправки сообщения в Telegram:', err);
}
}
// 5. Если это исходящее сообщение для Email — отправляем email
if(channel==='email'&&direction==='out'){
try{
// Получаем email пользователя
constemailIdentity=awaitdb.getQuery()(
'SELECT decrypt_text(provider_id_encrypted, $3) as provider_id FROM user_identities WHERE user_id = $1 AND provider_encrypted = encrypt_text($2, $3) LIMIT 1',
WHERE decrypt_text(identifier_encrypted, $2) = $1 AND processed = true`,
[`web:${guestId}`,encryptionKey]
);
returnresult.rows.length>0;
}catch(error){
logger.error(`[isGuestIdProcessed] Error checking guest ID ${guestId}:`,error);
returnfalse;
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.