2018-08-13 22:24:44 +02:00
|
|
|
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
|
2019-01-12 14:54:04 +01:00
|
|
|
// Copyright (C) 2019 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 (
|
2019-03-14 00:06:06 +01:00
|
|
|
"encoding/json"
|
2019-05-15 22:04:09 +02:00
|
|
|
"fmt"
|
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
|
|
|
|
2019-05-27 13:15:45 +02:00
|
|
|
"github.com/pkg/errors"
|
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-15 22:04:09 +02:00
|
|
|
"maunium.net/go/mautrix"
|
|
|
|
"maunium.net/go/mautrix/format"
|
|
|
|
|
2019-05-21 22:44:14 +02:00
|
|
|
"github.com/Rhymen/go-whatsapp"
|
2019-05-22 15:46:18 +02:00
|
|
|
waProto "github.com/Rhymen/go-whatsapp/binary/proto"
|
2019-05-21 22:44:14 +02:00
|
|
|
|
2018-08-24 18:46:14 +02:00
|
|
|
"maunium.net/go/mautrix-whatsapp/database"
|
2018-08-16 23:11:28 +02:00
|
|
|
"maunium.net/go/mautrix-whatsapp/types"
|
2018-08-23 00:12:26 +02:00
|
|
|
"maunium.net/go/mautrix-whatsapp/whatsapp-ext"
|
2018-08-16 14:59:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type User struct {
|
|
|
|
*database.User
|
2018-08-26 00:55:21 +02:00
|
|
|
Conn *whatsappExt.ExtendedConn
|
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
|
|
|
|
2018-08-26 16:08:37 +02:00
|
|
|
Admin bool
|
|
|
|
Whitelisted bool
|
2019-05-15 22:04:09 +02:00
|
|
|
Connected bool
|
2019-05-17 22:53:57 +02:00
|
|
|
|
|
|
|
ConnectionErrors int
|
2019-05-22 22:05:58 +02:00
|
|
|
|
|
|
|
messages chan PortalMessage
|
|
|
|
syncLock sync.Mutex
|
2018-08-28 23:40:54 +02:00
|
|
|
}
|
2018-08-26 16:08:37 +02:00
|
|
|
|
2018-08-28 23:40:54 +02:00
|
|
|
func (bridge *Bridge) GetUserByMXID(userID types.MatrixUserID) *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
|
|
|
}
|
|
|
|
|
2018-08-28 23:40:54 +02:00
|
|
|
func (bridge *Bridge) GetUserByJID(userID types.WhatsAppID) *User {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2019-05-28 20:31:25 +02:00
|
|
|
func (bridge *Bridge) loadDBUser(dbUser *database.User, mxid *types.MatrixUserID) *User {
|
|
|
|
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()
|
|
|
|
defer user.bridge.portalsLock.Unlock()
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
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
|
|
|
|
|
|
|
messages: make(chan PortalMessage, 256),
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
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()
|
2018-08-25 23:26:24 +02:00
|
|
|
return user
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2018-08-18 21:57:08 +02:00
|
|
|
func (user *User) SetManagementRoom(roomID types.MatrixRoomID) {
|
|
|
|
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) {
|
|
|
|
user.Session = session
|
2019-05-22 15:46:18 +02:00
|
|
|
if session == nil {
|
|
|
|
user.LastConnection = 0
|
|
|
|
}
|
2018-08-18 21:57:08 +02:00
|
|
|
user.Update()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) Connect(evenIfNoSession bool) bool {
|
|
|
|
if user.Conn != nil {
|
|
|
|
return true
|
|
|
|
} else if !evenIfNoSession && user.Session == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
user.log.Debugln("Connecting to WhatsApp")
|
2019-05-16 17:08:30 +02:00
|
|
|
timeout := time.Duration(user.bridge.Config.Bridge.ConnectionTimeout)
|
|
|
|
if timeout == 0 {
|
|
|
|
timeout = 20
|
|
|
|
}
|
|
|
|
conn, err := whatsapp.NewConn(timeout * time.Second)
|
2018-08-16 14:59:18 +02:00
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to connect to WhatsApp:", err)
|
2019-05-16 17:18:11 +02:00
|
|
|
msg := format.RenderMarkdown(fmt.Sprintf("\u26a0 Failed to connect to WhatsApp server. " +
|
|
|
|
"This indicates a network problem on the bridge server. See bridge logs for more info."))
|
|
|
|
_, _ = user.bridge.Bot.SendMessageEvent(user.ManagementRoom, mautrix.EventMessage, msg)
|
2018-08-18 21:57:08 +02:00
|
|
|
return false
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2018-08-26 00:55:21 +02:00
|
|
|
user.Conn = whatsappExt.ExtendConn(conn)
|
2019-05-15 22:04:09 +02:00
|
|
|
_ = user.Conn.SetClientName("Mautrix-WhatsApp bridge", "mx-wa")
|
2018-08-18 21:57:08 +02:00
|
|
|
user.log.Debugln("WhatsApp connection successful")
|
2018-08-16 14:59:18 +02:00
|
|
|
user.Conn.AddHandler(user)
|
2019-05-16 17:24:54 +02:00
|
|
|
return user.RestoreSession()
|
2018-08-16 14:59:18 +02: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 {
|
2019-05-15 22:04:09 +02:00
|
|
|
sess, err := user.Conn.RestoreWithSession(*user.Session)
|
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)
|
2019-05-15 23:18:43 +02:00
|
|
|
msg := format.RenderMarkdown(fmt.Sprintf("\u26a0 Failed to connect to WhatsApp. Make sure WhatsApp "+
|
|
|
|
"on your phone is reachable and use `%s reconnect` to try connecting again.",
|
|
|
|
user.bridge.Config.Bridge.CommandPrefix))
|
|
|
|
_, _ = user.bridge.Bot.SendMessageEvent(user.ManagementRoom, mautrix.EventMessage, msg)
|
2018-08-18 21:57:08 +02:00
|
|
|
return false
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
2019-05-15 22:04:09 +02:00
|
|
|
user.Connected = true
|
2019-05-17 22:53:57 +02:00
|
|
|
user.ConnectionErrors = 0
|
2018-08-18 21:57:08 +02:00
|
|
|
user.SetSession(&sess)
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2018-08-28 23:40:54 +02:00
|
|
|
func (user *User) IsLoggedIn() bool {
|
|
|
|
return user.Conn != nil
|
|
|
|
}
|
|
|
|
|
2019-05-15 22:17:09 +02:00
|
|
|
func (user *User) Login(ce *CommandEvent) {
|
2018-08-16 14:59:18 +02:00
|
|
|
qrChan := make(chan string, 2)
|
|
|
|
go func() {
|
|
|
|
code := <-qrChan
|
|
|
|
if code == "error" {
|
|
|
|
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-05-15 22:17:09 +02:00
|
|
|
_, err = bot.SendImage(ce.RoomID, string(code), resp.ContentURI)
|
2019-01-21 22:55:16 +01:00
|
|
|
if err != nil {
|
|
|
|
user.log.Errorln("Failed to send QR code to user:", err)
|
|
|
|
}
|
2018-08-16 14:59:18 +02:00
|
|
|
}()
|
|
|
|
session, err := user.Conn.Login(qrChan)
|
|
|
|
if err != nil {
|
|
|
|
qrChan <- "error"
|
2019-05-15 22:17:09 +02:00
|
|
|
if err == whatsapp.ErrAlreadyLoggedIn {
|
|
|
|
ce.Reply("You're already logged in.")
|
|
|
|
} else if err == whatsapp.ErrLoginInProgress {
|
|
|
|
ce.Reply("You have a login in progress already.")
|
2019-05-15 23:18:43 +02:00
|
|
|
} else if err.Error() == "qr code scan timed out" {
|
|
|
|
ce.Reply("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-05-16 17:00:46 +02:00
|
|
|
ce.Reply("Unknown error while logging in: %v", err)
|
2019-05-15 22:17:09 +02:00
|
|
|
}
|
2018-08-16 14:59:18 +02:00
|
|
|
return
|
|
|
|
}
|
2019-05-15 22:04:09 +02:00
|
|
|
user.Connected = true
|
2019-05-17 22:53:57 +02:00
|
|
|
user.ConnectionErrors = 0
|
2018-08-28 23:40:54 +02:00
|
|
|
user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
|
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 {
|
|
|
|
return cl[i].LastMessageTime < cl[i].LastMessageTime
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cl ChatList) Swap(i, j int) {
|
|
|
|
cl[i], cl[j] = cl[j], cl[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) PostLogin() {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.syncLock.Lock()
|
2019-05-30 16:48:22 +02:00
|
|
|
go user.intPostLogin()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) intPostLogin() {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.log.Debugln("Waiting a second for contacts to arrive")
|
2019-05-22 15:46:18 +02:00
|
|
|
// Hacky way to wait for chats and contacts to arrive automatically
|
2019-05-22 22:05:58 +02:00
|
|
|
time.Sleep(1 * time.Second)
|
2019-05-22 22:27:58 +02:00
|
|
|
user.log.Debugln("Waited a second, have", len(user.Conn.Store.Chats), "chats and", len(user.Conn.Store.Contacts), "contacts")
|
2019-05-22 15:46:18 +02:00
|
|
|
|
|
|
|
go user.syncPuppets()
|
2019-05-23 21:57:52 +02:00
|
|
|
user.syncPortals(false)
|
2019-05-22 22:05:58 +02:00
|
|
|
user.syncLock.Unlock()
|
2019-05-22 15:46:18 +02:00
|
|
|
}
|
|
|
|
|
2019-05-23 21:57:52 +02:00
|
|
|
func (user *User) syncPortals(createAll bool) {
|
2019-05-28 20:31:25 +02:00
|
|
|
chats := make(ChatList, 0, len(user.Conn.Store.Chats))
|
|
|
|
portalKeys := make([]database.PortalKey, 0, len(user.Conn.Store.Chats))
|
2019-05-22 15:46:18 +02:00
|
|
|
for _, chat := range user.Conn.Store.Chats {
|
|
|
|
ts, err := strconv.ParseUint(chat.LastMessageTime, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnfln("Non-integer last message time in %s: %s", chat.Jid, chat.LastMessageTime)
|
|
|
|
continue
|
|
|
|
}
|
2019-05-28 20:31:25 +02:00
|
|
|
portal := user.GetPortalByJID(chat.Jid)
|
|
|
|
|
2019-05-22 15:46:18 +02:00
|
|
|
chats = append(chats, Chat{
|
2019-05-28 20:31:25 +02:00
|
|
|
Portal: portal,
|
2019-05-22 15:46:18 +02:00
|
|
|
Contact: user.Conn.Store.Contacts[chat.Jid],
|
|
|
|
LastMessageTime: ts,
|
|
|
|
})
|
2019-05-28 20:31:25 +02:00
|
|
|
portalKeys = append(portalKeys, portal.Key)
|
|
|
|
}
|
|
|
|
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)
|
|
|
|
}
|
2019-05-23 19:25:46 +02:00
|
|
|
now := uint64(time.Now().Unix())
|
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 {
|
2019-05-22 15:46:18 +02:00
|
|
|
chat.Portal.Sync(user, chat.Contact)
|
2019-05-22 22:05:58 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) syncPuppets() {
|
|
|
|
for jid, contact := range user.Conn.Store.Contacts {
|
|
|
|
if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
|
|
|
|
puppet := user.bridge.GetPuppetByJID(contact.Jid)
|
|
|
|
puppet.Sync(user, contact)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
2019-05-27 13:15:45 +02:00
|
|
|
if errors.Cause(err) != whatsapp.ErrInvalidWsData {
|
2019-05-27 12:46:04 +02:00
|
|
|
user.log.Errorln("WhatsApp error:", err)
|
|
|
|
}
|
2019-05-17 22:53:57 +02:00
|
|
|
if closed, ok := err.(*whatsapp.ErrConnectionClosed); ok {
|
|
|
|
user.Connected = false
|
|
|
|
if closed.Code == 1000 {
|
|
|
|
// Normal closure
|
|
|
|
return
|
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 {
|
2019-05-15 22:04:09 +02:00
|
|
|
user.Connected = false
|
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))
|
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) {
|
2019-05-17 22:53:57 +02:00
|
|
|
if user.ConnectionErrors > user.bridge.Config.Bridge.MaxConnectionAttempts {
|
|
|
|
content := format.RenderMarkdown(fmt.Sprintf("%s. Use the `reconnect` command to reconnect.", msg))
|
|
|
|
_, _ = user.bridge.Bot.SendMessageEvent(user.ManagementRoom, mautrix.EventMessage, content)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
|
|
|
_, _ = user.bridge.Bot.SendNotice(user.ManagementRoom, fmt.Sprintf("%s. Reconnecting...", msg))
|
|
|
|
// 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
|
2019-05-17 22:53:57 +02:00
|
|
|
for user.ConnectionErrors <= user.bridge.Config.Bridge.MaxConnectionAttempts {
|
2019-05-28 13:09:49 +02:00
|
|
|
err := user.Conn.Restore()
|
2019-05-17 22:53:57 +02:00
|
|
|
if err == nil {
|
|
|
|
user.ConnectionErrors = 0
|
|
|
|
user.Connected = true
|
|
|
|
_, _ = user.bridge.Bot.SendNotice(user.ManagementRoom, "Reconnected successfully")
|
2019-05-30 16:48:22 +02:00
|
|
|
user.PostLogin()
|
2019-05-17 22:53:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
user.log.Errorln("Error while trying to reconnect after disconnection:", err)
|
|
|
|
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 {
|
|
|
|
_, _ = user.bridge.Bot.SendNotice(user.ManagementRoom,
|
2019-05-28 13:09:49 +02:00
|
|
|
fmt.Sprintf("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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if user.bridge.Config.Bridge.ReportConnectionRetry {
|
|
|
|
msg = fmt.Sprintf("%d reconnection attempts failed. Use the `reconnect` command to try to reconnect manually.", tries)
|
|
|
|
} else {
|
|
|
|
msg = fmt.Sprintf("\u26a0 %sAdditionally, %d reconnection attempts failed. "+
|
|
|
|
"Use the `reconnect` command to try to reconnect.", msg, tries)
|
|
|
|
}
|
|
|
|
|
|
|
|
content := format.RenderMarkdown(msg)
|
|
|
|
_, _ = user.bridge.Bot.SendMessageEvent(user.ManagementRoom, mautrix.EventMessage, content)
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2019-05-21 22:44:14 +02:00
|
|
|
func (user *User) ShouldCallSynchronously() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2018-08-24 18:46:14 +02:00
|
|
|
func (user *User) HandleJSONParseError(err error) {
|
|
|
|
user.log.Errorln("WhatsApp JSON parse error:", err)
|
|
|
|
}
|
|
|
|
|
2018-08-28 23:40:54 +02:00
|
|
|
func (user *User) PortalKey(jid types.WhatsAppID) database.PortalKey {
|
|
|
|
return database.NewPortalKey(jid, user.JID)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) GetPortalByJID(jid types.WhatsAppID) *Portal {
|
|
|
|
return user.bridge.GetPortalByJID(user.PortalKey(jid))
|
|
|
|
}
|
|
|
|
|
2019-05-22 22:05:58 +02:00
|
|
|
func (user *User) handleMessageLoop() {
|
|
|
|
for msg := range user.messages {
|
|
|
|
user.syncLock.Lock()
|
|
|
|
user.GetPortalByJID(msg.chat).messages <- msg
|
|
|
|
user.syncLock.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) putMessage(message PortalMessage) {
|
|
|
|
select {
|
|
|
|
case user.messages <- message:
|
|
|
|
default:
|
|
|
|
user.log.Warnln("Buffer is full, dropping message in", message.chat)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-16 14:59:18 +02:00
|
|
|
func (user *User) HandleTextMessage(message whatsapp.TextMessage) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp})
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleImageMessage(message whatsapp.ImageMessage) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp})
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleVideoMessage(message whatsapp.VideoMessage) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp})
|
2018-08-23 23:52:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleAudioMessage(message whatsapp.AudioMessage) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp})
|
2018-08-23 23:52:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleDocumentMessage(message whatsapp.DocumentMessage) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp})
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|
|
|
|
|
2019-05-16 00:59:36 +02:00
|
|
|
func (user *User) HandleMessageRevoke(message whatsappExt.MessageRevocation) {
|
2019-05-22 22:05:58 +02:00
|
|
|
user.putMessage(PortalMessage{message.RemoteJid, user, message, 0})
|
2019-05-16 00:59:36 +02:00
|
|
|
}
|
|
|
|
|
2019-05-30 16:00:36 +02:00
|
|
|
type FakeMessage struct {
|
|
|
|
Text string
|
|
|
|
ID string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleCallInfo(info whatsappExt.CallInfo) {
|
|
|
|
if info.Data != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
data := FakeMessage{
|
|
|
|
ID: info.ID,
|
|
|
|
}
|
|
|
|
switch info.Type {
|
|
|
|
case whatsappExt.CallOffer:
|
|
|
|
data.Text = "Incoming call"
|
|
|
|
case whatsappExt.CallOfferVideo:
|
|
|
|
data.Text = "Incoming video call"
|
|
|
|
case whatsappExt.CallTerminate:
|
|
|
|
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}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-26 00:55:21 +02:00
|
|
|
func (user *User) HandlePresence(info whatsappExt.Presence) {
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-26 00:55:21 +02:00
|
|
|
func (user *User) HandleMsgInfo(info whatsappExt.MsgInfo) {
|
|
|
|
if (info.Command == whatsappExt.MsgInfoCommandAck || info.Command == whatsappExt.MsgInfoCommandAcks) && info.Acknowledgement == whatsappExt.AckMessageRead {
|
2018-08-24 18:46:14 +02:00
|
|
|
portal := user.GetPortalByJID(info.ToJID)
|
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-21 22:44:14 +02:00
|
|
|
go func() {
|
2019-05-24 01:33:26 +02:00
|
|
|
intent := user.bridge.GetPuppetByJID(info.SenderJID).IntentFor(portal)
|
2019-05-21 22:44:14 +02:00
|
|
|
for _, id := range info.IDs {
|
|
|
|
msg := user.bridge.DB.Message.GetByJID(portal.Key, id)
|
|
|
|
if msg == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
2019-05-21 22:44:14 +02:00
|
|
|
}()
|
2018-08-24 18:46:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-26 00:55:21 +02:00
|
|
|
func (user *User) HandleCommand(cmd whatsappExt.Command) {
|
2018-08-25 23:39:36 +02:00
|
|
|
switch cmd.Type {
|
2018-08-26 00:55:21 +02:00
|
|
|
case whatsappExt.CommandPicture:
|
|
|
|
if strings.HasSuffix(cmd.JID, whatsappExt.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)
|
2018-08-26 00:55:21 +02:00
|
|
|
} else {
|
|
|
|
portal := user.GetPortalByJID(cmd.JID)
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.UpdateAvatar(user, cmd.ProfilePicInfo)
|
2018-08-26 00:55:21 +02:00
|
|
|
}
|
2019-05-15 22:04:09 +02:00
|
|
|
case whatsappExt.CommandDisconnect:
|
|
|
|
var msg string
|
|
|
|
if cmd.Kind == "replaced" {
|
|
|
|
msg = "\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."
|
|
|
|
} else {
|
2019-05-16 17:00:46 +02:00
|
|
|
user.log.Warnln("Unknown kind of disconnect:", string(cmd.Raw))
|
2019-05-15 22:17:09 +02:00
|
|
|
msg = fmt.Sprintf("\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)
|
|
|
|
}
|
2019-05-21 22:44:14 +02:00
|
|
|
go user.bridge.Bot.SendMessageEvent(user.ManagementRoom, mautrix.EventMessage, format.RenderMarkdown(msg))
|
2018-08-26 00:55:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleChatUpdate(cmd whatsappExt.ChatUpdate) {
|
|
|
|
if cmd.Command != whatsappExt.ChatUpdateCommandAction {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
portal := user.GetPortalByJID(cmd.JID)
|
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch cmd.Data.Action {
|
|
|
|
case whatsappExt.ChatActionNameChange:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.UpdateName(cmd.Data.NameChange.Name, cmd.Data.SenderJID)
|
2018-08-26 00:55:21 +02:00
|
|
|
case whatsappExt.ChatActionAddTopic:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.UpdateTopic(cmd.Data.AddTopic.Topic, cmd.Data.SenderJID)
|
2018-08-26 00:55:21 +02:00
|
|
|
case whatsappExt.ChatActionRemoveTopic:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.UpdateTopic("", cmd.Data.SenderJID)
|
2018-08-26 15:11:48 +02:00
|
|
|
case whatsappExt.ChatActionPromote:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.ChangeAdminStatus(cmd.Data.PermissionChange.JIDs, true)
|
2018-08-26 15:11:48 +02:00
|
|
|
case whatsappExt.ChatActionDemote:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.ChangeAdminStatus(cmd.Data.PermissionChange.JIDs, false)
|
2018-08-26 15:11:48 +02:00
|
|
|
case whatsappExt.ChatActionAnnounce:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.RestrictMessageSending(cmd.Data.Announce)
|
2018-08-26 15:11:48 +02:00
|
|
|
case whatsappExt.ChatActionRestrict:
|
2019-05-21 22:44:14 +02:00
|
|
|
go portal.RestrictMetadataChanges(cmd.Data.Restrict)
|
2018-08-25 23:39:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-16 14:59:18 +02:00
|
|
|
func (user *User) HandleJsonMessage(message string) {
|
2019-03-14 00:06:06 +01:00
|
|
|
var msg json.RawMessage
|
|
|
|
err := json.Unmarshal([]byte(message), &msg)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-08-18 21:57:08 +02:00
|
|
|
user.log.Debugln("JSON message:", message)
|
2019-05-22 15:46:18 +02:00
|
|
|
user.updateLastConnectionIfNecessary()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (user *User) HandleRawMessage(message *waProto.WebMessageInfo) {
|
|
|
|
user.updateLastConnectionIfNecessary()
|
2018-08-16 14:59:18 +02:00
|
|
|
}
|