commands.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2022 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. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "html"
  23. "net/http"
  24. "strconv"
  25. "strings"
  26. "github.com/bwmarrin/discordgo"
  27. "github.com/skip2/go-qrcode"
  28. "maunium.net/go/mautrix"
  29. "maunium.net/go/mautrix/bridge/commands"
  30. "maunium.net/go/mautrix/event"
  31. "maunium.net/go/mautrix/id"
  32. "go.mau.fi/mautrix-discord/remoteauth"
  33. )
  34. type WrappedCommandEvent struct {
  35. *commands.Event
  36. Bridge *DiscordBridge
  37. User *User
  38. Portal *Portal
  39. }
  40. func (br *DiscordBridge) RegisterCommands() {
  41. proc := br.CommandProcessor.(*commands.Processor)
  42. proc.AddHandlers(
  43. cmdLoginToken,
  44. cmdLoginQR,
  45. cmdLogout,
  46. cmdReconnect,
  47. cmdDisconnect,
  48. cmdGuilds,
  49. cmdRejoinSpace,
  50. cmdDeleteAllPortals,
  51. cmdExec,
  52. cmdCommands,
  53. )
  54. }
  55. func wrapCommand(handler func(*WrappedCommandEvent)) func(*commands.Event) {
  56. return func(ce *commands.Event) {
  57. user := ce.User.(*User)
  58. var portal *Portal
  59. if ce.Portal != nil {
  60. portal = ce.Portal.(*Portal)
  61. }
  62. br := ce.Bridge.Child.(*DiscordBridge)
  63. handler(&WrappedCommandEvent{ce, br, user, portal})
  64. }
  65. }
  66. var cmdLoginToken = &commands.FullHandler{
  67. Func: wrapCommand(fnLoginToken),
  68. Name: "login-token",
  69. Help: commands.HelpMeta{
  70. Section: commands.HelpSectionAuth,
  71. Description: "Link the bridge to your Discord account by extracting the access token manually.",
  72. },
  73. }
  74. func fnLoginToken(ce *WrappedCommandEvent) {
  75. if len(ce.Args) == 0 {
  76. ce.Reply("**Usage**: `$cmdprefix login-token <token>`")
  77. return
  78. }
  79. ce.MarkRead()
  80. defer ce.Redact()
  81. if ce.User.IsLoggedIn() {
  82. ce.Reply("You're already logged in")
  83. return
  84. }
  85. if err := ce.User.Login(ce.Args[0]); err != nil {
  86. ce.Reply("Error connecting to Discord: %v", err)
  87. return
  88. }
  89. ce.Reply("Successfully logged in as %s#%s", ce.User.Session.State.User.Username, ce.User.Session.State.User.Discriminator)
  90. }
  91. var cmdLoginQR = &commands.FullHandler{
  92. Func: wrapCommand(fnLoginQR),
  93. Name: "login-qr",
  94. Aliases: []string{"login"},
  95. Help: commands.HelpMeta{
  96. Section: commands.HelpSectionAuth,
  97. Description: "Link the bridge to your Discord account by scanning a QR code.",
  98. },
  99. }
  100. func fnLoginQR(ce *WrappedCommandEvent) {
  101. if ce.User.IsLoggedIn() {
  102. ce.Reply("You're already logged in")
  103. return
  104. }
  105. client, err := remoteauth.New()
  106. if err != nil {
  107. ce.Reply("Failed to prepare login: %v", err)
  108. return
  109. }
  110. qrChan := make(chan string)
  111. doneChan := make(chan struct{})
  112. var qrCodeEvent id.EventID
  113. go func() {
  114. code := <-qrChan
  115. resp := sendQRCode(ce, code)
  116. qrCodeEvent = resp
  117. }()
  118. ctx := context.Background()
  119. if err = client.Dial(ctx, qrChan, doneChan); err != nil {
  120. close(qrChan)
  121. close(doneChan)
  122. ce.Reply("Error connecting to login websocket: %v", err)
  123. return
  124. }
  125. <-doneChan
  126. if qrCodeEvent != "" {
  127. _, _ = ce.MainIntent().RedactEvent(ce.RoomID, qrCodeEvent)
  128. }
  129. user, err := client.Result()
  130. if err != nil || len(user.Token) == 0 {
  131. if restErr := (&discordgo.RESTError{}); errors.As(err, &restErr) &&
  132. restErr.Response.StatusCode == http.StatusBadRequest &&
  133. bytes.Contains(restErr.ResponseBody, []byte("captcha-required")) {
  134. ce.Reply("Error logging in: %v\n\nCAPTCHAs are currently not supported - use token login instead", err)
  135. } else {
  136. ce.Reply("Error logging in: %v", err)
  137. }
  138. return
  139. } else if err = ce.User.Login(user.Token); err != nil {
  140. ce.Reply("Error connecting after login: %v", err)
  141. return
  142. }
  143. ce.User.Lock()
  144. ce.User.DiscordID = user.UserID
  145. ce.User.Update()
  146. ce.User.Unlock()
  147. ce.Reply("Successfully logged in as %s#%s", user.Username, user.Discriminator)
  148. }
  149. func sendQRCode(ce *WrappedCommandEvent, code string) id.EventID {
  150. url, ok := uploadQRCode(ce, code)
  151. if !ok {
  152. return ""
  153. }
  154. content := event.MessageEventContent{
  155. MsgType: event.MsgImage,
  156. Body: code,
  157. URL: url.CUString(),
  158. }
  159. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  160. if err != nil {
  161. ce.Log.Errorfln("Failed to send QR code: %v", err)
  162. return ""
  163. }
  164. return resp.EventID
  165. }
  166. func uploadQRCode(ce *WrappedCommandEvent, code string) (id.ContentURI, bool) {
  167. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  168. if err != nil {
  169. ce.Log.Errorln("Failed to encode QR code:", err)
  170. ce.Reply("Failed to encode QR code: %v", err)
  171. return id.ContentURI{}, false
  172. }
  173. resp, err := ce.Bot.UploadBytes(qrCode, "image/png")
  174. if err != nil {
  175. ce.Log.Errorln("Failed to upload QR code:", err)
  176. ce.Reply("Failed to upload QR code: %v", err)
  177. return id.ContentURI{}, false
  178. }
  179. return resp.ContentURI, true
  180. }
  181. var cmdLogout = &commands.FullHandler{
  182. Func: wrapCommand(fnLogout),
  183. Name: "logout",
  184. Help: commands.HelpMeta{
  185. Section: commands.HelpSectionAuth,
  186. Description: "Forget the stored Discord auth token.",
  187. },
  188. }
  189. func fnLogout(ce *WrappedCommandEvent) {
  190. wasLoggedIn := ce.User.DiscordID != ""
  191. ce.User.Logout()
  192. if wasLoggedIn {
  193. ce.Reply("Logged out successfully.")
  194. } else {
  195. ce.Reply("You weren't logged in, but data was re-cleared just to be safe.")
  196. }
  197. }
  198. var cmdDisconnect = &commands.FullHandler{
  199. Func: wrapCommand(fnDisconnect),
  200. Name: "disconnect",
  201. Help: commands.HelpMeta{
  202. Section: commands.HelpSectionAuth,
  203. Description: "Disconnect from Discord (without logging out)",
  204. },
  205. RequiresLogin: true,
  206. }
  207. func fnDisconnect(ce *WrappedCommandEvent) {
  208. if !ce.User.Connected() {
  209. ce.Reply("You're already not connected")
  210. } else if err := ce.User.Disconnect(); err != nil {
  211. ce.Reply("Error while disconnecting: %v", err)
  212. } else {
  213. ce.Reply("Successfully disconnected")
  214. }
  215. }
  216. var cmdReconnect = &commands.FullHandler{
  217. Func: wrapCommand(fnReconnect),
  218. Name: "reconnect",
  219. Aliases: []string{"connect"},
  220. Help: commands.HelpMeta{
  221. Section: commands.HelpSectionAuth,
  222. Description: "Reconnect to Discord after disconnecting",
  223. },
  224. RequiresLogin: true,
  225. }
  226. func fnReconnect(ce *WrappedCommandEvent) {
  227. if ce.User.Connected() {
  228. ce.Reply("You're already connected")
  229. } else if err := ce.User.Connect(); err != nil {
  230. ce.Reply("Error while reconnecting: %v", err)
  231. } else {
  232. ce.Reply("Successfully reconnected")
  233. }
  234. }
  235. var cmdRejoinSpace = &commands.FullHandler{
  236. Func: wrapCommand(fnRejoinSpace),
  237. Name: "rejoin-space",
  238. Help: commands.HelpMeta{
  239. Section: commands.HelpSectionUnclassified,
  240. Description: "Ask the bridge for an invite to a space you left",
  241. Args: "<_guild ID_/main/dms>",
  242. },
  243. RequiresLogin: true,
  244. }
  245. func fnRejoinSpace(ce *WrappedCommandEvent) {
  246. if len(ce.Args) == 0 {
  247. ce.Reply("**Usage**: `$cmdprefix rejoin-space <guild ID/main/dms>`")
  248. return
  249. }
  250. user := ce.User
  251. if ce.Args[0] == "main" {
  252. user.ensureInvited(nil, user.GetSpaceRoom(), false)
  253. ce.Reply("Invited you to your main space ([link](%s))", user.GetSpaceRoom().URI(ce.Bridge.AS.HomeserverDomain).MatrixToURL())
  254. } else if ce.Args[0] == "dms" {
  255. user.ensureInvited(nil, user.GetDMSpaceRoom(), false)
  256. ce.Reply("Invited you to your DM space ([link](%s))", user.GetDMSpaceRoom().URI(ce.Bridge.AS.HomeserverDomain).MatrixToURL())
  257. } else if _, err := strconv.Atoi(ce.Args[0]); err == nil {
  258. ce.Reply("Rejoining guild spaces is not yet implemented")
  259. } else {
  260. ce.Reply("**Usage**: `$cmdprefix rejoin-space <guild ID/main/dms>`")
  261. return
  262. }
  263. }
  264. var cmdGuilds = &commands.FullHandler{
  265. Func: wrapCommand(fnGuilds),
  266. Name: "guilds",
  267. Aliases: []string{"servers", "guild", "server"},
  268. Help: commands.HelpMeta{
  269. Section: commands.HelpSectionUnclassified,
  270. Description: "Guild bridging management",
  271. Args: "<status/bridge/unbridge> [_guild ID_] [--entire]",
  272. },
  273. RequiresLogin: true,
  274. }
  275. const smallGuildsHelp = "**Usage**: `$cmdprefix guilds <help/status/bridge/unbridge> [guild ID] [--entire]`"
  276. const fullGuildsHelp = smallGuildsHelp + `
  277. * **help** - View this help message.
  278. * **status** - View the list of guilds and their bridging status.
  279. * **bridge <_guild ID_> [--entire]** - Enable bridging for a guild. The --entire flag auto-creates portals for all channels.
  280. * **unbridge <_guild ID_>** - Unbridge a guild and delete all channel portal rooms.`
  281. func fnGuilds(ce *WrappedCommandEvent) {
  282. if len(ce.Args) == 0 {
  283. ce.Reply(fullGuildsHelp)
  284. return
  285. }
  286. subcommand := strings.ToLower(ce.Args[0])
  287. ce.Args = ce.Args[1:]
  288. switch subcommand {
  289. case "status", "list":
  290. fnListGuilds(ce)
  291. case "bridge":
  292. fnBridgeGuild(ce)
  293. case "unbridge", "delete":
  294. fnUnbridgeGuild(ce)
  295. case "help":
  296. ce.Reply(fullGuildsHelp)
  297. default:
  298. ce.Reply("Unknown subcommand `%s`\n\n"+smallGuildsHelp, subcommand)
  299. }
  300. }
  301. func fnListGuilds(ce *WrappedCommandEvent) {
  302. var items []string
  303. for _, userGuild := range ce.User.GetPortals() {
  304. guild := ce.Bridge.GetGuildByID(userGuild.DiscordID, false)
  305. if guild == nil {
  306. continue
  307. }
  308. status := "not bridged"
  309. if guild.MXID != "" {
  310. status = "bridged"
  311. }
  312. var avatarHTML string
  313. if !guild.AvatarURL.IsEmpty() {
  314. avatarHTML = fmt.Sprintf(`<img data-mx-emoticon height="24" src="%s" alt="" title="Guild avatar"> `, guild.AvatarURL.String())
  315. }
  316. items = append(items, fmt.Sprintf("<li>%s%s (<code>%s</code>) - %s</li>", avatarHTML, html.EscapeString(guild.Name), guild.ID, status))
  317. }
  318. if len(items) == 0 {
  319. ce.Reply("No guilds found")
  320. } else {
  321. ce.ReplyAdvanced(fmt.Sprintf("<p>List of guilds:</p><ul>%s</ul>", strings.Join(items, "")), false, true)
  322. }
  323. }
  324. func fnBridgeGuild(ce *WrappedCommandEvent) {
  325. if len(ce.Args) == 0 || len(ce.Args) > 2 {
  326. ce.Reply("**Usage**: `$cmdprefix guilds bridge <guild ID> [--entire]")
  327. } else if err := ce.User.bridgeGuild(ce.Args[0], len(ce.Args) == 2 && strings.ToLower(ce.Args[1]) == "--entire"); err != nil {
  328. ce.Reply("Error bridging guild: %v", err)
  329. } else {
  330. ce.Reply("Successfully bridged guild")
  331. }
  332. }
  333. func fnUnbridgeGuild(ce *WrappedCommandEvent) {
  334. if len(ce.Args) != 1 {
  335. ce.Reply("**Usage**: `$cmdprefix guilds unbridge <guild ID>")
  336. } else if err := ce.User.unbridgeGuild(ce.Args[0]); err != nil {
  337. ce.Reply("Error unbridging guild: %v", err)
  338. } else {
  339. ce.Reply("Successfully unbridged guild")
  340. }
  341. }
  342. var cmdDeleteAllPortals = &commands.FullHandler{
  343. Func: wrapCommand(fnDeleteAllPortals),
  344. Name: "delete-all-portals",
  345. Help: commands.HelpMeta{
  346. Section: commands.HelpSectionUnclassified,
  347. Description: "Delete all portals.",
  348. },
  349. RequiresAdmin: true,
  350. }
  351. func fnDeleteAllPortals(ce *WrappedCommandEvent) {
  352. portals := ce.Bridge.GetAllPortals()
  353. if len(portals) == 0 {
  354. ce.Reply("Didn't find any portals")
  355. return
  356. }
  357. leave := func(portal *Portal) {
  358. if len(portal.MXID) > 0 {
  359. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  360. Reason: "Deleting portal",
  361. UserID: ce.User.MXID,
  362. })
  363. }
  364. }
  365. customPuppet := ce.Bridge.GetPuppetByCustomMXID(ce.User.MXID)
  366. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  367. intent := customPuppet.CustomIntent()
  368. leave = func(portal *Portal) {
  369. if len(portal.MXID) > 0 {
  370. _, _ = intent.LeaveRoom(portal.MXID)
  371. _, _ = intent.ForgetRoom(portal.MXID)
  372. }
  373. }
  374. }
  375. ce.Reply("Found %d portals, deleting...", len(portals))
  376. for _, portal := range portals {
  377. portal.Delete()
  378. leave(portal)
  379. }
  380. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  381. go func() {
  382. for _, portal := range portals {
  383. portal.cleanup(false)
  384. }
  385. ce.Reply("Finished background cleanup of deleted portal rooms.")
  386. }()
  387. }