commands.go 31 KB

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