commands.go 39 KB

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