commands.go 35 KB

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