Debian Codegraph @

pkg/services/chat/wecom/wecom_config.go

raw
1 package wecom
2
3 import (
4 "errors"
5 "fmt"
6 "net/url"
7 "strings"
8
9 "github.com/nicholas-fedor/shoutrrr/pkg/format"
10 "github.com/nicholas-fedor/shoutrrr/pkg/types"
11 )
12
13 // Config represents the configuration for the WeCom service.
14 type Config struct {
15 Key string `desc:"Bot webhook key" key:"key"`
16 MentionedList string `desc:"Users to mention (comma-separated)" key:"mentioned_list"`
17 MentionedMobileList string `desc:"Mobile numbers to mention (comma-separated)" key:"mentioned_mobile_list"`
18 }
19
20 // Scheme is the identifier for the WeCom service protocol.
21 const Scheme = "wecom"
22
23 // Error variables for the WeCom service.
24 var (
25 ErrEmptyKey = errors.New("WeCom webhook key cannot be empty")
26 ErrInvalidKey = errors.New("invalid WeCom webhook key format")
27 )
28
29 // Enums returns a map of enum formatters (none for this service).
30 func (c *Config) Enums() map[string]types.EnumFormatter {
31 return map[string]types.EnumFormatter{}
32 }
33
34 // GetURL constructs a URL from the Config fields.
35 func (c *Config) GetURL() *url.URL {
36 resolver := format.NewPropKeyResolver(c)
37
38 return c.getURL(&resolver)
39 }
40
41 // SetURL updates the Config from a URL.
42 func (c *Config) SetURL(serviceURL *url.URL) error {
43 resolver := format.NewPropKeyResolver(c)
44
45 return c.setURL(&resolver, serviceURL)
46 }
47
48 // getURL constructs a URL using the provided resolver.
49 func (c *Config) getURL(_ types.ConfigQueryResolver) *url.URL {
50 return &url.URL{
51 Scheme: Scheme,
52 Host: c.Key,
53 ForceQuery: false,
54 }
55 }
56
57 // setURL updates the Config from a URL using the provided resolver.
58 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
59 // Handle dummy URL used for documentation generation
60 if serviceURL.String() == "wecom://[email protected]" {
61 c.Key = "dummy-webhook-key"
62
63 return nil
64 }
65
66 // Extract key from host
67 c.Key = serviceURL.Host
68
69 // Validate key format (alphanumeric, hyphens, underscores only)
70 if c.Key == "" {
71 return ErrEmptyKey
72 }
73
74 if strings.ContainsAny(c.Key, "@!#$%^&*()+=[]{}|\\:;\"'<>?,./") {
75 return fmt.Errorf("%w: %s", ErrInvalidKey, c.Key)
76 }
77
78 // Handle query parameters
79 for key, vals := range serviceURL.Query() {
80 if err := resolver.Set(key, vals[0]); err != nil {
81 return fmt.Errorf("setting query parameter %q: %w", key, err)
82 }
83 }
84
85 return nil
86 }