2018-08-13 22:24:44 +02:00
|
|
|
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
|
2021-10-22 19:14:34 +02:00
|
|
|
// Copyright (C) 2021 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-10-27 14:54:34 +02: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 22:05:58 +02:00
|
|
|
"sync"
|
2018-08-16 14:59:18 +02:00
|
|
|
"time"
|
2018-08-24 18:46:14 +02:00
|
|
|
|
2019-01-11 20:17:31 +01:00
|
|
|
log "maunium.net/go/maulogger/v2"
|
2021-05-18 14:23:19 +02:00
|
|
|
|
2021-10-26 16:01:10 +02:00
|
|
|
"go.mau.fi/whatsmeow/appstate"
|
|
|
|
waProto "go.mau.fi/whatsmeow/binary/proto"
|
2021-04-19 21:14:32 +02:00
|
|
|
"maunium.net/go/mautrix/appservice"
|
|
|
|
"maunium.net/go/mautrix/pushrules"
|
2019-01-11 20:17:31 +01:00
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
"go.mau.fi/whatsmeow"
|
|
|
|
"go.mau.fi/whatsmeow/store"
|
|
|
|
"go.mau.fi/whatsmeow/types"
|
|
|
|
"go.mau.fi/whatsmeow/types/events"
|
|
|
|
waLog "go.mau.fi/whatsmeow/util/log"
|
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-10-22 19:14:34 +02:00
|
|
|
Client *whatsmeow.Client
|
|
|
|
Session *store.Device
|
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
|
|
|
|
2021-10-28 13:03:55 +02:00
|
|
|
Admin bool
|
|
|
|
Whitelisted bool
|
|
|
|
RelayWhitelisted bool
|
2019-11-10 20:22:11 +01:00
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
mgmtCreateLock sync.Mutex
|
|
|
|
connLock sync.Mutex
|
2019-05-22 22:05:58 +02:00
|
|
|
|
2021-10-26 16:01:10 +02:00
|
|
|
historySyncs chan *events.HistorySync
|
|
|
|
|
2021-06-01 14:19:47 +02:00
|
|
|
prevBridgeStatus *BridgeState
|
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-10-22 19:14:34 +02:00
|
|
|
func (bridge *Bridge) GetUserByJID(jid types.JID) *User {
|
2018-08-28 23:40:54 +02:00
|
|
|
bridge.usersLock.Lock()
|
|
|
|
defer bridge.usersLock.Unlock()
|
2021-10-22 19:14:34 +02:00
|
|
|
user, ok := bridge.usersByUsername[jid.User]
|
2018-08-16 14:59:18 +02:00
|
|
|
if !ok {
|
2021-10-22 19:14:34 +02:00
|
|
|
return bridge.loadDBUser(bridge.DB.User.GetByUsername(jid.User), 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()
|
2021-10-22 19:14:34 +02:00
|
|
|
user.bridge.usersByUsername[user.JID.User] = user
|
2020-05-21 18:49:01 +02:00
|
|
|
user.bridge.usersLock.Unlock()
|
|
|
|
}
|
|
|
|
|
2021-08-04 15:14:26 +02:00
|
|
|
func (user *User) removeFromJIDMap(state BridgeStateEvent) {
|
2020-05-21 18:49:01 +02:00
|
|
|
user.bridge.usersLock.Lock()
|
2021-10-22 19:14:34 +02:00
|
|
|
jidUser, ok := user.bridge.usersByUsername[user.JID.User]
|
2020-10-04 12:55:09 +02:00
|
|
|
if ok && user == jidUser {
|
2021-10-22 19:14:34 +02:00
|
|
|
delete(user.bridge.usersByUsername, user.JID.User)
|
2020-10-04 12:55:09 +02:00
|
|
|
}
|
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-08-04 15:14:26 +02:00
|
|
|
user.sendBridgeState(BridgeState{StateEvent: state, Error: WANotLoggedIn})
|
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
|
2021-10-22 19:14:34 +02:00
|
|
|
if !user.JID.IsEmpty() {
|
|
|
|
var err error
|
|
|
|
user.Session, err = bridge.WAContainer.GetDevice(user.JID)
|
|
|
|
if err != nil {
|
2021-10-27 14:54:34 +02:00
|
|
|
user.log.Errorfln("Failed to load user's whatsapp session: %v", err)
|
2021-10-22 19:14:34 +02:00
|
|
|
} else if user.Session == nil {
|
|
|
|
user.log.Warnfln("Didn't find session data for %s, treating user as logged out", user.JID)
|
|
|
|
user.JID = types.EmptyJID
|
|
|
|
user.Update()
|
|
|
|
} else {
|
|
|
|
bridge.usersByUsername[user.JID.User] = user
|
|
|
|
}
|
2019-05-28 20:31:25 +02:00
|
|
|
}
|
|
|
|
if len(user.ManagementRoom) > 0 {
|
|
|
|
bridge.managementRooms[user.ManagementRoom] = user
|
|
|
|
}
|
|
|
|
return user
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
2021-10-26 16:01:10 +02:00
|
|
|
historySyncs: make(chan *events.HistorySync, 32),
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2021-10-28 13:03:55 +02:00
|
|
|
user.RelayWhitelisted = user.bridge.Config.Bridge.Permissions.IsRelayWhitelisted(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)
|
2021-10-26 16:01:10 +02:00
|
|
|
go func() {
|
|
|
|
for evt := range user.historySyncs {
|
|
|
|
if evt == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user.handleHistorySync(evt.Data)
|
|
|
|
}
|
|
|
|
}()
|
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
|
|
|
|
}
|
2021-11-01 10:17:44 +01:00
|
|
|
creationContent := make(map[string]interface{})
|
|
|
|
if !user.bridge.Config.Bridge.FederateRooms {
|
|
|
|
creationContent["m.federate"] = false
|
|
|
|
}
|
2020-05-27 11:16:05 +02:00
|
|
|
resp, err := user.bridge.Bot.CreateRoom(&mautrix.ReqCreateRoom{
|
2021-11-01 10:17:44 +01:00
|
|
|
Topic: "WhatsApp bridge notices",
|
|
|
|
IsDirect: true,
|
|
|
|
CreationContent: creationContent,
|
2020-05-27 11:16:05 +02:00
|
|
|
})
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
type waLogger struct{ l log.Logger }
|
|
|
|
|
|
|
|
func (w *waLogger) Debugf(msg string, args ...interface{}) { w.l.Debugfln(msg, args...) }
|
|
|
|
func (w *waLogger) Infof(msg string, args ...interface{}) { w.l.Infofln(msg, args...) }
|
|
|
|
func (w *waLogger) Warnf(msg string, args ...interface{}) { w.l.Warnfln(msg, args...) }
|
|
|
|
func (w *waLogger) Errorf(msg string, args ...interface{}) { w.l.Errorfln(msg, args...) }
|
|
|
|
func (w *waLogger) Sub(module string) waLog.Logger { return &waLogger{l: w.l.Sub(module)} }
|
2018-08-18 21:57:08 +02:00
|
|
|
|
2021-10-27 14:54:34 +02:00
|
|
|
var ErrAlreadyLoggedIn = errors.New("already logged in")
|
|
|
|
|
|
|
|
func (user *User) Login(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error) {
|
|
|
|
user.connLock.Lock()
|
|
|
|
defer user.connLock.Unlock()
|
|
|
|
if user.Session != nil {
|
|
|
|
return nil, ErrAlreadyLoggedIn
|
|
|
|
} else if user.Client != nil {
|
|
|
|
user.unlockedDeleteConnection()
|
|
|
|
}
|
|
|
|
newSession := user.bridge.WAContainer.NewDevice()
|
|
|
|
newSession.Log = &waLogger{user.log.Sub("Session")}
|
|
|
|
user.Client = whatsmeow.NewClient(newSession, &waLogger{user.log.Sub("Client")})
|
2021-10-29 15:50:29 +02:00
|
|
|
user.Client.AddEventHandler(user.HandleEvent)
|
2021-10-27 14:54:34 +02:00
|
|
|
qrChan, err := user.Client.GetQRChannel(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to get QR channel: %w", err)
|
|
|
|
}
|
|
|
|
err = user.Client.Connect()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to connect to WhatsApp: %w", err)
|
|
|
|
}
|
|
|
|
return qrChan, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) Connect() bool {
|
2021-02-05 18:26:09 +01:00
|
|
|
user.connLock.Lock()
|
2021-10-22 19:14:34 +02:00
|
|
|
defer user.connLock.Unlock()
|
|
|
|
if user.Client != nil {
|
|
|
|
return user.Client.IsConnected()
|
2021-10-27 14:54:34 +02:00
|
|
|
} else if user.Session == nil {
|
2018-08-18 21:57:08 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
user.log.Debugln("Connecting to WhatsApp")
|
2021-10-27 14:54:34 +02:00
|
|
|
user.sendBridgeState(BridgeState{StateEvent: StateConnecting, Error: WAConnecting})
|
|
|
|
user.Client = whatsmeow.NewClient(user.Session, &waLogger{user.log.Sub("Client")})
|
2021-10-22 19:14:34 +02:00
|
|
|
user.Client.AddEventHandler(user.HandleEvent)
|
|
|
|
err := user.Client.Connect()
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Error connecting to WhatsApp:", err)
|
|
|
|
return false
|
2019-05-16 17:08:30 +02:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
return true
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2021-10-27 14:54:34 +02:00
|
|
|
func (user *User) unlockedDeleteConnection() {
|
2021-10-22 19:14:34 +02:00
|
|
|
if user.Client == nil {
|
2021-02-18 22:36:14 +01:00
|
|
|
return
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
user.Client.Disconnect()
|
|
|
|
user.Client.RemoveEventHandlers()
|
|
|
|
user.Client = nil
|
2021-02-05 18:26:09 +01:00
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
2021-10-27 14:54:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) DeleteConnection() {
|
|
|
|
user.connLock.Lock()
|
|
|
|
defer user.connLock.Unlock()
|
|
|
|
user.unlockedDeleteConnection()
|
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
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) DeleteSession() {
|
|
|
|
if user.Session != nil {
|
|
|
|
err := user.Session.Delete()
|
2018-08-16 14:59:18 +02:00
|
|
|
if err != nil {
|
2021-10-22 19:14:34 +02:00
|
|
|
user.log.Warnln("Failed to delete session:", err)
|
2019-01-21 22:55:16 +01:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
user.Session = nil
|
2019-07-17 23:14:04 +02:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
if !user.JID.IsEmpty() {
|
|
|
|
user.JID = types.EmptyJID
|
|
|
|
user.Update()
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
2021-10-27 14:54:34 +02:00
|
|
|
func (user *User) IsConnected() bool {
|
|
|
|
return user.Client != nil && user.Client.IsConnected()
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) IsLoggedIn() bool {
|
2021-10-27 14:54:34 +02:00
|
|
|
return user.IsConnected() && user.Client.IsLoggedIn
|
2019-05-22 15:46:18 +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-11-01 14:30:56 +01:00
|
|
|
func containsSupportedMessages(conv *waProto.Conversation) bool {
|
|
|
|
for _, msg := range conv.GetMessages() {
|
|
|
|
if containsSupportedMessage(msg.GetMessage().GetMessage()) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-11-02 13:06:21 +01:00
|
|
|
type portalToBackfill struct {
|
|
|
|
portal *Portal
|
2021-11-02 14:46:31 +01:00
|
|
|
conv *waProto.Conversation
|
2021-11-02 13:06:21 +01:00
|
|
|
}
|
|
|
|
|
2021-10-26 16:01:10 +02:00
|
|
|
func (user *User) handleHistorySync(evt *waProto.HistorySync) {
|
|
|
|
if evt.GetSyncType() != waProto.HistorySync_RECENT && evt.GetSyncType() != waProto.HistorySync_FULL {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user.log.Infofln("Handling history sync with type %s, chunk order %d, progress %d%%", evt.GetSyncType(), evt.GetChunkOrder(), evt.GetProgress())
|
2021-10-30 20:54:35 +02:00
|
|
|
maxAge := user.bridge.Config.Bridge.HistorySync.MaxAge
|
|
|
|
minLastMsgToCreate := time.Now().Add(-time.Duration(maxAge) * time.Second)
|
|
|
|
createRooms := user.bridge.Config.Bridge.HistorySync.CreatePortals
|
2021-11-02 13:06:21 +01:00
|
|
|
portalsToBackfill := make([]portalToBackfill, 0)
|
2021-10-26 16:01:10 +02:00
|
|
|
for _, conv := range evt.GetConversations() {
|
|
|
|
jid, err := types.ParseJID(conv.GetId())
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-10-28 11:59:22 +02:00
|
|
|
muteEnd := time.Unix(int64(conv.GetMuteEndTime()), 0)
|
|
|
|
if muteEnd.After(time.Now()) {
|
|
|
|
_ = user.Client.Store.ChatSettings.PutMutedUntil(jid, muteEnd)
|
|
|
|
}
|
|
|
|
if conv.GetArchived() {
|
|
|
|
_ = user.Client.Store.ChatSettings.PutArchived(jid, true)
|
|
|
|
}
|
|
|
|
if conv.GetPinned() > 0 {
|
|
|
|
_ = user.Client.Store.ChatSettings.PutPinned(jid, true)
|
|
|
|
}
|
|
|
|
|
2021-10-30 20:54:35 +02:00
|
|
|
lastMsg := time.Unix(int64(conv.GetConversationTimestamp()), 0)
|
2021-10-26 16:01:10 +02:00
|
|
|
portal := user.GetPortalByJID(jid)
|
2021-10-30 20:54:35 +02:00
|
|
|
if createRooms && len(portal.MXID) == 0 {
|
2021-11-01 14:30:56 +01:00
|
|
|
if !containsSupportedMessages(conv) {
|
|
|
|
user.log.Debugfln("Not creating portal for %s: no interesting messages found", portal.Key.JID)
|
|
|
|
continue
|
|
|
|
} else if maxAge > 0 && !lastMsg.After(minLastMsgToCreate) {
|
2021-10-30 20:54:35 +02:00
|
|
|
user.log.Debugfln("Not creating portal for %s: last message older than limit (%s)", portal.Key.JID, lastMsg)
|
|
|
|
continue
|
|
|
|
}
|
2021-10-29 21:07:40 +02:00
|
|
|
user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
|
2021-10-31 18:59:23 +01:00
|
|
|
err = portal.CreateMatrixRoom(user, nil)
|
2021-10-28 11:59:22 +02:00
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
2021-10-29 21:07:40 +02:00
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
user.log.Debugln("No room created, not bridging history sync payload for", portal.Key.JID)
|
|
|
|
} else if !user.bridge.Config.Bridge.HistorySync.Backfill {
|
|
|
|
user.log.Debugln("Backfill is disabled, not bridging history sync payload for", portal.Key.JID)
|
|
|
|
} else {
|
2021-11-02 13:06:21 +01:00
|
|
|
portalsToBackfill = append(portalsToBackfill, portalToBackfill{portal, conv})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, ptb := range portalsToBackfill {
|
|
|
|
user.log.Debugln("Bridging history sync payload for", ptb.portal.Key.JID)
|
|
|
|
ptb.portal.backfill(user, ptb.conv.GetMessages())
|
|
|
|
if !ptb.conv.GetMarkedAsUnread() && ptb.conv.GetUnreadCount() == 0 {
|
|
|
|
user.markSelfReadFull(ptb.portal)
|
2021-10-26 16:01:10 +02:00
|
|
|
}
|
|
|
|
}
|
2021-11-02 13:06:21 +01:00
|
|
|
user.log.Infofln("Finished handling history sync with type %s, chunk order %d, progress %d%%", evt.GetSyncType(), evt.GetChunkOrder(), evt.GetProgress())
|
2021-10-26 16:01:10 +02:00
|
|
|
}
|
|
|
|
|
2021-11-02 14:46:31 +01:00
|
|
|
func (user *User) handleCallStart(sender types.JID, id, callType string) {
|
|
|
|
if !user.bridge.Config.Bridge.CallStartNotices {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
portal := user.GetPortalByJID(sender)
|
|
|
|
text := "Incoming call"
|
|
|
|
if callType != "" {
|
2021-11-02 14:52:12 +01:00
|
|
|
text = fmt.Sprintf("Incoming %s call", callType)
|
2021-11-02 14:46:31 +01:00
|
|
|
}
|
|
|
|
portal.messages <- PortalMessage{
|
|
|
|
fake: &fakeMessage{
|
|
|
|
Sender: sender,
|
|
|
|
Text: text,
|
|
|
|
ID: id,
|
|
|
|
},
|
|
|
|
source: user,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
func (user *User) HandleEvent(event interface{}) {
|
|
|
|
switch v := event.(type) {
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.LoggedOut:
|
2021-10-29 15:50:29 +02:00
|
|
|
go user.handleLoggedOut(v.OnConnect)
|
2021-10-22 19:14:34 +02:00
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
|
|
|
user.bridge.Metrics.TrackLoginState(user.JID, false)
|
|
|
|
case *events.Connected:
|
|
|
|
go user.sendBridgeState(BridgeState{StateEvent: StateConnected})
|
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, true)
|
|
|
|
user.bridge.Metrics.TrackLoginState(user.JID, true)
|
|
|
|
go func() {
|
|
|
|
err := user.Client.SendPresence(types.PresenceUnavailable)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to send initial presence:", err)
|
|
|
|
}
|
|
|
|
}()
|
2021-10-25 17:31:37 +02:00
|
|
|
go user.tryAutomaticDoublePuppeting()
|
2021-10-26 16:01:10 +02:00
|
|
|
case *events.AppStateSyncComplete:
|
|
|
|
if len(user.Client.Store.PushName) > 0 && v.Name == appstate.WAPatchCriticalBlock {
|
|
|
|
err := user.Client.SendPresence(types.PresenceUnavailable)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to send presence after app state sync:", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case *events.PushNameSetting:
|
|
|
|
// Send presence available when connecting and when the pushname is changed.
|
|
|
|
// This makes sure that outgoing messages always have the right pushname.
|
|
|
|
err := user.Client.SendPresence(types.PresenceUnavailable)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Failed to send presence after push name update:", err)
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.PairSuccess:
|
2021-10-29 15:50:29 +02:00
|
|
|
user.Session = user.Client.Store
|
2021-10-22 19:14:34 +02:00
|
|
|
user.JID = v.ID
|
|
|
|
user.addToJIDMap()
|
|
|
|
user.Update()
|
|
|
|
case *events.ConnectFailure, *events.StreamError:
|
|
|
|
go user.sendBridgeState(BridgeState{StateEvent: StateUnknownError})
|
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
|
|
|
case *events.Disconnected:
|
|
|
|
go user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect})
|
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
|
|
|
case *events.Contact:
|
|
|
|
go user.syncPuppet(v.JID)
|
|
|
|
case *events.PushName:
|
|
|
|
go user.syncPuppet(v.JID)
|
2021-10-28 11:59:22 +02:00
|
|
|
case *events.GroupInfo:
|
|
|
|
go user.handleGroupUpdate(v)
|
2021-10-31 18:59:23 +01:00
|
|
|
case *events.JoinedGroup:
|
|
|
|
go user.handleGroupCreate(v)
|
2021-10-28 11:59:22 +02:00
|
|
|
case *events.Picture:
|
|
|
|
go user.handlePictureUpdate(v)
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.Receipt:
|
|
|
|
go user.handleReceipt(v)
|
2021-10-27 18:30:34 +02:00
|
|
|
case *events.ChatPresence:
|
|
|
|
go user.handleChatPresence(v)
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.Message:
|
|
|
|
portal := user.GetPortalByJID(v.Info.Chat)
|
2021-10-27 17:31:33 +02:00
|
|
|
portal.messages <- PortalMessage{evt: v, source: user}
|
2021-11-02 14:46:31 +01:00
|
|
|
case *events.CallOffer:
|
|
|
|
user.handleCallStart(v.CallCreator, v.CallID, "")
|
|
|
|
case *events.CallOfferNotice:
|
|
|
|
user.handleCallStart(v.CallCreator, v.CallID, v.Type)
|
|
|
|
case *events.CallTerminate, *events.CallRelayLatency, *events.CallAccept, *events.UnknownCallEvent:
|
|
|
|
// ignore
|
2021-10-27 17:31:33 +02:00
|
|
|
case *events.UndecryptableMessage:
|
|
|
|
portal := user.GetPortalByJID(v.Info.Chat)
|
|
|
|
portal.messages <- PortalMessage{undecryptable: v, source: user}
|
2021-10-26 16:01:10 +02:00
|
|
|
case *events.HistorySync:
|
|
|
|
user.historySyncs <- v
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.Mute:
|
2021-10-29 15:50:29 +02:00
|
|
|
portal := user.GetPortalByJID(v.JID)
|
2021-04-19 21:14:32 +02:00
|
|
|
if portal != nil {
|
2021-10-22 19:14:34 +02:00
|
|
|
var mutedUntil time.Time
|
|
|
|
if v.Action.GetMuted() {
|
|
|
|
mutedUntil = time.Unix(v.Action.GetMuteEndTimestamp(), 0)
|
|
|
|
}
|
|
|
|
go user.updateChatMute(nil, portal, mutedUntil)
|
2021-04-19 21:14:32 +02:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.Archive:
|
2021-10-29 15:50:29 +02:00
|
|
|
portal := user.GetPortalByJID(v.JID)
|
2021-04-19 21:14:32 +02:00
|
|
|
if portal != nil {
|
2021-10-22 19:14:34 +02:00
|
|
|
go user.updateChatTag(nil, portal, user.bridge.Config.Bridge.ArchiveTag, v.Action.GetArchived())
|
2021-04-20 15:32:23 +02:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
case *events.Pin:
|
2021-10-29 15:50:29 +02:00
|
|
|
portal := user.GetPortalByJID(v.JID)
|
2021-04-20 15:32:23 +02:00
|
|
|
if portal != nil {
|
2021-10-22 19:14:34 +02:00
|
|
|
go user.updateChatTag(nil, portal, user.bridge.Config.Bridge.PinnedTag, v.Action.GetPinned())
|
2021-04-19 21:14:32 +02:00
|
|
|
}
|
2021-10-27 17:31:33 +02:00
|
|
|
case *events.AppState:
|
|
|
|
// Ignore
|
2021-02-17 00:21:30 +01:00
|
|
|
default:
|
|
|
|
user.log.Debugfln("Unknown type of event in HandleEvent: %T", v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) updateChatMute(intent *appservice.IntentAPI, portal *Portal, mutedUntil time.Time) {
|
2021-04-19 21:14:32 +02:00
|
|
|
if len(portal.MXID) == 0 || !user.bridge.Config.Bridge.MuteBridging {
|
|
|
|
return
|
|
|
|
} else if intent == nil {
|
|
|
|
doublePuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if doublePuppet == nil || doublePuppet.CustomIntent() == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
intent = doublePuppet.CustomIntent()
|
|
|
|
}
|
|
|
|
var err error
|
2021-10-22 19:14:34 +02:00
|
|
|
if mutedUntil.IsZero() && mutedUntil.Before(time.Now()) {
|
2021-05-04 12:50:35 +02:00
|
|
|
user.log.Debugfln("Portal %s is muted until %d, unmuting...", portal.MXID, mutedUntil)
|
2021-04-19 21:14:32 +02:00
|
|
|
err = intent.DeletePushRule("global", pushrules.RoomRule, string(portal.MXID))
|
|
|
|
} else {
|
2021-05-04 12:50:35 +02:00
|
|
|
user.log.Debugfln("Portal %s is muted until %d, muting...", portal.MXID, mutedUntil)
|
2021-04-19 21:14:32 +02:00
|
|
|
err = intent.PutPushRule("global", pushrules.RoomRule, string(portal.MXID), &mautrix.ReqPutPushRule{
|
|
|
|
Actions: []pushrules.PushActionType{pushrules.ActionDontNotify},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if err != nil && !errors.Is(err, mautrix.MNotFound) {
|
|
|
|
user.log.Warnfln("Failed to update push rule for %s through double puppet: %v", portal.MXID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-20 15:32:23 +02:00
|
|
|
type CustomTagData struct {
|
|
|
|
Order json.Number `json:"order"`
|
|
|
|
DoublePuppet bool `json:"net.maunium.whatsapp.puppet"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type CustomTagEventContent struct {
|
|
|
|
Tags map[string]CustomTagData `json:"tags"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) updateChatTag(intent *appservice.IntentAPI, portal *Portal, tag string, active bool) {
|
|
|
|
if len(portal.MXID) == 0 || len(tag) == 0 {
|
2021-04-19 21:14:32 +02:00
|
|
|
return
|
|
|
|
} else if intent == nil {
|
|
|
|
doublePuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if doublePuppet == nil || doublePuppet.CustomIntent() == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
intent = doublePuppet.CustomIntent()
|
|
|
|
}
|
2021-04-20 15:32:23 +02:00
|
|
|
var existingTags CustomTagEventContent
|
|
|
|
err := intent.GetTagsWithCustomData(portal.MXID, &existingTags)
|
|
|
|
if err != nil && !errors.Is(err, mautrix.MNotFound) {
|
|
|
|
user.log.Warnfln("Failed to get tags of %s: %v", portal.MXID, err)
|
|
|
|
}
|
|
|
|
currentTag, ok := existingTags.Tags[tag]
|
|
|
|
if active && !ok {
|
|
|
|
user.log.Debugln("Adding tag", tag, "to", portal.MXID)
|
|
|
|
data := CustomTagData{"0.5", true}
|
|
|
|
err = intent.AddTagWithCustomData(portal.MXID, tag, &data)
|
|
|
|
} else if !active && ok && currentTag.DoublePuppet {
|
|
|
|
user.log.Debugln("Removing tag", tag, "from", portal.MXID)
|
|
|
|
err = intent.RemoveTag(portal.MXID, tag)
|
2021-04-19 21:14:32 +02:00
|
|
|
} else {
|
2021-04-20 15:32:23 +02:00
|
|
|
err = nil
|
2021-04-19 21:14:32 +02:00
|
|
|
}
|
|
|
|
if err != nil {
|
2021-04-20 15:32:23 +02:00
|
|
|
user.log.Warnfln("Failed to update tag %s for %s through double puppet: %v", tag, portal.MXID, err)
|
2021-04-19 21:14:32 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-18 14:23:19 +02:00
|
|
|
type CustomReadReceipt struct {
|
|
|
|
Timestamp int64 `json:"ts,omitempty"`
|
|
|
|
DoublePuppet bool `json:"net.maunium.whatsapp.puppet,omitempty"`
|
|
|
|
}
|
|
|
|
|
2021-10-28 11:59:22 +02:00
|
|
|
func (user *User) syncChatDoublePuppetDetails(portal *Portal, justCreated bool) {
|
|
|
|
doublePuppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if doublePuppet == nil {
|
|
|
|
return
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
if doublePuppet == nil || doublePuppet.CustomIntent() == nil || len(portal.MXID) == 0 {
|
2021-04-19 21:14:32 +02:00
|
|
|
return
|
|
|
|
}
|
2021-04-29 10:57:05 +02:00
|
|
|
if justCreated || !user.bridge.Config.Bridge.TagOnlyOnCreate {
|
2021-10-22 19:14:34 +02:00
|
|
|
chat, err := user.Client.Store.ChatSettings.GetChatSettings(portal.Key.JID)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Failed to get settings of %s: %v", portal.Key.JID, err)
|
2021-06-01 14:28:15 +02:00
|
|
|
return
|
|
|
|
}
|
2021-10-28 11:59:22 +02:00
|
|
|
intent := doublePuppet.CustomIntent()
|
2021-10-22 19:14:34 +02:00
|
|
|
user.updateChatMute(intent, portal, chat.MutedUntil)
|
|
|
|
user.updateChatTag(intent, portal, user.bridge.Config.Bridge.ArchiveTag, chat.Archived)
|
|
|
|
user.updateChatTag(intent, portal, user.bridge.Config.Bridge.PinnedTag, chat.Pinned)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-22 12:07:55 +02:00
|
|
|
func (user *User) getDirectChats() map[id.UserID][]id.RoomID {
|
|
|
|
res := make(map[id.UserID][]id.RoomID)
|
2021-10-22 19:14:34 +02:00
|
|
|
privateChats := user.bridge.DB.Portal.FindPrivateChats(user.JID.ToNonAD())
|
2020-08-22 12:07:55 +02:00
|
|
|
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 {
|
2021-03-15 21:05:26 +01:00
|
|
|
urlPath := intent.BuildBaseURL("_matrix", "client", "unstable", "com.beeper.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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-29 15:50:29 +02:00
|
|
|
func (user *User) handleLoggedOut(onConnect bool) {
|
2021-10-22 19:14:34 +02:00
|
|
|
user.JID = types.EmptyJID
|
|
|
|
user.Update()
|
2021-10-29 15:50:29 +02:00
|
|
|
if onConnect {
|
|
|
|
user.sendMarkdownBridgeAlert("Connecting to WhatsApp failed as the device was logged out. Please link the bridge to your phone again.")
|
|
|
|
} else {
|
|
|
|
user.sendMarkdownBridgeAlert("You were logged out from another device. Please link the bridge to your phone again.")
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotLoggedIn})
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) GetPortalByJID(jid types.JID) *Portal {
|
2021-10-29 15:50:29 +02:00
|
|
|
return user.bridge.GetPortalByJID(database.NewPortalKey(jid, user.JID))
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) syncPuppet(jid types.JID) {
|
|
|
|
user.bridge.GetPuppetByJID(jid).SyncContact(user, false)
|
|
|
|
}
|
|
|
|
|
2021-10-27 18:30:34 +02:00
|
|
|
const WATypingTimeout = 15 * time.Second
|
|
|
|
|
|
|
|
func (user *User) handleChatPresence(presence *events.ChatPresence) {
|
|
|
|
puppet := user.bridge.GetPuppetByJID(presence.Sender)
|
|
|
|
portal := user.GetPortalByJID(presence.Chat)
|
|
|
|
if puppet == nil || portal == nil || len(portal.MXID) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if presence.State == types.ChatPresenceComposing {
|
|
|
|
if puppet.typingIn != "" && puppet.typingAt.Add(WATypingTimeout).Before(time.Now()) {
|
|
|
|
if puppet.typingIn == portal.MXID {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
|
|
|
|
}
|
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, true, WATypingTimeout.Milliseconds())
|
|
|
|
puppet.typingIn = portal.MXID
|
|
|
|
puppet.typingAt = time.Now()
|
|
|
|
} else {
|
|
|
|
_, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, false, 0)
|
|
|
|
puppet.typingIn = ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) handleReceipt(receipt *events.Receipt) {
|
|
|
|
if receipt.Type != events.ReceiptTypeRead {
|
2019-05-30 16:00:36 +02:00
|
|
|
return
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
portal := user.GetPortalByJID(receipt.Chat)
|
|
|
|
if portal == nil || len(portal.MXID) == 0 {
|
2019-05-30 16:00:36 +02:00
|
|
|
return
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
if receipt.IsFromMe {
|
|
|
|
user.markSelfRead(portal, receipt.MessageID)
|
|
|
|
} else {
|
|
|
|
intent := user.bridge.GetPuppetByJID(receipt.Sender).IntentFor(portal)
|
|
|
|
ok := user.markOtherRead(portal, intent, receipt.MessageID)
|
|
|
|
if !ok {
|
|
|
|
// Message not found, try any previous IDs
|
|
|
|
for i := len(receipt.PreviousIDs) - 1; i >= 0; i-- {
|
|
|
|
ok = user.markOtherRead(portal, intent, receipt.PreviousIDs[i])
|
|
|
|
if ok {
|
|
|
|
break
|
|
|
|
}
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
2021-08-18 14:52:50 +02:00
|
|
|
}
|
2018-08-24 19:02:38 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) markOtherRead(portal *Portal, intent *appservice.IntentAPI, messageID types.MessageID) bool {
|
|
|
|
msg := user.bridge.DB.Message.GetByJID(portal.Key, messageID)
|
|
|
|
if msg == nil || msg.IsFakeMXID() {
|
|
|
|
return false
|
2018-08-24 18:46:14 +02:00
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
err := intent.MarkReadWithContent(portal.MXID, msg.MXID, &CustomReadReceipt{DoublePuppet: intent.IsCustomPuppet})
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Failed to mark message %s as read by %s: %v", msg.MXID, intent.UserID, err)
|
2020-07-30 17:25:42 +02:00
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
return true
|
2020-07-30 17:25:42 +02:00
|
|
|
}
|
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
func (user *User) markSelfRead(portal *Portal, messageID types.MessageID) {
|
2021-10-28 11:59:22 +02:00
|
|
|
puppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if puppet == nil || puppet.CustomIntent() == nil {
|
2020-07-30 17:08:26 +02:00
|
|
|
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
|
|
|
}
|
2021-10-28 11:59:22 +02:00
|
|
|
err := puppet.CustomIntent().MarkReadWithContent(portal.MXID, message.MXID, &CustomReadReceipt{DoublePuppet: true})
|
2020-07-30 17:08:26 +02:00
|
|
|
if err != nil {
|
2021-10-22 19:14:34 +02:00
|
|
|
user.log.Warnfln("Failed to bridge own read receipt in %s: %v", portal.Key.JID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-28 11:59:22 +02:00
|
|
|
func (user *User) markSelfReadFull(portal *Portal) {
|
|
|
|
puppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
|
|
|
|
if puppet == nil || puppet.CustomIntent() == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
lastMessage := user.bridge.DB.Message.GetLastInChat(portal.Key)
|
|
|
|
if lastMessage == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err := puppet.CustomIntent().MarkReadWithContent(portal.MXID, lastMessage.MXID, &CustomReadReceipt{DoublePuppet: true})
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Failed to mark %s in %s as read after backfill: %v", lastMessage.MXID, portal.MXID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-31 18:59:23 +01:00
|
|
|
func (user *User) handleGroupCreate(evt *events.JoinedGroup) {
|
|
|
|
portal := user.GetPortalByJID(evt.JID)
|
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
err := portal.CreateMatrixRoom(user, &evt.GroupInfo)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to create Matrix room after join notification: %v", err)
|
|
|
|
}
|
|
|
|
} else {
|
2021-11-01 10:28:52 +01:00
|
|
|
portal.UpdateMatrixRoom(user, &evt.GroupInfo)
|
2021-10-31 18:59:23 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-28 11:59:22 +02:00
|
|
|
func (user *User) handleGroupUpdate(evt *events.GroupInfo) {
|
|
|
|
portal := user.GetPortalByJID(evt.JID)
|
|
|
|
if portal == nil || len(portal.MXID) == 0 {
|
|
|
|
user.log.Debugfln("Ignoring group info update in chat with no portal: %+v", evt)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
switch {
|
|
|
|
case evt.Announce != nil:
|
|
|
|
portal.RestrictMessageSending(evt.Announce.IsAnnounce)
|
|
|
|
case evt.Locked != nil:
|
|
|
|
portal.RestrictMetadataChanges(evt.Locked.IsLocked)
|
|
|
|
case evt.Name != nil:
|
|
|
|
portal.UpdateName(evt.Name.Name, evt.Name.NameSetBy, true)
|
|
|
|
case evt.Topic != nil:
|
|
|
|
portal.UpdateTopic(evt.Topic.Topic, evt.Topic.TopicSetBy, true)
|
|
|
|
case evt.Leave != nil:
|
|
|
|
if evt.Sender != nil && !evt.Sender.IsEmpty() {
|
|
|
|
portal.HandleWhatsAppKick(user, *evt.Sender, evt.Leave)
|
|
|
|
}
|
|
|
|
case evt.Join != nil:
|
|
|
|
portal.HandleWhatsAppInvite(user, evt.Sender, evt.Join)
|
|
|
|
case evt.Promote != nil:
|
|
|
|
portal.ChangeAdminStatus(evt.Promote, true)
|
|
|
|
case evt.Demote != nil:
|
|
|
|
portal.ChangeAdminStatus(evt.Demote, false)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) handlePictureUpdate(evt *events.Picture) {
|
|
|
|
if evt.JID.Server == types.DefaultUserServer {
|
|
|
|
puppet := user.bridge.GetPuppetByJID(evt.JID)
|
|
|
|
if puppet.Avatar != evt.PictureID {
|
|
|
|
puppet.UpdateAvatar(user)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
portal := user.GetPortalByJID(evt.JID)
|
|
|
|
if portal != nil && portal.Avatar != evt.PictureID {
|
|
|
|
portal.UpdateAvatar(user, evt.Author, true)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|