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. "github.com/skip2/go-qrcode"
  28. "github.com/tidwall/gjson"
  29. "maunium.net/go/maulogger/v2"
  30. "maunium.net/go/mautrix-whatsapp/database"
  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. )
  40. type CommandHandler struct {
  41. bridge *Bridge
  42. log maulogger.Logger
  43. }
  44. // NewCommandHandler creates a CommandHandler
  45. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  46. return &CommandHandler{
  47. bridge: bridge,
  48. log: bridge.Log.Sub("Command handler"),
  49. }
  50. }
  51. // CommandEvent stores all data which might be used to handle commands
  52. type CommandEvent struct {
  53. Bot *appservice.IntentAPI
  54. Bridge *Bridge
  55. Portal *Portal
  56. Handler *CommandHandler
  57. RoomID id.RoomID
  58. EventID id.EventID
  59. User *User
  60. Command string
  61. Args []string
  62. ReplyTo id.EventID
  63. }
  64. // Reply sends a reply to command as notice
  65. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  66. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  67. content.MsgType = event.MsgNotice
  68. intent := ce.Bot
  69. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  70. intent = ce.Portal.MainIntent()
  71. }
  72. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  73. if err != nil {
  74. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  75. }
  76. }
  77. // Handle handles messages to the bridge
  78. func (handler *CommandHandler) Handle(roomID id.RoomID, eventID id.EventID, user *User, message string, replyTo id.EventID) {
  79. args := strings.Fields(message)
  80. if len(args) == 0 {
  81. args = []string{"unknown-command"}
  82. }
  83. ce := &CommandEvent{
  84. Bot: handler.bridge.Bot,
  85. Bridge: handler.bridge,
  86. Portal: handler.bridge.GetPortalByMXID(roomID),
  87. Handler: handler,
  88. RoomID: roomID,
  89. EventID: eventID,
  90. User: user,
  91. Command: strings.ToLower(args[0]),
  92. Args: args[1:],
  93. ReplyTo: replyTo,
  94. }
  95. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  96. handler.CommandMux(ce)
  97. }
  98. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  99. switch ce.Command {
  100. case "login":
  101. handler.CommandLogin(ce)
  102. case "ping-matrix":
  103. handler.CommandPingMatrix(ce)
  104. case "logout-matrix":
  105. handler.CommandLogoutMatrix(ce)
  106. case "help":
  107. handler.CommandHelp(ce)
  108. case "version":
  109. handler.CommandVersion(ce)
  110. case "reconnect", "connect":
  111. handler.CommandReconnect(ce)
  112. case "disconnect":
  113. handler.CommandDisconnect(ce)
  114. case "ping":
  115. handler.CommandPing(ce)
  116. case "delete-session":
  117. handler.CommandDeleteSession(ce)
  118. case "delete-portal":
  119. handler.CommandDeletePortal(ce)
  120. case "delete-all-portals":
  121. handler.CommandDeleteAllPortals(ce)
  122. case "discard-megolm-session", "discard-session":
  123. handler.CommandDiscardMegolmSession(ce)
  124. case "dev-test":
  125. handler.CommandDevTest(ce)
  126. case "set-pl":
  127. handler.CommandSetPowerLevel(ce)
  128. case "logout":
  129. handler.CommandLogout(ce)
  130. case "toggle":
  131. handler.CommandToggle(ce)
  132. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "search", "open", "pm", "invite-link", "resolve", "resolve-link", "join", "create", "accept", "backfill":
  133. if !ce.User.HasSession() {
  134. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  135. return
  136. } else if !ce.User.IsLoggedIn() {
  137. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  138. return
  139. }
  140. switch ce.Command {
  141. case "set-relay":
  142. handler.CommandSetRelay(ce)
  143. case "unset-relay":
  144. handler.CommandUnsetRelay(ce)
  145. case "login-matrix":
  146. handler.CommandLoginMatrix(ce)
  147. case "sync":
  148. handler.CommandSync(ce)
  149. case "list":
  150. handler.CommandList(ce)
  151. case "search":
  152. handler.CommandSearch(ce)
  153. case "open":
  154. handler.CommandOpen(ce)
  155. case "pm":
  156. handler.CommandPM(ce)
  157. case "invite-link":
  158. handler.CommandInviteLink(ce)
  159. case "resolve", "resolve-link":
  160. handler.CommandResolveLink(ce)
  161. case "join":
  162. handler.CommandJoin(ce)
  163. case "create":
  164. handler.CommandCreate(ce)
  165. case "accept":
  166. handler.CommandAccept(ce)
  167. case "backfill":
  168. handler.CommandBackfill(ce)
  169. }
  170. default:
  171. ce.Reply("Unknown command, use the `help` command for help.")
  172. }
  173. }
  174. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  175. if handler.bridge.Crypto == nil {
  176. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  177. } else if !ce.User.Admin {
  178. ce.Reply("Only the bridge admin can reset Megolm sessions")
  179. } else {
  180. handler.bridge.Crypto.ResetSession(ce.RoomID)
  181. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  182. }
  183. }
  184. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  185. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  186. if !handler.bridge.Config.Bridge.Relay.Enabled {
  187. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  188. } else if ce.Portal == nil {
  189. ce.Reply("This is not a portal room")
  190. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  191. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  192. } else {
  193. ce.Portal.RelayUserID = ce.User.MXID
  194. ce.Portal.Update()
  195. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  196. }
  197. }
  198. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  199. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  200. if !handler.bridge.Config.Bridge.Relay.Enabled {
  201. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  202. } else if ce.Portal == nil {
  203. ce.Reply("This is not a portal room")
  204. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  205. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  206. } else {
  207. ce.Portal.RelayUserID = ""
  208. ce.Portal.Update()
  209. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  210. }
  211. }
  212. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  213. }
  214. const cmdVersionHelp = `version - View the bridge version`
  215. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  216. linkifiedVersion := fmt.Sprintf("v%s", Version)
  217. if Tag == Version {
  218. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  219. } else if len(Commit) > 8 {
  220. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  221. }
  222. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  223. }
  224. const cmdInviteLinkHelp = `invite-link [--reset] - Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.`
  225. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  226. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  227. if ce.Portal == nil {
  228. ce.Reply("Not a portal room")
  229. } else if ce.Portal.IsPrivateChat() {
  230. ce.Reply("Can't get invite link to private chat")
  231. } else if ce.Portal.IsBroadcastList() {
  232. ce.Reply("Can't get invite link to broadcast list")
  233. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  234. ce.Reply("Failed to get invite link: %v", err)
  235. } else {
  236. ce.Reply(link)
  237. }
  238. }
  239. const cmdResolveLinkHelp = `resolve-link <group or message link> - Resolve a WhatsApp group invite or business message link.`
  240. func (handler *CommandHandler) CommandResolveLink(ce *CommandEvent) {
  241. if len(ce.Args) == 0 {
  242. ce.Reply("**Usage:** `resolve-link <group or message link>`")
  243. return
  244. }
  245. if strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  246. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  247. if err != nil {
  248. ce.Reply("Failed to get group info: %v", err)
  249. return
  250. }
  251. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  252. } else if strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkPrefix) || strings.HasPrefix(ce.Args[0], whatsmeow.BusinessMessageLinkDirectPrefix) {
  253. target, err := ce.User.Client.ResolveBusinessMessageLink(ce.Args[0])
  254. if err != nil {
  255. ce.Reply("Failed to get business info: %v", err)
  256. return
  257. }
  258. message := ""
  259. if len(target.Message) > 0 {
  260. parts := strings.Split(target.Message, "\n")
  261. for i, part := range parts {
  262. parts[i] = "> " + html.EscapeString(part)
  263. }
  264. message = fmt.Sprintf(" The following prefilled message is attached:\n\n%s", strings.Join(parts, "\n"))
  265. }
  266. ce.Reply("That link points at %s (+%s).%s", target.PushName, target.JID.User, message)
  267. } else {
  268. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  269. }
  270. }
  271. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  272. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  273. if len(ce.Args) == 0 {
  274. ce.Reply("**Usage:** `join <invite link>`")
  275. return
  276. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  277. ce.Reply("That doesn't look like a WhatsApp invite link")
  278. return
  279. }
  280. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  281. if err != nil {
  282. ce.Reply("Failed to join group: %v", err)
  283. return
  284. }
  285. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  286. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  287. }
  288. func tryDecryptEvent(crypto Crypto, evt *event.Event) (json.RawMessage, error) {
  289. var data json.RawMessage
  290. if evt.Type != event.EventEncrypted {
  291. data = evt.Content.VeryRaw
  292. } else {
  293. err := evt.Content.ParseRaw(evt.Type)
  294. if err != nil && !errors.Is(err, event.ErrContentAlreadyParsed) {
  295. return nil, err
  296. }
  297. decrypted, err := crypto.Decrypt(evt)
  298. if err != nil {
  299. return nil, err
  300. }
  301. data = decrypted.Content.VeryRaw
  302. }
  303. return data, nil
  304. }
  305. func parseInviteMeta(data json.RawMessage) (*InviteMeta, error) {
  306. result := gjson.GetBytes(data, escapedInviteMetaField)
  307. if !result.Exists() || !result.IsObject() {
  308. return nil, nil
  309. }
  310. var meta InviteMeta
  311. err := json.Unmarshal([]byte(result.Raw), &meta)
  312. if err != nil {
  313. return nil, nil
  314. }
  315. return &meta, nil
  316. }
  317. func (handler *CommandHandler) CommandAccept(ce *CommandEvent) {
  318. if ce.Portal == nil || len(ce.ReplyTo) == 0 {
  319. ce.Reply("You must reply to a group invite message when using this command.")
  320. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  321. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  322. ce.Reply("Failed to get reply event")
  323. } else if rawContent, err := tryDecryptEvent(ce.Bridge.Crypto, evt); err != nil {
  324. handler.log.Errorln("Failed to decrypt event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  325. ce.Reply("Failed to decrypt reply event")
  326. } else if meta, err := parseInviteMeta(rawContent); err != nil || meta == nil {
  327. ce.Reply("That doesn't look like a group invite message.")
  328. } else if meta.Inviter.User == ce.User.JID.User {
  329. ce.Reply("You can't accept your own invites")
  330. } else if err = ce.User.Client.JoinGroupWithInvite(meta.JID, meta.Inviter, meta.Code, meta.Expiration); err != nil {
  331. ce.Reply("Failed to accept group invite: %v", err)
  332. } else {
  333. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  334. }
  335. }
  336. const cmdCreateHelp = `create - Create a group chat.`
  337. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  338. if ce.Portal != nil {
  339. ce.Reply("This is already a portal room")
  340. return
  341. }
  342. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  343. if err != nil {
  344. ce.Reply("Failed to get room members: %v", err)
  345. return
  346. }
  347. var roomNameEvent event.RoomNameEventContent
  348. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  349. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  350. handler.log.Errorln("Failed to get room name to create group:", err)
  351. ce.Reply("Failed to get room name")
  352. return
  353. } else if len(roomNameEvent.Name) == 0 {
  354. ce.Reply("Please set a name for the room first")
  355. return
  356. }
  357. var encryptionEvent event.EncryptionEventContent
  358. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  359. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  360. ce.Reply("Failed to get room encryption status")
  361. return
  362. }
  363. var participants []types.JID
  364. participantDedup := make(map[types.JID]bool)
  365. participantDedup[ce.User.JID.ToNonAD()] = true
  366. participantDedup[types.EmptyJID] = true
  367. for userID := range members.Joined {
  368. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  369. if !ok {
  370. user := handler.bridge.GetUserByMXID(userID)
  371. if user != nil && !user.JID.IsEmpty() {
  372. jid = user.JID.ToNonAD()
  373. }
  374. }
  375. if !participantDedup[jid] {
  376. participantDedup[jid] = true
  377. participants = append(participants, jid)
  378. }
  379. }
  380. handler.log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  381. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  382. if err != nil {
  383. ce.Reply("Failed to create group: %v", err)
  384. return
  385. }
  386. portal := ce.User.GetPortalByJID(resp.JID)
  387. portal.roomCreateLock.Lock()
  388. defer portal.roomCreateLock.Unlock()
  389. if len(portal.MXID) != 0 {
  390. portal.log.Warnln("Detected race condition in room creation")
  391. // TODO race condition, clean up the old room
  392. }
  393. portal.MXID = ce.RoomID
  394. portal.Name = roomNameEvent.Name
  395. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  396. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  397. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  398. if err != nil {
  399. portal.log.Warnln("Failed to enable encryption in room:", err)
  400. if errors.Is(err, mautrix.MForbidden) {
  401. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  402. } else {
  403. ce.Reply("Failed to enable encryption in room: %v", err)
  404. }
  405. }
  406. portal.Encrypted = true
  407. }
  408. portal.Update()
  409. portal.UpdateBridgeInfo()
  410. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  411. }
  412. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  413. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  414. if !ce.User.Admin {
  415. ce.Reply("Only bridge admins can use `set-pl`")
  416. return
  417. } else if ce.Portal == nil {
  418. ce.Reply("This is not a portal room")
  419. return
  420. }
  421. var level int
  422. var userID id.UserID
  423. var err error
  424. if len(ce.Args) == 1 {
  425. level, err = strconv.Atoi(ce.Args[0])
  426. if err != nil {
  427. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  428. return
  429. }
  430. userID = ce.User.MXID
  431. } else if len(ce.Args) == 2 {
  432. userID = id.UserID(ce.Args[0])
  433. _, _, err := userID.Parse()
  434. if err != nil {
  435. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  436. return
  437. }
  438. level, err = strconv.Atoi(ce.Args[1])
  439. if err != nil {
  440. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  441. return
  442. }
  443. } else {
  444. ce.Reply("**Usage:** `set-pl [user] <level>`")
  445. return
  446. }
  447. intent := ce.Portal.MainIntent()
  448. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  449. if err != nil {
  450. ce.Reply("Failed to set power levels: %v", err)
  451. }
  452. }
  453. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  454. // CommandLogin handles login command
  455. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  456. if ce.User.Session != nil {
  457. if ce.User.IsConnected() {
  458. ce.Reply("You're already logged in")
  459. } else {
  460. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  461. }
  462. return
  463. }
  464. qrChan, err := ce.User.Login(context.Background())
  465. if err != nil {
  466. ce.User.log.Errorf("Failed to log in:", err)
  467. ce.Reply("Failed to log in: %v", err)
  468. return
  469. }
  470. var qrEventID id.EventID
  471. for item := range qrChan {
  472. switch item.Event {
  473. case whatsmeow.QRChannelSuccess.Event:
  474. jid := ce.User.Client.Store.ID
  475. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  476. case whatsmeow.QRChannelTimeout.Event:
  477. ce.Reply("QR code timed out. Please restart the login.")
  478. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  479. ce.Reply("Failed to log in: unexpected connection event from server")
  480. case whatsmeow.QRChannelClientOutdated.Event:
  481. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  482. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  483. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  484. case "error":
  485. ce.Reply("Failed to log in: %v", item.Error)
  486. case "code":
  487. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  488. }
  489. }
  490. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  491. }
  492. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  493. url, ok := user.uploadQR(ce, code)
  494. if !ok {
  495. return prevEvent
  496. }
  497. content := event.MessageEventContent{
  498. MsgType: event.MsgImage,
  499. Body: code,
  500. URL: url.CUString(),
  501. }
  502. if len(prevEvent) != 0 {
  503. content.SetEdit(prevEvent)
  504. }
  505. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  506. if err != nil {
  507. user.log.Errorln("Failed to send edited QR code to user:", err)
  508. } else if len(prevEvent) == 0 {
  509. prevEvent = resp.EventID
  510. }
  511. return prevEvent
  512. }
  513. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  514. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  515. if err != nil {
  516. user.log.Errorln("Failed to encode QR code:", err)
  517. ce.Reply("Failed to encode QR code: %v", err)
  518. return id.ContentURI{}, false
  519. }
  520. bot := user.bridge.AS.BotClient()
  521. resp, err := bot.UploadBytes(qrCode, "image/png")
  522. if err != nil {
  523. user.log.Errorln("Failed to upload QR code:", err)
  524. ce.Reply("Failed to upload QR code: %v", err)
  525. return id.ContentURI{}, false
  526. }
  527. return resp.ContentURI, true
  528. }
  529. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  530. // CommandLogout handles !logout command
  531. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  532. if ce.User.Session == nil {
  533. ce.Reply("You're not logged in.")
  534. return
  535. } else if !ce.User.IsLoggedIn() {
  536. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  537. return
  538. }
  539. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  540. if puppet.CustomMXID != "" {
  541. err := puppet.SwitchCustomMXID("", "")
  542. if err != nil {
  543. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  544. }
  545. }
  546. err := ce.User.Client.Logout()
  547. if err != nil {
  548. ce.User.log.Warnln("Error while logging out:", err)
  549. ce.Reply("Unknown error while logging out: %v", err)
  550. return
  551. }
  552. ce.User.Session = nil
  553. ce.User.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  554. ce.User.DeleteConnection()
  555. ce.User.DeleteSession()
  556. ce.Reply("Logged out successfully.")
  557. }
  558. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  559. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  560. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  561. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  562. return
  563. }
  564. if ce.User.Session == nil {
  565. ce.Reply("You're not logged in.")
  566. return
  567. }
  568. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  569. if customPuppet == nil {
  570. ce.Reply("You're not logged in with your Matrix account.")
  571. return
  572. }
  573. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  574. customPuppet.EnablePresence = !customPuppet.EnablePresence
  575. var newPresence types.Presence
  576. if customPuppet.EnablePresence {
  577. newPresence = types.PresenceAvailable
  578. ce.Reply("Enabled presence bridging")
  579. } else {
  580. newPresence = types.PresenceUnavailable
  581. ce.Reply("Disabled presence bridging")
  582. }
  583. if ce.User.IsLoggedIn() {
  584. err := ce.User.Client.SendPresence(newPresence)
  585. if err != nil {
  586. ce.User.log.Warnln("Failed to set presence:", err)
  587. }
  588. }
  589. }
  590. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  591. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  592. if customPuppet.EnableReceipts {
  593. ce.Reply("Enabled read receipt bridging")
  594. } else {
  595. ce.Reply("Disabled read receipt bridging")
  596. }
  597. }
  598. customPuppet.Update()
  599. }
  600. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  601. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  602. if ce.User.Session == nil && ce.User.Client == nil {
  603. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  604. return
  605. }
  606. ce.User.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  607. ce.User.DeleteConnection()
  608. ce.User.DeleteSession()
  609. ce.Reply("Session information purged")
  610. }
  611. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  612. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  613. if ce.User.Client == nil {
  614. if ce.User.Session == nil {
  615. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  616. } else {
  617. ce.User.Connect()
  618. ce.Reply("Started connecting to WhatsApp")
  619. }
  620. } else {
  621. ce.User.DeleteConnection()
  622. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  623. ce.User.Connect()
  624. ce.Reply("Restarted connection to WhatsApp")
  625. }
  626. }
  627. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  628. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  629. if ce.User.Client == nil {
  630. ce.Reply("You don't have a WhatsApp connection.")
  631. return
  632. }
  633. ce.User.DeleteConnection()
  634. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  635. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  636. }
  637. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  638. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  639. if ce.User.Session == nil {
  640. if ce.User.Client != nil {
  641. ce.Reply("Connected to WhatsApp, but not logged in.")
  642. } else {
  643. ce.Reply("You're not logged into WhatsApp.")
  644. }
  645. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  646. 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)
  647. } else {
  648. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  649. }
  650. }
  651. const cmdHelpHelp = `help - Prints this help`
  652. // CommandHelp handles help command
  653. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  654. cmdPrefix := ""
  655. if ce.User.ManagementRoom != ce.RoomID {
  656. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  657. }
  658. ce.Reply("* " + strings.Join([]string{
  659. cmdPrefix + cmdHelpHelp,
  660. cmdPrefix + cmdVersionHelp,
  661. cmdPrefix + cmdLoginHelp,
  662. cmdPrefix + cmdLogoutHelp,
  663. cmdPrefix + cmdDeleteSessionHelp,
  664. cmdPrefix + cmdReconnectHelp,
  665. cmdPrefix + cmdDisconnectHelp,
  666. cmdPrefix + cmdPingHelp,
  667. cmdPrefix + cmdSetRelayHelp,
  668. cmdPrefix + cmdUnsetRelayHelp,
  669. cmdPrefix + cmdLoginMatrixHelp,
  670. cmdPrefix + cmdPingMatrixHelp,
  671. cmdPrefix + cmdLogoutMatrixHelp,
  672. cmdPrefix + cmdToggleHelp,
  673. cmdPrefix + cmdListHelp,
  674. cmdPrefix + cmdSearchHelp,
  675. cmdPrefix + cmdSyncHelp,
  676. cmdPrefix + cmdOpenHelp,
  677. cmdPrefix + cmdPMHelp,
  678. cmdPrefix + cmdInviteLinkHelp,
  679. cmdPrefix + cmdResolveLinkHelp,
  680. cmdPrefix + cmdJoinHelp,
  681. cmdPrefix + cmdCreateHelp,
  682. cmdPrefix + cmdSetPowerLevelHelp,
  683. cmdPrefix + cmdDeletePortalHelp,
  684. cmdPrefix + cmdDeleteAllPortalsHelp,
  685. cmdPrefix + cmdBackfillHelp,
  686. }, "\n* "))
  687. }
  688. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  689. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  690. if err != nil {
  691. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  692. return false
  693. }
  694. for otherUser := range members.Joined {
  695. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  696. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  697. continue
  698. }
  699. user := portal.bridge.GetUserByMXID(otherUser)
  700. if user != nil && user.Session != nil {
  701. return false
  702. }
  703. }
  704. return true
  705. }
  706. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  707. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  708. if ce.Portal == nil {
  709. ce.Reply("You must be in a portal room to use that command")
  710. return
  711. }
  712. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  713. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  714. return
  715. }
  716. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  717. ce.Portal.Delete()
  718. ce.Portal.Cleanup(false)
  719. }
  720. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  721. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  722. portals := handler.bridge.GetAllPortals()
  723. var portalsToDelete []*Portal
  724. if ce.User.Admin {
  725. portalsToDelete = portals
  726. } else {
  727. portalsToDelete = portals[:0]
  728. for _, portal := range portals {
  729. if canDeletePortal(portal, ce.User.MXID) {
  730. portalsToDelete = append(portalsToDelete, portal)
  731. }
  732. }
  733. }
  734. leave := func(portal *Portal) {
  735. if len(portal.MXID) > 0 {
  736. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  737. Reason: "Deleting portal",
  738. UserID: ce.User.MXID,
  739. })
  740. }
  741. }
  742. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  743. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  744. intent := customPuppet.CustomIntent()
  745. leave = func(portal *Portal) {
  746. if len(portal.MXID) > 0 {
  747. _, _ = intent.LeaveRoom(portal.MXID)
  748. _, _ = intent.ForgetRoom(portal.MXID)
  749. }
  750. }
  751. }
  752. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  753. for _, portal := range portalsToDelete {
  754. portal.Delete()
  755. leave(portal)
  756. }
  757. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  758. go func() {
  759. for _, portal := range portalsToDelete {
  760. portal.Cleanup(false)
  761. }
  762. ce.Reply("Finished background cleanup of deleted portal rooms.")
  763. }()
  764. }
  765. const cmdBackfillHelp = `backfill [batch size] [batch delay] - Backfill all messages the portal.`
  766. func (handler *CommandHandler) CommandBackfill(ce *CommandEvent) {
  767. if ce.Portal == nil {
  768. ce.Reply("This is not a portal room")
  769. return
  770. }
  771. if !ce.Bridge.Config.Bridge.HistorySync.Backfill {
  772. ce.Reply("Backfill is not enabled for this bridge.")
  773. return
  774. }
  775. batchSize := 100
  776. batchDelay := 5
  777. if len(ce.Args) >= 1 {
  778. var err error
  779. batchSize, err = strconv.Atoi(ce.Args[0])
  780. if err != nil || batchSize < 1 {
  781. ce.Reply("\"%s\" isn't a valid batch size", ce.Args[0])
  782. return
  783. }
  784. }
  785. if len(ce.Args) >= 2 {
  786. var err error
  787. batchDelay, err = strconv.Atoi(ce.Args[0])
  788. if err != nil || batchSize < 0 {
  789. ce.Reply("\"%s\" isn't a valid batch delay", ce.Args[1])
  790. return
  791. }
  792. }
  793. backfillMessages := ce.Portal.bridge.DB.BackfillQuery.NewWithValues(ce.User.MXID, database.BackfillImmediate, 0, &ce.Portal.Key, nil, nil, batchSize, -1, batchDelay)
  794. backfillMessages.Insert()
  795. if ce.Bridge.Config.Bridge.HistorySync.BackfillMedia {
  796. backfillMedia := ce.Portal.bridge.DB.BackfillQuery.NewWithValues(ce.User.MXID, database.BackfillMedia, 1, &ce.Portal.Key, nil, nil, batchSize, -1, batchDelay)
  797. backfillMedia.Insert()
  798. }
  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. }