commands.go 34 KB

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