avatar and room on join

This commit is contained in:
Karmanyaah Malhotra 2021-02-27 17:38:47 -05:00
parent 27d3e0322d
commit b5af55122e
8 changed files with 313 additions and 300 deletions

View File

@ -918,31 +918,31 @@ func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'` const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) { func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
if len(ce.Args) == 0 { //if len(ce.Args) == 0 {
ce.Reply("**Usage:** `login-matrix <access token>`") // ce.Reply("**Usage:** `login-matrix <access token>`")
return // return
} //}
puppet := handler.bridge.GetPuppetByJID(ce.User.JID) //puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID) //err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
if err != nil { //if err != nil {
ce.Reply("Failed to switch puppet: %v", err) // ce.Reply("Failed to switch puppet: %v", err)
return // return
} //}
ce.Reply("Successfully switched puppet") //ce.Reply("Successfully switched puppet")
} }
const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.` const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) { func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
puppet := handler.bridge.GetPuppetByJID(ce.User.JID) //puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
if len(puppet.CustomMXID) == 0 { //if len(puppet.CustomMXID) == 0 {
ce.Reply("You had not changed your WhatsApp account's Matrix puppet.") // ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
return // return
} //}
err := puppet.SwitchCustomMXID("", "") //err := puppet.SwitchCustomMXID("", "")
if err != nil { //if err != nil {
ce.Reply("Failed to remove custom puppet: %v", err) // ce.Reply("Failed to remove custom puppet: %v", err)
return // return
} //}
ce.Reply("Successfully removed custom puppet") //ce.Reply("Successfully removed custom puppet")
} }

View File

@ -157,7 +157,7 @@ type UsernameTemplateArgs struct {
UserID id.UserID UserID id.UserID
} }
func (bc BridgeConfig) FormatDisplayname(contact groupme.User) (string, int8) { func (bc BridgeConfig) FormatDisplayname(contact groupme.Member) (string, int8) {
var buf bytes.Buffer var buf bytes.Buffer
if index := strings.IndexRune(contact.ID.String(), '@'); index > 0 { if index := strings.IndexRune(contact.ID.String(), '@'); index > 0 {
contact.ID = groupme.ID("+" + contact.ID.String()[:index]) contact.ID = groupme.ID("+" + contact.ID.String()[:index])
@ -165,10 +165,9 @@ func (bc BridgeConfig) FormatDisplayname(contact groupme.User) (string, int8) {
bc.displaynameTemplate.Execute(&buf, contact) bc.displaynameTemplate.Execute(&buf, contact)
var quality int8 var quality int8
switch { switch {
case len(contact.Name) > 0: case len(contact.Nickname) > 0:
quality = 3 quality = 3
case len(contact.Name) > 0 || len(contact.Name) > 0: //TODO what
quality = 2
case len(contact.ID) > 0: case len(contact.ID) > 0:
quality = 1 quality = 1
default: default:

View File

@ -17,18 +17,8 @@
package main package main
import ( import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"errors" "errors"
"time"
// "github.com/Rhymen/go-whatsapp" // "github.com/Rhymen/go-whatsapp"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
) )
var ( var (
@ -36,246 +26,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

@ -75,7 +75,7 @@ bridge:
# {{.Short}} - short display name from contact list # {{.Short}} - short display name from contact list
# To use multiple if's, you need to use: {{else if .Name}}, for example: # To use multiple if's, you need to use: {{else if .Name}}, for example:
# "{{if .Notify}}{{.Notify}}{{else if .Name}}{{.Name}}{{else}}{{.Jid}}{{end}} (WA)" # "{{if .Notify}}{{.Notify}}{{else if .Name}}{{.Name}}{{else}}{{.Jid}}{{end}} (WA)"
displayname_template: "{{if .Notify}}{{.Notify}}{{else}}{{.Jid}}{{end}} (WA)" displayname_template: "{{if .Nickname}}{{.Nickname}}{{else}}{{call .ID.String}}{{end}} (WA)"
# Localpart template for per-user room grouping community IDs. # Localpart template for per-user room grouping community IDs.
# On startup, the bridge will try to create these communities, add all of the specific user's # On startup, the bridge will try to create these communities, add all of the specific user's
# portals to the community, and invite the Matrix user to it. # portals to the community, and invite the Matrix user to it.

View File

@ -20,7 +20,7 @@ func NewClient(authToken string) *Client {
} }
func (c Client) IndexAllGroups() ([]*groupme.Group, error) { func (c Client) IndexAllGroups() ([]*groupme.Group, error) {
return c.IndexGroups(context.TODO(), &groupme.GroupsQuery{ return c.IndexGroups(context.TODO(), &groupme.GroupsQuery{
Omit: "memberships", // Omit: "memberships",
PerPage: 100, //TODO: Configurable and add multipage support PerPage: 100, //TODO: Configurable and add multipage support
}) })
} }

View File

@ -370,7 +370,6 @@ func (portal *Portal) SyncParticipants(metadata *groupme.Group) {
participantMap := make(map[string]bool) participantMap := make(map[string]bool)
for _, participant := range metadata.Members { for _, participant := range metadata.Members {
participantMap[participant.ID.String()] = true participantMap[participant.ID.String()] = true
fmt.Println(participant.ID.String())
user := portal.bridge.GetUserByJID(participant.ID.String()) user := portal.bridge.GetUserByJID(participant.ID.String())
portal.userMXIDAction(user, portal.ensureMXIDInvited) portal.userMXIDAction(user, portal.ensureMXIDInvited)
@ -390,6 +389,7 @@ func (portal *Portal) SyncParticipants(metadata *groupme.Group) {
if user != nil { if user != nil {
changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed
} }
puppet.Sync(nil, *participant) //why nil whynot
} }
if changed { if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels) _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
@ -405,7 +405,6 @@ func (portal *Portal) SyncParticipants(metadata *groupme.Group) {
jid, ok := portal.bridge.ParsePuppetMXID(member) jid, ok := portal.bridge.ParsePuppetMXID(member)
if ok { if ok {
_, shouldBePresent := participantMap[jid] _, shouldBePresent := participantMap[jid]
fmt.Println(jid)
if !shouldBePresent { if !shouldBePresent {
_, err := portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{ _, err := portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
UserID: member, UserID: member,
@ -708,11 +707,9 @@ func (portal *Portal) BackfillHistory(user *User, lastMessageTime uint64) error
defer endBackfill() defer endBackfill()
lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key) lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
fmt.Println(lastMessage)
if lastMessage == nil { if lastMessage == nil {
return nil return nil
} }
println(lastMessage.Timestamp, lastMessageTime)
if lastMessage.Timestamp >= lastMessageTime { if lastMessage.Timestamp >= lastMessageTime {
portal.log.Debugln("Not backfilling: no new messages") portal.log.Debugln("Not backfilling: no new messages")
return nil return nil
@ -2036,13 +2033,21 @@ func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event) {
} }
for _, i := range info { for _, i := range info {
portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info[0].ID) portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info[0].ID)
i = portal.sendRaw(sender, evt, info[0], false) //TODO deal with multiple messages for longer messages
portal.markHandled(sender, i, evt.ID) var err error
i, err = portal.sendRaw(sender, evt, info[0], false) //TODO deal with multiple messages for longer messages
if err != nil {
portal.log.Warnln("Unable to handle message from Matrix", evt.ID)
//TODO handle deleted room and such
} else {
portal.markHandled(sender, i, evt.ID)
}
} }
} }
func (portal *Portal) sendRaw(sender *User, evt *event.Event, info *groupme.Message, isRetry bool) *groupme.Message { func (portal *Portal) sendRaw(sender *User, evt *event.Event, info *groupme.Message, isRetry bool) (*groupme.Message, error) {
m, err := sender.Client.CreateMessage(context.TODO(), info.GroupID, info) m, err := sender.Client.CreateMessage(context.TODO(), info.GroupID, info)
id := "" id := ""
@ -2055,7 +2060,10 @@ func (portal *Portal) sendRaw(sender *User, evt *event.Event, info *groupme.Mess
if isRetry && err != nil { if isRetry && err != nil {
m, err = sender.Client.CreateMessage(context.TODO(), info.GroupID, info) m, err = sender.Client.CreateMessage(context.TODO(), info.GroupID, info)
} }
return m if err != nil {
return nil, err
}
return m, nil
// errChan := make(chan error, 1) // errChan := make(chan error, 1)
// go sender.Conn.SendRaw(info, errChan) // go sender.Conn.SendRaw(info, errChan)

View File

@ -232,7 +232,7 @@ func (puppet *Puppet) UpdateAvatar(source *User, avatar string) bool {
return true return true
} }
func (puppet *Puppet) UpdateName(source *User, contact groupme.User) bool { func (puppet *Puppet) UpdateName(source *User, contact groupme.Member) bool {
newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact) newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact)
if puppet.Displayname != newName && quality >= puppet.NameQuality { if puppet.Displayname != newName && quality >= puppet.NameQuality {
err := puppet.DefaultIntent().SetDisplayName(newName) err := puppet.DefaultIntent().SetDisplayName(newName)
@ -284,20 +284,30 @@ func (puppet *Puppet) updatePortalName() {
}) })
} }
func (puppet *Puppet) Sync(source *User, contact groupme.User) { func (puppet *Puppet) Sync(source *User, contact groupme.Member) {
if contact.UserID.String() == "system" {
puppet.log.Warnln("Trying to sync system puppet")
puppet.
portal.Sync(puppet.bridge.GetUserByJID(portal.Key.Receiver), groupme.Group{})
//TODO permissoins idk if its fine to use portal owner
return
}
err := puppet.DefaultIntent().EnsureRegistered() err := puppet.DefaultIntent().EnsureRegistered()
if err != nil { if err != nil {
puppet.log.Errorln("Failed to ensure registered:", err) puppet.log.Errorln("Failed to ensure registered:", err)
} }
if contact.ID.String() == source.JID { //if contact.ID.String() == source.JID {
//TODO What is this //TODO What is this
// contact.Notify = source.Conn.Info.Pushname // contact.Notify = source.Conn.Info.Pushname
} //}
update := false update := false
update = puppet.UpdateName(source, contact) || update update = puppet.UpdateName(source, contact) || update
update = puppet.UpdateAvatar(source, contact.AvatarURL) || update update = puppet.UpdateAvatar(source, contact.ImageURL) || update
if update { if update {
puppet.Update() puppet.Update()
} }

14
user.go
View File

@ -799,10 +799,11 @@ func (user *User) handleMessageLoop() {
user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput)) user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput))
puppet := user.bridge.GetPuppetByJID(msg.data.UserID.String()) puppet := user.bridge.GetPuppetByJID(msg.data.UserID.String())
if puppet != nil { if puppet != nil {
puppet.Sync(user, groupme.User{ puppet.Sync(user, groupme.Member{
ID: msg.data.ID, ID: msg.data.ID,
Name: msg.data.Name, UserID: msg.data.UserID,
AvatarURL: msg.data.AvatarURL, Nickname: msg.data.Name,
ImageURL: msg.data.AvatarURL,
}) //TODO: add params or docs? }) //TODO: add params or docs?
} }
user.GetPortalByJID(msg.chat).messages <- msg user.GetPortalByJID(msg.chat).messages <- msg
@ -848,6 +849,11 @@ func (user *User) HandleTextMessage(message groupme.Message) {
user.messageInput <- PortalMessage{message.GroupID.String(), user, &message, uint64(message.CreatedAt.ToTime().Unix())} user.messageInput <- PortalMessage{message.GroupID.String(), user, &message, uint64(message.CreatedAt.ToTime().Unix())}
} }
func (user *User) HandleJoin(id groupme.ID) {
user.HandleChatList()
//TODO: efficient
}
//func (user *User) HandleImageMessage(message whatsapp.ImageMessage) { //func (user *User) HandleImageMessage(message whatsapp.ImageMessage) {
// user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp} // user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
//} //}