commands.go 39 KB

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