2018-08-13 22:24:44 +02:00
|
|
|
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
|
2020-05-08 21:32:22 +02:00
|
|
|
// Copyright (C) 2020 Tulir Asokan
|
2018-08-13 22:24:44 +02:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
package main
|
2018-08-16 14:59:18 +02:00
|
|
|
|
|
|
|
import (
|
2021-02-18 22:36:14 +01:00
|
|
|
"context"
|
2019-03-14 00:06:06 +01:00
|
|
|
"encoding/json"
|
2020-09-24 14:25:36 +02:00
|
|
|
"errors"
|
2019-05-15 22:04:09 +02:00
|
|
|
"fmt"
|
2020-08-22 12:07:55 +02:00
|
|
|
"net/http"
|
2019-05-22 15:46:18 +02:00
|
|
|
"sort"
|
|
|
|
"strconv"
|
2018-08-24 18:46:14 +02:00
|
|
|
"strings"
|
2019-05-22 22:05:58 +02:00
|
|
|
"sync"
|
2018-08-16 14:59:18 +02:00
|
|
|
"time"
|
2018-08-24 18:46:14 +02:00
|
|
|
|
2018-08-16 14:59:18 +02:00
|
|
|
"github.com/skip2/go-qrcode"
|
2019-01-11 20:17:31 +01:00
|
|
|
log "maunium.net/go/maulogger/v2"
|
|
|
|
|
2019-05-21 22:44:14 +02:00
|
|
|
"github.com/Rhymen/go-whatsapp"
|
2020-07-30 17:08:26 +02:00
|
|
|
waBinary "github.com/Rhymen/go-whatsapp/binary"
|
2019-05-22 15:46:18 +02:00
|
|
|
waProto "github.com/Rhymen/go-whatsapp/binary/proto"
|
2019-05-21 22:44:14 +02:00
|
|
|
|
2020-08-22 12:07:55 +02:00
|
|
|
"maunium.net/go/mautrix"
|
2020-05-08 21:32:22 +02:00
|
|
|
"maunium.net/go/mautrix/event"
|
2019-08-10 14:24:53 +02:00
|
|
|
"maunium.net/go/mautrix/format"
|
2020-05-08 21:32:22 +02:00
|
|
|
"maunium.net/go/mautrix/id"
|
2019-08-10 14:24:53 +02:00
|
|
|
|
2018-08-24 18:46:14 +02:00
|
|
|
"maunium.net/go/mautrix-whatsapp/database"
|
2018-08-16 14:59:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type User struct {
|
|
|
|
*database.User
|
2021-02-17 00:21:30 +01:00
|
|
|
Conn *whatsapp.Conn
|
2018-08-16 14:59:18 +02:00
|
|
|
|
|
|
|
bridge *Bridge
|
2018-08-16 18:20:07 +02:00
|
|
|
log log.Logger
|
2018-08-16 14:59:18 +02:00
|
|
|
|
2019-11-10 20:22:11 +01:00
|
|
|
Admin bool
|
|
|
|
Whitelisted bool
|
|
|
|
RelaybotWhitelisted bool
|
|
|
|
|
|
|
|
IsRelaybot bool
|
2019-05-17 22:53:57 +02:00
|
|
|
|
|
|
|
ConnectionErrors int
|
2019-08-10 14:24:53 +02:00
|
|
|
CommunityID string
|
2019-05-22 22:05:58 +02:00
|
|
|
|
2020-06-25 15:44:51 +02:00
|
|
|
cleanDisconnection bool
|
|
|
|
batteryWarningsSent int
|
2020-09-17 17:48:37 +02:00
|
|
|
lastReconnection int64
|
2021-02-18 22:36:14 +01:00
|
|
|
pushName string
|
2019-07-04 14:08:58 +02:00
|
|
|
|
2019-08-30 19:57:08 +02:00
|
|
|
chatListReceived chan struct{}
|
|
|
|
syncPortalsDone chan struct{}
|
2019-08-24 23:25:29 +02:00
|
|
|
|
2020-11-06 14:52:16 +01:00
|
|
|
messageInput chan PortalMessage
|
|
|
|
messageOutput chan PortalMessage
|
2020-07-23 19:10:21 +02:00
|
|
|
|
|
|
|
syncStart chan struct{}
|
|
|
|
syncWait sync.WaitGroup
|
2020-05-27 11:16:05 +02:00
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
mgmtCreateLock sync.Mutex
|
|
|
|
connLock sync.Mutex
|
|
|
|
cancelReconnect func()
|
2021-03-15 17:06:16 +01:00
|
|
|
|
|
|
|
prevBridgeStatus *AsmuxPong
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
2018-08-26 16:08:37 +02:00
|
|
|
|
2020-05-08 21:32:22 +02:00
|
|
|
func (bridge *Bridge) GetUserByMXID(userID id.UserID) *User {
|
2019-05-16 19:14:32 +02:00
|
|
|
_, isPuppet := bridge.ParsePuppetMXID(userID)
|
|
|
|
if isPuppet || userID == bridge.Bot.UserID {
|
|
|
|
return nil
|
|
|
|
}
|
2018-08-28 23:40:54 +02:00
|
|
|
bridge.usersLock.Lock()
|
|
|
|
defer bridge.usersLock.Unlock()
|
|
|
|
user, ok := bridge.usersByMXID[userID]
|
|
|
|
if !ok {
|
2019-05-28 20:31:25 +02:00
|
|
|
return bridge.loadDBUser(bridge.DB.User.GetByMXID(userID), &userID)
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
|
|
|
return user
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (bridge *Bridge) GetUserByJID(userID whatsapp.JID) *User {
|
2018-08-28 23:40:54 +02:00
|
|
|
bridge.usersLock.Lock()
|
|
|
|
defer bridge.usersLock.Unlock()
|
|
|
|
user, ok := bridge.usersByJID[userID]
|
2018-08-16 14:59:18 +02:00
|
|
|
if !ok {
|
2019-05-28 20:31:25 +02:00
|
|
|
return bridge.loadDBUser(bridge.DB.User.GetByJID(userID), nil)
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
return user
|
|
|
|
}
|
|
|
|
|
2020-05-21 18:49:01 +02:00
|
|
|
func (user *User) addToJIDMap() {
|
|
|
|
user.bridge.usersLock.Lock()
|
|
|
|
user.bridge.usersByJID[user.JID] = user
|
|
|
|
user.bridge.usersLock.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) removeFromJIDMap() {
|
|
|
|
user.bridge.usersLock.Lock()
|
2020-10-04 12:55:09 +02:00
|
|
|
jidUser, ok := user.bridge.usersByJID[user.JID]
|
|
|
|
if ok && user == jidUser {
|
|
|
|
delete(user.bridge.usersByJID, user.JID)
|
|
|
|
}
|
2020-05-21 18:49:01 +02:00
|
|
|
user.bridge.usersLock.Unlock()
|
2020-09-27 21:30:08 +02:00
|
|
|
user.bridge.Metrics.TrackLoginState(user.JID, false)
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotLoggedIn})
|
2020-05-21 18:49:01 +02:00
|
|
|
}
|
|
|
|
|
2018-08-16 14:59:18 +02:00
|
|
|
func (bridge *Bridge) GetAllUsers() []*User {
|
2018-08-28 23:40:54 +02:00
|
|
|
bridge.usersLock.Lock()
|
|
|
|
defer bridge.usersLock.Unlock()
|
2018-08-16 14:59:18 +02:00
|
|
|
dbUsers := bridge.DB.User.GetAll()
|
|
|
|
output := make([]*User, len(dbUsers))
|
|
|
|
for index, dbUser := range dbUsers {
|
2018-08-28 23:40:54 +02:00
|
|
|
user, ok := bridge.usersByMXID[dbUser.MXID]
|
2018-08-16 14:59:18 +02:00
|
|
|
if !ok {
|
2019-05-28 20:31:25 +02:00
|
|
|
user = bridge.loadDBUser(dbUser, nil)
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
output[index] = user
|
|
|
|
}
|
|
|
|
return output
|
|
|
|
}
|
|
|
|
|
2020-05-08 21:32:22 +02:00
|
|
|
func (bridge *Bridge) loadDBUser(dbUser *database.User, mxid *id.UserID) *User {
|
2019-05-28 20:31:25 +02:00
|
|
|
if dbUser == nil {
|
|
|
|
if mxid == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
dbUser = bridge.DB.User.New()
|
|
|
|
dbUser.MXID = *mxid
|
|
|
|
dbUser.Insert()
|
|
|
|
}
|
|
|
|
user := bridge.NewUser(dbUser)
|
|
|
|
bridge.usersByMXID[user.MXID] = user
|
|
|
|
if len(user.JID) > 0 {
|
|
|
|
bridge.usersByJID[user.JID] = user
|
|
|
|
}
|
|
|
|
if len(user.ManagementRoom) > 0 {
|
|
|
|
bridge.managementRooms[user.ManagementRoom] = user
|
|
|
|
}
|
|
|
|
return user
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) GetPortals() []*Portal {
|
|
|
|
keys := user.User.GetPortalKeys()
|
|
|
|
portals := make([]*Portal, len(keys))
|
|
|
|
|
|
|
|
user.bridge.portalsLock.Lock()
|
|
|
|
for i, key := range keys {
|
|
|
|
portal, ok := user.bridge.portalsByJID[key]
|
|
|
|
if !ok {
|
|
|
|
portal = user.bridge.loadDBPortal(user.bridge.DB.Portal.GetByJID(key), &key)
|
|
|
|
}
|
|
|
|
portals[i] = portal
|
|
|
|
}
|
2020-05-28 19:35:43 +02:00
|
|
|
user.bridge.portalsLock.Unlock()
|
2019-05-28 20:31:25 +02:00
|
|
|
return portals
|
|
|
|
}
|
|
|
|
|
2018-08-18 21:57:08 +02:00
|
|
|
func (bridge *Bridge) NewUser(dbUser *database.User) *User {
|
2018-08-25 23:26:24 +02:00
|
|
|
user := &User{
|
2019-01-11 20:17:31 +01:00
|
|
|
User: dbUser,
|
|
|
|
bridge: bridge,
|
|
|
|
log: bridge.Log.Sub("User").Sub(string(dbUser.MXID)),
|
2019-05-22 22:05:58 +02:00
|
|
|
|
2019-11-10 20:22:11 +01:00
|
|
|
IsRelaybot: false,
|
|
|
|
|
2021-02-10 19:59:50 +01:00
|
|
|
chatListReceived: make(chan struct{}, 1),
|
|
|
|
syncPortalsDone: make(chan struct{}, 1),
|
2020-07-23 19:10:21 +02:00
|
|
|
syncStart: make(chan struct{}, 1),
|
2020-11-06 14:52:16 +01:00
|
|
|
messageInput: make(chan PortalMessage),
|
|
|
|
messageOutput: make(chan PortalMessage, bridge.Config.Bridge.UserMessageBuffer),
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2019-11-10 20:22:11 +01:00
|
|
|
user.RelaybotWhitelisted = user.bridge.Config.Bridge.Permissions.IsRelaybotWhitelisted(user.MXID)
|
2018-08-28 23:40:54 +02:00
|
|
|
user.Whitelisted = user.bridge.Config.Bridge.Permissions.IsWhitelisted(user.MXID)
|
|
|
|
user.Admin = user.bridge.Config.Bridge.Permissions.IsAdmin(user.MXID)
|
2019-05-22 22:05:58 +02:00
|
|
|
go user.handleMessageLoop()
|
2020-11-06 14:52:16 +01:00
|
|
|
go user.runMessageRingBuffer()
|
2018-08-25 23:26:24 +02:00
|
|
|
return user
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2020-05-27 11:16:05 +02:00
|
|
|
func (user *User) GetManagementRoom() id.RoomID {
|
|
|
|
if len(user.ManagementRoom) == 0 {
|
|
|
|
user.mgmtCreateLock.Lock()
|
|
|
|
defer user.mgmtCreateLock.Unlock()
|
|
|
|
if len(user.ManagementRoom) > 0 {
|
|
|
|
return user.ManagementRoom
|
|
|
|
}
|
|
|
|
resp, err := user.bridge.Bot.CreateRoom(&mautrix.ReqCreateRoom{
|
|
|
|
Topic: "WhatsApp bridge notices",
|
|
|
|
IsDirect: true,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to auto-create management room:", err)
|
|
|
|
} else {
|
|
|
|
user.SetManagementRoom(resp.RoomID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return user.ManagementRoom
|
|
|
|
}
|
|
|
|
|
2020-05-08 21:32:22 +02:00
|
|
|
func (user *User) SetManagementRoom(roomID id.RoomID) {
|
2018-08-18 21:57:08 +02:00
|
|
|
existingUser, ok := user.bridge.managementRooms[roomID]
|
|
|
|
if ok {
|
|
|
|
existingUser.ManagementRoom = ""
|
|
|
|
existingUser.Update()
|
|
|
|
}
|
|
|
|
|
|
|
|
user.ManagementRoom = roomID
|
|
|
|
user.bridge.managementRooms[user.ManagementRoom] = user
|
|
|
|
user.Update()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) SetSession(session *whatsapp.Session) {
|
2019-05-22 15:46:18 +02:00
|
|
|
if session == nil {
|
2021-02-05 18:26:09 +01:00
|
|
|
user.Session = nil
|
2019-05-22 15:46:18 +02:00
|
|
|
user.LastConnection = 0
|
2021-02-05 18:26:09 +01:00
|
|
|
} else if len(session.Wid) > 0 {
|
|
|
|
user.Session = session
|
|
|
|
} else {
|
|
|
|
return
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
2018-08-18 21:57:08 +02:00
|
|
|
user.Update()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) Connect(evenIfNoSession bool) bool {
|
2021-02-05 18:26:09 +01:00
|
|
|
user.connLock.Lock()
|
2021-02-18 22:36:14 +01:00
|
|
|
if user.Conn != nil {
|
2021-02-05 18:26:09 +01:00
|
|
|
user.connLock.Unlock()
|
2021-02-18 22:36:14 +01:00
|
|
|
if user.Conn.IsConnected() {
|
|
|
|
return true
|
|
|
|
} else {
|
|
|
|
return user.RestoreSession()
|
|
|
|
}
|
2018-08-18 21:57:08 +02:00
|
|
|
} else if !evenIfNoSession && user.Session == nil {
|
2021-02-05 18:26:09 +01:00
|
|
|
user.connLock.Unlock()
|
2018-08-18 21:57:08 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
user.log.Debugln("Connecting to WhatsApp")
|
2021-03-15 17:06:16 +01:00
|
|
|
if user.Session != nil {
|
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWAConnecting})
|
|
|
|
}
|
2019-05-16 17:08:30 +02:00
|
|
|
timeout := time.Duration(user.bridge.Config.Bridge.ConnectionTimeout)
|
|
|
|
if timeout == 0 {
|
|
|
|
timeout = 20
|
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
user.Conn = whatsapp.NewConn(&whatsapp.Options{
|
2021-02-05 18:26:09 +01:00
|
|
|
Timeout: timeout * time.Second,
|
|
|
|
LongClientName: user.bridge.Config.WhatsApp.OSName,
|
|
|
|
ShortClientName: user.bridge.Config.WhatsApp.BrowserName,
|
|
|
|
ClientVersion: WAVersion,
|
2021-02-18 22:36:14 +01:00
|
|
|
Log: user.log.Sub("Conn"),
|
|
|
|
Handler: []whatsapp.Handler{user},
|
2021-02-05 18:26:09 +01:00
|
|
|
})
|
2021-03-15 17:06:16 +01:00
|
|
|
user.setupAdminTestHooks()
|
2021-02-05 18:26:09 +01:00
|
|
|
user.connLock.Unlock()
|
2019-05-16 17:24:54 +02:00
|
|
|
return user.RestoreSession()
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
func (user *User) DeleteConnection() {
|
|
|
|
user.connLock.Lock()
|
|
|
|
if user.Conn == nil {
|
|
|
|
user.connLock.Unlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err := user.Conn.Disconnect()
|
2021-02-05 18:26:09 +01:00
|
|
|
if err != nil && err != whatsapp.ErrNotConnected {
|
|
|
|
user.log.Warnln("Error disconnecting: %v", err)
|
|
|
|
}
|
|
|
|
user.Conn.RemoveHandlers()
|
|
|
|
user.Conn = nil
|
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2021-02-18 22:36:14 +01:00
|
|
|
user.connLock.Unlock()
|
2021-02-05 18:26:09 +01:00
|
|
|
}
|
|
|
|
|
2018-08-18 21:57:08 +02:00
|
|
|
func (user *User) RestoreSession() bool {
|
2018-08-16 14:59:18 +02:00
|
|
|
if user.Session != nil {
|
2021-02-18 22:36:14 +01:00
|
|
|
user.Conn.SetSession(*user.Session)
|
2021-02-23 23:06:11 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
2021-02-18 22:36:14 +01:00
|
|
|
defer cancel()
|
|
|
|
err := user.Conn.Restore(true, ctx)
|
2019-05-16 17:24:54 +02:00
|
|
|
if err == whatsapp.ErrAlreadyLoggedIn {
|
|
|
|
return true
|
|
|
|
} else if err != nil {
|
2018-08-16 14:59:18 +02:00
|
|
|
user.log.Errorln("Failed to restore session:", err)
|
2020-07-30 17:08:26 +02:00
|
|
|
if errors.Is(err, whatsapp.ErrUnpaired) {
|
|
|
|
user.sendMarkdownBridgeAlert("\u26a0 Failed to connect to WhatsApp: unpaired from phone. " +
|
2021-02-05 18:26:09 +01:00
|
|
|
"To re-pair your phone, log in again.")
|
|
|
|
user.removeFromJIDMap()
|
|
|
|
//user.JID = ""
|
|
|
|
user.SetSession(nil)
|
2021-02-18 22:36:14 +01:00
|
|
|
user.DeleteConnection()
|
2021-02-05 18:26:09 +01:00
|
|
|
return false
|
2020-07-30 17:08:26 +02:00
|
|
|
} else {
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2020-07-30 17:08:26 +02:00
|
|
|
user.sendMarkdownBridgeAlert("\u26a0 Failed to connect to WhatsApp. Make sure WhatsApp " +
|
|
|
|
"on your phone is reachable and use `reconnect` to try connecting again.")
|
|
|
|
}
|
2019-08-30 20:31:55 +02:00
|
|
|
user.log.Debugln("Disconnecting due to failed session restore...")
|
2021-02-18 22:36:14 +01:00
|
|
|
err = user.Conn.Disconnect()
|
2019-08-30 20:31:55 +02:00
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to disconnect after failed session restore:", err)
|
|
|
|
}
|
2018-08-18 21:57:08 +02:00
|
|
|
return false
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2019-05-17 22:53:57 +02:00
|
|
|
user.ConnectionErrors = 0
|
2018-08-18 21:57:08 +02:00
|
|
|
user.log.Debugln("Session restored successfully")
|
2019-05-30 16:48:22 +02:00
|
|
|
user.PostLogin()
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2019-05-16 17:24:54 +02:00
|
|
|
return true
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2019-08-24 21:39:12 +02:00
|
|
|
func (user *User) HasSession() bool {
|
|
|
|
return user.Session != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) IsConnected() bool {
|
|
|
|
return user.Conn != nil && user.Conn.IsConnected() && user.Conn.IsLoggedIn()
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
|
|
|
|
2019-08-30 21:04:57 +02:00
|
|
|
func (user *User) IsLoginInProgress() bool {
|
|
|
|
return user.Conn != nil && user.Conn.IsLoginInProgress()
|
|
|
|
}
|
|
|
|
|
2020-05-08 21:32:22 +02:00
|
|
|
func (user *User) loginQrChannel(ce *CommandEvent, qrChan <-chan string, eventIDChan chan<- id.EventID) {
|
|
|
|
var qrEventID id.EventID
|
2019-07-17 23:14:04 +02:00
|
|
|
for code := range qrChan {
|
|
|
|
if code == "stop" {
|
2018-08-16 14:59:18 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to encode QR code:", err)
|
2019-05-15 23:18:43 +02:00
|
|
|
ce.Reply("Failed to encode QR code: %v", err)
|
2018-08-16 14:59:18 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-15 22:17:09 +02:00
|
|
|
bot := user.bridge.AS.BotClient()
|
|
|
|
|
2018-08-16 14:59:18 +02:00
|
|
|
resp, err := bot.UploadBytes(qrCode, "image/png")
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to upload QR code:", err)
|
2019-05-15 23:18:43 +02:00
|
|
|
ce.Reply("Failed to upload QR code: %v", err)
|
2018-08-16 14:59:18 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-07-17 23:14:04 +02:00
|
|
|
if qrEventID == "" {
|
|
|
|
sendResp, err := bot.SendImage(ce.RoomID, code, resp.ContentURI)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to send QR code to user:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
qrEventID = sendResp.EventID
|
|
|
|
eventIDChan <- qrEventID
|
|
|
|
} else {
|
2020-05-08 21:32:22 +02:00
|
|
|
_, err = bot.SendMessageEvent(ce.RoomID, event.EventMessage, &event.MessageEventContent{
|
|
|
|
MsgType: event.MsgImage,
|
2019-07-17 23:14:04 +02:00
|
|
|
Body: code,
|
2020-05-08 21:32:22 +02:00
|
|
|
URL: resp.ContentURI.CUString(),
|
|
|
|
NewContent: &event.MessageEventContent{
|
|
|
|
MsgType: event.MsgImage,
|
2019-07-17 23:14:04 +02:00
|
|
|
Body: code,
|
2020-05-08 21:32:22 +02:00
|
|
|
URL: resp.ContentURI.CUString(),
|
2019-07-17 23:14:04 +02:00
|
|
|
},
|
2020-05-08 21:32:22 +02:00
|
|
|
RelatesTo: &event.RelatesTo{
|
|
|
|
Type: event.RelReplace,
|
2019-07-17 23:14:04 +02:00
|
|
|
EventID: qrEventID,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to send edited QR code to user:", err)
|
|
|
|
}
|
2019-01-21 22:55:16 +01:00
|
|
|
}
|
2019-07-17 23:14:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) Login(ce *CommandEvent) {
|
|
|
|
qrChan := make(chan string, 3)
|
2020-05-08 21:32:22 +02:00
|
|
|
eventIDChan := make(chan id.EventID, 1)
|
2019-07-17 23:14:04 +02:00
|
|
|
go user.loginQrChannel(ce, qrChan, eventIDChan)
|
2021-02-18 22:36:14 +01:00
|
|
|
session, jid, err := user.Conn.Login(qrChan, nil, user.bridge.Config.Bridge.LoginQRRegenCount)
|
2019-07-17 23:14:04 +02:00
|
|
|
qrChan <- "stop"
|
2018-08-16 14:59:18 +02:00
|
|
|
if err != nil {
|
2020-05-08 21:32:22 +02:00
|
|
|
var eventID id.EventID
|
2019-07-17 23:14:04 +02:00
|
|
|
select {
|
|
|
|
case eventID = <-eventIDChan:
|
|
|
|
default:
|
|
|
|
}
|
2020-05-08 21:32:22 +02:00
|
|
|
reply := event.MessageEventContent{
|
|
|
|
MsgType: event.MsgText,
|
2019-07-17 23:14:04 +02:00
|
|
|
}
|
2019-05-15 22:17:09 +02:00
|
|
|
if err == whatsapp.ErrAlreadyLoggedIn {
|
2019-07-17 23:14:04 +02:00
|
|
|
reply.Body = "You're already logged in"
|
2019-05-15 22:17:09 +02:00
|
|
|
} else if err == whatsapp.ErrLoginInProgress {
|
2019-07-17 23:14:04 +02:00
|
|
|
reply.Body = "You have a login in progress already."
|
|
|
|
} else if err == whatsapp.ErrLoginTimedOut {
|
|
|
|
reply.Body = "QR code scan timed out. Please try again."
|
2019-05-15 22:17:09 +02:00
|
|
|
} else {
|
|
|
|
user.log.Warnln("Failed to log in:", err)
|
2019-07-17 23:14:04 +02:00
|
|
|
reply.Body = fmt.Sprintf("Unknown error while logging in: %v", err)
|
|
|
|
}
|
|
|
|
msg := reply
|
|
|
|
if eventID != "" {
|
|
|
|
msg.NewContent = &reply
|
2020-05-08 21:32:22 +02:00
|
|
|
msg.RelatesTo = &event.RelatesTo{
|
|
|
|
Type: event.RelReplace,
|
2019-07-17 23:14:04 +02:00
|
|
|
EventID: eventID,
|
|
|
|
}
|
2019-05-15 22:17:09 +02:00
|
|
|
}
|
2020-05-08 21:32:22 +02:00
|
|
|
_, _ = ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &msg)
|
2018-08-16 14:59:18 +02:00
|
|
|
return
|
|
|
|
}
|
2020-05-21 18:49:01 +02:00
|
|
|
// TODO there's a bit of duplication between this and the provisioning API login method
|
|
|
|
// Also between the two logout methods (commands.go and provisioning.go)
|
2021-02-18 22:36:14 +01:00
|
|
|
user.log.Debugln("Successful login as", jid, "via command")
|
2019-05-17 22:53:57 +02:00
|
|
|
user.ConnectionErrors = 0
|
2021-02-18 22:36:14 +01:00
|
|
|
user.JID = strings.Replace(jid, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, 1)
|
2020-05-21 18:49:01 +02:00
|
|
|
user.addToJIDMap()
|
2019-05-15 23:18:43 +02:00
|
|
|
user.SetSession(&session)
|
2019-05-22 15:46:18 +02:00
|
|
|
ce.Reply("Successfully logged in, synchronizing chats...")
|
2019-05-30 16:48:22 +02:00
|
|
|
user.PostLogin()
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type Chat struct {
|
|
|
|
Portal *Portal
|
|
|
|
LastMessageTime uint64
|
|
|
|
Contact whatsapp.Contact
|
|
|
|
}
|
|
|
|
|
|
|
|
type ChatList []Chat
|
|
|
|
|
|
|
|
func (cl ChatList) Len() int {
|
|
|
|
return len(cl)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cl ChatList) Less(i, j int) bool {
|
2019-05-31 20:59:23 +02:00
|
|
|
return cl[i].LastMessageTime > cl[j].LastMessageTime
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cl ChatList) Swap(i, j int) {
|
|
|
|
cl[i], cl[j] = cl[j], cl[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) PostLogin() {
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{OK: true})
|
2020-09-27 21:30:08 +02:00
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, true)
|
|
|
|
user.bridge.Metrics.TrackLoginState(user.JID, true)
|
2020-11-16 13:28:08 +01:00
|
|
|
user.bridge.Metrics.TrackBufferLength(user.MXID, 0)
|
2019-08-10 14:24:53 +02:00
|
|
|
user.log.Debugln("Locking processing of incoming messages and starting post-login sync")
|
2021-02-10 11:13:18 +01:00
|
|
|
// TODO can an old sync still be ongoing when PostLogin is called again?
|
|
|
|
// TODO 2: can the new sync happen before this happens?
|
2021-02-10 19:59:50 +01:00
|
|
|
user.chatListReceived = make(chan struct{}, 1)
|
|
|
|
user.syncPortalsDone = make(chan struct{}, 1)
|
2020-07-23 19:10:21 +02:00
|
|
|
user.syncWait.Add(1)
|
|
|
|
user.syncStart <- struct{}{}
|
2021-02-24 16:18:27 +01:00
|
|
|
go user.intPostLogin()
|
2019-05-30 16:48:22 +02:00
|
|
|
}
|
|
|
|
|
2019-12-31 19:17:03 +01:00
|
|
|
func (user *User) tryAutomaticDoublePuppeting() {
|
2021-02-11 19:47:10 +01:00
|
|
|
if !user.bridge.Config.CanDoublePuppet(user.MXID) {
|
2019-12-30 19:21:04 +01:00
|
|
|
return
|
|
|
|
}
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Checking if double puppeting needs to be enabled")
|
2019-12-30 19:21:04 +01:00
|
|
|
puppet := user.bridge.GetPuppetByJID(user.JID)
|
|
|
|
if len(puppet.CustomMXID) > 0 {
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("User already has double-puppeting enabled")
|
2019-12-30 19:21:04 +01:00
|
|
|
// Custom puppet already enabled
|
|
|
|
return
|
|
|
|
}
|
|
|
|
accessToken, err := puppet.loginWithSharedSecret(user.MXID)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to login with shared secret:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = puppet.SwitchCustomMXID(accessToken, user.MXID)
|
|
|
|
if err != nil {
|
|
|
|
puppet.log.Warnln("Failed to switch to auto-logined custom puppet:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user.log.Infoln("Successfully automatically enabled custom puppet")
|
|
|
|
}
|
|
|
|
|
2020-07-27 12:05:42 +02:00
|
|
|
func (user *User) sendBridgeNotice(formatString string, args ...interface{}) {
|
|
|
|
notice := fmt.Sprintf(formatString, args...)
|
|
|
|
_, err := user.bridge.Bot.SendNotice(user.GetManagementRoom(), notice)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnf("Failed to send bridge notice \"%s\": %v", notice, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) sendMarkdownBridgeAlert(formatString string, args ...interface{}) {
|
|
|
|
notice := fmt.Sprintf(formatString, args...)
|
|
|
|
content := format.RenderMarkdown(notice, true, false)
|
|
|
|
_, err := user.bridge.Bot.SendMessageEvent(user.GetManagementRoom(), event.EventMessage, content)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnf("Failed to send bridge alert \"%s\": %v", notice, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
func (user *User) postConnPing() bool {
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Making post-connection ping")
|
2021-02-18 22:36:14 +01:00
|
|
|
var err error
|
|
|
|
for i := 0; ; i++ {
|
|
|
|
err = user.Conn.AdminTest()
|
|
|
|
if err == nil {
|
|
|
|
user.log.Debugln("Post-connection ping OK")
|
|
|
|
return true
|
|
|
|
} else if errors.Is(err, whatsapp.ErrConnectionTimeout) && i < 5 {
|
|
|
|
user.log.Warnfln("Post-connection ping timed out, sending new one")
|
2020-07-28 14:58:36 +02:00
|
|
|
} else {
|
2021-02-18 22:36:14 +01:00
|
|
|
break
|
2020-07-28 14:58:36 +02:00
|
|
|
}
|
2020-07-27 12:06:03 +02:00
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
user.log.Errorfln("Post-connection ping failed: %v. Disconnecting and then reconnecting after a second", err)
|
|
|
|
disconnectErr := user.Conn.Disconnect()
|
|
|
|
if disconnectErr != nil {
|
|
|
|
user.log.Warnln("Error while disconnecting after failed post-connection ping:", disconnectErr)
|
|
|
|
}
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2021-02-18 22:36:14 +01:00
|
|
|
user.bridge.Metrics.TrackDisconnection(user.MXID)
|
|
|
|
go func() {
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
user.tryReconnect(fmt.Sprintf("Post-connection ping failed: %v", err))
|
|
|
|
}()
|
|
|
|
return false
|
2020-08-05 21:06:54 +02:00
|
|
|
}
|
|
|
|
|
2021-02-24 16:18:27 +01:00
|
|
|
func (user *User) intPostLogin() {
|
2020-08-05 21:06:54 +02:00
|
|
|
defer user.syncWait.Done()
|
2020-09-17 17:48:37 +02:00
|
|
|
user.lastReconnection = time.Now().Unix()
|
2020-08-05 21:06:54 +02:00
|
|
|
user.createCommunity()
|
|
|
|
user.tryAutomaticDoublePuppeting()
|
2020-07-27 12:06:03 +02:00
|
|
|
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Waiting for chat list receive confirmation")
|
2019-08-24 23:25:29 +02:00
|
|
|
select {
|
2019-08-30 19:57:08 +02:00
|
|
|
case <-user.chatListReceived:
|
|
|
|
user.log.Debugln("Chat list receive confirmation received in PostLogin")
|
|
|
|
case <-time.After(time.Duration(user.bridge.Config.Bridge.ChatListWait) * time.Second):
|
2020-07-23 19:10:21 +02:00
|
|
|
user.log.Warnln("Timed out waiting for chat list to arrive!")
|
2021-02-18 22:36:14 +01:00
|
|
|
user.postConnPing()
|
2020-08-05 21:06:54 +02:00
|
|
|
return
|
|
|
|
}
|
2020-11-06 01:29:14 +01:00
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
if !user.postConnPing() {
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Post-connection ping failed, unlocking processing of incoming messages.")
|
2019-08-30 19:57:08 +02:00
|
|
|
return
|
|
|
|
}
|
2020-11-06 01:29:14 +01:00
|
|
|
|
|
|
|
user.log.Debugln("Waiting for portal sync complete confirmation")
|
2019-08-30 19:57:08 +02:00
|
|
|
select {
|
|
|
|
case <-user.syncPortalsDone:
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Post-connection portal sync complete, unlocking processing of incoming messages.")
|
2020-11-10 11:37:33 +01:00
|
|
|
// TODO this is too short, maybe a per-portal duration?
|
2019-08-30 19:57:08 +02:00
|
|
|
case <-time.After(time.Duration(user.bridge.Config.Bridge.PortalSyncWait) * time.Second):
|
2020-07-23 19:10:21 +02:00
|
|
|
user.log.Warnln("Timed out waiting for portal sync to complete! Unlocking processing of incoming messages.")
|
2019-08-24 23:25:29 +02:00
|
|
|
}
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
type NormalMessage interface {
|
2021-02-17 00:21:30 +01:00
|
|
|
GetInfo() whatsapp.MessageInfo
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleEvent(event interface{}) {
|
|
|
|
switch v := event.(type) {
|
2021-02-18 22:36:14 +01:00
|
|
|
case NormalMessage:
|
|
|
|
info := v.GetInfo()
|
2021-02-17 00:21:30 +01:00
|
|
|
user.messageInput <- PortalMessage{info.RemoteJid, user, v, info.Timestamp}
|
|
|
|
case whatsapp.MessageRevocation:
|
|
|
|
user.messageInput <- PortalMessage{v.RemoteJid, user, v, 0}
|
|
|
|
case whatsapp.StreamEvent:
|
|
|
|
user.HandleStreamEvent(v)
|
|
|
|
case []whatsapp.Chat:
|
|
|
|
user.HandleChatList(v)
|
|
|
|
case []whatsapp.Contact:
|
|
|
|
user.HandleContactList(v)
|
|
|
|
case error:
|
|
|
|
user.HandleError(v)
|
|
|
|
case whatsapp.Contact:
|
|
|
|
go user.HandleNewContact(v)
|
|
|
|
case whatsapp.BatteryMessage:
|
|
|
|
user.HandleBatteryMessage(v)
|
|
|
|
case whatsapp.CallInfo:
|
|
|
|
user.HandleCallInfo(v)
|
|
|
|
case whatsapp.PresenceEvent:
|
|
|
|
go user.HandlePresence(v)
|
|
|
|
case whatsapp.JSONMsgInfo:
|
|
|
|
go user.HandleMsgInfo(v)
|
|
|
|
case whatsapp.ReceivedMessage:
|
|
|
|
user.HandleReceivedMessage(v)
|
|
|
|
case whatsapp.ReadMessage:
|
|
|
|
user.HandleReadMessage(v)
|
|
|
|
case whatsapp.JSONCommand:
|
|
|
|
user.HandleCommand(v)
|
|
|
|
case whatsapp.ChatUpdate:
|
|
|
|
user.HandleChatUpdate(v)
|
2021-02-18 22:36:14 +01:00
|
|
|
case whatsapp.ConnInfo:
|
|
|
|
user.HandleConnInfo(v)
|
2021-02-17 00:21:30 +01:00
|
|
|
case json.RawMessage:
|
|
|
|
user.HandleJSONMessage(v)
|
|
|
|
case *waProto.WebMessageInfo:
|
|
|
|
user.updateLastConnectionIfNecessary()
|
|
|
|
// TODO trace log
|
2021-02-21 16:11:36 +01:00
|
|
|
//user.log.Debugfln("WebMessageInfo: %+v", v)
|
2021-02-17 00:21:30 +01:00
|
|
|
case *waBinary.Node:
|
|
|
|
user.log.Debugfln("Unknown binary message: %+v", v)
|
|
|
|
default:
|
|
|
|
user.log.Debugfln("Unknown type of event in HandleEvent: %T", v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleStreamEvent(evt whatsapp.StreamEvent) {
|
|
|
|
if evt.Type == whatsapp.StreamSleep {
|
2020-09-17 17:48:37 +02:00
|
|
|
if user.lastReconnection+60 > time.Now().Unix() {
|
|
|
|
user.lastReconnection = 0
|
|
|
|
user.log.Infoln("Stream went to sleep soon after reconnection, making new post-connection ping in 20 seconds")
|
|
|
|
go func() {
|
|
|
|
time.Sleep(20 * time.Second)
|
2020-12-27 23:22:40 +01:00
|
|
|
// TODO if this happens during the post-login sync, it can get stuck forever
|
2021-02-18 22:36:14 +01:00
|
|
|
// TODO check if the above is still true
|
|
|
|
user.postConnPing()
|
2020-09-17 17:48:37 +02:00
|
|
|
}()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
user.log.Infofln("Stream event: %+v", evt)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-24 23:25:29 +02:00
|
|
|
func (user *User) HandleChatList(chats []whatsapp.Chat) {
|
2019-08-30 19:57:08 +02:00
|
|
|
user.log.Infoln("Chat list received")
|
2019-08-24 23:25:29 +02:00
|
|
|
chatMap := make(map[string]whatsapp.Chat)
|
|
|
|
for _, chat := range user.Conn.Store.Chats {
|
2021-02-18 22:36:14 +01:00
|
|
|
chatMap[chat.JID] = chat
|
2019-08-24 23:25:29 +02:00
|
|
|
}
|
|
|
|
for _, chat := range chats {
|
2021-02-18 22:36:14 +01:00
|
|
|
chatMap[chat.JID] = chat
|
2019-08-24 23:25:29 +02:00
|
|
|
}
|
2019-08-30 19:57:08 +02:00
|
|
|
select {
|
|
|
|
case user.chatListReceived <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
2019-08-24 23:25:29 +02:00
|
|
|
go user.syncPortals(chatMap, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) syncPortals(chatMap map[string]whatsapp.Chat, createAll bool) {
|
2021-02-10 11:13:18 +01:00
|
|
|
// TODO use contexts instead of checking if user.Conn is the same?
|
|
|
|
connAtStart := user.Conn
|
2019-08-24 23:25:29 +02:00
|
|
|
if chatMap == nil {
|
|
|
|
chatMap = user.Conn.Store.Chats
|
|
|
|
}
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Reading chat list")
|
2019-08-24 23:25:29 +02:00
|
|
|
chats := make(ChatList, 0, len(chatMap))
|
2019-08-10 14:24:53 +02:00
|
|
|
existingKeys := user.GetInCommunityMap()
|
2019-08-24 23:25:29 +02:00
|
|
|
portalKeys := make([]database.PortalKeyWithMeta, 0, len(chatMap))
|
|
|
|
for _, chat := range chatMap {
|
2019-05-22 15:46:18 +02:00
|
|
|
ts, err := strconv.ParseUint(chat.LastMessageTime, 10, 64)
|
|
|
|
if err != nil {
|
2021-02-18 22:36:14 +01:00
|
|
|
user.log.Warnfln("Non-integer last message time in %s: %s", chat.JID, chat.LastMessageTime)
|
2019-05-22 15:46:18 +02:00
|
|
|
continue
|
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
portal := user.GetPortalByJID(chat.JID)
|
2019-05-28 20:31:25 +02:00
|
|
|
|
2019-05-22 15:46:18 +02:00
|
|
|
chats = append(chats, Chat{
|
2019-05-28 20:31:25 +02:00
|
|
|
Portal: portal,
|
2021-02-18 22:36:14 +01:00
|
|
|
Contact: user.Conn.Store.Contacts[chat.JID],
|
2019-05-22 15:46:18 +02:00
|
|
|
LastMessageTime: ts,
|
|
|
|
})
|
2019-08-10 14:24:53 +02:00
|
|
|
var inCommunity, ok bool
|
|
|
|
if inCommunity, ok = existingKeys[portal.Key]; !ok || !inCommunity {
|
|
|
|
inCommunity = user.addPortalToCommunity(portal)
|
2020-01-07 20:25:41 +01:00
|
|
|
if portal.IsPrivateChat() {
|
|
|
|
puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
|
|
|
|
user.addPuppetToCommunity(puppet)
|
|
|
|
}
|
2019-08-10 14:24:53 +02:00
|
|
|
}
|
|
|
|
portalKeys = append(portalKeys, database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
|
2019-05-28 20:31:25 +02:00
|
|
|
}
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Read chat list, updating user-portal mapping")
|
2019-05-28 20:31:25 +02:00
|
|
|
err := user.SetPortalKeys(portalKeys)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to update user-portal mapping:", err)
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
sort.Sort(chats)
|
|
|
|
limit := user.bridge.Config.Bridge.InitialChatSync
|
|
|
|
if limit < 0 {
|
|
|
|
limit = len(chats)
|
|
|
|
}
|
2021-02-10 11:13:18 +01:00
|
|
|
if user.Conn != connAtStart {
|
|
|
|
user.log.Debugln("Connection seems to have changed before sync, cancelling")
|
|
|
|
return
|
|
|
|
}
|
2019-05-23 19:25:46 +02:00
|
|
|
now := uint64(time.Now().Unix())
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Syncing portals")
|
2019-05-22 15:46:18 +02:00
|
|
|
for i, chat := range chats {
|
2019-05-28 20:31:25 +02:00
|
|
|
if chat.LastMessageTime+user.bridge.Config.Bridge.SyncChatMaxAge < now {
|
2019-05-23 19:25:46 +02:00
|
|
|
break
|
|
|
|
}
|
2019-05-22 15:46:18 +02:00
|
|
|
create := (chat.LastMessageTime >= user.LastConnection && user.LastConnection > 0) || i < limit
|
2019-05-23 21:57:52 +02:00
|
|
|
if len(chat.Portal.MXID) > 0 || create || createAll {
|
2021-02-09 22:41:14 +01:00
|
|
|
// Don't sync unless chat meta sync is enabled or portal doesn't exist
|
|
|
|
if user.bridge.Config.Bridge.ChatMetaSync || len(chat.Portal.MXID) == 0 {
|
|
|
|
chat.Portal.Sync(user, chat.Contact)
|
|
|
|
}
|
|
|
|
err = chat.Portal.BackfillHistory(user, chat.LastMessageTime)
|
2019-05-22 15:46:18 +02:00
|
|
|
if err != nil {
|
|
|
|
chat.Portal.log.Errorln("Error backfilling history:", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-02-10 11:13:18 +01:00
|
|
|
if user.Conn != connAtStart {
|
|
|
|
user.log.Debugln("Connection seems to have changed during sync, cancelling")
|
|
|
|
return
|
|
|
|
}
|
2020-08-22 12:07:55 +02:00
|
|
|
user.UpdateDirectChats(nil)
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Finished syncing portals")
|
2019-08-24 23:25:29 +02:00
|
|
|
select {
|
|
|
|
case user.syncPortalsDone <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
2020-08-22 12:07:55 +02:00
|
|
|
func (user *User) getDirectChats() map[id.UserID][]id.RoomID {
|
|
|
|
res := make(map[id.UserID][]id.RoomID)
|
|
|
|
privateChats := user.bridge.DB.Portal.FindPrivateChats(user.JID)
|
|
|
|
for _, portal := range privateChats {
|
|
|
|
if len(portal.MXID) > 0 {
|
|
|
|
res[user.bridge.FormatPuppetMXID(portal.Key.JID)] = []id.RoomID{portal.MXID}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) UpdateDirectChats(chats map[id.UserID][]id.RoomID) {
|
|
|
|
if !user.bridge.Config.Bridge.SyncDirectChatList {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
puppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if puppet == nil || puppet.CustomIntent() == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
intent := puppet.CustomIntent()
|
|
|
|
method := http.MethodPatch
|
|
|
|
if chats == nil {
|
|
|
|
chats = user.getDirectChats()
|
|
|
|
method = http.MethodPut
|
|
|
|
}
|
|
|
|
user.log.Debugln("Updating m.direct list on homeserver")
|
|
|
|
var err error
|
|
|
|
if user.bridge.Config.Homeserver.Asmux {
|
|
|
|
urlPath := intent.BuildBaseURL("_matrix", "client", "unstable", "net.maunium.asmux", "dms")
|
2021-03-04 18:35:07 +01:00
|
|
|
_, err = intent.MakeFullRequest(mautrix.FullRequest{
|
|
|
|
Method: method,
|
|
|
|
URL: urlPath,
|
|
|
|
Headers: http.Header{"X-Asmux-Auth": {user.bridge.AS.Registration.AppToken}},
|
|
|
|
RequestJSON: chats,
|
|
|
|
})
|
2020-08-22 12:07:55 +02:00
|
|
|
} else {
|
|
|
|
existingChats := make(map[id.UserID][]id.RoomID)
|
|
|
|
err = intent.GetAccountData(event.AccountDataDirectChats.Type, &existingChats)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to get m.direct list to update it:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for userID, rooms := range existingChats {
|
|
|
|
if _, ok := user.bridge.ParsePuppetMXID(userID); !ok {
|
|
|
|
// This is not a ghost user, include it in the new list
|
|
|
|
chats[userID] = rooms
|
|
|
|
} else if _, ok := chats[userID]; !ok && method == http.MethodPatch {
|
|
|
|
// This is a ghost user, but we're not replacing the whole list, so include it too
|
|
|
|
chats[userID] = rooms
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err = intent.SetAccountData(event.AccountDataDirectChats.Type, &chats)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to update m.direct list:", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-24 23:25:29 +02:00
|
|
|
func (user *User) HandleContactList(contacts []whatsapp.Contact) {
|
2021-02-21 13:18:15 +01:00
|
|
|
contactMap := make(map[whatsapp.JID]whatsapp.Contact)
|
2019-08-24 23:25:29 +02:00
|
|
|
for _, contact := range contacts {
|
2021-02-18 22:36:14 +01:00
|
|
|
contactMap[contact.JID] = contact
|
2019-08-24 23:25:29 +02:00
|
|
|
}
|
|
|
|
go user.syncPuppets(contactMap)
|
|
|
|
}
|
|
|
|
|
2021-02-21 13:18:15 +01:00
|
|
|
func (user *User) syncPuppets(contacts map[whatsapp.JID]whatsapp.Contact) {
|
2019-08-24 23:25:29 +02:00
|
|
|
if contacts == nil {
|
|
|
|
contacts = user.Conn.Store.Contacts
|
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
|
|
|
|
_, hasSelf := contacts[user.JID]
|
|
|
|
if !hasSelf {
|
|
|
|
contacts[user.JID] = whatsapp.Contact{
|
|
|
|
Name: user.pushName,
|
|
|
|
Notify: user.pushName,
|
|
|
|
JID: user.JID,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Syncing puppet info from contacts")
|
2019-08-24 23:25:29 +02:00
|
|
|
for jid, contact := range contacts {
|
2021-02-17 00:21:30 +01:00
|
|
|
if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
|
2021-02-18 22:36:14 +01:00
|
|
|
puppet := user.bridge.GetPuppetByJID(contact.JID)
|
2019-05-22 15:46:18 +02:00
|
|
|
puppet.Sync(user, contact)
|
2021-02-21 13:18:15 +01:00
|
|
|
} else if strings.HasSuffix(jid, whatsapp.BroadcastSuffix) {
|
|
|
|
portal := user.GetPortalByJID(contact.JID)
|
|
|
|
portal.Sync(user, contact)
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
}
|
2019-05-31 19:51:16 +02:00
|
|
|
user.log.Infoln("Finished syncing puppet info from contacts")
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) updateLastConnectionIfNecessary() {
|
|
|
|
if user.LastConnection+60 < uint64(time.Now().Unix()) {
|
|
|
|
user.UpdateLastConnection()
|
|
|
|
}
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleError(err error) {
|
2020-09-24 14:25:36 +02:00
|
|
|
if !errors.Is(err, whatsapp.ErrInvalidWsData) {
|
2019-08-30 08:39:37 +02:00
|
|
|
user.log.Errorfln("WhatsApp error: %v", err)
|
2019-05-27 12:46:04 +02:00
|
|
|
}
|
2019-05-17 22:53:57 +02:00
|
|
|
if closed, ok := err.(*whatsapp.ErrConnectionClosed); ok {
|
2020-06-17 16:57:14 +02:00
|
|
|
user.bridge.Metrics.TrackDisconnection(user.MXID)
|
2019-07-04 14:08:58 +02:00
|
|
|
if closed.Code == 1000 && user.cleanDisconnection {
|
|
|
|
user.cleanDisconnection = false
|
2021-02-05 18:26:26 +01:00
|
|
|
if !user.bridge.Config.Bridge.AggressiveReconnect {
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2021-02-05 18:26:26 +01:00
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
|
|
|
user.log.Infoln("Clean disconnection by server")
|
|
|
|
return
|
|
|
|
} else {
|
|
|
|
user.log.Debugln("Clean disconnection by server, but aggressive reconnection is enabled")
|
|
|
|
}
|
2019-05-15 22:04:09 +02:00
|
|
|
}
|
2019-05-28 13:09:49 +02:00
|
|
|
go user.tryReconnect(fmt.Sprintf("Your WhatsApp connection was closed with websocket status code %d", closed.Code))
|
2019-05-17 22:53:57 +02:00
|
|
|
} else if failed, ok := err.(*whatsapp.ErrConnectionFailed); ok {
|
2021-02-25 12:49:28 +01:00
|
|
|
disconnectErr := user.Conn.Disconnect()
|
|
|
|
if disconnectErr != nil {
|
|
|
|
user.log.Warnln("Failed to disconnect after connection fail:", disconnectErr)
|
|
|
|
}
|
2020-06-17 16:57:14 +02:00
|
|
|
user.bridge.Metrics.TrackDisconnection(user.MXID)
|
2019-05-17 22:53:57 +02:00
|
|
|
user.ConnectionErrors++
|
2019-05-28 13:09:49 +02:00
|
|
|
go user.tryReconnect(fmt.Sprintf("Your WhatsApp connection failed: %v", failed.Err))
|
2021-02-23 16:36:38 +01:00
|
|
|
} else if err == whatsapp.ErrPingFalse {
|
2021-02-23 23:06:11 +01:00
|
|
|
disconnectErr := user.Conn.Disconnect()
|
|
|
|
if disconnectErr != nil {
|
|
|
|
user.log.Warnln("Failed to disconnect after failed ping:", disconnectErr)
|
|
|
|
}
|
2021-02-23 16:36:38 +01:00
|
|
|
user.bridge.Metrics.TrackDisconnection(user.MXID)
|
|
|
|
user.ConnectionErrors++
|
|
|
|
go user.tryReconnect(fmt.Sprintf("Your WhatsApp connection failed: %v", err))
|
2019-05-15 22:04:09 +02:00
|
|
|
}
|
2019-05-28 13:09:49 +02:00
|
|
|
// Otherwise unknown error, probably mostly harmless
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) tryReconnect(msg string) {
|
2020-09-27 21:30:08 +02:00
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
2019-05-17 22:53:57 +02:00
|
|
|
if user.ConnectionErrors > user.bridge.Config.Bridge.MaxConnectionAttempts {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendMarkdownBridgeAlert("%s. Use the `reconnect` command to reconnect.", msg)
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2019-05-17 22:53:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendBridgeNotice("%s. Reconnecting...", msg)
|
2019-05-17 22:53:57 +02:00
|
|
|
// Don't want the same error to be repeated
|
|
|
|
msg = ""
|
2019-05-16 00:56:33 +02:00
|
|
|
}
|
2019-05-28 13:09:49 +02:00
|
|
|
var tries uint
|
|
|
|
var exponentialBackoff bool
|
|
|
|
baseDelay := time.Duration(user.bridge.Config.Bridge.ConnectionRetryDelay)
|
|
|
|
if baseDelay < 0 {
|
|
|
|
exponentialBackoff = true
|
|
|
|
baseDelay = -baseDelay + 1
|
|
|
|
}
|
|
|
|
delay := baseDelay
|
2021-02-18 22:36:14 +01:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
user.cancelReconnect = cancel
|
2019-05-17 22:53:57 +02:00
|
|
|
for user.ConnectionErrors <= user.bridge.Config.Bridge.MaxConnectionAttempts {
|
2021-02-18 22:36:14 +01:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
user.log.Debugln("tryReconnect context cancelled, aborting reconnection attempts")
|
2021-02-05 18:26:09 +01:00
|
|
|
return
|
2021-02-18 22:36:14 +01:00
|
|
|
default:
|
2021-02-05 18:26:09 +01:00
|
|
|
}
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWAConnecting})
|
2021-02-23 23:13:26 +01:00
|
|
|
err := user.Conn.Restore(true, ctx)
|
2019-05-17 22:53:57 +02:00
|
|
|
if err == nil {
|
|
|
|
user.ConnectionErrors = 0
|
2020-05-29 20:06:25 +02:00
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendBridgeNotice("Reconnected successfully")
|
2020-05-29 20:06:25 +02:00
|
|
|
}
|
2019-05-30 16:48:22 +02:00
|
|
|
user.PostLogin()
|
2019-05-17 22:53:57 +02:00
|
|
|
return
|
2021-02-05 18:26:09 +01:00
|
|
|
} else if errors.Is(err, whatsapp.ErrBadRequest) {
|
2021-02-18 22:36:14 +01:00
|
|
|
user.log.Warnln("Got init 400 error when trying to reconnect, resetting connection...")
|
|
|
|
err = user.Conn.Disconnect()
|
2019-08-24 21:39:12 +02:00
|
|
|
if err != nil {
|
|
|
|
user.log.Debugln("Error while disconnecting for connection reset:", err)
|
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
} else if errors.Is(err, whatsapp.ErrUnpaired) {
|
|
|
|
user.log.Errorln("Got init 401 (unpaired) error when trying to reconnect, not retrying")
|
|
|
|
user.removeFromJIDMap()
|
|
|
|
//user.JID = ""
|
|
|
|
user.SetSession(nil)
|
|
|
|
user.DeleteConnection()
|
|
|
|
user.sendMarkdownBridgeAlert("\u26a0 Failed to reconnect to WhatsApp: unpaired from phone. " +
|
|
|
|
"To re-pair your phone, log in again.")
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotLoggedIn})
|
2021-02-18 22:36:14 +01:00
|
|
|
return
|
2021-02-23 23:06:11 +01:00
|
|
|
} else if errors.Is(err, whatsapp.ErrAlreadyLoggedIn) {
|
|
|
|
user.log.Warnln("Reconnection said we're already logged in, not trying anymore")
|
|
|
|
return
|
2021-02-18 22:36:14 +01:00
|
|
|
} else {
|
|
|
|
user.log.Errorln("Error while trying to reconnect after disconnection:", err)
|
2019-05-17 22:53:57 +02:00
|
|
|
}
|
|
|
|
tries++
|
|
|
|
user.ConnectionErrors++
|
|
|
|
if user.ConnectionErrors <= user.bridge.Config.Bridge.MaxConnectionAttempts {
|
2019-05-28 13:09:49 +02:00
|
|
|
if exponentialBackoff {
|
|
|
|
delay = (1 << tries) + baseDelay
|
|
|
|
}
|
2019-05-17 22:53:57 +02:00
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendBridgeNotice("Reconnection attempt failed: %v. Retrying in %d seconds...", err, delay)
|
2019-05-17 22:53:57 +02:00
|
|
|
}
|
2019-05-28 13:09:49 +02:00
|
|
|
time.Sleep(delay * time.Second)
|
2019-05-17 22:53:57 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-15 17:06:16 +01:00
|
|
|
user.sendBridgeStatus(AsmuxPong{Error: AsmuxWANotConnected})
|
2019-05-17 22:53:57 +02:00
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendMarkdownBridgeAlert("%d reconnection attempts failed. Use the `reconnect` command to try to reconnect manually.", tries)
|
2019-05-17 22:53:57 +02:00
|
|
|
} else {
|
2020-07-27 12:05:42 +02:00
|
|
|
user.sendMarkdownBridgeAlert("\u26a0 %s. Additionally, %d reconnection attempts failed. Use the `reconnect` command to try to reconnect.", msg, tries)
|
2019-05-17 22:53:57 +02:00
|
|
|
}
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) PortalKey(jid whatsapp.JID) database.PortalKey {
|
2018-08-28 23:40:54 +02:00
|
|
|
return database.NewPortalKey(jid, user.JID)
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) GetPortalByJID(jid whatsapp.JID) *Portal {
|
2018-08-28 23:40:54 +02:00
|
|
|
return user.bridge.GetPortalByJID(user.PortalKey(jid))
|
|
|
|
}
|
|
|
|
|
2020-11-06 14:52:16 +01:00
|
|
|
func (user *User) runMessageRingBuffer() {
|
|
|
|
for msg := range user.messageInput {
|
|
|
|
select {
|
|
|
|
case user.messageOutput <- msg:
|
2020-11-16 13:28:08 +01:00
|
|
|
user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput))
|
2020-11-06 14:52:16 +01:00
|
|
|
default:
|
2020-11-06 14:56:07 +01:00
|
|
|
dropped := <-user.messageOutput
|
|
|
|
user.log.Warnln("Buffer is full, dropping message in", dropped.chat)
|
2021-02-05 18:26:09 +01:00
|
|
|
user.messageOutput <- msg
|
2020-11-06 14:52:16 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-22 22:05:58 +02:00
|
|
|
func (user *User) handleMessageLoop() {
|
2020-07-23 19:10:21 +02:00
|
|
|
for {
|
|
|
|
select {
|
2020-11-06 14:52:16 +01:00
|
|
|
case msg := <-user.messageOutput:
|
2020-11-16 13:28:08 +01:00
|
|
|
user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput))
|
2020-07-23 19:10:21 +02:00
|
|
|
user.GetPortalByJID(msg.chat).messages <- msg
|
|
|
|
case <-user.syncStart:
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Processing of incoming messages is locked")
|
2020-11-06 01:38:31 +01:00
|
|
|
user.bridge.Metrics.TrackSyncLock(user.JID, true)
|
2020-07-23 19:10:21 +02:00
|
|
|
user.syncWait.Wait()
|
2020-11-06 01:38:31 +01:00
|
|
|
user.bridge.Metrics.TrackSyncLock(user.JID, false)
|
2020-11-06 01:29:14 +01:00
|
|
|
user.log.Debugln("Processing of incoming messages unlocked")
|
2020-07-23 19:10:21 +02:00
|
|
|
}
|
2019-05-22 22:05:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:44:51 +02:00
|
|
|
func (user *User) HandleNewContact(contact whatsapp.Contact) {
|
|
|
|
user.log.Debugfln("Contact message: %+v", contact)
|
2021-02-18 22:36:14 +01:00
|
|
|
if strings.HasSuffix(contact.JID, whatsapp.OldUserSuffix) {
|
|
|
|
contact.JID = strings.Replace(contact.JID, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, -1)
|
2021-02-17 00:21:30 +01:00
|
|
|
}
|
2021-02-21 13:18:15 +01:00
|
|
|
if strings.HasSuffix(contact.JID, whatsapp.NewUserSuffix) {
|
|
|
|
puppet := user.bridge.GetPuppetByJID(contact.JID)
|
|
|
|
puppet.UpdateName(user, contact)
|
|
|
|
} else if strings.HasSuffix(contact.JID, whatsapp.BroadcastSuffix) {
|
|
|
|
portal := user.GetPortalByJID(contact.JID)
|
|
|
|
portal.UpdateName(contact.Name, "", nil, true)
|
|
|
|
}
|
2020-06-25 15:44:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleBatteryMessage(battery whatsapp.BatteryMessage) {
|
|
|
|
user.log.Debugfln("Battery message: %+v", battery)
|
|
|
|
var notice string
|
|
|
|
if !battery.Plugged && battery.Percentage < 15 && user.batteryWarningsSent < 1 {
|
2020-07-04 15:21:41 +02:00
|
|
|
notice = fmt.Sprintf("Phone battery low (%d %% remaining)", battery.Percentage)
|
2020-06-25 15:44:51 +02:00
|
|
|
user.batteryWarningsSent = 1
|
2020-06-30 16:21:17 +02:00
|
|
|
} else if !battery.Plugged && battery.Percentage < 5 && user.batteryWarningsSent < 2 {
|
2020-07-04 15:21:41 +02:00
|
|
|
notice = fmt.Sprintf("Phone battery very low (%d %% remaining)", battery.Percentage)
|
2020-06-25 15:44:51 +02:00
|
|
|
user.batteryWarningsSent = 2
|
2020-06-30 16:21:17 +02:00
|
|
|
} else if battery.Percentage > 15 || battery.Plugged {
|
2020-06-25 15:44:51 +02:00
|
|
|
user.batteryWarningsSent = 0
|
|
|
|
}
|
|
|
|
if notice != "" {
|
2020-07-27 12:05:42 +02:00
|
|
|
go user.sendBridgeNotice("%s", notice)
|
2020-06-25 15:44:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-30 16:00:36 +02:00
|
|
|
type FakeMessage struct {
|
2020-05-21 19:14:43 +02:00
|
|
|
Text string
|
|
|
|
ID string
|
|
|
|
Alert bool
|
2019-05-30 16:00:36 +02:00
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleCallInfo(info whatsapp.CallInfo) {
|
2019-05-30 16:00:36 +02:00
|
|
|
if info.Data != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
data := FakeMessage{
|
|
|
|
ID: info.ID,
|
|
|
|
}
|
|
|
|
switch info.Type {
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.CallOffer:
|
2019-08-24 21:42:03 +02:00
|
|
|
if !user.bridge.Config.Bridge.CallNotices.Start {
|
|
|
|
return
|
|
|
|
}
|
2019-05-30 16:00:36 +02:00
|
|
|
data.Text = "Incoming call"
|
2020-05-21 19:14:43 +02:00
|
|
|
data.Alert = true
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.CallOfferVideo:
|
2019-08-24 21:42:03 +02:00
|
|
|
if !user.bridge.Config.Bridge.CallNotices.Start {
|
|
|
|
return
|
|
|
|
}
|
2019-05-30 16:00:36 +02:00
|
|
|
data.Text = "Incoming video call"
|
2020-05-21 19:14:43 +02:00
|
|
|
data.Alert = true
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.CallTerminate:
|
2019-08-24 21:42:03 +02:00
|
|
|
if !user.bridge.Config.Bridge.CallNotices.End {
|
|
|
|
return
|
|
|
|
}
|
2019-05-30 16:00:36 +02:00
|
|
|
data.Text = "Call ended"
|
|
|
|
data.ID += "E"
|
|
|
|
default:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
portal := user.GetPortalByJID(info.From)
|
|
|
|
if portal != nil {
|
|
|
|
portal.messages <- PortalMessage{info.From, user, data, 0}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandlePresence(info whatsapp.PresenceEvent) {
|
2018-08-28 23:40:54 +02:00
|
|
|
puppet := user.bridge.GetPuppetByJID(info.SenderJID)
|
2018-08-24 19:02:38 +02:00
|
|
|
switch info.Status {
|
2019-05-27 12:46:04 +02:00
|
|
|
case whatsapp.PresenceUnavailable:
|
2019-05-24 01:33:26 +02:00
|
|
|
_ = puppet.DefaultIntent().SetPresence("offline")
|
2019-05-27 12:46:04 +02:00
|
|
|
case whatsapp.PresenceAvailable:
|
2018-08-25 23:26:24 +02:00
|
|
|
if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
|
2019-05-24 01:33:26 +02:00
|
|
|
portal := user.bridge.GetPortalByMXID(puppet.typingIn)
|
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
|
2018-08-24 19:02:38 +02:00
|
|
|
puppet.typingIn = ""
|
2018-08-24 21:06:17 +02:00
|
|
|
puppet.typingAt = 0
|
2018-08-24 19:02:38 +02:00
|
|
|
} else {
|
2019-05-24 01:33:26 +02:00
|
|
|
_ = puppet.DefaultIntent().SetPresence("online")
|
2018-08-24 19:02:38 +02:00
|
|
|
}
|
2019-05-27 12:46:04 +02:00
|
|
|
case whatsapp.PresenceComposing:
|
2018-08-24 19:02:38 +02:00
|
|
|
portal := user.GetPortalByJID(info.JID)
|
2018-08-28 23:40:54 +02:00
|
|
|
if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
|
|
|
|
if puppet.typingIn == portal.MXID {
|
|
|
|
return
|
|
|
|
}
|
2019-05-24 01:33:26 +02:00
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
2018-08-24 19:02:38 +02:00
|
|
|
puppet.typingIn = portal.MXID
|
2018-08-24 21:06:17 +02:00
|
|
|
puppet.typingAt = time.Now().Unix()
|
2019-05-24 01:33:26 +02:00
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, true, 15*1000)
|
2018-08-24 19:02:38 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleMsgInfo(info whatsapp.JSONMsgInfo) {
|
|
|
|
if (info.Command == whatsapp.MsgInfoCommandAck || info.Command == whatsapp.MsgInfoCommandAcks) && info.Acknowledgement == whatsapp.AckMessageRead {
|
2018-08-24 18:46:14 +02:00
|
|
|
portal := user.GetPortalByJID(info.ToJID)
|
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
intent := user.bridge.GetPuppetByJID(info.SenderJID).IntentFor(portal)
|
|
|
|
for _, msgID := range info.IDs {
|
|
|
|
msg := user.bridge.DB.Message.GetByJID(portal.Key, msgID)
|
|
|
|
if msg == nil || msg.IsFakeMXID() {
|
|
|
|
continue
|
|
|
|
}
|
2019-05-21 22:44:14 +02:00
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
err := intent.MarkRead(portal.MXID, msg.MXID)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to mark message %s as read by %s: %v", msg.MXID, info.SenderJID, err)
|
2018-08-24 18:46:14 +02:00
|
|
|
}
|
2021-02-17 00:21:30 +01:00
|
|
|
}
|
2018-08-24 18:46:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-30 17:25:42 +02:00
|
|
|
func (user *User) HandleReceivedMessage(received whatsapp.ReceivedMessage) {
|
|
|
|
if received.Type == "read" {
|
2021-02-17 00:21:30 +01:00
|
|
|
go user.markSelfRead(received.Jid, received.Index)
|
2020-07-30 17:25:42 +02:00
|
|
|
} else {
|
|
|
|
user.log.Debugfln("Unknown received message type: %+v", received)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-30 17:08:26 +02:00
|
|
|
func (user *User) HandleReadMessage(read whatsapp.ReadMessage) {
|
2020-07-30 17:25:42 +02:00
|
|
|
user.log.Debugfln("Received chat read message: %+v", read)
|
2021-02-17 00:21:30 +01:00
|
|
|
go user.markSelfRead(read.Jid, "")
|
2020-07-30 17:25:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) markSelfRead(jid, messageID string) {
|
2021-02-17 00:21:30 +01:00
|
|
|
if strings.HasSuffix(jid, whatsapp.OldUserSuffix) {
|
|
|
|
jid = strings.Replace(jid, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, -1)
|
2020-07-30 17:08:26 +02:00
|
|
|
}
|
|
|
|
puppet := user.bridge.GetPuppetByJID(user.JID)
|
|
|
|
if puppet == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
intent := puppet.CustomIntent()
|
|
|
|
if intent == nil {
|
|
|
|
return
|
|
|
|
}
|
2020-07-30 17:25:42 +02:00
|
|
|
portal := user.GetPortalByJID(jid)
|
2020-07-30 17:08:26 +02:00
|
|
|
if portal == nil {
|
|
|
|
return
|
|
|
|
}
|
2020-07-30 17:25:42 +02:00
|
|
|
var message *database.Message
|
|
|
|
if messageID == "" {
|
|
|
|
message = user.bridge.DB.Message.GetLastInChat(portal.Key)
|
|
|
|
if message == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user.log.Debugfln("User read chat %s/%s in WhatsApp mobile (last known event: %s/%s)", portal.Key.JID, portal.MXID, message.JID, message.MXID)
|
|
|
|
} else {
|
|
|
|
message = user.bridge.DB.Message.GetByJID(portal.Key, messageID)
|
2021-02-09 22:41:14 +01:00
|
|
|
if message == nil || message.IsFakeMXID() {
|
2020-07-30 17:25:42 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
user.log.Debugfln("User read message %s/%s in %s/%s in WhatsApp mobile", message.JID, message.MXID, portal.Key.JID, portal.MXID)
|
2020-07-30 17:08:26 +02:00
|
|
|
}
|
|
|
|
err := intent.MarkRead(portal.MXID, message.MXID)
|
|
|
|
if err != nil {
|
2020-07-30 17:25:42 +02:00
|
|
|
user.log.Warnfln("Failed to bridge own read receipt in %s: %v", jid, err)
|
2020-07-30 17:08:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleCommand(cmd whatsapp.JSONCommand) {
|
2018-08-25 23:39:36 +02:00
|
|
|
switch cmd.Type {
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.CommandPicture:
|
|
|
|
if strings.HasSuffix(cmd.JID, whatsapp.NewUserSuffix) {
|
2018-08-28 23:40:54 +02:00
|
|
|
puppet := user.bridge.GetPuppetByJID(cmd.JID)
|
2019-05-21 22:44:14 +02:00
|
|
|
go puppet.UpdateAvatar(user, cmd.ProfilePicInfo)
|
2021-02-09 22:52:12 +01:00
|
|
|
} else if user.bridge.Config.Bridge.ChatMetaSync {
|
2018-08-26 00:55:21 +02:00
|
|
|
portal := user.GetPortalByJID(cmd.JID)
|
2020-06-15 13:56:52 +02:00
|
|
|
go portal.UpdateAvatar(user, cmd.ProfilePicInfo, true)
|
2018-08-26 00:55:21 +02:00
|
|
|
}
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.CommandDisconnect:
|
2019-05-15 22:04:09 +02:00
|
|
|
if cmd.Kind == "replaced" {
|
2021-02-05 18:26:26 +01:00
|
|
|
user.cleanDisconnection = true
|
2020-07-27 12:05:42 +02:00
|
|
|
go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server because you opened another WhatsApp Web client.\n\n" +
|
|
|
|
"Use the `reconnect` command to disconnect the other client and resume bridging.")
|
2019-05-15 22:04:09 +02:00
|
|
|
} else {
|
2019-05-16 17:00:46 +02:00
|
|
|
user.log.Warnln("Unknown kind of disconnect:", string(cmd.Raw))
|
2020-07-27 12:05:42 +02:00
|
|
|
go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server (reason code: %s).\n\n"+
|
2019-05-15 22:04:09 +02:00
|
|
|
"Use the `reconnect` command to reconnect.", cmd.Kind)
|
|
|
|
}
|
2018-08-26 00:55:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleChatUpdate(cmd whatsapp.ChatUpdate) {
|
|
|
|
if cmd.Command != whatsapp.ChatUpdateCommandAction {
|
2018-08-26 00:55:21 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
portal := user.GetPortalByJID(cmd.JID)
|
|
|
|
if len(portal.MXID) == 0 {
|
2021-02-17 00:21:30 +01:00
|
|
|
if cmd.Data.Action == whatsapp.ChatActionIntroduce || cmd.Data.Action == whatsapp.ChatActionCreate {
|
2020-06-25 22:58:35 +02:00
|
|
|
go func() {
|
|
|
|
err := portal.CreateMatrixRoom(user)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to create portal room after receiving join event:", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
2018-08-26 00:55:21 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-09 22:41:14 +01:00
|
|
|
// These don't come down the message history :(
|
2018-08-26 00:55:21 +02:00
|
|
|
switch cmd.Data.Action {
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionAddTopic:
|
|
|
|
go portal.UpdateTopic(cmd.Data.AddTopic.Topic, cmd.Data.SenderJID, nil, true)
|
|
|
|
case whatsapp.ChatActionRemoveTopic:
|
|
|
|
go portal.UpdateTopic("", cmd.Data.SenderJID, nil, true)
|
|
|
|
case whatsapp.ChatActionRemove:
|
2021-02-10 19:27:14 +01:00
|
|
|
// We ignore leaving groups in the message history to avoid accidentally leaving rejoined groups,
|
|
|
|
// but if we get a real-time command that says we left, it should be safe to bridge it.
|
|
|
|
if !user.bridge.Config.Bridge.ChatMetaSync {
|
|
|
|
for _, jid := range cmd.Data.UserChange.JIDs {
|
|
|
|
if jid == user.JID {
|
|
|
|
go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-02-09 22:41:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if !user.bridge.Config.Bridge.ChatMetaSync {
|
|
|
|
// Ignore chat update commands, we're relying on the message history.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch cmd.Data.Action {
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionNameChange:
|
2021-02-09 22:41:14 +01:00
|
|
|
go portal.UpdateName(cmd.Data.NameChange.Name, cmd.Data.SenderJID, nil, true)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionPromote:
|
2020-06-25 22:58:35 +02:00
|
|
|
go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, true)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionDemote:
|
2020-06-25 22:58:35 +02:00
|
|
|
go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, false)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionAnnounce:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.RestrictMessageSending(cmd.Data.Announce)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionRestrict:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.RestrictMetadataChanges(cmd.Data.Restrict)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionRemove:
|
2021-02-10 19:27:14 +01:00
|
|
|
go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionAdd:
|
2021-02-09 22:41:14 +01:00
|
|
|
go portal.HandleWhatsAppInvite(cmd.Data.SenderJID, nil, cmd.Data.UserChange.JIDs)
|
2021-02-17 00:21:30 +01:00
|
|
|
case whatsapp.ChatActionIntroduce:
|
2020-06-25 22:58:35 +02:00
|
|
|
if cmd.Data.SenderJID != "unknown" {
|
2021-02-18 22:36:14 +01:00
|
|
|
go portal.Sync(user, whatsapp.Contact{JID: portal.Key.JID})
|
2020-06-25 22:58:35 +02:00
|
|
|
}
|
2018-08-25 23:39:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-18 22:36:14 +01:00
|
|
|
func (user *User) HandleConnInfo(info whatsapp.ConnInfo) {
|
|
|
|
if user.Session != nil && info.Connected && len(info.ClientToken) > 0 {
|
|
|
|
user.log.Debugln("Received new tokens")
|
|
|
|
user.Session.ClientToken = info.ClientToken
|
|
|
|
user.Session.ServerToken = info.ServerToken
|
|
|
|
user.Session.Wid = info.WID
|
2021-02-19 19:39:50 +01:00
|
|
|
user.Update()
|
2021-02-18 22:36:14 +01:00
|
|
|
}
|
|
|
|
if len(info.PushName) > 0 {
|
|
|
|
user.pushName = info.PushName
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleJSONMessage(message json.RawMessage) {
|
|
|
|
if !json.Valid(message) {
|
2019-03-14 00:06:06 +01:00
|
|
|
return
|
|
|
|
}
|
2021-02-17 00:21:30 +01:00
|
|
|
user.log.Debugfln("JSON message: %s", message)
|
2019-05-22 15:46:18 +02:00
|
|
|
user.updateLastConnectionIfNecessary()
|
|
|
|
}
|
|
|
|
|
2019-11-10 20:22:11 +01:00
|
|
|
func (user *User) NeedsRelaybot(portal *Portal) bool {
|
2019-11-11 21:41:58 +01:00
|
|
|
return !user.HasSession() || !user.IsInPortal(portal.Key)
|
2019-11-10 20:22:11 +01:00
|
|
|
}
|