|
| 1 | +package lark |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/url" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 9 | + "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 10 | +) |
| 11 | + |
| 12 | +// Scheme is the identifier for the Lark service protocol. |
| 13 | +const Scheme = "lark" |
| 14 | + |
| 15 | +// Config represents the configuration for the Lark service. |
| 16 | +type Config struct { |
| 17 | + Host string `default:"open.larksuite.com" desc:"Custom bot URL Host" url:"Host"` |
| 18 | + Secret string `default:"" desc:"Custom bot secret" key:"secret"` |
| 19 | + Path string ` desc:"Custom bot token" url:"Path"` |
| 20 | + Title string `default:"" desc:"Message Title" key:"title"` |
| 21 | + Link string `default:"" desc:"Optional link URL" key:"link"` |
| 22 | +} |
| 23 | + |
| 24 | +// Enums returns a map of enum formatters (none for this service). |
| 25 | +func (config *Config) Enums() map[string]types.EnumFormatter { |
| 26 | + return map[string]types.EnumFormatter{} |
| 27 | +} |
| 28 | + |
| 29 | +// GetURL constructs a URL from the Config fields. |
| 30 | +func (config *Config) GetURL() *url.URL { |
| 31 | + resolver := format.NewPropKeyResolver(config) |
| 32 | + |
| 33 | + return config.getURL(&resolver) |
| 34 | +} |
| 35 | + |
| 36 | +// getURL constructs a URL using the provided resolver. |
| 37 | +func (config *Config) getURL(resolver types.ConfigQueryResolver) *url.URL { |
| 38 | + return &url.URL{ |
| 39 | + Host: config.Host, |
| 40 | + Path: "/" + config.Path, |
| 41 | + Scheme: Scheme, |
| 42 | + ForceQuery: true, |
| 43 | + RawQuery: format.BuildQuery(resolver), |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// SetURL updates the Config from a URL. |
| 48 | +func (config *Config) SetURL(url *url.URL) error { |
| 49 | + resolver := format.NewPropKeyResolver(config) |
| 50 | + |
| 51 | + return config.setURL(&resolver, url) |
| 52 | +} |
| 53 | + |
| 54 | +// setURL updates the Config from a URL using the provided resolver. |
| 55 | +// It sets the host, path, and query parameters, validating host and path, and returns an error if parsing or validation fails. |
| 56 | +func (config *Config) setURL(resolver types.ConfigQueryResolver, url *url.URL) error { |
| 57 | + config.Host = url.Host |
| 58 | + if config.Host != larkHost && config.Host != feishuHost { |
| 59 | + return ErrInvalidHost |
| 60 | + } |
| 61 | + |
| 62 | + config.Path = strings.Trim(url.Path, "/") |
| 63 | + if config.Path == "" { |
| 64 | + return ErrNoPath |
| 65 | + } |
| 66 | + |
| 67 | + for key, vals := range url.Query() { |
| 68 | + if err := resolver.Set(key, vals[0]); err != nil { |
| 69 | + return fmt.Errorf("setting query parameter %q: %w", key, err) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return nil |
| 74 | +} |
0 commit comments