Disable commands and fix associated bugs

This commit is contained in:
Karmanyaah Malhotra 2021-03-02 19:55:35 -05:00
parent 7069e7d358
commit 27bbc12d77
5 changed files with 63 additions and 57 deletions

View File

@ -119,8 +119,8 @@ func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
handler.CommandReconnect(ce) handler.CommandReconnect(ce)
case "disconnect": case "disconnect":
handler.CommandDisconnect(ce) handler.CommandDisconnect(ce)
case "ping": // case "ping":
handler.CommandPing(ce) // handler.CommandPing(ce)
case "delete-connection": case "delete-connection":
handler.CommandDeleteConnection(ce) handler.CommandDeleteConnection(ce)
case "delete-session": case "delete-session":
@ -379,7 +379,7 @@ func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
} }
} }
const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client` const cmdLoginHelp = `login - Authenticate this Bridge as a GroupMe Client, requires an access token from https://dev.groupme.com/`
// CommandLogin handles login command // CommandLogin handles login command
func (handler *CommandHandler) CommandLogin(ce *CommandEvent) { func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
@ -492,10 +492,9 @@ func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
// ce.Reply("Session information purged") // ce.Reply("Session information purged")
} }
const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp` const cmdReconnectHelp = `reconnect - Reconnect to GroupMe`
func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) { func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
fmt.Println(ce.User.Conn)
if ce.User.Conn == nil { if ce.User.Conn == nil {
if len(ce.User.Token) == 0 { if len(ce.User.Token) == 0 {
ce.Reply("No existing connection and no token. Did you mean `login`?") ce.Reply("No existing connection and no token. Did you mean `login`?")
@ -506,8 +505,11 @@ func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
return return
} }
// wasConnected := true wasConnected := true
// sess, err := ce.User.Conn.Disconnect() ce.User.Conn.Stop(context.TODO())
ce.User.Conn = nil
//TODO: better connection handling
// if err == whatsapp.ErrNotConnected { // if err == whatsapp.ErrNotConnected {
// wasConnected = false // wasConnected = false
// } else if err != nil { // } else if err != nil {
@ -553,14 +555,19 @@ func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
// return // return
// } // }
// ce.User.ConnectionErrors = 0 // ce.User.ConnectionErrors = 0
connected := ce.User.Connect()
if !connected {
ce.Reply("Unsuccessful connection")
return
}
// var msg string var msg string
// if wasConnected { if wasConnected {
// msg = "Reconnected successfully." msg = "Reconnected successfully."
// } else { } else {
// msg = "Connected successfully." msg = "Connected successfully."
// } }
// ce.Reply(msg) ce.Reply(msg)
// ce.User.PostLogin() // ce.User.PostLogin()
} }
@ -635,35 +642,36 @@ func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
ce.Reply("* " + strings.Join([]string{ ce.Reply("* " + strings.Join([]string{
cmdPrefix + cmdHelpHelp, cmdPrefix + cmdHelpHelp,
cmdPrefix + cmdLoginHelp, cmdPrefix + cmdLoginHelp,
cmdPrefix + cmdLogoutHelp, // cmdPrefix + cmdLogoutHelp,
cmdPrefix + cmdDeleteSessionHelp, // cmdPrefix + cmdDeleteSessionHelp,
cmdPrefix + cmdReconnectHelp, cmdPrefix + cmdReconnectHelp,
cmdPrefix + cmdDisconnectHelp, // cmdPrefix + cmdDisconnectHelp,
cmdPrefix + cmdDeleteConnectionHelp, // cmdPrefix + cmdDeleteConnectionHelp,
cmdPrefix + cmdPingHelp, // cmdPrefix + cmdPingHelp,
cmdPrefix + cmdLoginMatrixHelp, // cmdPrefix + cmdLoginMatrixHelp,
cmdPrefix + cmdLogoutMatrixHelp, // cmdPrefix + cmdLogoutMatrixHelp,
cmdPrefix + cmdToggleHelp, // cmdPrefix + cmdToggleHelp,
cmdPrefix + cmdSyncHelp, cmdPrefix + cmdSyncHelp,
cmdPrefix + cmdListHelp, cmdPrefix + cmdListHelp,
cmdPrefix + cmdOpenHelp, cmdPrefix + cmdOpenHelp,
cmdPrefix + cmdPMHelp, // cmdPrefix + cmdPMHelp,
cmdPrefix + cmdInviteLinkHelp, // cmdPrefix + cmdInviteLinkHelp,
cmdPrefix + cmdJoinHelp, // cmdPrefix + cmdJoinHelp,
cmdPrefix + cmdCreateHelp, // cmdPrefix + cmdCreateHelp,
cmdPrefix + cmdSetPowerLevelHelp, // cmdPrefix + cmdSetPowerLevelHelp,
cmdPrefix + cmdDeletePortalHelp, cmdPrefix + cmdDeletePortalHelp,
cmdPrefix + cmdDeleteAllPortalsHelp, cmdPrefix + cmdDeleteAllPortalsHelp,
}, "\n* ")) }, "\n* "))
} }
const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.` const cmdSyncHelp = `sync - Synchronize contacts from phone and optionally create portals for group chats.` //TODO: add [--create-all]
// CommandSync handles sync command // CommandSync handles sync command
func (handler *CommandHandler) CommandSync(ce *CommandEvent) { func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
// user := ce.User user := ce.User
//create := len(ce.Args) > 0 && ce.Args[0] == "--create-all" //create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
go user.HandleChatList()
// ce.Reply("Updating contact and chat list...") // ce.Reply("Updating contact and chat list...")
// handler.log.Debugln("Importing contacts of", user.MXID) // handler.log.Debugln("Importing contacts of", user.MXID)
// _, err := user.Conn.Contacts() // _, err := user.Conn.Contacts()
@ -685,7 +693,7 @@ func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
// ce.Reply("Syncing chats...") // ce.Reply("Syncing chats...")
// user.syncPortals(nil, create) // user.syncPortals(nil, create)
// ce.Reply("Sync complete.") ce.Reply("Syncing...")
} }
const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.` const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
@ -754,7 +762,9 @@ func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
}() }()
} }
const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.` const cmdListHelp = `list groups [page] [items per page] - Get a list of all contacts and groups.`
//<contacts|groups> //TODO
func formatContacts(contacts bool, input map[string]string) (result []string) { func formatContacts(contacts bool, input map[string]string) (result []string) {
for jid, contact := range input { for jid, contact := range input {

View File

@ -173,13 +173,12 @@ func (portal *Portal) Delete() {
} }
func (portal *Portal) GetUserIDs() []id.UserID { func (portal *Portal) GetUserIDs() []id.UserID {
println("HI AAAAAAAAAAAAAAAAAAAa") //TODO: gorm this
rows, err := portal.db.Raw(`SELECT "user".mxid FROM "user", user_portal rows, err := portal.db.Raw(`SELECT "users".mxid FROM "users", user_portals
WHERE "user".jid=user_portal.user_jid WHERE "users".jid=user_portals.user_jid
AND user_portal.portal_jid=$1 AND user_portals.portal_jid = ?
AND user_portal.portal_receiver=$2`, AND user_portals.portal_receiver = ?`,
portal.Key.JID, portal.Key.Receiver).Rows() portal.Key.JID, portal.Key.Receiver).Rows()
print("maybe maybe sql 760476084")
if err != nil { if err != nil {
portal.log.Debugln("Failed to get portal user ids:", err) portal.log.Debugln("Failed to get portal user ids:", err)
return nil return nil

View File

@ -222,7 +222,7 @@ func (user *User) GetPortalKeys() []PortalKey {
var keys []PortalKey var keys []PortalKey
for _, i := range up { for _, i := range up {
key := PortalKey{ key := PortalKey{
JID: i.UserJID, JID: i.PortalJID,
Receiver: i.PortalReceiver, Receiver: i.PortalReceiver,
} }
keys = append(keys, key) keys = append(keys, key)

View File

@ -19,7 +19,6 @@ package main
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/gob"
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
@ -43,7 +42,6 @@ import (
"maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mautrix/crypto/attachment"
"github.com/Rhymen/go-whatsapp" "github.com/Rhymen/go-whatsapp"
waProto "github.com/Rhymen/go-whatsapp/binary/proto"
"github.com/karmanyaahm/groupme" "github.com/karmanyaahm/groupme"
"maunium.net/go/mautrix" "maunium.net/go/mautrix"
@ -131,7 +129,7 @@ func (bridge *Bridge) NewManualPortal(key database.PortalKey) *Portal {
bridge: bridge, bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", key)), log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", key)),
recentlyHandled: [recentlyHandledLength]string{}, recentlyHandled: make([]string, recentlyHandledLength),
messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer), messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer),
} }
@ -146,7 +144,7 @@ func (bridge *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
bridge: bridge, bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)), log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
recentlyHandled: [recentlyHandledLength]string{}, recentlyHandled: make([]string, recentlyHandledLength),
messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer), messages: make(chan PortalMessage, bridge.Config.Bridge.PortalMessageBuffer),
} }
@ -172,7 +170,7 @@ type Portal struct {
roomCreateLock sync.Mutex roomCreateLock sync.Mutex
recentlyHandled [recentlyHandledLength]string recentlyHandled []string
recentlyHandledLock sync.Mutex recentlyHandledLock sync.Mutex
recentlyHandledIndex uint8 recentlyHandledIndex uint8
@ -266,12 +264,8 @@ func (portal *Portal) handleMessage(msg PortalMessage) {
} }
func (portal *Portal) isRecentlyHandled(id groupme.ID) bool { func (portal *Portal) isRecentlyHandled(id groupme.ID) bool {
start := int(portal.recentlyHandledIndex) //int bc -1 loops over to 255 in uint8
idStr := id.String() idStr := id.String()
for i := (start - 1) % recentlyHandledLength; i != start; i = (i - 1) % recentlyHandledLength { for i := recentlyHandledLength - 1; i >= 0; i-- {
if i < 0 { //do this to get modulo not remainder
i += recentlyHandledLength
}
if portal.recentlyHandled[i] == idStr { if portal.recentlyHandled[i] == idStr {
return true return true
} }
@ -289,7 +283,6 @@ func (portal *Portal) isDuplicate(id groupme.ID) bool {
} }
func init() { func init() {
gob.Register(&waProto.Message{})
} }
func (portal *Portal) markHandled(source *User, message *groupme.Message, mxid id.EventID) { func (portal *Portal) markHandled(source *User, message *groupme.Message, mxid id.EventID) {
@ -313,10 +306,10 @@ func (portal *Portal) markHandled(source *User, message *groupme.Message, mxid i
msg.Insert() msg.Insert()
portal.recentlyHandledLock.Lock() portal.recentlyHandledLock.Lock()
index := portal.recentlyHandledIndex portal.recentlyHandled[0] = "" //FIFO queue being implemented here //TODO: is this efficent
portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength portal.recentlyHandled = portal.recentlyHandled[1:]
portal.recentlyHandled = append(portal.recentlyHandled, message.ID.String())
portal.recentlyHandledLock.Unlock() portal.recentlyHandledLock.Unlock()
portal.recentlyHandled[index] = message.ID.String()
} }
func (portal *Portal) getMessageIntent(user *User, info *groupme.Message) *appservice.IntentAPI { func (portal *Portal) getMessageIntent(user *User, info *groupme.Message) *appservice.IntentAPI {
@ -393,7 +386,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 go 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)
@ -423,7 +416,7 @@ func (portal *Portal) SyncParticipants(metadata *groupme.Group) {
} }
} }
func (portal *Portal) UpdateAvatar(user *User, avatar *whatsappExt.ProfilePicInfo, updateInfo bool) bool { func (portal *Portal) UpdateAvatar(user *User, avatar string, updateInfo bool) bool {
// if avatar == nil { // if avatar == nil {
// var err error // var err error
// avatar, err = user.Conn.GetProfilePicThumb(portal.Key.JID) // avatar, err = user.Conn.GetProfilePicThumb(portal.Key.JID)
@ -599,7 +592,7 @@ func (portal *Portal) Sync(user *User, group groupme.Group) {
update := false update := false
update = portal.UpdateMetadata(user) || update update = portal.UpdateMetadata(user) || update
if !portal.IsStatusBroadcastRoom() { if !portal.IsStatusBroadcastRoom() {
update = portal.UpdateAvatar(user, nil, false) || update update = portal.UpdateAvatar(user, "", false) || update
} }
if update { if update {
portal.Update() portal.Update()
@ -984,7 +977,7 @@ func (portal *Portal) CreateMatrixRoom(user *User) error {
portal.Name = metadata.Name portal.Name = metadata.Name
portal.Topic = metadata.Description portal.Topic = metadata.Description
} }
portal.UpdateAvatar(user, nil, false) portal.UpdateAvatar(user, "", false)
} }
bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo() bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()

View File

@ -362,6 +362,10 @@ func (user *User) Login(ce *CommandEvent) {
// // Also between the two logout methods (commands.go and provisioning.go) // // Also between the two logout methods (commands.go and provisioning.go)
// user.ConnectionErrors = 0 // user.ConnectionErrors = 0
// user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1) // user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
if len(ce.Args) == 0 {
ce.Reply(`Get your access token from https://dev.groupme.com/ which should be the first argument to login`)
return
}
user.Token = ce.Args[0] user.Token = ce.Args[0]
user.addToJIDMap() user.addToJIDMap()