commands.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "html"
  23. "math"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/skip2/go-qrcode"
  29. "github.com/tidwall/gjson"
  30. "go.mau.fi/whatsmeow"
  31. "go.mau.fi/whatsmeow/appstate"
  32. "go.mau.fi/whatsmeow/types"
  33. "maunium.net/go/mautrix"
  34. "maunium.net/go/mautrix/bridge"
  35. "maunium.net/go/mautrix/bridge/commands"
  36. "maunium.net/go/mautrix/event"
  37. "maunium.net/go/mautrix/id"
  38. "maunium.net/go/mautrix-whatsapp/database"
  39. )
  40. type WrappedCommandEvent struct {
  41. *commands.Event
  42. Bridge *WABridge
  43. User *User
  44. Portal *Portal
  45. }
  46. func (br *WABridge) RegisterCommands() {
  47. proc := br.CommandProcessor.(*commands.Processor)
  48. proc.AddHandlers(
  49. cmdSetRelay,
  50. cmdUnsetRelay,
  51. cmdInviteLink,
  52. cmdResolveLink,
  53. cmdJoin,
  54. cmdAccept,
  55. cmdCreate,
  56. cmdLogin,
  57. cmdLogout,
  58. cmdTogglePresence,
  59. cmdDeleteSession,
  60. cmdReconnect,
  61. cmdDisconnect,
  62. cmdPing,
  63. cmdDeletePortal,
  64. cmdDeleteAllPortals,
  65. cmdBackfill,
  66. cmdList,
  67. cmdSearch,
  68. cmdOpen,
  69. cmdPM,
  70. cmdSync,
  71. 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 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 {
  194. ce.Reply("That doesn't look like a group invite link nor a business message link.")
  195. }
  196. }
  197. var cmdJoin = &commands.FullHandler{
  198. Func: wrapCommand(fnJoin),
  199. Name: "join",
  200. Help: commands.HelpMeta{
  201. Section: HelpSectionInvites,
  202. Description: "Join a group chat with an invite link.",
  203. Args: "<_invite link_>",
  204. },
  205. RequiresLogin: true,
  206. }
  207. func fnJoin(ce *WrappedCommandEvent) {
  208. if len(ce.Args) == 0 {
  209. ce.Reply("**Usage:** `join <invite link>`")
  210. return
  211. } else if !strings.HasPrefix(ce.Args[0], whatsmeow.InviteLinkPrefix) {
  212. ce.Reply("That doesn't look like a WhatsApp invite link")
  213. return
  214. }
  215. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  216. if err != nil {
  217. ce.Reply("Failed to join group: %v", err)
  218. return
  219. }
  220. ce.Log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  221. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  222. }
  223. func tryDecryptEvent(crypto bridge.Crypto, evt *event.Event) (json.RawMessage, error) {
  224. var data json.RawMessage
  225. if evt.Type != event.EventEncrypted {
  226. data = evt.Content.VeryRaw
  227. } else {
  228. err := evt.Content.ParseRaw(evt.Type)
  229. if err != nil && !errors.Is(err, event.ErrContentAlreadyParsed) {
  230. return nil, err
  231. }
  232. decrypted, err := crypto.Decrypt(evt)
  233. if err != nil {
  234. return nil, err
  235. }
  236. data = decrypted.Content.VeryRaw
  237. }
  238. return data, nil
  239. }
  240. func parseInviteMeta(data json.RawMessage) (*InviteMeta, error) {
  241. result := gjson.GetBytes(data, escapedInviteMetaField)
  242. if !result.Exists() || !result.IsObject() {
  243. return nil, nil
  244. }
  245. var meta InviteMeta
  246. err := json.Unmarshal([]byte(result.Raw), &meta)
  247. if err != nil {
  248. return nil, nil
  249. }
  250. return &meta, nil
  251. }
  252. var cmdAccept = &commands.FullHandler{
  253. Func: wrapCommand(fnAccept),
  254. Name: "accept",
  255. Help: commands.HelpMeta{
  256. Section: HelpSectionInvites,
  257. Description: "Accept a group invite. This can only be used in reply to a group invite message.",
  258. },
  259. RequiresLogin: true,
  260. RequiresPortal: true,
  261. }
  262. func fnAccept(ce *WrappedCommandEvent) {
  263. if len(ce.ReplyTo) == 0 {
  264. ce.Reply("You must reply to a group invite message when using this command.")
  265. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  266. ce.Log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  267. ce.Reply("Failed to get reply event")
  268. } else if rawContent, err := tryDecryptEvent(ce.Bridge.Crypto, evt); err != nil {
  269. ce.Log.Errorln("Failed to decrypt event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  270. ce.Reply("Failed to decrypt reply event")
  271. } else if meta, err := parseInviteMeta(rawContent); err != nil || meta == nil {
  272. ce.Reply("That doesn't look like a group invite message.")
  273. } else if meta.Inviter.User == ce.User.JID.User {
  274. ce.Reply("You can't accept your own invites")
  275. } else if err = ce.User.Client.JoinGroupWithInvite(meta.JID, meta.Inviter, meta.Code, meta.Expiration); err != nil {
  276. ce.Reply("Failed to accept group invite: %v", err)
  277. } else {
  278. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  279. }
  280. }
  281. var cmdCreate = &commands.FullHandler{
  282. Func: wrapCommand(fnCreate),
  283. Name: "create",
  284. Help: commands.HelpMeta{
  285. Section: HelpSectionCreatingPortals,
  286. Description: "Create a WhatsApp group chat for the current Matrix room.",
  287. },
  288. RequiresLogin: true,
  289. }
  290. func fnCreate(ce *WrappedCommandEvent) {
  291. if ce.Portal != nil {
  292. ce.Reply("This is already a portal room")
  293. return
  294. }
  295. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  296. if err != nil {
  297. ce.Reply("Failed to get room members: %v", err)
  298. return
  299. }
  300. var roomNameEvent event.RoomNameEventContent
  301. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  302. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  303. ce.Log.Errorln("Failed to get room name to create group:", err)
  304. ce.Reply("Failed to get room name")
  305. return
  306. } else if len(roomNameEvent.Name) == 0 {
  307. ce.Reply("Please set a name for the room first")
  308. return
  309. }
  310. var encryptionEvent event.EncryptionEventContent
  311. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  312. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  313. ce.Reply("Failed to get room encryption status")
  314. return
  315. }
  316. var participants []types.JID
  317. participantDedup := make(map[types.JID]bool)
  318. participantDedup[ce.User.JID.ToNonAD()] = true
  319. participantDedup[types.EmptyJID] = true
  320. for userID := range members.Joined {
  321. jid, ok := ce.Bridge.ParsePuppetMXID(userID)
  322. if !ok {
  323. user := ce.Bridge.GetUserByMXID(userID)
  324. if user != nil && !user.JID.IsEmpty() {
  325. jid = user.JID.ToNonAD()
  326. }
  327. }
  328. if !participantDedup[jid] {
  329. participantDedup[jid] = true
  330. participants = append(participants, jid)
  331. }
  332. }
  333. ce.Log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  334. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  335. if err != nil {
  336. ce.Reply("Failed to create group: %v", err)
  337. return
  338. }
  339. portal := ce.User.GetPortalByJID(resp.JID)
  340. portal.roomCreateLock.Lock()
  341. defer portal.roomCreateLock.Unlock()
  342. if len(portal.MXID) != 0 {
  343. portal.log.Warnln("Detected race condition in room creation")
  344. // TODO race condition, clean up the old room
  345. }
  346. portal.MXID = ce.RoomID
  347. portal.Name = roomNameEvent.Name
  348. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  349. if !portal.Encrypted && ce.Bridge.Config.Bridge.Encryption.Default {
  350. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  351. if err != nil {
  352. portal.log.Warnln("Failed to enable encryption in room:", err)
  353. if errors.Is(err, mautrix.MForbidden) {
  354. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  355. } else {
  356. ce.Reply("Failed to enable encryption in room: %v", err)
  357. }
  358. }
  359. portal.Encrypted = true
  360. }
  361. portal.Update(nil)
  362. portal.UpdateBridgeInfo()
  363. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  364. }
  365. var cmdLogin = &commands.FullHandler{
  366. Func: wrapCommand(fnLogin),
  367. Name: "login",
  368. Help: commands.HelpMeta{
  369. Section: commands.HelpSectionAuth,
  370. Description: "Link the bridge to your WhatsApp account as a web client.",
  371. },
  372. }
  373. func fnLogin(ce *WrappedCommandEvent) {
  374. if ce.User.Session != nil {
  375. if ce.User.IsConnected() {
  376. ce.Reply("You're already logged in")
  377. } else {
  378. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  379. }
  380. return
  381. }
  382. qrChan, err := ce.User.Login(context.Background())
  383. if err != nil {
  384. ce.User.log.Errorf("Failed to log in:", err)
  385. ce.Reply("Failed to log in: %v", err)
  386. return
  387. }
  388. var qrEventID id.EventID
  389. for item := range qrChan {
  390. switch item.Event {
  391. case whatsmeow.QRChannelSuccess.Event:
  392. jid := ce.User.Client.Store.ID
  393. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  394. case whatsmeow.QRChannelTimeout.Event:
  395. ce.Reply("QR code timed out. Please restart the login.")
  396. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  397. ce.Reply("Failed to log in: unexpected connection event from server")
  398. case whatsmeow.QRChannelClientOutdated.Event:
  399. ce.Reply("Failed to log in: outdated client. The bridge must be updated to continue.")
  400. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  401. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  402. case "error":
  403. ce.Reply("Failed to log in: %v", item.Error)
  404. case "code":
  405. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  406. }
  407. }
  408. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  409. }
  410. func (user *User) sendQR(ce *WrappedCommandEvent, code string, prevEvent id.EventID) id.EventID {
  411. url, ok := user.uploadQR(ce, code)
  412. if !ok {
  413. return prevEvent
  414. }
  415. content := event.MessageEventContent{
  416. MsgType: event.MsgImage,
  417. Body: code,
  418. URL: url.CUString(),
  419. }
  420. if len(prevEvent) != 0 {
  421. content.SetEdit(prevEvent)
  422. }
  423. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  424. if err != nil {
  425. user.log.Errorln("Failed to send edited QR code to user:", err)
  426. } else if len(prevEvent) == 0 {
  427. prevEvent = resp.EventID
  428. }
  429. return prevEvent
  430. }
  431. func (user *User) uploadQR(ce *WrappedCommandEvent, code string) (id.ContentURI, bool) {
  432. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  433. if err != nil {
  434. user.log.Errorln("Failed to encode QR code:", err)
  435. ce.Reply("Failed to encode QR code: %v", err)
  436. return id.ContentURI{}, false
  437. }
  438. bot := user.bridge.AS.BotClient()
  439. resp, err := bot.UploadBytes(qrCode, "image/png")
  440. if err != nil {
  441. user.log.Errorln("Failed to upload QR code:", err)
  442. ce.Reply("Failed to upload QR code: %v", err)
  443. return id.ContentURI{}, false
  444. }
  445. return resp.ContentURI, true
  446. }
  447. var cmdLogout = &commands.FullHandler{
  448. Func: wrapCommand(fnLogout),
  449. Name: "logout",
  450. Help: commands.HelpMeta{
  451. Section: commands.HelpSectionAuth,
  452. Description: "Unlink the bridge from your WhatsApp account.",
  453. },
  454. }
  455. func fnLogout(ce *WrappedCommandEvent) {
  456. if ce.User.Session == nil {
  457. ce.Reply("You're not logged in.")
  458. return
  459. } else if !ce.User.IsLoggedIn() {
  460. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  461. return
  462. }
  463. puppet := ce.Bridge.GetPuppetByJID(ce.User.JID)
  464. if puppet.CustomMXID != "" {
  465. err := puppet.SwitchCustomMXID("", "")
  466. if err != nil {
  467. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  468. }
  469. }
  470. err := ce.User.Client.Logout()
  471. if err != nil {
  472. ce.User.log.Warnln("Error while logging out:", err)
  473. ce.Reply("Unknown error while logging out: %v", err)
  474. return
  475. }
  476. ce.User.Session = nil
  477. ce.User.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  478. ce.User.DeleteConnection()
  479. ce.User.DeleteSession()
  480. ce.Reply("Logged out successfully.")
  481. }
  482. var cmdTogglePresence = &commands.FullHandler{
  483. Func: wrapCommand(fnTogglePresence),
  484. Name: "toggle-presence",
  485. Help: commands.HelpMeta{
  486. Section: HelpSectionConnectionManagement,
  487. Description: "Toggle bridging of presence or read receipts.",
  488. },
  489. }
  490. func fnTogglePresence(ce *WrappedCommandEvent) {
  491. if ce.User.Session == nil {
  492. ce.Reply("You're not logged in.")
  493. return
  494. }
  495. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  496. if customPuppet == nil {
  497. ce.Reply("You're not logged in with your Matrix account.")
  498. return
  499. }
  500. customPuppet.EnablePresence = !customPuppet.EnablePresence
  501. var newPresence types.Presence
  502. if customPuppet.EnablePresence {
  503. newPresence = types.PresenceAvailable
  504. ce.Reply("Enabled presence bridging")
  505. } else {
  506. newPresence = types.PresenceUnavailable
  507. ce.Reply("Disabled presence bridging")
  508. }
  509. if ce.User.IsLoggedIn() {
  510. err := ce.User.Client.SendPresence(newPresence)
  511. if err != nil {
  512. ce.User.log.Warnln("Failed to set presence:", err)
  513. }
  514. }
  515. customPuppet.Update()
  516. }
  517. var cmdDeleteSession = &commands.FullHandler{
  518. Func: wrapCommand(fnDeleteSession),
  519. Name: "delete-session",
  520. Help: commands.HelpMeta{
  521. Section: commands.HelpSectionAuth,
  522. Description: "Delete session information and disconnect from WhatsApp without sending a logout request.",
  523. },
  524. }
  525. func fnDeleteSession(ce *WrappedCommandEvent) {
  526. if ce.User.Session == nil && ce.User.Client == nil {
  527. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  528. return
  529. }
  530. ce.User.removeFromJIDMap(BridgeState{StateEvent: StateLoggedOut})
  531. ce.User.DeleteConnection()
  532. ce.User.DeleteSession()
  533. ce.Reply("Session information purged")
  534. }
  535. var cmdReconnect = &commands.FullHandler{
  536. Func: wrapCommand(fnReconnect),
  537. Name: "reconnect",
  538. Help: commands.HelpMeta{
  539. Section: HelpSectionConnectionManagement,
  540. Description: "Reconnect to WhatsApp.",
  541. },
  542. }
  543. func fnReconnect(ce *WrappedCommandEvent) {
  544. if ce.User.Client == nil {
  545. if ce.User.Session == nil {
  546. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  547. } else {
  548. ce.User.Connect()
  549. ce.Reply("Started connecting to WhatsApp")
  550. }
  551. } else {
  552. ce.User.DeleteConnection()
  553. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  554. ce.User.Connect()
  555. ce.Reply("Restarted connection to WhatsApp")
  556. }
  557. }
  558. var cmdDisconnect = &commands.FullHandler{
  559. Func: wrapCommand(fnDisconnect),
  560. Name: "disconnect",
  561. Help: commands.HelpMeta{
  562. Section: HelpSectionConnectionManagement,
  563. Description: "Disconnect from WhatsApp (without logging out).",
  564. },
  565. }
  566. func fnDisconnect(ce *WrappedCommandEvent) {
  567. if ce.User.Client == nil {
  568. ce.Reply("You don't have a WhatsApp connection.")
  569. return
  570. }
  571. ce.User.DeleteConnection()
  572. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  573. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  574. }
  575. var cmdPing = &commands.FullHandler{
  576. Func: wrapCommand(fnPing),
  577. Name: "ping",
  578. Help: commands.HelpMeta{
  579. Section: HelpSectionConnectionManagement,
  580. Description: "Check your connection to WhatsApp.",
  581. },
  582. }
  583. func fnPing(ce *WrappedCommandEvent) {
  584. if ce.User.Session == nil {
  585. if ce.User.Client != nil {
  586. ce.Reply("Connected to WhatsApp, but not logged in.")
  587. } else {
  588. ce.Reply("You're not logged into WhatsApp.")
  589. }
  590. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  591. 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)
  592. } else {
  593. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  594. if !ce.User.PhoneRecentlySeen(false) {
  595. ce.Reply("Phone hasn't been seen in %s", formatDisconnectTime(time.Now().Sub(ce.User.PhoneLastSeen)))
  596. }
  597. }
  598. }
  599. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  600. if len(portal.MXID) == 0 {
  601. return false
  602. }
  603. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  604. if err != nil {
  605. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  606. return false
  607. }
  608. for otherUser := range members.Joined {
  609. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  610. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  611. continue
  612. }
  613. user := portal.bridge.GetUserByMXID(otherUser)
  614. if user != nil && user.Session != nil {
  615. return false
  616. }
  617. }
  618. return true
  619. }
  620. var cmdDeletePortal = &commands.FullHandler{
  621. Func: wrapCommand(fnDeletePortal),
  622. Name: "delete-portal",
  623. Help: commands.HelpMeta{
  624. Section: HelpSectionPortalManagement,
  625. Description: "Delete the current portal. If the portal is used by other people, this is limited to bridge admins.",
  626. },
  627. RequiresPortal: true,
  628. }
  629. func fnDeletePortal(ce *WrappedCommandEvent) {
  630. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  631. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  632. return
  633. }
  634. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  635. ce.Portal.Delete()
  636. ce.Portal.Cleanup(false)
  637. }
  638. var cmdDeleteAllPortals = &commands.FullHandler{
  639. Func: wrapCommand(fnDeleteAllPortals),
  640. Name: "delete-all-portals",
  641. Help: commands.HelpMeta{
  642. Section: HelpSectionPortalManagement,
  643. Description: "Delete all portals.",
  644. },
  645. }
  646. func fnDeleteAllPortals(ce *WrappedCommandEvent) {
  647. portals := ce.Bridge.GetAllPortals()
  648. var portalsToDelete []*Portal
  649. if ce.User.Admin {
  650. portalsToDelete = portals
  651. } else {
  652. portalsToDelete = portals[:0]
  653. for _, portal := range portals {
  654. if canDeletePortal(portal, ce.User.MXID) {
  655. portalsToDelete = append(portalsToDelete, portal)
  656. }
  657. }
  658. }
  659. if len(portalsToDelete) == 0 {
  660. ce.Reply("Didn't find any portals to delete")
  661. return
  662. }
  663. leave := func(portal *Portal) {
  664. if len(portal.MXID) > 0 {
  665. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  666. Reason: "Deleting portal",
  667. UserID: ce.User.MXID,
  668. })
  669. }
  670. }
  671. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  672. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  673. intent := customPuppet.CustomIntent()
  674. leave = func(portal *Portal) {
  675. if len(portal.MXID) > 0 {
  676. _, _ = intent.LeaveRoom(portal.MXID)
  677. _, _ = intent.ForgetRoom(portal.MXID)
  678. }
  679. }
  680. }
  681. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  682. for _, portal := range portalsToDelete {
  683. portal.Delete()
  684. leave(portal)
  685. }
  686. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  687. go func() {
  688. for _, portal := range portalsToDelete {
  689. portal.Cleanup(false)
  690. }
  691. ce.Reply("Finished background cleanup of deleted portal rooms.")
  692. }()
  693. }
  694. var cmdBackfill = &commands.FullHandler{
  695. Func: wrapCommand(fnBackfill),
  696. Name: "backfill",
  697. Help: commands.HelpMeta{
  698. Section: HelpSectionPortalManagement,
  699. Description: "Backfill all messages the portal.",
  700. Args: "[_batch size_] [_batch delay_]",
  701. },
  702. RequiresPortal: true,
  703. }
  704. func fnBackfill(ce *WrappedCommandEvent) {
  705. if !ce.Bridge.Config.Bridge.HistorySync.Backfill {
  706. ce.Reply("Backfill is not enabled for this bridge.")
  707. return
  708. }
  709. batchSize := 100
  710. batchDelay := 5
  711. if len(ce.Args) >= 1 {
  712. var err error
  713. batchSize, err = strconv.Atoi(ce.Args[0])
  714. if err != nil || batchSize < 1 {
  715. ce.Reply("\"%s\" isn't a valid batch size", ce.Args[0])
  716. return
  717. }
  718. }
  719. if len(ce.Args) >= 2 {
  720. var err error
  721. batchDelay, err = strconv.Atoi(ce.Args[0])
  722. if err != nil || batchSize < 0 {
  723. ce.Reply("\"%s\" isn't a valid batch delay", ce.Args[1])
  724. return
  725. }
  726. }
  727. backfillMessages := ce.Portal.bridge.DB.Backfill.NewWithValues(ce.User.MXID, database.BackfillImmediate, 0, &ce.Portal.Key, nil, batchSize, -1, batchDelay)
  728. backfillMessages.Insert()
  729. ce.User.BackfillQueue.ReCheck()
  730. }
  731. func matchesQuery(str string, query string) bool {
  732. if query == "" {
  733. return true
  734. }
  735. return strings.Contains(strings.ToLower(str), query)
  736. }
  737. func formatContacts(bridge *WABridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  738. hasQuery := len(query) > 0
  739. for jid, contact := range input {
  740. if len(contact.FullName) == 0 {
  741. continue
  742. }
  743. puppet := bridge.GetPuppetByJID(jid)
  744. pushName := contact.PushName
  745. if len(pushName) == 0 {
  746. pushName = contact.FullName
  747. }
  748. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  749. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  750. }
  751. }
  752. sort.Sort(sort.StringSlice(result))
  753. return
  754. }
  755. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  756. hasQuery := len(query) > 0
  757. for _, group := range input {
  758. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  759. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  760. }
  761. }
  762. sort.Sort(sort.StringSlice(result))
  763. return
  764. }
  765. var cmdList = &commands.FullHandler{
  766. Func: wrapCommand(fnList),
  767. Name: "list",
  768. Help: commands.HelpMeta{
  769. Section: HelpSectionMiscellaneous,
  770. Description: "Get a list of all contacts and groups.",
  771. Args: "<`contacts`|`groups`> [_page_] [_items per page_]",
  772. },
  773. RequiresLogin: true,
  774. }
  775. func fnList(ce *WrappedCommandEvent) {
  776. if len(ce.Args) == 0 {
  777. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  778. return
  779. }
  780. mode := strings.ToLower(ce.Args[0])
  781. if mode[0] != 'g' && mode[0] != 'c' {
  782. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  783. return
  784. }
  785. var err error
  786. page := 1
  787. max := 100
  788. if len(ce.Args) > 1 {
  789. page, err = strconv.Atoi(ce.Args[1])
  790. if err != nil || page <= 0 {
  791. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  792. return
  793. }
  794. }
  795. if len(ce.Args) > 2 {
  796. max, err = strconv.Atoi(ce.Args[2])
  797. if err != nil || max <= 0 {
  798. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  799. return
  800. } else if max > 400 {
  801. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  802. }
  803. }
  804. contacts := mode[0] == 'c'
  805. typeName := "Groups"
  806. var result []string
  807. if contacts {
  808. typeName = "Contacts"
  809. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  810. if err != nil {
  811. ce.Reply("Failed to get contacts: %s", err)
  812. return
  813. }
  814. result = formatContacts(ce.User.bridge, contactList, "")
  815. } else {
  816. groupList, err := ce.User.Client.GetJoinedGroups()
  817. if err != nil {
  818. ce.Reply("Failed to get groups: %s", err)
  819. return
  820. }
  821. result = formatGroups(groupList, "")
  822. }
  823. if len(result) == 0 {
  824. ce.Reply("No %s found", strings.ToLower(typeName))
  825. return
  826. }
  827. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  828. if (page-1)*max >= len(result) {
  829. if pages == 1 {
  830. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  831. } else {
  832. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  833. }
  834. return
  835. }
  836. lastIndex := page * max
  837. if lastIndex > len(result) {
  838. lastIndex = len(result)
  839. }
  840. result = result[(page-1)*max : lastIndex]
  841. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  842. }
  843. var cmdSearch = &commands.FullHandler{
  844. Func: wrapCommand(fnSearch),
  845. Name: "search",
  846. Help: commands.HelpMeta{
  847. Section: HelpSectionMiscellaneous,
  848. Description: "Search for contacts or groups.",
  849. Args: "<_query_>",
  850. },
  851. RequiresLogin: true,
  852. }
  853. func fnSearch(ce *WrappedCommandEvent) {
  854. if len(ce.Args) == 0 {
  855. ce.Reply("**Usage:** `search <query>`")
  856. return
  857. }
  858. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  859. if err != nil {
  860. ce.Reply("Failed to get contacts: %s", err)
  861. return
  862. }
  863. groupList, err := ce.User.Client.GetJoinedGroups()
  864. if err != nil {
  865. ce.Reply("Failed to get groups: %s", err)
  866. return
  867. }
  868. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  869. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  870. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  871. result := make([]string, 0, 2)
  872. if len(formattedContacts) > 0 {
  873. result = append(result, "### Contacts\n\n"+formattedContacts)
  874. }
  875. if len(formattedGroups) > 0 {
  876. result = append(result, "### Groups\n\n"+formattedGroups)
  877. }
  878. if len(result) == 0 {
  879. ce.Reply("No contacts or groups found")
  880. return
  881. }
  882. ce.Reply(strings.Join(result, "\n\n"))
  883. }
  884. var cmdOpen = &commands.FullHandler{
  885. Func: wrapCommand(fnOpen),
  886. Name: "open",
  887. Help: commands.HelpMeta{
  888. Section: HelpSectionCreatingPortals,
  889. Description: "Open a group chat portal.",
  890. Args: "<_group JID_>",
  891. },
  892. RequiresLogin: true,
  893. }
  894. func fnOpen(ce *WrappedCommandEvent) {
  895. if len(ce.Args) == 0 {
  896. ce.Reply("**Usage:** `open <group JID>`")
  897. return
  898. }
  899. var jid types.JID
  900. if strings.ContainsRune(ce.Args[0], '@') {
  901. jid, _ = types.ParseJID(ce.Args[0])
  902. } else {
  903. jid = types.NewJID(ce.Args[0], types.GroupServer)
  904. }
  905. if jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  906. ce.Reply("That does not look like a group JID")
  907. return
  908. }
  909. info, err := ce.User.Client.GetGroupInfo(jid)
  910. if err != nil {
  911. ce.Reply("Failed to get group info: %v", err)
  912. return
  913. }
  914. ce.Log.Debugln("Importing", jid, "for", ce.User.MXID)
  915. portal := ce.User.GetPortalByJID(info.JID)
  916. if len(portal.MXID) > 0 {
  917. portal.UpdateMatrixRoom(ce.User, info)
  918. ce.Reply("Portal room synced.")
  919. } else {
  920. err = portal.CreateMatrixRoom(ce.User, info, true, true)
  921. if err != nil {
  922. ce.Reply("Failed to create room: %v", err)
  923. } else {
  924. ce.Reply("Portal room created.")
  925. }
  926. }
  927. }
  928. var cmdPM = &commands.FullHandler{
  929. Func: wrapCommand(fnPM),
  930. Name: "pm",
  931. Help: commands.HelpMeta{
  932. Section: HelpSectionCreatingPortals,
  933. Description: "Open a private chat with the given phone number.",
  934. Args: "<_international phone number_>",
  935. },
  936. RequiresLogin: true,
  937. }
  938. func fnPM(ce *WrappedCommandEvent) {
  939. if len(ce.Args) == 0 {
  940. ce.Reply("**Usage:** `pm <international phone number>`")
  941. return
  942. }
  943. user := ce.User
  944. number := strings.Join(ce.Args, "")
  945. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  946. if err != nil {
  947. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  948. return
  949. } else if len(resp) == 0 {
  950. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  951. return
  952. }
  953. targetUser := resp[0]
  954. if !targetUser.IsIn {
  955. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  956. return
  957. }
  958. portal, puppet, justCreated, err := user.StartPM(targetUser.JID, "manual PM command")
  959. if err != nil {
  960. ce.Reply("Failed to create portal room: %v", err)
  961. } else if !justCreated {
  962. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  963. } else {
  964. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  965. }
  966. }
  967. var cmdSync = &commands.FullHandler{
  968. Func: wrapCommand(fnSync),
  969. Name: "sync",
  970. Help: commands.HelpMeta{
  971. Section: HelpSectionMiscellaneous,
  972. Description: "Synchronize data from WhatsApp.",
  973. Args: "<appstate/contacts/groups/space> [--create-portals]",
  974. },
  975. RequiresLogin: true,
  976. }
  977. func fnSync(ce *WrappedCommandEvent) {
  978. if len(ce.Args) == 0 {
  979. ce.Reply("**Usage:** `sync <appstate/contacts/groups/space> [--create-portals]`")
  980. return
  981. }
  982. args := strings.ToLower(strings.Join(ce.Args, " "))
  983. contacts := strings.Contains(args, "contacts")
  984. appState := strings.Contains(args, "appstate")
  985. space := strings.Contains(args, "space")
  986. groups := strings.Contains(args, "groups") || space
  987. createPortals := strings.Contains(args, "--create-portals")
  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()
  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.addToSpace(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. }
  1048. func fnDisappearingTimer(ce *WrappedCommandEvent) {
  1049. duration, ok := whatsmeow.ParseDisappearingTimerString(ce.Args[0])
  1050. if !ok {
  1051. ce.Reply("Invalid timer '%s'", ce.Args[0])
  1052. return
  1053. }
  1054. prevExpirationTime := ce.Portal.ExpirationTime
  1055. ce.Portal.ExpirationTime = uint32(duration.Seconds())
  1056. err := ce.User.Client.SetDisappearingTimer(ce.Portal.Key.JID, duration)
  1057. if err != nil {
  1058. ce.Reply("Failed to set disappearing timer: %v", err)
  1059. ce.Portal.ExpirationTime = prevExpirationTime
  1060. return
  1061. }
  1062. ce.Portal.Update(nil)
  1063. if !ce.Portal.IsPrivateChat() && !ce.Bridge.Config.Bridge.DisappearingMessagesInGroups {
  1064. ce.Reply("Disappearing timer changed successfully, but this bridge is not configured to disappear messages in group chats.")
  1065. } else {
  1066. ce.React("✅")
  1067. }
  1068. }