commands.go 33 KB

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