commands.go 10 KB

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