-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathplugin.go
363 lines (321 loc) · 7.43 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/appleboy/drone-template-lib/template"
)
const (
// DroneIconURL default drone logo url
DroneIconURL = "https://c1.staticflickr.com/5/4236/34957940160_435d83114f_z.jpg"
// DroneDesc default drone description
DroneDesc = "Powered by Drone Discord Plugin"
)
type (
// GitHub information.
GitHub struct {
Workflow string
Workspace string
Action string
EventName string
EventPath string
}
// Repo information.
Repo struct {
FullName string
Namespace string
Name string
}
// Commit information.
Commit struct {
Sha string
Ref string
Branch string
Link string
Author string
Avatar string
Email string
Message string
}
Source struct {
Branch string
}
// Build information.
Build struct {
Tag string
Event string
Number int
Status string
Link string
Started int64
Finished int64
PR string
DeployTo string
}
// Config for the plugin.
Config struct {
WebhookID string
WebhookToken string
Color string
Message []string
File []string
Drone bool
GitHub bool
}
// EmbedFooterObject for Embed Footer Structure.
EmbedFooterObject struct {
Text string `json:"text"`
IconURL string `json:"icon_url"`
}
// EmbedAuthorObject for Embed Author Structure
EmbedAuthorObject struct {
Name string `json:"name"`
URL string `json:"url"`
IconURL string `json:"icon_url"`
}
// EmbedFieldObject for Embed Field Structure
EmbedFieldObject struct {
Name string `json:"name"`
Value string `json:"value"`
}
// EmbedObject is for Embed Structure
EmbedObject struct {
Title string `json:"title"`
Description string `json:"description"`
URL string `json:"url"`
Color int `json:"color"`
Footer EmbedFooterObject `json:"footer"`
Author EmbedAuthorObject `json:"author"`
Fields []EmbedFieldObject `json:"fields"`
}
// Payload struct
Payload struct {
Wait bool `json:"wait"`
Content string `json:"content"`
Username string `json:"username,omitempty"`
AvatarURL string `json:"avatar_url"`
TTS bool `json:"tts"`
Embeds []EmbedObject `json:"embeds"`
}
// Plugin values.
Plugin struct {
GitHub GitHub
Repo Repo
Build Build
Source Source
Config Config
Payload Payload
Commit Commit
}
)
func templateMessage(t string, plugin Plugin) (string, error) {
return template.RenderTrim(t, plugin)
}
// Creates a new file upload http request with optional extra params
// https://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
if err != nil {
return nil, err
}
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, err
}
// Exec executes the plugin.
func (p *Plugin) Exec() error {
if p.Config.WebhookID == "" || p.Config.WebhookToken == "" {
return errors.New("missing discord config")
}
if len(p.Config.Message) == 0 {
object := p.Template()
p.Payload.Embeds = []EmbedObject{object}
err := p.SendMessage()
if err != nil {
return err
}
}
if len(p.Config.Message) > 0 {
for _, m := range p.Config.Message {
txt, err := templateMessage(m, *p)
if err != nil {
return err
}
if len(p.Config.Color) != 0 {
object := p.DefaultTemplate(txt)
p.Payload.Embeds = append(p.Payload.Embeds, object)
} else {
p.Payload.Content = txt
err = p.SendMessage()
if err != nil {
return err
}
}
}
if len(p.Payload.Embeds) > 0 {
err := p.SendMessage()
if err != nil {
return err
}
}
}
for _, f := range p.Config.File {
if f == "" {
continue
}
err := p.SendFile(f)
if err != nil {
return err
}
}
return nil
}
// SendFile upload file to discord
func (p *Plugin) SendFile(file string) error {
webhookURL := fmt.Sprintf("https://discord.com/api/webhooks/%s/%s", p.Config.WebhookID, p.Config.WebhookToken)
extraParams := map[string]string{}
if p.Payload.Username != "" {
extraParams["username"] = p.Payload.Username
}
if p.Payload.AvatarURL != "" {
extraParams["avatar_url"] = p.Payload.AvatarURL
}
if p.Payload.TTS {
extraParams["tts"] = "true"
}
request, err := newfileUploadRequest(
webhookURL,
extraParams,
"file",
file,
)
if err != nil {
return err
}
client := &http.Client{}
_, err = client.Do(request)
if err != nil {
return err
}
return nil
}
// SendMessage to send discord message.
func (p *Plugin) SendMessage() error {
webhookURL := fmt.Sprintf("https://discordapp.com/api/webhooks/%s/%s", p.Config.WebhookID, p.Config.WebhookToken)
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(p.Payload); err != nil {
return err
}
_, err := http.Post(webhookURL, "application/json; charset=utf-8", b)
if err != nil {
return err
}
return nil
}
// DefaultTemplate is plugin default template for Drone CI.
func (p *Plugin) DefaultTemplate(title string) EmbedObject {
return EmbedObject{
Title: title,
Color: p.Color(),
}
}
// Template is plugin default template for Drone CI or GitHub Action.
func (p *Plugin) Template() EmbedObject {
if p.Config.GitHub {
message := fmt.Sprintf("%s/%s triggered by %s (%s)",
p.Repo.FullName,
p.GitHub.Workflow,
p.Repo.Namespace,
p.GitHub.EventName,
)
return EmbedObject{
Title: message,
Color: p.Color(),
Footer: EmbedFooterObject{
Text: DroneDesc,
IconURL: DroneIconURL,
},
}
}
description := ""
switch p.Build.Event {
case "push":
description = fmt.Sprintf("%s pushed to %s", p.Commit.Author, p.Commit.Branch)
case "pull_request":
branch := ""
if p.Commit.Ref != "" {
branch = p.Commit.Ref
} else {
branch = p.Commit.Branch
}
description = fmt.Sprintf("%s updated pull request %s", p.Commit.Author, branch)
case "tag":
description = fmt.Sprintf("%s pushed tag %s", p.Commit.Author, p.Commit.Branch)
}
return EmbedObject{
Title: p.Commit.Message,
Description: description,
URL: p.Build.Link,
Color: p.Color(),
Author: EmbedAuthorObject{
Name: p.Commit.Author,
IconURL: p.Commit.Avatar,
},
Footer: EmbedFooterObject{
Text: DroneDesc,
IconURL: DroneIconURL,
},
}
}
// Clear reset to default
func (p *Plugin) Clear() {
// clear content field.
p.Payload.Content = ""
p.Payload.Embeds = []EmbedObject{}
}
// Color code of the embed
func (p *Plugin) Color() int {
if p.Config.Color != "" {
p.Config.Color = strings.Replace(p.Config.Color, "#", "", -1)
if s, err := strconv.ParseInt(p.Config.Color, 16, 32); err == nil {
return int(s)
}
}
switch p.Build.Status {
case "success":
// green
return 0x1ac600
case "failure", "error", "killed":
// red
return 0xff3232
default:
// yellow
return 0xffd930
}
}