Compare commits

...

10 commits

Author SHA1 Message Date
Bohdan Horbeshko
bc5e8f1217 Crash hotfix for the ANNOYING PALOCHKA fix 2026-06-20 12:57:27 -04:00
Bohdan Horbeshko
1c160a8a13 Fix the annoying PALOCHKA 2026-06-04 20:04:35 -04:00
Bohdan Horbeshko
7d9f20d007 Support reply ID accounting for SFS uploads 2026-06-02 21:48:59 -04:00
Bohdan Horbeshko
eee277e36e Track updated message ids for more reliable message edit check 2025-10-31 13:16:56 -04:00
Bohdan Horbeshko
5650850be9 Return text acknowledges for arbitrary commands 2025-10-27 18:21:49 -04:00
Bohdan Horbeshko
1d29aa4694 Generic online safety check for commands 2025-10-27 17:52:46 -04:00
Bohdan Horbeshko
e073ded9e4 Version 1.12.8 2025-10-19 13:07:16 -04:00
Bohdan Horbeshko
78a4305872 Respond to urn:xmpp:time (XEP-0202) queries 2025-10-18 16:42:40 -04:00
Bohdan Horbeshko
aaca93e66d Respond to jabber:version (XEP-0092) queries 2025-10-10 07:44:44 -04:00
Bohdan Horbeshko
e7c6318e48 Add /cancelauth command && unsubscribe from chats more eagerly 2025-10-09 11:32:33 -04:00
11 changed files with 432 additions and 149 deletions

View file

@ -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.6" VERSION := "v1.12.8"
MAKEOPTS := "-j4" MAKEOPTS := "-j4"
all: all:

View file

@ -16,7 +16,7 @@ import (
goxmpp "gosrc.io/xmpp" goxmpp "gosrc.io/xmpp"
) )
var version string = "1.12.6" var version string = "1.12.8"
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) sm, component, err = xmpp.NewComponent(config.XMPP, config.Telegram, *idsPath, version)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View file

@ -27,6 +27,41 @@ 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
@ -64,6 +99,9 @@ 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
} }
@ -149,6 +187,7 @@ func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component
lastMsgIds: make(map[int64]string), lastMsgIds: make(map[int64]string),
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),
}, },

View file

@ -51,22 +51,23 @@ 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}, "help": command{0, []string{}, "help", false, nil, false},
"login": command{1, []string{"phone"}, "sign in", false, nil}, "login": command{1, []string{"phone"}, "sign in", false, nil, false},
"logout": command{0, []string{}, "sign out", true, nil}, "logout": command{0, []string{}, "sign out", true, nil, true},
"cancelauth": command{0, []string{}, "quit the signin wizard", false, nil}, "cleanup": command{0, []string{}, "unsubscribe from all known chats", false, nil, false},
"code": command{1, []string{"xxxxx"}, "check one-time code", false, nil}, "cancelauth": command{0, []string{}, "quit the signin wizard", false, nil, false},
"password": command{1, []string{"********"}, "check 2fa password", false, nil}, "code": command{1, []string{"xxxxx"}, "check one-time code", false, nil, false},
"setusername": command{0, []string{"@username"}, "update @username", true, nil}, "password": command{1, []string{"********"}, "check 2fa password", false, nil, false},
"setname": command{1, []string{"first", "last"}, "update name", true, nil}, "setusername": command{0, []string{"@username"}, "update @username", true, nil, true},
"setbio": command{0, []string{"Lorem ipsum"}, "update about", true, nil}, "setname": command{1, []string{"first", "last"}, "update name", true, nil, false},
"setpassword": command{0, []string{"old", "new"}, "set or remove password", true, nil}, "setbio": command{0, []string{"Lorem ipsum"}, "update about", true, nil, true},
"config": command{0, []string{"param", "value"}, "view or update configuration options", false, nil}, "setpassword": command{0, []string{"old", "new"}, "set or remove password", true, nil, true},
"report": command{2, []string{"chat", "comment"}, "report a chat by id or @username", true, nil}, "config": command{0, []string{"param", "value"}, "view or update configuration options", false, nil, false},
"add": command{1, []string{"@username"}, "add @username to your chat list", true, nil}, "report": command{2, []string{"chat", "comment"}, "report a chat by id or @username", true, nil, true},
"join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", true, nil}, "add": command{1, []string{"@username"}, "add @username to your chat list", true, nil, true},
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", true, nil}, "join": command{1, []string{"https://t.me/invite_link"}, "join to chat via invite link or @publicname", true, nil, true},
"channel": command{1, []string{"title", "description"}, "create new channel «title» with «description»", true, 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»", true, nil, true},
} }
var notForGroups = []ChatType{ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel} var notForGroups = []ChatType{ChatTypeBasicGroup, ChatTypeSupergroup, ChatTypeChannel}
@ -75,38 +76,38 @@ 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}, "help": command{0, []string{}, "help", false, nil, false},
"d": command{0, []string{"n"}, "delete your last message(s)", true, nil}, "d": command{0, []string{"n"}, "delete your last message(s)", true, nil, true},
"s": command{1, []string{"edited message"}, "edit your last message", true, nil}, "s": command{1, []string{"edited message"}, "edit your last message", true, nil, true},
"silent": command{1, []string{"message"}, "send a message without sound", true, nil}, "silent": command{1, []string{"message"}, "send a message without sound", 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", true, 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},
"raw": command{1, []string{"message"}, "send a raw message not interpeted as a transport command (e.g. a bot command)", true, 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", true, nil}, "forward": command{2, []string{"message_id", "target_chat"}, "forwards a message", true, nil, true},
"vcard": command{0, []string{}, "print vCard as text", true, nil}, "vcard": command{0, []string{}, "print vCard as text", true, nil, true},
"add": command{1, []string{"@username"}, "add @username to your chat list", true, 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", true, 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", true, &notForGroups}, "group": command{1, []string{"title"}, "create groupchat «title» with current user", true, &notForGroups, true},
"supergroup": command{1, []string{"title", "description"}, "create new supergroup «title» with «description»", true, 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»", true, 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", true, &notForGroups}, "secret": command{0, []string{}, "create secretchat with current user", true, &notForGroups, true},
"search": command{0, []string{"string", "[limit]"}, "search <string> in current chat", true, 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", true, nil}, "history": command{0, []string{"limit"}, "get last [limit] messages from current chat", true, nil, true},
"block": command{0, []string{}, "blacklist current user", true, &notForGroups}, "block": command{0, []string{}, "blacklist current user", true, &notForGroups, true},
"unblock": command{0, []string{}, "unblacklist current user", true, &notForGroups}, "unblock": command{0, []string{}, "unblacklist current user", true, &notForGroups, true},
"invite": command{1, []string{"id or @username"}, "add user to current chat", true, &notForPM}, "invite": command{1, []string{"id or @username"}, "add user to current chat", true, &notForPM, true},
"link": command{0, []string{}, "get invite link for current chat", true, &notForPM}, "link": command{0, []string{}, "get invite link for current chat", true, &notForPM, true},
"kick": command{1, []string{"id or @username"}, "remove user from current chat", true, &notForPM}, "kick": command{1, []string{"id or @username"}, "remove user from current chat", true, &notForPM, true},
"mute": command{0, []string{"id or @username", "hours"}, "mute the whole chat or a user in current chat", true, &notForPMAndBasic}, "mute": command{0, []string{"id or @username", "hours"}, "mute the whole chat or a user in current chat", true, &notForPMAndBasic, true},
"unmute": command{0, []string{"id or @username"}, "unmute the whole chat or a user in the current chat", true, &notForPMAndBasic}, "unmute": command{0, []string{"id or @username"}, "unmute the whole chat or a user in the current chat", true, &notForPMAndBasic, true},
"ban": command{1, []string{"id or @username", "hours"}, "restrict @username from current chat for [hours] or forever", true, &notForPM}, "ban": command{1, []string{"id or @username", "hours"}, "restrict @username from current chat for [hours] or forever", true, &notForPM, true},
"unban": command{1, []string{"id or @username"}, "unbans @username in current chat (and devotes from admins)", true, &notForPM}, "unban": command{1, []string{"id or @username"}, "unbans @username in current chat (and devotes from admins)", true, &notForPM, true},
"promote": command{1, []string{"id or @username", "title"}, "promote user to admin in current chat", true, &notForPM}, "promote": command{1, []string{"id or @username", "title"}, "promote user to admin in current chat", true, &notForPM, true},
"leave": command{0, []string{}, "leave current chat", true, &notForPM}, "leave": command{0, []string{}, "leave current chat", true, &notForPM, true},
"leave!": command{0, []string{}, "leave current chat (for owners)", true, &notForPM}, "leave!": command{0, []string{}, "leave current chat (for owners)", true, &notForPM, true},
"ttl": command{0, []string{"seconds"}, "set secret chat messages TTL before self-destroying", true, &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", true, &onlyForSecret}, "close": command{0, []string{}, "close current secret chat", true, &onlyForSecret, true},
"delete": command{0, []string{}, "delete current chat from chat list", true, 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)", true, 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{
@ -128,6 +129,7 @@ type command struct {
Description string Description string
LoginOnly bool LoginOnly bool
NotFor *[]ChatType NotFor *[]ChatType
OnlineOnly bool
} }
type configurationOption struct { type configurationOption struct {
arguments string arguments string
@ -142,6 +144,15 @@ 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
@ -164,14 +175,20 @@ 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) []string { func SortedCommandKeys(commandMap map[string]command, onlineFilter OnlineFilter) []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)
@ -214,24 +231,32 @@ func IsCommandForChatType(cmd command, chatType ChatType) bool {
return true return true
} }
func (c *Client) helpString(typ CommandType, chatId int64) string { func commandsToHelpString(str *strings.Builder, chatType ChatType, onlineFilter OnlineFilter, commandMap map[string]command) {
var str strings.Builder for _, name := range SortedCommandKeys(commandMap, onlineFilter) {
commandMap := GetCommands(typ)
chatType, chatTypeErr := c.GetChatType(chatId, true)
str.WriteString("Available commands:\n")
for _, name := range SortedCommandKeys(commandMap) {
command := commandMap[name] command := commandMap[name]
if chatTypeErr == nil && !IsCommandForChatType(command, chatType) { if !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 {
str.WriteString("Configuration options\n") commandsToHelpString(&str, chatType, OnlineFilterNotOnline, commandMap)
str.WriteString("\nOnline-only commands:\n")
commandsToHelpString(&str, chatType, OnlineFilterOnline, commandMap)
str.WriteString("\nConfiguration options\n")
for _, name := range persistence.ConfigKeys { for _, name := range persistence.ConfigKeys {
option := transportConfigurationOptions[name] option := transportConfigurationOptions[name]
str.WriteString(name) str.WriteString(name)
@ -241,6 +266,8 @@ 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")
@ -279,6 +306,12 @@ 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]
@ -329,6 +362,9 @@ 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":
@ -367,22 +403,20 @@ 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
} }
for _, id := range c.cache.OwnChatsKeys() { c.unsubscribeFromAll()
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() {
@ -392,10 +426,6 @@ 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]
@ -440,10 +470,6 @@ 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),
}) })
@ -452,10 +478,6 @@ 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 { if len(args) > 0 {
@ -542,10 +564,6 @@ 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 {
@ -554,6 +572,10 @@ 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, true) chatType, chatTypeErr := c.GetChatType(chatID, true)
if chatTypeErr == nil && !IsCommandForChatType(command, chatType) { if chatTypeErr == nil && !IsCommandForChatType(command, chatType) {
@ -599,6 +621,7 @@ 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 {
@ -632,6 +655,7 @@ 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))
@ -659,11 +683,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
state = &client.MessageSchedulingStateSendWhenOnline{} state = &client.MessageSchedulingStateSendWhenOnline{}
result = due result = due
} else { } else {
if c.Session.Timezone == "" { due += c.GetTZD()
due += "Z"
} else {
due += c.Session.Timezone
}
switch 0 { switch 0 {
default: default:
@ -741,6 +761,7 @@ 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
// 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)
@ -1123,6 +1144,7 @@ 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
@ -1159,6 +1181,7 @@ 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
@ -1188,7 +1211,7 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool,
return "", false, false return "", false, false
} }
return "", true, true return "Success", true, true
} }
func (c *Client) cmdAdd(args []string) (string, bool) { func (c *Client) cmdAdd(args []string) (string, bool) {
@ -1204,7 +1227,7 @@ func (c *Client) cmdAdd(args []string) (string, bool) {
c.subscribeToID(chat.Id, chat) c.subscribeToID(chat.Id, chat)
return "", true return "Subscription sent", true
} }
func (c *Client) cmdJoin(args []string) (string, bool) { func (c *Client) cmdJoin(args []string) (string, bool) {
@ -1233,7 +1256,7 @@ func (c *Client) cmdJoin(args []string) (string, bool) {
} }
} }
return "", true return "Joined", true
} }
func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) { func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) {
@ -1245,7 +1268,7 @@ func (c *Client) cmdSupergroup(args []string, cmdline string) (string, bool) {
return err.Error(), false return err.Error(), false
} }
return "", true return "Created", true
} }
func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) { func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) {
@ -1258,5 +1281,5 @@ func (c *Client) cmdChannel(args []string, cmdline string) (string, bool) {
return err.Error(), false return err.Error(), false
} }
return "", true return "Created", true
} }

View file

@ -153,11 +153,13 @@ func (c *Client) Connect(resource string) error {
c.addResource(resource) c.addResource(resource)
go func() { go func() {
_, err = c.client.GetChats(&client.GetChatsRequest{ chats, 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)

View file

@ -312,67 +312,99 @@ 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
message, messageErr := c.client.GetMessage(&client.GetMessageRequest{ go func() {
ChatId: update.ChatId, message, messageErr := c.client.GetMessage(&client.GetMessageRequest{
MessageId: update.MessageId, ChatId: update.ChatId,
}) MessageId: update.MessageId,
var prefix string })
if messageErr == nil { if messageErr != nil {
if message.EditDate == 0 { // odnako za vremya puti
return // 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 messageErr == nil {
if message.EditDate == 0 {
return
}
log.Debugf("editDate: %v", message.EditDate)
isCarbon = c.isCarbonsEnabled() && message.IsOutgoing isCarbon = c.isCarbonsEnabled() && message.IsOutgoing
// reply correction support in clients is suboptimal yet, so cut them out for now // reply correction support in clients is suboptimal yet, so cut them out for now
prefix, _ = c.messageToPrefix(message, "", "", true) prefix, _ = c.messageToPrefix(message, "", "", true)
} else {
log.Errorf("No message %v/%v found, cannot reliably determine if it is a carbon and if it is edited", update.ChatId, update.MessageId)
}
// use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
if c.Session.NativeEdits {
lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
if xmppIdErr != nil {
xmppId = sId
}
if ok && lastXmppId == xmppId {
replaceId = xmppId
} else { } else {
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId) 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())
} }
}
var text strings.Builder // use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
if c.Session.NativeEdits {
if replaceId == "" { lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
var editChar string if xmppIdErr != nil {
if c.Session.AsciiArrows { xmppId = sId
editChar = "e" }
} else { if ok && lastXmppId == xmppId {
editChar = "✎" replaceId = xmppId
} else {
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId)
}
} }
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( var text strings.Builder
textContent.Text.Text,
textContent.Text.Entities,
markupFunction,
))
sChatId := strconv.FormatInt(update.ChatId, 10) if replaceId == "" {
for _, jid := range jids { var editChar string
gateway.SendMessage(jid, sChatId, text.String(), "e"+sId, c.xmpp, nil, replaceId, isCarbon, false) if c.Session.AsciiArrows {
} editChar = "e"
} else {
editChar = "✎"
}
text.WriteString(fmt.Sprintf("%s %v | ", editChar, update.MessageId))
} else if prefix != "" {
text.WriteString(prefix)
text.WriteString(c.getPrefixSeparator(update.ChatId))
}
text.WriteString(formatter.Format(
textContent.Text.Text,
textContent.Text.Entities,
markupFunction,
))
sChatId := strconv.FormatInt(update.ChatId, 10)
for _, jid := range jids {
gateway.SendMessage(jid, sChatId, text.String(), "e"+sId, c.xmpp, nil, replaceId, isCarbon, false)
}
}()
} }
} }
// 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
} }
@ -411,6 +443,20 @@ 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()
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)
// clean uploaded files // clean uploaded files
@ -420,6 +466,8 @@ 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 {
@ -446,3 +494,15 @@ 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()
}

View file

@ -1273,7 +1273,11 @@ func (c *Client) ProcessIncomingMessage(chatId int64, message *client.Message) {
if text != "" { if text != "" {
if prefix != "" { if prefix != "" {
newText.WriteString(c.getPrefixSeparator(chatId)) separator := c.getPrefixSeparator(chatId)
newText.WriteString(separator)
if reply != nil {
reply.End += uint64(len(separator))
}
} }
newText.WriteString(text) newText.WriteString(text)
} }
@ -1792,6 +1796,13 @@ 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

View file

@ -39,10 +39,11 @@ 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) (*xmpp.StreamManager, *xmpp.Component, error) { func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string, version 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
} }
@ -147,6 +148,18 @@ func heartbeat(component *xmpp.Component) {
} }
} }
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()

View file

@ -213,6 +213,20 @@ 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
@ -278,11 +292,26 @@ 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{
@ -362,4 +391,16 @@ 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{})
} }

View file

@ -50,6 +50,9 @@ 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

View file

@ -8,6 +8,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "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"
@ -75,6 +76,16 @@ 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 {
@ -138,12 +149,15 @@ 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
@ -219,12 +233,16 @@ func HandleMessage(s xmpp.Sender, p stanza.Packet) {
} */ } */
session.AddToEditOutbox(replace.Id, resource) session.AddToEditOutbox(replace.Id, resource)
} else { } else {
err = gateway.IdsDB.Set(session.Session.Login, bare, toID, tgMessageId, msg.Id) messageId := 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, msg.Id) session.UpdateLastChatMessageId(toID, messageId)
} else { } else {
log.Errorf("Failed to save ids %v/%v %v", toID, tgMessageId, msg.Id) log.Errorf("Failed to save ids %v/%v %v", toID, tgMessageId, messageId)
} }
} }
} else { } else {
@ -643,6 +661,8 @@ 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)
@ -727,7 +747,7 @@ func handleGetDiscoItems(s xmpp.Sender, iq *stanza.IQ, di *stanza.DiscoItems) {
} }
commands := telegram.GetCommands(cmdType) commands := telegram.GetCommands(cmdType)
for _, name := range telegram.SortedCommandKeys(commands) { for _, name := range telegram.SortedCommandKeys(commands, telegram.OnlineFilterAny) {
command := commands[name] command := commands[name]
if chatTypeErr == nil && !telegram.IsCommandForChatType(command, chatType) { if chatTypeErr == nil && !telegram.IsCommandForChatType(command, chatType) {
continue continue
@ -801,6 +821,77 @@ 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 {