-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathplugin.go
498 lines (420 loc) · 10.6 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/appleboy/drone-template-lib/template"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
const (
formatMarkdown = "Markdown"
formatHTML = "HTML"
)
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
}
// 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 {
Token string
Debug bool
MatchEmail bool
To []string
Message string
MessageFile string
TemplateVarsFile string
TemplateVars string
Photo []string
Document []string
Sticker []string
Audio []string
Voice []string
Location []string
Video []string
Venue []string
Format string
GitHub bool
Socks5 string
DisableWebPagePreview bool
DisableNotification bool
}
// Plugin values.
Plugin struct {
GitHub GitHub
Repo Repo
Commit Commit
Build Build
Config Config
Tpl map[string]string
}
// Location format
Location struct {
Title string
Address string
Latitude float64
Longitude float64
}
)
var icons = map[string]string{
"failure": "❌",
"cancelled": "❕",
"success": "✅",
}
func trimElement(keys []string) []string {
var newKeys []string
for _, value := range keys {
value = strings.Trim(value, " ")
if len(value) == 0 {
continue
}
newKeys = append(newKeys, value)
}
return newKeys
}
func escapeMarkdown(keys []string) []string {
var newKeys []string
for _, value := range keys {
value = escapeMarkdownOne(value)
if len(value) == 0 {
continue
}
newKeys = append(newKeys, value)
}
return newKeys
}
func escapeMarkdownOne(str string) string {
str = strings.ReplaceAll(str, `\_`, `_`)
str = strings.ReplaceAll(str, `_`, `\_`)
return str
}
func globList(keys []string) []string {
var newKeys []string
for _, pattern := range keys {
pattern = strings.Trim(pattern, " ")
matches, err := filepath.Glob(pattern)
if err != nil {
fmt.Printf("Glob error for %q: %s\n", pattern, err)
continue
}
newKeys = append(newKeys, matches...)
}
return newKeys
}
func convertLocation(value string) (Location, bool) {
var latitude, longitude float64
var title, address string
var err error
values := trimElement(strings.Split(value, " "))
if len(values) < 2 {
return Location{}, true
}
if len(values) > 2 {
title = values[2]
}
if len(values) > 3 {
title = values[2]
address = values[3]
}
latitude, err = strconv.ParseFloat(values[0], 64)
if err != nil {
log.Println(err.Error())
return Location{}, true
}
longitude, err = strconv.ParseFloat(values[1], 64)
if err != nil {
log.Println(err.Error())
return Location{}, true
}
return Location{
Title: title,
Address: address,
Latitude: latitude,
Longitude: longitude,
}, false
}
func loadTextFromFile(filename string) ([]string, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
content, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return []string{string(content)}, nil
}
func parseTo(to []string, authorEmail string, matchEmail bool) []int64 {
var emails []int64
var ids []int64
attachEmail := true
for _, value := range trimElement(to) {
idArray := trimElement(strings.Split(value, ":"))
// check id
id, err := strconv.ParseInt(idArray[0], 10, 64)
if err != nil {
continue
}
// check match author email
if len(idArray) > 1 {
if email := idArray[1]; email != authorEmail {
continue
}
emails = append(emails, id)
attachEmail = false
continue
}
ids = append(ids, id)
}
if matchEmail && !attachEmail {
return emails
}
ids = append(ids, emails...)
return ids
}
func templateMessage(t string, plugin Plugin) (string, error) {
return template.RenderTrim(t, plugin)
}
// Exec executes the plugin.
func (p Plugin) Exec() (err error) {
if len(p.Config.Token) == 0 || len(p.Config.To) == 0 {
return errors.New("missing telegram token or user list")
}
var message []string
switch {
case len(p.Config.MessageFile) > 0:
message, err = loadTextFromFile(p.Config.MessageFile)
if err != nil {
return fmt.Errorf("error loading message file '%s': %v", p.Config.MessageFile, err)
}
case len(p.Config.Message) > 0:
message = []string{p.Config.Message}
default:
p.Config.Format = formatMarkdown
message = p.Message()
}
if p.Config.TemplateVars != "" {
p.Tpl = make(map[string]string)
if err = json.Unmarshal([]byte(p.Config.TemplateVars), &p.Tpl); err != nil {
return fmt.Errorf("unable to unmarshall template vars from JSON string '%s': %v", p.Config.TemplateVars, err)
}
}
if p.Config.TemplateVarsFile != "" {
content, err := os.ReadFile(p.Config.TemplateVarsFile)
if err != nil {
return fmt.Errorf("unable to read file with template vars '%s': %v", p.Config.TemplateVarsFile, err)
}
vars := make(map[string]string)
if err = json.Unmarshal(content, &vars); err != nil {
return fmt.Errorf("unable to unmarshall template vars from JSON file '%s': %v", p.Config.TemplateVarsFile, err)
}
// Merging templates variables from file to the variables form plugin settings (variables from file takes precedence)
if p.Tpl == nil {
p.Tpl = vars
} else {
for k, v := range vars {
p.Tpl[k] = v
}
}
}
var proxyURL *url.URL
if proxyURL, err = url.Parse(p.Config.Socks5); err != nil {
return fmt.Errorf("unable to unmarshall socks5 proxy url from string '%s': %v", p.Config.Socks5, err)
}
var bot *tgbotapi.BotAPI
if len(p.Config.Socks5) > 0 {
proxyClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
bot, err = tgbotapi.NewBotAPIWithClient(p.Config.Token, proxyClient)
} else {
bot, err = tgbotapi.NewBotAPI(p.Config.Token)
}
if err != nil {
return err
}
bot.Debug = p.Config.Debug
ids := parseTo(p.Config.To, p.Commit.Email, p.Config.MatchEmail)
photos := globList(trimElement(p.Config.Photo))
documents := globList(trimElement(p.Config.Document))
stickers := globList(trimElement(p.Config.Sticker))
audios := globList(trimElement(p.Config.Audio))
voices := globList(trimElement(p.Config.Voice))
videos := globList(trimElement(p.Config.Video))
locations := trimElement(p.Config.Location)
venues := trimElement(p.Config.Venue)
message = trimElement(message)
if p.Config.Format == formatMarkdown {
message = escapeMarkdown(message)
p.Commit.Message = escapeMarkdownOne(p.Commit.Message)
p.Commit.Branch = escapeMarkdownOne(p.Commit.Branch)
p.Commit.Link = escapeMarkdownOne(p.Commit.Link)
p.Commit.Author = escapeMarkdownOne(p.Commit.Author)
p.Commit.Email = escapeMarkdownOne(p.Commit.Email)
p.Build.Tag = escapeMarkdownOne(p.Build.Tag)
p.Build.Link = escapeMarkdownOne(p.Build.Link)
p.Build.PR = escapeMarkdownOne(p.Build.PR)
p.Repo.Namespace = escapeMarkdownOne(p.Repo.Namespace)
p.Repo.Name = escapeMarkdownOne(p.Repo.Name)
}
// send message.
for _, user := range ids {
for _, value := range message {
txt, err := templateMessage(value, p)
if err != nil {
return err
}
txt = html.UnescapeString(txt)
msg := tgbotapi.NewMessage(user, txt)
msg.ParseMode = p.Config.Format
msg.DisableWebPagePreview = p.Config.DisableWebPagePreview
msg.DisableNotification = p.Config.DisableNotification
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range photos {
msg := tgbotapi.NewPhotoUpload(user, value)
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range documents {
msg := tgbotapi.NewDocumentUpload(user, value)
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range stickers {
msg := tgbotapi.NewStickerUpload(user, value)
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range audios {
msg := tgbotapi.NewAudioUpload(user, value)
msg.Title = "Audio Message."
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range voices {
msg := tgbotapi.NewVoiceUpload(user, value)
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range videos {
msg := tgbotapi.NewVideoUpload(user, value)
msg.Caption = "Video Message"
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range locations {
location, empty := convertLocation(value)
if empty {
continue
}
msg := tgbotapi.NewLocation(user, location.Latitude, location.Longitude)
if err := p.Send(bot, msg); err != nil {
return err
}
}
for _, value := range venues {
location, empty := convertLocation(value)
if empty {
continue
}
msg := tgbotapi.NewVenue(user, location.Title, location.Address, location.Latitude, location.Longitude)
if err := p.Send(bot, msg); err != nil {
return err
}
}
}
return nil
}
// Send bot message.
func (p Plugin) Send(bot *tgbotapi.BotAPI, msg tgbotapi.Chattable) error {
message, err := bot.Send(msg)
if p.Config.Debug {
log.Println("=====================")
log.Printf("Response Message: %#v\n", message)
log.Println("=====================")
}
if err == nil {
return nil
}
return errors.New(strings.ReplaceAll(err.Error(), p.Config.Token, "<token>"))
}
// Message is plugin default message.
func (p Plugin) Message() []string {
icon := icons[strings.ToLower(p.Build.Status)]
if p.Config.GitHub {
return []string{fmt.Sprintf("%s/%s triggered by %s (%s)",
p.Repo.FullName,
p.GitHub.Workflow,
p.Repo.Namespace,
p.GitHub.EventName,
)}
}
// ✅ Build #106 of drone-telegram succeeded.
//
// 📝 Commit by appleboy on master:
// chore: update default template
//
// 🌐 https://cloud.drone.io/appleboy/drone-telegram/106
return []string{fmt.Sprintf("%s Build #%d of `%s` %s.\n\n📝 Commit by %s on `%s`:\n``` %s ```\n\n🌐 %s",
icon,
p.Build.Number,
p.Repo.FullName,
p.Build.Status,
p.Commit.Author,
p.Commit.Branch,
p.Commit.Message,
p.Build.Link,
)}
}