aboutsummaryrefslogtreecommitdiff
path: root/telegram/handlers.go
blob: 93ac2846d5ea8bd1771cbc64284c8b8854c34f14 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package telegram

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"

	"dev.narayana.im/narayana/telegabber/telegram/formatter"
	"dev.narayana.im/narayana/telegabber/xmpp/gateway"

	log "github.com/sirupsen/logrus"
	"github.com/zelenin/go-tdlib/client"
)

func uhOh() {
	log.Fatal("Update type mismatch")
}

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) 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)
			case client.TypeUpdateUserStatus:
				typedUpdate, ok := update.(*client.UpdateUserStatus)
				if !ok {
					uhOh()
				}
				c.updateUserStatus(typedUpdate)
				log.Debugf("%#v", typedUpdate.Status)
			case client.TypeUpdateNewChat:
				typedUpdate, ok := update.(*client.UpdateNewChat)
				if !ok {
					uhOh()
				}
				c.updateNewChat(typedUpdate)
				log.Debugf("%#v", typedUpdate.Chat)
			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)
			case client.TypeUpdateNewMessage:
				typedUpdate, ok := update.(*client.UpdateNewMessage)
				if !ok {
					uhOh()
				}
				c.updateNewMessage(typedUpdate)
				log.Debugf("%#v", typedUpdate.Message)
			case client.TypeUpdateMessageEdited:
				typedUpdate, ok := update.(*client.UpdateMessageEdited)
				if !ok {
					uhOh()
				}
				c.updateMessageEdited(typedUpdate)
				log.Debugf("%#v", typedUpdate)
			case client.TypeUpdateMessageContent:
				typedUpdate, ok := update.(*client.UpdateMessageContent)
				if !ok {
					uhOh()
				}
				c.updateMessageContent(typedUpdate)
				log.Debugf("%#v", typedUpdate.NewContent)
			case client.TypeUpdateDeleteMessages:
				typedUpdate, ok := update.(*client.UpdateDeleteMessages)
				if !ok {
					uhOh()
				}
				c.updateDeleteMessages(typedUpdate)
			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)
			default:
				// log only handled types
				continue
			}

			log.Debugf("%#v", update)
		}
	}
}

// new user discovered
func (c *Client) updateUser(update *client.UpdateUser) {
	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))
}

// user status changed
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))
}

// new chat discovered
func (c *Client) updateNewChat(update *client.UpdateNewChat) {
	go func() {
		if update.Chat != nil && update.Chat.Photo != nil && update.Chat.Photo.Small != nil {
			_, err := c.DownloadFile(update.Chat.Photo.Small.Id, 10, true)

			if err != nil {
				log.Error("Failed to download the chat photo")
			}
		}

		c.cache.SetChat(update.Chat.Id, update.Chat)

		if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
			c.subscribeToID(update.Chat.Id, update.Chat)
		}

		if update.Chat.Id < 0 {
			c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat")
		}
	}()
}

// 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)
	}
}

// message received
func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
	chatId := update.Message.ChatId

	c.SendMessageLock.Lock()
	c.SendMessageLock.Unlock()
	xmppId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, chatId, update.Message.Id)
	var ignoredResource string
	if err == nil {
		ignoredResource = c.popFromOutbox(xmppId)
	} else {
		log.Infof("Couldn't retrieve XMPP message ids for %v, an echo may happen", update.Message.Id)
	}

	// guarantee sequential message delivering per chat
	lock := c.getChatMessageLock(chatId)
	go func() {
		lock.Lock()
		defer lock.Unlock()

		log.WithFields(log.Fields{
			"chat_id": chatId,
		}).Warn("New message from chat")

		c.ProcessIncomingMessage(chatId, update.Message, ignoredResource)
	}()
}

// message content edited
func (c *Client) updateMessageEdited(update *client.UpdateMessageEdited) {
	c.addToEditQueue(update.ChatId, update.MessageId)
}

// message content updated
func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
	markupFunction := formatter.EntityToXEP0393

	c.SendMessageLock.Lock()
	c.SendMessageLock.Unlock()
	xmppId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, update.ChatId, update.MessageId)
	var ignoredResource string
	if err == nil {
		ignoredResource = c.popFromOutbox(xmppId)
	} else {
		log.Infof("Couldn't retrieve XMPP message ids for %v, an echo may happen", update.MessageId)
	}
	log.Infof("ignoredResource: %v", ignoredResource)

	if !c.deleteFromEditQueue(update.ChatId, update.MessageId) {
		log.WithFields(log.Fields{
			"chatId":    update.ChatId,
			"messageId": update.MessageId,
		}).Infof("Content update with no preceding message edit, ignoring")
		return
	}

	jids := c.getCarbonFullJids(true, ignoredResource)
	if len(jids) == 0 {
		log.Info("The only resource is ignored, aborting")
		return
	}

	if update.NewContent.MessageContentType() == client.TypeMessageText {
		textContent := update.NewContent.(*client.MessageText)
		var editChar string
		if c.Session.AsciiArrows {
			editChar = "e "
		} else {
			editChar = "✎ "
		}
		text := editChar + fmt.Sprintf("%v | %s", update.MessageId, formatter.Format(
			textContent.Text.Text,
			textContent.Text.Entities,
			markupFunction,
		))
		for _, jid := range jids {
			gateway.SendMessage(jid, strconv.FormatInt(update.ChatId, 10), text, "e"+strconv.FormatInt(update.MessageId, 10), c.xmpp, nil, false)
		}
	}
}

// message(s) deleted
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
	if update.IsPermanent {
		var deleteChar string
		if c.Session.AsciiArrows {
			deleteChar = "X "
		} else {
			deleteChar = "✗ "
		}
		text := deleteChar + strings.Join(int64SliceToStringSlice(update.MessageIds), ",")
		gateway.SendTextMessage(c.jid, strconv.FormatInt(update.ChatId, 10), text, c.xmpp)
	}
}

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()
	}
}

// clean uploaded files
func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucceeded) {
	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 {
		log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
	}

	file, _ := c.contentToFile(update.Message.Content)
	if file != nil && file.Local != nil {
		c.cleanTempFile(file.Local.Path)
	}
}
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
	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)
	chat, user, _ := c.GetContactByID(update.ChatId, nil)
	if user == nil {
		c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", gateway.SPImmed(true))
	}

	// update chat title in the cache
	if chat != nil {
		chat.Title = update.Title
	}
}