commands.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "html"
  23. "math"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "github.com/skip2/go-qrcode"
  28. "github.com/tidwall/gjson"
  29. "maunium.net/go/maulogger/v2"
  30. "go.mau.fi/whatsmeow"
  31. "go.mau.fi/whatsmeow/appstate"
  32. "go.mau.fi/whatsmeow/types"
  33. "maunium.net/go/mautrix"
  34. "maunium.net/go/mautrix/appservice"
  35. "maunium.net/go/mautrix/event"
  36. "maunium.net/go/mautrix/format"
  37. "maunium.net/go/mautrix/id"
  38. )
  39. type CommandHandler struct {
  40. bridge *Bridge
  41. log maulogger.Logger
  42. }
  43. // NewCommandHandler creates a CommandHandler
  44. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  45. return &CommandHandler{
  46. bridge: bridge,
  47. log: bridge.Log.Sub("Command handler"),
  48. }
  49. }
  50. // CommandEvent stores all data which might be used to handle commands
  51. type CommandEvent struct {
  52. Bot *appservice.IntentAPI
  53. Bridge *Bridge
  54. Portal *Portal
  55. Handler *CommandHandler
  56. RoomID id.RoomID
  57. EventID id.EventID
  58. User *User
  59. Command string
  60. Args []string
  61. ReplyTo id.EventID
  62. }
  63. // Reply sends a reply to command as notice
  64. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  65. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  66. content.MsgType = event.MsgNotice
  67. intent := ce.Bot
  68. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  69. intent = ce.Portal.MainIntent()
  70. }
  71. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  72. if err != nil {
  73. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  74. }
  75. }
  76. // Handle handles messages to the bridge
  77. func (handler *CommandHandler) Handle(roomID id.RoomID, eventID id.EventID, user *User, message string, replyTo id.EventID) {
  78. args := strings.Fields(message)
  79. if len(args) == 0 {
  80. args = []string{"unknown-command"}
  81. }
  82. ce := &CommandEvent{
  83. Bot: handler.bridge.Bot,
  84. Bridge: handler.bridge,
  85. Portal: handler.bridge.GetPortalByMXID(roomID),
  86. Handler: handler,
  87. RoomID: roomID,
  88. EventID: eventID,
  89. User: user,
  90. Command: strings.ToLower(args[0]),
  91. Args: args[1:],
  92. ReplyTo: replyTo,
  93. }
  94. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  95. handler.CommandMux(ce)
  96. }
  97. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  98. switch ce.Command {
  99. case "login":
  100. handler.CommandLogin(ce)
  101. case "ping-matrix":
  102. handler.CommandPingMatrix(ce)
  103. case "logout-matrix":
  104. handler.CommandLogoutMatrix(ce)
  105. case "help":
  106. handler.CommandHelp(ce)
  107. case "version":
  108. handler.CommandVersion(ce)
  109. case "reconnect", "connect":
  110. handler.CommandReconnect(ce)
  111. case "disconnect":
  112. handler.CommandDisconnect(ce)
  113. case "ping":
  114. handler.CommandPing(ce)
  115. case "delete-session":
  116. handler.CommandDeleteSession(ce)
  117. case "delete-portal":
  118. handler.CommandDeletePortal(ce)
  119. case "delete-all-portals":
  120. handler.CommandDeleteAllPortals(ce)
  121. case "discard-megolm-session", "discard-session":
  122. handler.CommandDiscardMegolmSession(ce)
  123. case "dev-test":
  124. handler.CommandDevTest(ce)
  125. case "set-pl":
  126. handler.CommandSetPowerLevel(ce)
  127. case "logout":
  128. handler.CommandLogout(ce)
  129. case "toggle":
  130. handler.CommandToggle(ce)
  131. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "search", "open", "pm", "invite-link", "resolve", "resolve-link", "join", "create", "accept":
  132. if !ce.User.HasSession() {
  133. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  134. return
  135. } else if !ce.User.IsLoggedIn() {
  136. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  137. return
  138. }
  139. switch ce.Command {
  140. case "set-relay":
  141. handler.CommandSetRelay(ce)
  142. case "unset-relay":
  143. handler.CommandUnsetRelay(ce)
  144. case "login-matrix":
  145. handler.CommandLoginMatrix(ce)
  146. case "sync":
  147. handler.CommandSync(ce)
  148. case "list":
  149. handler.CommandList(ce)
  150. case "search":
  151. handler.CommandSearch(ce)
  152. case "open":
  153. handler.CommandOpen(ce)
  154. case "pm":
  155. handler.CommandPM(ce)
  156. case "invite-link":
  157. handler.CommandInviteLink(ce)
  158. case "resolve", "resolve-link":
  159. handler.CommandResolveLink(ce)
  160. case "join":
  161. handler.CommandJoin(ce)
  162. case "create":
  163. handler.CommandCreate(ce)
  164. case "accept":
  165. handler.CommandAccept(ce)
  166. }
  167. default:
  168. ce.Reply("Unknown command, use the `help` command for help.")
  169. }
  170. }
  171. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  172. if handler.bridge.Crypto == nil {
  173. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  174. } else if !ce.User.Admin {
  175. ce.Reply("Only the bridge admin can reset Megolm sessions")
  176. } else {
  177. handler.bridge.Crypto.ResetSession(ce.RoomID)
  178. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  179. }
  180. }
  181. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  182. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  183. if !handler.bridge.Config.Bridge.Relay.Enabled {
  184. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  185. } else if ce.Portal == nil {
  186. ce.Reply("This is not a portal room")
  187. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  188. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  189. } else {
  190. ce.Portal.RelayUserID = ce.User.MXID
  191. ce.Portal.Update()
  192. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  193. }
  194. }
  195. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  196. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  197. if !handler.bridge.Config.Bridge.Relay.Enabled {
  198. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  199. } else if ce.Portal == nil {
  200. ce.Reply("This is not a portal room")
  201. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  202. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  203. } else {
  204. ce.Portal.RelayUserID = ""
  205. ce.Portal.Update()
  206. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  207. }
  208. }
  209. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  210. }
  211. const cmdVersionHelp = `version - View the bridge version`
  212. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  213. linkifiedVersion := fmt.Sprintf("v%s", Version)
  214. if Tag == Version {
  215. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  216. } else if len(Commit) > 8 {
  217. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  218. }
  219. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  220. }
  221. const cmdInviteLinkHelp = `invite-link [--reset] - Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.`
  222. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  223. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  224. if ce.Portal == nil {
  225. ce.Reply("Not a portal room")
  226. } else if ce.Portal.IsPrivateChat() {
  227. ce.Reply("Can't get invite link to private chat")
  228. } else if ce.Portal.IsBroadcastList() {
  229. ce.Reply("Can't get invite link to broadcast list")
  230. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  231. ce.Reply("Failed to get invite link: %v", err)
  232. } else {
  233. ce.Reply(link)
  234. }
  235. }
  236. const cmdResolveLinkHelp = `resolve-link <group or message link> - Resolve a WhatsApp group invite or business message link.`
  237. func (handler *CommandHandler) CommandResolveLink(ce *CommandEvent) {
  238. if len(ce.Args) == 0 {
  239. ce.Reply("**Usage:** `resolve-link <group or message link>`")
  240. return
  241. }
  242. if strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  243. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  244. if err != nil {
  245. ce.Reply("Failed to get group info: %v", err)
  246. return
  247. }
  248. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  249. } else if strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkDirectPrefix) {
  250. target, err := ce.User.Client.ResolveBusinessMessageLink(ce.Args[0])
  251. if err != nil {
  252. ce.Reply("Failed to get business info: %v", err)
  253. return
  254. }
  255. message := ""
  256. if len(target.Message) > 0 {
  257. parts := strings.Split(target.Message, "\n")
  258. for i, part := range parts {
  259. parts[i] = "> " + html.EscapeString(part)
  260. }
  261. message = fmt.Sprintf(" The following prefilled message is attached:\n\n%s", strings.Join(parts, "\n"))
  262. }
  263. ce.Reply("That link points at %s (+%s).%s", target.PushName, target.JID.User, message)
  264. } else {
  265. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  266. }
  267. }
  268. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  269. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  270. if len(ce.Args) == 0 {
  271. ce.Reply("**Usage:** `join <invite link>`")
  272. return
  273. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  274. ce.Reply("That doesn't look like a WhatsApp invite link")
  275. return
  276. }
  277. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  278. if err != nil {
  279. ce.Reply("Failed to join group: %v", err)
  280. return
  281. }
  282. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  283. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  284. }
  285. func tryDecryptEvent(crypto Crypto, evt *event.Event) (json.RawMessage, error) {
  286. var data json.RawMessage
  287. if evt.Type != event.EventEncrypted {
  288. data = evt.Content.VeryRaw
  289. } else {
  290. err := evt.Content.ParseRaw(evt.Type)
  291. if err != nil && !errors.Is(err, event.ErrContentAlreadyParsed) {
  292. return nil, err
  293. }
  294. decrypted, err := crypto.Decrypt(evt)
  295. if err != nil {
  296. return nil, err
  297. }
  298. data = decrypted.Content.VeryRaw
  299. }
  300. return data, nil
  301. }
  302. func parseInviteMeta(data json.RawMessage) (*InviteMeta, error) {
  303. result := gjson.GetBytes(data, escapedInviteMetaField)
  304. if !result.Exists() || !result.IsObject() {
  305. return nil, nil
  306. }
  307. var meta InviteMeta
  308. err := json.Unmarshal([]byte(result.Raw), &meta)
  309. if err != nil {
  310. return nil, nil
  311. }
  312. return &meta, nil
  313. }
  314. func (handler *CommandHandler) CommandAccept(ce *CommandEvent) {
  315. if ce.Portal == nil || len(ce.ReplyTo) == 0 {
  316. ce.Reply("You must reply to a group invite message when using this command.")
  317. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  318. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  319. ce.Reply("Failed to get reply event")
  320. } else if rawContent, err := tryDecryptEvent(ce.Bridge.Crypto, evt); err != nil {
  321. handler.log.Errorln("Failed to decrypt event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  322. ce.Reply("Failed to decrypt reply event")
  323. } else if meta, err := parseInviteMeta(rawContent); err != nil || meta == nil {
  324. ce.Reply("That doesn't look like a group invite message.")
  325. } else if meta.Inviter.User == ce.User.JID.User {
  326. ce.Reply("You can't accept your own invites")
  327. } else if err = ce.User.Client.JoinGroupWithInvite(meta.JID, meta.Inviter, meta.Code, meta.Expiration); err != nil {
  328. ce.Reply("Failed to accept group invite: %v", err)
  329. } else {
  330. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  331. }
  332. }
  333. const cmdCreateHelp = `create - Create a group chat.`
  334. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  335. if ce.Portal != nil {
  336. ce.Reply("This is already a portal room")
  337. return
  338. }
  339. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  340. if err != nil {
  341. ce.Reply("Failed to get room members: %v", err)
  342. return
  343. }
  344. var roomNameEvent event.RoomNameEventContent
  345. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  346. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  347. handler.log.Errorln("Failed to get room name to create group:", err)
  348. ce.Reply("Failed to get room name")
  349. return
  350. } else if len(roomNameEvent.Name) == 0 {
  351. ce.Reply("Please set a name for the room first")
  352. return
  353. }
  354. var encryptionEvent event.EncryptionEventContent
  355. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  356. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  357. ce.Reply("Failed to get room encryption status")
  358. return
  359. }
  360. var participants []types.JID
  361. participantDedup := make(map[types.JID]bool)
  362. participantDedup[ce.User.JID.ToNonAD()] = true
  363. participantDedup[types.EmptyJID] = true
  364. for userID := range members.Joined {
  365. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  366. if !ok {
  367. user := handler.bridge.GetUserByMXID(userID)
  368. if user != nil && !user.JID.IsEmpty() {
  369. jid = user.JID.ToNonAD()
  370. }
  371. }
  372. if !participantDedup[jid] {
  373. participantDedup[jid] = true
  374. participants = append(participants, jid)
  375. }
  376. }
  377. handler.log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  378. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  379. if err != nil {
  380. ce.Reply("Failed to create group: %v", err)
  381. return
  382. }
  383. portal := ce.User.GetPortalByJID(resp.JID)
  384. portal.roomCreateLock.Lock()
  385. defer portal.roomCreateLock.Unlock()
  386. if len(portal.MXID) != 0 {
  387. portal.log.Warnln("Detected race condition in room creation")
  388. // TODO race condition, clean up the old room
  389. }
  390. portal.MXID = ce.RoomID
  391. portal.Name = roomNameEvent.Name
  392. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  393. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  394. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  395. if err != nil {
  396. portal.log.Warnln("Failed to enable encryption in room:", err)
  397. if errors.Is(err, mautrix.MForbidden) {
  398. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  399. } else {
  400. ce.Reply("Failed to enable encryption in room: %v", err)
  401. }
  402. }
  403. portal.Encrypted = true
  404. }
  405. portal.Update()
  406. portal.UpdateBridgeInfo()
  407. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  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.User.Admin {
  412. ce.Reply("Only bridge admins can use `set-pl`")
  413. return
  414. } else if ce.Portal == nil {
  415. ce.Reply("This is not a portal room")
  416. return
  417. }
  418. var level int
  419. var userID id.UserID
  420. var err error
  421. if len(ce.Args) == 1 {
  422. level, err = strconv.Atoi(ce.Args[0])
  423. if err != nil {
  424. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  425. return
  426. }
  427. userID = ce.User.MXID
  428. } else if len(ce.Args) == 2 {
  429. userID = id.UserID(ce.Args[0])
  430. _, _, err := userID.Parse()
  431. if err != nil {
  432. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  433. return
  434. }
  435. level, err = strconv.Atoi(ce.Args[1])
  436. if err != nil {
  437. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  438. return
  439. }
  440. } else {
  441. ce.Reply("**Usage:** `set-pl [user] <level>`")
  442. return
  443. }
  444. intent := ce.Portal.MainIntent()
  445. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  446. if err != nil {
  447. ce.Reply("Failed to set power levels: %v", err)
  448. }
  449. }
  450. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  451. // CommandLogin handles login command
  452. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  453. if ce.User.Session != nil {
  454. if ce.User.IsConnected() {
  455. ce.Reply("You're already logged in")
  456. } else {
  457. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  458. }
  459. return
  460. }
  461. qrChan, err := ce.User.Login(context.Background())
  462. if err != nil {
  463. ce.User.log.Errorf("Failed to log in:", err)
  464. ce.Reply("Failed to log in: %v", err)
  465. return
  466. }
  467. var qrEventID id.EventID
  468. for item := range qrChan {
  469. switch item.Event {
  470. case whatsmeow.QRChannelSuccess.Event:
  471. jid := ce.User.Client.Store.ID
  472. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  473. case whatsmeow.QRChannelTimeout.Event:
  474. ce.Reply("QR code timed out. Please restart the login.")
  475. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  476. ce.Reply("Failed to log in: unexpected connection event from server")
  477. case whatsmeow.QRChannelClientOutdated.Event:
  478. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  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(BridgeState{StateEvent: 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(BridgeState{StateEvent: 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, '-') && len(jid.User) < 15) {
  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. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  953. if err != nil {
  954. ce.Reply("Failed to create portal room: %v", err)
  955. } else if !justCreated {
  956. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  957. } else {
  958. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  959. }
  960. }
  961. const cmdSyncHelp = `sync <appstate/contacts/groups/space> [--create-portals] - Synchronize data from WhatsApp.`
  962. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  963. if len(ce.Args) == 0 {
  964. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--create-portals]`")
  965. return
  966. }
  967. args := strings.ToLower(strings.Join(ce.Args, " "))
  968. contacts := strings.Contains(args, "contacts")
  969. appState := strings.Contains(args, "appstate")
  970. space := strings.Contains(args, "space")
  971. groups := strings.Contains(args, "groups") || space
  972. createPortals := strings.Contains(args, "--create-portals")
  973. if appState {
  974. for _, name := range appstate.AllPatchNames {
  975. err := ce.User.Client.FetchAppState(name, true, false)
  976. if err != nil {
  977. ce.Reply("Error syncing app state %s: %v", name, err)
  978. } else if name == appstate.WAPatchCriticalUnblockLow {
  979. ce.Reply("Synced app state %s, contact sync running in background", name)
  980. } else {
  981. ce.Reply("Synced app state %s", name)
  982. }
  983. }
  984. } else if contacts {
  985. err := ce.User.ResyncContacts()
  986. if err != nil {
  987. ce.Reply("Error resyncing contacts: %v", err)
  988. } else {
  989. ce.Reply("Resynced contacts")
  990. }
  991. }
  992. if space {
  993. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  994. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  995. return
  996. }
  997. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  998. count := 0
  999. for _, key := range keys {
  1000. portal := ce.Bridge.GetPortalByJID(key)
  1001. portal.addToSpace(ce.User)
  1002. count++
  1003. }
  1004. plural := "s"
  1005. if count == 1 {
  1006. plural = ""
  1007. }
  1008. ce.Reply("Added %d DM room%s to space", count, plural)
  1009. }
  1010. if groups {
  1011. err := ce.User.ResyncGroups(createPortals)
  1012. if err != nil {
  1013. ce.Reply("Error resyncing groups: %v", err)
  1014. } else {
  1015. ce.Reply("Resynced groups")
  1016. }
  1017. }
  1018. }
  1019. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  1020. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  1021. if len(ce.Args) == 0 {
  1022. ce.Reply("**Usage:** `login-matrix <access token>`")
  1023. return
  1024. }
  1025. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  1026. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  1027. if err != nil {
  1028. ce.Reply("Failed to switch puppet: %v", err)
  1029. return
  1030. }
  1031. ce.Reply("Successfully switched puppet")
  1032. }
  1033. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  1034. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  1035. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1036. if puppet == nil || puppet.CustomIntent() == nil {
  1037. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  1038. return
  1039. }
  1040. resp, err := puppet.CustomIntent().Whoami()
  1041. if err != nil {
  1042. ce.Reply("Failed to validate Matrix login: %v", err)
  1043. } else {
  1044. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  1045. }
  1046. }
  1047. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  1048. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  1049. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1050. if puppet == nil || puppet.CustomIntent() == nil {
  1051. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  1052. return
  1053. }
  1054. err := puppet.SwitchCustomMXID("", "")
  1055. if err != nil {
  1056. ce.Reply("Failed to remove custom puppet: %v", err)
  1057. return
  1058. }
  1059. ce.Reply("Successfully removed custom puppet")
  1060. }