diff --git a/commands.go b/commands.go index f3ff562..b3861d9 100644 --- a/commands.go +++ b/commands.go @@ -7,6 +7,7 @@ import ( "github.com/kelaresg/matrix-skype/database" skypeExt "github.com/kelaresg/matrix-skype/skype-ext" "math" + "maunium.net/go/mautrix/patch" "sort" "strconv" @@ -234,7 +235,7 @@ func (handler *CommandHandler) CommandLogin(ce *CommandEvent) { ce.Reply("**Usage:** `login username password`") return } - + leavePortals(ce) if !ce.User.Connect(true) { ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.") return @@ -251,7 +252,7 @@ func (handler *CommandHandler) CommandLogout(ce *CommandEvent) { if ce.User.Conn == nil { return } - _ = ce.User.Conn.GetConversations("", ce.User.bridge.Config.Bridge.InitialChatSync) + //_ = ce.User.Conn.GetConversations("", ce.User.bridge.Config.Bridge.InitialChatSync) ce.User.Conn.LoggedIn = false username := "" password := "" @@ -271,20 +272,33 @@ func (handler *CommandHandler) CommandLogout(ce *CommandEvent) { Password: password, } - portals := ce.User.GetPortals() - newPortals := ce.User.GetPortalsNew() - allPortals := newPortals[0:] - for _, portal := range portals { - var newPortalsHas bool - for _, newPortal := range newPortals { - if portal.Key == newPortal.Key { - newPortalsHas = true - } - } - if !newPortalsHas { - allPortals = append(allPortals, portal) - } + ce.User.Conn.Store = &skype.Store{ + Contacts: make(map[string]skype.Contact), + Chats: make(map[string]skype.Conversation), } + ce.Reply("Logged out successfully.") + if ce.User.Conn.Refresh != nil { + ce.User.Conn.Refresh <- -1 + } else { + leavePortals(ce) + } +} + +func leavePortals(ce *CommandEvent) { + portals := ce.User.GetPortals() + //newPortals := ce.User.GetPortalsNew() + //allPortals := newPortals[0:] + //for _, portal := range portals { + // var newPortalsHas bool + // for _, newPortal := range newPortals { + // if portal.Key == newPortal.Key { + // newPortalsHas = true + // } + // } + // if !newPortalsHas { + // allPortals = append(allPortals, portal) + // } + //} leave := func(portal *Portal) { if len(portal.MXID) > 0 { @@ -294,47 +308,11 @@ func (handler *CommandHandler) CommandLogout(ce *CommandEvent) { }) } } - for _, portal := range allPortals { + for _, portal := range portals { leave(portal) } - ce.Reply("Logged out successfully.") } -// CommandLogout handles !logout command -//func (handler *CommandHandler) CommandLogout(ce *CommandEvent) { -// if ce.User.Session == nil { -// ce.Reply("You're not logged in.") -// return -// } else if !ce.User.IsConnected() { -// ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.") -// return -// } -// puppet := handler.bridge.GetPuppetByJID(ce.User.JID) -// if puppet.CustomMXID != "" { -// err := puppet.SwitchCustomMXID("", "") -// if err != nil { -// ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err) -// } -// } -// err := ce.User.Conn.Logout() -// if err != nil { -// ce.User.log.Warnln("Error while logging out:", err) -// ce.Reply("Unknown error while logging out: %v", err) -// return -// } -// _, err = ce.User.Conn.Disconnect() -// if err != nil { -// ce.User.log.Warnln("Error while disconnecting after logout:", err) -// } -// ce.User.Conn.RemoveHandlers() -// ce.User.Conn = nil -// ce.User.removeFromJIDMap() -// // TODO this causes a foreign key violation, which should be fixed -// //ce.User.JID = "" -// ce.User.SetSession(nil) -// ce.Reply("Logged out successfully.") -//} - const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request` //func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) { @@ -475,7 +453,17 @@ func (handler *CommandHandler) CommandPing(ce *CommandEvent) { if len(ce.User.Conn.UserProfile.LastName) > 0 { username = username + ce.User.Conn.UserProfile.LastName } - ce.Reply("You're logged in as @" + username) + if username == "" { + username = ce.User.Conn.UserProfile.Username + } + + orgId := "" + if patch.ThirdPartyIdEncrypt { + orgId = patch.Enc(strings.TrimSuffix(ce.User.JID, skypeExt.NewUserSuffix)) + } else { + orgId = strings.TrimSuffix(ce.User.JID, skypeExt.NewUserSuffix) + } + ce.Reply("You're logged in as @" + username + ", orgid is " + orgId) } } diff --git a/crypto.go b/crypto.go index f67db9a..14ecc97 100644 --- a/crypto.go +++ b/crypto.go @@ -122,20 +122,20 @@ func (helper *CryptoHelper) loginBot() (*mautrix.Client, error) { return nil, fmt.Errorf("failed to initialize client: %w", err) } client.Logger = helper.baseLog.Sub("Bot") + client.Client = helper.bridge.AS.HTTPClient + client.DefaultHTTPRetries = helper.bridge.AS.DefaultHTTPRetries flows, err := client.GetLoginFlows() if err != nil { return nil, fmt.Errorf("failed to get supported login flows: %w", err) } - if !flows.HasFlow(mautrix.AuthTypeAppservice) { - // TODO after synapse 1.22, turn this into an error - helper.log.Warnln("Encryption enabled in config, but homeserver does not advertise appservice login") - //return nil, fmt.Errorf("homeserver does not support appservice login") + if !flows.HasFlow(mautrix.AuthTypeHalfyAppservice) { + return nil, fmt.Errorf("homeserver does not support appservice login") } // We set the API token to the AS token here to authenticate the appservice login // It'll get overridden after the login client.AccessToken = helper.bridge.AS.Registration.AppToken resp, err := client.Login(&mautrix.ReqLogin{ - Type: mautrix.AuthTypeAppservice, + Type: mautrix.AuthTypeHalfyAppservice, Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(helper.bridge.AS.BotMXID())}, DeviceID: deviceID, InitialDeviceDisplayName: "Skype Bridge", diff --git a/database/user.go b/database/user.go index 14ed243..45ac771 100644 --- a/database/user.go +++ b/database/user.go @@ -183,6 +183,17 @@ func (user *User) SetPortalKeys(newKeys []PortalKeyWithMeta) error { return tx.Commit() } +func (user *User) CreateUserPortal(newKey PortalKeyWithMeta) { + user.log.Debugfln("Creating new portal %s for %s", newKey.PortalKey.JID, newKey.PortalKey.Receiver) + _, err := user.db.Exec(`INSERT INTO user_portal (user_jid, portal_jid, portal_receiver, in_community) VALUES ($1, $2, $3, $4)`, + user.jidPtr(), + newKey.PortalKey.JID, newKey.PortalKey.Receiver, + newKey.InCommunity) + if err != nil { + user.log.Warnfln("Failed to insert %s: %v", user.MXID, err) + } +} + func (user *User) IsInPortal(key PortalKey) bool { row := user.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM user_portal WHERE user_jid=$1 AND portal_jid=$2 AND portal_receiver=$3)`, user.jidPtr(), &key.JID, &key.Receiver) var exists bool diff --git a/formatting.go b/formatting.go index 8940f3e..9c8d881 100644 --- a/formatting.go +++ b/formatting.go @@ -122,7 +122,7 @@ func (formatter *Formatter) ParseSkype(content *event.MessageEventContent, RoomM // parse quote message(set reply) content.Body = strings.ReplaceAll(content.Body, "\n", "") - quoteReg := regexp.MustCompile(`]+\bauthor="([^"]+)" authorname="([^"]+)" timestamp="([^"]+)" conversation.* messageid="([^"]+)".*>.*?(.*?).*?(.*)`) + quoteReg := regexp.MustCompile(`]+\bauthor="([^"]+)" authorname="([^"]+)" timestamp="([^"]+)" conversation="([^"]+)" messageid="([^"]+)".*>.*?(.*?).*?(.*)`) quoteMatches := quoteReg.FindAllStringSubmatch(content.Body, -1) if len(quoteMatches) > 0 { @@ -132,8 +132,18 @@ func (formatter *Formatter) ParseSkype(content *event.MessageEventContent, RoomM fmt.Println("ParseSkype quoteMatches a:", a) fmt.Println() } + portal := formatter.bridge.GetPortalByMXID(RoomMXID) + if portal.Key.JID != match[4] { + content.FormattedBody = match[6] + content.Body = fmt.Sprintf("%s\n\n", match[6]) + + // this means that there are forwarding messages across groups + if strings.HasSuffix(match[4], skypeExt.GroupSuffix) || strings.HasSuffix(portal.Key.JID, skypeExt.GroupSuffix){ + continue + } + } msgMXID := "" - msg := formatter.bridge.DB.Message.GetByID(match[4]) + msg := formatter.bridge.DB.Message.GetByID(match[5]) if msg != nil { msgMXID = string(msg.MXID) } @@ -144,21 +154,21 @@ func (formatter *Formatter) ParseSkype(content *event.MessageEventContent, RoomM href1, href2, mxid, - match[5]) + match[6]) content.FormattedBody = newContent - content.Body = fmt.Sprintf("> <%s> %s\n\n", mxid, match[5]) + content.Body = fmt.Sprintf("> <%s> %s\n\n", mxid, match[6]) inRelateTo := &event.RelatesTo{ Type: event.RelReply, EventID: id.EventID(msgMXID), } content.SetRelatesTo(inRelateTo) - backStr = match[6] + backStr = match[7] } } } // parse mention user message - r := regexp.MustCompile(`(?m)]+\bid="([^"]+)"(.*?)`) + r := regexp.MustCompile(`(?m)]+\bid="([^"]+)">(.*?)`) var originStr string var originBodyStr string if len(backStr) == 0 { @@ -170,8 +180,14 @@ func (formatter *Formatter) ParseSkype(content *event.MessageEventContent, RoomM if len(matches) > 0 { for _, match := range matches { mxid, displayname := formatter.getMatrixInfoByJID(match[1] + skypeExt.NewUserSuffix) + replaceStr := "" + if len(displayname) < 1 { + // TODO need to optimize + replaceStr = match[2] + ":" + } else { + replaceStr = fmt.Sprintf(`%s:`, formatter.bridge.Config.Homeserver.ServerName, mxid, displayname) + } // number := "@" + strings.Replace(match[1], skypeExt.NewUserSuffix, "", 1) - replaceStr := fmt.Sprintf(`%s:`, formatter.bridge.Config.Homeserver.ServerName, mxid, displayname) originStr = strings.ReplaceAll(originStr, match[0], replaceStr) originBodyStr = strings.ReplaceAll(originStr, replaceStr, displayname + ":") } diff --git a/go.mod b/go.mod index 24cf9b1..43e87ab 100644 --- a/go.mod +++ b/go.mod @@ -4,17 +4,17 @@ go 1.14 require ( github.com/chai2010/webp v1.1.0 + github.com/gabriel-vasile/mimetype v1.1.2 github.com/gorilla/websocket v1.4.2 - github.com/kelaresg/go-skypeapi v0.1.2-0.20210128115834-086b2e03dd09 - github.com/lib/pq v1.7.0 + github.com/kelaresg/go-skypeapi v0.1.2-0.20210603114428-9c103d451110 + github.com/lib/pq v1.9.0 github.com/mattn/go-sqlite3 v2.0.3+incompatible github.com/pkg/errors v0.9.1 - github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e golang.org/x/image v0.0.0-20200618115811-c13761719519 gopkg.in/yaml.v2 v2.3.0 maunium.net/go/mauflag v1.0.0 - maunium.net/go/maulogger/v2 v2.1.1 + maunium.net/go/maulogger/v2 v2.2.4 maunium.net/go/mautrix v0.8.0-rc.4 ) -replace maunium.net/go/mautrix => github.com/pidongqianqian/mautrix-go v0.8.0-rc.4.0.20201208081810-787323a21113 +replace maunium.net/go/mautrix => github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe diff --git a/go.sum b/go.sum index 4c5ae4b..3cddb7c 100644 --- a/go.sum +++ b/go.sum @@ -64,6 +64,8 @@ github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8 github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/gabriel-vasile/mimetype v1.1.2 h1:gaPnPcNor5aZSVCJVSGipcpbgMWiAAj9z182ocSGbHU= +github.com/gabriel-vasile/mimetype v1.1.2/go.mod h1:6CDPel/o/3/s4+bp6kIbsWATq8pmgOisOPG40CJa6To= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= @@ -113,6 +115,8 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGa github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -162,6 +166,8 @@ github.com/kelaresg/go-skypeapi v0.1.2-0.20210120095455-33c3f50415c4 h1:8tif5ndo github.com/kelaresg/go-skypeapi v0.1.2-0.20210120095455-33c3f50415c4/go.mod h1:2Mxwa2Flo+PKlVYEM4QBNgs408C/mUSBXRzAb6+B+Zg= github.com/kelaresg/go-skypeapi v0.1.2-0.20210128115834-086b2e03dd09 h1:Hy1sgotN3qqglcmoT4G295UiX7Ucdyn/mGq/GlwDNgc= github.com/kelaresg/go-skypeapi v0.1.2-0.20210128115834-086b2e03dd09/go.mod h1:2Mxwa2Flo+PKlVYEM4QBNgs408C/mUSBXRzAb6+B+Zg= +github.com/kelaresg/go-skypeapi v0.1.2-0.20210526124154-2e6d23e27010 h1:Mvm+MyoqKBUKbbZhIBpjSKNoiixinmNHBJtJ6EbfpuE= +github.com/kelaresg/go-skypeapi v0.1.2-0.20210526124154-2e6d23e27010/go.mod h1:2Mxwa2Flo+PKlVYEM4QBNgs408C/mUSBXRzAb6+B+Zg= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= @@ -176,6 +182,8 @@ github.com/lib/pq v1.5.2 h1:yTSXVswvWUOQ3k1sd7vJfDrbSl8lKuscqFJRqjC0ifw= github.com/lib/pq v1.5.2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.7.0 h1:h93mCPfUSkaul3Ka/VG8uZdmW1uMHDGxzu0NWHuJmHY= github.com/lib/pq v1.7.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.9.0 h1:L8nSXQQzAYByakOFMTwpjRoHsMJklur4Gi59b6VivR8= +github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= @@ -183,6 +191,7 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -222,6 +231,8 @@ github.com/pidongqianqian/mautrix-go v0.8.0-rc.4.0.20201126070406-7b13ac473bcc h github.com/pidongqianqian/mautrix-go v0.8.0-rc.4.0.20201126070406-7b13ac473bcc/go.mod h1:TtVePxoEaw6+RZDKVajw66Yaj1lqLjH8l4FF3krsqWY= github.com/pidongqianqian/mautrix-go v0.8.0-rc.4.0.20201208081810-787323a21113 h1:tetxcECwIGgb7Gl4AyY/9+MXmuUfp33FweuGU/Bb7AM= github.com/pidongqianqian/mautrix-go v0.8.0-rc.4.0.20201208081810-787323a21113/go.mod h1:TtVePxoEaw6+RZDKVajw66Yaj1lqLjH8l4FF3krsqWY= +github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe h1:ZPK2QEV0zE5jUHl00AW0xl6kdCxtBaWxklcnMHtQGbs= +github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe/go.mod h1:7IzKfWvpQtN+W2Lzxc0rLvIxFM3ryKX6Ys3S/ZoWbg8= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -249,6 +260,8 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= @@ -286,13 +299,21 @@ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tidwall/gjson v1.6.0 h1:9VEQWz6LLMUsUl6PueE49ir4Ka6CzLymOAZDxpFsTDc= github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= +github.com/tidwall/gjson v1.6.8 h1:CTmXMClGYPAmln7652e69B7OLXfTi5ABcPPwjIWUv7w= +github.com/tidwall/gjson v1.6.8/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI= github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc= github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= +github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE= +github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tidwall/pretty v1.0.1 h1:WE4RBSZ1x6McVVC8S/Md+Qse8YUv6HRObAx6ke00NY8= github.com/tidwall/pretty v1.0.1/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU= +github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tidwall/sjson v1.1.1 h1:7h1vk049Jnd5EH9NyzNiEuwYW4b5qgreBbqRC19AS3U= github.com/tidwall/sjson v1.1.1/go.mod h1:yvVuSnpEQv5cYIrO+AT6kw4QVfd5SDZoGIS7/5+fZFs= +github.com/tidwall/sjson v1.1.5 h1:wsUceI/XDyZk3J1FUvuuYlK62zJv2HO2Pzb8A5EWdUE= +github.com/tidwall/sjson v1.1.5/go.mod h1:VuJzsZnTowhSxWdOgsAnb886i4AjEyTkk7tNtsL7EYE= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tulir/go-whatsapp v0.2.8 h1:0dpAQ/2ONT6T2//aAl+9IeFGMRtqOZpMEqJlhX9vxos= github.com/tulir/go-whatsapp v0.2.8/go.mod h1:gyw9zGup1/Y3ZQUueZaqz3iR/WX9a2Lth4aqEbXjkok= @@ -315,6 +336,8 @@ golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -359,6 +382,8 @@ golang.org/x/net v0.0.0-20200602114024-627f9648deb9 h1:pNX+40auqi2JqRfOP1akLGtYc golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201026091529-146b70c837a4 h1:awiuzyrRjJDb+OXi9ceHO3SDxVoN3JER57mhtqkdQBs= golang.org/x/net v0.0.0-20201026091529-146b70c837a4/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d h1:1aflnvSoWWLI2k/dMUAl5lvU1YO4Mb4hz0gh+1rjcxU= +golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -383,6 +408,7 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9 h1:YTzHMGlqJu67/uEo1lBv0n3wBXhXNeUbB1XfN2vmTm0= @@ -391,6 +417,10 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= @@ -475,6 +505,8 @@ maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M= maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA= maunium.net/go/maulogger/v2 v2.1.1 h1:NAZNc6XUFJzgzfewCzVoGkxNAsblLCSSEdtDuIjP0XA= maunium.net/go/maulogger/v2 v2.1.1/go.mod h1:TYWy7wKwz/tIXTpsx8G3mZseIRiC5DoMxSZazOHy68A= +maunium.net/go/maulogger/v2 v2.2.4 h1:oV2GDeM4fx1uRysdpDC0FcrPg+thFicSd9XzPcYMbVY= +maunium.net/go/maulogger/v2 v2.2.4/go.mod h1:TYWy7wKwz/tIXTpsx8G3mZseIRiC5DoMxSZazOHy68A= maunium.net/go/mautrix v0.7.13 h1:qfnvLxvQafvLgHbdZF/+9qs9gyArYf8fUnzfQbjgQaU= maunium.net/go/mautrix v0.7.13/go.mod h1:Jn0ijwXwMFvJFIN9IljirIVKpZQbZP/Dk7pdX2qDmXk= maunium.net/go/mautrix-whatsapp v0.1.4 h1:qlkb3eXcKm1QE6AjrAl9aKxokHlwj7BNr+aUQFXFmWE= diff --git a/main.go b/main.go index 9bc4dda..b4d7d64 100644 --- a/main.go +++ b/main.go @@ -258,8 +258,8 @@ func (bridge *Bridge) Start() { bridge.Provisioning.Init() } bridge.LoadRelaybot() - bridge.Log.Debugln("Checking connection to homeserver") - bridge.ensureConnection() + //bridge.Log.Debugln("Checking connection to homeserver") + //bridge.ensureConnection() bridge.Log.Debugln("Starting application service HTTP server") go bridge.AS.Start() bridge.Log.Debugln("Starting event processor") @@ -377,7 +377,7 @@ func (bridge *Bridge) Main() { func main() { flag.SetHelpTitles( - "matrix-skype - A Matrix-WhatsApp puppeting bridge.", + "matrix-skype - A Matrix-Skype puppeting bridge.", "matrix-skype [-h] [-c ] [-r ] [-g] [--migrate-db ]") err := flag.Parse() if err != nil { diff --git a/matrix.go b/matrix.go index 69fcfde..74a5396 100644 --- a/matrix.go +++ b/matrix.go @@ -366,7 +366,7 @@ func (mx *MatrixHandler) shouldIgnoreEvent(evt *event.Event) bool { fmt.Println() return true } - isCustomPuppet, ok := evt.Content.Raw["net.maunium.whatsapp.puppet"].(bool) + isCustomPuppet, ok := evt.Content.Raw["net.maunium.skype.puppet"].(bool) if ok && isCustomPuppet && mx.bridge.GetPuppetByCustomMXID(evt.Sender) != nil { return true } diff --git a/portal.go b/portal.go index d7489e0..53d2b9c 100644 --- a/portal.go +++ b/portal.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "github.com/gabriel-vasile/mimetype" "maunium.net/go/mautrix/patch" "encoding/hex" @@ -175,6 +176,11 @@ func (portal *Portal) handleMessageLoop() { fmt.Printf("portal handleMessageLoop2: %+v", msg) return } + } else { + if !msg.source.IsInPortal(portal.Key) { + fmt.Println("portal handleMessageLoop InPortal:") + msg.source.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: false}) + } } fmt.Println() fmt.Printf("portal handleMessageLoop3: %+v", msg) @@ -1237,7 +1243,7 @@ func (portal *Portal) CreateMatrixRoom(user *User) error { _ = customPuppet.CustomIntent().EnsureJoined(portal.MXID) } } - user.addPortalToCommunity(portal) + inCommunity := user.addPortalToCommunity(portal) if portal.IsPrivateChat() { puppet := user.bridge.GetPuppetByJID(portal.Key.JID) user.addPuppetToCommunity(puppet) @@ -1249,6 +1255,7 @@ func (portal *Portal) CreateMatrixRoom(user *User) error { } } } + user.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity}) err = portal.FillInitialHistory(user) if err != nil { portal.log.Errorln("Failed to fill history:", err) @@ -1417,11 +1424,11 @@ func (portal *Portal) sendMessage(intent *appservice.IntentAPI, eventType event. wrappedContent := event.Content{Parsed: content} if timestamp != 0 && intent.IsCustomPuppet { wrappedContent.Raw = map[string]interface{}{ - "net.maunium.whatsapp.puppet": intent.IsCustomPuppet, + "net.maunium.skype.puppet": intent.IsCustomPuppet, } } fmt.Println("portal sendMessage timestamp:", timestamp) - fmt.Printf("portal sendMessage: %+v", content) + fmt.Printf("portal sendMessage: %+v\n", content) if portal.Encrypted && portal.bridge.Crypto != nil { encrypted, err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, wrappedContent) if err != nil { @@ -1474,22 +1481,43 @@ func (portal *Portal) HandleTextMessage(source *User, message skype.Resource) { } } } - // portal.SetReplySkype(content, message) - - fmt.Println() - fmt.Printf("portal HandleTextMessage2: %+v", content) + fmt.Printf("\nportal HandleTextMessage2: %+v", content) _, _ = intent.UserTyping(portal.MXID, false, 0) - resp, err := portal.sendMessage(intent, event.EventMessage, content, message.Timestamp * 1000) - if err != nil { - portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) - return + resp, err := portal.trySendMessage(intent, event.EventMessage, content, source, message) + if err == nil { + portal.finishHandlingSkype(source, &message, resp.EventID) } - fmt.Println() - fmt.Printf("portal HandleTextMessage3: %+v", content) - portal.finishHandlingSkype(source, &message, resp.EventID) } } +func (portal *Portal) trySendMessage(intent *appservice.IntentAPI, eventType event.Type, content interface{}, source *User, message skype.Resource) (resp *mautrix.RespSendEvent, err error) { + resp, err = portal.sendMessage(intent, eventType, content, message.Timestamp * 1000) + if err != nil { + portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) + if strings.Index(err.Error(), "M_UNKNOWN_TOKEN (HTTP 401)") > -1 { + puppet := source.bridge.GetPuppetByJID(source.JID) + err, accessToken := source.UpdateAccessToken(puppet) + if err == nil && accessToken != "" { + intent.AccessToken = accessToken + resp, err = portal.sendMessage(intent, eventType, content, message.Timestamp * 1000) + if err != nil { + portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) + } + } + } else if strings.Index(err.Error(), "M_FORBIDDEN (HTTP 403)") > -1 { + puppet := source.bridge.GetPuppetByJID(message.Jid) + intentP := puppet.IntentFor(portal) + _, err = intentP.InviteUser(portal.MXID, &mautrix.ReqInviteUser{ + UserID: intent.UserID, + }) + if err == nil { + resp, err = portal.sendMessage(intent, eventType, content, message.Timestamp * 1000) + } + } + } + return +} + func (portal *Portal) HandleLocationMessageSkype(source *User, message skype.Resource) { intent, endHandlePrivateChatFromMe := portal.startHandlingSkype(source, message) if endHandlePrivateChatFromMe != nil { @@ -1518,12 +1546,17 @@ func (portal *Portal) HandleLocationMessageSkype(source *User, message skype.Res // portal.SetReplySkype(content, message) _, _ = intent.UserTyping(portal.MXID, false, 0) - resp, err := portal.sendMessage(intent, event.EventMessage, content, message.Timestamp * 1000) - if err != nil { - portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) - return + + resp, err := portal.trySendMessage(intent, event.EventMessage, content, source, message) + if err == nil { + portal.finishHandlingSkype(source, &message, resp.EventID) } - portal.finishHandlingSkype(source, &message, resp.EventID) + //resp, err := portal.sendMessage(intent, event.EventMessage, content, message.Timestamp * 1000) + //if err != nil { + // portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) + // return + //} + //portal.finishHandlingSkype(source, &message, resp.EventID) } func (portal *Portal) HandleContactMessageSkype(source *User, message skype.Resource) { @@ -1548,24 +1581,28 @@ func (portal *Portal) HandleContactMessageSkype(source *User, message skype.Reso // portal.SetReplySkype(content, message) _, _ = intent.UserTyping(portal.MXID, false, 0) - resp, err := portal.sendMessage(intent, event.EventMessage, content, message.Timestamp * 1000) - if err != nil { - portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) - return + resp, err := portal.trySendMessage(intent, event.EventMessage, content, source, message) + if err == nil { + portal.finishHandlingSkype(source, &message, resp.EventID) } - portal.finishHandlingSkype(source, &message, resp.EventID) + //resp, err := portal.sendMessage(intent, event.EventMessage, content, message.Timestamp * 1000) + //if err != nil { + // portal.log.Errorfln("Failed to handle message %s: %v", message.Id, err) + // return + //} + //portal.finishHandlingSkype(source, &message, resp.EventID) } func (portal *Portal) sendMediaBridgeFailureSkype(source *User, intent *appservice.IntentAPI, info skype.Resource, downloadErr error) { portal.log.Errorfln("Failed to download media for %s: %v", info.Id, downloadErr) - resp, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{ + resp, err := portal.trySendMessage(intent, event.EventMessage, &event.MessageEventContent{ MsgType: event.MsgNotice, Body: "Failed to bridge media", - }, int64(info.Timestamp*1000)) - if err != nil { - portal.log.Errorfln("Failed to send media download error message for %s: %v", info.Id, err) - } else { + }, source, info) + if err == nil { portal.finishHandlingSkype(source, &info, resp.EventID) + } else { + portal.log.Errorfln("Failed to send media download error message for %s: %v", info.Id, err) } } @@ -1594,6 +1631,11 @@ func (portal *Portal) tryKickUser(userID id.UserID, intent *appservice.IntentAPI } func (portal *Portal) HandleMediaMessageSkype(source *User, download func(conn *skype.Conn, mediaType string) (data []byte, mediaMessage *skype.MediaMessageContent, err error), mediaType string, thumbnail []byte, info skype.Resource, sendAsSticker bool) { + if info.ClientMessageId == "" && info.Content == "" && len(info.SkypeEditedId) > 0 { + portal.HandleMessageRevokeSkype(source, info) + return + } + intent, endHandlePrivateChatFromMe := portal.startHandlingSkype(source, info) if endHandlePrivateChatFromMe != nil { defer endHandlePrivateChatFromMe() @@ -1621,8 +1663,7 @@ func (portal *Portal) HandleMediaMessageSkype(source *User, download func(conn * } // synapse doesn't handle webp well, so we convert it. This can be dropped once https://github.com/matrix-org/synapse/issues/4382 is fixed - mimeType := http.DetectContentType(data) - //length := len(data) + mimeType := mimetype.Detect(data).String() if mimeType == "image/webp" { img, err := decodeWebp(bytes.NewReader(data)) if err != nil { @@ -1744,10 +1785,10 @@ func (portal *Portal) HandleMediaMessageSkype(source *User, download func(conn * if sendAsSticker { eventType = event.EventSticker } - resp, err := portal.sendMessage(intent, eventType, content, info.Timestamp * 1000) - if err != nil { - portal.log.Errorfln("Failed to handle message %s: %v", info.Id, err) - return + + resp, err := portal.trySendMessage(intent, eventType, content, source, info) + if err == nil { + portal.finishHandlingSkype(source, &info, resp.EventID) } //if len(caption) > 0 { @@ -1764,7 +1805,6 @@ func (portal *Portal) HandleMediaMessageSkype(source *User, download func(conn * // } // // TODO store caption mxid? //} - portal.finishHandlingSkype(source, &info, resp.EventID) } func makeMessageID() *string { @@ -2207,6 +2247,9 @@ func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event) { } if err != nil { portal.log.Errorfln("Error handling Matrix event %s: %v", evt.ID, err) + if !sender.Conn.LoggedIn { + err = errors.New("Skype account has been logged out.") + } portal.sendErrorMessage(err) } else { portal.log.Debugfln("Handled Matrix event %s", evt.ID) @@ -2222,7 +2265,7 @@ func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event) { func SendMsg(sender *User, chatThreadId string, content *skype.SendMessage, output chan<- error) (err error) { fmt.Println("message SendMsg type: ", content.Type) - if sender.Conn.LoginInfo != nil { + if sender.Conn.LoginInfo != nil && sender.Conn.LoggedIn != false { switch event.MessageType(content.Type) { case event.MsgText, event.MsgEmote, event.MsgNotice: err = sender.Conn.SendText(chatThreadId, content) diff --git a/user.go b/user.go index 018679c..40a2118 100644 --- a/user.go +++ b/user.go @@ -3,9 +3,11 @@ package main import ( "encoding/json" "encoding/xml" + "errors" "fmt" skype "github.com/kelaresg/go-skypeapi" skypeExt "github.com/kelaresg/matrix-skype/skype-ext" + "maunium.net/go/mautrix/patch" "sort" //"strconv" "strings" @@ -284,6 +286,7 @@ func (user *User) Connect(evenIfNoSession bool) bool { //_ = user.Conn.SetClientName("matrix-skype bridge", "mx-wa", SkypeVersion) user.log.Debugln("skype connection successful") user.Conn.AddHandler(user) + return user.RestoreSession() } @@ -333,7 +336,13 @@ func (user *User) Login(ce *CommandEvent, name string, password string) (err err err = user.Conn.Login(name, password) if err != nil { user.log.Errorln("Failed to login:", err) - ce.Reply(err.Error()) + orgId := "" + if patch.ThirdPartyIdEncrypt { + orgId = patch.Enc(strings.TrimSuffix(user.JID, skypeExt.NewUserSuffix)) + } else { + orgId = strings.TrimSuffix(user.JID, skypeExt.NewUserSuffix) + } + ce.Reply(err.Error() + ", orgid is " + orgId) return err } username := user.Conn.UserProfile.FirstName @@ -343,7 +352,14 @@ func (user *User) Login(ce *CommandEvent, name string, password string) (err err if username == "" { username = user.Conn.UserProfile.Username } - ce.Reply("Successfully logged in as @" + username) + + orgId := "" + if patch.ThirdPartyIdEncrypt { + orgId = patch.Enc(strings.TrimSuffix(user.JID, skypeExt.NewUserSuffix)) + } else { + orgId = strings.TrimSuffix(user.JID, skypeExt.NewUserSuffix) + } + ce.Reply("Successfully logged in as @" + username + ", orgid is " + orgId) user.Conn.Subscribes() // subscribe basic event err = user.Conn.Conn.ContactList(user.Conn.UserProfile.Username) @@ -357,9 +373,10 @@ func (user *User) Login(ce *CommandEvent, name string, password string) (err err userIds = append(userIds, userId) } ce.User.Conn.SubscribeUsers(userIds) - go loopPresence(ce, user) + go loopPresence(user) } go user.Conn.Poll() + go user.monitorSession(ce) user.ConnectionErrors = 0 user.JID = "8:" + user.Conn.UserProfile.Username + skypeExt.NewUserSuffix @@ -370,12 +387,28 @@ func (user *User) Login(ce *CommandEvent, name string, password string) (err err return } -func loopPresence(ce *CommandEvent, user *User) { - for { - if user.Conn.LoggedIn == false { +func (user *User) monitorSession(ce *CommandEvent) { + user.Conn.Refresh = make(chan int) + for x := range user.Conn.Refresh { + fmt.Println("monitorSession: ", x) + if x > 0 { + user.SetSession(user.Conn.LoginInfo) + } else { ce.Reply("Session expired") - break + close(user.Conn.Refresh) + leavePortals(ce) } + } + + item, ok := <- user.Conn.Refresh + if !ok { + user.Conn.Refresh = nil + } + fmt.Println("monitorSession1", item, ok) +} + +func loopPresence(user *User) { + for { for cid, contact := range user.contactsPresence { puppet := user.bridge.GetPuppetByJID(cid) _ = puppet.DefaultIntent().SetPresence(event.Presence(strings.ToLower(contact.Availability))) @@ -430,7 +463,17 @@ func (user *User) tryAutomaticDoublePuppeting() { return } fmt.Println("tryAutomaticDoublePuppeting2", user.MXID) - accessToken, err := puppet.loginWithSharedSecret(user.MXID) + _,_ = user.UpdateAccessToken(puppet) +} + +func (user *User) UpdateAccessToken(puppet *Puppet) (err error, accessToken string) { + if len(user.bridge.Config.Bridge.LoginSharedSecret) == 0 { + return errors.New("you didn't set LoginSharedSecret"), "" + } else if _, homeserver, _ := user.MXID.Parse(); homeserver != user.bridge.Config.Homeserver.Domain { + // user is on another homeserver + return errors.New("user is on another homeServer"), "" + } + accessToken, err = puppet.loginWithSharedSecret(user.MXID) if err != nil { user.log.Warnln("Failed to login with shared secret:", err) return @@ -441,6 +484,7 @@ func (user *User) tryAutomaticDoublePuppeting() { return } user.log.Infoln("Successfully automatically enabled custom puppet") + return } func (user *User) intPostLogin() { @@ -463,23 +507,6 @@ func (user *User) intPostLogin() { } } -func (user *User) HandleChatList(chats []skype.Conversation) { - user.log.Infoln("Chat list received") - chatMap := make(map[string]skype.Conversation) - //for _, chat := range user.Conn.Store.Chats { - // chatMap[chat.Jid] = chat - //} - for _, chat := range chats { - cid, _ := chat.Id.(string) - chatMap[cid] = chat - } - select { - case user.chatListReceived <- struct{}{}: - default: - } - go user.syncPortals(chatMap, false) -} - func (user *User) syncPortals(chatMap map[string]skype.Conversation, createAll bool) { if chatMap == nil { chatMap = user.Conn.Store.Chats