You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.4 KiB

3 weeks ago
  1. // maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
  2. // Copyright (C) 2024 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. "flag"
  20. "fmt"
  21. "os"
  22. "regexp"
  23. "time"
  24. "go.mau.fi/util/exerrors"
  25. "gopkg.in/yaml.v3"
  26. "maunium.net/go/mautrix/federation"
  27. "maunium.net/go/mautrix/mediaproxy"
  28. )
  29. type Config struct {
  30. mediaproxy.BasicConfig `yaml:",inline"`
  31. mediaproxy.ServerConfig `yaml:",inline"`
  32. Destination string `yaml:"destination"`
  33. }
  34. var configPath = flag.String("config", "config.yaml", "config file path")
  35. var generateServerKey = flag.Bool("generate-key", false, "generate a new server key and exit")
  36. var giphyIDRegex = regexp.MustCompile(`^[a-zA-Z0-9-_]+$`)
  37. var destination = "https://i.giphy.com/%s.webp"
  38. func main() {
  39. flag.Parse()
  40. if *generateServerKey {
  41. fmt.Println(federation.GenerateSigningKey().SynapseString())
  42. } else {
  43. cfgFile := exerrors.Must(os.ReadFile(*configPath))
  44. var cfg Config
  45. exerrors.PanicIfNotNil(yaml.Unmarshal(cfgFile, &cfg))
  46. mp := exerrors.Must(mediaproxy.NewFromConfig(cfg.BasicConfig, getMedia))
  47. mp.KeyServer.Version.Name = "maunium-stickerpicker giphy proxy"
  48. mp.ForceProxyLegacyFederation = true
  49. if cfg.Destination != "" {
  50. destination = cfg.Destination
  51. }
  52. exerrors.PanicIfNotNil(mp.Listen(cfg.ServerConfig))
  53. }
  54. }
  55. func getMedia(_ context.Context, id string, _ map[string]string) (response mediaproxy.GetMediaResponse, err error) {
  56. // This is not related to giphy, but random cats are always fun
  57. if id == "cat" {
  58. return &mediaproxy.GetMediaResponseURL{
  59. URL: "https://cataas.com/cat",
  60. ExpiresAt: time.Now(),
  61. }, nil
  62. }
  63. if !giphyIDRegex.MatchString(id) {
  64. return nil, mediaproxy.ErrInvalidMediaIDSyntax
  65. }
  66. return &mediaproxy.GetMediaResponseURL{
  67. URL: fmt.Sprintf(destination, id),
  68. }, nil
  69. }