commands.go 37 KB

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