cmd.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package registration
  2. import (
  3. "fmt"
  4. "os"
  5. "regexp"
  6. "maunium.net/go/mautrix/appservice"
  7. "go.mau.fi/mautrix-discord/config"
  8. "go.mau.fi/mautrix-discord/globals"
  9. )
  10. type Cmd struct {
  11. Filename string `kong:"flag,help='The filename to store the registration into',name='REGISTRATION',short='r',default='registration.yaml'"`
  12. Force bool `kong:"flag,help='Overwrite an existing registration file if it already exists',short='f',default='0'"`
  13. }
  14. func (c *Cmd) Run(g *globals.Globals) error {
  15. // Check if the file exists before blinding overwriting it.
  16. if _, err := os.Stat(c.Filename); err == nil {
  17. if c.Force == false {
  18. return fmt.Errorf("file %q exists, use -f to overwrite", c.Filename)
  19. }
  20. }
  21. cfg, err := config.FromFile(g.Config)
  22. if err != nil {
  23. return err
  24. }
  25. registration := appservice.CreateRegistration()
  26. // Load existing values from the config into the registration.
  27. if err := cfg.CopyToRegistration(registration); err != nil {
  28. return err
  29. }
  30. // Save the new App and Server tokens in the config.
  31. cfg.Appservice.ASToken = registration.AppToken
  32. cfg.Appservice.HSToken = registration.ServerToken
  33. // Workaround for https://github.com/matrix-org/synapse/pull/5758
  34. registration.SenderLocalpart = appservice.RandomString(32)
  35. // Register the bot's user.
  36. pattern := fmt.Sprintf(
  37. "^@%s:%s$",
  38. cfg.Appservice.Bot.Username,
  39. cfg.Homeserver.Domain,
  40. )
  41. botRegex, err := regexp.Compile(pattern)
  42. if err != nil {
  43. return err
  44. }
  45. registration.Namespaces.RegisterUserIDs(botRegex, true)
  46. // Finally save the registration and the updated config file.
  47. if err := registration.Save(c.Filename); err != nil {
  48. return err
  49. }
  50. if err := cfg.Save(g.Config); err != nil {
  51. return err
  52. }
  53. return nil
  54. }