telegabber/telegram/handlers.go

432 lines
12 KiB
Go
Raw Permalink Normal View History

2019-11-29 00:51:41 +00:00
package telegram
import (
2019-12-03 21:14:32 +00:00
"fmt"
"os"
"path/filepath"
2019-11-30 00:41:22 +00:00
"strconv"
2019-12-01 13:13:45 +00:00
"strings"
2019-12-03 21:14:32 +00:00
"sync"
2019-11-30 00:41:22 +00:00
2020-01-13 17:22:45 +00:00
"dev.narayana.im/narayana/telegabber/telegram/formatter"
2019-11-29 11:48:27 +00:00
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
2019-11-29 00:51:41 +00:00
log "github.com/sirupsen/logrus"
2022-01-17 20:45:40 +00:00
"github.com/zelenin/go-tdlib/client"
2019-11-29 00:51:41 +00:00
)
func uhOh() {
log.Fatal("Update type mismatch")
}
2019-12-03 21:14:32 +00:00
func int64SliceToStringSlice(ints []int64) []string {
strings := make([]string, len(ints))
wg := sync.WaitGroup{}
for i, xi := range ints {
wg.Add(1)
go func(i int, xi int64) {
strings[i] = strconv.FormatInt(xi, 10)
wg.Done()
}(i, xi)
}
wg.Wait()
return strings
}
func (c *Client) getChatMessageLock(chatID int64) *sync.Mutex {
lock, ok := c.locks.chatMessageLocks[chatID]
if !ok {
lock = &sync.Mutex{}
c.locks.chatMessageLocks[chatID] = lock
}
return lock
}
func (c *Client) cleanTempFile(path string) {
os.Remove(path)
dir := filepath.Dir(path)
dirName := filepath.Base(dir)
if strings.HasPrefix(dirName, "telegabber-") {
os.Remove(dir)
}
}
func (c *Client) sendMarker(chatId, messageId int64, typ gateway.MarkerType) {
xmppId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, chatId, messageId)
if err != nil {
xmppId = strconv.FormatInt(messageId, 10)
}
var stringType string
if typ == gateway.MarkerTypeReceived {
stringType = "received"
} else if typ == gateway.MarkerTypeDisplayed {
stringType = "displayed"
}
log.WithFields(log.Fields{
2024-04-12 02:24:22 +00:00
"xmppId": xmppId,
}).Debugf("marker: %s", stringType)
gateway.SendMessageMarker(
c.jid,
strconv.FormatInt(chatId, 10),
c.xmpp,
typ,
xmppId,
)
}
2019-11-29 00:51:41 +00:00
func (c *Client) updateHandler() {
listener := c.client.GetListener()
defer listener.Close()
for update := range listener.Updates {
if update.GetClass() == client.ClassUpdate {
switch update.GetType() {
case client.TypeUpdateUser:
typedUpdate, ok := update.(*client.UpdateUser)
if !ok {
uhOh()
}
c.updateUser(typedUpdate)
log.Debugf("%#v", typedUpdate.User)
2019-11-29 11:48:27 +00:00
case client.TypeUpdateUserStatus:
typedUpdate, ok := update.(*client.UpdateUserStatus)
if !ok {
uhOh()
}
c.updateUserStatus(typedUpdate)
log.Debugf("%#v", typedUpdate.Status)
2019-11-30 00:41:22 +00:00
case client.TypeUpdateNewChat:
typedUpdate, ok := update.(*client.UpdateNewChat)
if !ok {
uhOh()
}
c.updateNewChat(typedUpdate)
log.Debugf("%#v", typedUpdate.Chat)
2022-02-06 13:25:46 +00:00
case client.TypeUpdateChatPosition:
typedUpdate, ok := update.(*client.UpdateChatPosition)
if !ok {
uhOh()
}
c.updateChatPosition(typedUpdate)
log.Debugf("%#v", typedUpdate)
case client.TypeUpdateChatLastMessage:
typedUpdate, ok := update.(*client.UpdateChatLastMessage)
if !ok {
uhOh()
}
c.updateChatLastMessage(typedUpdate)
log.Debugf("%#v", typedUpdate)
2019-12-01 13:13:45 +00:00
case client.TypeUpdateNewMessage:
typedUpdate, ok := update.(*client.UpdateNewMessage)
if !ok {
uhOh()
}
c.updateNewMessage(typedUpdate)
log.Debugf("%#v", typedUpdate.Message)
2019-12-03 21:14:32 +00:00
case client.TypeUpdateMessageContent:
typedUpdate, ok := update.(*client.UpdateMessageContent)
if !ok {
uhOh()
}
c.updateMessageContent(typedUpdate)
log.Debugf("%#v", typedUpdate.NewContent)
2019-12-03 21:14:32 +00:00
case client.TypeUpdateDeleteMessages:
typedUpdate, ok := update.(*client.UpdateDeleteMessages)
if !ok {
uhOh()
}
c.updateDeleteMessages(typedUpdate)
2019-12-17 01:56:11 +00:00
case client.TypeUpdateAuthorizationState:
typedUpdate, ok := update.(*client.UpdateAuthorizationState)
if !ok {
uhOh()
}
c.updateAuthorizationState(typedUpdate)
case client.TypeUpdateMessageSendSucceeded:
typedUpdate, ok := update.(*client.UpdateMessageSendSucceeded)
if !ok {
uhOh()
}
c.updateMessageSendSucceeded(typedUpdate)
case client.TypeUpdateMessageSendFailed:
typedUpdate, ok := update.(*client.UpdateMessageSendFailed)
if !ok {
uhOh()
}
c.updateMessageSendFailed(typedUpdate)
case client.TypeUpdateChatTitle:
typedUpdate, ok := update.(*client.UpdateChatTitle)
if !ok {
uhOh()
}
c.updateChatTitle(typedUpdate)
case client.TypeUpdateChatReadOutbox:
typedUpdate, ok := update.(*client.UpdateChatReadOutbox)
if !ok {
uhOh()
}
c.updateChatReadOutbox(typedUpdate)
2019-11-29 00:51:41 +00:00
default:
// log only handled types
continue
}
log.Debugf("%#v", update)
}
}
}
2019-12-03 22:17:36 +00:00
// new user discovered
2019-11-29 00:51:41 +00:00
func (c *Client) updateUser(update *client.UpdateUser) {
2022-01-17 20:45:40 +00:00
c.cache.SetUser(update.User.Id, update.User)
show, status, presenceType := c.userStatusToText(update.User.Status, update.User.Id)
go c.ProcessStatusUpdate(update.User.Id, status, show, gateway.SPType(presenceType))
2019-11-29 00:51:41 +00:00
}
2019-11-29 11:48:27 +00:00
2019-12-03 22:17:36 +00:00
// user status changed
2019-11-29 11:48:27 +00:00
func (c *Client) updateUserStatus(update *client.UpdateUserStatus) {
show, status, presenceType := c.userStatusToText(update.Status, update.UserId)
go c.ProcessStatusUpdate(update.UserId, status, show, gateway.SPImmed(false), gateway.SPType(presenceType))
2019-11-30 00:41:22 +00:00
}
2019-12-03 22:17:36 +00:00
// new chat discovered
2019-11-30 00:41:22 +00:00
func (c *Client) updateNewChat(update *client.UpdateNewChat) {
go func() {
if update.Chat != nil && update.Chat.Photo != nil && update.Chat.Photo.Small != nil {
2022-02-03 21:01:38 +00:00
_, err := c.DownloadFile(update.Chat.Photo.Small.Id, 10, true)
if err != nil {
log.Error("Failed to download the chat photo")
}
2019-11-30 00:41:22 +00:00
}
2022-01-17 20:45:40 +00:00
c.cache.SetChat(update.Chat.Id, update.Chat)
2019-11-30 00:41:22 +00:00
2022-02-06 13:25:46 +00:00
if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
c.subscribeToID(update.Chat.Id, update.Chat)
}
2019-11-30 00:41:22 +00:00
2022-01-17 20:45:40 +00:00
if update.Chat.Id < 0 {
c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat")
}
}()
2019-11-29 11:48:27 +00:00
}
2019-12-01 13:13:45 +00:00
2022-02-06 13:25:46 +00:00
// chat position is updated
func (c *Client) updateChatPosition(update *client.UpdateChatPosition) {
if update.Position != nil && update.Position.Order != 0 {
go c.subscribeToID(update.ChatId, nil)
}
}
// chat last message is updated
func (c *Client) updateChatLastMessage(update *client.UpdateChatLastMessage) {
if update.Positions != nil && len(update.Positions) > 0 {
go c.subscribeToID(update.ChatId, nil)
}
}
2019-12-03 22:17:36 +00:00
// message received
2019-12-01 13:13:45 +00:00
func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
chatId := update.Message.ChatId
if c.Session.IsChatIgnored(chatId) {
return
}
// guarantee sequential message delivering per chat
lock := c.getChatMessageLock(chatId)
go func() {
lock.Lock()
defer lock.Unlock()
c.updateLastMessageHash(update.Message.ChatId, update.Message.Id, update.Message.Content)
// ignore self outgoing messages
if update.Message.IsOutgoing &&
update.Message.SendingState != nil &&
update.Message.SendingState.MessageSendingStateType() == client.TypeMessageSendingStatePending {
return
}
log.WithFields(log.Fields{
"chat_id": chatId,
}).Warn("New message from chat")
2019-12-01 13:13:45 +00:00
c.ProcessIncomingMessage(chatId, update.Message)
}()
2019-12-01 13:13:45 +00:00
}
2019-12-03 21:14:32 +00:00
2019-12-03 22:17:36 +00:00
// message content updated
2019-12-03 21:14:32 +00:00
func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
if c.Session.IsChatIgnored(update.ChatId) {
return
}
markupFunction := c.getFormatter()
defer c.updateLastMessageHash(update.ChatId, update.MessageId, update.NewContent)
log.Debugf("newContent: %#v", update.NewContent)
lock := c.getChatMessageLock(update.ChatId)
lock.Lock()
lock.Unlock()
c.SendMessageLock.Lock()
c.SendMessageLock.Unlock()
xmppId, xmppIdErr := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, update.ChatId, update.MessageId)
var ignoredResource string
if xmppIdErr == nil {
ignoredResource = c.popFromEditOutbox(xmppId)
} else {
log.Infof("Couldn't retrieve XMPP message ids for %v, an echo may happen", update.MessageId)
}
log.Infof("ignoredResource: %v", ignoredResource)
jids := c.getCarbonFullJids(true, ignoredResource)
if len(jids) == 0 {
log.Info("The only resource is ignored, aborting")
return
}
if update.NewContent.MessageContentType() == client.TypeMessageText && c.hasLastMessageHashChanged(update.ChatId, update.MessageId, update.NewContent) {
2019-12-03 21:14:32 +00:00
textContent := update.NewContent.(*client.MessageText)
log.Debugf("textContent: %#v", textContent.Text)
var replaceId string
sId := strconv.FormatInt(update.MessageId, 10)
var isCarbon bool
// use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
if c.Session.NativeEdits {
lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
if xmppIdErr != nil {
xmppId = sId
}
if ok && lastXmppId == xmppId {
replaceId = xmppId
} else {
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId)
}
}
message, messageErr := c.client.GetMessage(&client.GetMessageRequest{
2024-04-12 00:59:49 +00:00
ChatId: update.ChatId,
MessageId: update.MessageId,
})
var prefix string
if messageErr == nil {
2024-04-12 00:59:49 +00:00
isCarbon = c.isCarbonsEnabled() && message.IsOutgoing
// reply correction support in clients is suboptimal yet, so cut them out for now
prefix, _ = c.messageToPrefix(message, "", "", true)
2024-04-12 00:59:49 +00:00
} else {
log.Errorf("No message %v/%v found, cannot reliably determine if it's a carbon", update.ChatId, update.MessageId)
}
var text strings.Builder
if replaceId == "" {
var editChar string
if c.Session.AsciiArrows {
editChar = "e"
} else {
editChar = "✎"
}
text.WriteString(fmt.Sprintf("%s %v | ", editChar, update.MessageId))
} else if prefix != "" {
text.WriteString(prefix)
text.WriteString(c.getPrefixSeparator(update.ChatId))
}
text.WriteString(formatter.Format(
textContent.Text.Text,
textContent.Text.Entities,
markupFunction,
))
sChatId := strconv.FormatInt(update.ChatId, 10)
for _, jid := range jids {
gateway.SendMessage(jid, sChatId, text.String(), "e"+sId, c.xmpp, nil, replaceId, isCarbon, false)
}
2019-12-03 21:14:32 +00:00
}
}
2019-12-03 22:17:36 +00:00
// message(s) deleted
2019-12-03 21:14:32 +00:00
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
if update.IsPermanent {
if c.Session.IsChatIgnored(update.ChatId) {
return
}
var deleteChar string
if c.Session.AsciiArrows {
deleteChar = "X "
} else {
deleteChar = "✗ "
}
text := deleteChar + strings.Join(int64SliceToStringSlice(update.MessageIds), ",")
2023-03-05 08:00:53 +00:00
gateway.SendTextMessage(c.jid, strconv.FormatInt(update.ChatId, 10), text, c.xmpp)
2019-12-03 21:14:32 +00:00
}
}
2019-12-03 22:17:36 +00:00
2019-12-17 01:56:11 +00:00
func (c *Client) updateAuthorizationState(update *client.UpdateAuthorizationState) {
switch update.AuthorizationState.AuthorizationStateType() {
case client.TypeAuthorizationStateClosing:
log.Warn("Closing the updates listener")
case client.TypeAuthorizationStateClosed:
log.Warn("Closed the updates listener")
c.forceClose()
}
}
func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucceeded) {
// replace message ID in local database
2023-06-05 08:22:13 +00:00
log.Debugf("replace message %v with %v", update.OldMessageId, update.Message.Id)
if err := gateway.IdsDB.ReplaceTgId(c.Session.Login, c.jid, update.Message.ChatId, update.OldMessageId, update.Message.Id); err != nil {
2023-06-08 17:33:22 +00:00
log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
2023-06-05 08:22:13 +00:00
}
c.updateLastMessageHash(update.Message.ChatId, update.Message.Id, update.Message.Content)
c.sendMarker(update.Message.ChatId, update.Message.Id, gateway.MarkerTypeReceived)
// clean uploaded files
file, _ := c.contentToFile(update.Message.Content)
if file != nil && file.Local != nil {
c.cleanTempFile(file.Local.Path)
}
}
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
// clean uploaded files
file, _ := c.contentToFile(update.Message.Content)
if file != nil && file.Local != nil {
c.cleanTempFile(file.Local.Path)
}
}
// chat title changed
func (c *Client) updateChatTitle(update *client.UpdateChatTitle) {
gateway.SetNickname(c.jid, strconv.FormatInt(update.ChatId, 10), update.Title, c.xmpp)
// set also the status (for group chats only)
2023-06-30 12:48:36 +00:00
chat, user, _ := c.GetContactByID(update.ChatId, nil)
if user == nil {
c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", gateway.SPImmed(true))
}
2023-06-30 12:48:36 +00:00
// update chat title in the cache
if chat != nil {
chat.Title = update.Title
}
}
func (c *Client) updateChatReadOutbox(update *client.UpdateChatReadOutbox) {
c.sendMarker(update.ChatId, update.LastReadOutboxMessageId, gateway.MarkerTypeDisplayed)
}