commands.go 31 KB

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