commands.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  262. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  263. ce.Reply("Failed to get reply event")
  264. } else if meta, ok := evt.Content.Raw[inviteMetaField].(map[string]interface{}); !ok {
  265. ce.Reply("That doesn't look like a group invite message.")
  266. } else if jid, inviter, code, expiration, ok := parseInviteMeta(meta); !ok {
  267. ce.Reply("That doesn't look like a group invite message.")
  268. } else if inviter.User == ce.User.JID.User {
  269. ce.Reply("You can't accept your own invites")
  270. } else if err = ce.User.Client.AcceptGroupInvite(jid, inviter, code, expiration); err != nil {
  271. ce.Reply("Failed to accept group invite: %v", err)
  272. } else {
  273. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  274. }
  275. }
  276. const cmdCreateHelp = `create - Create a group chat.`
  277. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  278. if ce.Portal != nil {
  279. ce.Reply("This is already a portal room")
  280. return
  281. }
  282. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  283. if err != nil {
  284. ce.Reply("Failed to get room members: %v", err)
  285. return
  286. }
  287. var roomNameEvent event.RoomNameEventContent
  288. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  289. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  290. ce.Reply("Failed to get room name")
  291. return
  292. } else if len(roomNameEvent.Name) == 0 {
  293. ce.Reply("Please set a name for the room first")
  294. return
  295. }
  296. var encryptionEvent event.EncryptionEventContent
  297. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  298. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  299. ce.Reply("Failed to get room encryption status")
  300. return
  301. }
  302. participants := []types.JID{ce.User.JID.ToNonAD()}
  303. for userID := range members.Joined {
  304. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  305. if ok && jid.User != ce.User.JID.User {
  306. participants = append(participants, jid)
  307. }
  308. }
  309. ce.Reply("Not yet implemented")
  310. // TODO reimplement
  311. //resp, err := ce.User.Conn.CreateGroup(roomNameEvent.Name, participants)
  312. //if err != nil {
  313. // ce.Reply("Failed to create group: %v", err)
  314. // return
  315. //}
  316. //portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(resp.GroupID))
  317. //portal.roomCreateLock.Lock()
  318. //defer portal.roomCreateLock.Unlock()
  319. //if len(portal.MXID) != 0 {
  320. // portal.log.Warnln("Detected race condition in room creation")
  321. // // TODO race condition, clean up the old room
  322. //}
  323. //portal.MXID = ce.RoomID
  324. //portal.Name = roomNameEvent.Name
  325. //portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  326. //if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  327. // _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  328. // if err != nil {
  329. // portal.log.Warnln("Failed to enable e2be:", err)
  330. // }
  331. // portal.Encrypted = true
  332. //}
  333. //
  334. //portal.Update()
  335. //portal.UpdateBridgeInfo()
  336. //
  337. //ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  338. //inCommunity := ce.User.addPortalToCommunity(portal)
  339. //ce.User.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
  340. }
  341. func parseInviteMeta(meta map[string]interface{}) (jid, inviter types.JID, code string, expiration int64, ok bool) {
  342. var fieldFound bool
  343. code, fieldFound = meta["code"].(string)
  344. if !fieldFound {
  345. return
  346. }
  347. expirationStr, fieldFound := meta["expiration"].(string)
  348. if !fieldFound {
  349. return
  350. }
  351. inviterStr, fieldFound := meta["inviter"].(string)
  352. if !fieldFound {
  353. return
  354. }
  355. jidStr, fieldFound := meta["jid"].(string)
  356. if !fieldFound {
  357. return
  358. }
  359. var err error
  360. expiration, err = strconv.ParseInt(expirationStr, 10, 64)
  361. if err != nil {
  362. return
  363. }
  364. inviter, err = types.ParseJID(inviterStr)
  365. if err != nil {
  366. return
  367. }
  368. jid, err = types.ParseJID(jidStr)
  369. if err != nil {
  370. return
  371. }
  372. ok = true
  373. return
  374. }
  375. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  376. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  377. if ce.Portal == nil {
  378. ce.Reply("Not a portal room")
  379. return
  380. }
  381. var level int
  382. var userID id.UserID
  383. var err error
  384. if len(ce.Args) == 1 {
  385. level, err = strconv.Atoi(ce.Args[0])
  386. if err != nil {
  387. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  388. return
  389. }
  390. userID = ce.User.MXID
  391. } else if len(ce.Args) == 2 {
  392. userID = id.UserID(ce.Args[0])
  393. _, _, err := userID.Parse()
  394. if err != nil {
  395. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  396. return
  397. }
  398. level, err = strconv.Atoi(ce.Args[1])
  399. if err != nil {
  400. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  401. return
  402. }
  403. } else {
  404. ce.Reply("**Usage:** `set-pl [user] <level>`")
  405. return
  406. }
  407. intent := ce.Portal.MainIntent()
  408. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  409. if err != nil {
  410. ce.Reply("Failed to set power levels: %v", err)
  411. }
  412. }
  413. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  414. // CommandLogin handles login command
  415. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  416. if ce.User.Session != nil {
  417. if ce.User.IsConnected() {
  418. ce.Reply("You're already logged in")
  419. } else {
  420. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  421. }
  422. return
  423. }
  424. qrChan, err := ce.User.Login(context.Background())
  425. if err != nil {
  426. ce.User.log.Errorf("Failed to log in:", err)
  427. ce.Reply("Failed to log in: %v", err)
  428. return
  429. }
  430. var qrEventID id.EventID
  431. for item := range qrChan {
  432. switch item {
  433. case whatsmeow.QRChannelSuccess:
  434. jid := ce.User.Client.Store.ID
  435. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  436. case whatsmeow.QRChannelTimeout:
  437. ce.Reply("QR code timed out. Please restart the login.")
  438. case whatsmeow.QRChannelErrUnexpectedEvent:
  439. ce.Reply("Failed to log in: unexpected connection event from server")
  440. case whatsmeow.QRChannelScannedWithoutMultidevice:
  441. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  442. default:
  443. qrEventID = ce.User.sendQR(ce, string(item), qrEventID)
  444. }
  445. }
  446. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  447. }
  448. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  449. url, ok := user.uploadQR(ce, code)
  450. if !ok {
  451. return prevEvent
  452. }
  453. content := event.MessageEventContent{
  454. MsgType: event.MsgImage,
  455. Body: code,
  456. URL: url.CUString(),
  457. }
  458. if len(prevEvent) != 0 {
  459. content.SetEdit(prevEvent)
  460. }
  461. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  462. if err != nil {
  463. user.log.Errorln("Failed to send edited QR code to user:", err)
  464. } else if len(prevEvent) == 0 {
  465. prevEvent = resp.EventID
  466. }
  467. return prevEvent
  468. }
  469. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  470. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  471. if err != nil {
  472. user.log.Errorln("Failed to encode QR code:", err)
  473. ce.Reply("Failed to encode QR code: %v", err)
  474. return id.ContentURI{}, false
  475. }
  476. bot := user.bridge.AS.BotClient()
  477. resp, err := bot.UploadBytes(qrCode, "image/png")
  478. if err != nil {
  479. user.log.Errorln("Failed to upload QR code:", err)
  480. ce.Reply("Failed to upload QR code: %v", err)
  481. return id.ContentURI{}, false
  482. }
  483. return resp.ContentURI, true
  484. }
  485. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  486. // CommandLogout handles !logout command
  487. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  488. if ce.User.Session == nil {
  489. ce.Reply("You're not logged in.")
  490. return
  491. } else if !ce.User.IsLoggedIn() {
  492. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  493. return
  494. }
  495. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  496. if puppet.CustomMXID != "" {
  497. err := puppet.SwitchCustomMXID("", "")
  498. if err != nil {
  499. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  500. }
  501. }
  502. err := ce.User.Client.Logout()
  503. if err != nil {
  504. ce.User.log.Warnln("Error while logging out:", err)
  505. ce.Reply("Unknown error while logging out: %v", err)
  506. return
  507. }
  508. ce.User.Session = nil
  509. ce.User.removeFromJIDMap(StateLoggedOut)
  510. ce.User.DeleteConnection()
  511. ce.User.DeleteSession()
  512. ce.Reply("Logged out successfully.")
  513. }
  514. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  515. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  516. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  517. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  518. return
  519. }
  520. if ce.User.Session == nil {
  521. ce.Reply("You're not logged in.")
  522. return
  523. }
  524. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  525. if customPuppet == nil {
  526. ce.Reply("You're not logged in with your Matrix account.")
  527. return
  528. }
  529. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  530. customPuppet.EnablePresence = !customPuppet.EnablePresence
  531. var newPresence types.Presence
  532. if customPuppet.EnablePresence {
  533. newPresence = types.PresenceAvailable
  534. ce.Reply("Enabled presence bridging")
  535. } else {
  536. newPresence = types.PresenceUnavailable
  537. ce.Reply("Disabled presence bridging")
  538. }
  539. if ce.User.IsLoggedIn() {
  540. err := ce.User.Client.SendPresence(newPresence)
  541. if err != nil {
  542. ce.User.log.Warnln("Failed to set presence:", err)
  543. }
  544. }
  545. }
  546. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  547. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  548. if customPuppet.EnableReceipts {
  549. ce.Reply("Enabled read receipt bridging")
  550. } else {
  551. ce.Reply("Disabled read receipt bridging")
  552. }
  553. }
  554. customPuppet.Update()
  555. }
  556. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  557. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  558. if ce.User.Session == nil && ce.User.Client == nil {
  559. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  560. return
  561. }
  562. ce.User.removeFromJIDMap(StateLoggedOut)
  563. ce.User.DeleteConnection()
  564. ce.User.DeleteSession()
  565. ce.Reply("Session information purged")
  566. }
  567. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  568. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  569. if ce.User.Client == nil {
  570. if ce.User.Session == nil {
  571. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  572. } else {
  573. ce.User.Connect()
  574. ce.Reply("Started connecting to WhatsApp")
  575. }
  576. } else {
  577. ce.User.DeleteConnection()
  578. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  579. ce.User.Connect()
  580. ce.Reply("Restarted connection to WhatsApp")
  581. }
  582. }
  583. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  584. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  585. if ce.User.Client == nil {
  586. ce.Reply("You don't have a WhatsApp connection.")
  587. return
  588. }
  589. ce.User.DeleteConnection()
  590. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  591. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  592. }
  593. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  594. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  595. if ce.User.Session == nil {
  596. ce.Reply("You're not logged into WhatsApp.")
  597. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  598. ce.Reply("You don't have a WhatsApp connection.")
  599. } else {
  600. ce.Reply("Connection to WhatsApp OK (probably)")
  601. }
  602. }
  603. const cmdHelpHelp = `help - Prints this help`
  604. // CommandHelp handles help command
  605. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  606. cmdPrefix := ""
  607. if ce.User.ManagementRoom != ce.RoomID {
  608. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  609. }
  610. ce.Reply("* " + strings.Join([]string{
  611. cmdPrefix + cmdHelpHelp,
  612. cmdPrefix + cmdVersionHelp,
  613. cmdPrefix + cmdLoginHelp,
  614. cmdPrefix + cmdLogoutHelp,
  615. cmdPrefix + cmdDeleteSessionHelp,
  616. cmdPrefix + cmdReconnectHelp,
  617. cmdPrefix + cmdDisconnectHelp,
  618. cmdPrefix + cmdPingHelp,
  619. cmdPrefix + cmdSetRelayHelp,
  620. cmdPrefix + cmdUnsetRelayHelp,
  621. cmdPrefix + cmdLoginMatrixHelp,
  622. cmdPrefix + cmdPingMatrixHelp,
  623. cmdPrefix + cmdLogoutMatrixHelp,
  624. cmdPrefix + cmdToggleHelp,
  625. cmdPrefix + cmdListHelp,
  626. cmdPrefix + cmdOpenHelp,
  627. cmdPrefix + cmdPMHelp,
  628. cmdPrefix + cmdInviteLinkHelp,
  629. cmdPrefix + cmdCheckInviteHelp,
  630. cmdPrefix + cmdJoinHelp,
  631. cmdPrefix + cmdCreateHelp,
  632. cmdPrefix + cmdSetPowerLevelHelp,
  633. cmdPrefix + cmdDeletePortalHelp,
  634. cmdPrefix + cmdDeleteAllPortalsHelp,
  635. }, "\n* "))
  636. }
  637. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  638. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  639. if err != nil {
  640. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  641. return false
  642. }
  643. for otherUser := range members.Joined {
  644. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  645. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  646. continue
  647. }
  648. user := portal.bridge.GetUserByMXID(otherUser)
  649. if user != nil && user.Session != nil {
  650. return false
  651. }
  652. }
  653. return true
  654. }
  655. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  656. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  657. if ce.Portal == nil {
  658. ce.Reply("You must be in a portal room to use that command")
  659. return
  660. }
  661. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  662. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  663. return
  664. }
  665. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  666. ce.Portal.Delete()
  667. ce.Portal.Cleanup(false)
  668. }
  669. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  670. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  671. portals := handler.bridge.GetAllPortals()
  672. var portalsToDelete []*Portal
  673. if ce.User.Admin {
  674. portalsToDelete = portals
  675. } else {
  676. portalsToDelete = portals[:0]
  677. for _, portal := range portals {
  678. if canDeletePortal(portal, ce.User.MXID) {
  679. portalsToDelete = append(portalsToDelete, portal)
  680. }
  681. }
  682. }
  683. leave := func(portal *Portal) {
  684. if len(portal.MXID) > 0 {
  685. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  686. Reason: "Deleting portal",
  687. UserID: ce.User.MXID,
  688. })
  689. }
  690. }
  691. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  692. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  693. intent := customPuppet.CustomIntent()
  694. leave = func(portal *Portal) {
  695. if len(portal.MXID) > 0 {
  696. _, _ = intent.LeaveRoom(portal.MXID)
  697. _, _ = intent.ForgetRoom(portal.MXID)
  698. }
  699. }
  700. }
  701. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  702. for _, portal := range portalsToDelete {
  703. portal.Delete()
  704. leave(portal)
  705. }
  706. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  707. go func() {
  708. for _, portal := range portalsToDelete {
  709. portal.Cleanup(false)
  710. }
  711. ce.Reply("Finished background cleanup of deleted portal rooms.")
  712. }()
  713. }
  714. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  715. //func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  716. // for jid, contact := range input {
  717. // if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  718. // continue
  719. // }
  720. //
  721. // if contacts {
  722. // result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  723. // } else {
  724. // result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  725. // }
  726. // }
  727. // sort.Sort(sort.StringSlice(result))
  728. // return
  729. //}
  730. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  731. if len(ce.Args) == 0 {
  732. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  733. return
  734. }
  735. mode := strings.ToLower(ce.Args[0])
  736. if mode[0] != 'g' && mode[0] != 'c' {
  737. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  738. return
  739. }
  740. var err error
  741. page := 1
  742. max := 100
  743. if len(ce.Args) > 1 {
  744. page, err = strconv.Atoi(ce.Args[1])
  745. if err != nil || page <= 0 {
  746. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  747. return
  748. }
  749. }
  750. if len(ce.Args) > 2 {
  751. max, err = strconv.Atoi(ce.Args[2])
  752. if err != nil || max <= 0 {
  753. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  754. return
  755. } else if max > 400 {
  756. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  757. }
  758. }
  759. ce.Reply("Not yet implemented")
  760. // TODO reimplement
  761. //contacts := mode[0] == 'c'
  762. //typeName := "Groups"
  763. //if contacts {
  764. // typeName = "Contacts"
  765. //}
  766. //ce.User.Conn.Store.ContactsLock.RLock()
  767. //result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  768. //ce.User.Conn.Store.ContactsLock.RUnlock()
  769. //if len(result) == 0 {
  770. // ce.Reply("No %s found", strings.ToLower(typeName))
  771. // return
  772. //}
  773. //pages := int(math.Ceil(float64(len(result)) / float64(max)))
  774. //if (page-1)*max >= len(result) {
  775. // if pages == 1 {
  776. // ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  777. // } else {
  778. // ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  779. // }
  780. // return
  781. //}
  782. //lastIndex := page * max
  783. //if lastIndex > len(result) {
  784. // lastIndex = len(result)
  785. //}
  786. //result = result[(page-1)*max : lastIndex]
  787. //ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  788. }
  789. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  790. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  791. if len(ce.Args) == 0 {
  792. ce.Reply("**Usage:** `open <group JID>`")
  793. return
  794. }
  795. ce.Reply("Not yet implemented")
  796. // TODO reimplement
  797. //user := ce.User
  798. //jid := ce.Args[0]
  799. //if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  800. // ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  801. // return
  802. //}
  803. //
  804. //user.Conn.Store.ContactsLock.RLock()
  805. //contact, ok := user.Conn.Store.Contacts[jid]
  806. //user.Conn.Store.ContactsLock.RUnlock()
  807. //if !ok {
  808. // ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  809. // return
  810. //}
  811. //handler.log.Debugln("Importing", jid, "for", user)
  812. //portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  813. //if len(portal.MXID) > 0 {
  814. // portal.Sync(user, contact)
  815. // ce.Reply("Portal room synced.")
  816. //} else {
  817. // portal.Sync(user, contact)
  818. // ce.Reply("Portal room created.")
  819. //}
  820. //_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  821. }
  822. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  823. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  824. if len(ce.Args) == 0 {
  825. ce.Reply("**Usage:** `pm <international phone number>`")
  826. return
  827. }
  828. user := ce.User
  829. number := strings.Join(ce.Args, "")
  830. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  831. if err != nil {
  832. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  833. return
  834. } else if len(resp) == 0 {
  835. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  836. return
  837. }
  838. targetUser := resp[0]
  839. if !targetUser.IsIn {
  840. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  841. return
  842. }
  843. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  844. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  845. puppet.SyncContact(user, true)
  846. portal := user.GetPortalByJID(puppet.JID)
  847. if len(portal.MXID) > 0 {
  848. ok := portal.ensureUserInvited(user)
  849. if !ok {
  850. portal.log.Warnfln("ensureUserInvited(%s) returned false, creating new portal", user.MXID)
  851. portal.MXID = ""
  852. } else {
  853. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  854. return
  855. }
  856. }
  857. err = portal.CreateMatrixRoom(user, nil)
  858. if err != nil {
  859. ce.Reply("Failed to create portal room: %v", err)
  860. return
  861. }
  862. ce.Reply("Created portal room and invited you to it.")
  863. }
  864. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  865. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  866. if len(ce.Args) == 0 {
  867. ce.Reply("**Usage:** `login-matrix <access token>`")
  868. return
  869. }
  870. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  871. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  872. if err != nil {
  873. ce.Reply("Failed to switch puppet: %v", err)
  874. return
  875. }
  876. ce.Reply("Successfully switched puppet")
  877. }
  878. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  879. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  880. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  881. if puppet == nil || puppet.CustomIntent() == nil {
  882. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  883. return
  884. }
  885. resp, err := puppet.CustomIntent().Whoami()
  886. if err != nil {
  887. ce.Reply("Failed to validate Matrix login: %v", err)
  888. } else {
  889. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  890. }
  891. }
  892. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  893. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  894. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  895. if puppet == nil || puppet.CustomIntent() == nil {
  896. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  897. return
  898. }
  899. err := puppet.SwitchCustomMXID("", "")
  900. if err != nil {
  901. ce.Reply("Failed to remove custom puppet: %v", err)
  902. return
  903. }
  904. ce.Reply("Successfully removed custom puppet")
  905. }