commands.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "fmt"
  19. "strconv"
  20. "strings"
  21. "github.com/Rhymen/go-whatsapp"
  22. "maunium.net/go/maulogger/v2"
  23. "maunium.net/go/mautrix"
  24. "maunium.net/go/mautrix/appservice"
  25. "maunium.net/go/mautrix/event"
  26. "maunium.net/go/mautrix/format"
  27. "maunium.net/go/mautrix/id"
  28. "maunium.net/go/mautrix-whatsapp/database"
  29. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  30. )
  31. type CommandHandler struct {
  32. bridge *Bridge
  33. log maulogger.Logger
  34. }
  35. // NewCommandHandler creates a CommandHandler
  36. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  37. return &CommandHandler{
  38. bridge: bridge,
  39. log: bridge.Log.Sub("Command handler"),
  40. }
  41. }
  42. // CommandEvent stores all data which might be used to handle commands
  43. type CommandEvent struct {
  44. Bot *appservice.IntentAPI
  45. Bridge *Bridge
  46. Handler *CommandHandler
  47. RoomID id.RoomID
  48. User *User
  49. Command string
  50. Args []string
  51. }
  52. // Reply sends a reply to command as notice
  53. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  54. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  55. content.MsgType = event.MsgNotice
  56. room := ce.User.ManagementRoom
  57. if len(room) == 0 {
  58. room = ce.RoomID
  59. }
  60. _, err := ce.Bot.SendMessageEvent(room, event.EventMessage, content)
  61. if err != nil {
  62. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  63. }
  64. }
  65. // Handle handles messages to the bridge
  66. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
  67. args := strings.Split(message, " ")
  68. ce := &CommandEvent{
  69. Bot: handler.bridge.Bot,
  70. Bridge: handler.bridge,
  71. Handler: handler,
  72. RoomID: roomID,
  73. User: user,
  74. Command: strings.ToLower(args[0]),
  75. Args: args[1:],
  76. }
  77. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  78. if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
  79. handler.CommandRelaybot(ce)
  80. } else {
  81. handler.CommandMux(ce)
  82. }
  83. }
  84. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  85. switch ce.Command {
  86. case "relaybot":
  87. handler.CommandRelaybot(ce)
  88. case "login":
  89. handler.CommandLogin(ce)
  90. case "logout-matrix":
  91. handler.CommandLogoutMatrix(ce)
  92. case "help":
  93. handler.CommandHelp(ce)
  94. case "reconnect":
  95. handler.CommandReconnect(ce)
  96. case "disconnect":
  97. handler.CommandDisconnect(ce)
  98. case "ping":
  99. handler.CommandPing(ce)
  100. case "delete-connection":
  101. handler.CommandDeleteConnection(ce)
  102. case "delete-session":
  103. handler.CommandDeleteSession(ce)
  104. case "delete-portal":
  105. handler.CommandDeletePortal(ce)
  106. case "delete-all-portals":
  107. handler.CommandDeleteAllPortals(ce)
  108. case "dev-test":
  109. handler.CommandDevTest(ce)
  110. case "set-pl":
  111. handler.CommandSetPowerLevel(ce)
  112. case "login-matrix", "logout", "sync", "list", "open", "pm":
  113. if !ce.User.HasSession() {
  114. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  115. return
  116. } else if !ce.User.IsConnected() {
  117. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  118. return
  119. }
  120. switch ce.Command {
  121. case "login-matrix":
  122. handler.CommandLoginMatrix(ce)
  123. case "logout":
  124. handler.CommandLogout(ce)
  125. case "sync":
  126. handler.CommandSync(ce)
  127. case "list":
  128. handler.CommandList(ce)
  129. case "open":
  130. handler.CommandOpen(ce)
  131. case "pm":
  132. handler.CommandPM(ce)
  133. }
  134. default:
  135. ce.Reply("Unknown Command")
  136. }
  137. }
  138. func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
  139. if handler.bridge.Relaybot == nil {
  140. ce.Reply("The relaybot is disabled")
  141. } else if !ce.User.Admin {
  142. ce.Reply("Only admins can manage the relaybot")
  143. } else {
  144. if ce.Command == "relaybot" {
  145. if len(ce.Args) == 0 {
  146. ce.Reply("**Usage:** `relaybot <command>`")
  147. return
  148. }
  149. ce.Command = strings.ToLower(ce.Args[0])
  150. ce.Args = ce.Args[1:]
  151. }
  152. ce.User = handler.bridge.Relaybot
  153. handler.CommandMux(ce)
  154. }
  155. }
  156. func (handler *CommandHandler) CommandDevTest(ce *CommandEvent) {
  157. }
  158. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  159. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  160. if portal == nil {
  161. ce.Reply("Not a portal room")
  162. return
  163. }
  164. var level int
  165. var userID id.UserID
  166. var err error
  167. if len(ce.Args) == 1 {
  168. level, err = strconv.Atoi(ce.Args[0])
  169. if err != nil {
  170. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  171. return
  172. }
  173. userID = ce.User.MXID
  174. } else if len(ce.Args) == 2 {
  175. userID = id.UserID(ce.Args[0])
  176. _, _, err := userID.Parse()
  177. if err != nil {
  178. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  179. return
  180. }
  181. level, err = strconv.Atoi(ce.Args[1])
  182. if err != nil {
  183. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  184. return
  185. }
  186. } else {
  187. ce.Reply("**Usage:** `set-pl [user] <level>`")
  188. return
  189. }
  190. intent := portal.MainIntent()
  191. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  192. if err != nil {
  193. ce.Reply("Failed to set power levels: %v", err)
  194. }
  195. }
  196. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  197. // CommandLogin handles login command
  198. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  199. if !ce.User.Connect(true) {
  200. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  201. return
  202. }
  203. ce.User.Login(ce)
  204. }
  205. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  206. // CommandLogout handles !logout command
  207. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  208. if ce.User.Session == nil {
  209. ce.Reply("You're not logged in.")
  210. return
  211. }
  212. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  213. if puppet.CustomMXID != "" {
  214. err := puppet.SwitchCustomMXID("", "")
  215. if err != nil {
  216. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  217. }
  218. }
  219. err := ce.User.Conn.Logout()
  220. if err != nil {
  221. ce.User.log.Warnln("Error while logging out:", err)
  222. ce.Reply("Unknown error while logging out: %v", err)
  223. return
  224. }
  225. _, err = ce.User.Conn.Disconnect()
  226. if err != nil {
  227. ce.User.log.Warnln("Error while disconnecting after logout:", err)
  228. }
  229. ce.User.Conn.RemoveHandlers()
  230. ce.User.Conn = nil
  231. ce.User.removeFromJIDMap()
  232. // TODO this causes a foreign key violation, which should be fixed
  233. //ce.User.JID = ""
  234. ce.User.SetSession(nil)
  235. ce.Reply("Logged out successfully.")
  236. }
  237. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  238. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  239. if ce.User.Session == nil && ce.User.Conn == nil {
  240. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  241. return
  242. }
  243. ce.User.SetSession(nil)
  244. if ce.User.Conn != nil {
  245. _, _ = ce.User.Conn.Disconnect()
  246. ce.User.Conn.RemoveHandlers()
  247. ce.User.Conn = nil
  248. }
  249. ce.Reply("Session information purged")
  250. }
  251. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  252. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  253. if ce.User.Conn == nil {
  254. if ce.User.Session == nil {
  255. ce.Reply("No existing connection and no session. Did you mean `login`?")
  256. } else {
  257. ce.Reply("No existing connection, creating one...")
  258. ce.User.Connect(false)
  259. }
  260. return
  261. }
  262. wasConnected := true
  263. sess, err := ce.User.Conn.Disconnect()
  264. if err == whatsapp.ErrNotConnected {
  265. wasConnected = false
  266. } else if err != nil {
  267. ce.User.log.Warnln("Error while disconnecting:", err)
  268. } else if len(sess.Wid) > 0 {
  269. ce.User.SetSession(&sess)
  270. }
  271. err = ce.User.Conn.Restore()
  272. if err == whatsapp.ErrInvalidSession {
  273. if ce.User.Session != nil {
  274. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  275. var sess whatsapp.Session
  276. sess, err = ce.User.Conn.RestoreWithSession(*ce.User.Session)
  277. if err == nil {
  278. ce.User.SetSession(&sess)
  279. }
  280. } else {
  281. ce.Reply("You are not logged in.")
  282. return
  283. }
  284. } else if err == whatsapp.ErrLoginInProgress {
  285. ce.Reply("A login or reconnection is already in progress.")
  286. return
  287. } else if err == whatsapp.ErrAlreadyLoggedIn {
  288. ce.Reply("You were already connected.")
  289. return
  290. }
  291. if err != nil {
  292. ce.User.log.Warnln("Error while reconnecting:", err)
  293. if err.Error() == "restore session connection timed out" {
  294. ce.Reply("Reconnection timed out. Is WhatsApp on your phone reachable?")
  295. } else {
  296. ce.Reply("Unknown error while reconnecting: %v", err)
  297. }
  298. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  299. sess, err := ce.User.Conn.Disconnect()
  300. if err != nil {
  301. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  302. } else if len(sess.Wid) > 0 {
  303. ce.User.SetSession(&sess)
  304. }
  305. return
  306. }
  307. ce.User.ConnectionErrors = 0
  308. var msg string
  309. if wasConnected {
  310. msg = "Reconnected successfully."
  311. } else {
  312. msg = "Connected successfully."
  313. }
  314. ce.Reply(msg)
  315. ce.User.PostLogin()
  316. }
  317. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  318. if ce.User.Conn == nil {
  319. ce.Reply("You don't have a WhatsApp connection.")
  320. return
  321. }
  322. sess, err := ce.User.Conn.Disconnect()
  323. if err == nil && len(sess.Wid) > 0 {
  324. ce.User.SetSession(&sess)
  325. }
  326. ce.User.Conn.RemoveHandlers()
  327. ce.User.Conn = nil
  328. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  329. }
  330. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  331. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  332. if ce.User.Conn == nil {
  333. ce.Reply("You don't have a WhatsApp connection.")
  334. return
  335. }
  336. sess, err := ce.User.Conn.Disconnect()
  337. if err == whatsapp.ErrNotConnected {
  338. ce.Reply("You were not connected.")
  339. return
  340. } else if err != nil {
  341. ce.User.log.Warnln("Error while disconnecting:", err)
  342. ce.Reply("Unknown error while disconnecting: %v", err)
  343. return
  344. } else if len(sess.Wid) > 0 {
  345. ce.User.SetSession(&sess)
  346. }
  347. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  348. }
  349. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  350. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  351. if ce.User.Session == nil {
  352. if ce.User.IsLoginInProgress() {
  353. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  354. } else {
  355. ce.Reply("You're not logged into WhatsApp.")
  356. }
  357. } else if ce.User.Conn == nil {
  358. ce.Reply("You don't have a WhatsApp connection.")
  359. } else if ok, err := ce.User.Conn.AdminTest(); err != nil {
  360. if ce.User.IsLoginInProgress() {
  361. ce.Reply("Connection not OK: %v, but login in progress", err)
  362. } else {
  363. ce.Reply("Connection not OK: %v", err)
  364. }
  365. } else if !ok {
  366. if ce.User.IsLoginInProgress() {
  367. ce.Reply("Connection not OK, but no error received and login in progress")
  368. } else {
  369. ce.Reply("Connection not OK, but no error received")
  370. }
  371. } else {
  372. ce.Reply("Connection to WhatsApp OK")
  373. }
  374. }
  375. const cmdHelpHelp = `help - Prints this help`
  376. // CommandHelp handles help command
  377. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  378. cmdPrefix := ""
  379. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  380. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  381. }
  382. ce.Reply("* " + strings.Join([]string{
  383. cmdPrefix + cmdHelpHelp,
  384. cmdPrefix + cmdLoginHelp,
  385. cmdPrefix + cmdLogoutHelp,
  386. cmdPrefix + cmdDeleteSessionHelp,
  387. cmdPrefix + cmdReconnectHelp,
  388. cmdPrefix + cmdDisconnectHelp,
  389. cmdPrefix + cmdPingHelp,
  390. cmdPrefix + cmdLoginMatrixHelp,
  391. cmdPrefix + cmdLogoutMatrixHelp,
  392. cmdPrefix + cmdSyncHelp,
  393. cmdPrefix + cmdListHelp,
  394. cmdPrefix + cmdOpenHelp,
  395. cmdPrefix + cmdPMHelp,
  396. }, "\n* "))
  397. }
  398. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  399. // CommandSync handles sync command
  400. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  401. user := ce.User
  402. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  403. ce.Reply("Updating contact and chat list...")
  404. handler.log.Debugln("Importing contacts of", user.MXID)
  405. _, err := user.Conn.Contacts()
  406. if err != nil {
  407. user.log.Errorln("Error updating contacts:", err)
  408. ce.Reply("Failed to sync contact list (see logs for details)")
  409. return
  410. }
  411. handler.log.Debugln("Importing chats of", user.MXID)
  412. _, err = user.Conn.Chats()
  413. if err != nil {
  414. user.log.Errorln("Error updating chats:", err)
  415. ce.Reply("Failed to sync chat list (see logs for details)")
  416. return
  417. }
  418. ce.Reply("Syncing contacts...")
  419. user.syncPuppets(nil)
  420. ce.Reply("Syncing chats...")
  421. user.syncPortals(nil, create)
  422. ce.Reply("Sync complete.")
  423. }
  424. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  425. if !ce.User.Admin {
  426. ce.Reply("Only bridge admins can delete portals")
  427. return
  428. }
  429. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  430. if portal == nil {
  431. ce.Reply("You must be in a portal room to use that command")
  432. return
  433. }
  434. portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  435. portal.Delete()
  436. portal.Cleanup(false)
  437. }
  438. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  439. portals := ce.User.GetPortals()
  440. portalsToDelete := make([]*Portal, 0, len(portals))
  441. for _, portal := range portals {
  442. users := portal.GetUserIDs()
  443. if len(users) == 1 && users[0] == ce.User.MXID {
  444. portalsToDelete = append(portalsToDelete, portal)
  445. }
  446. }
  447. leave := func(portal *Portal) {
  448. if len(portal.MXID) > 0 {
  449. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  450. Reason: "Deleting portal",
  451. UserID: ce.User.MXID,
  452. })
  453. }
  454. }
  455. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  456. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  457. intent := customPuppet.CustomIntent()
  458. leave = func(portal *Portal) {
  459. if len(portal.MXID) > 0 {
  460. _, _ = intent.LeaveRoom(portal.MXID)
  461. _, _ = intent.ForgetRoom(portal.MXID)
  462. }
  463. }
  464. }
  465. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  466. for _, portal := range portalsToDelete {
  467. portal.Delete()
  468. leave(portal)
  469. }
  470. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  471. "You may already continue using the bridge. Use `sync` to recreate portals.")
  472. go func() {
  473. for _, portal := range portalsToDelete {
  474. portal.Cleanup(false)
  475. }
  476. ce.Reply("Finished background cleanup of deleted portal rooms.")
  477. }()
  478. }
  479. const cmdListHelp = `list - Get a list of all contacts and groups.`
  480. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  481. var contacts strings.Builder
  482. var groups strings.Builder
  483. for jid, contact := range ce.User.Conn.Store.Contacts {
  484. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  485. _, _ = fmt.Fprintf(&contacts, "* %s / %s - `%s`\n", contact.Name, contact.Notify, contact.Jid[:len(contact.Jid)-len(whatsappExt.NewUserSuffix)])
  486. } else {
  487. _, _ = fmt.Fprintf(&groups, "* %s - `%s`\n", contact.Name, contact.Jid)
  488. }
  489. }
  490. ce.Reply("### Contacts\n%s\n\n### Groups\n%s", contacts.String(), groups.String())
  491. }
  492. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  493. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  494. if len(ce.Args) == 0 {
  495. ce.Reply("**Usage:** `open <group JID>`")
  496. return
  497. }
  498. user := ce.User
  499. jid := ce.Args[0]
  500. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  501. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)])
  502. return
  503. }
  504. contact, ok := user.Conn.Store.Contacts[jid]
  505. if !ok {
  506. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  507. return
  508. }
  509. handler.log.Debugln("Importing", jid, "for", user)
  510. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  511. if len(portal.MXID) > 0 {
  512. portal.Sync(user, contact)
  513. ce.Reply("Portal room synced.")
  514. } else {
  515. portal.Sync(user, contact)
  516. ce.Reply("Portal room created.")
  517. }
  518. _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  519. }
  520. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  521. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  522. if len(ce.Args) == 0 {
  523. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  524. return
  525. }
  526. force := ce.Args[0] == "--force"
  527. if force {
  528. ce.Args = ce.Args[1:]
  529. }
  530. user := ce.User
  531. number := strings.Join(ce.Args, "")
  532. if number[0] == '+' {
  533. number = number[1:]
  534. }
  535. for _, char := range number {
  536. if char < '0' || char > '9' {
  537. ce.Reply("Invalid phone number.")
  538. return
  539. }
  540. }
  541. jid := number + whatsappExt.NewUserSuffix
  542. handler.log.Debugln("Importing", jid, "for", user)
  543. contact, ok := user.Conn.Store.Contacts[jid]
  544. if !ok {
  545. if !force {
  546. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  547. "To create a portal anyway, use `pm --force <number>`.")
  548. return
  549. }
  550. contact = whatsapp.Contact{Jid: jid}
  551. }
  552. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  553. puppet.Sync(user, contact)
  554. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
  555. if len(portal.MXID) > 0 {
  556. _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  557. if err != nil {
  558. fmt.Println(err)
  559. } else {
  560. ce.Reply("Existing portal room found, invited you to it.")
  561. }
  562. return
  563. }
  564. err := portal.CreateMatrixRoom(user)
  565. if err != nil {
  566. ce.Reply("Failed to create portal room: %v", err)
  567. return
  568. }
  569. ce.Reply("Created portal room and invited you to it.")
  570. }
  571. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  572. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  573. if len(ce.Args) == 0 {
  574. ce.Reply("**Usage:** `login-matrix <access token>`")
  575. return
  576. }
  577. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  578. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  579. if err != nil {
  580. ce.Reply("Failed to switch puppet: %v", err)
  581. return
  582. }
  583. ce.Reply("Successfully switched puppet")
  584. }
  585. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  586. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  587. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  588. if len(puppet.CustomMXID) == 0 {
  589. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  590. return
  591. }
  592. err := puppet.SwitchCustomMXID("", "")
  593. if err != nil {
  594. ce.Reply("Failed to remove custom puppet: %v", err)
  595. return
  596. }
  597. ce.Reply("Successfully removed custom puppet")
  598. }