2020-02-09 19:32:14 +01:00
|
|
|
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
|
2022-02-17 14:14:53 +01:00
|
|
|
// Copyright (C) 2022 Tulir Asokan
|
2020-02-09 19:32:14 +01:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
2021-03-15 17:06:16 +01:00
|
|
|
|
2020-02-09 19:32:14 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-02-09 16:03:34 +01:00
|
|
|
"bufio"
|
2020-02-09 19:32:14 +01:00
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2021-02-05 18:26:09 +01:00
|
|
|
"errors"
|
2021-10-27 14:54:34 +02:00
|
|
|
"fmt"
|
2021-02-09 16:03:34 +01:00
|
|
|
"net"
|
2020-02-09 19:32:14 +01:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
2021-02-09 16:03:34 +01:00
|
|
|
"time"
|
2020-02-09 19:32:14 +01:00
|
|
|
|
2022-01-10 11:31:13 +01:00
|
|
|
"github.com/gorilla/mux"
|
2020-02-09 19:32:14 +01:00
|
|
|
"github.com/gorilla/websocket"
|
2022-02-17 14:14:53 +01:00
|
|
|
|
2022-01-10 11:31:13 +01:00
|
|
|
"go.mau.fi/whatsmeow/appstate"
|
2022-02-17 14:14:53 +01:00
|
|
|
"go.mau.fi/whatsmeow/types"
|
2020-02-09 19:32:14 +01:00
|
|
|
|
2021-10-27 14:54:34 +02:00
|
|
|
"go.mau.fi/whatsmeow"
|
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
log "maunium.net/go/maulogger/v2"
|
2021-05-12 13:54:40 +02:00
|
|
|
|
2021-02-17 00:21:30 +01:00
|
|
|
"maunium.net/go/mautrix/id"
|
2020-02-09 19:32:14 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type ProvisioningAPI struct {
|
2022-03-10 06:58:14 +01:00
|
|
|
bridge *Bridge
|
|
|
|
log log.Logger
|
|
|
|
segment *Segment
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) Init() {
|
|
|
|
prov.log = prov.bridge.Log.Sub("Provisioning")
|
2022-03-10 06:58:14 +01:00
|
|
|
|
|
|
|
// Set up segment
|
|
|
|
prov.segment = NewSegment(prov.bridge.Config.AppService.Provisioning.SegmentKey, prov.log)
|
|
|
|
|
2020-02-09 19:32:14 +01:00
|
|
|
prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
|
|
|
|
r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
|
|
|
|
r.Use(prov.AuthMiddleware)
|
2022-03-01 19:39:05 +01:00
|
|
|
r.HandleFunc("/v1/ping", prov.Ping).Methods(http.MethodGet)
|
|
|
|
r.HandleFunc("/v1/login", prov.Login).Methods(http.MethodGet)
|
|
|
|
r.HandleFunc("/v1/logout", prov.Logout).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/delete_session", prov.DeleteSession).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/disconnect", prov.Disconnect).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/reconnect", prov.Reconnect).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/sync/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/contacts", prov.ListContacts).Methods(http.MethodGet)
|
|
|
|
r.HandleFunc("/v1/groups", prov.ListGroups).Methods(http.MethodGet)
|
|
|
|
r.HandleFunc("/v1/pm/{number}", prov.StartPM).Methods(http.MethodPost)
|
|
|
|
r.HandleFunc("/v1/open/{groupID}", prov.OpenGroup).Methods(http.MethodPost)
|
2021-06-01 14:19:47 +02:00
|
|
|
prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
|
|
|
|
prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
|
2021-10-27 14:54:34 +02:00
|
|
|
|
|
|
|
// Deprecated, just use /disconnect
|
2022-03-01 19:39:05 +01:00
|
|
|
r.HandleFunc("/v1/delete_connection", prov.Disconnect).Methods(http.MethodPost)
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
|
2021-02-09 16:03:34 +01:00
|
|
|
type responseWrap struct {
|
|
|
|
http.ResponseWriter
|
|
|
|
statusCode int
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ http.Hijacker = (*responseWrap)(nil)
|
|
|
|
|
|
|
|
func (rw *responseWrap) WriteHeader(statusCode int) {
|
|
|
|
rw.ResponseWriter.WriteHeader(statusCode)
|
|
|
|
rw.statusCode = statusCode
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
|
|
|
hijacker, ok := rw.ResponseWriter.(http.Hijacker)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil, errors.New("response does not implement http.Hijacker")
|
|
|
|
}
|
|
|
|
return hijacker.Hijack()
|
|
|
|
}
|
|
|
|
|
2020-02-09 19:32:14 +01:00
|
|
|
func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
auth := r.Header.Get("Authorization")
|
2020-11-24 15:48:29 +01:00
|
|
|
if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
|
|
|
|
authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
|
|
|
|
for _, part := range authParts {
|
|
|
|
part = strings.TrimSpace(part)
|
|
|
|
if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
|
|
|
|
auth = part[len("net.maunium.whatsapp.auth-"):]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if strings.HasPrefix(auth, "Bearer ") {
|
|
|
|
auth = auth[len("Bearer "):]
|
|
|
|
}
|
2020-02-09 19:32:14 +01:00
|
|
|
if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
|
|
|
|
jsonResponse(w, http.StatusForbidden, map[string]interface{}{
|
|
|
|
"error": "Invalid auth token",
|
|
|
|
"errcode": "M_FORBIDDEN",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
userID := r.URL.Query().Get("user_id")
|
2020-05-08 21:32:22 +02:00
|
|
|
user := prov.bridge.GetUserByMXID(id.UserID(userID))
|
2021-02-09 16:03:34 +01:00
|
|
|
start := time.Now()
|
|
|
|
wWrap := &responseWrap{w, 200}
|
|
|
|
h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
|
|
|
|
duration := time.Now().Sub(start).Seconds()
|
|
|
|
prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
|
2020-02-09 19:32:14 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
type Error struct {
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Error string `json:"error"`
|
|
|
|
ErrCode string `json:"errcode"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Response struct {
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Status string `json:"status"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
2021-10-22 19:14:34 +02:00
|
|
|
if user.Session == nil && user.Client == nil {
|
2020-02-09 19:32:14 +01:00
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: "Nothing to purge: no session information stored and no active connection.",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
user.DeleteConnection()
|
2021-10-22 19:14:34 +02:00
|
|
|
user.DeleteSession()
|
2020-02-09 19:32:14 +01:00
|
|
|
jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
|
2022-03-10 21:20:10 +01:00
|
|
|
user.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
2021-10-22 19:14:34 +02:00
|
|
|
if user.Client == nil {
|
2020-02-09 19:32:14 +01:00
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: "You don't have a WhatsApp connection.",
|
|
|
|
ErrCode: "no connection",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-10-22 19:14:34 +02:00
|
|
|
user.DeleteConnection()
|
2020-02-09 19:32:14 +01:00
|
|
|
jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
|
2021-10-29 21:03:00 +02:00
|
|
|
user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
2021-10-22 19:14:34 +02:00
|
|
|
if user.Client == nil {
|
2020-02-09 19:32:14 +01:00
|
|
|
if user.Session == nil {
|
|
|
|
jsonResponse(w, http.StatusForbidden, Error{
|
|
|
|
Error: "No existing connection and no session. Please log in first.",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
} else {
|
2021-10-27 14:54:34 +02:00
|
|
|
user.Connect()
|
|
|
|
jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
2021-10-27 14:54:34 +02:00
|
|
|
} else {
|
|
|
|
user.DeleteConnection()
|
2021-10-29 21:03:00 +02:00
|
|
|
user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
|
2021-10-27 14:54:34 +02:00
|
|
|
user.Connect()
|
|
|
|
jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-10 11:31:13 +01:00
|
|
|
func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
|
|
|
if user == nil || user.Client == nil {
|
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: "User is not connected to WhatsApp",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
vars := mux.Vars(r)
|
|
|
|
nameStr := vars["name"]
|
|
|
|
if len(nameStr) == 0 {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "The `name` parameter is required",
|
|
|
|
ErrCode: "missing-name-param",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var name appstate.WAPatchName
|
|
|
|
for _, existingName := range appstate.AllPatchNames {
|
|
|
|
if nameStr == string(existingName) {
|
|
|
|
name = existingName
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(name) == 0 {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
|
|
|
|
ErrCode: "invalid-name-param",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fullStr := r.URL.Query().Get("full")
|
|
|
|
fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
|
|
|
|
err := user.Client.FetchAppState(name, fullSync, false)
|
|
|
|
if err != nil {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
|
|
|
|
} else {
|
|
|
|
jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-17 14:14:53 +01:00
|
|
|
func (prov *ProvisioningAPI) ListContacts(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if user := r.Context().Value("user").(*User); user.Session == nil {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "User is not logged into WhatsApp",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
} else if contacts, err := user.Session.Contacts.GetAllContacts(); err != nil {
|
|
|
|
prov.log.Errorfln("Failed to fetch %s's contacts: %v", user.MXID, err)
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: "Internal server error while fetching contact list",
|
|
|
|
ErrCode: "failed to get contacts",
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
jsonResponse(w, http.StatusOK, contacts)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-01 19:25:46 +01:00
|
|
|
func (prov *ProvisioningAPI) ListGroups(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if user := r.Context().Value("user").(*User); user.Session == nil {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "User is not logged into WhatsApp",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
} else if groups, err := user.getCachedGroupList(); err != nil {
|
|
|
|
prov.log.Errorfln("Failed to fetch %s's groups: %v", user.MXID, err)
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: "Internal server error while fetching group list",
|
|
|
|
ErrCode: "failed to get groups",
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
jsonResponse(w, http.StatusOK, groups)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-17 14:14:53 +01:00
|
|
|
type OtherUserInfo struct {
|
|
|
|
MXID id.UserID `json:"mxid"`
|
|
|
|
JID types.JID `json:"jid"`
|
|
|
|
Name string `json:"displayname"`
|
|
|
|
Avatar id.ContentURI `json:"avatar_url"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type PortalInfo struct {
|
2022-03-01 19:25:46 +01:00
|
|
|
RoomID id.RoomID `json:"room_id"`
|
|
|
|
OtherUser *OtherUserInfo `json:"other_user,omitempty"`
|
|
|
|
GroupInfo *types.GroupInfo `json:"group_info,omitempty"`
|
|
|
|
JustCreated bool `json:"just_created"`
|
2022-02-17 14:14:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) StartPM(w http.ResponseWriter, r *http.Request) {
|
|
|
|
number, _ := mux.Vars(r)["number"]
|
|
|
|
if strings.HasSuffix(number, "@"+types.DefaultUserServer) {
|
|
|
|
jid, _ := types.ParseJID(number)
|
|
|
|
number = "+" + jid.User
|
|
|
|
}
|
|
|
|
if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "User is not logged into WhatsApp",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
} else if resp, err := user.Client.IsOnWhatsApp([]string{number}); err != nil {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
|
|
|
|
ErrCode: "error checking number",
|
|
|
|
})
|
|
|
|
} else if len(resp) == 0 {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: "Didn't get a response to checking if the number is on WhatsApp",
|
|
|
|
ErrCode: "error checking number",
|
|
|
|
})
|
|
|
|
} else if !resp[0].IsIn {
|
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: fmt.Sprintf("The server said +%s is not on WhatsApp", resp[0].JID.User),
|
|
|
|
ErrCode: "not on whatsapp",
|
|
|
|
})
|
|
|
|
} else if portal, puppet, justCreated, err := user.StartPM(resp[0].JID, "provisioning API PM"); err != nil {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: fmt.Sprintf("Failed to create portal: %v", err),
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
status := http.StatusOK
|
|
|
|
if justCreated {
|
|
|
|
status = http.StatusCreated
|
|
|
|
}
|
|
|
|
jsonResponse(w, status, PortalInfo{
|
|
|
|
RoomID: portal.MXID,
|
2022-03-01 19:25:46 +01:00
|
|
|
OtherUser: &OtherUserInfo{
|
2022-02-17 14:14:53 +01:00
|
|
|
JID: puppet.JID,
|
|
|
|
MXID: puppet.MXID,
|
|
|
|
Name: puppet.Displayname,
|
|
|
|
Avatar: puppet.AvatarURL,
|
|
|
|
},
|
|
|
|
JustCreated: justCreated,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-01 19:25:46 +01:00
|
|
|
func (prov *ProvisioningAPI) OpenGroup(w http.ResponseWriter, r *http.Request) {
|
|
|
|
groupID, _ := mux.Vars(r)["groupID"]
|
|
|
|
if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "User is not logged into WhatsApp",
|
|
|
|
ErrCode: "no session",
|
|
|
|
})
|
|
|
|
} else if jid, err := types.ParseJID(groupID); err != nil || jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
|
|
|
|
jsonResponse(w, http.StatusBadRequest, Error{
|
|
|
|
Error: "Invalid group ID",
|
|
|
|
ErrCode: "invalid group id",
|
|
|
|
})
|
|
|
|
} else if info, err := user.Client.GetGroupInfo(jid); err != nil {
|
|
|
|
// TODO return better responses for different errors (like ErrGroupNotFound and ErrNotInGroup)
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: fmt.Sprintf("Failed to get group info: %v", err),
|
|
|
|
ErrCode: "error getting group info",
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
prov.log.Debugln("Importing", jid, "for", user.MXID)
|
|
|
|
portal := user.GetPortalByJID(info.JID)
|
|
|
|
status := http.StatusOK
|
|
|
|
if len(portal.MXID) == 0 {
|
|
|
|
err = portal.CreateMatrixRoom(user, info, true)
|
|
|
|
if err != nil {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: fmt.Sprintf("Failed to create portal: %v", err),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
status = http.StatusCreated
|
|
|
|
}
|
|
|
|
jsonResponse(w, status, PortalInfo{
|
|
|
|
RoomID: portal.MXID,
|
|
|
|
GroupInfo: info,
|
|
|
|
JustCreated: status == http.StatusCreated,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-09 19:32:14 +01:00
|
|
|
func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
|
|
|
wa := map[string]interface{}{
|
|
|
|
"has_session": user.Session != nil,
|
|
|
|
"management_room": user.ManagementRoom,
|
|
|
|
"conn": nil,
|
|
|
|
}
|
2021-11-01 17:45:58 +01:00
|
|
|
if !user.JID.IsEmpty() {
|
2021-10-22 19:14:34 +02:00
|
|
|
wa["jid"] = user.JID.String()
|
2021-11-04 11:06:56 +01:00
|
|
|
wa["phone"] = "+" + user.JID.User
|
|
|
|
wa["device"] = user.JID.Device
|
2021-10-22 19:14:34 +02:00
|
|
|
}
|
|
|
|
if user.Client != nil {
|
2020-02-09 19:32:14 +01:00
|
|
|
wa["conn"] = map[string]interface{}{
|
2021-10-22 19:14:34 +02:00
|
|
|
"is_connected": user.Client.IsConnected(),
|
2021-11-30 14:14:56 +01:00
|
|
|
"is_logged_in": user.Client.IsLoggedIn(),
|
2021-01-28 21:46:57 +01:00
|
|
|
}
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
resp := map[string]interface{}{
|
2021-10-28 13:03:55 +02:00
|
|
|
"mxid": user.MXID,
|
|
|
|
"admin": user.Admin,
|
|
|
|
"whitelisted": user.Whitelisted,
|
|
|
|
"relay_whitelisted": user.RelayWhitelisted,
|
|
|
|
"whatsapp": wa,
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
|
|
|
jsonResponse(w, http.StatusOK, resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
|
|
|
|
w.Header().Add("Content-Type", "application/json")
|
|
|
|
w.WriteHeader(status)
|
|
|
|
_ = json.NewEncoder(w).Encode(response)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user := r.Context().Value("user").(*User)
|
|
|
|
if user.Session == nil {
|
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: "You're not logged in",
|
|
|
|
ErrCode: "not logged in",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-11-19 19:08:27 +01:00
|
|
|
force := strings.ToLower(r.URL.Query().Get("force")) != "false"
|
2020-11-19 18:18:34 +01:00
|
|
|
|
2021-10-22 19:14:34 +02:00
|
|
|
if user.Client == nil {
|
2020-11-19 18:18:34 +01:00
|
|
|
if !force {
|
|
|
|
jsonResponse(w, http.StatusNotFound, Error{
|
|
|
|
Error: "You're not connected",
|
|
|
|
ErrCode: "not connected",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} else {
|
2021-10-27 14:54:34 +02:00
|
|
|
err := user.Client.Logout()
|
|
|
|
if err != nil {
|
|
|
|
user.log.Warnln("Error while logging out:", err)
|
|
|
|
if !force {
|
|
|
|
jsonResponse(w, http.StatusInternalServerError, Error{
|
|
|
|
Error: fmt.Sprintf("Unknown error while logging out: %v", err),
|
|
|
|
ErrCode: err.Error(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-10-29 21:03:00 +02:00
|
|
|
} else {
|
|
|
|
user.Session = nil
|
2021-10-27 14:54:34 +02:00
|
|
|
}
|
2021-02-18 22:36:14 +01:00
|
|
|
user.DeleteConnection()
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|
2020-11-19 18:18:34 +01:00
|
|
|
|
|
|
|
user.bridge.Metrics.TrackConnectionState(user.JID, false)
|
2022-03-10 21:20:10 +01:00
|
|
|
user.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
|
2021-10-22 19:14:34 +02:00
|
|
|
user.DeleteSession()
|
2020-02-09 19:32:14 +01:00
|
|
|
jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
|
|
|
|
}
|
|
|
|
|
2020-11-24 15:48:29 +01:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
|
|
return true
|
|
|
|
},
|
|
|
|
Subprotocols: []string{"net.maunium.whatsapp.login"},
|
|
|
|
}
|
2020-02-09 19:32:14 +01:00
|
|
|
|
|
|
|
func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
|
2021-10-27 14:54:34 +02:00
|
|
|
userID := r.URL.Query().Get("user_id")
|
|
|
|
user := prov.bridge.GetUserByMXID(id.UserID(userID))
|
2020-02-09 19:32:14 +01:00
|
|
|
|
2021-10-27 14:54:34 +02:00
|
|
|
c, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
prov.log.Errorln("Failed to upgrade connection to websocket:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
err := c.Close()
|
|
|
|
if err != nil {
|
|
|
|
user.log.Debugln("Error closing websocket:", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
// Read everything so SetCloseHandler() works
|
|
|
|
for {
|
|
|
|
_, _, err = c.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
c.SetCloseHandler(func(code int, text string) error {
|
|
|
|
user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
|
|
|
|
cancel()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
qrChan, err := user.Login(ctx)
|
|
|
|
if err != nil {
|
2022-03-05 20:22:31 +01:00
|
|
|
user.log.Errorln("Failed to log in from provisioning API:", err)
|
2021-10-27 14:54:34 +02:00
|
|
|
if errors.Is(err, ErrAlreadyLoggedIn) {
|
|
|
|
go user.Connect()
|
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "You're already logged into WhatsApp",
|
|
|
|
ErrCode: "already logged in",
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "Failed to connect to WhatsApp",
|
|
|
|
ErrCode: "connection error",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
user.log.Debugln("Started login via provisioning API")
|
2022-03-10 06:58:14 +01:00
|
|
|
prov.segment.Track(user.MXID, "$login_start")
|
2021-10-27 14:54:34 +02:00
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case evt := <-qrChan:
|
2021-12-09 14:54:01 +01:00
|
|
|
switch evt.Event {
|
2021-12-09 14:57:26 +01:00
|
|
|
case whatsmeow.QRChannelSuccess.Event:
|
2021-10-27 14:54:34 +02:00
|
|
|
jid := user.Client.Store.ID
|
|
|
|
user.log.Debugln("Successful login as", jid, "via provisioning API")
|
2022-03-10 06:58:14 +01:00
|
|
|
prov.segment.Track(user.MXID, "$login_success")
|
2021-10-27 14:54:34 +02:00
|
|
|
_ = c.WriteJSON(map[string]interface{}{
|
|
|
|
"success": true,
|
|
|
|
"jid": jid,
|
|
|
|
"phone": fmt.Sprintf("+%s", jid.User),
|
|
|
|
})
|
2021-12-09 14:57:26 +01:00
|
|
|
case whatsmeow.QRChannelTimeout.Event:
|
2021-10-27 14:54:34 +02:00
|
|
|
user.log.Debugln("Login via provisioning API timed out")
|
2022-03-10 06:58:14 +01:00
|
|
|
errCode := "login timed out"
|
|
|
|
prov.segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
|
2021-10-27 14:54:34 +02:00
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "QR code scan timed out. Please try again.",
|
2022-03-10 06:58:14 +01:00
|
|
|
ErrCode: errCode,
|
2021-10-27 14:54:34 +02:00
|
|
|
})
|
2021-12-09 14:57:26 +01:00
|
|
|
case whatsmeow.QRChannelErrUnexpectedEvent.Event:
|
2021-10-28 20:22:34 +02:00
|
|
|
user.log.Debugln("Login via provisioning API failed due to unexpected event")
|
2022-03-10 06:58:14 +01:00
|
|
|
errCode := "unexpected event"
|
|
|
|
prov.segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
|
2021-10-28 20:22:34 +02:00
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
|
2022-03-10 06:58:14 +01:00
|
|
|
ErrCode: errCode,
|
2021-10-28 20:22:34 +02:00
|
|
|
})
|
2022-02-17 14:33:31 +01:00
|
|
|
case whatsmeow.QRChannelClientOutdated.Event:
|
|
|
|
user.log.Debugln("Login via provisioning API failed due to outdated client")
|
2022-03-10 06:58:14 +01:00
|
|
|
errCode := "bridge outdated"
|
|
|
|
prov.segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
|
2022-02-17 14:33:31 +01:00
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "Got client outdated error while waiting for QRs. The bridge must be updated to continue.",
|
2022-03-10 06:58:14 +01:00
|
|
|
ErrCode: errCode,
|
2022-02-17 14:33:31 +01:00
|
|
|
})
|
2021-12-09 14:57:26 +01:00
|
|
|
case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
|
2022-03-10 06:58:14 +01:00
|
|
|
errCode := "multidevice not enabled"
|
|
|
|
prov.segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
|
2021-10-28 20:22:34 +02:00
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
|
2022-03-10 06:58:14 +01:00
|
|
|
ErrCode: errCode,
|
2021-10-28 20:22:34 +02:00
|
|
|
})
|
2021-10-29 20:41:03 +02:00
|
|
|
continue
|
2021-12-09 11:27:31 +01:00
|
|
|
case "error":
|
2022-03-10 06:58:14 +01:00
|
|
|
errCode := "fatal error"
|
|
|
|
prov.segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
|
2021-12-09 11:27:31 +01:00
|
|
|
_ = c.WriteJSON(Error{
|
|
|
|
Error: "Fatal error while logging in",
|
2022-03-10 06:58:14 +01:00
|
|
|
ErrCode: errCode,
|
2021-12-09 11:27:31 +01:00
|
|
|
})
|
|
|
|
case "code":
|
2022-03-10 06:58:14 +01:00
|
|
|
prov.segment.Track(user.MXID, "$qrcode_retrieved")
|
2021-10-27 14:54:34 +02:00
|
|
|
_ = c.WriteJSON(map[string]interface{}{
|
2021-11-15 13:42:06 +01:00
|
|
|
"code": evt.Code,
|
2021-11-15 12:38:10 +01:00
|
|
|
"timeout": int(evt.Timeout.Seconds()),
|
2021-10-27 14:54:34 +02:00
|
|
|
})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2020-02-09 19:32:14 +01:00
|
|
|
}
|