commands.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "context"
  19. "errors"
  20. "fmt"
  21. "html"
  22. "math"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "github.com/skip2/go-qrcode"
  27. "maunium.net/go/maulogger/v2"
  28. "go.mau.fi/whatsmeow"
  29. "go.mau.fi/whatsmeow/appstate"
  30. "go.mau.fi/whatsmeow/types"
  31. "maunium.net/go/mautrix"
  32. "maunium.net/go/mautrix/appservice"
  33. "maunium.net/go/mautrix/event"
  34. "maunium.net/go/mautrix/format"
  35. "maunium.net/go/mautrix/id"
  36. )
  37. type CommandHandler struct {
  38. bridge *Bridge
  39. log maulogger.Logger
  40. }
  41. // NewCommandHandler creates a CommandHandler
  42. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  43. return &CommandHandler{
  44. bridge: bridge,
  45. log: bridge.Log.Sub("Command handler"),
  46. }
  47. }
  48. // CommandEvent stores all data which might be used to handle commands
  49. type CommandEvent struct {
  50. Bot *appservice.IntentAPI
  51. Bridge *Bridge
  52. Portal *Portal
  53. Handler *CommandHandler
  54. RoomID id.RoomID
  55. User *User
  56. Command string
  57. Args []string
  58. ReplyTo id.EventID
  59. }
  60. // Reply sends a reply to command as notice
  61. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  62. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  63. content.MsgType = event.MsgNotice
  64. intent := ce.Bot
  65. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  66. intent = ce.Portal.MainIntent()
  67. }
  68. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  69. if err != nil {
  70. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  71. }
  72. }
  73. // Handle handles messages to the bridge
  74. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string, replyTo id.EventID) {
  75. args := strings.Fields(message)
  76. if len(args) == 0 {
  77. args = []string{"unknown-command"}
  78. }
  79. ce := &CommandEvent{
  80. Bot: handler.bridge.Bot,
  81. Bridge: handler.bridge,
  82. Portal: handler.bridge.GetPortalByMXID(roomID),
  83. Handler: handler,
  84. RoomID: roomID,
  85. User: user,
  86. Command: strings.ToLower(args[0]),
  87. Args: args[1:],
  88. ReplyTo: replyTo,
  89. }
  90. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  91. handler.CommandMux(ce)
  92. }
  93. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  94. switch ce.Command {
  95. case "login":
  96. handler.CommandLogin(ce)
  97. case "ping-matrix":
  98. handler.CommandPingMatrix(ce)
  99. case "logout-matrix":
  100. handler.CommandLogoutMatrix(ce)
  101. case "help":
  102. handler.CommandHelp(ce)
  103. case "version":
  104. handler.CommandVersion(ce)
  105. case "reconnect", "connect":
  106. handler.CommandReconnect(ce)
  107. case "disconnect":
  108. handler.CommandDisconnect(ce)
  109. case "ping":
  110. handler.CommandPing(ce)
  111. case "delete-session":
  112. handler.CommandDeleteSession(ce)
  113. case "delete-portal":
  114. handler.CommandDeletePortal(ce)
  115. case "delete-all-portals":
  116. handler.CommandDeleteAllPortals(ce)
  117. case "discard-megolm-session", "discard-session":
  118. handler.CommandDiscardMegolmSession(ce)
  119. case "dev-test":
  120. handler.CommandDevTest(ce)
  121. case "set-pl":
  122. handler.CommandSetPowerLevel(ce)
  123. case "logout":
  124. handler.CommandLogout(ce)
  125. case "toggle":
  126. handler.CommandToggle(ce)
  127. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "search", "open", "pm", "invite-link", "resolve", "resolve-link", "join", "create", "accept":
  128. if !ce.User.HasSession() {
  129. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  130. return
  131. } else if !ce.User.IsLoggedIn() {
  132. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  133. return
  134. }
  135. switch ce.Command {
  136. case "set-relay":
  137. handler.CommandSetRelay(ce)
  138. case "unset-relay":
  139. handler.CommandUnsetRelay(ce)
  140. case "login-matrix":
  141. handler.CommandLoginMatrix(ce)
  142. case "sync":
  143. handler.CommandSync(ce)
  144. case "list":
  145. handler.CommandList(ce)
  146. case "search":
  147. handler.CommandSearch(ce)
  148. case "open":
  149. handler.CommandOpen(ce)
  150. case "pm":
  151. handler.CommandPM(ce)
  152. case "invite-link":
  153. handler.CommandInviteLink(ce)
  154. case "resolve", "resolve-link":
  155. handler.CommandResolveLink(ce)
  156. case "join":
  157. handler.CommandJoin(ce)
  158. case "create":
  159. handler.CommandCreate(ce)
  160. case "accept":
  161. handler.CommandAccept(ce)
  162. }
  163. default:
  164. ce.Reply("Unknown command, use the `help` command for help.")
  165. }
  166. }
  167. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  168. if handler.bridge.Crypto == nil {
  169. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  170. } else if !ce.User.Admin {
  171. ce.Reply("Only the bridge admin can reset Megolm sessions")
  172. } else {
  173. handler.bridge.Crypto.ResetSession(ce.RoomID)
  174. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  175. }
  176. }
  177. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  178. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  179. if !handler.bridge.Config.Bridge.Relay.Enabled {
  180. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  181. } else if ce.Portal == nil {
  182. ce.Reply("This is not a portal room")
  183. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  184. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  185. } else {
  186. ce.Portal.RelayUserID = ce.User.MXID
  187. ce.Portal.Update()
  188. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  189. }
  190. }
  191. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  192. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  193. if !handler.bridge.Config.Bridge.Relay.Enabled {
  194. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  195. } else if ce.Portal == nil {
  196. ce.Reply("This is not a portal room")
  197. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  198. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  199. } else {
  200. ce.Portal.RelayUserID = ""
  201. ce.Portal.Update()
  202. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  203. }
  204. }
  205. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  206. }
  207. const cmdVersionHelp = `version - View the bridge version`
  208. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  209. linkifiedVersion := fmt.Sprintf("v%s", Version)
  210. if Tag == Version {
  211. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  212. } else if len(Commit) > 8 {
  213. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  214. }
  215. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  216. }
  217. const cmdInviteLinkHelp = `invite-link [--reset] - Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.`
  218. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  219. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  220. if ce.Portal == nil {
  221. ce.Reply("Not a portal room")
  222. } else if ce.Portal.IsPrivateChat() {
  223. ce.Reply("Can't get invite link to private chat")
  224. } else if ce.Portal.IsBroadcastList() {
  225. ce.Reply("Can't get invite link to broadcast list")
  226. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  227. ce.Reply("Failed to get invite link: %v", err)
  228. } else {
  229. ce.Reply(link)
  230. }
  231. }
  232. const cmdResolveLinkHelp = `resolve-link <group or message link> - Resolve a WhatsApp group invite or business message link.`
  233. func (handler *CommandHandler) CommandResolveLink(ce *CommandEvent) {
  234. if len(ce.Args) == 0 {
  235. ce.Reply("**Usage:** `resolve-link <group or message link>`")
  236. return
  237. }
  238. if strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  239. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  240. if err != nil {
  241. ce.Reply("Failed to get group info: %v", err)
  242. return
  243. }
  244. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  245. } else if strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkDirectPrefix) {
  246. target, err := ce.User.Client.ResolveBusinessMessageLink(ce.Args[0])
  247. if err != nil {
  248. ce.Reply("Failed to get business info: %v", err)
  249. return
  250. }
  251. message := ""
  252. if len(target.Message) > 0 {
  253. parts := strings.Split(target.Message, "\n")
  254. for i, part := range parts {
  255. parts[i] = "> " + html.EscapeString(part)
  256. }
  257. message = fmt.Sprintf(" The following prefilled message is attached:\n\n%s", strings.Join(parts, "\n"))
  258. }
  259. ce.Reply("That link points at %s (+%s).%s", target.PushName, target.JID.User, message)
  260. } else {
  261. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  262. }
  263. }
  264. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  265. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  266. if len(ce.Args) == 0 {
  267. ce.Reply("**Usage:** `join <invite link>`")
  268. return
  269. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  270. ce.Reply("That doesn't look like a WhatsApp invite link")
  271. return
  272. }
  273. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  274. if err != nil {
  275. ce.Reply("Failed to join group: %v", err)
  276. return
  277. }
  278. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  279. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  280. }
  281. func (handler *CommandHandler) CommandAccept(ce *CommandEvent) {
  282. if ce.Portal == nil || len(ce.ReplyTo) == 0 {
  283. ce.Reply("You must reply to a group invite message when using this command.")
  284. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  285. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  286. ce.Reply("Failed to get reply event")
  287. } else if meta, ok := evt.Content.Raw[inviteMetaField].(map[string]interface{}); !ok {
  288. ce.Reply("That doesn't look like a group invite message.")
  289. } else if jid, inviter, code, expiration, ok := parseInviteMeta(meta); !ok {
  290. ce.Reply("That doesn't look like a group invite message.")
  291. } else if inviter.User == ce.User.JID.User {
  292. ce.Reply("You can't accept your own invites")
  293. } else if err = ce.User.Client.JoinGroupWithInvite(jid, inviter, code, expiration); err != nil {
  294. ce.Reply("Failed to accept group invite: %v", err)
  295. } else {
  296. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  297. }
  298. }
  299. const cmdCreateHelp = `create - Create a group chat.`
  300. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  301. if ce.Portal != nil {
  302. ce.Reply("This is already a portal room")
  303. return
  304. }
  305. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  306. if err != nil {
  307. ce.Reply("Failed to get room members: %v", err)
  308. return
  309. }
  310. var roomNameEvent event.RoomNameEventContent
  311. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  312. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  313. handler.log.Errorln("Failed to get room name to create group:", err)
  314. ce.Reply("Failed to get room name")
  315. return
  316. } else if len(roomNameEvent.Name) == 0 {
  317. ce.Reply("Please set a name for the room first")
  318. return
  319. }
  320. var encryptionEvent event.EncryptionEventContent
  321. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  322. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  323. ce.Reply("Failed to get room encryption status")
  324. return
  325. }
  326. var participants []types.JID
  327. participantDedup := make(map[types.JID]bool)
  328. participantDedup[ce.User.JID.ToNonAD()] = true
  329. participantDedup[types.EmptyJID] = true
  330. for userID := range members.Joined {
  331. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  332. if !ok {
  333. user := handler.bridge.GetUserByMXID(userID)
  334. if user != nil && !user.JID.IsEmpty() {
  335. jid = user.JID.ToNonAD()
  336. }
  337. }
  338. if !participantDedup[jid] {
  339. participantDedup[jid] = true
  340. participants = append(participants, jid)
  341. }
  342. }
  343. handler.log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  344. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  345. if err != nil {
  346. ce.Reply("Failed to create group: %v", err)
  347. return
  348. }
  349. portal := ce.User.GetPortalByJID(resp.JID)
  350. portal.roomCreateLock.Lock()
  351. defer portal.roomCreateLock.Unlock()
  352. if len(portal.MXID) != 0 {
  353. portal.log.Warnln("Detected race condition in room creation")
  354. // TODO race condition, clean up the old room
  355. }
  356. portal.MXID = ce.RoomID
  357. portal.Name = roomNameEvent.Name
  358. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  359. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  360. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  361. if err != nil {
  362. portal.log.Warnln("Failed to enable encryption in room:", err)
  363. if errors.Is(err, mautrix.MForbidden) {
  364. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  365. } else {
  366. ce.Reply("Failed to enable encryption in room: %v", err)
  367. }
  368. }
  369. portal.Encrypted = true
  370. }
  371. portal.Update()
  372. portal.UpdateBridgeInfo()
  373. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  374. }
  375. func parseInviteMeta(meta map[string]interface{}) (jid, inviter types.JID, code string, expiration int64, ok bool) {
  376. var fieldFound bool
  377. code, fieldFound = meta["code"].(string)
  378. if !fieldFound {
  379. return
  380. }
  381. expirationStr, fieldFound := meta["expiration"].(string)
  382. if !fieldFound {
  383. return
  384. }
  385. inviterStr, fieldFound := meta["inviter"].(string)
  386. if !fieldFound {
  387. return
  388. }
  389. jidStr, fieldFound := meta["jid"].(string)
  390. if !fieldFound {
  391. return
  392. }
  393. var err error
  394. expiration, err = strconv.ParseInt(expirationStr, 10, 64)
  395. if err != nil {
  396. return
  397. }
  398. inviter, err = types.ParseJID(inviterStr)
  399. if err != nil {
  400. return
  401. }
  402. jid, err = types.ParseJID(jidStr)
  403. if err != nil {
  404. return
  405. }
  406. ok = true
  407. return
  408. }
  409. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  410. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  411. if ce.Portal == nil {
  412. ce.Reply("Not a portal room")
  413. return
  414. }
  415. var level int
  416. var userID id.UserID
  417. var err error
  418. if len(ce.Args) == 1 {
  419. level, err = strconv.Atoi(ce.Args[0])
  420. if err != nil {
  421. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  422. return
  423. }
  424. userID = ce.User.MXID
  425. } else if len(ce.Args) == 2 {
  426. userID = id.UserID(ce.Args[0])
  427. _, _, err := userID.Parse()
  428. if err != nil {
  429. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  430. return
  431. }
  432. level, err = strconv.Atoi(ce.Args[1])
  433. if err != nil {
  434. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  435. return
  436. }
  437. } else {
  438. ce.Reply("**Usage:** `set-pl [user] <level>`")
  439. return
  440. }
  441. intent := ce.Portal.MainIntent()
  442. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  443. if err != nil {
  444. ce.Reply("Failed to set power levels: %v", err)
  445. }
  446. }
  447. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  448. // CommandLogin handles login command
  449. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  450. if ce.User.Session != nil {
  451. if ce.User.IsConnected() {
  452. ce.Reply("You're already logged in")
  453. } else {
  454. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  455. }
  456. return
  457. }
  458. qrChan, err := ce.User.Login(context.Background())
  459. if err != nil {
  460. ce.User.log.Errorf("Failed to log in:", err)
  461. ce.Reply("Failed to log in: %v", err)
  462. return
  463. }
  464. var qrEventID id.EventID
  465. for item := range qrChan {
  466. switch item.Event {
  467. case whatsmeow.QRChannelSuccess.Event:
  468. jid := ce.User.Client.Store.ID
  469. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  470. case whatsmeow.QRChannelTimeout.Event:
  471. ce.Reply("QR code timed out. Please restart the login.")
  472. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  473. ce.Reply("Failed to log in: unexpected connection event from server")
  474. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  475. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  476. case "error":
  477. ce.Reply("Failed to log in: %v", item.Error)
  478. case "code":
  479. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  480. }
  481. }
  482. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  483. }
  484. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  485. url, ok := user.uploadQR(ce, code)
  486. if !ok {
  487. return prevEvent
  488. }
  489. content := event.MessageEventContent{
  490. MsgType: event.MsgImage,
  491. Body: code,
  492. URL: url.CUString(),
  493. }
  494. if len(prevEvent) != 0 {
  495. content.SetEdit(prevEvent)
  496. }
  497. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  498. if err != nil {
  499. user.log.Errorln("Failed to send edited QR code to user:", err)
  500. } else if len(prevEvent) == 0 {
  501. prevEvent = resp.EventID
  502. }
  503. return prevEvent
  504. }
  505. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  506. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  507. if err != nil {
  508. user.log.Errorln("Failed to encode QR code:", err)
  509. ce.Reply("Failed to encode QR code: %v", err)
  510. return id.ContentURI{}, false
  511. }
  512. bot := user.bridge.AS.BotClient()
  513. resp, err := bot.UploadBytes(qrCode, "image/png")
  514. if err != nil {
  515. user.log.Errorln("Failed to upload QR code:", err)
  516. ce.Reply("Failed to upload QR code: %v", err)
  517. return id.ContentURI{}, false
  518. }
  519. return resp.ContentURI, true
  520. }
  521. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  522. // CommandLogout handles !logout command
  523. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  524. if ce.User.Session == nil {
  525. ce.Reply("You're not logged in.")
  526. return
  527. } else if !ce.User.IsLoggedIn() {
  528. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  529. return
  530. }
  531. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  532. if puppet.CustomMXID != "" {
  533. err := puppet.SwitchCustomMXID("", "")
  534. if err != nil {
  535. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  536. }
  537. }
  538. err := ce.User.Client.Logout()
  539. if err != nil {
  540. ce.User.log.Warnln("Error while logging out:", err)
  541. ce.Reply("Unknown error while logging out: %v", err)
  542. return
  543. }
  544. ce.User.Session = nil
  545. ce.User.removeFromJIDMap(StateLoggedOut)
  546. ce.User.DeleteConnection()
  547. ce.User.DeleteSession()
  548. ce.Reply("Logged out successfully.")
  549. }
  550. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  551. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  552. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  553. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  554. return
  555. }
  556. if ce.User.Session == nil {
  557. ce.Reply("You're not logged in.")
  558. return
  559. }
  560. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  561. if customPuppet == nil {
  562. ce.Reply("You're not logged in with your Matrix account.")
  563. return
  564. }
  565. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  566. customPuppet.EnablePresence = !customPuppet.EnablePresence
  567. var newPresence types.Presence
  568. if customPuppet.EnablePresence {
  569. newPresence = types.PresenceAvailable
  570. ce.Reply("Enabled presence bridging")
  571. } else {
  572. newPresence = types.PresenceUnavailable
  573. ce.Reply("Disabled presence bridging")
  574. }
  575. if ce.User.IsLoggedIn() {
  576. err := ce.User.Client.SendPresence(newPresence)
  577. if err != nil {
  578. ce.User.log.Warnln("Failed to set presence:", err)
  579. }
  580. }
  581. }
  582. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  583. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  584. if customPuppet.EnableReceipts {
  585. ce.Reply("Enabled read receipt bridging")
  586. } else {
  587. ce.Reply("Disabled read receipt bridging")
  588. }
  589. }
  590. customPuppet.Update()
  591. }
  592. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  593. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  594. if ce.User.Session == nil && ce.User.Client == nil {
  595. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  596. return
  597. }
  598. ce.User.removeFromJIDMap(StateLoggedOut)
  599. ce.User.DeleteConnection()
  600. ce.User.DeleteSession()
  601. ce.Reply("Session information purged")
  602. }
  603. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  604. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  605. if ce.User.Client == nil {
  606. if ce.User.Session == nil {
  607. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  608. } else {
  609. ce.User.Connect()
  610. ce.Reply("Started connecting to WhatsApp")
  611. }
  612. } else {
  613. ce.User.DeleteConnection()
  614. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  615. ce.User.Connect()
  616. ce.Reply("Restarted connection to WhatsApp")
  617. }
  618. }
  619. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  620. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  621. if ce.User.Client == nil {
  622. ce.Reply("You don't have a WhatsApp connection.")
  623. return
  624. }
  625. ce.User.DeleteConnection()
  626. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  627. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  628. }
  629. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  630. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  631. if ce.User.Session == nil {
  632. if ce.User.Client != nil {
  633. ce.Reply("Connected to WhatsApp, but not logged in.")
  634. } else {
  635. ce.Reply("You're not logged into WhatsApp.")
  636. }
  637. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  638. ce.Reply("You're logged in as +%s (device #%d), but you don't have a WhatsApp connection.", ce.User.JID.User, ce.User.JID.Device)
  639. } else {
  640. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  641. }
  642. }
  643. const cmdHelpHelp = `help - Prints this help`
  644. // CommandHelp handles help command
  645. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  646. cmdPrefix := ""
  647. if ce.User.ManagementRoom != ce.RoomID {
  648. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  649. }
  650. ce.Reply("* " + strings.Join([]string{
  651. cmdPrefix + cmdHelpHelp,
  652. cmdPrefix + cmdVersionHelp,
  653. cmdPrefix + cmdLoginHelp,
  654. cmdPrefix + cmdLogoutHelp,
  655. cmdPrefix + cmdDeleteSessionHelp,
  656. cmdPrefix + cmdReconnectHelp,
  657. cmdPrefix + cmdDisconnectHelp,
  658. cmdPrefix + cmdPingHelp,
  659. cmdPrefix + cmdSetRelayHelp,
  660. cmdPrefix + cmdUnsetRelayHelp,
  661. cmdPrefix + cmdLoginMatrixHelp,
  662. cmdPrefix + cmdPingMatrixHelp,
  663. cmdPrefix + cmdLogoutMatrixHelp,
  664. cmdPrefix + cmdToggleHelp,
  665. cmdPrefix + cmdListHelp,
  666. cmdPrefix + cmdSearchHelp,
  667. cmdPrefix + cmdSyncHelp,
  668. cmdPrefix + cmdOpenHelp,
  669. cmdPrefix + cmdPMHelp,
  670. cmdPrefix + cmdInviteLinkHelp,
  671. cmdPrefix + cmdResolveLinkHelp,
  672. cmdPrefix + cmdJoinHelp,
  673. cmdPrefix + cmdCreateHelp,
  674. cmdPrefix + cmdSetPowerLevelHelp,
  675. cmdPrefix + cmdDeletePortalHelp,
  676. cmdPrefix + cmdDeleteAllPortalsHelp,
  677. }, "\n* "))
  678. }
  679. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  680. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  681. if err != nil {
  682. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  683. return false
  684. }
  685. for otherUser := range members.Joined {
  686. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  687. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  688. continue
  689. }
  690. user := portal.bridge.GetUserByMXID(otherUser)
  691. if user != nil && user.Session != nil {
  692. return false
  693. }
  694. }
  695. return true
  696. }
  697. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  698. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  699. if ce.Portal == nil {
  700. ce.Reply("You must be in a portal room to use that command")
  701. return
  702. }
  703. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  704. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  705. return
  706. }
  707. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  708. ce.Portal.Delete()
  709. ce.Portal.Cleanup(false)
  710. }
  711. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  712. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  713. portals := handler.bridge.GetAllPortals()
  714. var portalsToDelete []*Portal
  715. if ce.User.Admin {
  716. portalsToDelete = portals
  717. } else {
  718. portalsToDelete = portals[:0]
  719. for _, portal := range portals {
  720. if canDeletePortal(portal, ce.User.MXID) {
  721. portalsToDelete = append(portalsToDelete, portal)
  722. }
  723. }
  724. }
  725. leave := func(portal *Portal) {
  726. if len(portal.MXID) > 0 {
  727. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  728. Reason: "Deleting portal",
  729. UserID: ce.User.MXID,
  730. })
  731. }
  732. }
  733. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  734. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  735. intent := customPuppet.CustomIntent()
  736. leave = func(portal *Portal) {
  737. if len(portal.MXID) > 0 {
  738. _, _ = intent.LeaveRoom(portal.MXID)
  739. _, _ = intent.ForgetRoom(portal.MXID)
  740. }
  741. }
  742. }
  743. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  744. for _, portal := range portalsToDelete {
  745. portal.Delete()
  746. leave(portal)
  747. }
  748. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  749. go func() {
  750. for _, portal := range portalsToDelete {
  751. portal.Cleanup(false)
  752. }
  753. ce.Reply("Finished background cleanup of deleted portal rooms.")
  754. }()
  755. }
  756. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  757. func matchesQuery(str string, query string) bool {
  758. if query == "" {
  759. return true
  760. }
  761. return strings.Contains(strings.ToLower(str), query)
  762. }
  763. func formatContacts(bridge *Bridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  764. hasQuery := len(query) > 0
  765. for jid, contact := range input {
  766. if len(contact.FullName) == 0 {
  767. continue
  768. }
  769. puppet := bridge.GetPuppetByJID(jid)
  770. pushName := contact.PushName
  771. if len(pushName) == 0 {
  772. pushName = contact.FullName
  773. }
  774. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  775. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  776. }
  777. }
  778. sort.Sort(sort.StringSlice(result))
  779. return
  780. }
  781. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  782. hasQuery := len(query) > 0
  783. for _, group := range input {
  784. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  785. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  786. }
  787. }
  788. sort.Sort(sort.StringSlice(result))
  789. return
  790. }
  791. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  792. if len(ce.Args) == 0 {
  793. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  794. return
  795. }
  796. mode := strings.ToLower(ce.Args[0])
  797. if mode[0] != 'g' && mode[0] != 'c' {
  798. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  799. return
  800. }
  801. var err error
  802. page := 1
  803. max := 100
  804. if len(ce.Args) > 1 {
  805. page, err = strconv.Atoi(ce.Args[1])
  806. if err != nil || page <= 0 {
  807. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  808. return
  809. }
  810. }
  811. if len(ce.Args) > 2 {
  812. max, err = strconv.Atoi(ce.Args[2])
  813. if err != nil || max <= 0 {
  814. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  815. return
  816. } else if max > 400 {
  817. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  818. }
  819. }
  820. contacts := mode[0] == 'c'
  821. typeName := "Groups"
  822. var result []string
  823. if contacts {
  824. typeName = "Contacts"
  825. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  826. if err != nil {
  827. ce.Reply("Failed to get contacts: %s", err)
  828. return
  829. }
  830. result = formatContacts(ce.User.bridge, contactList, "")
  831. } else {
  832. groupList, err := ce.User.Client.GetJoinedGroups()
  833. if err != nil {
  834. ce.Reply("Failed to get groups: %s", err)
  835. return
  836. }
  837. result = formatGroups(groupList, "")
  838. }
  839. if len(result) == 0 {
  840. ce.Reply("No %s found", strings.ToLower(typeName))
  841. return
  842. }
  843. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  844. if (page-1)*max >= len(result) {
  845. if pages == 1 {
  846. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  847. } else {
  848. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  849. }
  850. return
  851. }
  852. lastIndex := page * max
  853. if lastIndex > len(result) {
  854. lastIndex = len(result)
  855. }
  856. result = result[(page-1)*max : lastIndex]
  857. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  858. }
  859. const cmdSearchHelp = `search <query> - Search for contacts or groups.`
  860. func (handler *CommandHandler) CommandSearch(ce *CommandEvent) {
  861. if len(ce.Args) == 0 {
  862. ce.Reply("**Usage:** `search <query>`")
  863. return
  864. }
  865. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  866. if err != nil {
  867. ce.Reply("Failed to get contacts: %s", err)
  868. return
  869. }
  870. groupList, err := ce.User.Client.GetJoinedGroups()
  871. if err != nil {
  872. ce.Reply("Failed to get groups: %s", err)
  873. return
  874. }
  875. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  876. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  877. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  878. result := make([]string, 0, 2)
  879. if len(formattedContacts) > 0 {
  880. result = append(result, "### Contacts\n\n"+formattedContacts)
  881. }
  882. if len(formattedGroups) > 0 {
  883. result = append(result, "### Groups\n\n"+formattedGroups)
  884. }
  885. if len(result) == 0 {
  886. ce.Reply("No contacts or groups found")
  887. return
  888. }
  889. ce.Reply(strings.Join(result, "\n\n"))
  890. }
  891. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  892. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  893. if len(ce.Args) == 0 {
  894. ce.Reply("**Usage:** `open <group JID>`")
  895. return
  896. }
  897. var jid types.JID
  898. if strings.ContainsRune(ce.Args[0], '@') {
  899. jid, _ = types.ParseJID(ce.Args[0])
  900. } else {
  901. jid = types.NewJID(ce.Args[0], types.GroupServer)
  902. }
  903. if jid.Server != types.GroupServer || !strings.ContainsRune(jid.User, '-') {
  904. ce.Reply("That does not look like a group JID")
  905. return
  906. }
  907. info, err := ce.User.Client.GetGroupInfo(jid)
  908. if err != nil {
  909. ce.Reply("Failed to get group info: %v", err)
  910. return
  911. }
  912. handler.log.Debugln("Importing", jid, "for", ce.User.MXID)
  913. portal := ce.User.GetPortalByJID(info.JID)
  914. if len(portal.MXID) > 0 {
  915. portal.UpdateMatrixRoom(ce.User, info)
  916. ce.Reply("Portal room synced.")
  917. } else {
  918. err = portal.CreateMatrixRoom(ce.User, info, true)
  919. if err != nil {
  920. ce.Reply("Failed to create room: %v", err)
  921. } else {
  922. ce.Reply("Portal room created.")
  923. }
  924. }
  925. }
  926. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  927. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  928. if len(ce.Args) == 0 {
  929. ce.Reply("**Usage:** `pm <international phone number>`")
  930. return
  931. }
  932. user := ce.User
  933. number := strings.Join(ce.Args, "")
  934. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  935. if err != nil {
  936. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  937. return
  938. } else if len(resp) == 0 {
  939. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  940. return
  941. }
  942. targetUser := resp[0]
  943. if !targetUser.IsIn {
  944. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  945. return
  946. }
  947. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  948. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  949. puppet.SyncContact(user, true, "manual pm command")
  950. portal := user.GetPortalByJID(puppet.JID)
  951. if len(portal.MXID) > 0 {
  952. ok := portal.ensureUserInvited(user)
  953. if !ok {
  954. portal.log.Warnfln("ensureUserInvited(%s) returned false, creating new portal", user.MXID)
  955. portal.MXID = ""
  956. } else {
  957. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  958. return
  959. }
  960. }
  961. err = portal.CreateMatrixRoom(user, nil, false)
  962. if err != nil {
  963. ce.Reply("Failed to create portal room: %v", err)
  964. return
  965. }
  966. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  967. }
  968. const cmdSyncHelp = `sync <appstate/contacts/groups> [--create-portals] - Synchronize data from WhatsApp.`
  969. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  970. if len(ce.Args) == 0 {
  971. ce.Reply("**Usage:** `sync <appstate/contacts/groups> [--create-portals]`")
  972. return
  973. }
  974. args := strings.ToLower(strings.Join(ce.Args, " "))
  975. contacts := strings.Contains(args, "contacts")
  976. appState := strings.Contains(args, "appstate")
  977. groups := strings.Contains(args, "groups")
  978. createPortals := strings.Contains(args, "--create-portals")
  979. if appState {
  980. for _, name := range appstate.AllPatchNames {
  981. err := ce.User.Client.FetchAppState(name, true, false)
  982. if err != nil {
  983. ce.Reply("Error syncing app state %s: %v", name, err)
  984. } else if name == appstate.WAPatchCriticalUnblockLow {
  985. ce.Reply("Synced app state %s, contact sync running in background", name)
  986. } else {
  987. ce.Reply("Synced app state %s", name)
  988. }
  989. }
  990. } else if contacts {
  991. err := ce.User.ResyncContacts()
  992. if err != nil {
  993. ce.Reply("Error resyncing contacts: %v", err)
  994. } else {
  995. ce.Reply("Resynced contacts")
  996. }
  997. }
  998. if groups {
  999. err := ce.User.ResyncGroups(createPortals)
  1000. if err != nil {
  1001. ce.Reply("Error resyncing groups: %v", err)
  1002. } else {
  1003. ce.Reply("Resynced groups")
  1004. }
  1005. }
  1006. }
  1007. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  1008. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  1009. if len(ce.Args) == 0 {
  1010. ce.Reply("**Usage:** `login-matrix <access token>`")
  1011. return
  1012. }
  1013. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  1014. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  1015. if err != nil {
  1016. ce.Reply("Failed to switch puppet: %v", err)
  1017. return
  1018. }
  1019. ce.Reply("Successfully switched puppet")
  1020. }
  1021. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  1022. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  1023. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1024. if puppet == nil || puppet.CustomIntent() == nil {
  1025. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  1026. return
  1027. }
  1028. resp, err := puppet.CustomIntent().Whoami()
  1029. if err != nil {
  1030. ce.Reply("Failed to validate Matrix login: %v", err)
  1031. } else {
  1032. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  1033. }
  1034. }
  1035. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  1036. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  1037. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1038. if puppet == nil || puppet.CustomIntent() == nil {
  1039. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  1040. return
  1041. }
  1042. err := puppet.SwitchCustomMXID("", "")
  1043. if err != nil {
  1044. ce.Reply("Failed to remove custom puppet: %v", err)
  1045. return
  1046. }
  1047. ce.Reply("Successfully removed custom puppet")
  1048. }