commands.go 29 KB

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