aboutsummaryrefslogtreecommitdiff
path: root/xmpp/handlers.go
blob: 08278d2477e0797abe09f0f71c8b491be410c5f1 (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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
package xmpp

import (
	"bytes"
	"encoding/base64"
	"encoding/xml"
	"fmt"
	"github.com/pkg/errors"
	"io"
	"sort"
	"strconv"
	"strings"

	"dev.narayana.im/narayana/telegabber/persistence"
	"dev.narayana.im/narayana/telegabber/telegram"
	"dev.narayana.im/narayana/telegabber/xmpp/extensions"
	"dev.narayana.im/narayana/telegabber/xmpp/gateway"

	log "github.com/sirupsen/logrus"
	"github.com/soheilhy/args"
	"gosrc.io/xmpp"
	"gosrc.io/xmpp/stanza"
)

const (
	TypeVCardTemp byte = iota
	TypeVCard4
)
const NodeVCard4 string = "urn:xmpp:vcard4"
const NSCommand string = "http://jabber.org/protocol/commands"

func logPacketType(p stanza.Packet) {
	log.Warnf("Ignoring packet: %T\n", p)
}

// HandleIq processes an incoming XMPP iq
func HandleIq(s xmpp.Sender, p stanza.Packet) {
	iq, ok := p.(*stanza.IQ)
	if !ok {
		logPacketType(p)
		return
	}

	log.Debugf("%#v", iq)
	if iq.Type == "get" {
		_, ok := iq.Payload.(*extensions.IqVcardTemp)
		if ok {
			go handleGetVcardIq(s, iq, TypeVCardTemp)
			return
		}
		pubsub, ok := iq.Payload.(*stanza.PubSubGeneric)
		if ok {
			if pubsub.Items != nil && pubsub.Items.Node == NodeVCard4 {
				go handleGetVcardIq(s, iq, TypeVCard4)
				return
			}
		}
		discoInfo, ok := iq.Payload.(*stanza.DiscoInfo)
		if ok {
			go handleGetDiscoInfo(s, iq, discoInfo)
			return
		}
		discoItems, ok := iq.Payload.(*stanza.DiscoItems)
		if ok {
			go handleGetDiscoItems(s, iq, discoItems)
			return
		}
		_, ok = iq.Payload.(*extensions.QueryRegister)
		if ok {
			go handleGetQueryRegister(s, iq)
			return
		}
	} else if iq.Type == "set" {
		query, ok := iq.Payload.(*extensions.QueryRegister)
		if ok {
			go handleSetQueryRegister(s, iq, query)
			return
		}
		command, ok := iq.Payload.(*stanza.Command)
		if ok {
			go handleSetQueryCommand(s, iq, command)
			return
		}
	}
}

// HandleMessage processes an incoming XMPP message
func HandleMessage(s xmpp.Sender, p stanza.Packet) {
	msg, ok := p.(stanza.Message)
	if !ok {
		logPacketType(p)
		return
	}

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	if msg.Type != "error" && msg.Body != "" {
		log.WithFields(log.Fields{
			"from": msg.From,
			"to":   msg.To,
		}).Warn("Message")
		log.Debugf("%#v", msg)

		bare, resource, ok := gateway.SplitJID(msg.From)
		if !ok {
			return
		}

		gatewayJid := gateway.Jid.Bare()

		session, ok := sessions[bare]
		if !ok {
			if msg.To == gatewayJid {
				gateway.SubscribeToTransport(component, msg.From)
			} else {
				log.Error("Message from stranger")
			}
			return
		}

		toID, ok := toToID(msg.To)
		if ok {
			var reply extensions.Reply
			var fallback extensions.Fallback
			var replace extensions.Replace
			msg.Get(&reply)
			msg.Get(&fallback)
			msg.Get(&replace)
			log.Debugf("reply: %#v", reply)
			log.Debugf("fallback: %#v", fallback)
			log.Debugf("replace: %#v", replace)

			var replyId int64
			var err error
			text := msg.Body
			if len(reply.Id) > 0 {
				chatId, msgId, err := gateway.IdsDB.GetByXmppId(session.Session.Login, bare, reply.Id)
				if err == nil {
					if chatId != toID {
						log.Warnf("Chat mismatch: %v ≠ %v", chatId, toID)
					} else {
						replyId = msgId
						log.Debugf("replace tg: %#v %#v", chatId, msgId)
					}
				} else {
					id := reply.Id
					if id[0] == 'e' {
						id = id[1:]
					}
					replyId, err = strconv.ParseInt(id, 10, 64)
					if err != nil {
						log.Warn(errors.Wrap(err, "Failed to parse message ID!"))
					}
				}

				if replyId != 0 && fallback.For == "urn:xmpp:reply:0" && len(fallback.Body) > 0 {
					body := fallback.Body[0]
					var start, end int64
					start, err = strconv.ParseInt(body.Start, 10, 64)
					if err != nil {
						log.WithFields(log.Fields{
							"start": body.Start,
						}).Warn(errors.Wrap(err, "Failed to parse fallback start!"))
					}
					end, err = strconv.ParseInt(body.End, 10, 64)
					if err != nil {
						log.WithFields(log.Fields{
							"end": body.End,
						}).Warn(errors.Wrap(err, "Failed to parse fallback end!"))
					}

					fullRunes := []rune(text)
					cutRunes := make([]rune, 0, len(text)-int(end-start))
					cutRunes = append(cutRunes, fullRunes[:start]...)
					cutRunes = append(cutRunes, fullRunes[end:]...)
					text = string(cutRunes)
				}
			}
			var replaceId int64
			if replace.Id != "" {
				chatId, msgId, err := gateway.IdsDB.GetByXmppId(session.Session.Login, bare, replace.Id)
				if err == nil {
					if chatId != toID {
						gateway.SendTextMessage(msg.From, strconv.FormatInt(toID, 10), "<ERROR: Chat mismatch>", component)
						return
					}
					replaceId = msgId
					log.Debugf("replace tg: %#v %#v", chatId, msgId)
				} else {
					gateway.SendTextMessage(msg.From, strconv.FormatInt(toID, 10), "<ERROR: Could not find matching message to edit>", component)
					return
				}
			}

			session.SendMessageLock.Lock()
			defer session.SendMessageLock.Unlock()
			tgMessageId := session.ProcessOutgoingMessage(toID, text, msg.From, replyId, replaceId)
			if tgMessageId != 0 {
				if replaceId != 0 {
					// not needed (is it persistent among clients though?)
					/* err = gateway.IdsDB.ReplaceIdPair(session.Session.Login, bare, replace.Id, msg.Id, tgMessageId)
					if err != nil {
						log.Errorf("Failed to replace id %v with %v %v", replace.Id, msg.Id, tgMessageId)
					} */
					session.AddToEditOutbox(replace.Id, resource)
				} else {
					err = gateway.IdsDB.Set(session.Session.Login, bare, toID, tgMessageId, msg.Id)
					if err == nil {
						session.AddToOutbox(msg.Id, resource)
						session.UpdateLastChatMessageId(toID, msg.Id)
					} else {
						log.Errorf("Failed to save ids %v/%v %v", toID, tgMessageId, msg.Id)
					}
				}
			} else {
				/*
					// if a message failed to edit on Telegram side, match new XMPP ID with old Telegram ID anyway
					if replaceId != 0 {
						err = gateway.IdsDB.ReplaceXmppId(session.Session.Login, bare, replace.Id, msg.Id)
						if err != nil {
							log.Errorf("Failed to replace id %v with %v", replace.Id, msg.Id)
						}
					} */
			}
			return
		} else {
			toJid, err := stanza.NewJid(msg.To)
			if err == nil && toJid.Bare() == gatewayJid && (strings.HasPrefix(msg.Body, "/") || strings.HasPrefix(msg.Body, "!")) {
				response := session.ProcessTransportCommand(msg.Body, resource)
				if response != "" {
					gateway.SendServiceMessage(msg.From, response, component)
				}
				return
			}
		}
		log.Warn("Unknown purpose of the message, skipping")
	}

	if msg.Body == "" {
		var privilege1 extensions.ComponentPrivilege1
		if ok := msg.Get(&privilege1); ok {
			log.Debugf("privilege1: %#v", privilege1)
		}

		for _, perm := range privilege1.Perms {
			if perm.Access == "message" && perm.Type == "outgoing" {
				gateway.MessageOutgoingPermissionVersion = 1
			}
		}

		var privilege2 extensions.ComponentPrivilege2
		if ok := msg.Get(&privilege2); ok {
			log.Debugf("privilege2: %#v", privilege2)
		}

		for _, perm := range privilege2.Perms {
			if perm.Access == "message" && perm.Type == "outgoing" {
				gateway.MessageOutgoingPermissionVersion = 2
			}
		}

		var displayed stanza.MarkDisplayed
		msg.Get(&displayed)
		if displayed.ID != "" {
			log.Debugf("displayed: %#v", displayed)

			bare, _, ok := gateway.SplitJID(msg.From)
			if !ok {
				return
			}
			session, ok := sessions[bare]
			if !ok {
				return
			}
			toID, ok := toToID(msg.To)
			if !ok {
				return
			}
			msgId, err := strconv.ParseInt(displayed.ID, 10, 64)
			if err == nil {
				session.MarkAsRead(toID, msgId)
			}
			return
		}
	}

	if msg.Type == "error" {
		log.Errorf("MESSAGE ERROR: %#v", p)

		if msg.XMLName.Space == "jabber:component:accept" && msg.Error.Code == 401 {
			suffix := "@" + msg.From
			for bare := range sessions {
				if strings.HasSuffix(bare, suffix) {
					gateway.SendServiceMessage(bare, "Your server \""+msg.From+"\" does not allow to send carbons", component)
				}
			}
		}
	}
}

// HandlePresence processes an incoming XMPP presence
func HandlePresence(s xmpp.Sender, p stanza.Packet) {
	prs, ok := p.(stanza.Presence)
	if !ok {
		logPacketType(p)
		return
	}

	if prs.Type == "subscribe" {
		handleSubscription(s, prs)
	}
	if prs.To == gateway.Jid.Bare() {
		handlePresence(s, prs)
	}
}

func handleSubscription(s xmpp.Sender, p stanza.Presence) {
	log.WithFields(log.Fields{
		"from": p.From,
		"to":   p.To,
	}).Warn("Subscription request")
	log.Debugf("%#v", p)

	reply := stanza.Presence{Attrs: stanza.Attrs{
		From: p.To,
		To:   p.From,
		Id:   p.Id,
		Type: "subscribed",
	}}

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	_ = gateway.ResumableSend(component, reply)

	toID, ok := toToID(p.To)
	if !ok {
		return
	}
	bare, _, ok := gateway.SplitJID(p.From)
	if !ok {
		return
	}
	session, ok := getTelegramInstance(bare, &persistence.Session{}, component)
	if !ok {
		return
	}
	go session.ProcessStatusUpdate(toID, "", "", gateway.SPImmed(false))
}

func handlePresence(s xmpp.Sender, p stanza.Presence) {
	presenceType := p.Type
	if presenceType == "" {
		presenceType = "online"
	}

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	log.WithFields(log.Fields{
		"type": presenceType,
		"from": p.From,
		"to":   p.To,
	}).Warn("Presence")
	log.Debugf("%#v", p)

	// create session
	bare, resource, ok := gateway.SplitJID(p.From)
	if !ok {
		return
	}
	session, ok := getTelegramInstance(bare, &persistence.Session{}, component)
	if !ok {
		return
	}

	switch p.Type {
	// destroy session
	case "unsubscribed", "unsubscribe":
		if session.Disconnect(resource, false) {
			sessionLock.Lock()
			delete(sessions, bare)
			sessionLock.Unlock()
		}
	// go offline
	case "unavailable", "error":
		session.Disconnect(resource, false)
	// go online
	case "probe", "", "online", "subscribe":
		// due to the weird implementation of go-tdlib wrapper, it won't
		// return the client instance until successful authorization
		go func() {
			err := session.Connect(resource)
			if err != nil {
				log.Error(errors.Wrap(err, "TDlib connection failure"))
			} else {
				for status := range session.StatusesRange() {
					show, description, typ := status.Destruct()
					newArgs := []args.V{
						gateway.SPImmed(false),
					}
					if typ != "" {
						newArgs = append(newArgs, gateway.SPType(typ))
					}
					go session.ProcessStatusUpdate(
						status.ID,
						description,
						show,
						newArgs...,
					)
				}
				session.UpdateChatNicknames()
			}
		}()
	}
}

func handleGetVcardIq(s xmpp.Sender, iq *stanza.IQ, typ byte) {
	log.WithFields(log.Fields{
		"from": iq.From,
		"to":   iq.To,
	}).Warn("VCard request")

	fromJid, err := stanza.NewJid(iq.From)
	if err != nil {
		log.Error("Invalid from JID!")
		return
	}

	session, ok := sessions[fromJid.Bare()]
	if !ok {
		log.Error("IQ from stranger")
		return
	}

	toParts := strings.Split(iq.To, "@")
	toID, err := strconv.ParseInt(toParts[0], 10, 64)
	if err != nil {
		log.Error("Invalid IQ to")
		return
	}
	info, err := session.GetVcardInfo(toID)
	if err != nil {
		log.Error(err)
		return
	}

	answer := stanza.IQ{
		Attrs: stanza.Attrs{
			From: iq.To,
			To:   iq.From,
			Id:   iq.Id,
			Type: "result",
		},
		Payload: makeVCardPayload(typ, iq.To, info, session),
	}
	log.Debugf("%#v", answer)

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	_ = gateway.ResumableSend(component, &answer)
}

func handleGetDiscoInfo(s xmpp.Sender, iq *stanza.IQ, di *stanza.DiscoInfo) {
	answer, err := stanza.NewIQ(stanza.Attrs{
		Type: stanza.IQTypeResult,
		From: iq.To,
		To:   iq.From,
		Id:   iq.Id,
		Lang: "en",
	})
	if err != nil {
		log.Errorf("Failed to create answer IQ: %v", err)
		return
	}

	disco := answer.DiscoInfo()
	_, ok := toToID(iq.To)
	if di.Node == "" {
		if ok {
			disco.AddIdentity("", "account", "registered")
			disco.AddFeatures(stanza.NSMsgChatMarkers)
			disco.AddFeatures(stanza.NSMsgReceipts)
		} else {
			disco.AddIdentity("Telegram Gateway", "gateway", "telegram")
			disco.AddFeatures("jabber:iq:register")
		}
		disco.AddFeatures(NSCommand)
	} else {
		var cmdType telegram.CommandType
		if ok {
			cmdType = telegram.CommandTypeChat
		} else {
			cmdType = telegram.CommandTypeTransport
		}

		for name, command := range telegram.GetCommands(cmdType) {
			if di.Node == name {
				answer.Payload = di
				di.AddIdentity(telegram.CommandToHelpString(name, command), "automation", "command-node")
				di.AddFeatures(NSCommand, "jabber:x:data")
				break
			}
		}
	}
	answer.Payload = disco

	log.Debugf("%#v", answer)

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	_ = gateway.ResumableSend(component, answer)
}

func handleGetDiscoItems(s xmpp.Sender, iq *stanza.IQ, di *stanza.DiscoItems) {
	answer, err := stanza.NewIQ(stanza.Attrs{
		Type: stanza.IQTypeResult,
		From: iq.To,
		To:   iq.From,
		Id:   iq.Id,
		Lang: "en",
	})
	if err != nil {
		log.Errorf("Failed to create answer IQ: %v", err)
		return
	}

	log.Debugf("discoItems: %#v", di)

	_, ok := toToID(iq.To)
	if di.Node == NSCommand {
		answer.Payload = di

		var cmdType telegram.CommandType
		if ok {
			cmdType = telegram.CommandTypeChat
		} else {
			cmdType = telegram.CommandTypeTransport
		}

		commands := telegram.GetCommands(cmdType)
		for name, command := range commands {
			di.AddItem(iq.To, name, telegram.CommandToHelpString(name, command))
		}
	} else {
		answer.Payload = answer.DiscoItems()
	}

	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	_ = gateway.ResumableSend(component, answer)
}

func handleGetQueryRegister(s xmpp.Sender, iq *stanza.IQ) {
	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	answer, err := stanza.NewIQ(stanza.Attrs{
		Type: stanza.IQTypeResult,
		From: iq.To,
		To:   iq.From,
		Id:   iq.Id,
		Lang: "en",
	})
	if err != nil {
		log.Errorf("Failed to create answer IQ: %v", err)
		return
	}

	var login string
	bare, _, ok := gateway.SplitJID(iq.From)
	if ok {
		session, ok := sessions[bare]
		if ok {
			login = session.Session.Login
		}
	}

	var query stanza.IQPayload
	if login == "" {
		query = extensions.QueryRegister{
			Instructions: fmt.Sprintf("Authorization in Telegram is a multi-step process, so please accept %v to your contacts and follow further instructions (provide the authentication code there, etc.).\nFor now, please provide your login.", iq.To),
		}
	} else {
		query = extensions.QueryRegister{
			Instructions: "Already logged in",
			Username:     login,
			Registered:   &extensions.QueryRegisterRegistered{},
		}
	}
	answer.Payload = query

	log.Debugf("%#v", query)

	_ = gateway.ResumableSend(component, answer)

	if login == "" {
		gateway.SubscribeToTransport(component, iq.From)
	}
}

func handleSetQueryRegister(s xmpp.Sender, iq *stanza.IQ, query *extensions.QueryRegister) {
	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	answer, err := stanza.NewIQ(stanza.Attrs{
		Type: stanza.IQTypeResult,
		From: iq.To,
		To:   iq.From,
		Id:   iq.Id,
		Lang: "en",
	})
	if err != nil {
		log.Errorf("Failed to create answer IQ: %v", err)
		return
	}

	defer gateway.ResumableSend(component, answer)

	if query.Remove != nil {
		iqAnswerSetError(answer, query, 405)
		return
	}

	var login string
	var session *telegram.Client
	bare, resource, ok := gateway.SplitJID(iq.From)
	if ok {
		session, ok = sessions[bare]
		if ok {
			login = session.Session.Login
		}
	}

	if login == "" {
		if !ok {
			session, ok = getTelegramInstance(bare, &persistence.Session{}, component)
			if !ok {
				iqAnswerSetError(answer, query, 500)
				return
			}
		}

		err := session.TryLogin(resource, query.Username)
		if err != nil {
			if err.Error() == telegram.TelegramAuthDone {
				iqAnswerSetError(answer, query, 406)
			} else {
				iqAnswerSetError(answer, query, 500)
			}
			return
		}

		err = session.SetPhoneNumber(query.Username)
		if err != nil {
			iqAnswerSetError(answer, query, 500)
			return
		}

		// everything okay, the response should be empty with no payload/error at this point
		gateway.SubscribeToTransport(component, iq.From)
	} else {
		iqAnswerSetError(answer, query, 406)
	}
}

func handleSetQueryCommand(s xmpp.Sender, iq *stanza.IQ, command *stanza.Command) {
	component, ok := s.(*xmpp.Component)
	if !ok {
		log.Error("Not a component")
		return
	}

	answer, err := stanza.NewIQ(stanza.Attrs{
		Type: stanza.IQTypeResult,
		From: iq.To,
		To:   iq.From,
		Id:   iq.Id,
		Lang: "en",
	})
	if err != nil {
		log.Errorf("Failed to create answer IQ: %v", err)
		return
	}

	defer gateway.ResumableSend(component, answer)

	log.Debugf("command: %#v", command)

	bare, resource, ok := gateway.SplitJID(iq.From)
	if !ok {
		return
	}
	toId, toOk := toToID(iq.To)

	var cmdString string
	var cmdType telegram.CommandType
	form, formOk := command.CommandElement.(*stanza.Form)
	if toOk {
		cmdType = telegram.CommandTypeChat
	} else {
		cmdType = telegram.CommandTypeTransport
	}
	if formOk {
		// just for the case the client messed the order somehow
		sort.Slice(form.Fields, func(i int, j int) bool {
			iField := form.Fields[i]
			jField := form.Fields[j]
			if iField != nil && jField != nil {
				ii, iErr := strconv.ParseInt(iField.Var, 10, 64)
				ji, jErr := strconv.ParseInt(jField.Var, 10, 64)
				return iErr == nil && jErr == nil && ii < ji
			}
			return false
		})

		var cmd strings.Builder
		cmd.WriteString("/")
		cmd.WriteString(command.Node)
		for _, field := range form.Fields {
			cmd.WriteString(" ")
			if len(field.ValuesList) > 0 {
				cmd.WriteString(field.ValuesList[0])
			}
		}

		cmdString = cmd.String()
	} else {
		if command.Action == "" || command.Action == stanza.CommandActionExecute {
			cmd, ok := telegram.GetCommand(cmdType, command.Node)
			if ok && len(cmd.Arguments) > 0 {
				var fields []*stanza.Field
				for i, arg := range cmd.Arguments {
					var required *string
					if i < cmd.RequiredArgs {
						dummyString := ""
						required = &dummyString
					}
					fields = append(fields, &stanza.Field{
						Var:      strconv.FormatInt(int64(i), 10),
						Label:    arg,
						Required: required,
					})
				}
				answer.Payload = &stanza.Command{
					SessionId:      command.Node,
					Node:           command.Node,
					Status:         stanza.CommandStatusExecuting,
					CommandElement: &stanza.Form{
						Type:         stanza.FormTypeForm,
						Title:        command.Node,
						Instructions: []string{cmd.Description},
						Fields:       fields,
					},
				}
			} else {
				cmdString = "/" + command.Node
			}
		} else if command.Action == stanza.CommandActionCancel {
			answer.Payload = &stanza.Command{
				SessionId: command.Node,
				Node:      command.Node,
				Status:    stanza.CommandStatusCancelled,
			}
		}
	}

	if cmdString != "" {
		session, ok := sessions[bare]
		if !ok {
			return
		}

		var response string
		if toOk {
			response, _ = session.ProcessChatCommand(toId, cmdString)
		} else {
			response = session.ProcessTransportCommand(cmdString, resource)
		}

		answer.Payload = &stanza.Command{
			SessionId:      command.Node,
			Node:           command.Node,
			Status:         stanza.CommandStatusCompleted,
			CommandElement: &stanza.Note{
				Text: response,
				Type: stanza.CommandNoteTypeInfo,
			},
		}

		log.Debugf("command response: %#v", answer.Payload)
	}
}

func iqAnswerSetError(answer *stanza.IQ, payload *extensions.QueryRegister, code int) {
	answer.Type = stanza.IQTypeError
	answer.Payload = *payload
	switch code {
	case 400:
		answer.Error = &stanza.Err{
			Code:   code,
			Type:   stanza.ErrorTypeModify,
			Reason: "bad-request",
		}
	case 405:
		answer.Error = &stanza.Err{
			Code:   code,
			Type:   stanza.ErrorTypeCancel,
			Reason: "not-allowed",
			Text:   "Logging out is dangerous. If you are sure you would be able to receive the authentication code again, issue the /logout command to the transport",
		}
	case 406:
		answer.Error = &stanza.Err{
			Code:   code,
			Type:   stanza.ErrorTypeModify,
			Reason: "not-acceptable",
			Text:   "Phone number already provided, chat with the transport for further instruction",
		}
	case 500:
		answer.Error = &stanza.Err{
			Code:   code,
			Type:   stanza.ErrorTypeWait,
			Reason: "internal-server-error",
		}
	default:
		log.Error("Unknown error code, falling back with empty reason")
		answer.Error = &stanza.Err{
			Code:   code,
			Type:   stanza.ErrorTypeCancel,
			Reason: "undefined-condition",
		}
	}
}

func toToID(to string) (int64, bool) {
	toParts := strings.Split(to, "@")
	if len(toParts) < 2 {
		return 0, false
	}
	toID, err := strconv.ParseInt(toParts[0], 10, 64)
	if err != nil {
		log.WithFields(log.Fields{
			"to": to,
		}).Error(errors.Wrap(err, "Invalid to JID!"))
		return 0, false
	}
	return toID, true
}

func makeVCardPayload(typ byte, id string, info telegram.VCardInfo, session *telegram.Client) stanza.IQPayload {
	var base64Photo string
	if info.Photo != nil {
		file, path, err := session.ForceOpenFile(info.Photo, 32)
		if err == nil {
			defer file.Close()

			buf := new(bytes.Buffer)
			binval := base64.NewEncoder(base64.StdEncoding, buf)
			_, err = io.Copy(binval, file)
			binval.Close()
			if err == nil {
				base64Photo = buf.String()
			} else {
				log.Errorf("Error calculating base64: %v", path)
			}
		} else if path != "" {
			log.Errorf("Photo does not exist: %v", path)
		} else {
			log.Errorf("PHOTO: %#v", err.Error())
		}
	}

	if typ == TypeVCardTemp {
		vcard := &extensions.IqVcardTemp{}

		vcard.Fn.Text = info.Fn
		if base64Photo != "" {
			vcard.Photo.Type.Text = "image/jpeg"
			vcard.Photo.Binval.Text = base64Photo
		}
		vcard.Nickname.Text = strings.Join(info.Nicknames, ",")
		vcard.N.Given.Text = info.Given
		vcard.N.Family.Text = info.Family
		vcard.Tel.Number.Text = info.Tel
		vcard.Desc.Text = info.Info

		return vcard
	} else if typ == TypeVCard4 {
		nodes := []stanza.Node{}
		if info.Fn != "" {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "fn"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "text"},
						Content: info.Fn,
					},
				},
			})
		}
		if base64Photo != "" {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "photo"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "uri"},
						Content: "data:image/jpeg;base64," + base64Photo,
					},
				},
			})
		}
		for _, nickname := range info.Nicknames {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "nickname"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "text"},
						Content: nickname,
					},
				},
			}, stanza.Node{
				XMLName: xml.Name{Local: "impp"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "uri"},
						Content: "https://t.me/" + nickname,
					},
				},
			})
		}
		if info.Family != "" || info.Given != "" {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "n"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "surname"},
						Content: info.Family,
					},
					stanza.Node{
						XMLName: xml.Name{Local: "given"},
						Content: info.Given,
					},
				},
			})
		}
		if info.Tel != "" {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "tel"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "uri"},
						Content: "tel:" + info.Tel,
					},
				},
			})
		}
		if info.Info != "" {
			nodes = append(nodes, stanza.Node{
				XMLName: xml.Name{Local: "note"},
				Nodes: []stanza.Node{
					stanza.Node{
						XMLName: xml.Name{Local: "text"},
						Content: info.Info,
					},
				},
			})
		}

		pubsub := &stanza.PubSubGeneric{
			Items: &stanza.Items{
				Node: NodeVCard4,
				List: []stanza.Item{
					stanza.Item{
						Id: id,
						Any: &stanza.Node{
							XMLName: xml.Name{Local: "vcard"},
							Attrs: []xml.Attr{
								xml.Attr{
									Name:  xml.Name{Local: "xmlns"},
									Value: "urn:ietf:params:xml:ns:vcard-4.0",
								},
							},
							Nodes: nodes,
						},
					},
				},
			},
		}

		return pubsub
	}

	return nil
}