commands.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. "errors"
  20. "fmt"
  21. "strconv"
  22. "strings"
  23. "github.com/skip2/go-qrcode"
  24. "maunium.net/go/maulogger/v2"
  25. "go.mau.fi/whatsmeow"
  26. "go.mau.fi/whatsmeow/types"
  27. "maunium.net/go/mautrix"
  28. "maunium.net/go/mautrix/appservice"
  29. "maunium.net/go/mautrix/event"
  30. "maunium.net/go/mautrix/format"
  31. "maunium.net/go/mautrix/id"
  32. )
  33. type CommandHandler struct {
  34. bridge *Bridge
  35. log maulogger.Logger
  36. }
  37. // NewCommandHandler creates a CommandHandler
  38. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  39. return &CommandHandler{
  40. bridge: bridge,
  41. log: bridge.Log.Sub("Command handler"),
  42. }
  43. }
  44. // CommandEvent stores all data which might be used to handle commands
  45. type CommandEvent struct {
  46. Bot *appservice.IntentAPI
  47. Bridge *Bridge
  48. Portal *Portal
  49. Handler *CommandHandler
  50. RoomID id.RoomID
  51. User *User
  52. Command string
  53. Args []string
  54. }
  55. // Reply sends a reply to command as notice
  56. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  57. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  58. content.MsgType = event.MsgNotice
  59. intent := ce.Bot
  60. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  61. intent = ce.Portal.MainIntent()
  62. }
  63. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  64. if err != nil {
  65. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  66. }
  67. }
  68. // Handle handles messages to the bridge
  69. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
  70. args := strings.Fields(message)
  71. if len(args) == 0 {
  72. args = []string{"unknown-command"}
  73. }
  74. ce := &CommandEvent{
  75. Bot: handler.bridge.Bot,
  76. Bridge: handler.bridge,
  77. Portal: handler.bridge.GetPortalByMXID(roomID),
  78. Handler: handler,
  79. RoomID: roomID,
  80. User: user,
  81. Command: strings.ToLower(args[0]),
  82. Args: args[1:],
  83. }
  84. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  85. handler.CommandMux(ce)
  86. }
  87. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  88. switch ce.Command {
  89. case "login":
  90. handler.CommandLogin(ce)
  91. case "ping-matrix":
  92. handler.CommandPingMatrix(ce)
  93. case "logout-matrix":
  94. handler.CommandLogoutMatrix(ce)
  95. case "help":
  96. handler.CommandHelp(ce)
  97. case "version":
  98. handler.CommandVersion(ce)
  99. case "reconnect", "connect":
  100. handler.CommandReconnect(ce)
  101. case "disconnect":
  102. handler.CommandDisconnect(ce)
  103. case "ping":
  104. handler.CommandPing(ce)
  105. case "delete-session":
  106. handler.CommandDeleteSession(ce)
  107. case "delete-portal":
  108. handler.CommandDeletePortal(ce)
  109. case "delete-all-portals":
  110. handler.CommandDeleteAllPortals(ce)
  111. case "discard-megolm-session", "discard-session":
  112. handler.CommandDiscardMegolmSession(ce)
  113. case "dev-test":
  114. handler.CommandDevTest(ce)
  115. case "set-pl":
  116. handler.CommandSetPowerLevel(ce)
  117. case "logout":
  118. handler.CommandLogout(ce)
  119. case "toggle":
  120. handler.CommandToggle(ce)
  121. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "open", "pm", "invite-link", "join", "create":
  122. if !ce.User.HasSession() {
  123. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  124. return
  125. } else if !ce.User.IsLoggedIn() {
  126. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  127. return
  128. }
  129. switch ce.Command {
  130. case "set-relay":
  131. handler.CommandSetRelay(ce)
  132. case "unset-relay":
  133. handler.CommandUnsetRelay(ce)
  134. case "login-matrix":
  135. handler.CommandLoginMatrix(ce)
  136. case "list":
  137. handler.CommandList(ce)
  138. case "open":
  139. handler.CommandOpen(ce)
  140. case "pm":
  141. handler.CommandPM(ce)
  142. case "invite-link":
  143. handler.CommandInviteLink(ce)
  144. case "join":
  145. handler.CommandJoin(ce)
  146. case "create":
  147. handler.CommandCreate(ce)
  148. }
  149. default:
  150. ce.Reply("Unknown command, use the `help` command for help.")
  151. }
  152. }
  153. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  154. if handler.bridge.Crypto == nil {
  155. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  156. } else if !ce.User.Admin {
  157. ce.Reply("Only the bridge admin can reset Megolm sessions")
  158. } else {
  159. handler.bridge.Crypto.ResetSession(ce.RoomID)
  160. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  161. }
  162. }
  163. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  164. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  165. if !handler.bridge.Config.Bridge.Relay.Enabled {
  166. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  167. } else if ce.Portal == nil {
  168. ce.Reply("This is not a portal room")
  169. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  170. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  171. } else {
  172. ce.Portal.RelayUserID = ce.User.MXID
  173. ce.Portal.Update()
  174. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  175. }
  176. }
  177. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  178. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  179. if !handler.bridge.Config.Bridge.Relay.Enabled {
  180. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  181. } else if ce.Portal == nil {
  182. ce.Reply("This is not a portal room")
  183. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  184. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  185. } else {
  186. ce.Portal.RelayUserID = ""
  187. ce.Portal.Update()
  188. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  189. }
  190. }
  191. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  192. }
  193. const cmdVersionHelp = `version - View the bridge version`
  194. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  195. linkifiedVersion := fmt.Sprintf("v%s", Version)
  196. if Tag == Version {
  197. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  198. } else if len(Commit) > 8 {
  199. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  200. }
  201. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  202. }
  203. const cmdInviteLinkHelp = `invite-link - Get an invite link to the current group chat.`
  204. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  205. if ce.Portal == nil {
  206. ce.Reply("Not a portal room")
  207. return
  208. } else if ce.Portal.IsPrivateChat() {
  209. ce.Reply("Can't get invite link to private chat")
  210. return
  211. }
  212. ce.Reply("Not yet implemented")
  213. // TODO reimplement
  214. //link, err := ce.User.Conn.GroupInviteLink(ce.Portal.Key.JID)
  215. //if err != nil {
  216. // ce.Reply("Failed to get invite link: %v", err)
  217. // return
  218. //}
  219. //ce.Reply("%s%s", inviteLinkPrefix, link)
  220. }
  221. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  222. const inviteLinkPrefix = "https://chat.whatsapp.com/"
  223. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  224. if len(ce.Args) == 0 {
  225. ce.Reply("**Usage:** `join <invite link>`")
  226. return
  227. } else if len(ce.Args[0]) <= len(inviteLinkPrefix) || ce.Args[0][:len(inviteLinkPrefix)] != inviteLinkPrefix {
  228. ce.Reply("That doesn't look like a WhatsApp invite link")
  229. return
  230. }
  231. ce.Reply("Not yet implemented")
  232. // TODO reimplement
  233. //jid, err := ce.User.Conn.GroupAcceptInviteCode(ce.Args[0][len(inviteLinkPrefix):])
  234. //if err != nil {
  235. // ce.Reply("Failed to join group: %v", err)
  236. // return
  237. //}
  238. //
  239. //handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  240. //portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  241. //if len(portal.MXID) > 0 {
  242. // portal.Sync(ce.User, whatsapp.Contact{JID: portal.Key.JID})
  243. // ce.Reply("Successfully joined group \"%s\" and synced portal room: [%s](https://matrix.to/#/%s)", portal.Name, portal.Name, portal.MXID)
  244. //} else {
  245. // err = portal.CreateMatrixRoom(ce.User)
  246. // if err != nil {
  247. // ce.Reply("Failed to create portal room: %v", err)
  248. // return
  249. // }
  250. //
  251. // ce.Reply("Successfully joined group \"%s\" and created portal room: [%s](https://matrix.to/#/%s)", portal.Name, portal.Name, portal.MXID)
  252. //}
  253. }
  254. const cmdCreateHelp = `create - Create a group chat.`
  255. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  256. if ce.Portal != nil {
  257. ce.Reply("This is already a portal room")
  258. return
  259. }
  260. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  261. if err != nil {
  262. ce.Reply("Failed to get room members: %v", err)
  263. return
  264. }
  265. var roomNameEvent event.RoomNameEventContent
  266. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  267. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  268. ce.Reply("Failed to get room name")
  269. return
  270. } else if len(roomNameEvent.Name) == 0 {
  271. ce.Reply("Please set a name for the room first")
  272. return
  273. }
  274. var encryptionEvent event.EncryptionEventContent
  275. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  276. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  277. ce.Reply("Failed to get room encryption status")
  278. return
  279. }
  280. participants := []types.JID{ce.User.JID.ToNonAD()}
  281. for userID := range members.Joined {
  282. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  283. if ok && jid.User != ce.User.JID.User {
  284. participants = append(participants, jid)
  285. }
  286. }
  287. ce.Reply("Not yet implemented")
  288. // TODO reimplement
  289. //resp, err := ce.User.Conn.CreateGroup(roomNameEvent.Name, participants)
  290. //if err != nil {
  291. // ce.Reply("Failed to create group: %v", err)
  292. // return
  293. //}
  294. //portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(resp.GroupID))
  295. //portal.roomCreateLock.Lock()
  296. //defer portal.roomCreateLock.Unlock()
  297. //if len(portal.MXID) != 0 {
  298. // portal.log.Warnln("Detected race condition in room creation")
  299. // // TODO race condition, clean up the old room
  300. //}
  301. //portal.MXID = ce.RoomID
  302. //portal.Name = roomNameEvent.Name
  303. //portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  304. //if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  305. // _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  306. // if err != nil {
  307. // portal.log.Warnln("Failed to enable e2be:", err)
  308. // }
  309. // portal.Encrypted = true
  310. //}
  311. //
  312. //portal.Update()
  313. //portal.UpdateBridgeInfo()
  314. //
  315. //ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  316. //inCommunity := ce.User.addPortalToCommunity(portal)
  317. //ce.User.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
  318. }
  319. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  320. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  321. if ce.Portal == nil {
  322. ce.Reply("Not a portal room")
  323. return
  324. }
  325. var level int
  326. var userID id.UserID
  327. var err error
  328. if len(ce.Args) == 1 {
  329. level, err = strconv.Atoi(ce.Args[0])
  330. if err != nil {
  331. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  332. return
  333. }
  334. userID = ce.User.MXID
  335. } else if len(ce.Args) == 2 {
  336. userID = id.UserID(ce.Args[0])
  337. _, _, err := userID.Parse()
  338. if err != nil {
  339. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  340. return
  341. }
  342. level, err = strconv.Atoi(ce.Args[1])
  343. if err != nil {
  344. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  345. return
  346. }
  347. } else {
  348. ce.Reply("**Usage:** `set-pl [user] <level>`")
  349. return
  350. }
  351. intent := ce.Portal.MainIntent()
  352. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  353. if err != nil {
  354. ce.Reply("Failed to set power levels: %v", err)
  355. }
  356. }
  357. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  358. // CommandLogin handles login command
  359. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  360. if ce.User.Session != nil {
  361. if ce.User.IsConnected() {
  362. ce.Reply("You're already logged in")
  363. } else {
  364. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  365. }
  366. return
  367. }
  368. qrChan, err := ce.User.Login(context.Background())
  369. if err != nil {
  370. ce.User.log.Errorf("Failed to log in:", err)
  371. ce.Reply("Failed to log in: %v", err)
  372. return
  373. }
  374. var qrEventID id.EventID
  375. for item := range qrChan {
  376. switch item {
  377. case whatsmeow.QRChannelSuccess:
  378. jid := ce.User.Client.Store.ID
  379. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  380. case whatsmeow.QRChannelTimeout:
  381. ce.Reply("QR code timed out. Please restart the login.")
  382. case whatsmeow.QRChannelErrUnexpectedEvent:
  383. ce.Reply("Failed to log in: unexpected connection event from server")
  384. case whatsmeow.QRChannelScannedWithoutMultidevice:
  385. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  386. default:
  387. qrEventID = ce.User.sendQR(ce, string(item), qrEventID)
  388. }
  389. }
  390. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  391. }
  392. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  393. url, ok := user.uploadQR(ce, code)
  394. if !ok {
  395. return prevEvent
  396. }
  397. content := event.MessageEventContent{
  398. MsgType: event.MsgImage,
  399. Body: code,
  400. URL: url.CUString(),
  401. }
  402. if len(prevEvent) != 0 {
  403. content.SetEdit(prevEvent)
  404. }
  405. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  406. if err != nil {
  407. user.log.Errorln("Failed to send edited QR code to user:", err)
  408. } else if len(prevEvent) == 0 {
  409. prevEvent = resp.EventID
  410. }
  411. return prevEvent
  412. }
  413. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  414. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  415. if err != nil {
  416. user.log.Errorln("Failed to encode QR code:", err)
  417. ce.Reply("Failed to encode QR code: %v", err)
  418. return id.ContentURI{}, false
  419. }
  420. bot := user.bridge.AS.BotClient()
  421. resp, err := bot.UploadBytes(qrCode, "image/png")
  422. if err != nil {
  423. user.log.Errorln("Failed to upload QR code:", err)
  424. ce.Reply("Failed to upload QR code: %v", err)
  425. return id.ContentURI{}, false
  426. }
  427. return resp.ContentURI, true
  428. }
  429. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  430. // CommandLogout handles !logout command
  431. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  432. if ce.User.Session == nil {
  433. ce.Reply("You're not logged in.")
  434. return
  435. } else if !ce.User.IsLoggedIn() {
  436. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  437. return
  438. }
  439. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  440. if puppet.CustomMXID != "" {
  441. err := puppet.SwitchCustomMXID("", "")
  442. if err != nil {
  443. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  444. }
  445. }
  446. err := ce.User.Client.Logout()
  447. if err != nil {
  448. ce.User.log.Warnln("Error while logging out:", err)
  449. ce.Reply("Unknown error while logging out: %v", err)
  450. return
  451. }
  452. ce.User.Session = nil
  453. ce.User.removeFromJIDMap(StateLoggedOut)
  454. ce.User.DeleteConnection()
  455. ce.User.DeleteSession()
  456. ce.Reply("Logged out successfully.")
  457. }
  458. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  459. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  460. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  461. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  462. return
  463. }
  464. if ce.User.Session == nil {
  465. ce.Reply("You're not logged in.")
  466. return
  467. }
  468. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  469. if customPuppet == nil {
  470. ce.Reply("You're not logged in with your Matrix account.")
  471. return
  472. }
  473. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  474. customPuppet.EnablePresence = !customPuppet.EnablePresence
  475. var newPresence types.Presence
  476. if customPuppet.EnablePresence {
  477. newPresence = types.PresenceAvailable
  478. ce.Reply("Enabled presence bridging")
  479. } else {
  480. newPresence = types.PresenceUnavailable
  481. ce.Reply("Disabled presence bridging")
  482. }
  483. if ce.User.IsLoggedIn() {
  484. err := ce.User.Client.SendPresence(newPresence)
  485. if err != nil {
  486. ce.User.log.Warnln("Failed to set presence:", err)
  487. }
  488. }
  489. }
  490. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  491. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  492. if customPuppet.EnableReceipts {
  493. ce.Reply("Enabled read receipt bridging")
  494. } else {
  495. ce.Reply("Disabled read receipt bridging")
  496. }
  497. }
  498. customPuppet.Update()
  499. }
  500. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  501. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  502. if ce.User.Session == nil && ce.User.Client == nil {
  503. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  504. return
  505. }
  506. ce.User.removeFromJIDMap(StateLoggedOut)
  507. ce.User.DeleteConnection()
  508. ce.User.DeleteSession()
  509. ce.Reply("Session information purged")
  510. }
  511. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  512. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  513. if ce.User.Client == nil {
  514. if ce.User.Session == nil {
  515. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  516. } else {
  517. ce.User.Connect()
  518. ce.Reply("Started connecting to WhatsApp")
  519. }
  520. } else {
  521. ce.User.DeleteConnection()
  522. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  523. ce.User.Connect()
  524. ce.Reply("Restarted connection to WhatsApp")
  525. }
  526. }
  527. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  528. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  529. if ce.User.Client == nil {
  530. ce.Reply("You don't have a WhatsApp connection.")
  531. return
  532. }
  533. ce.User.DeleteConnection()
  534. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  535. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  536. }
  537. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  538. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  539. if ce.User.Session == nil {
  540. ce.Reply("You're not logged into WhatsApp.")
  541. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  542. ce.Reply("You don't have a WhatsApp connection.")
  543. } else {
  544. ce.Reply("Connection to WhatsApp OK (probably)")
  545. }
  546. }
  547. const cmdHelpHelp = `help - Prints this help`
  548. // CommandHelp handles help command
  549. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  550. cmdPrefix := ""
  551. if ce.User.ManagementRoom != ce.RoomID {
  552. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  553. }
  554. ce.Reply("* " + strings.Join([]string{
  555. cmdPrefix + cmdHelpHelp,
  556. cmdPrefix + cmdVersionHelp,
  557. cmdPrefix + cmdLoginHelp,
  558. cmdPrefix + cmdLogoutHelp,
  559. cmdPrefix + cmdDeleteSessionHelp,
  560. cmdPrefix + cmdReconnectHelp,
  561. cmdPrefix + cmdDisconnectHelp,
  562. cmdPrefix + cmdPingHelp,
  563. cmdPrefix + cmdSetRelayHelp,
  564. cmdPrefix + cmdUnsetRelayHelp,
  565. cmdPrefix + cmdLoginMatrixHelp,
  566. cmdPrefix + cmdPingMatrixHelp,
  567. cmdPrefix + cmdLogoutMatrixHelp,
  568. cmdPrefix + cmdToggleHelp,
  569. cmdPrefix + cmdListHelp,
  570. cmdPrefix + cmdOpenHelp,
  571. cmdPrefix + cmdPMHelp,
  572. cmdPrefix + cmdInviteLinkHelp,
  573. cmdPrefix + cmdJoinHelp,
  574. cmdPrefix + cmdCreateHelp,
  575. cmdPrefix + cmdSetPowerLevelHelp,
  576. cmdPrefix + cmdDeletePortalHelp,
  577. cmdPrefix + cmdDeleteAllPortalsHelp,
  578. }, "\n* "))
  579. }
  580. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  581. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  582. if err != nil {
  583. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  584. return false
  585. }
  586. for otherUser := range members.Joined {
  587. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  588. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  589. continue
  590. }
  591. user := portal.bridge.GetUserByMXID(otherUser)
  592. if user != nil && user.Session != nil {
  593. return false
  594. }
  595. }
  596. return true
  597. }
  598. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  599. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  600. if ce.Portal == nil {
  601. ce.Reply("You must be in a portal room to use that command")
  602. return
  603. }
  604. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  605. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  606. return
  607. }
  608. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  609. ce.Portal.Delete()
  610. ce.Portal.Cleanup(false)
  611. }
  612. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  613. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  614. portals := handler.bridge.GetAllPortals()
  615. var portalsToDelete []*Portal
  616. if ce.User.Admin {
  617. portalsToDelete = portals
  618. } else {
  619. portalsToDelete = portals[:0]
  620. for _, portal := range portals {
  621. if canDeletePortal(portal, ce.User.MXID) {
  622. portalsToDelete = append(portalsToDelete, portal)
  623. }
  624. }
  625. }
  626. leave := func(portal *Portal) {
  627. if len(portal.MXID) > 0 {
  628. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  629. Reason: "Deleting portal",
  630. UserID: ce.User.MXID,
  631. })
  632. }
  633. }
  634. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  635. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  636. intent := customPuppet.CustomIntent()
  637. leave = func(portal *Portal) {
  638. if len(portal.MXID) > 0 {
  639. _, _ = intent.LeaveRoom(portal.MXID)
  640. _, _ = intent.ForgetRoom(portal.MXID)
  641. }
  642. }
  643. }
  644. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  645. for _, portal := range portalsToDelete {
  646. portal.Delete()
  647. leave(portal)
  648. }
  649. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  650. go func() {
  651. for _, portal := range portalsToDelete {
  652. portal.Cleanup(false)
  653. }
  654. ce.Reply("Finished background cleanup of deleted portal rooms.")
  655. }()
  656. }
  657. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  658. //func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  659. // for jid, contact := range input {
  660. // if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  661. // continue
  662. // }
  663. //
  664. // if contacts {
  665. // result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  666. // } else {
  667. // result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  668. // }
  669. // }
  670. // sort.Sort(sort.StringSlice(result))
  671. // return
  672. //}
  673. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  674. if len(ce.Args) == 0 {
  675. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  676. return
  677. }
  678. mode := strings.ToLower(ce.Args[0])
  679. if mode[0] != 'g' && mode[0] != 'c' {
  680. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  681. return
  682. }
  683. var err error
  684. page := 1
  685. max := 100
  686. if len(ce.Args) > 1 {
  687. page, err = strconv.Atoi(ce.Args[1])
  688. if err != nil || page <= 0 {
  689. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  690. return
  691. }
  692. }
  693. if len(ce.Args) > 2 {
  694. max, err = strconv.Atoi(ce.Args[2])
  695. if err != nil || max <= 0 {
  696. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  697. return
  698. } else if max > 400 {
  699. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  700. }
  701. }
  702. ce.Reply("Not yet implemented")
  703. // TODO reimplement
  704. //contacts := mode[0] == 'c'
  705. //typeName := "Groups"
  706. //if contacts {
  707. // typeName = "Contacts"
  708. //}
  709. //ce.User.Conn.Store.ContactsLock.RLock()
  710. //result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  711. //ce.User.Conn.Store.ContactsLock.RUnlock()
  712. //if len(result) == 0 {
  713. // ce.Reply("No %s found", strings.ToLower(typeName))
  714. // return
  715. //}
  716. //pages := int(math.Ceil(float64(len(result)) / float64(max)))
  717. //if (page-1)*max >= len(result) {
  718. // if pages == 1 {
  719. // ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  720. // } else {
  721. // ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  722. // }
  723. // return
  724. //}
  725. //lastIndex := page * max
  726. //if lastIndex > len(result) {
  727. // lastIndex = len(result)
  728. //}
  729. //result = result[(page-1)*max : lastIndex]
  730. //ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  731. }
  732. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  733. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  734. if len(ce.Args) == 0 {
  735. ce.Reply("**Usage:** `open <group JID>`")
  736. return
  737. }
  738. ce.Reply("Not yet implemented")
  739. // TODO reimplement
  740. //user := ce.User
  741. //jid := ce.Args[0]
  742. //if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  743. // ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  744. // return
  745. //}
  746. //
  747. //user.Conn.Store.ContactsLock.RLock()
  748. //contact, ok := user.Conn.Store.Contacts[jid]
  749. //user.Conn.Store.ContactsLock.RUnlock()
  750. //if !ok {
  751. // ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  752. // return
  753. //}
  754. //handler.log.Debugln("Importing", jid, "for", user)
  755. //portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  756. //if len(portal.MXID) > 0 {
  757. // portal.Sync(user, contact)
  758. // ce.Reply("Portal room synced.")
  759. //} else {
  760. // portal.Sync(user, contact)
  761. // ce.Reply("Portal room created.")
  762. //}
  763. //_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  764. }
  765. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  766. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  767. if len(ce.Args) == 0 {
  768. ce.Reply("**Usage:** `pm <international phone number>`")
  769. return
  770. }
  771. user := ce.User
  772. number := strings.Join(ce.Args, "")
  773. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  774. if err != nil {
  775. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  776. return
  777. } else if len(resp) == 0 {
  778. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  779. return
  780. }
  781. targetUser := resp[0]
  782. if !targetUser.IsIn {
  783. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  784. return
  785. }
  786. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  787. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  788. puppet.SyncContact(user, true)
  789. portal := user.GetPortalByJID(puppet.JID)
  790. if len(portal.MXID) > 0 {
  791. ok := portal.ensureUserInvited(user)
  792. if !ok {
  793. portal.log.Warnfln("ensureUserInvited(%s) returned false, creating new portal", user.MXID)
  794. portal.MXID = ""
  795. } else {
  796. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  797. return
  798. }
  799. }
  800. err = portal.CreateMatrixRoom(user)
  801. if err != nil {
  802. ce.Reply("Failed to create portal room: %v", err)
  803. return
  804. }
  805. ce.Reply("Created portal room and invited you to it.")
  806. }
  807. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  808. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  809. if len(ce.Args) == 0 {
  810. ce.Reply("**Usage:** `login-matrix <access token>`")
  811. return
  812. }
  813. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  814. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  815. if err != nil {
  816. ce.Reply("Failed to switch puppet: %v", err)
  817. return
  818. }
  819. ce.Reply("Successfully switched puppet")
  820. }
  821. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  822. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  823. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  824. if puppet == nil || puppet.CustomIntent() == nil {
  825. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  826. return
  827. }
  828. resp, err := puppet.CustomIntent().Whoami()
  829. if err != nil {
  830. ce.Reply("Failed to validate Matrix login: %v", err)
  831. } else {
  832. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  833. }
  834. }
  835. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  836. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  837. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  838. if puppet == nil || puppet.CustomIntent() == nil {
  839. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  840. return
  841. }
  842. err := puppet.SwitchCustomMXID("", "")
  843. if err != nil {
  844. ce.Reply("Failed to remove custom puppet: %v", err)
  845. return
  846. }
  847. ce.Reply("Successfully removed custom puppet")
  848. }