mirror of
https://dev.narayana.im/narayana/telegabber.git
synced 2026-08-05 20:17:08 +00:00
Compare commits
No commits in common. "master" and "v1.10.0" have entirely different histories.
15 changed files with 374 additions and 1220 deletions
2
Makefile
2
Makefile
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
COMMIT := $(shell git rev-parse --short HEAD)
|
COMMIT := $(shell git rev-parse --short HEAD)
|
||||||
TD_COMMIT := "5bbfc1cf5dab94f82e02f3430ded7241d4653551"
|
TD_COMMIT := "5bbfc1cf5dab94f82e02f3430ded7241d4653551"
|
||||||
VERSION := "v1.12.8"
|
VERSION := "v1.10.0"
|
||||||
MAKEOPTS := "-j4"
|
MAKEOPTS := "-j4"
|
||||||
|
|
||||||
all:
|
all:
|
||||||
|
|
|
||||||
|
|
@ -47,17 +47,9 @@ type Session struct {
|
||||||
NativeEdits bool `yaml:":nativeedits"`
|
NativeEdits bool `yaml:":nativeedits"`
|
||||||
IgnoredChats []int64 `yaml:":ignoredchats"`
|
IgnoredChats []int64 `yaml:":ignoredchats"`
|
||||||
ignoredChatsMap map[int64]bool `yaml:"-"`
|
ignoredChatsMap map[int64]bool `yaml:"-"`
|
||||||
|
|
||||||
IgnoreGroupDeletions bool `yaml:":ignoregroupdeletions"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
var configKeys = []string{
|
||||||
PropertyTypeUnknown byte = iota
|
|
||||||
PropertyTypeString
|
|
||||||
PropertyTypeBool
|
|
||||||
)
|
|
||||||
|
|
||||||
var ConfigKeys = []string{
|
|
||||||
"timezone",
|
"timezone",
|
||||||
"keeponline",
|
"keeponline",
|
||||||
"rawmessages",
|
"rawmessages",
|
||||||
|
|
@ -67,7 +59,6 @@ var ConfigKeys = []string{
|
||||||
"hideids",
|
"hideids",
|
||||||
"receipts",
|
"receipts",
|
||||||
"nativeedits",
|
"nativeedits",
|
||||||
"ignoregroupdeletions",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var sessionDB *SessionsYamlDB
|
var sessionDB *SessionsYamlDB
|
||||||
|
|
@ -174,8 +165,6 @@ func (s *Session) get(key string) (string, error) {
|
||||||
return fromBool(s.Receipts), nil
|
return fromBool(s.Receipts), nil
|
||||||
case "nativeedits":
|
case "nativeedits":
|
||||||
return fromBool(s.NativeEdits), nil
|
return fromBool(s.NativeEdits), nil
|
||||||
case "ignoregroupdeletions":
|
|
||||||
return fromBool(s.IgnoreGroupDeletions), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", errors.New("Unknown session property")
|
return "", errors.New("Unknown session property")
|
||||||
|
|
@ -187,7 +176,7 @@ func (s *Session) ToMap() map[string]string {
|
||||||
defer sessionsLock.Unlock()
|
defer sessionsLock.Unlock()
|
||||||
|
|
||||||
m := make(map[string]string)
|
m := make(map[string]string)
|
||||||
for _, configKey := range ConfigKeys {
|
for _, configKey := range configKeys {
|
||||||
value, _ := s.get(configKey)
|
value, _ := s.get(configKey)
|
||||||
m[configKey] = value
|
m[configKey] = value
|
||||||
}
|
}
|
||||||
|
|
@ -260,30 +249,11 @@ func (s *Session) Set(key string, value string) (string, error) {
|
||||||
}
|
}
|
||||||
s.NativeEdits = b
|
s.NativeEdits = b
|
||||||
return value, nil
|
return value, nil
|
||||||
case "ignoregroupdeletions":
|
|
||||||
b, err := toBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
s.IgnoreGroupDeletions = b
|
|
||||||
return value, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", errors.New("Unknown session property")
|
return "", errors.New("Unknown session property")
|
||||||
}
|
}
|
||||||
|
|
||||||
// PropertyType determines the property type
|
|
||||||
func PropertyType(key string) byte {
|
|
||||||
switch key {
|
|
||||||
case "timezone":
|
|
||||||
return PropertyTypeString
|
|
||||||
case "keeponline", "rawmessages", "asciiarrows", "oobmode", "carbons", "hideids",
|
|
||||||
"receipts", "nativeedits", "ignoregroupdeletions":
|
|
||||||
return PropertyTypeBool
|
|
||||||
}
|
|
||||||
return PropertyTypeUnknown
|
|
||||||
}
|
|
||||||
|
|
||||||
// TimezoneToLocation tries to convert config timezone to location
|
// TimezoneToLocation tries to convert config timezone to location
|
||||||
func (s *Session) TimezoneToLocation() *time.Location {
|
func (s *Session) TimezoneToLocation() *time.Location {
|
||||||
time, err := time.Parse("-07:00", s.Timezone)
|
time, err := time.Parse("-07:00", s.Timezone)
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ import (
|
||||||
goxmpp "gosrc.io/xmpp"
|
goxmpp "gosrc.io/xmpp"
|
||||||
)
|
)
|
||||||
|
|
||||||
var version string = "1.12.8"
|
var version string = "1.10.0"
|
||||||
var commit string
|
var commit string
|
||||||
|
|
||||||
var sm *goxmpp.StreamManager
|
var sm *goxmpp.StreamManager
|
||||||
|
|
@ -68,7 +68,7 @@ func main() {
|
||||||
|
|
||||||
log.Infof("Starting telegabber version %v", version)
|
log.Infof("Starting telegabber version %v", version)
|
||||||
|
|
||||||
sm, component, err = xmpp.NewComponent(config.XMPP, config.Telegram, *idsPath, version)
|
sm, component, err = xmpp.NewComponent(config.XMPP, config.Telegram, *idsPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
43
telegram/cache/cache.go
vendored
43
telegram/cache/cache.go
vendored
|
|
@ -16,8 +16,7 @@ type Status struct {
|
||||||
// Cache allows operating the chats and users cache in
|
// Cache allows operating the chats and users cache in
|
||||||
// a thread-safe manner
|
// a thread-safe manner
|
||||||
type Cache struct {
|
type Cache struct {
|
||||||
ownChats map[int64]*client.Chat
|
chats map[int64]*client.Chat
|
||||||
auxChats map[int64]*client.Chat
|
|
||||||
users map[int64]*client.User
|
users map[int64]*client.User
|
||||||
statuses map[int64]*Status
|
statuses map[int64]*Status
|
||||||
chatsLock sync.Mutex
|
chatsLock sync.Mutex
|
||||||
|
|
@ -28,8 +27,7 @@ type Cache struct {
|
||||||
// NewCache initializes a cache
|
// NewCache initializes a cache
|
||||||
func NewCache() *Cache {
|
func NewCache() *Cache {
|
||||||
return &Cache{
|
return &Cache{
|
||||||
ownChats: map[int64]*client.Chat{},
|
chats: map[int64]*client.Chat{},
|
||||||
auxChats: map[int64]*client.Chat{},
|
|
||||||
users: map[int64]*client.User{},
|
users: map[int64]*client.User{},
|
||||||
statuses: map[int64]*Status{},
|
statuses: map[int64]*Status{},
|
||||||
}
|
}
|
||||||
|
|
@ -42,23 +40,7 @@ func (cache *Cache) ChatsKeys() []int64 {
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
var keys []int64
|
var keys []int64
|
||||||
for id := range cache.ownChats {
|
for id := range cache.chats {
|
||||||
keys = append(keys, id)
|
|
||||||
}
|
|
||||||
for id := range cache.auxChats {
|
|
||||||
keys = append(keys, id)
|
|
||||||
}
|
|
||||||
return keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// OwnChatsKeys grabs only own chat ids synchronously to avoid lockups
|
|
||||||
// while they are used
|
|
||||||
func (cache *Cache) OwnChatsKeys() []int64 {
|
|
||||||
cache.chatsLock.Lock()
|
|
||||||
defer cache.chatsLock.Unlock()
|
|
||||||
|
|
||||||
var keys []int64
|
|
||||||
for id := range cache.ownChats {
|
|
||||||
keys = append(keys, id)
|
keys = append(keys, id)
|
||||||
}
|
}
|
||||||
return keys
|
return keys
|
||||||
|
|
@ -102,10 +84,7 @@ func (cache *Cache) GetChat(id int64) (*client.Chat, bool) {
|
||||||
cache.chatsLock.Lock()
|
cache.chatsLock.Lock()
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
chat, ok := cache.ownChats[id]
|
chat, ok := cache.chats[id]
|
||||||
if !ok {
|
|
||||||
chat, ok = cache.auxChats[id]
|
|
||||||
}
|
|
||||||
return chat, ok
|
return chat, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -128,21 +107,11 @@ func (cache *Cache) GetStatus(id int64) (*Status, bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetChat stores a chat in the cache
|
// SetChat stores a chat in the cache
|
||||||
func (cache *Cache) SetChat(id int64, chat *client.Chat, own bool) {
|
func (cache *Cache) SetChat(id int64, chat *client.Chat) {
|
||||||
cache.chatsLock.Lock()
|
cache.chatsLock.Lock()
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
if own {
|
cache.chats[id] = chat
|
||||||
cache.ownChats[id] = chat
|
|
||||||
// move from aux to own, but not vice versa
|
|
||||||
// (own: true means that presences for the chat are needed
|
|
||||||
// for sure, false means just "not necessarily")
|
|
||||||
if _, ok := cache.auxChats[id]; ok {
|
|
||||||
delete(cache.auxChats, id)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
cache.auxChats[id] = chat
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetUser stores a user in the cache
|
// SetUser stores a user in the cache
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ package telegram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"hash/maphash"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
@ -27,41 +28,6 @@ type HashedAvatar struct {
|
||||||
File int32
|
File int32
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewId stores message ids and timestamps of their additions so old ones can be truncated to save memory
|
|
||||||
type newId struct {
|
|
||||||
Id int64
|
|
||||||
Ts int64
|
|
||||||
lock sync.Mutex
|
|
||||||
ownLock sync.Mutex
|
|
||||||
locked bool
|
|
||||||
fired bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newNewId() *newId {
|
|
||||||
return &newId{Ts: time.Now().Unix()}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *newId) Lock() {
|
|
||||||
i.ownLock.Lock()
|
|
||||||
if i.fired {
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
i.locked = true
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
i.lock.Lock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *newId) Unlock() {
|
|
||||||
i.ownLock.Lock()
|
|
||||||
if i.locked {
|
|
||||||
i.lock.Unlock()
|
|
||||||
i.locked = false
|
|
||||||
i.fired = true
|
|
||||||
}
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client stores the metadata for lazily invoked TDlib instance
|
// Client stores the metadata for lazily invoked TDlib instance
|
||||||
type Client struct {
|
type Client struct {
|
||||||
client *client.Client
|
client *client.Client
|
||||||
|
|
@ -78,10 +44,6 @@ type Client struct {
|
||||||
cache *cache.Cache
|
cache *cache.Cache
|
||||||
online bool
|
online bool
|
||||||
|
|
||||||
loginWizard *loginWizardMetadata
|
|
||||||
|
|
||||||
lastAuthorizationStateType string
|
|
||||||
|
|
||||||
outbox map[string]string
|
outbox map[string]string
|
||||||
editOutbox map[string]string
|
editOutbox map[string]string
|
||||||
|
|
||||||
|
|
@ -90,8 +52,7 @@ type Client struct {
|
||||||
|
|
||||||
lastMsgHashes map[int64]uint64
|
lastMsgHashes map[int64]uint64
|
||||||
lastMsgIds map[int64]string
|
lastMsgIds map[int64]string
|
||||||
|
msgHashSeed maphash.Seed
|
||||||
LastBotCmdString string
|
|
||||||
|
|
||||||
XmppClientFeatures map[string]*[]string
|
XmppClientFeatures map[string]*[]string
|
||||||
XmppClientFeaturesLock sync.Mutex
|
XmppClientFeaturesLock sync.Mutex
|
||||||
|
|
@ -99,9 +60,6 @@ type Client struct {
|
||||||
AvatarHashes map[int64]*HashedAvatar
|
AvatarHashes map[int64]*HashedAvatar
|
||||||
AvatarHashesLock sync.Mutex
|
AvatarHashesLock sync.Mutex
|
||||||
|
|
||||||
MessageIdChanges map[int64]map[int64]*newId
|
|
||||||
MessageIdChangesLock sync.Mutex
|
|
||||||
|
|
||||||
locks clientLocks
|
locks clientLocks
|
||||||
SendMessageLock sync.Mutex
|
SendMessageLock sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
@ -117,15 +75,6 @@ type clientLocks struct {
|
||||||
|
|
||||||
authorizerReadLock sync.Mutex
|
authorizerReadLock sync.Mutex
|
||||||
authorizerWriteLock sync.Mutex
|
authorizerWriteLock sync.Mutex
|
||||||
|
|
||||||
loginWizardReadLock sync.Mutex
|
|
||||||
loginWizardWriteLock sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginWizardMetadata struct {
|
|
||||||
nextStage chan string
|
|
||||||
chanBusy bool
|
|
||||||
commandSent bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient instantiates a Telegram App
|
// NewClient instantiates a Telegram App
|
||||||
|
|
@ -185,9 +134,9 @@ func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component
|
||||||
DelayedStatuses: make(map[int64]*DelayedStatus),
|
DelayedStatuses: make(map[int64]*DelayedStatus),
|
||||||
lastMsgHashes: make(map[int64]uint64),
|
lastMsgHashes: make(map[int64]uint64),
|
||||||
lastMsgIds: make(map[int64]string),
|
lastMsgIds: make(map[int64]string),
|
||||||
|
msgHashSeed: maphash.MakeSeed(),
|
||||||
XmppClientFeatures: make(map[string]*[]string),
|
XmppClientFeatures: make(map[string]*[]string),
|
||||||
AvatarHashes: make(map[int64]*HashedAvatar),
|
AvatarHashes: make(map[int64]*HashedAvatar),
|
||||||
MessageIdChanges: make(map[int64]map[int64]*newId),
|
|
||||||
locks: clientLocks{
|
locks: clientLocks{
|
||||||
chatMessageLocks: make(map[int64]*sync.Mutex),
|
chatMessageLocks: make(map[int64]*sync.Mutex),
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/persistence"
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
|
|
@ -51,23 +50,22 @@ var permissionsMember = client.ChatPermissions{
|
||||||
var permissionsReadonly = client.ChatPermissions{}
|
var permissionsReadonly = client.ChatPermissions{}
|
||||||
|
|
||||||
var transportCommands = map[string]command{
|
var transportCommands = map[string]command{
|
||||||
"help": command{0, []string{}, "help", false, nil, false},
|
"help": command{0, []string{}, "help", nil},
|
||||||
"login": command{1, []string{"phone"}, "sign in", false, nil, false},
|
"login": command{1, []string{"phone"}, "sign in", nil},
|
||||||
"logout": command{0, []string{}, "sign out", true, nil, true},
|
"logout": command{0, []string{}, "sign out", nil},
|
||||||
"cleanup": command{0, []string{}, "unsubscribe from all known chats", false, nil, false},
|
"cancelauth": command{0, []string{}, "quit the signin wizard", nil},
|
||||||
"cancelauth": command{0, []string{}, "quit the signin wizard", false, nil, false},
|
"code": command{1, []string{"xxxxx"}, "check one-time code", nil},
|
||||||
"code": command{1, []string{"xxxxx"}, "check one-time code", false, nil, false},
|
"password": command{1, []string{"********"}, "check 2fa password", nil},
|
||||||
"password": command{1, []string{"********"}, "check 2fa password", false, nil, false},
|
"setusername": command{0, []string{"@username"}, "update @username", nil},
|
||||||
"setusername": command{0, []string{"@username"}, "update @username", true, nil, true},
|
"setname": command{1, []string{"first", "last"}, "update name", nil},
|
||||||
"setname": command{1, []string{"first", "last"}, "update name", true, nil, false},
|
"setbio": command{0, []string{"Lorem ipsum"}, "update about", nil},
|
||||||
"setbio": command{0, []string{"Lorem ipsum"}, "update about", true, nil, true},
|
"setpassword": command{0, []string{"old", "new"}, "set or remove password", nil},
|
||||||
"setpassword": command{0, []string{"old", "new"}, "set or remove password", true, nil, true},
|
"config": command{0, []string{"param", "value"}, "view or update configuration options", nil},
|
||||||
"config": command{0, []string{"param", "value"}, "view or update configuration options", false, nil, false},
|
"report": command{2, []string{"chat", "comment"}, "report a chat by id or @username", nil},
|
||||||
"report": command{2, []string{"chat", "comment"}, "report a chat by id or @username", true, nil, true},
|
"add": command{1, []string{"@username"}, "add @username to your chat list", nil},
|
||||||
"add": command{1, []string{"@username"}, "add @username to your chat list", true, nil, true},
|
"join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", nil},
|
||||||
"join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", true, nil, true},
|
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", nil},
|
||||||
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", true, nil, true},
|
"channel": command{1, []string{"title", "description"}, "create new channel «title» with «description»", nil},
|
||||||
"channel": command{1, []string{"title", "description"}, "create new channel «title» with «description»", true, nil, true},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var notForGroups = []ChatType{ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel}
|
var notForGroups = []ChatType{ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel}
|
||||||
|
|
@ -76,60 +74,50 @@ var notForPMAndBasic = []ChatType{ChatTypePrivate, ChatTypeSecret, ChatTypeBasic
|
||||||
var onlyForSecret = []ChatType{ChatTypePrivate, ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel}
|
var onlyForSecret = []ChatType{ChatTypePrivate, ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel}
|
||||||
|
|
||||||
var chatCommands = map[string]command{
|
var chatCommands = map[string]command{
|
||||||
"help": command{0, []string{}, "help", false, nil, false},
|
"help": command{0, []string{}, "help", nil},
|
||||||
"d": command{0, []string{"n"}, "delete your last message(s)", true, nil, true},
|
"d": command{0, []string{"n"}, "delete your last message(s)", nil},
|
||||||
"s": command{1, []string{"edited message"}, "edit your last message", true, nil, true},
|
"s": command{1, []string{"edited message"}, "edit your last message", nil},
|
||||||
"silent": command{1, []string{"message"}, "send a message without sound", true, nil, true},
|
"silent": command{1, []string{"message"}, "send a message without sound", nil},
|
||||||
"schedule": command{2, []string{"{online | 2006-01-02T15:04:05 | 15:04:05}", "message"}, "schedules a message either to timestamp or to whenever the user goes online", true, nil, true},
|
"schedule": command{2, []string{"{online | 2006-01-02T15:04:05 | 15:04:05}", "message"}, "schedules a message either to timestamp or to whenever the user goes online", nil},
|
||||||
"raw": command{1, []string{"message"}, "send a raw message not interpeted as a transport command (e.g. a bot command)", true, nil, true},
|
"forward": command{2, []string{"message_id", "target_chat"}, "forwards a message", nil},
|
||||||
"forward": command{2, []string{"message_id", "target_chat"}, "forwards a message", true, nil, true},
|
"vcard": command{0, []string{}, "print vCard as text", nil},
|
||||||
"vcard": command{0, []string{}, "print vCard as text", true, nil, true},
|
"add": command{1, []string{"@username"}, "add @username to your chat list", nil},
|
||||||
"add": command{1, []string{"@username"}, "add @username to your chat list", true, nil, true},
|
"join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", nil},
|
||||||
"join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", true, nil, true},
|
"group": command{1, []string{"title"}, "create groupchat «title» with current user", ¬ForGroups},
|
||||||
"group": command{1, []string{"title"}, "create groupchat «title» with current user", true, ¬ForGroups, true},
|
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", nil},
|
||||||
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", true, nil, true},
|
"channel": command{1, []string{"title", "description"}, "create new channel «title» with «description»", nil},
|
||||||
"channel": command{1, []string{"title", "description"}, "create new channel «title» with «description»", true, nil, true},
|
"secret": command{0, []string{}, "create secretchat with current user", ¬ForGroups},
|
||||||
"secret": command{0, []string{}, "create secretchat with current user", true, ¬ForGroups, true},
|
"search": command{0, []string{"string", "[limit]"}, "search <string> in current chat", nil},
|
||||||
"search": command{0, []string{"string", "[limit]"}, "search <string> in current chat", true, nil, true},
|
"history": command{0, []string{"limit"}, "get last [limit] messages from current chat", nil},
|
||||||
"history": command{0, []string{"limit"}, "get last [limit] messages from current chat", true, nil, true},
|
"block": command{0, []string{}, "blacklist current user", ¬ForGroups},
|
||||||
"block": command{0, []string{}, "blacklist current user", true, ¬ForGroups, true},
|
"unblock": command{0, []string{}, "unblacklist current user", ¬ForGroups},
|
||||||
"unblock": command{0, []string{}, "unblacklist current user", true, ¬ForGroups, true},
|
"invite": command{1, []string{"id or @username"}, "add user to current chat", ¬ForPM},
|
||||||
"invite": command{1, []string{"id or @username"}, "add user to current chat", true, ¬ForPM, true},
|
"link": command{0, []string{}, "get invite link for current chat", ¬ForPM},
|
||||||
"link": command{0, []string{}, "get invite link for current chat", true, ¬ForPM, true},
|
"kick": command{1, []string{"id or @username"}, "remove user from current chat", ¬ForPM},
|
||||||
"kick": command{1, []string{"id or @username"}, "remove user from current chat", true, ¬ForPM, true},
|
"mute": command{0, []string{"id or @username", "hours"}, "mute the whole chat or a user in current chat", ¬ForPMAndBasic},
|
||||||
"mute": command{0, []string{"id or @username", "hours"}, "mute the whole chat or a user in current chat", true, ¬ForPMAndBasic, true},
|
"unmute": command{0, []string{"id or @username"}, "unmute the whole chat or a user in the current chat", ¬ForPMAndBasic},
|
||||||
"unmute": command{0, []string{"id or @username"}, "unmute the whole chat or a user in the current chat", true, ¬ForPMAndBasic, true},
|
"ban": command{1, []string{"id or @username", "hours"}, "restrict @username from current chat for [hours] or forever", ¬ForPM},
|
||||||
"ban": command{1, []string{"id or @username", "hours"}, "restrict @username from current chat for [hours] or forever", true, ¬ForPM, true},
|
"unban": command{1, []string{"id or @username"}, "unbans @username in current chat (and devotes from admins)", ¬ForPM},
|
||||||
"unban": command{1, []string{"id or @username"}, "unbans @username in current chat (and devotes from admins)", true, ¬ForPM, true},
|
"promote": command{1, []string{"id or @username", "title"}, "promote user to admin in current chat", ¬ForPM},
|
||||||
"promote": command{1, []string{"id or @username", "title"}, "promote user to admin in current chat", true, ¬ForPM, true},
|
"leave": command{0, []string{}, "leave current chat", ¬ForPM},
|
||||||
"leave": command{0, []string{}, "leave current chat", true, ¬ForPM, true},
|
"leave!": command{0, []string{}, "leave current chat (for owners)", ¬ForPM},
|
||||||
"leave!": command{0, []string{}, "leave current chat (for owners)", true, ¬ForPM, true},
|
"ttl": command{0, []string{"seconds"}, "set secret chat messages TTL before self-destroying", &onlyForSecret},
|
||||||
"ttl": command{0, []string{"seconds"}, "set secret chat messages TTL before self-destroying", true, &onlyForSecret, true},
|
"close": command{0, []string{}, "close current secret chat", &onlyForSecret},
|
||||||
"close": command{0, []string{}, "close current secret chat", true, &onlyForSecret, true},
|
"delete": command{0, []string{}, "delete current chat from chat list", nil},
|
||||||
"delete": command{0, []string{}, "delete current chat from chat list", true, nil, true},
|
"members": command{0, []string{"query"}, "search members [by optional query] in current chat (requires admin rights)", nil},
|
||||||
"members": command{0, []string{"query"}, "search members [by optional query] in current chat (requires admin rights)", true, nil, true},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var transportConfigurationOptions = map[string]configurationOption{
|
var transportConfigurationOptions = map[string]configurationOption{
|
||||||
"timezone": configurationOption{"<timezone>", "adjust timezone for Telegram user statuses (example: +02:00)"},
|
"timezone": configurationOption{"<timezone>", "adjust timezone for Telegram user statuses (example: +02:00)"},
|
||||||
"keeponline": configurationOption{"<bool>", "always keep telegram session online and rely on jabber offline messages (true/false)"},
|
"keeponline": configurationOption{"<bool>", "always keep telegram session online and rely on jabber offline messages (example: true)"},
|
||||||
"rawmessages": configurationOption{"<bool>", "do not add additional info (message id, origin etc.) to incoming messages (true/false)"},
|
"rawmessages": configurationOption{"<bool>", "do not add additional info (message id, origin etc.) to incoming messages (example: true)"},
|
||||||
"asciiarrows": configurationOption{"<bool>", "replace some Unicode symbols with ASCII alternatives for better compatibility (true/false)"},
|
|
||||||
"oobmode": configurationOption{"<bool>", "use XEP-0066 (OOB); pros: some modern clients won't show images without it, cons: very restricted, Tkabber would flood with popups (true/false)"},
|
|
||||||
"carbons": configurationOption{"<bool>", "send carbons to your another clients, will turn on only if supported by the server (true/false)"},
|
|
||||||
"hideids": configurationOption{"<bool>", "hide message IDs from message info (true/false)"},
|
|
||||||
"receipts": configurationOption{"<bool>", "if enabled, XMPP read receipts are synced to Telegram, otherwise, messages are marked as read automatically (true/false)"},
|
|
||||||
"nativeedits": configurationOption{"<bool>", "if possible, edit XMPP messages instead of showing Telegram edits as separate messages (true/false)"},
|
|
||||||
"ignoregroupdeletions": configurationOption{"<bool>", "suppress message deletion messages in group chats (true/false)"},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type command struct {
|
type command struct {
|
||||||
RequiredArgs int
|
RequiredArgs int
|
||||||
Arguments []string
|
Arguments []string
|
||||||
Description string
|
Description string
|
||||||
LoginOnly bool
|
|
||||||
NotFor *[]ChatType
|
NotFor *[]ChatType
|
||||||
OnlineOnly bool
|
|
||||||
}
|
}
|
||||||
type configurationOption struct {
|
type configurationOption struct {
|
||||||
arguments string
|
arguments string
|
||||||
|
|
@ -144,15 +132,6 @@ const (
|
||||||
CommandTypeChat
|
CommandTypeChat
|
||||||
)
|
)
|
||||||
|
|
||||||
// OnlineFilter is a tri-state condition for commands selection
|
|
||||||
type OnlineFilter int
|
|
||||||
|
|
||||||
const (
|
|
||||||
OnlineFilterOnline OnlineFilter = iota
|
|
||||||
OnlineFilterNotOnline
|
|
||||||
OnlineFilterAny
|
|
||||||
)
|
|
||||||
|
|
||||||
// GetCommands exposes the set of commands
|
// GetCommands exposes the set of commands
|
||||||
func GetCommands(typ CommandType) map[string]command {
|
func GetCommands(typ CommandType) map[string]command {
|
||||||
var commandMap map[string]command
|
var commandMap map[string]command
|
||||||
|
|
@ -175,20 +154,14 @@ func GetCommand(typ CommandType, cmd string) (command, bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// SortedCommandKeys sorts a slice with command keys
|
// SortedCommandKeys sorts a slice with command keys
|
||||||
func SortedCommandKeys(commandMap map[string]command, onlineFilter OnlineFilter) []string {
|
func SortedCommandKeys(commandMap map[string]command) []string {
|
||||||
keys := make([]string, len(commandMap))
|
keys := make([]string, len(commandMap))
|
||||||
|
|
||||||
i := 0
|
i := 0
|
||||||
for k := range commandMap {
|
for k := range commandMap {
|
||||||
command := commandMap[k]
|
|
||||||
if (onlineFilter == OnlineFilterOnline && !command.OnlineOnly) || (onlineFilter == OnlineFilterNotOnline && command.OnlineOnly) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
keys[i] = k
|
keys[i] = k
|
||||||
i++
|
i++
|
||||||
}
|
}
|
||||||
keys = keys[:i]
|
|
||||||
|
|
||||||
sort.Strings(keys)
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
|
@ -231,34 +204,25 @@ func IsCommandForChatType(cmd command, chatType ChatType) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func commandsToHelpString(str *strings.Builder, chatType ChatType, onlineFilter OnlineFilter, commandMap map[string]command) {
|
func (c *Client) helpString(typ CommandType, chatId int64) string {
|
||||||
for _, name := range SortedCommandKeys(commandMap, onlineFilter) {
|
var str strings.Builder
|
||||||
|
|
||||||
|
commandMap := GetCommands(typ)
|
||||||
|
chatType, chatTypeErr := c.GetChatType(chatId)
|
||||||
|
|
||||||
|
str.WriteString("Available commands:\n")
|
||||||
|
for _, name := range SortedCommandKeys(commandMap) {
|
||||||
command := commandMap[name]
|
command := commandMap[name]
|
||||||
if !IsCommandForChatType(command, chatType) {
|
if chatTypeErr == nil && !IsCommandForChatType(command, chatType) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
str.WriteString(CommandToHelpString(name, command))
|
str.WriteString(CommandToHelpString(name, command))
|
||||||
str.WriteString("\n")
|
str.WriteString("\n")
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) helpString(typ CommandType, chatId int64) string {
|
|
||||||
var str strings.Builder
|
|
||||||
|
|
||||||
commandMap := GetCommands(typ)
|
|
||||||
chatType, _ := c.GetChatType(chatId, true)
|
|
||||||
|
|
||||||
str.WriteString("Available commands:\n")
|
|
||||||
|
|
||||||
if typ == CommandTypeTransport {
|
if typ == CommandTypeTransport {
|
||||||
commandsToHelpString(&str, chatType, OnlineFilterNotOnline, commandMap)
|
str.WriteString("Configuration options\n")
|
||||||
|
for name, option := range transportConfigurationOptions {
|
||||||
str.WriteString("\nOnline-only commands:\n")
|
|
||||||
commandsToHelpString(&str, chatType, OnlineFilterOnline, commandMap)
|
|
||||||
|
|
||||||
str.WriteString("\nConfiguration options\n")
|
|
||||||
for _, name := range persistence.ConfigKeys {
|
|
||||||
option := transportConfigurationOptions[name]
|
|
||||||
str.WriteString(name)
|
str.WriteString(name)
|
||||||
str.WriteString(" ")
|
str.WriteString(" ")
|
||||||
str.WriteString(option.arguments)
|
str.WriteString(option.arguments)
|
||||||
|
|
@ -266,8 +230,6 @@ func (c *Client) helpString(typ CommandType, chatId int64) string {
|
||||||
str.WriteString(option.description)
|
str.WriteString(option.description)
|
||||||
str.WriteString("\n")
|
str.WriteString("\n")
|
||||||
}
|
}
|
||||||
} else if typ == CommandTypeChat {
|
|
||||||
commandsToHelpString(&str, chatType, OnlineFilterAny, commandMap)
|
|
||||||
}
|
}
|
||||||
str.WriteString("\nYou may use ! instead of / if it conflicts with internal commands of a client")
|
str.WriteString("\nYou may use ! instead of / if it conflicts with internal commands of a client")
|
||||||
|
|
||||||
|
|
@ -306,12 +268,6 @@ func (c *Client) unsubscribe(chatID int64) error {
|
||||||
return c.sendPresence(args...)
|
return c.sendPresence(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) unsubscribeFromAll() {
|
|
||||||
for _, id := range c.cache.ChatsKeys() {
|
|
||||||
c.unsubscribe(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) sendMessagesReverse(chatID int64, messages []*client.Message) {
|
func (c *Client) sendMessagesReverse(chatID int64, messages []*client.Message) {
|
||||||
for i := len(messages) - 1; i >= 0; i-- {
|
for i := len(messages) - 1; i >= 0; i-- {
|
||||||
message := messages[i]
|
message := messages[i]
|
||||||
|
|
@ -362,9 +318,6 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
if len(args) < command.RequiredArgs {
|
if len(args) < command.RequiredArgs {
|
||||||
return notEnoughArguments, false
|
return notEnoughArguments, false
|
||||||
}
|
}
|
||||||
if command.OnlineOnly && !c.Online() {
|
|
||||||
return notOnline, false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch cmd {
|
switch cmd {
|
||||||
case "login", "code", "password":
|
case "login", "code", "password":
|
||||||
|
|
@ -403,20 +356,22 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
c.authorizer.Password <- args[0]
|
c.authorizer.Password <- args[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", true
|
|
||||||
// sign out
|
// sign out
|
||||||
case "logout":
|
case "logout":
|
||||||
|
if !c.Online() {
|
||||||
|
return notOnline, false
|
||||||
|
}
|
||||||
|
|
||||||
_, err := c.client.LogOut()
|
_, err := c.client.LogOut()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "Logout error").Error(), false
|
return errors.Wrap(err, "Logout error").Error(), false
|
||||||
}
|
}
|
||||||
|
|
||||||
c.unsubscribeFromAll()
|
for _, id := range c.cache.ChatsKeys() {
|
||||||
|
c.unsubscribe(id)
|
||||||
|
}
|
||||||
|
|
||||||
c.Session.Login = ""
|
c.Session.Login = ""
|
||||||
// cleanup
|
|
||||||
case "cleanup":
|
|
||||||
c.unsubscribeFromAll()
|
|
||||||
// cancel auth
|
// cancel auth
|
||||||
case "cancelauth":
|
case "cancelauth":
|
||||||
if c.Online() {
|
if c.Online() {
|
||||||
|
|
@ -426,6 +381,10 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
return "Cancelled", true
|
return "Cancelled", true
|
||||||
// set @username
|
// set @username
|
||||||
case "setusername":
|
case "setusername":
|
||||||
|
if !c.Online() {
|
||||||
|
return notOnline, false
|
||||||
|
}
|
||||||
|
|
||||||
var username string
|
var username string
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
username = args[0]
|
username = args[0]
|
||||||
|
|
@ -470,6 +429,10 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
}
|
}
|
||||||
// set About
|
// set About
|
||||||
case "setbio":
|
case "setbio":
|
||||||
|
if !c.Online() {
|
||||||
|
return notOnline, false
|
||||||
|
}
|
||||||
|
|
||||||
_, err := c.client.SetBio(&client.SetBioRequest{
|
_, err := c.client.SetBio(&client.SetBioRequest{
|
||||||
Bio: rawCmdArguments(cmdline, 0),
|
Bio: rawCmdArguments(cmdline, 0),
|
||||||
})
|
})
|
||||||
|
|
@ -478,12 +441,15 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
}
|
}
|
||||||
// set password
|
// set password
|
||||||
case "setpassword":
|
case "setpassword":
|
||||||
|
if !c.Online() {
|
||||||
|
return notOnline, false
|
||||||
|
}
|
||||||
|
|
||||||
var oldPassword string
|
var oldPassword string
|
||||||
var newPassword string
|
var newPassword string
|
||||||
if len(args) > 0 {
|
// 0 or 1 argument is ignored and the password is reset
|
||||||
oldPassword = args[0]
|
|
||||||
}
|
|
||||||
if len(args) > 1 {
|
if len(args) > 1 {
|
||||||
|
oldPassword = args[0]
|
||||||
newPassword = args[1]
|
newPassword = args[1]
|
||||||
}
|
}
|
||||||
_, err := c.client.SetPassword(&client.SetPasswordRequest{
|
_, err := c.client.SetPassword(&client.SetPasswordRequest{
|
||||||
|
|
@ -495,6 +461,7 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
}
|
}
|
||||||
case "config":
|
case "config":
|
||||||
if len(args) > 1 {
|
if len(args) > 1 {
|
||||||
|
var msg string
|
||||||
if gateway.MessageOutgoingPermissionVersion == 0 && args[0] == "carbons" && args[1] == "true" {
|
if gateway.MessageOutgoingPermissionVersion == 0 && args[0] == "carbons" && args[1] == "true" {
|
||||||
return "The server did not allow to enable carbons", false
|
return "The server did not allow to enable carbons", false
|
||||||
}
|
}
|
||||||
|
|
@ -505,7 +472,7 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
}
|
}
|
||||||
gateway.DirtySessions = true
|
gateway.DirtySessions = true
|
||||||
|
|
||||||
return fmt.Sprintf("%s set to %s", args[0], value), true
|
return fmt.Sprintf("%s%s set to %s", msg, args[0], value), true
|
||||||
} else if len(args) > 0 {
|
} else if len(args) > 0 {
|
||||||
value, err := c.Session.Get(args[0])
|
value, err := c.Session.Get(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -516,18 +483,13 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
}
|
}
|
||||||
|
|
||||||
var entries []string
|
var entries []string
|
||||||
for _, key := range persistence.ConfigKeys {
|
for key, value := range c.Session.ToMap() {
|
||||||
value, err := c.Session.Get(key)
|
|
||||||
if err != nil {
|
|
||||||
log.Errorf("Achtung! Programming error in sessions with key %v", key)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
entries = append(entries, fmt.Sprintf("%s is set to %s", key, value))
|
entries = append(entries, fmt.Sprintf("%s is set to %s", key, value))
|
||||||
}
|
}
|
||||||
|
|
||||||
return strings.Join(entries, "\n"), true
|
return strings.Join(entries, "\n"), true
|
||||||
case "report":
|
case "report":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), false
|
return err.Error(), false
|
||||||
}
|
}
|
||||||
|
|
@ -564,6 +526,10 @@ func (c *Client) ProcessTransportCommand(cmdline string, resource string) (strin
|
||||||
// ProcessChatCommand executes a command sent in a mapped chat
|
// ProcessChatCommand executes a command sent in a mapped chat
|
||||||
// and returns a response, the status of command support and the execution success result
|
// and returns a response, the status of command support and the execution success result
|
||||||
func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool, bool) {
|
func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool, bool) {
|
||||||
|
if !c.Online() {
|
||||||
|
return notOnline, true, false
|
||||||
|
}
|
||||||
|
|
||||||
cmd, args := parseCommand(cmdline)
|
cmd, args := parseCommand(cmdline)
|
||||||
command, ok := chatCommands[cmd]
|
command, ok := chatCommands[cmd]
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|
@ -572,12 +538,8 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
if len(args) < command.RequiredArgs {
|
if len(args) < command.RequiredArgs {
|
||||||
return notEnoughArguments, true, false
|
return notEnoughArguments, true, false
|
||||||
}
|
}
|
||||||
if command.OnlineOnly && !c.Online() {
|
|
||||||
return notOnline, true, false
|
|
||||||
}
|
|
||||||
|
|
||||||
|
chatType, chatTypeErr := c.GetChatType(chatID)
|
||||||
chatType, chatTypeErr := c.GetChatType(chatID, true)
|
|
||||||
if chatTypeErr == nil && !IsCommandForChatType(command, chatType) {
|
if chatTypeErr == nil && !IsCommandForChatType(command, chatType) {
|
||||||
return "Not applicable for this chat type", true, false
|
return "Not applicable for this chat type", true, false
|
||||||
}
|
}
|
||||||
|
|
@ -621,7 +583,6 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
return "", true, true
|
|
||||||
// edit message
|
// edit message
|
||||||
case "s":
|
case "s":
|
||||||
if c.me == nil {
|
if c.me == nil {
|
||||||
|
|
@ -655,7 +616,6 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
} else {
|
} else {
|
||||||
return "Message processing error", true, false
|
return "Message processing error", true, false
|
||||||
}
|
}
|
||||||
return "", true, true
|
|
||||||
// send without sound
|
// send without sound
|
||||||
case "silent":
|
case "silent":
|
||||||
content := c.PrepareOutgoingMessageContent(rawCmdArguments(cmdline, 0))
|
content := c.PrepareOutgoingMessageContent(rawCmdArguments(cmdline, 0))
|
||||||
|
|
@ -683,7 +643,11 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
state = &client.MessageSchedulingStateSendWhenOnline{}
|
state = &client.MessageSchedulingStateSendWhenOnline{}
|
||||||
result = due
|
result = due
|
||||||
} else {
|
} else {
|
||||||
due += c.GetTZD()
|
if c.Session.Timezone == "" {
|
||||||
|
due += "Z"
|
||||||
|
} else {
|
||||||
|
due += c.Session.Timezone
|
||||||
|
}
|
||||||
|
|
||||||
switch 0 {
|
switch 0 {
|
||||||
default:
|
default:
|
||||||
|
|
@ -746,22 +710,6 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
} else {
|
} else {
|
||||||
return "Message processing error", true, false
|
return "Message processing error", true, false
|
||||||
}
|
}
|
||||||
// sends a raw non-interpreted message
|
|
||||||
case "raw":
|
|
||||||
content := c.PrepareOutgoingMessageContent(rawCmdArguments(cmdline, 0))
|
|
||||||
|
|
||||||
if content != nil {
|
|
||||||
_, err := c.client.SendMessage(&client.SendMessageRequest{
|
|
||||||
ChatId: chatID,
|
|
||||||
InputMessageContent: content,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err.Error(), true, false
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return "Message processing error", true, false
|
|
||||||
}
|
|
||||||
return "", true, true
|
|
||||||
// forward a message to chat
|
// forward a message to chat
|
||||||
case "forward":
|
case "forward":
|
||||||
messageId, err := strconv.ParseInt(args[0], 10, 64)
|
messageId, err := strconv.ParseInt(args[0], 10, 64)
|
||||||
|
|
@ -856,7 +804,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
// invite @username to current groupchat
|
// invite @username to current groupchat
|
||||||
case "invite":
|
case "invite":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -883,7 +831,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
return link.InviteLink, true, true
|
return link.InviteLink, true, true
|
||||||
// kick @username from current group chat
|
// kick @username from current group chat
|
||||||
case "kick":
|
case "kick":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -902,7 +850,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
// mute [@username [n hours]]
|
// mute [@username [n hours]]
|
||||||
case "mute":
|
case "mute":
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -939,7 +887,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
// unmute [@username]
|
// unmute [@username]
|
||||||
case "unmute":
|
case "unmute":
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -967,7 +915,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
// ban @username from current chat [for N hours]
|
// ban @username from current chat [for N hours]
|
||||||
case "ban":
|
case "ban":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -995,7 +943,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
// unban @username
|
// unban @username
|
||||||
case "unban":
|
case "unban":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -1013,7 +961,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
// promote @username to admin
|
// promote @username to admin
|
||||||
case "promote":
|
case "promote":
|
||||||
contact, _, err := c.GetContactByUsername(args[0], false)
|
contact, _, err := c.GetContactByUsername(args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -1085,7 +1033,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
// close secret chat
|
// close secret chat
|
||||||
case "close":
|
case "close":
|
||||||
chat, _, err := c.GetContactByID(chatID, nil, true)
|
chat, _, err := c.GetContactByID(chatID, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err.Error(), true, false
|
return err.Error(), true, false
|
||||||
}
|
}
|
||||||
|
|
@ -1144,7 +1092,6 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
c.sendMessagesReverse(chatID, messages.Messages)
|
c.sendMessagesReverse(chatID, messages.Messages)
|
||||||
return "", true, true
|
|
||||||
// get latest entries from history
|
// get latest entries from history
|
||||||
case "history":
|
case "history":
|
||||||
var limit int32 = 10
|
var limit int32 = 10
|
||||||
|
|
@ -1181,7 +1128,6 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
c.sendMessagesReverse(chatID, messages)
|
c.sendMessagesReverse(chatID, messages)
|
||||||
return "", true, true
|
|
||||||
// chat members
|
// chat members
|
||||||
case "members":
|
case "members":
|
||||||
var query string
|
var query string
|
||||||
|
|
@ -1211,7 +1157,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
|
||||||
return "", false, false
|
return "", false, false
|
||||||
}
|
}
|
||||||
|
|
||||||
return "Success", true, true
|
return "", true, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cmdAdd(args []string) (string, bool) {
|
func (c *Client) cmdAdd(args []string) (string, bool) {
|
||||||
|
|
@ -1227,7 +1173,7 @@ func (c *Client) cmdAdd(args []string) (string, bool) {
|
||||||
|
|
||||||
c.subscribeToID(chat.Id, chat)
|
c.subscribeToID(chat.Id, chat)
|
||||||
|
|
||||||
return "Subscription sent", true
|
return "", true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cmdJoin(args []string) (string, bool) {
|
func (c *Client) cmdJoin(args []string) (string, bool) {
|
||||||
|
|
@ -1256,7 +1202,7 @@ func (c *Client) cmdJoin(args []string) (string, bool) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "Joined", true
|
return "", true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) {
|
func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) {
|
||||||
|
|
@ -1268,7 +1214,7 @@ func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) {
|
||||||
return err.Error(), false
|
return err.Error(), false
|
||||||
}
|
}
|
||||||
|
|
||||||
return "Created", true
|
return "", true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) {
|
func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) {
|
||||||
|
|
@ -1281,5 +1227,5 @@ func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) {
|
||||||
return err.Error(), false
|
return err.Error(), false
|
||||||
}
|
}
|
||||||
|
|
||||||
return "Created", true
|
return "", true
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -129,7 +129,6 @@ func (c *Client) Connect(resource string) error {
|
||||||
tdlibClient, err := client.NewClient(c.authorizer, c.options...)
|
tdlibClient, err := client.NewClient(c.authorizer, c.options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.locks.authorizationReady.Unlock()
|
c.locks.authorizationReady.Unlock()
|
||||||
c.wizardStageOrPrompt("cancel", "")
|
|
||||||
return errors.Wrap(err, "Couldn't initialize a Telegram client instance")
|
return errors.Wrap(err, "Couldn't initialize a Telegram client instance")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -138,8 +137,6 @@ func (c *Client) Connect(resource string) error {
|
||||||
// stage 3: if a client is succesfully created, AuthorizationStateReady is already reached
|
// stage 3: if a client is succesfully created, AuthorizationStateReady is already reached
|
||||||
log.Warn("Authorization successful!")
|
log.Warn("Authorization successful!")
|
||||||
|
|
||||||
c.wizardStageOrPrompt("success", "")
|
|
||||||
|
|
||||||
c.me, err = c.client.GetMe()
|
c.me, err = c.client.GetMe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Could not retrieve me info")
|
log.Error("Could not retrieve me info")
|
||||||
|
|
@ -153,13 +150,11 @@ func (c *Client) Connect(resource string) error {
|
||||||
c.addResource(resource)
|
c.addResource(resource)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
chats, err := c.client.GetChats(&client.GetChatsRequest{
|
_, err = c.client.GetChats(&client.GetChatsRequest{
|
||||||
Limit: chatsLimit,
|
Limit: chatsLimit,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("Could not retrieve chats: %v", err)
|
log.Errorf("Could not retrieve chats: %v", err)
|
||||||
} else {
|
|
||||||
log.Infof("Obtained ≈%v chats for initialization", chats.TotalCount)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gateway.SubscribeToTransport(c.xmpp, c.jid)
|
gateway.SubscribeToTransport(c.xmpp, c.jid)
|
||||||
|
|
@ -231,7 +226,7 @@ func (c *Client) Disconnect(resource string, quit bool) bool {
|
||||||
log.Warn("Disconnecting from Telegram network...")
|
log.Warn("Disconnecting from Telegram network...")
|
||||||
|
|
||||||
// we're offline (unsubscribe if logout)
|
// we're offline (unsubscribe if logout)
|
||||||
for _, id := range c.cache.OwnChatsKeys() {
|
for _, id := range c.cache.ChatsKeys() {
|
||||||
args := gateway.SimplePresence(id, "unavailable")
|
args := gateway.SimplePresence(id, "unavailable")
|
||||||
c.sendPresence(args...)
|
c.sendPresence(args...)
|
||||||
}
|
}
|
||||||
|
|
@ -260,8 +255,6 @@ func (c *Client) interactor() {
|
||||||
log.Infof("Telegram authorization state: %#v", stateType)
|
log.Infof("Telegram authorization state: %#v", stateType)
|
||||||
log.Debugf("%#v", state)
|
log.Debugf("%#v", state)
|
||||||
|
|
||||||
c.lastAuthorizationStateType = stateType
|
|
||||||
|
|
||||||
switch stateType {
|
switch stateType {
|
||||||
// stage 0: set login
|
// stage 0: set login
|
||||||
case client.TypeAuthorizationStateWaitPhoneNumber:
|
case client.TypeAuthorizationStateWaitPhoneNumber:
|
||||||
|
|
@ -269,12 +262,12 @@ func (c *Client) interactor() {
|
||||||
if c.Session.Login != "" {
|
if c.Session.Login != "" {
|
||||||
c.authorizer.PhoneNumber <- c.Session.Login
|
c.authorizer.PhoneNumber <- c.Session.Login
|
||||||
} else {
|
} else {
|
||||||
c.wizardStageOrPrompt("login", "Please, enter your Telegram login via /login 12345, or use the Login Wizard via Ad-Hoc commands")
|
gateway.SendServiceMessage(c.jid, "Please, enter your Telegram login via /login 12345", c.xmpp)
|
||||||
}
|
}
|
||||||
// stage 1: wait for auth code
|
// stage 1: wait for auth code
|
||||||
case client.TypeAuthorizationStateWaitCode:
|
case client.TypeAuthorizationStateWaitCode:
|
||||||
log.Warn("Waiting for authorization code...")
|
log.Warn("Waiting for authorization code...")
|
||||||
c.wizardStageOrPrompt("code", "Please, enter authorization code via /code 12345")
|
gateway.SendServiceMessage(c.jid, "Please, enter authorization code via /code 12345", c.xmpp)
|
||||||
// stage 1b: wait for registration
|
// stage 1b: wait for registration
|
||||||
case client.TypeAuthorizationStateWaitRegistration:
|
case client.TypeAuthorizationStateWaitRegistration:
|
||||||
log.Warn("Waiting for full name...")
|
log.Warn("Waiting for full name...")
|
||||||
|
|
@ -282,7 +275,7 @@ func (c *Client) interactor() {
|
||||||
// stage 2: wait for 2fa
|
// stage 2: wait for 2fa
|
||||||
case client.TypeAuthorizationStateWaitPassword:
|
case client.TypeAuthorizationStateWaitPassword:
|
||||||
log.Warn("Waiting for 2FA password...")
|
log.Warn("Waiting for 2FA password...")
|
||||||
c.wizardStageOrPrompt("password", "Please, enter 2FA passphrase via /password 12345")
|
gateway.SendServiceMessage(c.jid, "Please, enter 2FA passphrase via /password 12345", c.xmpp)
|
||||||
}
|
}
|
||||||
c.locks.authorizerReadLock.Unlock()
|
c.locks.authorizerReadLock.Unlock()
|
||||||
}
|
}
|
||||||
|
|
@ -301,7 +294,6 @@ func (c *Client) forceClose() {
|
||||||
func (c *Client) close() {
|
func (c *Client) close() {
|
||||||
c.locks.authorizerWriteLock.Lock()
|
c.locks.authorizerWriteLock.Lock()
|
||||||
if c.authorizer != nil && !c.authorizer.isClosed {
|
if c.authorizer != nil && !c.authorizer.isClosed {
|
||||||
log.Debug("Closing authorizer")
|
|
||||||
c.authorizer.Close()
|
c.authorizer.Close()
|
||||||
}
|
}
|
||||||
c.locks.authorizerWriteLock.Unlock()
|
c.locks.authorizerWriteLock.Unlock()
|
||||||
|
|
@ -316,7 +308,6 @@ func (c *Client) close() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cancelAuth() {
|
func (c *Client) cancelAuth() {
|
||||||
c.StopLoginWizard()
|
|
||||||
c.close()
|
c.close()
|
||||||
c.Session.Login = ""
|
c.Session.Login = ""
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -186,13 +186,13 @@ func (c *Client) updateHandler() {
|
||||||
func (c *Client) updateUser(update *client.UpdateUser) {
|
func (c *Client) updateUser(update *client.UpdateUser) {
|
||||||
c.cache.SetUser(update.User.Id, update.User)
|
c.cache.SetUser(update.User.Id, update.User)
|
||||||
show, status, presenceType := c.userStatusToText(update.User.Status, update.User.Id)
|
show, status, presenceType := c.userStatusToText(update.User.Status, update.User.Id)
|
||||||
go c.ProcessStatusUpdate(update.User.Id, status, show, false, gateway.SPType(presenceType))
|
go c.ProcessStatusUpdate(update.User.Id, status, show, gateway.SPType(presenceType))
|
||||||
}
|
}
|
||||||
|
|
||||||
// user status changed
|
// user status changed
|
||||||
func (c *Client) updateUserStatus(update *client.UpdateUserStatus) {
|
func (c *Client) updateUserStatus(update *client.UpdateUserStatus) {
|
||||||
show, status, presenceType := c.userStatusToText(update.Status, update.UserId)
|
show, status, presenceType := c.userStatusToText(update.Status, update.UserId)
|
||||||
go c.ProcessStatusUpdate(update.UserId, status, show, false, gateway.SPImmed(false), gateway.SPType(presenceType))
|
go c.ProcessStatusUpdate(update.UserId, status, show, gateway.SPImmed(false), gateway.SPType(presenceType))
|
||||||
}
|
}
|
||||||
|
|
||||||
// new chat discovered
|
// new chat discovered
|
||||||
|
|
@ -206,14 +206,14 @@ func (c *Client) updateNewChat(update *client.UpdateNewChat) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c.cache.SetChat(update.Chat.Id, update.Chat, true)
|
c.cache.SetChat(update.Chat.Id, update.Chat)
|
||||||
|
|
||||||
if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
|
if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
|
||||||
c.subscribeToID(update.Chat.Id, update.Chat)
|
c.subscribeToID(update.Chat.Id, update.Chat)
|
||||||
}
|
}
|
||||||
|
|
||||||
if update.Chat.Id < 0 {
|
if update.Chat.Id < 0 {
|
||||||
c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat", true)
|
c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat")
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -245,23 +245,12 @@ func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
|
||||||
lock.Lock()
|
lock.Lock()
|
||||||
defer lock.Unlock()
|
defer lock.Unlock()
|
||||||
|
|
||||||
var forceCmd bool
|
c.updateLastMessageHash(update.Message.ChatId, update.Message.Id, update.Message.Content)
|
||||||
if c.LastBotCmdString != "" && update.Message.IsOutgoing {
|
|
||||||
if update.Message.Content.MessageContentType() == client.TypeMessageText {
|
|
||||||
textMessage, _ := update.Message.Content.(*client.MessageText)
|
|
||||||
|
|
||||||
if textMessage.Text != nil && textMessage.Text.Text == c.LastBotCmdString {
|
|
||||||
forceCmd = true
|
|
||||||
c.LastBotCmdString = ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ignore self outgoing messages
|
// ignore self outgoing messages
|
||||||
if update.Message.IsOutgoing &&
|
if update.Message.IsOutgoing &&
|
||||||
update.Message.SendingState != nil &&
|
update.Message.SendingState != nil &&
|
||||||
update.Message.SendingState.MessageSendingStateType() == client.TypeMessageSendingStatePending &&
|
update.Message.SendingState.MessageSendingStateType() == client.TypeMessageSendingStatePending {
|
||||||
!forceCmd {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -281,6 +270,8 @@ func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
||||||
|
|
||||||
markupFunction := c.getFormatter()
|
markupFunction := c.getFormatter()
|
||||||
|
|
||||||
|
defer c.updateLastMessageHash(update.ChatId, update.MessageId, update.NewContent)
|
||||||
|
|
||||||
log.Debugf("newContent: %#v", update.NewContent)
|
log.Debugf("newContent: %#v", update.NewContent)
|
||||||
|
|
||||||
lock := c.getChatMessageLock(update.ChatId)
|
lock := c.getChatMessageLock(update.ChatId)
|
||||||
|
|
@ -304,7 +295,7 @@ func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if update.NewContent.MessageContentType() == client.TypeMessageText {
|
if update.NewContent.MessageContentType() == client.TypeMessageText && c.hasLastMessageHashChanged(update.ChatId, update.MessageId, update.NewContent) {
|
||||||
textContent := update.NewContent.(*client.MessageText)
|
textContent := update.NewContent.(*client.MessageText)
|
||||||
log.Debugf("textContent: %#v", textContent.Text)
|
log.Debugf("textContent: %#v", textContent.Text)
|
||||||
|
|
||||||
|
|
@ -312,108 +303,66 @@ func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
||||||
sId := strconv.FormatInt(update.MessageId, 10)
|
sId := strconv.FormatInt(update.MessageId, 10)
|
||||||
var isCarbon bool
|
var isCarbon bool
|
||||||
|
|
||||||
go func() {
|
// use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
|
||||||
message, messageErr := c.client.GetMessage(&client.GetMessageRequest{
|
if c.Session.NativeEdits {
|
||||||
ChatId: update.ChatId,
|
lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
|
||||||
MessageId: update.MessageId,
|
if xmppIdErr != nil {
|
||||||
})
|
xmppId = sId
|
||||||
if messageErr != nil {
|
|
||||||
// odnako za vremya puti
|
|
||||||
// sobaka mogla podrasti
|
|
||||||
c.MessageIdChangesLock.Lock()
|
|
||||||
idsMap, idsMapOk := c.MessageIdChanges[update.ChatId]
|
|
||||||
hadNoId := false
|
|
||||||
if idsMapOk {
|
|
||||||
newId, newIdOk := idsMap[update.MessageId]
|
|
||||||
if newIdOk {
|
|
||||||
if newId.Id == 0 {
|
|
||||||
hadNoId = true
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
newId.Lock()
|
|
||||||
}
|
|
||||||
log.Infof("falling back to updated message id: %v/%v->%v", update.ChatId, update.MessageId, newId.Id)
|
|
||||||
message, messageErr = c.client.GetMessage(&client.GetMessageRequest{
|
|
||||||
ChatId: update.ChatId,
|
|
||||||
MessageId: newId.Id,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hadNoId {
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
var prefix string
|
if ok && lastXmppId == xmppId {
|
||||||
if messageErr == nil {
|
replaceId = xmppId
|
||||||
if message.EditDate == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Debugf("editDate: %v", message.EditDate)
|
|
||||||
|
|
||||||
isCarbon = c.isCarbonsEnabled() && message.IsOutgoing
|
|
||||||
// reply correction support in clients is suboptimal yet, so cut them out for now
|
|
||||||
prefix, _ = c.messageToPrefix(message, "", "", true)
|
|
||||||
} else {
|
} else {
|
||||||
log.Errorf("No message %v/%v found, cannot reliably determine if it is a carbon and if it is edited: %v", update.ChatId, update.MessageId, messageErr.Error())
|
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
|
message, messageErr := c.client.GetMessage(&client.GetMessageRequest{
|
||||||
if c.Session.NativeEdits {
|
ChatId: update.ChatId,
|
||||||
lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
|
MessageId: update.MessageId,
|
||||||
if xmppIdErr != nil {
|
})
|
||||||
xmppId = sId
|
var prefix string
|
||||||
}
|
if messageErr == nil {
|
||||||
if ok && lastXmppId == xmppId {
|
isCarbon = c.isCarbonsEnabled() && message.IsOutgoing
|
||||||
replaceId = xmppId
|
// reply correction support in clients is suboptimal yet, so cut them out for now
|
||||||
} else {
|
prefix, _ = c.messageToPrefix(message, "", "", true)
|
||||||
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId)
|
} 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))
|
||||||
|
}
|
||||||
|
|
||||||
var text strings.Builder
|
text.WriteString(formatter.Format(
|
||||||
|
textContent.Text.Text,
|
||||||
|
textContent.Text.Entities,
|
||||||
|
markupFunction,
|
||||||
|
))
|
||||||
|
|
||||||
if replaceId == "" {
|
sChatId := strconv.FormatInt(update.ChatId, 10)
|
||||||
var editChar string
|
for _, jid := range jids {
|
||||||
if c.Session.AsciiArrows {
|
gateway.SendMessage(jid, sChatId, text.String(), "e"+sId, c.xmpp, nil, replaceId, isCarbon, false)
|
||||||
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)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// message(s) deleted
|
// message(s) deleted
|
||||||
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
|
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
|
||||||
if update.IsPermanent {
|
if update.IsPermanent {
|
||||||
for _, deleteId := range update.MessageIds {
|
|
||||||
c.tryUnlockMessageId(update.ChatId, deleteId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Session.IsChatIgnored(update.ChatId) {
|
if c.Session.IsChatIgnored(update.ChatId) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if c.Session.IgnoreGroupDeletions {
|
|
||||||
chatType, chatTypeErr := c.GetChatType(update.ChatId, false)
|
|
||||||
if chatTypeErr == nil && (chatType == ChatTypeBasicGroup || chatType == ChatTypeSupergroup) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var deleteChar string
|
var deleteChar string
|
||||||
if c.Session.AsciiArrows {
|
if c.Session.AsciiArrows {
|
||||||
|
|
@ -443,19 +392,7 @@ func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucc
|
||||||
log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
|
log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
c.MessageIdChangesLock.Lock()
|
c.updateLastMessageHash(update.Message.ChatId, update.Message.Id, update.Message.Content)
|
||||||
idsMap, ok := c.MessageIdChanges[update.Message.ChatId]
|
|
||||||
if !ok {
|
|
||||||
idsMap = make(map[int64]*newId)
|
|
||||||
c.MessageIdChanges[update.Message.ChatId] = idsMap
|
|
||||||
}
|
|
||||||
id, ok := idsMap[update.OldMessageId]
|
|
||||||
if !ok {
|
|
||||||
id = newNewId()
|
|
||||||
idsMap[update.OldMessageId] = id
|
|
||||||
}
|
|
||||||
id.Id = update.Message.Id
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
|
|
||||||
c.sendMarker(update.Message.ChatId, update.Message.Id, gateway.MarkerTypeReceived)
|
c.sendMarker(update.Message.ChatId, update.Message.Id, gateway.MarkerTypeReceived)
|
||||||
|
|
||||||
|
|
@ -466,8 +403,6 @@ func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucc
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
|
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
|
||||||
c.tryUnlockMessageId(update.Message.ChatId, update.OldMessageId)
|
|
||||||
|
|
||||||
// clean uploaded files
|
// clean uploaded files
|
||||||
file, _ := c.contentToFile(update.Message.Content)
|
file, _ := c.contentToFile(update.Message.Content)
|
||||||
if file != nil && file.Local != nil {
|
if file != nil && file.Local != nil {
|
||||||
|
|
@ -480,9 +415,9 @@ func (c *Client) updateChatTitle(update *client.UpdateChatTitle) {
|
||||||
gateway.SetNickname(c.jid, strconv.FormatInt(update.ChatId, 10), update.Title, c.xmpp)
|
gateway.SetNickname(c.jid, strconv.FormatInt(update.ChatId, 10), update.Title, c.xmpp)
|
||||||
|
|
||||||
// set also the status (for group chats only)
|
// set also the status (for group chats only)
|
||||||
chat, user, _ := c.GetContactByID(update.ChatId, nil, false)
|
chat, user, _ := c.GetContactByID(update.ChatId, nil)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", false, gateway.SPImmed(true))
|
c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", gateway.SPImmed(true))
|
||||||
}
|
}
|
||||||
|
|
||||||
// update chat title in the cache
|
// update chat title in the cache
|
||||||
|
|
@ -494,15 +429,3 @@ func (c *Client) updateChatTitle(update *client.UpdateChatTitle) {
|
||||||
func (c *Client) updateChatReadOutbox(update *client.UpdateChatReadOutbox) {
|
func (c *Client) updateChatReadOutbox(update *client.UpdateChatReadOutbox) {
|
||||||
c.sendMarker(update.ChatId, update.LastReadOutboxMessageId, gateway.MarkerTypeDisplayed)
|
c.sendMarker(update.ChatId, update.LastReadOutboxMessageId, gateway.MarkerTypeDisplayed)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) tryUnlockMessageId(chatId, messageId int64) {
|
|
||||||
c.MessageIdChangesLock.Lock()
|
|
||||||
idsMap, ok := c.MessageIdChanges[chatId]
|
|
||||||
if ok {
|
|
||||||
id, ok := idsMap[messageId]
|
|
||||||
if ok {
|
|
||||||
id.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
package telegram
|
|
||||||
|
|
||||||
import (
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/zelenin/go-tdlib/client"
|
|
||||||
)
|
|
||||||
|
|
||||||
// StartLoginWizard initiates a loginWizard object
|
|
||||||
func (c *Client) StartLoginWizard(inCommand bool) {
|
|
||||||
if c.loginWizard == nil {
|
|
||||||
c.loginWizard = &loginWizardMetadata{
|
|
||||||
nextStage: make(chan string, 1),
|
|
||||||
commandSent: inCommand,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
c.loginWizard.commandSent = inCommand
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// StopLoginWizard safely destroys the loginWizard object
|
|
||||||
func (c *Client) StopLoginWizard() {
|
|
||||||
c.locks.loginWizardReadLock.Lock()
|
|
||||||
c.locks.loginWizardWriteLock.Lock()
|
|
||||||
if c.loginWizard != nil {
|
|
||||||
close(c.loginWizard.nextStage)
|
|
||||||
c.loginWizard = nil
|
|
||||||
}
|
|
||||||
c.locks.loginWizardReadLock.Unlock()
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetLoginWizardNextStage waits for the next stage from the channel
|
|
||||||
func (c *Client) GetLoginWizardNextStage() string {
|
|
||||||
c.locks.loginWizardReadLock.Lock()
|
|
||||||
defer c.locks.loginWizardReadLock.Unlock()
|
|
||||||
|
|
||||||
if c.loginWizard != nil {
|
|
||||||
if c.loginWizard.commandSent {
|
|
||||||
log.Debugf("waiting for nextStage...")
|
|
||||||
nextStage := <-c.loginWizard.nextStage
|
|
||||||
c.loginWizard.commandSent = false
|
|
||||||
c.loginWizard.chanBusy = false
|
|
||||||
log.Debugf("yielded stage %v", nextStage)
|
|
||||||
return nextStage
|
|
||||||
} else {
|
|
||||||
if c.lastAuthorizationStateType == client.TypeAuthorizationStateWaitPhoneNumber ||
|
|
||||||
c.lastAuthorizationStateType == client.TypeAuthorizationStateClosing ||
|
|
||||||
c.Session.Login == "" {
|
|
||||||
return "login"
|
|
||||||
}
|
|
||||||
switch c.lastAuthorizationStateType {
|
|
||||||
case client.TypeAuthorizationStateWaitCode:
|
|
||||||
return "code"
|
|
||||||
case client.TypeAuthorizationStateWaitPassword:
|
|
||||||
return "password"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) wizardStageOrPrompt(stage, message string) {
|
|
||||||
c.locks.loginWizardWriteLock.Lock()
|
|
||||||
if c.loginWizard == nil {
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
if message != "" {
|
|
||||||
gateway.SendServiceMessage(c.jid, message, c.xmpp)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if !c.loginWizard.chanBusy {
|
|
||||||
log.Debugf("writing wizard stage %v", stage)
|
|
||||||
c.loginWizard.nextStage <- stage
|
|
||||||
} else {
|
|
||||||
log.Warn("Skipping stage %v, wizard cannot keep up", stage)
|
|
||||||
}
|
|
||||||
c.loginWizard.chanBusy = true
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -4,8 +4,10 @@ import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/sha1"
|
"crypto/sha1"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"hash/maphash"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
@ -45,16 +47,6 @@ type messageStub struct {
|
||||||
Text string
|
Text string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BotCommand struct {
|
|
||||||
Command string
|
|
||||||
Description string
|
|
||||||
}
|
|
||||||
|
|
||||||
type BotLink struct {
|
|
||||||
Description string
|
|
||||||
Link string
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
typeFileDataSha1 byte = iota
|
typeFileDataSha1 byte = iota
|
||||||
typeFileDataBase64
|
typeFileDataBase64
|
||||||
|
|
@ -91,10 +83,8 @@ const (
|
||||||
MembersListBannedAndAdministrators
|
MembersListBannedAndAdministrators
|
||||||
)
|
)
|
||||||
|
|
||||||
const AVATAR_SIZE_LIMIT int64 = 128 * 1024
|
|
||||||
|
|
||||||
// GetContactByUsername resolves username to user id retrieves user and chat information
|
// GetContactByUsername resolves username to user id retrieves user and chat information
|
||||||
func (c *Client) GetContactByUsername(username string, own bool) (*client.Chat, *client.User, error) {
|
func (c *Client) GetContactByUsername(username string) (*client.Chat, *client.User, error) {
|
||||||
if !c.Online() {
|
if !c.Online() {
|
||||||
return nil, nil, errOffline
|
return nil, nil, errOffline
|
||||||
}
|
}
|
||||||
|
|
@ -119,11 +109,11 @@ func (c *Client) GetContactByUsername(username string, own bool) (*client.Chat,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.GetContactByID(userID, chat, own)
|
return c.GetContactByID(userID, chat)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetContactByID gets user and chat information from cache (or tries to retrieve it, if missing)
|
// GetContactByID gets user and chat information from cache (or tries to retrieve it, if missing)
|
||||||
func (c *Client) GetContactByID(id int64, chat *client.Chat, own bool) (*client.Chat, *client.User, error) {
|
func (c *Client) GetContactByID(id int64, chat *client.Chat) (*client.Chat, *client.User, error) {
|
||||||
if !c.Online() || id == 0 {
|
if !c.Online() || id == 0 {
|
||||||
return nil, nil, errOffline
|
return nil, nil, errOffline
|
||||||
}
|
}
|
||||||
|
|
@ -158,9 +148,9 @@ func (c *Client) GetContactByID(id int64, chat *client.Chat, own bool) (*client.
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c.cache.SetChat(id, cacheChat, own)
|
c.cache.SetChat(id, cacheChat)
|
||||||
} else {
|
} else {
|
||||||
c.cache.SetChat(id, chat, own)
|
c.cache.SetChat(id, chat)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if chat == nil {
|
if chat == nil {
|
||||||
|
|
@ -171,7 +161,7 @@ func (c *Client) GetContactByID(id int64, chat *client.Chat, own bool) (*client.
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetChatType obtains chat type from its information
|
// GetChatType obtains chat type from its information
|
||||||
func (c *Client) GetChatType(id int64, own bool) (ChatType, error) {
|
func (c *Client) GetChatType(id int64) (ChatType, error) {
|
||||||
if !c.Online() || id == 0 {
|
if !c.Online() || id == 0 {
|
||||||
return ChatTypeUnknown, errOffline
|
return ChatTypeUnknown, errOffline
|
||||||
}
|
}
|
||||||
|
|
@ -187,7 +177,7 @@ func (c *Client) GetChatType(id int64, own bool) (ChatType, error) {
|
||||||
return ChatTypeUnknown, err
|
return ChatTypeUnknown, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c.cache.SetChat(id, chat, own)
|
c.cache.SetChat(id, chat)
|
||||||
}
|
}
|
||||||
|
|
||||||
chatType := chat.Type.ChatTypeType()
|
chatType := chat.Type.ChatTypeType()
|
||||||
|
|
@ -209,8 +199,8 @@ func (c *Client) GetChatType(id int64, own bool) (ChatType, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsPM checks if a chat is PM
|
// IsPM checks if a chat is PM
|
||||||
func (c *Client) IsPM(id int64, own bool) (bool, error) {
|
func (c *Client) IsPM(id int64) (bool, error) {
|
||||||
typ, err := c.GetChatType(id, own)
|
typ, err := c.GetChatType(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
@ -221,40 +211,6 @@ func (c *Client) IsPM(id int64, own bool) (bool, error) {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsBot checks if a chat is a bot
|
|
||||||
func (c *Client) IsBot(id int64, own bool) (bool, error) {
|
|
||||||
_, user, err := c.GetContactByID(id, nil, own)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
if user == nil || user.Type == nil {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return user.Type.UserTypeType() == client.TypeUserTypeBot, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBotMenu retrieves the bot's attachment menu
|
|
||||||
func (c *Client) GetBotMenu(id int64) (*BotLink, []*BotCommand, error) {
|
|
||||||
fullInfo, err := c.client.GetUserFullInfo(&client.GetUserFullInfoRequest{
|
|
||||||
UserId: id,
|
|
||||||
})
|
|
||||||
if err == nil && fullInfo.BotInfo != nil {
|
|
||||||
if fullInfo.BotInfo.MenuButton != nil {
|
|
||||||
menuButton := fullInfo.BotInfo.MenuButton
|
|
||||||
return &BotLink{menuButton.Text, menuButton.Url}, nil, nil
|
|
||||||
} else {
|
|
||||||
var commands []*BotCommand
|
|
||||||
for _, command := range fullInfo.BotInfo.Commands {
|
|
||||||
commands = append(commands, &BotCommand{command.Command, command.Description})
|
|
||||||
}
|
|
||||||
return nil, commands, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) userStatusToText(status client.UserStatus, chatID int64) (string, string, string) {
|
func (c *Client) userStatusToText(status client.UserStatus, chatID int64) (string, string, string) {
|
||||||
var show, textStatus, presenceType string
|
var show, textStatus, presenceType string
|
||||||
|
|
||||||
|
|
@ -317,12 +273,6 @@ func (c *Client) getFileData(tgFile *client.File, typ byte) string {
|
||||||
priority = 32
|
priority = 32
|
||||||
}
|
}
|
||||||
|
|
||||||
// avoid not-well-formed stanza errors
|
|
||||||
if typ == typeFileDataBase64 && c.GetPhotoSize(tgFile) > AVATAR_SIZE_LIMIT {
|
|
||||||
log.Warnf("Photo %v skipped as it's too huge", tgFile.Id)
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
file, path, err := c.ForceOpenFile(tgFile, priority)
|
file, path, err := c.ForceOpenFile(tgFile, priority)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
@ -365,16 +315,16 @@ func (c *Client) SetEmptyAvatarHash(chatId int64) {
|
||||||
c.AvatarHashesLock.Unlock()
|
c.AvatarHashesLock.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPhotoSize return at least a rough size
|
// GetPhotoSha1AndSize obtains data for PEP
|
||||||
func (c *Client) GetPhotoSize(photo *client.File) int64 {
|
func (c *Client) GetPhotoSha1AndSize(photo *client.File, chatId int64) (string, int64) {
|
||||||
if photo == nil {
|
sha1 := c.GetPhotoSha1(photo, chatId)
|
||||||
return 0
|
|
||||||
}
|
|
||||||
size := photo.Size
|
size := photo.Size
|
||||||
if size == 0 {
|
if size == 0 {
|
||||||
size = photo.ExpectedSize
|
size = photo.ExpectedSize
|
||||||
}
|
}
|
||||||
return size
|
|
||||||
|
return sha1, size
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPhotoSha1 computes the photo hash
|
// GetPhotoSha1 computes the photo hash
|
||||||
|
|
@ -395,7 +345,7 @@ func (c *Client) GetPhotoBase64(photo *client.File) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProcessStatusUpdate sets contact status
|
// ProcessStatusUpdate sets contact status
|
||||||
func (c *Client) ProcessStatusUpdate(chatID int64, status string, show string, own bool, oldArgs ...args.V) error {
|
func (c *Client) ProcessStatusUpdate(chatID int64, status string, show string, oldArgs ...args.V) error {
|
||||||
if !c.Online() {
|
if !c.Online() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -404,7 +354,7 @@ func (c *Client) ProcessStatusUpdate(chatID int64, status string, show string, o
|
||||||
"chat_id": chatID,
|
"chat_id": chatID,
|
||||||
}).Info("Status update for")
|
}).Info("Status update for")
|
||||||
|
|
||||||
chat, user, err := c.GetContactByID(chatID, nil, own)
|
chat, user, err := c.GetContactByID(chatID, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -470,7 +420,7 @@ func (c *Client) FormatContact(chatID int64) string {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
chat, user, err := c.GetContactByID(chatID, nil, false)
|
chat, user, err := c.GetContactByID(chatID, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "unknown contact: " + err.Error()
|
return "unknown contact: " + err.Error()
|
||||||
}
|
}
|
||||||
|
|
@ -1091,7 +1041,7 @@ func (c *Client) isCarbonsEnabled() bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) messageToPrefix(message *client.Message, previewString string, fileString string, suppressReply bool) (string, *gateway.Reply) {
|
func (c *Client) messageToPrefix(message *client.Message, previewString string, fileString string, suppressReply bool) (string, *gateway.Reply) {
|
||||||
isPM, err := c.IsPM(message.ChatId, true)
|
isPM, err := c.IsPM(message.ChatId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("Could not determine if chat is PM: %v", err)
|
log.Errorf("Could not determine if chat is PM: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -1116,8 +1066,7 @@ func (c *Client) messageToPrefix(message *client.Message, previewString string,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// with hideids options enabled, hide the id for everything but non-carbons in group chats
|
if !isPM || !c.Session.HideIds {
|
||||||
if (!isPM && !(c.isCarbonsEnabled() && message.IsOutgoing)) || !c.Session.HideIds {
|
|
||||||
prefix = append(prefix, directionChar+strconv.FormatInt(message.Id, 10))
|
prefix = append(prefix, directionChar+strconv.FormatInt(message.Id, 10))
|
||||||
}
|
}
|
||||||
// show sender in group chats
|
// show sender in group chats
|
||||||
|
|
@ -1215,15 +1164,14 @@ func (c *Client) ProcessIncomingMessage(chatId int64, message *client.Message) {
|
||||||
ChatId: chatId,
|
ChatId: chatId,
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.cache.SetChat(chatId, chat, true)
|
c.cache.SetChat(chatId, chat)
|
||||||
go c.ProcessStatusUpdate(chatId, "", "", true, gateway.SPImmed(true))
|
go c.ProcessStatusUpdate(chatId, "", "", gateway.SPImmed(true))
|
||||||
text = "<Chat photo has changed>"
|
text = "<Chat photo has changed>"
|
||||||
|
|
||||||
if chat.Photo == nil {
|
if chat.Photo == nil {
|
||||||
c.SetEmptyAvatarHash(chatId)
|
c.SetEmptyAvatarHash(chatId)
|
||||||
} else {
|
} else {
|
||||||
sha1 := c.GetPhotoSha1(chat.Photo.Small, chatId)
|
sha1, size := c.GetPhotoSha1AndSize(chat.Photo.Small, chatId)
|
||||||
size := c.GetPhotoSize(chat.Photo.Small)
|
|
||||||
|
|
||||||
for resource := range c.resourcesRange() {
|
for resource := range c.resourcesRange() {
|
||||||
features, ok := c.XmppClientFeatures[resource]
|
features, ok := c.XmppClientFeatures[resource]
|
||||||
|
|
@ -1258,8 +1206,10 @@ func (c *Client) ProcessIncomingMessage(chatId int64, message *client.Message) {
|
||||||
var ignorePrefix bool
|
var ignorePrefix bool
|
||||||
if oobSwap {
|
if oobSwap {
|
||||||
if text == "" || message.Content.MessageContentType() == client.TypeMessageSticker {
|
if text == "" || message.Content.MessageContentType() == client.TypeMessageSticker {
|
||||||
chatType, err := c.GetChatType(chatId, true)
|
isPM, err := c.IsPM(chatId)
|
||||||
ignorePrefix = err == nil && (chatType != ChatTypeBasicGroup && chatType != ChatTypeSupergroup) && c.isCarbonsEnabled()
|
if err == nil {
|
||||||
|
ignorePrefix = isPM && c.isCarbonsEnabled()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1273,11 +1223,7 @@ func (c *Client) ProcessIncomingMessage(chatId int64, message *client.Message) {
|
||||||
|
|
||||||
if text != "" {
|
if text != "" {
|
||||||
if prefix != "" {
|
if prefix != "" {
|
||||||
separator := c.getPrefixSeparator(chatId)
|
newText.WriteString(c.getPrefixSeparator(chatId))
|
||||||
newText.WriteString(separator)
|
|
||||||
if reply != nil {
|
|
||||||
reply.End += uint64(len(separator))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
newText.WriteString(text)
|
newText.WriteString(text)
|
||||||
}
|
}
|
||||||
|
|
@ -1329,13 +1275,13 @@ func (c *Client) PrepareOutgoingMessageContent(text string) client.InputMessageC
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProcessOutgoingMessage executes commands or sends messages to mapped chats, returns message id
|
// ProcessOutgoingMessage executes commands or sends messages to mapped chats, returns message id
|
||||||
func (c *Client) ProcessOutgoingMessage(chatID int64, text string, returnJid string, replyId int64, replaceId int64, raw bool) int64 {
|
func (c *Client) ProcessOutgoingMessage(chatID int64, text string, returnJid string, replyId int64, replaceId int64) int64 {
|
||||||
if !c.Online() {
|
if !c.Online() {
|
||||||
// we're offline
|
// we're offline
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
if replaceId == 0 && !raw && (strings.HasPrefix(text, "/") || strings.HasPrefix(text, "!")) {
|
if replaceId == 0 && (strings.HasPrefix(text, "/") || strings.HasPrefix(text, "!")) {
|
||||||
// try to execute commands
|
// try to execute commands
|
||||||
response, isCommand, _ := c.ProcessChatCommand(chatID, text)
|
response, isCommand, _ := c.ProcessChatCommand(chatID, text)
|
||||||
if response != "" {
|
if response != "" {
|
||||||
|
|
@ -1460,9 +1406,9 @@ func (c *Client) prepareOutgoingMessageContent(text string, file *client.InputFi
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
// OwnChatsKeys proxies the following function from unexported cache
|
// ChatsKeys proxies the following function from unexported cache
|
||||||
func (c *Client) OwnChatsKeys() []int64 {
|
func (c *Client) ChatsKeys() []int64 {
|
||||||
return c.cache.OwnChatsKeys()
|
return c.cache.ChatsKeys()
|
||||||
}
|
}
|
||||||
|
|
||||||
// StatusesRange proxies the following function from unexported cache
|
// StatusesRange proxies the following function from unexported cache
|
||||||
|
|
@ -1519,8 +1465,8 @@ func (c *Client) roster(resource string) {
|
||||||
|
|
||||||
log.Warnf("Sending roster for %v", resource)
|
log.Warnf("Sending roster for %v", resource)
|
||||||
|
|
||||||
for _, chat := range c.cache.OwnChatsKeys() {
|
for _, chat := range c.cache.ChatsKeys() {
|
||||||
c.ProcessStatusUpdate(chat, "", "", true)
|
c.ProcessStatusUpdate(chat, "", "")
|
||||||
}
|
}
|
||||||
|
|
||||||
c.sendPresence(gateway.SPStatus("Logged in as: " + c.Session.Login))
|
c.sendPresence(gateway.SPStatus("Logged in as: " + c.Session.Login))
|
||||||
|
|
@ -1634,7 +1580,7 @@ func (c *Client) subscribeToID(id int64, chat *client.Chat) {
|
||||||
args := gateway.SimplePresence(id, "subscribe")
|
args := gateway.SimplePresence(id, "subscribe")
|
||||||
|
|
||||||
if chat == nil {
|
if chat == nil {
|
||||||
chat, _, _ = c.GetContactByID(id, nil, true)
|
chat, _, _ = c.GetContactByID(id, nil)
|
||||||
}
|
}
|
||||||
if chat != nil {
|
if chat != nil {
|
||||||
args = append(args, gateway.SPNickname(chat.Title))
|
args = append(args, gateway.SPNickname(chat.Title))
|
||||||
|
|
@ -1664,7 +1610,7 @@ func (c *Client) prepareDiskSpace(size uint64) {
|
||||||
|
|
||||||
func (c *Client) GetVcardInfo(toID int64) (VCardInfo, error) {
|
func (c *Client) GetVcardInfo(toID int64) (VCardInfo, error) {
|
||||||
var info VCardInfo
|
var info VCardInfo
|
||||||
chat, user, err := c.GetContactByID(toID, nil, false)
|
chat, user, err := c.GetContactByID(toID, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
}
|
}
|
||||||
|
|
@ -1691,7 +1637,7 @@ func (c *Client) GetVcardInfo(toID int64) (VCardInfo, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) UpdateChatNicknames() {
|
func (c *Client) UpdateChatNicknames() {
|
||||||
for _, id := range c.cache.OwnChatsKeys() {
|
for _, id := range c.cache.ChatsKeys() {
|
||||||
chat, ok := c.cache.GetChat(id)
|
chat, ok := c.cache.GetChat(id)
|
||||||
if ok {
|
if ok {
|
||||||
newArgs := []args.V{
|
newArgs := []args.V{
|
||||||
|
|
@ -1769,6 +1715,61 @@ func (c *Client) getCarbonFullJids(isOutgoing bool, ignoredResource string) []st
|
||||||
return jids
|
return jids
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) calculateMessageHash(messageId int64, content client.MessageContent) uint64 {
|
||||||
|
var h maphash.Hash
|
||||||
|
h.SetSeed(c.msgHashSeed)
|
||||||
|
|
||||||
|
buf8 := make([]byte, 8)
|
||||||
|
binary.BigEndian.PutUint64(buf8, uint64(messageId))
|
||||||
|
h.Write(buf8)
|
||||||
|
|
||||||
|
if content != nil && content.MessageContentType() == client.TypeMessageText {
|
||||||
|
textContent, ok := content.(*client.MessageText)
|
||||||
|
if !ok {
|
||||||
|
uhOh()
|
||||||
|
}
|
||||||
|
|
||||||
|
if textContent.Text != nil {
|
||||||
|
h.WriteString(textContent.Text.Text)
|
||||||
|
for _, entity := range textContent.Text.Entities {
|
||||||
|
buf4 := make([]byte, 4)
|
||||||
|
binary.BigEndian.PutUint32(buf4, uint32(entity.Offset))
|
||||||
|
h.Write(buf4)
|
||||||
|
binary.BigEndian.PutUint32(buf4, uint32(entity.Length))
|
||||||
|
h.Write(buf4)
|
||||||
|
h.WriteString(entity.Type.TextEntityTypeType())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return h.Sum64()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) updateLastMessageHash(chatId, messageId int64, content client.MessageContent) {
|
||||||
|
c.locks.lastMsgHashesLock.Lock()
|
||||||
|
defer c.locks.lastMsgHashesLock.Unlock()
|
||||||
|
|
||||||
|
c.lastMsgHashes[chatId] = c.calculateMessageHash(messageId, content)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) hasLastMessageHashChanged(chatId, messageId int64, content client.MessageContent) bool {
|
||||||
|
c.locks.lastMsgHashesLock.Lock()
|
||||||
|
defer c.locks.lastMsgHashesLock.Unlock()
|
||||||
|
|
||||||
|
oldHash, ok := c.lastMsgHashes[chatId]
|
||||||
|
newHash := c.calculateMessageHash(messageId, content)
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
log.Warnf("Last message hash for chat %v does not exist", chatId)
|
||||||
|
}
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"old hash": oldHash,
|
||||||
|
"new hash": newHash,
|
||||||
|
}).Info("Message hashes")
|
||||||
|
|
||||||
|
return !ok || oldHash != newHash
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) UpdateLastChatMessageId(chatId int64, messageId string) {
|
func (c *Client) UpdateLastChatMessageId(chatId int64, messageId string) {
|
||||||
c.locks.lastMsgIdsLock.Lock()
|
c.locks.lastMsgIdsLock.Lock()
|
||||||
defer c.locks.lastMsgIdsLock.Unlock()
|
defer c.locks.lastMsgIdsLock.Unlock()
|
||||||
|
|
@ -1796,13 +1797,6 @@ func (c *Client) usernamesToString(usernames []string) string {
|
||||||
return strings.Join(atUsernames, ", ")
|
return strings.Join(atUsernames, ", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) GetTZD() string {
|
|
||||||
if c.Session.Timezone == "" {
|
|
||||||
return "Z"
|
|
||||||
}
|
|
||||||
return c.Session.Timezone
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetChatMembers retrieves a list of chat members. "Limited" mode works only if there are no more than 20 members at all
|
// GetChatMembers retrieves a list of chat members. "Limited" mode works only if there are no more than 20 members at all
|
||||||
func (c *Client) GetChatMembers(chatID int64, limited bool, query string, membersList MembersList) ([]*client.ChatMember, error) {
|
func (c *Client) GetChatMembers(chatID int64, limited bool, query string, membersList MembersList) ([]*client.ChatMember, error) {
|
||||||
var filters []client.ChatMembersFilter
|
var filters []client.ChatMembersFilter
|
||||||
|
|
@ -1821,7 +1815,7 @@ func (c *Client) GetChatMembers(chatID int64, limited bool, query string, member
|
||||||
if limited {
|
if limited {
|
||||||
limit = 20
|
limit = 20
|
||||||
|
|
||||||
chat, _, err := c.GetContactByID(chatID, nil, true)
|
chat, _, err := c.GetContactByID(chatID, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else if chat == nil {
|
} else if chat == nil {
|
||||||
|
|
|
||||||
|
|
@ -39,11 +39,10 @@ var sizeRegex = regexp.MustCompile("\\A([0-9]+) ?([KMGTPE]?B?)\\z")
|
||||||
|
|
||||||
// NewComponent starts a new component and wraps it in
|
// NewComponent starts a new component and wraps it in
|
||||||
// a stream manager that you should start yourself
|
// a stream manager that you should start yourself
|
||||||
func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string, version string) (*xmpp.StreamManager, *xmpp.Component, error) {
|
func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string) (*xmpp.StreamManager, *xmpp.Component, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
gateway.Jid, err = stanza.NewJid(conf.Jid)
|
gateway.Jid, err = stanza.NewJid(conf.Jid)
|
||||||
gateway.Version = version
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -142,24 +141,11 @@ func heartbeat(component *xmpp.Component) {
|
||||||
chatID,
|
chatID,
|
||||||
session.LastSeenStatus(delayedStatus.TimestampOnline),
|
session.LastSeenStatus(delayedStatus.TimestampOnline),
|
||||||
"away",
|
"away",
|
||||||
true,
|
|
||||||
)
|
)
|
||||||
delete(session.DelayedStatuses, chatID)
|
delete(session.DelayedStatuses, chatID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
session.DelayedStatusesLock.Unlock()
|
session.DelayedStatusesLock.Unlock()
|
||||||
|
|
||||||
// shrink message id maps
|
|
||||||
session.MessageIdChangesLock.Lock()
|
|
||||||
for _, idsMap := range session.MessageIdChanges {
|
|
||||||
for oldMessageId, newId := range idsMap {
|
|
||||||
if newId.Ts < now - 60 {
|
|
||||||
newId.Unlock()
|
|
||||||
delete(idsMap, oldMessageId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
session.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
}
|
||||||
sessionLock.Unlock()
|
sessionLock.Unlock()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -213,20 +213,6 @@ type QueryRegisterRemove struct {
|
||||||
XMLName xml.Name `xml:"remove"`
|
XMLName xml.Name `xml:"remove"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EntityTime is from XEP-0202
|
|
||||||
type EntityTime struct {
|
|
||||||
XMLName xml.Name `xml:"urn:xmpp:time time"`
|
|
||||||
Tzo string `xml:"tzo"`
|
|
||||||
Utc string `xml:"utc"`
|
|
||||||
ResultSet *stanza.ResultSet `xml:"set,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AttachTo is from XEP-0367
|
|
||||||
type AttachTo struct {
|
|
||||||
XMLName xml.Name `xml:"urn:xmpp:message-attaching:1 attach-to"`
|
|
||||||
Id string `xml:"id,attr"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Namespace is a namespace!
|
// Namespace is a namespace!
|
||||||
func (c PresenceNickExtension) Namespace() string {
|
func (c PresenceNickExtension) Namespace() string {
|
||||||
return c.XMLName.Space
|
return c.XMLName.Space
|
||||||
|
|
@ -292,26 +278,11 @@ func (c QueryRegister) GetSet() *stanza.ResultSet {
|
||||||
return c.ResultSet
|
return c.ResultSet
|
||||||
}
|
}
|
||||||
|
|
||||||
// Namespace is a namespace!
|
|
||||||
func (c EntityTime) Namespace() string {
|
|
||||||
return c.XMLName.Space
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSet getsets!
|
|
||||||
func (c EntityTime) GetSet() *stanza.ResultSet {
|
|
||||||
return c.ResultSet
|
|
||||||
}
|
|
||||||
|
|
||||||
// Name is a packet name
|
// Name is a packet name
|
||||||
func (ClientMessage) Name() string {
|
func (ClientMessage) Name() string {
|
||||||
return "message"
|
return "message"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Namespace is a namespace!
|
|
||||||
func (c AttachTo) Namespace() string {
|
|
||||||
return c.XMLName.Space
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewReplyFallback initializes a fallback range
|
// NewReplyFallback initializes a fallback range
|
||||||
func NewReplyFallback(start uint64, end uint64) Fallback {
|
func NewReplyFallback(start uint64, end uint64) Fallback {
|
||||||
return Fallback{
|
return Fallback{
|
||||||
|
|
@ -391,16 +362,4 @@ func init() {
|
||||||
"jabber:iq:register",
|
"jabber:iq:register",
|
||||||
"query",
|
"query",
|
||||||
}, QueryRegister{})
|
}, QueryRegister{})
|
||||||
|
|
||||||
// entity time
|
|
||||||
stanza.TypeRegistry.MapExtension(stanza.PKTIQ, xml.Name{
|
|
||||||
"urn:xmpp:time",
|
|
||||||
"time",
|
|
||||||
}, EntityTime{})
|
|
||||||
|
|
||||||
// attach-to
|
|
||||||
stanza.TypeRegistry.MapExtension(stanza.PKTMessage, xml.Name{
|
|
||||||
"urn:xmpp:message-attaching:1",
|
|
||||||
"attach-to",
|
|
||||||
}, AttachTo{})
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,9 +50,6 @@ var QueueLock = sync.Mutex{}
|
||||||
// Jid stores the component's JID object
|
// Jid stores the component's JID object
|
||||||
var Jid *stanza.Jid
|
var Jid *stanza.Jid
|
||||||
|
|
||||||
// Version stores this software's version
|
|
||||||
var Version string
|
|
||||||
|
|
||||||
// IdsDB provides a disk-backed bidirectional dictionary of Telegram and XMPP ids
|
// IdsDB provides a disk-backed bidirectional dictionary of Telegram and XMPP ids
|
||||||
var IdsDB badger.IdsDB
|
var IdsDB badger.IdsDB
|
||||||
|
|
||||||
|
|
|
||||||
531
xmpp/handlers.go
531
xmpp/handlers.go
|
|
@ -7,8 +7,6 @@ import (
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/persistence"
|
"dev.narayana.im/narayana/telegabber/persistence"
|
||||||
"dev.narayana.im/narayana/telegabber/telegram"
|
"dev.narayana.im/narayana/telegabber/telegram"
|
||||||
|
|
@ -27,10 +25,6 @@ const (
|
||||||
TypeVCard4
|
TypeVCard4
|
||||||
)
|
)
|
||||||
|
|
||||||
// kludge for client resuming after the transport restart (by full jids)
|
|
||||||
var probeFired = make(map[string]bool)
|
|
||||||
var probeFiredLock = sync.Mutex{}
|
|
||||||
|
|
||||||
func logPacketType(p stanza.Packet) {
|
func logPacketType(p stanza.Packet) {
|
||||||
log.Warnf("Ignoring packet: %T\n", p)
|
log.Warnf("Ignoring packet: %T\n", p)
|
||||||
}
|
}
|
||||||
|
|
@ -76,16 +70,6 @@ func HandleIq(s xmpp.Sender, p stanza.Packet) {
|
||||||
go handleGetQueryRegister(s, iq)
|
go handleGetQueryRegister(s, iq)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, ok = iq.Payload.(*stanza.Version)
|
|
||||||
if ok {
|
|
||||||
go handleGetVersion(s, iq)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_, ok = iq.Payload.(*extensions.EntityTime)
|
|
||||||
if ok {
|
|
||||||
go handleGetEntityTime(s, iq)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else if iq.Type == stanza.IQTypeSet {
|
} else if iq.Type == stanza.IQTypeSet {
|
||||||
query, ok := iq.Payload.(*extensions.QueryRegister)
|
query, ok := iq.Payload.(*extensions.QueryRegister)
|
||||||
if ok {
|
if ok {
|
||||||
|
|
@ -149,15 +133,12 @@ func HandleMessage(s xmpp.Sender, p stanza.Packet) {
|
||||||
var reply extensions.Reply
|
var reply extensions.Reply
|
||||||
var fallback extensions.Fallback
|
var fallback extensions.Fallback
|
||||||
var replace extensions.Replace
|
var replace extensions.Replace
|
||||||
var attachTo extensions.AttachTo
|
|
||||||
msg.Get(&reply)
|
msg.Get(&reply)
|
||||||
msg.Get(&fallback)
|
msg.Get(&fallback)
|
||||||
msg.Get(&replace)
|
msg.Get(&replace)
|
||||||
msg.Get(&attachTo)
|
|
||||||
log.Debugf("reply: %#v", reply)
|
log.Debugf("reply: %#v", reply)
|
||||||
log.Debugf("fallback: %#v", fallback)
|
log.Debugf("fallback: %#v", fallback)
|
||||||
log.Debugf("replace: %#v", replace)
|
log.Debugf("replace: %#v", replace)
|
||||||
log.Debugf("attachTo: %#v", attachTo)
|
|
||||||
|
|
||||||
var replyId int64
|
var replyId int64
|
||||||
var err error
|
var err error
|
||||||
|
|
@ -223,7 +204,7 @@ func HandleMessage(s xmpp.Sender, p stanza.Packet) {
|
||||||
|
|
||||||
session.SendMessageLock.Lock()
|
session.SendMessageLock.Lock()
|
||||||
defer session.SendMessageLock.Unlock()
|
defer session.SendMessageLock.Unlock()
|
||||||
tgMessageId := session.ProcessOutgoingMessage(toID, text, msg.From, replyId, replaceId, false)
|
tgMessageId := session.ProcessOutgoingMessage(toID, text, msg.From, replyId, replaceId)
|
||||||
if tgMessageId != 0 {
|
if tgMessageId != 0 {
|
||||||
if replaceId != 0 {
|
if replaceId != 0 {
|
||||||
// not needed (is it persistent among clients though?)
|
// not needed (is it persistent among clients though?)
|
||||||
|
|
@ -233,16 +214,12 @@ func HandleMessage(s xmpp.Sender, p stanza.Packet) {
|
||||||
} */
|
} */
|
||||||
session.AddToEditOutbox(replace.Id, resource)
|
session.AddToEditOutbox(replace.Id, resource)
|
||||||
} else {
|
} else {
|
||||||
messageId := msg.Id
|
err = gateway.IdsDB.Set(session.Session.Login, bare, toID, tgMessageId, msg.Id)
|
||||||
if attachTo.Id != "" {
|
|
||||||
messageId = attachTo.Id
|
|
||||||
}
|
|
||||||
err = gateway.IdsDB.Set(session.Session.Login, bare, toID, tgMessageId, messageId)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
// session.AddToOutbox(msg.Id, resource)
|
// session.AddToOutbox(msg.Id, resource)
|
||||||
session.UpdateLastChatMessageId(toID, messageId)
|
session.UpdateLastChatMessageId(toID, msg.Id)
|
||||||
} else {
|
} else {
|
||||||
log.Errorf("Failed to save ids %v/%v %v", toID, tgMessageId, messageId)
|
log.Errorf("Failed to save ids %v/%v %v", toID, tgMessageId, msg.Id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -381,7 +358,7 @@ func handleSubscription(s xmpp.Sender, p stanza.Presence) {
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
go session.ProcessStatusUpdate(toID, "", "", true, gateway.SPImmed(false))
|
go session.ProcessStatusUpdate(toID, "", "", gateway.SPImmed(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
func handlePresence(s xmpp.Sender, p stanza.Presence) {
|
func handlePresence(s xmpp.Sender, p stanza.Presence) {
|
||||||
|
|
@ -433,32 +410,23 @@ func handlePresence(s xmpp.Sender, p stanza.Presence) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(errors.Wrap(err, "TDlib connection failure"))
|
log.Error(errors.Wrap(err, "TDlib connection failure"))
|
||||||
} else {
|
} else {
|
||||||
var probeFiredForFrom bool
|
for status := range session.StatusesRange() {
|
||||||
probeFiredLock.Lock()
|
show, description, typ := status.Destruct()
|
||||||
_, probeFiredForFrom = probeFired[p.From]
|
newArgs := []args.V{
|
||||||
probeFired[p.From] = true
|
gateway.SPImmed(false),
|
||||||
probeFiredLock.Unlock()
|
|
||||||
|
|
||||||
if p.Type != "probe" || !probeFiredForFrom {
|
|
||||||
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,
|
|
||||||
true,
|
|
||||||
newArgs...,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
probeClientFeatures(p.From, component)
|
if typ != "" {
|
||||||
session.UpdateChatNicknames()
|
newArgs = append(newArgs, gateway.SPType(typ))
|
||||||
|
}
|
||||||
|
go session.ProcessStatusUpdate(
|
||||||
|
status.ID,
|
||||||
|
description,
|
||||||
|
show,
|
||||||
|
newArgs...,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
probeClientFeatures(p.From, component)
|
||||||
|
session.UpdateChatNicknames()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -567,7 +535,7 @@ func handleGetAvatarDataIq(s xmpp.Sender, iq *stanza.IQ, pubsub *stanza.PubSubGe
|
||||||
if !ok {
|
if !ok {
|
||||||
log.Info("Could not find avatar in cache, fetching immediately")
|
log.Info("Could not find avatar in cache, fetching immediately")
|
||||||
|
|
||||||
chat, _, err := session.GetContactByID(chatId, nil, true)
|
chat, _, err := session.GetContactByID(chatId, nil)
|
||||||
if err != nil || chat == nil || chat.Photo == nil {
|
if err != nil || chat == nil || chat.Photo == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -628,7 +596,7 @@ func getTelegramChatType(from string, to string) (telegram.ChatType, error) {
|
||||||
if ok {
|
if ok {
|
||||||
session, ok := sessions[bare]
|
session, ok := sessions[bare]
|
||||||
if ok {
|
if ok {
|
||||||
return session.GetChatType(toId, true)
|
return session.GetChatType(toId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -661,8 +629,6 @@ func handleGetDiscoInfo(s xmpp.Sender, iq *stanza.IQ, di *stanza.DiscoInfo) {
|
||||||
disco.AddFeatures("jabber:iq:register")
|
disco.AddFeatures("jabber:iq:register")
|
||||||
}
|
}
|
||||||
disco.AddFeatures(gateway.NSCommand)
|
disco.AddFeatures(gateway.NSCommand)
|
||||||
disco.AddFeatures("jabber:iq:version")
|
|
||||||
disco.AddFeatures("urn:xmpp:time")
|
|
||||||
} else {
|
} else {
|
||||||
chatType, chatTypeErr := getTelegramChatType(iq.From, iq.To)
|
chatType, chatTypeErr := getTelegramChatType(iq.From, iq.To)
|
||||||
|
|
||||||
|
|
@ -713,48 +679,25 @@ func handleGetDiscoItems(s xmpp.Sender, iq *stanza.IQ, di *stanza.DiscoItems) {
|
||||||
|
|
||||||
log.Debugf("discoItems: %#v", di)
|
log.Debugf("discoItems: %#v", di)
|
||||||
|
|
||||||
toID, toOk := toToID(iq.To)
|
_, ok := toToID(iq.To)
|
||||||
if di.Node == gateway.NSCommand {
|
if di.Node == gateway.NSCommand {
|
||||||
answer.Payload = di
|
answer.Payload = di
|
||||||
|
|
||||||
chatType, chatTypeErr := getTelegramChatType(iq.From, iq.To)
|
chatType, chatTypeErr := getTelegramChatType(iq.From, iq.To)
|
||||||
|
|
||||||
var cmdType telegram.CommandType
|
var cmdType telegram.CommandType
|
||||||
if toOk {
|
if ok {
|
||||||
cmdType = telegram.CommandTypeChat
|
cmdType = telegram.CommandTypeChat
|
||||||
} else {
|
} else {
|
||||||
cmdType = telegram.CommandTypeTransport
|
cmdType = telegram.CommandTypeTransport
|
||||||
}
|
}
|
||||||
|
|
||||||
var isOnline bool
|
|
||||||
bare, _, ok := gateway.SplitJID(iq.From)
|
|
||||||
if ok {
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
if ok {
|
|
||||||
isOnline = session.Online()
|
|
||||||
|
|
||||||
if toOk {
|
|
||||||
isBot, err := session.IsBot(toID, true)
|
|
||||||
if err == nil && isBot {
|
|
||||||
di.AddItem(iq.To, "botmenu", "Bot Menu")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !(toOk || isOnline) {
|
|
||||||
di.AddItem(iq.To, "loginwizard", "Login Wizard")
|
|
||||||
}
|
|
||||||
|
|
||||||
commands := telegram.GetCommands(cmdType)
|
commands := telegram.GetCommands(cmdType)
|
||||||
for _, name := range telegram.SortedCommandKeys(commands, telegram.OnlineFilterAny) {
|
for _, name := range telegram.SortedCommandKeys(commands) {
|
||||||
command := commands[name]
|
command := commands[name]
|
||||||
if chatTypeErr == nil && !telegram.IsCommandForChatType(command, chatType) {
|
if chatTypeErr == nil && !telegram.IsCommandForChatType(command, chatType) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !isOnline && command.LoginOnly {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
di.AddItem(iq.To, name, telegram.CommandToHelpString(name, command))
|
di.AddItem(iq.To, name, telegram.CommandToHelpString(name, command))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -821,77 +764,6 @@ func handleGetQueryRegister(s xmpp.Sender, iq *stanza.IQ) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleGetVersion(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
|
|
||||||
}
|
|
||||||
|
|
||||||
answer.Version().SetInfo(gateway.Jid.Resource, gateway.Version, "")
|
|
||||||
|
|
||||||
log.Debugf("%#v", answer.Payload)
|
|
||||||
|
|
||||||
_ = gateway.ResumableSend(component, answer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleGetEntityTime(s xmpp.Sender, iq *stanza.IQ) {
|
|
||||||
component, ok := s.(*xmpp.Component)
|
|
||||||
if !ok {
|
|
||||||
log.Error("Not a component")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// separate declaration is crucial for passing as pointer to defer
|
|
||||||
var answer *stanza.IQ
|
|
||||||
var err error
|
|
||||||
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)
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
entityTime := extensions.EntityTime{
|
|
||||||
Tzo: session.GetTZD(),
|
|
||||||
Utc: time.Now().UTC().Format(time.RFC3339),
|
|
||||||
}
|
|
||||||
answer.Payload = &entityTime
|
|
||||||
|
|
||||||
log.Debugf("%#v", entityTime)
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleSetQueryRegister(s xmpp.Sender, iq *stanza.IQ, query *extensions.QueryRegister) {
|
func handleSetQueryRegister(s xmpp.Sender, iq *stanza.IQ, query *extensions.QueryRegister) {
|
||||||
component, ok := s.(*xmpp.Component)
|
component, ok := s.(*xmpp.Component)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|
@ -979,13 +851,7 @@ func handleSetQueryCommand(s xmpp.Sender, iq *stanza.IQ, command *stanza.Command
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
cancelSend := false
|
defer gateway.ResumableSend(component, answer)
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if !cancelSend {
|
|
||||||
gateway.ResumableSend(component, answer)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
log.Debugf("command: %#v", command)
|
log.Debugf("command: %#v", command)
|
||||||
|
|
||||||
|
|
@ -1011,220 +877,86 @@ func handleSetQueryCommand(s xmpp.Sender, iq *stanza.IQ, command *stanza.Command
|
||||||
cmdType = telegram.CommandTypeTransport
|
cmdType = telegram.CommandTypeTransport
|
||||||
}
|
}
|
||||||
if form != nil {
|
if form != nil {
|
||||||
if command.Node == "config" {
|
// just for the case the client messed the order somehow
|
||||||
session, ok := sessions[bare]
|
sort.Slice(form.Fields, func(i int, j int) bool {
|
||||||
if ok {
|
iField := form.Fields[i]
|
||||||
var infoStrings []string
|
jField := form.Fields[j]
|
||||||
var warnString, errString string
|
if iField != nil && jField != nil {
|
||||||
for _, field := range form.Fields {
|
ii, iErr := strconv.ParseInt(iField.Var, 10, 64)
|
||||||
if len(field.ValuesList) > 0 {
|
ji, jErr := strconv.ParseInt(jField.Var, 10, 64)
|
||||||
fieldValue := field.ValuesList[0]
|
return iErr == nil && jErr == nil && ii < ji
|
||||||
|
|
||||||
if gateway.MessageOutgoingPermissionVersion == 0 && field.Var == "carbons" && fieldValue == "true" {
|
|
||||||
warnString = "The server did not allow to enable carbons"
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// 10. In accordance with Section 3.2.2.1 of XML Schema Part 2: Datatypes, the allowable
|
|
||||||
// lexical representations for the xs:boolean datatype are the strings "0" and "false"
|
|
||||||
// for the concept 'false' and the strings "1" and "true" for the concept 'true';
|
|
||||||
// implementations MUST support both styles of lexical representation.
|
|
||||||
if persistence.PropertyType(field.Var) == persistence.PropertyTypeBool {
|
|
||||||
if fieldValue == "0" {
|
|
||||||
fieldValue = "false"
|
|
||||||
}
|
|
||||||
if fieldValue == "1" {
|
|
||||||
fieldValue = "true"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
oldValue, err := session.Session.Get(field.Var)
|
|
||||||
if err != nil || oldValue != fieldValue {
|
|
||||||
value, err := session.Session.Set(field.Var, fieldValue)
|
|
||||||
if err != nil {
|
|
||||||
errString = fmt.Sprintf("Error for field %v: %v, aborting", field.Var, err.Error())
|
|
||||||
break
|
|
||||||
}
|
|
||||||
infoStrings = append(infoStrings, fmt.Sprintf("%s set to %s", field.Var, value))
|
|
||||||
gateway.DirtySessions = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var elements []stanza.CommandElement
|
|
||||||
if errString != "" {
|
|
||||||
elements = append(elements, &stanza.Note{
|
|
||||||
Text: errString,
|
|
||||||
Type: stanza.CommandNoteTypeErr,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if warnString != "" {
|
|
||||||
elements = append(elements, &stanza.Note{
|
|
||||||
Text: warnString,
|
|
||||||
Type: stanza.CommandNoteTypeWarn,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for _, infoString := range infoStrings {
|
|
||||||
elements = append(elements, &stanza.Note{
|
|
||||||
Text: infoString,
|
|
||||||
Type: stanza.CommandNoteTypeInfo,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
answer.Payload = &stanza.Command{
|
|
||||||
SessionId: command.Node,
|
|
||||||
Node: command.Node,
|
|
||||||
Status: stanza.CommandStatusCompleted,
|
|
||||||
CommandElements: elements,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if !toOk && command.Node == "loginwizard" {
|
return false
|
||||||
var session *telegram.Client
|
})
|
||||||
answer.Payload, cancelSend, session = loginWizardPayload(bare, form, resource)
|
|
||||||
|
|
||||||
log.Debugf("immediate loginwizard payload: %#v", answer.Payload)
|
var cmd strings.Builder
|
||||||
if cancelSend {
|
cmd.WriteString("/")
|
||||||
go sendLoginWizardResponse(component, answer, session)
|
cmd.WriteString(command.Node)
|
||||||
|
for _, field := range form.Fields {
|
||||||
|
cmd.WriteString(" ")
|
||||||
|
if len(field.ValuesList) > 0 {
|
||||||
|
cmd.WriteString(field.ValuesList[0])
|
||||||
}
|
}
|
||||||
} else if toOk && command.Node == "botmenu" {
|
|
||||||
payload := &stanza.Command{
|
|
||||||
SessionId: command.Node,
|
|
||||||
Node: command.Node,
|
|
||||||
}
|
|
||||||
answer.Payload = payload
|
|
||||||
|
|
||||||
if len(form.Fields) == 1 && form.Fields[0] != nil &&
|
|
||||||
form.Fields[0].Var == "command" && len(form.Fields[0].ValuesList) == 1 {
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
if ok {
|
|
||||||
msgText := "/" + form.Fields[0].ValuesList[0]
|
|
||||||
session.LastBotCmdString = msgText
|
|
||||||
tgMessageId := session.ProcessOutgoingMessage(toId, msgText, iq.From, 0, 0, true)
|
|
||||||
if tgMessageId != 0 {
|
|
||||||
payload.Status = stanza.CommandStatusCompleted
|
|
||||||
} else {
|
|
||||||
setCommandPayloadError(payload, "Failed to send a bot command")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setCommandPayloadError(payload, "Session is lost")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setCommandPayloadError(payload, "Broken form")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cmdString = cmd.String()
|
||||||
} else {
|
} else {
|
||||||
if command.Action == "" || command.Action == stanza.CommandActionExecute {
|
if command.Action == "" || command.Action == stanza.CommandActionExecute {
|
||||||
cmd, ok := telegram.GetCommand(cmdType, command.Node)
|
cmd, ok := telegram.GetCommand(cmdType, command.Node)
|
||||||
if ok && len(cmd.Arguments) > 0 {
|
if ok && len(cmd.Arguments) > 0 {
|
||||||
var fields []*stanza.Field
|
var fields []*stanza.Field
|
||||||
if command.Node == "config" {
|
for i, arg := range cmd.Arguments {
|
||||||
session, ok := sessions[bare]
|
var required *string
|
||||||
if ok {
|
if i < cmd.RequiredArgs {
|
||||||
for _, key := range persistence.ConfigKeys {
|
dummyString := ""
|
||||||
// no reason to display the item if carbons won't work
|
required = &dummyString
|
||||||
if key == "carbons" && gateway.MessageOutgoingPermissionVersion == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
value, err := session.Session.Get(key)
|
|
||||||
if err != nil {
|
|
||||||
log.Errorf("Achtung! Programming error in sessions with key %v", key)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var fieldType string
|
|
||||||
if persistence.PropertyType(key) == persistence.PropertyTypeBool {
|
|
||||||
fieldType = stanza.FieldTypeBool
|
|
||||||
}
|
|
||||||
|
|
||||||
field := stanza.Field{
|
|
||||||
Var: key,
|
|
||||||
Label: key,
|
|
||||||
Type: fieldType,
|
|
||||||
ValuesList: []string{value},
|
|
||||||
}
|
|
||||||
fields = append(fields, &field)
|
|
||||||
log.Debugf("field: %#v", field)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
for i, arg := range cmd.Arguments {
|
|
||||||
var required *string
|
|
||||||
if i < cmd.RequiredArgs {
|
|
||||||
dummyString := ""
|
|
||||||
required = &dummyString
|
|
||||||
}
|
|
||||||
|
|
||||||
var fieldType string
|
var fieldType string
|
||||||
var options []stanza.Option
|
var options []stanza.Option
|
||||||
if toOk && i == 0 {
|
if toOk && i == 0 {
|
||||||
switch command.Node {
|
switch command.Node {
|
||||||
case "mute", "kick", "ban", "promote", "unmute", "unban":
|
case "mute", "kick", "ban", "promote", "unmute", "unban":
|
||||||
session, ok := sessions[bare]
|
session, ok := sessions[bare]
|
||||||
if ok {
|
if ok {
|
||||||
var membersList telegram.MembersList
|
var membersList telegram.MembersList
|
||||||
|
switch command.Node {
|
||||||
|
case "unmute":
|
||||||
|
membersList = telegram.MembersListRestricted
|
||||||
|
case "unban":
|
||||||
|
membersList = telegram.MembersListBannedAndAdministrators
|
||||||
|
}
|
||||||
|
members, err := session.GetChatMembers(toId, true, "", membersList)
|
||||||
|
if err == nil {
|
||||||
|
fieldType = stanza.FieldTypeListSingle
|
||||||
switch command.Node {
|
switch command.Node {
|
||||||
case "unmute":
|
// allow empty form
|
||||||
membersList = telegram.MembersListRestricted
|
case "mute", "unmute":
|
||||||
case "unban":
|
options = append(options, stanza.Option{
|
||||||
membersList = telegram.MembersListBannedAndAdministrators
|
ValuesList: []string{""},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
members, err := session.GetChatMembers(toId, true, "", membersList)
|
for _, member := range members {
|
||||||
if err == nil {
|
senderId := session.GetSenderId(member.MemberId)
|
||||||
fieldType = stanza.FieldTypeListSingle
|
options = append(options, stanza.Option{
|
||||||
switch command.Node {
|
Label: session.FormatContact(senderId),
|
||||||
// allow empty form
|
ValuesList: []string{strconv.FormatInt(senderId, 10)},
|
||||||
case "mute", "unmute":
|
})
|
||||||
options = append(options, stanza.Option{
|
|
||||||
ValuesList: []string{""},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for _, member := range members {
|
|
||||||
senderId := session.GetSenderId(member.MemberId)
|
|
||||||
options = append(options, stanza.Option{
|
|
||||||
Label: session.FormatContact(senderId),
|
|
||||||
ValuesList: []string{strconv.FormatInt(senderId, 10)},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
field := stanza.Field{
|
|
||||||
Var: strconv.FormatInt(int64(i), 10),
|
|
||||||
Label: arg,
|
|
||||||
Required: required,
|
|
||||||
Type: fieldType,
|
|
||||||
Options: options,
|
|
||||||
}
|
|
||||||
fields = append(fields, &field)
|
|
||||||
log.Debugf("field: %#v", field)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
field := stanza.Field{
|
||||||
|
Var: strconv.FormatInt(int64(i), 10),
|
||||||
|
Label: arg,
|
||||||
|
Required: required,
|
||||||
|
Type: fieldType,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
fields = append(fields, &field)
|
||||||
|
log.Debugf("field: %#v", field)
|
||||||
}
|
}
|
||||||
form := stanza.Form{
|
form := stanza.Form{
|
||||||
Type: stanza.FormTypeForm,
|
Type: stanza.FormTypeForm,
|
||||||
|
|
@ -1239,79 +971,10 @@ func handleSetQueryCommand(s xmpp.Sender, iq *stanza.IQ, command *stanza.Command
|
||||||
CommandElements: []stanza.CommandElement{&form},
|
CommandElements: []stanza.CommandElement{&form},
|
||||||
}
|
}
|
||||||
log.Debugf("form: %#v", form)
|
log.Debugf("form: %#v", form)
|
||||||
} else if !toOk && command.Node == "loginwizard" {
|
|
||||||
var session *telegram.Client
|
|
||||||
answer.Payload, cancelSend, session = loginWizardPayload(bare, nil, resource)
|
|
||||||
|
|
||||||
log.Debugf("immediate loginwizard payload: %#v", answer.Payload)
|
|
||||||
if cancelSend {
|
|
||||||
go sendLoginWizardResponse(component, answer, session)
|
|
||||||
}
|
|
||||||
} else if toOk && command.Node == "botmenu" {
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
|
|
||||||
var link *telegram.BotLink
|
|
||||||
var commands []*telegram.BotCommand
|
|
||||||
var err error
|
|
||||||
if ok {
|
|
||||||
link, commands, err = session.GetBotMenu(toId)
|
|
||||||
}
|
|
||||||
|
|
||||||
payload := &stanza.Command{
|
|
||||||
SessionId: command.Node,
|
|
||||||
Node: command.Node,
|
|
||||||
}
|
|
||||||
answer.Payload = payload
|
|
||||||
|
|
||||||
if !ok || err != nil {
|
|
||||||
setCommandPayloadError(payload, "Cannot retrieve commands")
|
|
||||||
} else {
|
|
||||||
if link != nil {
|
|
||||||
payload.Status = stanza.CommandStatusCompleted
|
|
||||||
payload.CommandElements = []stanza.CommandElement{
|
|
||||||
&stanza.Note{
|
|
||||||
Text: fmt.Sprintf("%v: %v", link.Description, link.Link),
|
|
||||||
Type: stanza.CommandNoteTypeInfo,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var options []stanza.Option
|
|
||||||
for _, cmd := range commands {
|
|
||||||
options = append(options, stanza.Option{
|
|
||||||
Label: fmt.Sprintf("/%v — %v", cmd.Command, cmd.Description),
|
|
||||||
ValuesList: []string{cmd.Command},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
dummyString := ""
|
|
||||||
field := stanza.Field{
|
|
||||||
Var: "command",
|
|
||||||
Type: stanza.FieldTypeListSingle,
|
|
||||||
Required: &dummyString,
|
|
||||||
Options: options,
|
|
||||||
}
|
|
||||||
log.Debugf("field: %#v", field)
|
|
||||||
|
|
||||||
form := stanza.Form{
|
|
||||||
Type: stanza.FormTypeForm,
|
|
||||||
Fields: []*stanza.Field{&field},
|
|
||||||
}
|
|
||||||
log.Debugf("form: %#v", form)
|
|
||||||
|
|
||||||
payload.Status = stanza.CommandStatusExecuting
|
|
||||||
payload.CommandElements = []stanza.CommandElement{&form}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
cmdString = "/" + command.Node
|
cmdString = "/" + command.Node
|
||||||
}
|
}
|
||||||
} else if command.Action == stanza.CommandActionCancel {
|
} else if command.Action == stanza.CommandActionCancel {
|
||||||
if command.Node == "loginwizard" {
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
if ok {
|
|
||||||
session.ProcessTransportCommand("/cancelauth", resource)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
answer.Payload = &stanza.Command{
|
answer.Payload = &stanza.Command{
|
||||||
SessionId: command.Node,
|
SessionId: command.Node,
|
||||||
Node: command.Node,
|
Node: command.Node,
|
||||||
|
|
@ -1355,7 +1018,7 @@ func handleSetQueryCommand(s xmpp.Sender, iq *stanza.IQ, command *stanza.Command
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugf("command response: %#v %v", answer.Payload, cancelSend)
|
log.Debugf("command response: %#v", answer.Payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
func iqAnswerSetError(answer *stanza.IQ, payload *extensions.QueryRegister, code int) {
|
func iqAnswerSetError(answer *stanza.IQ, payload *extensions.QueryRegister, code int) {
|
||||||
|
|
@ -1398,15 +1061,6 @@ func iqAnswerSetError(answer *stanza.IQ, payload *extensions.QueryRegister, code
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setCommandPayloadError(payload *stanza.Command, err string) {
|
|
||||||
note := stanza.Note{
|
|
||||||
Text: err,
|
|
||||||
Type: stanza.CommandNoteTypeErr,
|
|
||||||
}
|
|
||||||
payload.Status = stanza.CommandStatusCompleted
|
|
||||||
payload.CommandElements = append(payload.CommandElements, ¬e)
|
|
||||||
}
|
|
||||||
|
|
||||||
func probeClientFeatures(jid string, component *xmpp.Component) {
|
func probeClientFeatures(jid string, component *xmpp.Component) {
|
||||||
id, err := uuid.NewRandom()
|
id, err := uuid.NewRandom()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -1469,8 +1123,8 @@ func sendPubSubAvatarNotifications(s xmpp.Sender, jid string, session *telegram.
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, chatId := range session.OwnChatsKeys() {
|
for _, chatId := range session.ChatsKeys() {
|
||||||
chat, _, err := session.GetContactByID(chatId, nil, true)
|
chat, _, err := session.GetContactByID(chatId, nil)
|
||||||
if err != nil || chat == nil {
|
if err != nil || chat == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
@ -1480,8 +1134,7 @@ func sendPubSubAvatarNotifications(s xmpp.Sender, jid string, session *telegram.
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
sha1 := session.GetPhotoSha1(chat.Photo.Small, chat.Id)
|
sha1, size := session.GetPhotoSha1AndSize(chat.Photo.Small, chat.Id)
|
||||||
size := session.GetPhotoSize(chat.Photo.Small)
|
|
||||||
|
|
||||||
gateway.SendPubSubAvatarNotification(component, jid, chat.Id, sha1, size)
|
gateway.SendPubSubAvatarNotification(component, jid, chat.Id, sha1, size)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,101 +0,0 @@
|
||||||
package xmpp
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/telegram"
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"gosrc.io/xmpp"
|
|
||||||
"gosrc.io/xmpp/stanza"
|
|
||||||
)
|
|
||||||
|
|
||||||
func loginWizardPayload(bare string, requestForm *stanza.Form, resource string) (payload *stanza.Command, cancelSend bool, returnSession *telegram.Client) {
|
|
||||||
payload = &stanza.Command{
|
|
||||||
SessionId: "loginwizard",
|
|
||||||
Node: "loginwizard",
|
|
||||||
}
|
|
||||||
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
if ok {
|
|
||||||
returnSession = session
|
|
||||||
|
|
||||||
if requestForm == nil {
|
|
||||||
session.StartLoginWizard(false)
|
|
||||||
cancelSend = true
|
|
||||||
} else {
|
|
||||||
if len(requestForm.Fields) != 1 {
|
|
||||||
setCommandPayloadError(payload, "Hey, don't tinker with the form!")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
field := requestForm.Fields[0]
|
|
||||||
if field != nil {
|
|
||||||
if len(field.ValuesList) < 1 {
|
|
||||||
setCommandPayloadError(payload, "No value")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch field.Var {
|
|
||||||
case "login", "code", "password":
|
|
||||||
default:
|
|
||||||
setCommandPayloadError(payload, "Unknown field")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
session.StartLoginWizard(true)
|
|
||||||
response, success := session.ProcessTransportCommand(fmt.Sprintf("/%v %v", field.Var, field.ValuesList[0]), resource)
|
|
||||||
if !success {
|
|
||||||
setCommandPayloadError(payload, response)
|
|
||||||
session.StopLoginWizard()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cancelSend = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setCommandPayloadError(payload, fmt.Sprintf("Session is not initialized, add the transport (%v) to contacts first", gateway.Jid.Bare()))
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendLoginWizardResponse(component *xmpp.Component, answer *stanza.IQ, session *telegram.Client) {
|
|
||||||
payload := &stanza.Command{
|
|
||||||
SessionId: "loginwizard",
|
|
||||||
Node: "loginwizard",
|
|
||||||
}
|
|
||||||
|
|
||||||
nextStage := "login"
|
|
||||||
if session != nil {
|
|
||||||
nextStage = session.GetLoginWizardNextStage()
|
|
||||||
}
|
|
||||||
log.Debugf("nextStage: %v", nextStage)
|
|
||||||
|
|
||||||
if nextStage == "cancel" {
|
|
||||||
setCommandPayloadError(payload, "Cancelled")
|
|
||||||
session.StopLoginWizard()
|
|
||||||
} else if nextStage == "success" {
|
|
||||||
payload.Status = stanza.CommandStatusCompleted
|
|
||||||
session.StopLoginWizard()
|
|
||||||
} else {
|
|
||||||
required := ""
|
|
||||||
form := stanza.Form{
|
|
||||||
Type: stanza.FormTypeForm,
|
|
||||||
Title: "Login Wizard",
|
|
||||||
Fields: []*stanza.Field{
|
|
||||||
&stanza.Field{
|
|
||||||
Var: nextStage,
|
|
||||||
Label: nextStage,
|
|
||||||
Required: &required,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
payload.Status = stanza.CommandStatusExecuting
|
|
||||||
payload.CommandElements = append(payload.CommandElements, &form)
|
|
||||||
}
|
|
||||||
|
|
||||||
answer.Payload = payload
|
|
||||||
|
|
||||||
gateway.ResumableSend(component, answer)
|
|
||||||
}
|
|
||||||
Loading…
Reference in a new issue