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.Bridge.DB.BackfillQuery.DeleteAll(ce.User.MXID)
  557. ce.Bridge.DB.HistorySyncQuery.DeleteAllConversations(ce.User.MXID)
  558. ce.Bridge.DB.HistorySyncQuery.DeleteAllMessages(ce.User.MXID)
  559. ce.Reply("Logged out successfully.")
  560. }
  561. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  562. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  563. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  564. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  565. return
  566. }
  567. if ce.User.Session == nil {
  568. ce.Reply("You're not logged in.")
  569. return
  570. }
  571. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  572. if customPuppet == nil {
  573. ce.Reply("You're not logged in with your Matrix account.")
  574. return
  575. }
  576. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  577. customPuppet.EnablePresence = !customPuppet.EnablePresence
  578. var newPresence types.Presence
  579. if customPuppet.EnablePresence {
  580. newPresence = types.PresenceAvailable
  581. ce.Reply("Enabled presence bridging")
  582. } else {
  583. newPresence = types.PresenceUnavailable
  584. ce.Reply("Disabled presence bridging")
  585. }
  586. if ce.User.IsLoggedIn() {
  587. err := ce.User.Client.SendPresence(newPresence)
  588. if err != nil {
  589. ce.User.log.Warnln("Failed to set presence:", err)
  590. }
  591. }
  592. }
  593. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  594. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  595. if customPuppet.EnableReceipts {
  596. ce.Reply("Enabled read receipt bridging")
  597. } else {
  598. ce.Reply("Disabled read receipt bridging")
  599. }
  600. }
  601. customPuppet.Update()
  602. }
  603. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  604. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  605. if ce.User.Session == nil && ce.User.Client == nil {
  606. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  607. return
  608. }
  609. ce.User.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  610. ce.User.DeleteConnection()
  611. ce.User.DeleteSession()
  612. ce.Reply("Session information purged")
  613. }
  614. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  615. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  616. if ce.User.Client == nil {
  617. if ce.User.Session == nil {
  618. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  619. } else {
  620. ce.User.Connect()
  621. ce.Reply("Started connecting to WhatsApp")
  622. }
  623. } else {
  624. ce.User.DeleteConnection()
  625. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  626. ce.User.Connect()
  627. ce.Reply("Restarted connection to WhatsApp")
  628. }
  629. }
  630. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  631. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  632. if ce.User.Client == nil {
  633. ce.Reply("You don't have a WhatsApp connection.")
  634. return
  635. }
  636. ce.User.DeleteConnection()
  637. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  638. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  639. }
  640. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  641. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  642. if ce.User.Session == nil {
  643. if ce.User.Client != nil {
  644. ce.Reply("Connected to WhatsApp, but not logged in.")
  645. } else {
  646. ce.Reply("You're not logged into WhatsApp.")
  647. }
  648. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  649. 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)
  650. } else {
  651. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  652. }
  653. }
  654. const cmdHelpHelp = `help - Prints this help`
  655. // CommandHelp handles help command
  656. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  657. cmdPrefix := ""
  658. if ce.User.ManagementRoom != ce.RoomID {
  659. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  660. }
  661. ce.Reply("* " + strings.Join([]string{
  662. cmdPrefix + cmdHelpHelp,
  663. cmdPrefix + cmdVersionHelp,
  664. cmdPrefix + cmdLoginHelp,
  665. cmdPrefix + cmdLogoutHelp,
  666. cmdPrefix + cmdDeleteSessionHelp,
  667. cmdPrefix + cmdReconnectHelp,
  668. cmdPrefix + cmdDisconnectHelp,
  669. cmdPrefix + cmdPingHelp,
  670. cmdPrefix + cmdSetRelayHelp,
  671. cmdPrefix + cmdUnsetRelayHelp,
  672. cmdPrefix + cmdLoginMatrixHelp,
  673. cmdPrefix + cmdPingMatrixHelp,
  674. cmdPrefix + cmdLogoutMatrixHelp,
  675. cmdPrefix + cmdToggleHelp,
  676. cmdPrefix + cmdListHelp,
  677. cmdPrefix + cmdSearchHelp,
  678. cmdPrefix + cmdSyncHelp,
  679. cmdPrefix + cmdOpenHelp,
  680. cmdPrefix + cmdPMHelp,
  681. cmdPrefix + cmdInviteLinkHelp,
  682. cmdPrefix + cmdResolveLinkHelp,
  683. cmdPrefix + cmdJoinHelp,
  684. cmdPrefix + cmdCreateHelp,
  685. cmdPrefix + cmdSetPowerLevelHelp,
  686. cmdPrefix + cmdDeletePortalHelp,
  687. cmdPrefix + cmdDeleteAllPortalsHelp,
  688. cmdPrefix + cmdBackfillHelp,
  689. }, "\n* "))
  690. }
  691. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  692. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  693. if err != nil {
  694. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  695. return false
  696. }
  697. for otherUser := range members.Joined {
  698. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  699. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  700. continue
  701. }
  702. user := portal.bridge.GetUserByMXID(otherUser)
  703. if user != nil && user.Session != nil {
  704. return false
  705. }
  706. }
  707. return true
  708. }
  709. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  710. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  711. if ce.Portal == nil {
  712. ce.Reply("You must be in a portal room to use that command")
  713. return
  714. }
  715. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  716. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  717. return
  718. }
  719. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  720. ce.Portal.Delete()
  721. ce.Portal.Cleanup(false)
  722. }
  723. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  724. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  725. portals := handler.bridge.GetAllPortals()
  726. var portalsToDelete []*Portal
  727. if ce.User.Admin {
  728. portalsToDelete = portals
  729. } else {
  730. portalsToDelete = portals[:0]
  731. for _, portal := range portals {
  732. if canDeletePortal(portal, ce.User.MXID) {
  733. portalsToDelete = append(portalsToDelete, portal)
  734. }
  735. }
  736. }
  737. leave := func(portal *Portal) {
  738. if len(portal.MXID) > 0 {
  739. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  740. Reason: "Deleting portal",
  741. UserID: ce.User.MXID,
  742. })
  743. }
  744. }
  745. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  746. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  747. intent := customPuppet.CustomIntent()
  748. leave = func(portal *Portal) {
  749. if len(portal.MXID) > 0 {
  750. _, _ = intent.LeaveRoom(portal.MXID)
  751. _, _ = intent.ForgetRoom(portal.MXID)
  752. }
  753. }
  754. }
  755. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  756. for _, portal := range portalsToDelete {
  757. portal.Delete()
  758. leave(portal)
  759. }
  760. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  761. go func() {
  762. for _, portal := range portalsToDelete {
  763. portal.Cleanup(false)
  764. }
  765. ce.Reply("Finished background cleanup of deleted portal rooms.")
  766. }()
  767. }
  768. const cmdBackfillHelp = `backfill [batch size] [batch delay] - Backfill all messages the portal.`
  769. func (handler *CommandHandler) CommandBackfill(ce *CommandEvent) {
  770. if ce.Portal == nil {
  771. ce.Reply("This is not a portal room")
  772. return
  773. }
  774. if !ce.Bridge.Config.Bridge.HistorySync.Backfill {
  775. ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &event.MessageEventContent{
  776. MsgType: event.MsgNotice,
  777. Body: "Backfill is not enabled for this bridge.",
  778. })
  779. return
  780. }
  781. batchSize := 100
  782. batchDelay := 5
  783. if len(ce.Args) >= 1 {
  784. var err error
  785. batchSize, err = strconv.Atoi(ce.Args[0])
  786. if err != nil || batchSize < 1 {
  787. ce.Reply("\"%s\" isn't a valid batch size", ce.Args[0])
  788. return
  789. }
  790. }
  791. if len(ce.Args) >= 2 {
  792. var err error
  793. batchDelay, err = strconv.Atoi(ce.Args[0])
  794. if err != nil || batchSize < 0 {
  795. ce.Reply("\"%s\" isn't a valid batch delay", ce.Args[1])
  796. return
  797. }
  798. }
  799. backfill := ce.Portal.bridge.DB.BackfillQuery.NewWithValues(ce.User.MXID, database.BackfillImmediate, 0, &ce.Portal.Key, nil, nil, batchSize, -1, batchDelay)
  800. backfill.Insert()
  801. ce.User.BackfillQueue.ReCheckQueue <- true
  802. }
  803. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  804. func matchesQuery(str string, query string) bool {
  805. if query == "" {
  806. return true
  807. }
  808. return strings.Contains(strings.ToLower(str), query)
  809. }
  810. func formatContacts(bridge *Bridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  811. hasQuery := len(query) > 0
  812. for jid, contact := range input {
  813. if len(contact.FullName) == 0 {
  814. continue
  815. }
  816. puppet := bridge.GetPuppetByJID(jid)
  817. pushName := contact.PushName
  818. if len(pushName) == 0 {
  819. pushName = contact.FullName
  820. }
  821. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  822. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  823. }
  824. }
  825. sort.Sort(sort.StringSlice(result))
  826. return
  827. }
  828. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  829. hasQuery := len(query) > 0
  830. for _, group := range input {
  831. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  832. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  833. }
  834. }
  835. sort.Sort(sort.StringSlice(result))
  836. return
  837. }
  838. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  839. if len(ce.Args) == 0 {
  840. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  841. return
  842. }
  843. mode := strings.ToLower(ce.Args[0])
  844. if mode[0] != 'g' && mode[0] != 'c' {
  845. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  846. return
  847. }
  848. var err error
  849. page := 1
  850. max := 100
  851. if len(ce.Args) > 1 {
  852. page, err = strconv.Atoi(ce.Args[1])
  853. if err != nil || page <= 0 {
  854. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  855. return
  856. }
  857. }
  858. if len(ce.Args) > 2 {
  859. max, err = strconv.Atoi(ce.Args[2])
  860. if err != nil || max <= 0 {
  861. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  862. return
  863. } else if max > 400 {
  864. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  865. }
  866. }
  867. contacts := mode[0] == 'c'
  868. typeName := "Groups"
  869. var result []string
  870. if contacts {
  871. typeName = "Contacts"
  872. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  873. if err != nil {
  874. ce.Reply("Failed to get contacts: %s", err)
  875. return
  876. }
  877. result = formatContacts(ce.User.bridge, contactList, "")
  878. } else {
  879. groupList, err := ce.User.Client.GetJoinedGroups()
  880. if err != nil {
  881. ce.Reply("Failed to get groups: %s", err)
  882. return
  883. }
  884. result = formatGroups(groupList, "")
  885. }
  886. if len(result) == 0 {
  887. ce.Reply("No %s found", strings.ToLower(typeName))
  888. return
  889. }
  890. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  891. if (page-1)*max >= len(result) {
  892. if pages == 1 {
  893. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  894. } else {
  895. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  896. }
  897. return
  898. }
  899. lastIndex := page * max
  900. if lastIndex > len(result) {
  901. lastIndex = len(result)
  902. }
  903. result = result[(page-1)*max : lastIndex]
  904. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  905. }
  906. const cmdSearchHelp = `search <query> - Search for contacts or groups.`
  907. func (handler *CommandHandler) CommandSearch(ce *CommandEvent) {
  908. if len(ce.Args) == 0 {
  909. ce.Reply("**Usage:** `search <query>`")
  910. return
  911. }
  912. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  913. if err != nil {
  914. ce.Reply("Failed to get contacts: %s", err)
  915. return
  916. }
  917. groupList, err := ce.User.Client.GetJoinedGroups()
  918. if err != nil {
  919. ce.Reply("Failed to get groups: %s", err)
  920. return
  921. }
  922. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  923. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  924. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  925. result := make([]string, 0, 2)
  926. if len(formattedContacts) > 0 {
  927. result = append(result, "### Contacts\n\n"+formattedContacts)
  928. }
  929. if len(formattedGroups) > 0 {
  930. result = append(result, "### Groups\n\n"+formattedGroups)
  931. }
  932. if len(result) == 0 {
  933. ce.Reply("No contacts or groups found")
  934. return
  935. }
  936. ce.Reply(strings.Join(result, "\n\n"))
  937. }
  938. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  939. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  940. if len(ce.Args) == 0 {
  941. ce.Reply("**Usage:** `open <group JID>`")
  942. return
  943. }
  944. var jid types.JID
  945. if strings.ContainsRune(ce.Args[0], '@') {
  946. jid, _ = types.ParseJID(ce.Args[0])
  947. } else {
  948. jid = types.NewJID(ce.Args[0], types.GroupServer)
  949. }
  950. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  951. ce.Reply("That does not look like a group JID")
  952. return
  953. }
  954. info, err := ce.User.Client.GetGroupInfo(jid)
  955. if err != nil {
  956. ce.Reply("Failed to get group info: %v", err)
  957. return
  958. }
  959. handler.log.Debugln("Importing", jid, "for", ce.User.MXID)
  960. portal := ce.User.GetPortalByJID(info.JID)
  961. if len(portal.MXID) > 0 {
  962. portal.UpdateMatrixRoom(ce.User, info)
  963. ce.Reply("Portal room synced.")
  964. } else {
  965. err = portal.CreateMatrixRoom(ce.User, info, true)
  966. if err != nil {
  967. ce.Reply("Failed to create room: %v", err)
  968. } else {
  969. ce.Reply("Portal room created.")
  970. }
  971. }
  972. }
  973. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  974. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  975. if len(ce.Args) == 0 {
  976. ce.Reply("**Usage:** `pm <international phone number>`")
  977. return
  978. }
  979. user := ce.User
  980. number := strings.Join(ce.Args, "")
  981. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  982. if err != nil {
  983. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  984. return
  985. } else if len(resp) == 0 {
  986. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  987. return
  988. }
  989. targetUser := resp[0]
  990. if !targetUser.IsIn {
  991. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  992. return
  993. }
  994. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  995. if err != nil {
  996. ce.Reply("Failed to create portal room: %v", err)
  997. } else if !justCreated {
  998. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  999. } else {
  1000. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  1001. }
  1002. }
  1003. const cmdSyncHelp = `sync <appstate/contacts/groups/space> [--create-portals] - Synchronize data from WhatsApp.`
  1004. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  1005. if len(ce.Args) == 0 {
  1006. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--create-portals]`")
  1007. return
  1008. }
  1009. args := strings.ToLower(strings.Join(ce.Args, " "))
  1010. contacts := strings.Contains(args, "contacts")
  1011. appState := strings.Contains(args, "appstate")
  1012. space := strings.Contains(args, "space")
  1013. groups := strings.Contains(args, "groups") || space
  1014. createPortals := strings.Contains(args, "--create-portals")
  1015. if appState {
  1016. for _, name := range appstate.AllPatchNames {
  1017. err := ce.User.Client.FetchAppState(name, true, false)
  1018. if err != nil {
  1019. ce.Reply("Error syncing app state %s: %v", name, err)
  1020. } else if name == appstate.WAPatchCriticalUnblockLow {
  1021. ce.Reply("Synced app state %s, contact sync running in background", name)
  1022. } else {
  1023. ce.Reply("Synced app state %s", name)
  1024. }
  1025. }
  1026. } else if contacts {
  1027. err := ce.User.ResyncContacts()
  1028. if err != nil {
  1029. ce.Reply("Error resyncing contacts: %v", err)
  1030. } else {
  1031. ce.Reply("Resynced contacts")
  1032. }
  1033. }
  1034. if space {
  1035. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  1036. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  1037. return
  1038. }
  1039. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  1040. count := 0
  1041. for _, key := range keys {
  1042. portal := ce.Bridge.GetPortalByJID(key)
  1043. portal.addToSpace(ce.User)
  1044. count++
  1045. }
  1046. plural := "s"
  1047. if count == 1 {
  1048. plural = ""
  1049. }
  1050. ce.Reply("Added %d DM room%s to space", count, plural)
  1051. }
  1052. if groups {
  1053. err := ce.User.ResyncGroups(createPortals)
  1054. if err != nil {
  1055. ce.Reply("Error resyncing groups: %v", err)
  1056. } else {
  1057. ce.Reply("Resynced groups")
  1058. }
  1059. }
  1060. }
  1061. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  1062. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  1063. if len(ce.Args) == 0 {
  1064. ce.Reply("**Usage:** `login-matrix <access token>`")
  1065. return
  1066. }
  1067. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  1068. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  1069. if err != nil {
  1070. ce.Reply("Failed to switch puppet: %v", err)
  1071. return
  1072. }
  1073. ce.Reply("Successfully switched puppet")
  1074. }
  1075. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  1076. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  1077. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1078. if puppet == nil || puppet.CustomIntent() == nil {
  1079. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  1080. return
  1081. }
  1082. resp, err := puppet.CustomIntent().Whoami()
  1083. if err != nil {
  1084. ce.Reply("Failed to validate Matrix login: %v", err)
  1085. } else {
  1086. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  1087. }
  1088. }
  1089. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  1090. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  1091. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1092. if puppet == nil || puppet.CustomIntent() == nil {
  1093. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  1094. return
  1095. }
  1096. err := puppet.SwitchCustomMXID("", "")
  1097. if err != nil {
  1098. ce.Reply("Failed to remove custom puppet: %v", err)
  1099. return
  1100. }
  1101. ce.Reply("Successfully removed custom puppet")
  1102. }