handle leave chat from matrix side

This commit is contained in:
Karmanyaah Malhotra 2021-02-27 19:57:42 -05:00
parent b5af55122e
commit 3e75ffaf05
6 changed files with 279 additions and 262 deletions

View File

@ -17,8 +17,16 @@
package main package main
import ( import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"errors" "errors"
// "github.com/Rhymen/go-whatsapp" "time"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
) )
var ( var (
@ -26,246 +34,246 @@ var (
ErrMismatchingMXID = errors.New("whoami result does not match custom mxid") ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
) )
//func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error { func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
// prevCustomMXID := puppet.CustomMXID prevCustomMXID := puppet.CustomMXID
// if puppet.customIntent != nil { if puppet.customIntent != nil {
// puppet.stopSyncing() puppet.stopSyncing()
// } }
// puppet.CustomMXID = mxid puppet.CustomMXID = mxid
// puppet.AccessToken = accessToken puppet.AccessToken = accessToken
//
// err := puppet.StartCustomMXID() err := puppet.StartCustomMXID()
// if err != nil { if err != nil {
// return err return err
// } }
//
// if len(prevCustomMXID) > 0 { if len(prevCustomMXID) > 0 {
// delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID) delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
// } }
// if len(puppet.CustomMXID) > 0 { if len(puppet.CustomMXID) > 0 {
// puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
// } }
// puppet.EnablePresence = puppet.bridge.Config.Bridge.DefaultBridgePresence puppet.EnablePresence = puppet.bridge.Config.Bridge.DefaultBridgePresence
// puppet.EnableReceipts = puppet.bridge.Config.Bridge.DefaultBridgeReceipts puppet.EnableReceipts = puppet.bridge.Config.Bridge.DefaultBridgeReceipts
// puppet.bridge.AS.StateStore.MarkRegistered(puppet.CustomMXID) puppet.bridge.AS.StateStore.MarkRegistered(puppet.CustomMXID)
// puppet.Update() puppet.Update()
// // TODO leave rooms with default puppet // TODO leave rooms with default puppet
// return nil return nil
//} }
//
//func (puppet *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) { func (puppet *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) {
// puppet.log.Debugfln("Logging into %s with shared secret", mxid) puppet.log.Debugfln("Logging into %s with shared secret", mxid)
// mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret)) mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret))
// mac.Write([]byte(mxid)) mac.Write([]byte(mxid))
// resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{ resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{
// Type: mautrix.AuthTypePassword, Type: mautrix.AuthTypePassword,
// Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(mxid)}, Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(mxid)},
// Password: hex.EncodeToString(mac.Sum(nil)), Password: hex.EncodeToString(mac.Sum(nil)),
// DeviceID: "WhatsApp Bridge", DeviceID: "WhatsApp Bridge",
// InitialDeviceDisplayName: "WhatsApp Bridge", InitialDeviceDisplayName: "WhatsApp Bridge",
// }) })
// if err != nil { if err != nil {
// return "", err return "", err
// } }
// return resp.AccessToken, nil return resp.AccessToken, nil
//} }
//
//func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) { func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
// if len(puppet.CustomMXID) == 0 { if len(puppet.CustomMXID) == 0 {
// return nil, ErrNoCustomMXID return nil, ErrNoCustomMXID
// } }
// client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken) client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
// if err != nil { if err != nil {
// return nil, err return nil, err
// } }
// client.Logger = puppet.bridge.AS.Log.Sub(string(puppet.CustomMXID)) client.Logger = puppet.bridge.AS.Log.Sub(string(puppet.CustomMXID))
// client.Syncer = puppet client.Syncer = puppet
// client.Store = puppet client.Store = puppet
//
// ia := puppet.bridge.AS.NewIntentAPI("custom") ia := puppet.bridge.AS.NewIntentAPI("custom")
// ia.Client = client ia.Client = client
// ia.Localpart, _, _ = puppet.CustomMXID.Parse() ia.Localpart, _, _ = puppet.CustomMXID.Parse()
// ia.UserID = puppet.CustomMXID ia.UserID = puppet.CustomMXID
// ia.IsCustomPuppet = true ia.IsCustomPuppet = true
// return ia, nil return ia, nil
//} }
//
//func (puppet *Puppet) clearCustomMXID() { func (puppet *Puppet) clearCustomMXID() {
// puppet.CustomMXID = "" puppet.CustomMXID = ""
// puppet.AccessToken = "" puppet.AccessToken = ""
// puppet.customIntent = nil puppet.customIntent = nil
// puppet.customTypingIn = nil puppet.customTypingIn = nil
// puppet.customUser = nil puppet.customUser = nil
//} }
//
//func (puppet *Puppet) StartCustomMXID() error { func (puppet *Puppet) StartCustomMXID() error {
// if len(puppet.CustomMXID) == 0 { if len(puppet.CustomMXID) == 0 {
// puppet.clearCustomMXID() puppet.clearCustomMXID()
// return nil return nil
// } }
// intent, err := puppet.newCustomIntent() intent, err := puppet.newCustomIntent()
// if err != nil { if err != nil {
// puppet.clearCustomMXID() puppet.clearCustomMXID()
// return err return err
// } }
// resp, err := intent.Whoami() resp, err := intent.Whoami()
// if err != nil { if err != nil {
// puppet.clearCustomMXID() puppet.clearCustomMXID()
// return err return err
// } }
// if resp.UserID != puppet.CustomMXID { if resp.UserID != puppet.CustomMXID {
// puppet.clearCustomMXID() puppet.clearCustomMXID()
// return ErrMismatchingMXID return ErrMismatchingMXID
// } }
// puppet.customIntent = intent puppet.customIntent = intent
// puppet.customTypingIn = make(map[id.RoomID]bool) puppet.customTypingIn = make(map[id.RoomID]bool)
// puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID) puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
// puppet.startSyncing() puppet.startSyncing()
// return nil return nil
//} }
//
//func (puppet *Puppet) startSyncing() { func (puppet *Puppet) startSyncing() {
// if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets { if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
// return return
// } }
// go func() { go func() {
// puppet.log.Debugln("Starting syncing...") puppet.log.Debugln("Starting syncing...")
// puppet.customIntent.SyncPresence = "offline" puppet.customIntent.SyncPresence = "offline"
// err := puppet.customIntent.Sync() err := puppet.customIntent.Sync()
// if err != nil { if err != nil {
// puppet.log.Errorln("Fatal error syncing:", err) puppet.log.Errorln("Fatal error syncing:", err)
// } }
// }() }()
//} }
//
//func (puppet *Puppet) stopSyncing() { func (puppet *Puppet) stopSyncing() {
// if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets { if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
// return return
// } }
// puppet.customIntent.StopSync() puppet.customIntent.StopSync()
//} }
//
//func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error { func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
// if !puppet.customUser.IsConnected() { if !puppet.customUser.IsConnected() {
// puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp") puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
// return nil return nil
// } }
// for roomID, events := range resp.Rooms.Join { for roomID, events := range resp.Rooms.Join {
// portal := puppet.bridge.GetPortalByMXID(roomID) portal := puppet.bridge.GetPortalByMXID(roomID)
// if portal == nil { if portal == nil {
// continue continue
// } }
// for _, evt := range events.Ephemeral.Events { for _, evt := range events.Ephemeral.Events {
// err := evt.Content.ParseRaw(evt.Type) err := evt.Content.ParseRaw(evt.Type)
// if err != nil { if err != nil {
// continue continue
// } }
// switch evt.Type { switch evt.Type {
// case event.EphemeralEventReceipt: case event.EphemeralEventReceipt:
// if puppet.EnableReceipts { if puppet.EnableReceipts {
// go puppet.handleReceiptEvent(portal, evt) go puppet.handleReceiptEvent(portal, evt)
// } }
// case event.EphemeralEventTyping: case event.EphemeralEventTyping:
// go puppet.handleTypingEvent(portal, evt) go puppet.handleTypingEvent(portal, evt)
// } }
// } }
// } }
// if puppet.EnablePresence { if puppet.EnablePresence {
// for _, evt := range resp.Presence.Events { for _, evt := range resp.Presence.Events {
// if evt.Sender != puppet.CustomMXID { if evt.Sender != puppet.CustomMXID {
// continue continue
// } }
// err := evt.Content.ParseRaw(evt.Type) err := evt.Content.ParseRaw(evt.Type)
// if err != nil { if err != nil {
// continue continue
// } }
// go puppet.handlePresenceEvent(evt) go puppet.handlePresenceEvent(evt)
// } }
// } }
// return nil return nil
//} }
//
//func (puppet *Puppet) handlePresenceEvent(event *event.Event) { func (puppet *Puppet) handlePresenceEvent(event *event.Event) {
// // presence := whatsapp.PresenceAvailable // presence := whatsapp.PresenceAvailable
// // if event.Content.Raw["presence"].(string) != "online" { // if event.Content.Raw["presence"].(string) != "online" {
// // presence = whatsapp.PresenceUnavailable // presence = whatsapp.PresenceUnavailable
// // puppet.customUser.log.Debugln("Marking offline") // puppet.customUser.log.Debugln("Marking offline")
// // } else { // } else {
// // puppet.customUser.log.Debugln("Marking online") // puppet.customUser.log.Debugln("Marking online")
// // } // }
// // _, err := puppet.customUser.Conn.Presence("", presence) // _, err := puppet.customUser.Conn.Presence("", presence)
// // if err != nil { // if err != nil {
// // puppet.customUser.log.Warnln("Failed to set presence:", err) // puppet.customUser.log.Warnln("Failed to set presence:", err)
// // } // }
//} }
//
//func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) { func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) {
// // for eventID, receipts := range *event.Content.AsReceipt() { // for eventID, receipts := range *event.Content.AsReceipt() {
// // if _, ok := receipts.Read[puppet.CustomMXID]; !ok { // if _, ok := receipts.Read[puppet.CustomMXID]; !ok {
// // continue // continue
// // } // }
// // message := puppet.bridge.DB.Message.GetByMXID(eventID) // message := puppet.bridge.DB.Message.GetByMXID(eventID)
// // if message == nil { // if message == nil {
// // continue // continue
// // } // }
// // puppet.customUser.log.Debugfln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID) // puppet.customUser.log.Debugfln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
// // _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID) // _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
// // if err != nil { // if err != nil {
// // puppet.customUser.log.Warnln("Error marking read:", err) // puppet.customUser.log.Warnln("Error marking read:", err)
// // } // }
// // } // }
//} }
//
//func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) { func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) {
// // isTyping := false // isTyping := false
// // for _, userID := range evt.Content.AsTyping().UserIDs { // for _, userID := range evt.Content.AsTyping().UserIDs {
// // if userID == puppet.CustomMXID { // if userID == puppet.CustomMXID {
// // isTyping = true // isTyping = true
// // break // break
// // } // }
// // } // }
// // if puppet.customTypingIn[evt.RoomID] != isTyping { // if puppet.customTypingIn[evt.RoomID] != isTyping {
// // puppet.customTypingIn[evt.RoomID] = isTyping // puppet.customTypingIn[evt.RoomID] = isTyping
// // presence := whatsapp.PresenceComposing // presence := whatsapp.PresenceComposing
// // if !isTyping { // if !isTyping {
// // puppet.customUser.log.Debugfln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID) // puppet.customUser.log.Debugfln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
// // presence = whatsapp.PresencePaused // presence = whatsapp.PresencePaused
// // } else { // } else {
// // puppet.customUser.log.Debugfln("Marking typing in %s/%s", portal.Key.JID, portal.MXID) // puppet.customUser.log.Debugfln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
// // } // }
// // _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence) // _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
// // if err != nil { // if err != nil {
// // puppet.customUser.log.Warnln("Error setting typing:", err) // puppet.customUser.log.Warnln("Error setting typing:", err)
// // } // }
// // } // }
//} }
//
//func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) { func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
// puppet.log.Warnln("Sync error:", err) puppet.log.Warnln("Sync error:", err)
// return 10 * time.Second, nil return 10 * time.Second, nil
//} }
//
//func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter { func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
// everything := []event.Type{{Type: "*"}} everything := []event.Type{{Type: "*"}}
// return &mautrix.Filter{ return &mautrix.Filter{
// Presence: mautrix.FilterPart{ Presence: mautrix.FilterPart{
// Senders: []id.UserID{puppet.CustomMXID}, Senders: []id.UserID{puppet.CustomMXID},
// Types: []event.Type{event.EphemeralEventPresence}, Types: []event.Type{event.EphemeralEventPresence},
// }, },
// AccountData: mautrix.FilterPart{NotTypes: everything}, AccountData: mautrix.FilterPart{NotTypes: everything},
// Room: mautrix.RoomFilter{ Room: mautrix.RoomFilter{
// Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}}, Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
// IncludeLeave: false, IncludeLeave: false,
// AccountData: mautrix.FilterPart{NotTypes: everything}, AccountData: mautrix.FilterPart{NotTypes: everything},
// State: mautrix.FilterPart{NotTypes: everything}, State: mautrix.FilterPart{NotTypes: everything},
// Timeline: mautrix.FilterPart{NotTypes: everything}, Timeline: mautrix.FilterPart{NotTypes: everything},
// }, },
// } }
//} }
//
//func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {} func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
//func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() } func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
//func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {} func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {}
//func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" } func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
//func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch } func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
//func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil } func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }

View File

@ -171,7 +171,7 @@ func (portal *Portal) Update() {
} }
func (portal *Portal) Delete() { func (portal *Portal) Delete() {
ans := portal.db.Delete(&portal) ans := portal.db.Where("jid = ? AND receiver = ?", portal.Key.JID, portal.Key.Receiver).Delete(&portal)
if ans.Error != nil { if ans.Error != nil {
portal.log.Warnfln("Failed to delete %s: %v", portal.Key, ans.Error) portal.log.Warnfln("Failed to delete %s: %v", portal.Key, ans.Error)
} }

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"github.com/karmanyaahm/groupme" "github.com/karmanyaahm/groupme"
"maunium.net/go/mautrix-whatsapp/types"
) )
type Client struct { type Client struct {
@ -50,3 +51,12 @@ func (c Client) LoadMessagesBefore(groupID, lastMessageID string, num int) ([]*g
} }
return i.Messages, nil return i.Messages, nil
} }
func (c *Client) RemoveFromGroup(uid, groupID types.GroupMeID) error {
group, err := c.ShowGroup(context.TODO(), groupme.ID(groupID))
if err != nil {
return err
}
return c.RemoveMember(context.TODO(), groupme.ID(groupID), group.GetMemberByUserID(groupme.ID(uid)).ID)
}

View File

@ -2238,21 +2238,20 @@ func (portal *Portal) Cleanup(puppetsOnly bool) {
} }
func (portal *Portal) HandleMatrixLeave(sender *User) { func (portal *Portal) HandleMatrixLeave(sender *User) {
// if portal.IsPrivateChat() { if portal.IsPrivateChat() {
// portal.log.Debugln("User left private chat portal, cleaning up and deleting...") portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
// portal.Delete() portal.Delete()
// portal.Cleanup(false) portal.Cleanup(false)
// return return
// } else { } else {
// // TODO should we somehow deduplicate this call if this leave was sent by the bridge? // TODO should we somehow deduplicate this call if this leave was sent by the bridge?
// resp, err := sender.Conn.LeaveGroup(portal.Key.JID) err := sender.Client.RemoveFromGroup(sender.JID, portal.Key.JID)
// if err != nil { if err != nil {
// portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err) portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err)
// return return
// } }
// portal.log.Infoln("Leave response:", <-resp) portal.CleanupIfEmpty()
// portal.CleanupIfEmpty() }
// }
} }
func (portal *Portal) HandleMatrixKick(sender *User, evt *event.Event) { func (portal *Portal) HandleMatrixKick(sender *User, evt *event.Event) {

View File

@ -288,8 +288,7 @@ func (puppet *Puppet) Sync(source *User, contact groupme.Member) {
if contact.UserID.String() == "system" { if contact.UserID.String() == "system" {
puppet.log.Warnln("Trying to sync system puppet") puppet.log.Warnln("Trying to sync system puppet")
puppet. // portal.Sync(puppet.bridge.GetUserByJID(portal.Key.Receiver), groupme.Group{})
portal.Sync(puppet.bridge.GetUserByJID(portal.Key.Receiver), groupme.Group{})
//TODO permissoins idk if its fine to use portal owner //TODO permissoins idk if its fine to use portal owner
return return

View File

@ -592,6 +592,7 @@ func (user *User) syncPortals(chatMap map[string]groupme.Group, createAll bool)
} }
} }
} }
//TODO: handle leave from groupme side
user.UpdateDirectChats(nil) user.UpdateDirectChats(nil)
user.log.Infoln("Finished syncing portals") user.log.Infoln("Finished syncing portals")
select { select {