commands.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. }
  575. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  576. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  577. if ce.User.Session == nil {
  578. ce.Reply("You're not logged into WhatsApp.")
  579. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  580. ce.Reply("You don't have a WhatsApp connection.")
  581. } else {
  582. ce.Reply("Connection to WhatsApp OK (probably)")
  583. }
  584. }
  585. const cmdHelpHelp = `help - Prints this help`
  586. // CommandHelp handles help command
  587. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  588. cmdPrefix := ""
  589. if ce.User.ManagementRoom != ce.RoomID {
  590. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  591. }
  592. ce.Reply("* " + strings.Join([]string{
  593. cmdPrefix + cmdHelpHelp,
  594. cmdPrefix + cmdVersionHelp,
  595. cmdPrefix + cmdLoginHelp,
  596. cmdPrefix + cmdLogoutHelp,
  597. cmdPrefix + cmdDeleteSessionHelp,
  598. cmdPrefix + cmdReconnectHelp,
  599. cmdPrefix + cmdDisconnectHelp,
  600. cmdPrefix + cmdPingHelp,
  601. cmdPrefix + cmdSetRelayHelp,
  602. cmdPrefix + cmdUnsetRelayHelp,
  603. cmdPrefix + cmdLoginMatrixHelp,
  604. cmdPrefix + cmdLogoutMatrixHelp,
  605. cmdPrefix + cmdToggleHelp,
  606. cmdPrefix + cmdListHelp,
  607. cmdPrefix + cmdOpenHelp,
  608. cmdPrefix + cmdPMHelp,
  609. cmdPrefix + cmdInviteLinkHelp,
  610. cmdPrefix + cmdJoinHelp,
  611. cmdPrefix + cmdCreateHelp,
  612. cmdPrefix + cmdSetPowerLevelHelp,
  613. cmdPrefix + cmdDeletePortalHelp,
  614. cmdPrefix + cmdDeleteAllPortalsHelp,
  615. }, "\n* "))
  616. }
  617. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  618. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  619. if err != nil {
  620. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  621. return false
  622. }
  623. for otherUser := range members.Joined {
  624. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  625. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  626. continue
  627. }
  628. user := portal.bridge.GetUserByMXID(otherUser)
  629. if user != nil && user.Session != nil {
  630. return false
  631. }
  632. }
  633. return true
  634. }
  635. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  636. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  637. if ce.Portal == nil {
  638. ce.Reply("You must be in a portal room to use that command")
  639. return
  640. }
  641. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  642. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  643. return
  644. }
  645. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  646. ce.Portal.Delete()
  647. ce.Portal.Cleanup(false)
  648. }
  649. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  650. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  651. portals := handler.bridge.GetAllPortals()
  652. var portalsToDelete []*Portal
  653. if ce.User.Admin {
  654. portals = portalsToDelete
  655. } else {
  656. portalsToDelete = portals[:0]
  657. for _, portal := range portals {
  658. if canDeletePortal(portal, ce.User.MXID) {
  659. portalsToDelete = append(portalsToDelete, portal)
  660. }
  661. }
  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 := handler.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. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  695. //func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  696. // for jid, contact := range input {
  697. // if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  698. // continue
  699. // }
  700. //
  701. // if contacts {
  702. // result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  703. // } else {
  704. // result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  705. // }
  706. // }
  707. // sort.Sort(sort.StringSlice(result))
  708. // return
  709. //}
  710. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  711. if len(ce.Args) == 0 {
  712. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  713. return
  714. }
  715. mode := strings.ToLower(ce.Args[0])
  716. if mode[0] != 'g' && mode[0] != 'c' {
  717. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  718. return
  719. }
  720. var err error
  721. page := 1
  722. max := 100
  723. if len(ce.Args) > 1 {
  724. page, err = strconv.Atoi(ce.Args[1])
  725. if err != nil || page <= 0 {
  726. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  727. return
  728. }
  729. }
  730. if len(ce.Args) > 2 {
  731. max, err = strconv.Atoi(ce.Args[2])
  732. if err != nil || max <= 0 {
  733. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  734. return
  735. } else if max > 400 {
  736. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  737. }
  738. }
  739. ce.Reply("Not yet implemented")
  740. // TODO reimplement
  741. //contacts := mode[0] == 'c'
  742. //typeName := "Groups"
  743. //if contacts {
  744. // typeName = "Contacts"
  745. //}
  746. //ce.User.Conn.Store.ContactsLock.RLock()
  747. //result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  748. //ce.User.Conn.Store.ContactsLock.RUnlock()
  749. //if len(result) == 0 {
  750. // ce.Reply("No %s found", strings.ToLower(typeName))
  751. // return
  752. //}
  753. //pages := int(math.Ceil(float64(len(result)) / float64(max)))
  754. //if (page-1)*max >= len(result) {
  755. // if pages == 1 {
  756. // ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  757. // } else {
  758. // ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  759. // }
  760. // return
  761. //}
  762. //lastIndex := page * max
  763. //if lastIndex > len(result) {
  764. // lastIndex = len(result)
  765. //}
  766. //result = result[(page-1)*max : lastIndex]
  767. //ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  768. }
  769. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  770. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  771. if len(ce.Args) == 0 {
  772. ce.Reply("**Usage:** `open <group JID>`")
  773. return
  774. }
  775. ce.Reply("Not yet implemented")
  776. // TODO reimplement
  777. //user := ce.User
  778. //jid := ce.Args[0]
  779. //if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  780. // ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  781. // return
  782. //}
  783. //
  784. //user.Conn.Store.ContactsLock.RLock()
  785. //contact, ok := user.Conn.Store.Contacts[jid]
  786. //user.Conn.Store.ContactsLock.RUnlock()
  787. //if !ok {
  788. // ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  789. // return
  790. //}
  791. //handler.log.Debugln("Importing", jid, "for", user)
  792. //portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  793. //if len(portal.MXID) > 0 {
  794. // portal.Sync(user, contact)
  795. // ce.Reply("Portal room synced.")
  796. //} else {
  797. // portal.Sync(user, contact)
  798. // ce.Reply("Portal room created.")
  799. //}
  800. //_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  801. }
  802. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  803. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  804. if len(ce.Args) == 0 {
  805. ce.Reply("**Usage:** `pm <international phone number>`")
  806. return
  807. }
  808. user := ce.User
  809. number := strings.Join(ce.Args, "")
  810. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  811. if err != nil {
  812. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  813. return
  814. } else if len(resp) == 0 {
  815. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  816. return
  817. }
  818. targetUser := resp[0]
  819. if !targetUser.IsIn {
  820. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  821. return
  822. }
  823. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  824. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  825. puppet.SyncContact(user, true)
  826. portal := user.GetPortalByJID(puppet.JID)
  827. if len(portal.MXID) > 0 {
  828. ok := portal.ensureUserInvited(user)
  829. if !ok {
  830. portal.log.Warnfln("ensureUserInvited(%s) returned false, creating new portal", user.MXID)
  831. portal.MXID = ""
  832. } else {
  833. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  834. return
  835. }
  836. }
  837. err = portal.CreateMatrixRoom(user)
  838. if err != nil {
  839. ce.Reply("Failed to create portal room: %v", err)
  840. return
  841. }
  842. ce.Reply("Created portal room and invited you to it.")
  843. }
  844. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  845. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  846. if len(ce.Args) == 0 {
  847. ce.Reply("**Usage:** `login-matrix <access token>`")
  848. return
  849. }
  850. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  851. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  852. if err != nil {
  853. ce.Reply("Failed to switch puppet: %v", err)
  854. return
  855. }
  856. ce.Reply("Successfully switched puppet")
  857. }
  858. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  859. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  860. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  861. if len(puppet.CustomMXID) == 0 {
  862. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  863. return
  864. }
  865. err := puppet.SwitchCustomMXID("", "")
  866. if err != nil {
  867. ce.Reply("Failed to remove custom puppet: %v", err)
  868. return
  869. }
  870. ce.Reply("Successfully removed custom puppet")
  871. }