commands.go 38 KB

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