provisioning.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bufio"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "net"
  24. "net/http"
  25. "strings"
  26. "time"
  27. "github.com/gorilla/mux"
  28. "github.com/gorilla/websocket"
  29. "go.mau.fi/whatsmeow/appstate"
  30. "go.mau.fi/whatsmeow/types"
  31. "go.mau.fi/whatsmeow"
  32. log "maunium.net/go/maulogger/v2"
  33. "maunium.net/go/mautrix/id"
  34. )
  35. type ProvisioningAPI struct {
  36. bridge *Bridge
  37. log log.Logger
  38. }
  39. func (prov *ProvisioningAPI) Init() {
  40. prov.log = prov.bridge.Log.Sub("Provisioning")
  41. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  42. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  43. r.Use(prov.AuthMiddleware)
  44. r.HandleFunc("/v1/ping", prov.Ping).Methods(http.MethodGet)
  45. r.HandleFunc("/v1/login", prov.Login).Methods(http.MethodGet)
  46. r.HandleFunc("/v1/logout", prov.Logout).Methods(http.MethodPost)
  47. r.HandleFunc("/v1/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  48. r.HandleFunc("/v1/disconnect", prov.Disconnect).Methods(http.MethodPost)
  49. r.HandleFunc("/v1/reconnect", prov.Reconnect).Methods(http.MethodPost)
  50. r.HandleFunc("/v1/sync/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
  51. r.HandleFunc("/v1/contacts", prov.ListContacts).Methods(http.MethodGet)
  52. r.HandleFunc("/v1/groups", prov.ListGroups).Methods(http.MethodGet)
  53. r.HandleFunc("/v1/resolve_identifier/{number}", prov.ResolveIdentifier).Methods(http.MethodGet)
  54. r.HandleFunc("/v1/bulk_resolve_identifier", prov.BulkResolveIdentifier).Methods(http.MethodPost)
  55. r.HandleFunc("/v1/pm/{number}", prov.StartPM).Methods(http.MethodPost)
  56. r.HandleFunc("/v1/open/{groupID}", prov.OpenGroup).Methods(http.MethodPost)
  57. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  58. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  59. // Deprecated, just use /disconnect
  60. r.HandleFunc("/v1/delete_connection", prov.Disconnect).Methods(http.MethodPost)
  61. }
  62. type responseWrap struct {
  63. http.ResponseWriter
  64. statusCode int
  65. }
  66. var _ http.Hijacker = (*responseWrap)(nil)
  67. func (rw *responseWrap) WriteHeader(statusCode int) {
  68. rw.ResponseWriter.WriteHeader(statusCode)
  69. rw.statusCode = statusCode
  70. }
  71. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  72. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  73. if !ok {
  74. return nil, nil, errors.New("response does not implement http.Hijacker")
  75. }
  76. return hijacker.Hijack()
  77. }
  78. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  79. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  80. auth := r.Header.Get("Authorization")
  81. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  82. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  83. for _, part := range authParts {
  84. part = strings.TrimSpace(part)
  85. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  86. auth = part[len("net.maunium.whatsapp.auth-"):]
  87. break
  88. }
  89. }
  90. } else if strings.HasPrefix(auth, "Bearer ") {
  91. auth = auth[len("Bearer "):]
  92. }
  93. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  94. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  95. "error": "Invalid auth token",
  96. "errcode": "M_FORBIDDEN",
  97. })
  98. return
  99. }
  100. userID := r.URL.Query().Get("user_id")
  101. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  102. start := time.Now()
  103. wWrap := &responseWrap{w, 200}
  104. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  105. duration := time.Now().Sub(start).Seconds()
  106. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  107. })
  108. }
  109. type Error struct {
  110. Success bool `json:"success"`
  111. Error string `json:"error"`
  112. ErrCode string `json:"errcode"`
  113. }
  114. type Response struct {
  115. Success bool `json:"success"`
  116. Status string `json:"status"`
  117. }
  118. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  119. user := r.Context().Value("user").(*User)
  120. if user.Session == nil && user.Client == nil {
  121. jsonResponse(w, http.StatusNotFound, Error{
  122. Error: "Nothing to purge: no session information stored and no active connection.",
  123. ErrCode: "no session",
  124. })
  125. return
  126. }
  127. user.DeleteConnection()
  128. user.DeleteSession()
  129. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  130. user.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  131. }
  132. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  133. user := r.Context().Value("user").(*User)
  134. if user.Client == nil {
  135. jsonResponse(w, http.StatusNotFound, Error{
  136. Error: "You don't have a WhatsApp connection.",
  137. ErrCode: "no connection",
  138. })
  139. return
  140. }
  141. user.DeleteConnection()
  142. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  143. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  144. }
  145. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  146. user := r.Context().Value("user").(*User)
  147. if user.Client == nil {
  148. if user.Session == nil {
  149. jsonResponse(w, http.StatusForbidden, Error{
  150. Error: "No existing connection and no session. Please log in first.",
  151. ErrCode: "no session",
  152. })
  153. } else {
  154. user.Connect()
  155. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  156. }
  157. } else {
  158. user.DeleteConnection()
  159. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  160. user.Connect()
  161. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  162. }
  163. }
  164. func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
  165. user := r.Context().Value("user").(*User)
  166. if user == nil || user.Client == nil {
  167. jsonResponse(w, http.StatusNotFound, Error{
  168. Error: "User is not connected to WhatsApp",
  169. ErrCode: "no session",
  170. })
  171. return
  172. }
  173. vars := mux.Vars(r)
  174. nameStr := vars["name"]
  175. if len(nameStr) == 0 {
  176. jsonResponse(w, http.StatusBadRequest, Error{
  177. Error: "The `name` parameter is required",
  178. ErrCode: "missing-name-param",
  179. })
  180. return
  181. }
  182. var name appstate.WAPatchName
  183. for _, existingName := range appstate.AllPatchNames {
  184. if nameStr == string(existingName) {
  185. name = existingName
  186. }
  187. }
  188. if len(name) == 0 {
  189. jsonResponse(w, http.StatusBadRequest, Error{
  190. Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
  191. ErrCode: "invalid-name-param",
  192. })
  193. return
  194. }
  195. fullStr := r.URL.Query().Get("full")
  196. fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
  197. err := user.Client.FetchAppState(name, fullSync, false)
  198. if err != nil {
  199. jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
  200. } else {
  201. jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
  202. }
  203. }
  204. func (prov *ProvisioningAPI) ListContacts(w http.ResponseWriter, r *http.Request) {
  205. if user := r.Context().Value("user").(*User); user.Session == nil {
  206. jsonResponse(w, http.StatusBadRequest, Error{
  207. Error: "User is not logged into WhatsApp",
  208. ErrCode: "no session",
  209. })
  210. } else if contacts, err := user.Session.Contacts.GetAllContacts(); err != nil {
  211. prov.log.Errorfln("Failed to fetch %s's contacts: %v", user.MXID, err)
  212. jsonResponse(w, http.StatusInternalServerError, Error{
  213. Error: "Internal server error while fetching contact list",
  214. ErrCode: "failed to get contacts",
  215. })
  216. } else {
  217. jsonResponse(w, http.StatusOK, contacts)
  218. }
  219. }
  220. func (prov *ProvisioningAPI) ListGroups(w http.ResponseWriter, r *http.Request) {
  221. if user := r.Context().Value("user").(*User); user.Session == nil {
  222. jsonResponse(w, http.StatusBadRequest, Error{
  223. Error: "User is not logged into WhatsApp",
  224. ErrCode: "no session",
  225. })
  226. } else if groups, err := user.getCachedGroupList(); err != nil {
  227. prov.log.Errorfln("Failed to fetch %s's groups: %v", user.MXID, err)
  228. jsonResponse(w, http.StatusInternalServerError, Error{
  229. Error: "Internal server error while fetching group list",
  230. ErrCode: "failed to get groups",
  231. })
  232. } else {
  233. jsonResponse(w, http.StatusOK, groups)
  234. }
  235. }
  236. type OtherUserInfo struct {
  237. MXID id.UserID `json:"mxid"`
  238. JID types.JID `json:"jid"`
  239. Name string `json:"displayname"`
  240. Avatar id.ContentURI `json:"avatar_url"`
  241. }
  242. type PortalInfo struct {
  243. RoomID id.RoomID `json:"room_id"`
  244. OtherUser *OtherUserInfo `json:"other_user,omitempty"`
  245. GroupInfo *types.GroupInfo `json:"group_info,omitempty"`
  246. JustCreated bool `json:"just_created"`
  247. }
  248. func looksEmaily(str string) bool {
  249. for _, char := range str {
  250. // Characters that are usually in emails, but shouldn't be in phone numbers
  251. if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char == '@' {
  252. return true
  253. }
  254. }
  255. return false
  256. }
  257. func (prov *ProvisioningAPI) resolveIdentifier(w http.ResponseWriter, r *http.Request) (types.JID, *User) {
  258. number, _ := mux.Vars(r)["number"]
  259. if strings.HasSuffix(number, "@"+types.DefaultUserServer) {
  260. jid, _ := types.ParseJID(number)
  261. number = "+" + jid.User
  262. }
  263. if looksEmaily(number) {
  264. jsonResponse(w, http.StatusBadRequest, Error{
  265. Error: "WhatsApp only supports phone numbers as user identifiers",
  266. ErrCode: "number looks like email",
  267. })
  268. } else if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  269. jsonResponse(w, http.StatusBadRequest, Error{
  270. Error: "User is not logged into WhatsApp",
  271. ErrCode: "no session",
  272. })
  273. } else if resp, err := user.Client.IsOnWhatsApp([]string{number}); err != nil {
  274. jsonResponse(w, http.StatusInternalServerError, Error{
  275. Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
  276. ErrCode: "error checking number",
  277. })
  278. } else if len(resp) == 0 {
  279. jsonResponse(w, http.StatusInternalServerError, Error{
  280. Error: "Didn't get a response to checking if the number is on WhatsApp",
  281. ErrCode: "error checking number",
  282. })
  283. } else if !resp[0].IsIn {
  284. jsonResponse(w, http.StatusNotFound, Error{
  285. Error: fmt.Sprintf("The server said +%s is not on WhatsApp", resp[0].JID.User),
  286. ErrCode: "not on whatsapp",
  287. })
  288. } else {
  289. return resp[0].JID, user
  290. }
  291. return types.EmptyJID, nil
  292. }
  293. func (prov *ProvisioningAPI) StartPM(w http.ResponseWriter, r *http.Request) {
  294. jid, user := prov.resolveIdentifier(w, r)
  295. if jid.IsEmpty() || user == nil {
  296. // resolveIdentifier already responded with an error
  297. return
  298. }
  299. portal, puppet, justCreated, err := user.StartPM(jid, "provisioning API PM")
  300. if err != nil {
  301. jsonResponse(w, http.StatusInternalServerError, Error{
  302. Error: fmt.Sprintf("Failed to create portal: %v", err),
  303. })
  304. }
  305. status := http.StatusOK
  306. if justCreated {
  307. status = http.StatusCreated
  308. }
  309. jsonResponse(w, status, PortalInfo{
  310. RoomID: portal.MXID,
  311. OtherUser: &OtherUserInfo{
  312. JID: puppet.JID,
  313. MXID: puppet.MXID,
  314. Name: puppet.Displayname,
  315. Avatar: puppet.AvatarURL,
  316. },
  317. JustCreated: justCreated,
  318. })
  319. }
  320. func (prov *ProvisioningAPI) ResolveIdentifier(w http.ResponseWriter, r *http.Request) {
  321. jid, user := prov.resolveIdentifier(w, r)
  322. if jid.IsEmpty() || user == nil {
  323. // resolveIdentifier already responded with an error
  324. return
  325. }
  326. portal := user.GetPortalByJID(jid)
  327. puppet := user.bridge.GetPuppetByJID(jid)
  328. jsonResponse(w, http.StatusOK, PortalInfo{
  329. RoomID: portal.MXID,
  330. OtherUser: &OtherUserInfo{
  331. JID: puppet.JID,
  332. MXID: puppet.MXID,
  333. Name: puppet.Displayname,
  334. Avatar: puppet.AvatarURL,
  335. },
  336. })
  337. }
  338. type ReqBulkResolveIdentifier struct {
  339. Numbers []string `json:"numbers"`
  340. }
  341. func (prov *ProvisioningAPI) BulkResolveIdentifier(w http.ResponseWriter, r *http.Request) {
  342. var req ReqBulkResolveIdentifier
  343. var resp []types.IsOnWhatsAppResponse
  344. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  345. jsonResponse(w, http.StatusBadRequest, Error{
  346. Error: "Failed to parse request JSON",
  347. ErrCode: "bad json",
  348. })
  349. } else if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  350. jsonResponse(w, http.StatusBadRequest, Error{
  351. Error: "User is not logged into WhatsApp",
  352. ErrCode: "no session",
  353. })
  354. } else if resp, err = user.Client.IsOnWhatsApp(req.Numbers); err != nil {
  355. jsonResponse(w, http.StatusInternalServerError, Error{
  356. Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
  357. ErrCode: "error checking number",
  358. })
  359. } else {
  360. jsonResponse(w, http.StatusOK, resp)
  361. }
  362. }
  363. func (prov *ProvisioningAPI) OpenGroup(w http.ResponseWriter, r *http.Request) {
  364. groupID, _ := mux.Vars(r)["groupID"]
  365. if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  366. jsonResponse(w, http.StatusBadRequest, Error{
  367. Error: "User is not logged into WhatsApp",
  368. ErrCode: "no session",
  369. })
  370. } else if jid, err := types.ParseJID(groupID); err != nil || jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  371. jsonResponse(w, http.StatusBadRequest, Error{
  372. Error: "Invalid group ID",
  373. ErrCode: "invalid group id",
  374. })
  375. } else if info, err := user.Client.GetGroupInfo(jid); err != nil {
  376. // TODO return better responses for different errors (like ErrGroupNotFound and ErrNotInGroup)
  377. jsonResponse(w, http.StatusInternalServerError, Error{
  378. Error: fmt.Sprintf("Failed to get group info: %v", err),
  379. ErrCode: "error getting group info",
  380. })
  381. } else {
  382. prov.log.Debugln("Importing", jid, "for", user.MXID)
  383. portal := user.GetPortalByJID(info.JID)
  384. status := http.StatusOK
  385. if len(portal.MXID) == 0 {
  386. err = portal.CreateMatrixRoom(user, info, true, true)
  387. if err != nil {
  388. jsonResponse(w, http.StatusInternalServerError, Error{
  389. Error: fmt.Sprintf("Failed to create portal: %v", err),
  390. })
  391. return
  392. }
  393. status = http.StatusCreated
  394. }
  395. jsonResponse(w, status, PortalInfo{
  396. RoomID: portal.MXID,
  397. GroupInfo: info,
  398. JustCreated: status == http.StatusCreated,
  399. })
  400. }
  401. }
  402. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  403. user := r.Context().Value("user").(*User)
  404. wa := map[string]interface{}{
  405. "has_session": user.Session != nil,
  406. "management_room": user.ManagementRoom,
  407. "conn": nil,
  408. }
  409. if !user.JID.IsEmpty() {
  410. wa["jid"] = user.JID.String()
  411. wa["phone"] = "+" + user.JID.User
  412. wa["device"] = user.JID.Device
  413. if user.Session != nil {
  414. wa["platform"] = user.Session.Platform
  415. }
  416. }
  417. if user.Client != nil {
  418. wa["conn"] = map[string]interface{}{
  419. "is_connected": user.Client.IsConnected(),
  420. "is_logged_in": user.Client.IsLoggedIn(),
  421. }
  422. }
  423. resp := map[string]interface{}{
  424. "mxid": user.MXID,
  425. "admin": user.Admin,
  426. "whitelisted": user.Whitelisted,
  427. "relay_whitelisted": user.RelayWhitelisted,
  428. "whatsapp": wa,
  429. }
  430. jsonResponse(w, http.StatusOK, resp)
  431. }
  432. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  433. w.Header().Add("Content-Type", "application/json")
  434. w.WriteHeader(status)
  435. _ = json.NewEncoder(w).Encode(response)
  436. }
  437. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  438. user := r.Context().Value("user").(*User)
  439. if user.Session == nil {
  440. jsonResponse(w, http.StatusNotFound, Error{
  441. Error: "You're not logged in",
  442. ErrCode: "not logged in",
  443. })
  444. return
  445. }
  446. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  447. if user.Client == nil {
  448. if !force {
  449. jsonResponse(w, http.StatusNotFound, Error{
  450. Error: "You're not connected",
  451. ErrCode: "not connected",
  452. })
  453. }
  454. } else {
  455. err := user.Client.Logout()
  456. if err != nil {
  457. user.log.Warnln("Error while logging out:", err)
  458. if !force {
  459. jsonResponse(w, http.StatusInternalServerError, Error{
  460. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  461. ErrCode: err.Error(),
  462. })
  463. return
  464. }
  465. } else {
  466. user.Session = nil
  467. }
  468. user.DeleteConnection()
  469. }
  470. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  471. user.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  472. user.DeleteSession()
  473. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  474. }
  475. var upgrader = websocket.Upgrader{
  476. CheckOrigin: func(r *http.Request) bool {
  477. return true
  478. },
  479. Subprotocols: []string{"net.maunium.whatsapp.login"},
  480. }
  481. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  482. userID := r.URL.Query().Get("user_id")
  483. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  484. c, err := upgrader.Upgrade(w, r, nil)
  485. if err != nil {
  486. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  487. return
  488. }
  489. defer func() {
  490. err := c.Close()
  491. if err != nil {
  492. user.log.Debugln("Error closing websocket:", err)
  493. }
  494. }()
  495. go func() {
  496. // Read everything so SetCloseHandler() works
  497. for {
  498. _, _, err = c.ReadMessage()
  499. if err != nil {
  500. break
  501. }
  502. }
  503. }()
  504. ctx, cancel := context.WithCancel(context.Background())
  505. c.SetCloseHandler(func(code int, text string) error {
  506. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  507. cancel()
  508. return nil
  509. })
  510. qrChan, err := user.Login(ctx)
  511. if err != nil {
  512. user.log.Errorln("Failed to log in from provisioning API:", err)
  513. if errors.Is(err, ErrAlreadyLoggedIn) {
  514. go user.Connect()
  515. _ = c.WriteJSON(Error{
  516. Error: "You're already logged into WhatsApp",
  517. ErrCode: "already logged in",
  518. })
  519. } else {
  520. _ = c.WriteJSON(Error{
  521. Error: "Failed to connect to WhatsApp",
  522. ErrCode: "connection error",
  523. })
  524. }
  525. }
  526. user.log.Debugln("Started login via provisioning API")
  527. Segment.Track(user.MXID, "$login_start")
  528. for {
  529. select {
  530. case evt := <-qrChan:
  531. switch evt.Event {
  532. case whatsmeow.QRChannelSuccess.Event:
  533. jid := user.Client.Store.ID
  534. user.log.Debugln("Successful login as", jid, "via provisioning API")
  535. Segment.Track(user.MXID, "$login_success")
  536. _ = c.WriteJSON(map[string]interface{}{
  537. "success": true,
  538. "jid": jid,
  539. "phone": fmt.Sprintf("+%s", jid.User),
  540. "platform": user.Client.Store.Platform,
  541. })
  542. if userTimezone := r.URL.Query().Get("tz"); userTimezone != "" {
  543. user.Timezone = userTimezone
  544. user.Update()
  545. }
  546. case whatsmeow.QRChannelTimeout.Event:
  547. user.log.Debugln("Login via provisioning API timed out")
  548. errCode := "login timed out"
  549. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  550. _ = c.WriteJSON(Error{
  551. Error: "QR code scan timed out. Please try again.",
  552. ErrCode: errCode,
  553. })
  554. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  555. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  556. errCode := "unexpected event"
  557. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  558. _ = c.WriteJSON(Error{
  559. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  560. ErrCode: errCode,
  561. })
  562. case whatsmeow.QRChannelClientOutdated.Event:
  563. user.log.Debugln("Login via provisioning API failed due to outdated client")
  564. errCode := "bridge outdated"
  565. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  566. _ = c.WriteJSON(Error{
  567. Error: "Got client outdated error while waiting for QRs. The bridge must be updated to continue.",
  568. ErrCode: errCode,
  569. })
  570. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  571. errCode := "multidevice not enabled"
  572. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  573. _ = c.WriteJSON(Error{
  574. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  575. ErrCode: errCode,
  576. })
  577. continue
  578. case "error":
  579. errCode := "fatal error"
  580. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  581. _ = c.WriteJSON(Error{
  582. Error: "Fatal error while logging in",
  583. ErrCode: errCode,
  584. })
  585. case "code":
  586. Segment.Track(user.MXID, "$qrcode_retrieved")
  587. _ = c.WriteJSON(map[string]interface{}{
  588. "code": evt.Code,
  589. "timeout": int(evt.Timeout.Seconds()),
  590. })
  591. continue
  592. }
  593. return
  594. case <-ctx.Done():
  595. return
  596. }
  597. }
  598. }