@@ -6,17 +6,34 @@ package webhook
6
6
7
7
import (
8
8
"errors"
9
+ "fmt"
9
10
"io"
11
+ "os"
12
+ "path/filepath"
10
13
11
14
"gopkg.in/yaml.v2"
12
15
)
13
16
17
+ var Webhooks map [string ]* Webhook
18
+
14
19
// Webhook is a custom webhook
15
20
type Webhook struct {
16
21
ID string `yaml:"id"`
17
22
HTTP string `yaml:"http"`
18
23
Exec []string `yaml:"exec"`
19
24
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 )
20
37
}
21
38
22
39
// Form is a webhook form
@@ -45,11 +62,16 @@ func (w *Webhook) validate() error {
45
62
if form .Type == "" {
46
63
return errors .New ("form type is required" )
47
64
}
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
+ }
48
70
}
49
71
return nil
50
72
}
51
73
52
- // Parse parses a Webhooks from an io.Reader
74
+ // Parse parses a Webhook from an io.Reader
53
75
func Parse (r io.Reader ) (* Webhook , error ) {
54
76
b , err := io .ReadAll (r )
55
77
if err != nil {
@@ -67,3 +89,37 @@ func Parse(r io.Reader) (*Webhook, error) {
67
89
68
90
return & w , nil
69
91
}
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