commands.go 28 KB

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