commands.go 36 KB

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