commands.go 35 KB

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