commands.go 36 KB

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