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. messageID := whatsmeow.GenerateMessageID()
  353. ce.Log.Infofln("Creating group for %s with name %s and participants %+v (create key: %s)", ce.RoomID, roomNameEvent.Name, participants, messageID)
  354. ce.User.createKeyDedup = messageID
  355. resp, err := ce.User.Client.CreateGroup(whatsmeow.ReqCreateGroup{
  356. CreateKey: messageID,
  357. Name: roomNameEvent.Name,
  358. Participants: participants,
  359. GroupParent: types.GroupParent{
  360. IsParent: createEvent.Type == event.RoomTypeSpace,
  361. },
  362. })
  363. if err != nil {
  364. ce.Reply("Failed to create group: %v", err)
  365. return
  366. }
  367. portal := ce.User.GetPortalByJID(resp.JID)
  368. portal.roomCreateLock.Lock()
  369. defer portal.roomCreateLock.Unlock()
  370. if len(portal.MXID) != 0 {
  371. portal.log.Warnln("Detected race condition in room creation")
  372. // TODO race condition, clean up the old room
  373. }
  374. portal.MXID = ce.RoomID
  375. portal.Name = roomNameEvent.Name
  376. portal.IsParent = resp.IsParent
  377. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  378. if !portal.Encrypted && ce.Bridge.Config.Bridge.Encryption.Default {
  379. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", portal.GetEncryptionEventContent())
  380. if err != nil {
  381. portal.log.Warnln("Failed to enable encryption in room:", err)
  382. if errors.Is(err, mautrix.MForbidden) {
  383. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  384. } else {
  385. ce.Reply("Failed to enable encryption in room: %v", err)
  386. }
  387. }
  388. portal.Encrypted = true
  389. }
  390. portal.Update(nil)
  391. portal.UpdateBridgeInfo()
  392. ce.User.createKeyDedup = ""
  393. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  394. }
  395. var cmdLogin = &commands.FullHandler{
  396. Func: wrapCommand(fnLogin),
  397. Name: "login",
  398. Help: commands.HelpMeta{
  399. Section: commands.HelpSectionAuth,
  400. Description: "Link the bridge to your WhatsApp account as a web client.",
  401. },
  402. }
  403. func fnLogin(ce *WrappedCommandEvent) {
  404. if ce.User.Session != nil {
  405. if ce.User.IsConnected() {
  406. ce.Reply("You're already logged in")
  407. } else {
  408. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  409. }
  410. return
  411. }
  412. qrChan, err := ce.User.Login(context.Background())
  413. if err != nil {
  414. ce.User.log.Errorf("Failed to log in:", err)
  415. ce.Reply("Failed to log in: %v", err)
  416. return
  417. }
  418. var qrEventID id.EventID
  419. for item := range qrChan {
  420. switch item.Event {
  421. case whatsmeow.QRChannelSuccess.Event:
  422. jid := ce.User.Client.Store.ID
  423. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  424. case whatsmeow.QRChannelTimeout.Event:
  425. ce.Reply("QR code timed out. Please restart the login.")
  426. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  427. ce.Reply("Failed to log in: unexpected connection event from server")
  428. case whatsmeow.QRChannelClientOutdated.Event:
  429. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  430. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  431. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  432. case "error":
  433. ce.Reply("Failed to log in: %v", item.Error)
  434. case "code":
  435. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  436. }
  437. }
  438. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  439. }
  440. func (user *User) sendQR(ce *WrappedCommandEvent, code string, prevEvent id.EventID) id.EventID {
  441. url, ok := user.uploadQR(ce, code)
  442. if !ok {
  443. return prevEvent
  444. }
  445. content := event.MessageEventContent{
  446. MsgType: event.MsgImage,
  447. Body: code,
  448. URL: url.CUString(),
  449. }
  450. if len(prevEvent) != 0 {
  451. content.SetEdit(prevEvent)
  452. }
  453. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  454. if err != nil {
  455. user.log.Errorln("Failed to send edited QR code to user:", err)
  456. } else if len(prevEvent) == 0 {
  457. prevEvent = resp.EventID
  458. }
  459. return prevEvent
  460. }
  461. func (user *User) uploadQR(ce *WrappedCommandEvent, code string) (id.ContentURI, bool) {
  462. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  463. if err != nil {
  464. user.log.Errorln("Failed to encode QR code:", err)
  465. ce.Reply("Failed to encode QR code: %v", err)
  466. return id.ContentURI{}, false
  467. }
  468. bot := user.bridge.AS.BotClient()
  469. resp, err := bot.UploadBytes(qrCode, "image/png")
  470. if err != nil {
  471. user.log.Errorln("Failed to upload QR code:", err)
  472. ce.Reply("Failed to upload QR code: %v", err)
  473. return id.ContentURI{}, false
  474. }
  475. return resp.ContentURI, true
  476. }
  477. var cmdLogout = &commands.FullHandler{
  478. Func: wrapCommand(fnLogout),
  479. Name: "logout",
  480. Help: commands.HelpMeta{
  481. Section: commands.HelpSectionAuth,
  482. Description: "Unlink the bridge from your WhatsApp account.",
  483. },
  484. }
  485. func fnLogout(ce *WrappedCommandEvent) {
  486. if ce.User.Session == nil {
  487. ce.Reply("You're not logged in.")
  488. return
  489. } else if !ce.User.IsLoggedIn() {
  490. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  491. return
  492. }
  493. puppet := ce.Bridge.GetPuppetByJID(ce.User.JID)
  494. if puppet.CustomMXID != "" {
  495. err := puppet.SwitchCustomMXID("", "")
  496. if err != nil {
  497. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  498. }
  499. }
  500. err := ce.User.Client.Logout()
  501. if err != nil {
  502. ce.User.log.Warnln("Error while logging out:", err)
  503. ce.Reply("Unknown error while logging out: %v", err)
  504. return
  505. }
  506. ce.User.Session = nil
  507. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  508. ce.User.DeleteConnection()
  509. ce.User.DeleteSession()
  510. ce.Reply("Logged out successfully.")
  511. }
  512. var cmdTogglePresence = &commands.FullHandler{
  513. Func: wrapCommand(fnTogglePresence),
  514. Name: "toggle-presence",
  515. Help: commands.HelpMeta{
  516. Section: HelpSectionConnectionManagement,
  517. Description: "Toggle bridging of presence or read receipts.",
  518. },
  519. }
  520. func fnTogglePresence(ce *WrappedCommandEvent) {
  521. if ce.User.Session == nil {
  522. ce.Reply("You're not logged in.")
  523. return
  524. }
  525. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  526. if customPuppet == nil {
  527. ce.Reply("You're not logged in with your Matrix account.")
  528. return
  529. }
  530. customPuppet.EnablePresence = !customPuppet.EnablePresence
  531. var newPresence types.Presence
  532. if customPuppet.EnablePresence {
  533. newPresence = types.PresenceAvailable
  534. ce.Reply("Enabled presence bridging")
  535. } else {
  536. newPresence = types.PresenceUnavailable
  537. ce.Reply("Disabled presence bridging")
  538. }
  539. if ce.User.IsLoggedIn() {
  540. err := ce.User.Client.SendPresence(newPresence)
  541. if err != nil {
  542. ce.User.log.Warnln("Failed to set presence:", err)
  543. }
  544. }
  545. customPuppet.Update()
  546. }
  547. var cmdDeleteSession = &commands.FullHandler{
  548. Func: wrapCommand(fnDeleteSession),
  549. Name: "delete-session",
  550. Help: commands.HelpMeta{
  551. Section: commands.HelpSectionAuth,
  552. Description: "Delete session information and disconnect from WhatsApp without sending a logout request.",
  553. },
  554. }
  555. func fnDeleteSession(ce *WrappedCommandEvent) {
  556. if ce.User.Session == nil && ce.User.Client == nil {
  557. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  558. return
  559. }
  560. ce.User.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  561. ce.User.DeleteConnection()
  562. ce.User.DeleteSession()
  563. ce.Reply("Session information purged")
  564. }
  565. var cmdReconnect = &commands.FullHandler{
  566. Func: wrapCommand(fnReconnect),
  567. Name: "reconnect",
  568. Help: commands.HelpMeta{
  569. Section: HelpSectionConnectionManagement,
  570. Description: "Reconnect to WhatsApp.",
  571. },
  572. }
  573. func fnReconnect(ce *WrappedCommandEvent) {
  574. if ce.User.Client == nil {
  575. if ce.User.Session == nil {
  576. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  577. } else {
  578. ce.User.Connect()
  579. ce.Reply("Started connecting to WhatsApp")
  580. }
  581. } else {
  582. ce.User.DeleteConnection()
  583. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WANotConnected})
  584. ce.User.Connect()
  585. ce.Reply("Restarted connection to WhatsApp")
  586. }
  587. }
  588. var cmdDisconnect = &commands.FullHandler{
  589. Func: wrapCommand(fnDisconnect),
  590. Name: "disconnect",
  591. Help: commands.HelpMeta{
  592. Section: HelpSectionConnectionManagement,
  593. Description: "Disconnect from WhatsApp (without logging out).",
  594. },
  595. }
  596. func fnDisconnect(ce *WrappedCommandEvent) {
  597. if ce.User.Client == nil {
  598. ce.Reply("You don't have a WhatsApp connection.")
  599. return
  600. }
  601. ce.User.DeleteConnection()
  602. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  603. ce.User.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Error: WANotConnected})
  604. }
  605. var cmdPing = &commands.FullHandler{
  606. Func: wrapCommand(fnPing),
  607. Name: "ping",
  608. Help: commands.HelpMeta{
  609. Section: HelpSectionConnectionManagement,
  610. Description: "Check your connection to WhatsApp.",
  611. },
  612. }
  613. func fnPing(ce *WrappedCommandEvent) {
  614. if ce.User.Session == nil {
  615. if ce.User.Client != nil {
  616. ce.Reply("Connected to WhatsApp, but not logged in.")
  617. } else {
  618. ce.Reply("You're not logged into WhatsApp.")
  619. }
  620. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  621. 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)
  622. } else {
  623. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  624. if !ce.User.PhoneRecentlySeen(false) {
  625. ce.Reply("Phone hasn't been seen in %s", formatDisconnectTime(time.Now().Sub(ce.User.PhoneLastSeen)))
  626. }
  627. }
  628. }
  629. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  630. if len(portal.MXID) == 0 {
  631. return false
  632. }
  633. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  634. if err != nil {
  635. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  636. return false
  637. }
  638. for otherUser := range members.Joined {
  639. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  640. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  641. continue
  642. }
  643. user := portal.bridge.GetUserByMXID(otherUser)
  644. if user != nil && user.Session != nil {
  645. return false
  646. }
  647. }
  648. return true
  649. }
  650. var cmdDeletePortal = &commands.FullHandler{
  651. Func: wrapCommand(fnDeletePortal),
  652. Name: "delete-portal",
  653. Help: commands.HelpMeta{
  654. Section: HelpSectionPortalManagement,
  655. Description: "Delete the current portal. If the portal is used by other people, this is limited to bridge admins.",
  656. },
  657. RequiresPortal: true,
  658. }
  659. func fnDeletePortal(ce *WrappedCommandEvent) {
  660. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  661. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  662. return
  663. }
  664. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  665. ce.Portal.Delete()
  666. ce.Portal.Cleanup(false)
  667. }
  668. var cmdDeleteAllPortals = &commands.FullHandler{
  669. Func: wrapCommand(fnDeleteAllPortals),
  670. Name: "delete-all-portals",
  671. Help: commands.HelpMeta{
  672. Section: HelpSectionPortalManagement,
  673. Description: "Delete all portals.",
  674. },
  675. }
  676. func fnDeleteAllPortals(ce *WrappedCommandEvent) {
  677. portals := ce.Bridge.GetAllPortals()
  678. var portalsToDelete []*Portal
  679. if ce.User.Admin {
  680. portalsToDelete = portals
  681. } else {
  682. portalsToDelete = portals[:0]
  683. for _, portal := range portals {
  684. if canDeletePortal(portal, ce.User.MXID) {
  685. portalsToDelete = append(portalsToDelete, portal)
  686. }
  687. }
  688. }
  689. if len(portalsToDelete) == 0 {
  690. ce.Reply("Didn't find any portals to delete")
  691. return
  692. }
  693. leave := func(portal *Portal) {
  694. if len(portal.MXID) > 0 {
  695. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  696. Reason: "Deleting portal",
  697. UserID: ce.User.MXID,
  698. })
  699. }
  700. }
  701. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  702. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  703. intent := customPuppet.CustomIntent()
  704. leave = func(portal *Portal) {
  705. if len(portal.MXID) > 0 {
  706. _, _ = intent.LeaveRoom(portal.MXID)
  707. _, _ = intent.ForgetRoom(portal.MXID)
  708. }
  709. }
  710. }
  711. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  712. for _, portal := range portalsToDelete {
  713. portal.Delete()
  714. leave(portal)
  715. }
  716. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  717. go func() {
  718. for _, portal := range portalsToDelete {
  719. portal.Cleanup(false)
  720. }
  721. ce.Reply("Finished background cleanup of deleted portal rooms.")
  722. }()
  723. }
  724. var cmdBackfill = &commands.FullHandler{
  725. Func: wrapCommand(fnBackfill),
  726. Name: "backfill",
  727. Help: commands.HelpMeta{
  728. Section: HelpSectionPortalManagement,
  729. Description: "Backfill all messages the portal.",
  730. Args: "[_batch size_] [_batch delay_]",
  731. },
  732. RequiresPortal: true,
  733. }
  734. func fnBackfill(ce *WrappedCommandEvent) {
  735. if !ce.Bridge.Config.Bridge.HistorySync.Backfill {
  736. ce.Reply("Backfill is not enabled for this bridge.")
  737. return
  738. }
  739. batchSize := 100
  740. batchDelay := 5
  741. if len(ce.Args) >= 1 {
  742. var err error
  743. batchSize, err = strconv.Atoi(ce.Args[0])
  744. if err != nil || batchSize < 1 {
  745. ce.Reply("\"%s\" isn't a valid batch size", ce.Args[0])
  746. return
  747. }
  748. }
  749. if len(ce.Args) >= 2 {
  750. var err error
  751. batchDelay, err = strconv.Atoi(ce.Args[0])
  752. if err != nil || batchSize < 0 {
  753. ce.Reply("\"%s\" isn't a valid batch delay", ce.Args[1])
  754. return
  755. }
  756. }
  757. backfillMessages := ce.Portal.bridge.DB.Backfill.NewWithValues(ce.User.MXID, database.BackfillImmediate, 0, &ce.Portal.Key, nil, batchSize, -1, batchDelay)
  758. backfillMessages.Insert()
  759. ce.User.BackfillQueue.ReCheck()
  760. }
  761. func matchesQuery(str string, query string) bool {
  762. if query == "" {
  763. return true
  764. }
  765. return strings.Contains(strings.ToLower(str), query)
  766. }
  767. func formatContacts(bridge *WABridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  768. hasQuery := len(query) > 0
  769. for jid, contact := range input {
  770. if len(contact.FullName) == 0 {
  771. continue
  772. }
  773. puppet := bridge.GetPuppetByJID(jid)
  774. pushName := contact.PushName
  775. if len(pushName) == 0 {
  776. pushName = contact.FullName
  777. }
  778. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  779. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  780. }
  781. }
  782. sort.Sort(sort.StringSlice(result))
  783. return
  784. }
  785. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  786. hasQuery := len(query) > 0
  787. for _, group := range input {
  788. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  789. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  790. }
  791. }
  792. sort.Sort(sort.StringSlice(result))
  793. return
  794. }
  795. var cmdList = &commands.FullHandler{
  796. Func: wrapCommand(fnList),
  797. Name: "list",
  798. Help: commands.HelpMeta{
  799. Section: HelpSectionMiscellaneous,
  800. Description: "Get a list of all contacts and groups.",
  801. Args: "<`contacts`|`groups`> [_page_] [_items per page_]",
  802. },
  803. RequiresLogin: true,
  804. }
  805. func fnList(ce *WrappedCommandEvent) {
  806. if len(ce.Args) == 0 {
  807. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  808. return
  809. }
  810. mode := strings.ToLower(ce.Args[0])
  811. if mode[0] != 'g' && mode[0] != 'c' {
  812. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  813. return
  814. }
  815. var err error
  816. page := 1
  817. max := 100
  818. if len(ce.Args) > 1 {
  819. page, err = strconv.Atoi(ce.Args[1])
  820. if err != nil || page <= 0 {
  821. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  822. return
  823. }
  824. }
  825. if len(ce.Args) > 2 {
  826. max, err = strconv.Atoi(ce.Args[2])
  827. if err != nil || max <= 0 {
  828. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  829. return
  830. } else if max > 400 {
  831. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  832. }
  833. }
  834. contacts := mode[0] == 'c'
  835. typeName := "Groups"
  836. var result []string
  837. if contacts {
  838. typeName = "Contacts"
  839. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  840. if err != nil {
  841. ce.Reply("Failed to get contacts: %s", err)
  842. return
  843. }
  844. result = formatContacts(ce.User.bridge, contactList, "")
  845. } else {
  846. groupList, err := ce.User.Client.GetJoinedGroups()
  847. if err != nil {
  848. ce.Reply("Failed to get groups: %s", err)
  849. return
  850. }
  851. result = formatGroups(groupList, "")
  852. }
  853. if len(result) == 0 {
  854. ce.Reply("No %s found", strings.ToLower(typeName))
  855. return
  856. }
  857. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  858. if (page-1)*max >= len(result) {
  859. if pages == 1 {
  860. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  861. } else {
  862. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  863. }
  864. return
  865. }
  866. lastIndex := page * max
  867. if lastIndex > len(result) {
  868. lastIndex = len(result)
  869. }
  870. result = result[(page-1)*max : lastIndex]
  871. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  872. }
  873. var cmdSearch = &commands.FullHandler{
  874. Func: wrapCommand(fnSearch),
  875. Name: "search",
  876. Help: commands.HelpMeta{
  877. Section: HelpSectionMiscellaneous,
  878. Description: "Search for contacts or groups.",
  879. Args: "<_query_>",
  880. },
  881. RequiresLogin: true,
  882. }
  883. func fnSearch(ce *WrappedCommandEvent) {
  884. if len(ce.Args) == 0 {
  885. ce.Reply("**Usage:** `search <query>`")
  886. return
  887. }
  888. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  889. if err != nil {
  890. ce.Reply("Failed to get contacts: %s", err)
  891. return
  892. }
  893. groupList, err := ce.User.Client.GetJoinedGroups()
  894. if err != nil {
  895. ce.Reply("Failed to get groups: %s", err)
  896. return
  897. }
  898. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  899. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  900. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  901. result := make([]string, 0, 2)
  902. if len(formattedContacts) > 0 {
  903. result = append(result, "### Contacts\n\n"+formattedContacts)
  904. }
  905. if len(formattedGroups) > 0 {
  906. result = append(result, "### Groups\n\n"+formattedGroups)
  907. }
  908. if len(result) == 0 {
  909. ce.Reply("No contacts or groups found")
  910. return
  911. }
  912. ce.Reply(strings.Join(result, "\n\n"))
  913. }
  914. var cmdOpen = &commands.FullHandler{
  915. Func: wrapCommand(fnOpen),
  916. Name: "open",
  917. Help: commands.HelpMeta{
  918. Section: HelpSectionCreatingPortals,
  919. Description: "Open a group chat portal.",
  920. Args: "<_group JID_>",
  921. },
  922. RequiresLogin: true,
  923. }
  924. func fnOpen(ce *WrappedCommandEvent) {
  925. if len(ce.Args) == 0 {
  926. ce.Reply("**Usage:** `open <group JID>`")
  927. return
  928. }
  929. var jid types.JID
  930. if strings.ContainsRune(ce.Args[0], '@') {
  931. jid, _ = types.ParseJID(ce.Args[0])
  932. } else {
  933. jid = types.NewJID(ce.Args[0], types.GroupServer)
  934. }
  935. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  936. ce.Reply("That does not look like a group JID")
  937. return
  938. }
  939. info, err := ce.User.Client.GetGroupInfo(jid)
  940. if err != nil {
  941. ce.Reply("Failed to get group info: %v", err)
  942. return
  943. }
  944. ce.Log.Debugln("Importing", jid, "for", ce.User.MXID)
  945. portal := ce.User.GetPortalByJID(info.JID)
  946. if len(portal.MXID) > 0 {
  947. portal.UpdateMatrixRoom(ce.User, info)
  948. ce.Reply("Portal room synced.")
  949. } else {
  950. err = portal.CreateMatrixRoom(ce.User, info, true, true)
  951. if err != nil {
  952. ce.Reply("Failed to create room: %v", err)
  953. } else {
  954. ce.Reply("Portal room created.")
  955. }
  956. }
  957. }
  958. var cmdPM = &commands.FullHandler{
  959. Func: wrapCommand(fnPM),
  960. Name: "pm",
  961. Help: commands.HelpMeta{
  962. Section: HelpSectionCreatingPortals,
  963. Description: "Open a private chat with the given phone number.",
  964. Args: "<_international phone number_>",
  965. },
  966. RequiresLogin: true,
  967. }
  968. func fnPM(ce *WrappedCommandEvent) {
  969. if len(ce.Args) == 0 {
  970. ce.Reply("**Usage:** `pm <international phone number>`")
  971. return
  972. }
  973. user := ce.User
  974. number := strings.Join(ce.Args, "")
  975. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  976. if err != nil {
  977. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  978. return
  979. } else if len(resp) == 0 {
  980. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  981. return
  982. }
  983. targetUser := resp[0]
  984. if !targetUser.IsIn {
  985. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  986. return
  987. }
  988. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  989. if err != nil {
  990. ce.Reply("Failed to create portal room: %v", err)
  991. } else if !justCreated {
  992. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  993. } else {
  994. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  995. }
  996. }
  997. var cmdSync = &commands.FullHandler{
  998. Func: wrapCommand(fnSync),
  999. Name: "sync",
  1000. Help: commands.HelpMeta{
  1001. Section: HelpSectionMiscellaneous,
  1002. Description: "Synchronize data from WhatsApp.",
  1003. Args: "<appstate/contacts/groups/space> [--contact-avatars] [--create-portals]",
  1004. },
  1005. RequiresLogin: true,
  1006. }
  1007. func fnSync(ce *WrappedCommandEvent) {
  1008. args := strings.ToLower(strings.Join(ce.Args, " "))
  1009. contacts := strings.Contains(args, "contacts")
  1010. appState := strings.Contains(args, "appstate")
  1011. space := strings.Contains(args, "space")
  1012. groups := strings.Contains(args, "groups") || space
  1013. if !contacts && !appState && !space && !groups {
  1014. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--contact-avatars] [--create-portals]`")
  1015. return
  1016. }
  1017. createPortals := strings.Contains(args, "--create-portals")
  1018. contactAvatars := strings.Contains(args, "--contact-avatars")
  1019. if contactAvatars && (!contacts || appState) {
  1020. ce.Reply("`--contact-avatars` can only be used with `sync contacts`")
  1021. return
  1022. }
  1023. if createPortals && !groups {
  1024. ce.Reply("`--create-portals` can only be used with `sync groups`")
  1025. return
  1026. }
  1027. if appState {
  1028. for _, name := range appstate.AllPatchNames {
  1029. err := ce.User.Client.FetchAppState(name, true, false)
  1030. if errors.Is(err, appstate.ErrKeyNotFound) {
  1031. 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)
  1032. return
  1033. } else if err != nil {
  1034. ce.Reply("Error syncing app state %s: %v", name, err)
  1035. } else if name == appstate.WAPatchCriticalUnblockLow {
  1036. ce.Reply("Synced app state %s, contact sync running in background", name)
  1037. } else {
  1038. ce.Reply("Synced app state %s", name)
  1039. }
  1040. }
  1041. } else if contacts {
  1042. err := ce.User.ResyncContacts(contactAvatars)
  1043. if err != nil {
  1044. ce.Reply("Error resyncing contacts: %v", err)
  1045. } else {
  1046. ce.Reply("Resynced contacts")
  1047. }
  1048. }
  1049. if space {
  1050. if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
  1051. ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
  1052. return
  1053. }
  1054. keys := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ce.User.JID)
  1055. count := 0
  1056. for _, key := range keys {
  1057. portal := ce.Bridge.GetPortalByJID(key)
  1058. portal.addToPersonalSpace(ce.User)
  1059. count++
  1060. }
  1061. plural := "s"
  1062. if count == 1 {
  1063. plural = ""
  1064. }
  1065. ce.Reply("Added %d DM room%s to space", count, plural)
  1066. }
  1067. if groups {
  1068. err := ce.User.ResyncGroups(createPortals)
  1069. if err != nil {
  1070. ce.Reply("Error resyncing groups: %v", err)
  1071. } else {
  1072. ce.Reply("Resynced groups")
  1073. }
  1074. }
  1075. }
  1076. var cmdDisappearingTimer = &commands.FullHandler{
  1077. Func: wrapCommand(fnDisappearingTimer),
  1078. Name: "disappearing-timer",
  1079. Aliases: []string{"disappear-timer"},
  1080. Help: commands.HelpMeta{
  1081. Section: HelpSectionPortalManagement,
  1082. Description: "Set future messages in the room to disappear after the given time.",
  1083. Args: "<off/1d/7d/90d>",
  1084. },
  1085. RequiresLogin: true,
  1086. RequiresPortal: true,
  1087. }
  1088. func fnDisappearingTimer(ce *WrappedCommandEvent) {
  1089. if len(ce.Args) == 0 {
  1090. ce.Reply("**Usage:** `disappearing-timer <off/1d/7d/90d>`")
  1091. return
  1092. }
  1093. duration, ok := whatsmeow.ParseDisappearingTimerString(ce.Args[0])
  1094. if !ok {
  1095. ce.Reply("Invalid timer '%s'", ce.Args[0])
  1096. return
  1097. }
  1098. prevExpirationTime := ce.Portal.ExpirationTime
  1099. ce.Portal.ExpirationTime = uint32(duration.Seconds())
  1100. err := ce.User.Client.SetDisappearingTimer(ce.Portal.Key.JID, duration)
  1101. if err != nil {
  1102. ce.Reply("Failed to set disappearing timer: %v", err)
  1103. ce.Portal.ExpirationTime = prevExpirationTime
  1104. return
  1105. }
  1106. ce.Portal.Update(nil)
  1107. ce.React("✅")
  1108. }