commands.go 10 KB

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