@@ -6,17 +6,34 @@ package webhook
66
77import (
88 "errors"
9+ "fmt"
910 "io"
11+ "os"
12+ "path/filepath"
1013
1114 "gopkg.in/yaml.v2"
1215)
1316
17+ var Webhooks map [string ]* Webhook
18+
1419// Webhook is a custom webhook
1520type Webhook struct {
1621 ID string `yaml:"id"`
1722 HTTP string `yaml:"http"`
1823 Exec []string `yaml:"exec"`
1924 Form []Form `yaml:"form"`
25+ Path string `yaml:"-"`
26+ }
27+
28+ // Image returns a custom webhook image if it exists, else the default image
29+ func (w * Webhook ) Image () ([]byte , error ) {
30+ img , err := os .Open (filepath .Join (w .Path , "image.png" ))
31+ if err != nil {
32+ return nil , fmt .Errorf ("could not open custom webhook image: %w" , err )
33+ }
34+ defer img .Close ()
35+
36+ return io .ReadAll (img )
2037}
2138
2239// Form is a webhook form
@@ -45,11 +62,16 @@ func (w *Webhook) validate() error {
4562 if form .Type == "" {
4663 return errors .New ("form type is required" )
4764 }
65+ switch form .Type {
66+ case "text" , "secret" , "bool" , "number" :
67+ default :
68+ return errors .New ("form type is invalid; must be one of text, secret, bool, or number" )
69+ }
4870 }
4971 return nil
5072}
5173
52- // Parse parses a Webhooks from an io.Reader
74+ // Parse parses a Webhook from an io.Reader
5375func Parse (r io.Reader ) (* Webhook , error ) {
5476 b , err := io .ReadAll (r )
5577 if err != nil {
@@ -67,3 +89,37 @@ func Parse(r io.Reader) (*Webhook, error) {
6789
6890 return & w , nil
6991}
92+
93+ // Init initializes any custom webhooks found in path
94+ func Init (path string ) error {
95+ dir , err := os .ReadDir (path )
96+ if err != nil {
97+ return fmt .Errorf ("could not read dir %q: %w" , path , err )
98+ }
99+
100+ for _ , d := range dir {
101+ if ! d .IsDir () {
102+ continue
103+ }
104+
105+ hookPath := filepath .Join (path , d .Name ())
106+ cfg , err := os .Open (filepath .Join (hookPath , "config.yml" ))
107+ if err != nil {
108+ return fmt .Errorf ("could not open custom webhook config: %w" , err )
109+ }
110+
111+ hook , err := Parse (cfg )
112+ if err != nil {
113+ return fmt .Errorf ("could not parse custom webhook config: %w" , err )
114+ }
115+ hook .Path = hookPath
116+
117+ Webhooks [hook .ID ] = hook
118+
119+ if err := cfg .Close (); err != nil {
120+ return fmt .Errorf ("could not close custom webhook config: %w" , err )
121+ }
122+ }
123+
124+ return nil
125+ }
0 commit comments