Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 120 additions & 10 deletions bootstrap/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,67 @@ private function isMeaningfulTelegramUploadName($file)
return true;
}

private function sendTelegramChatFile($tchat, $fileData, $caption, $disableNotification = false)
public function saveTopicMsgId($msg, $topicMsgId)
{
if (!($msg instanceof erLhcoreClassModelmsg) || !(int)$topicMsgId || $msg->id <= 0) {
return;
}

$meta = is_array($msg->meta_msg_array) ? $msg->meta_msg_array : [];
$meta['tg_topic_msg_id'] = (int)$topicMsgId;
$msg->meta_msg_array = $meta;
$msg->meta_msg = json_encode($meta);

$stmt = ezcDbInstance::get()->prepare("UPDATE lh_msg SET meta_msg = :meta_msg WHERE id = :id");
$stmt->bindValue(':meta_msg', $msg->meta_msg);
$stmt->bindValue(':id', (int)$msg->id, PDO::PARAM_INT);
$stmt->execute();
}

public function getTopicReplyId($msg, $chatId)
{
if (!($msg instanceof erLhcoreClassModelmsg)) {
return null;
}

$meta = $msg->meta_msg_array;

if (isset($meta['content']['reply_to']['db_msg_id']) && (int)$meta['content']['reply_to']['db_msg_id'] > 0) {
$targetMsg = erLhcoreClassModelmsg::fetch((int)$meta['content']['reply_to']['db_msg_id']);
if ($targetMsg instanceof erLhcoreClassModelmsg && isset($targetMsg->meta_msg_array['tg_topic_msg_id']) && (int)$targetMsg->meta_msg_array['tg_topic_msg_id'] > 0) {
return (int)$targetMsg->meta_msg_array['tg_topic_msg_id'];
}
}

if (isset($meta['content']['reply_to']['iwh_msg_id']) && $meta['content']['reply_to']['iwh_msg_id'] != '') {
$iwhId = (string)$meta['content']['reply_to']['iwh_msg_id'];
$targetMsg = erLhcoreClassModelmsg::findOne([
'filter' => ['chat_id' => $chatId],
'customfilter' => ['`meta_msg` != \'\' AND JSON_VALID(`meta_msg`) AND (JSON_UNQUOTE(JSON_EXTRACT(meta_msg,\'$.iwh_msg_id\')) = ' . ezcDbInstance::get()->quote($iwhId) . ' OR JSON_EXTRACT(meta_msg,\'$.iwh_msg_id\') = ' . (is_numeric($iwhId) ? (int)$iwhId : ezcDbInstance::get()->quote($iwhId)) . ')']
]);
if ($targetMsg instanceof erLhcoreClassModelmsg && isset($targetMsg->meta_msg_array['tg_topic_msg_id']) && (int)$targetMsg->meta_msg_array['tg_topic_msg_id'] > 0) {
return (int)$targetMsg->meta_msg_array['tg_topic_msg_id'];
}
}

if (isset($meta['content']['quote']['id']) && (int)$meta['content']['quote']['id'] > 0) {
$targetMsg = erLhcoreClassModelmsg::fetch((int)$meta['content']['quote']['id']);
if ($targetMsg instanceof erLhcoreClassModelmsg && isset($targetMsg->meta_msg_array['tg_topic_msg_id']) && (int)$targetMsg->meta_msg_array['tg_topic_msg_id'] > 0) {
return (int)$targetMsg->meta_msg_array['tg_topic_msg_id'];
}
}

if (preg_match('#\[quote="?([0-9]+)"?\]#is', (string)$msg->msg, $m)) {
$targetMsg = erLhcoreClassModelmsg::fetch((int)$m[1]);
if ($targetMsg instanceof erLhcoreClassModelmsg && isset($targetMsg->meta_msg_array['tg_topic_msg_id']) && (int)$targetMsg->meta_msg_array['tg_topic_msg_id'] > 0) {
return (int)$targetMsg->meta_msg_array['tg_topic_msg_id'];
}
}

return null;
}

private function sendTelegramChatFile($tchat, $fileData, $caption, $disableNotification = false, $params = array())
{
$file = $fileData['file'];

Expand Down Expand Up @@ -475,6 +535,10 @@ private function sendTelegramChatFile($tchat, $fileData, $caption, $disableNotif
$field => $this->getTelegramChatFileUrl($file)
);

if (isset($params['reply_to_message_id']) && $params['reply_to_message_id'] > 0) {
$data['reply_to_message_id'] = $params['reply_to_message_id'];
}

if ($caption !== '') {
$data['caption'] = $caption;
}
Expand Down Expand Up @@ -515,7 +579,7 @@ private function sendTelegramChatFile($tchat, $fileData, $caption, $disableNotif
return false;
}

return true;
return $sendData->getResult()->getMessageId();
}

private function getTelegramChatFileUrl($file)
Expand Down Expand Up @@ -580,8 +644,17 @@ public function messageAdded($params)
$data['disable_notification'] = true;
}

$replyTopicMsgId = $this->getTopicReplyId($params['msg'], $chat->id);
if ($replyTopicMsgId > 0) {
$data['reply_to_message_id'] = $replyTopicMsgId;
}

$sendData = Longman\TelegramBot\Request::sendMessage($data);

if ($sendData->isOk()) {
$this->saveTopicMsgId($params['msg'], $sendData->getResult()->getMessageId());
}

if (!$sendData->isOk() && $sendData->getErrorCode() == 400 && str_contains( $sendData->getDescription(), 'TOPIC_DELETED') === true) {
// Reset telegram chat
$tchat->tchat_id = 0;
Expand Down Expand Up @@ -610,9 +683,13 @@ public function messageAdded($params)
$failedEmbedCodes = array();
$fileIndex = 0;

$replyTopicMsgId = $this->getTopicReplyId($params['msg'], $chat->id);
foreach ($telegramFiles as $telegramFile) {
if ($this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($params['msg'], $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT) === false) {
$sentFileMsgId = $this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($params['msg'], $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT, ['reply_to_message_id' => $replyTopicMsgId]);
if ($sentFileMsgId === false) {
$failedEmbedCodes[] = $telegramFile['embed'];
} else {
$this->saveTopicMsgId($params['msg'], $sentFileMsgId);
}
$fileIndex++;
}
Expand Down Expand Up @@ -671,7 +748,9 @@ public function messageAdded($params)
}
$sendData = Longman\TelegramBot\Request::sendMessage($data);

if (!$sendData->isOk()) {
if ($sendData->isOk()) {
$this->saveTopicMsgId($botMessage, $sendData->getResult()->getMessageId());
} else {
erLhcoreClassLog::write('SendMessage BOT ['.$sendData->getErrorCode().']'. $sendData->getDescription(),
ezcLog::SUCCESS_AUDIT,
array(
Expand All @@ -690,8 +769,11 @@ public function messageAdded($params)
$fileIndex = 0;

foreach ($telegramFiles as $telegramFile) {
if ($this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($botMessage, $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT) === false) {
$sentFileMsgId = $this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($botMessage, $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT);
if ($sentFileMsgId === false) {
$failedEmbedCodes[] = $telegramFile['embed'];
} else {
$this->saveTopicMsgId($botMessage, $sentFileMsgId);
}
$fileIndex++;
}
Expand Down Expand Up @@ -767,7 +849,9 @@ public function triggerClicked($params)
}
$sendData = Longman\TelegramBot\Request::sendMessage($data);

if (!$sendData->isOk()) {
if ($sendData->isOk()) {
$this->saveTopicMsgId($botMessage, $sendData->getResult()->getMessageId());
} else {
erLhcoreClassLog::write('['.$sendData->getErrorCode().']'. $sendData->getDescription(),
ezcLog::SUCCESS_AUDIT,
array(
Expand All @@ -786,8 +870,11 @@ public function triggerClicked($params)
$fileIndex = 0;

foreach ($telegramFiles as $telegramFile) {
if ($this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($botMessage, $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT) === false) {
$sentFileMsgId = $this->sendTelegramChatFile($tchat, $telegramFile, $this->getTelegramFileCaption($botMessage, $chat, $telegramFile['file'], $fileIndex === 0 ? $messageText : ''), $chat->status == erLhcoreClassModelChat::STATUS_BOT_CHAT);
if ($sentFileMsgId === false) {
$failedEmbedCodes[] = $telegramFile['embed'];
} else {
$this->saveTopicMsgId($botMessage, $sentFileMsgId);
}
$fileIndex++;
}
Expand Down Expand Up @@ -926,7 +1013,17 @@ public function chatStarted($params)

$sendData = Longman\TelegramBot\Request::sendMessage($data);

if (!$sendData->isOk()) {
if ($sendData->isOk()) {
$firstVisitorMsg = erLhcoreClassModelmsg::findOne(['filter' => ['chat_id' => $params['chat']->id, 'user_id' => 0], 'sort' => 'id ASC']);
if ($firstVisitorMsg instanceof erLhcoreClassModelmsg) {
$this->saveTopicMsgId($firstVisitorMsg, $sendData->getResult()->getMessageId());
} else {
$firstMsg = erLhcoreClassModelmsg::findOne(['filter' => ['chat_id' => $params['chat']->id], 'sort' => 'id ASC']);
if ($firstMsg instanceof erLhcoreClassModelmsg) {
$this->saveTopicMsgId($firstMsg, $sendData->getResult()->getMessageId());
}
}
} else {

// Try first time to create a topic if old one is gone
if ($sendData->getErrorCode() == 400 && (str_contains($sendData->getDescription(), 'message thread not found') || str_contains($sendData->getDescription(), 'TOPIC_DELETED'))) {
Expand All @@ -946,7 +1043,17 @@ public function chatStarted($params)
$data['message_thread_id'] = $tChat->tchat_id;
$sendData = Longman\TelegramBot\Request::sendMessage($data);

if (!$sendData->isOk()) {
if ($sendData->isOk()) {
$firstVisitorMsg = erLhcoreClassModelmsg::findOne(['filter' => ['chat_id' => $params['chat']->id, 'user_id' => 0], 'sort' => 'id ASC']);
if ($firstVisitorMsg instanceof erLhcoreClassModelmsg) {
$this->saveTopicMsgId($firstVisitorMsg, $sendData->getResult()->getMessageId());
} else {
$firstMsg = erLhcoreClassModelmsg::findOne(['filter' => ['chat_id' => $params['chat']->id], 'sort' => 'id ASC']);
if ($firstMsg instanceof erLhcoreClassModelmsg) {
$this->saveTopicMsgId($firstMsg, $sendData->getResult()->getMessageId());
}
}
} else {
erLhcoreClassLog::write('['.$sendData->getErrorCode().']'. $sendData->getDescription(),
ezcLog::SUCCESS_AUDIT,
array(
Expand All @@ -964,8 +1071,11 @@ public function chatStarted($params)
$failedEmbedCodes = array();

foreach ($initialTelegramFiles as $initialTelegramFile) {
if ($this->sendTelegramChatFile($tChat, $initialTelegramFile['file'], $this->getTelegramFileCaption($initialTelegramFile['msg'], $params['chat'], $initialTelegramFile['file']['file'], $initialTelegramFile['text']), $params['chat']->status == erLhcoreClassModelChat::STATUS_BOT_CHAT) === false) {
$sentFileMsgId = $this->sendTelegramChatFile($tChat, $initialTelegramFile['file'], $this->getTelegramFileCaption($initialTelegramFile['msg'], $params['chat'], $initialTelegramFile['file']['file'], $initialTelegramFile['text']), $params['chat']->status == erLhcoreClassModelChat::STATUS_BOT_CHAT);
if ($sentFileMsgId === false) {
$failedEmbedCodes[] = $initialTelegramFile['file']['embed'];
} else if (isset($initialTelegramFile['msg']) && $initialTelegramFile['msg'] instanceof erLhcoreClassModelmsg) {
$this->saveTopicMsgId($initialTelegramFile['msg'], $sentFileMsgId);
}
}

Expand Down
45 changes: 44 additions & 1 deletion classes/Commands/GenericmessageCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,50 @@ public function execute(): ServerResponse

if ($ignoreMessage == false) {
$msg = new \erLhcoreClassModelmsg();
$msg->msg = $text;
$msgText = $text;
$metaMsg = [];

$replyTo = $message->getReplyToMessage();
$isExplicitReply = ($replyTo && (int)$replyTo->getMessageId() !== (int)$message->getMessageThreadId() && !$replyTo->getForumTopicCreated());

if ($isExplicitReply) {
$replyTopicMsgId = (int)$replyTo->getMessageId();
$metaMsg['tg_topic_msg_id'] = (int)$message->getMessageId();

$replyMsg = \erLhcoreClassModelmsg::findOne([
'filter' => ['chat_id' => $chat->id],
'customfilter' => ['`meta_msg` != \'\' AND JSON_VALID(`meta_msg`) AND JSON_EXTRACT(meta_msg, \'$.tg_topic_msg_id\') = ' . $replyTopicMsgId]
]);

if ($replyMsg instanceof \erLhcoreClassModelmsg) {
$quoteText = $message->getQuote() ? trim($message->getQuote()->getText()) : $replyMsg->msg;
$replyNick = $replyMsg->name_support != '' ? $replyMsg->name_support : $chat->nick;
$msgText = '[quote=' . $replyMsg->id . ']' . $quoteText . '[/quote]' . $msgText;

$metaMsg['content'] = [
'quote' => [
'id' => $replyMsg->id,
'text' => $quoteText,
'nick' => $replyNick
],
'reply_to' => [
'db_msg_id' => $replyMsg->id
]
];

if (isset($replyMsg->meta_msg_array['iwh_msg_id']) && $replyMsg->meta_msg_array['iwh_msg_id'] != '') {
$metaMsg['content']['reply_to']['iwh_msg_id'] = $replyMsg->meta_msg_array['iwh_msg_id'];
}
}
} else {
$metaMsg['tg_topic_msg_id'] = (int)$message->getMessageId();
}

$msg->msg = $msgText;
if (!empty($metaMsg)) {
$msg->meta_msg = json_encode($metaMsg);
$msg->meta_msg_array = $metaMsg;
}
$msg->chat_id = $chat->id;
$msg->user_id = $messageUserId;
$msg->time = time();
Expand Down
Loading