-
Notifications
You must be signed in to change notification settings - Fork 6
/
workplace-incoming-hook.go
658 lines (568 loc) · 17.2 KB
/
workplace-incoming-hook.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package main
import (
"fmt"
"github.com/warungpintar/workplace-incoming-hook/data"
"github.com/warungpintar/workplace-incoming-hook/helper"
"github.com/grokify/html-strip-tags-go"
"github.com/nurza/logo"
"bytes"
"encoding/json"
"flag"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
/*
Global variables
*/
type GitlabGroup struct {
Link string
Channel string
}
var (
// Logging
l logo.Logger
// Configuration
ThreadGitlab string
ThreadTuleap string
ThreadAppCenter string
PushIcon string // Push icon (Fb emoji)
MergeIcon string // Merge icon (Fb emoji)
BuildIcon string // Build icon (Fb emoji)
BotStartMessage string // Bot's start message
FbAPIUrl string // Fb API URL
Verbose bool // Enable verbose mode
ShowAllCommits bool // Show all commits rather than latest
HTTPTimeout int // Http timeout in second
ChatType string
TuleapURL string
Port string
URLNoteHookFunction string
TimeZone string
ThreadGitlabGroup []GitlabGroup
// Misc
currentBuildID float64 // Current build ID
n = "%5CnX" // Encoded line return
)
type GitlabServ struct{}
/*
Flags
*/
var (
ConfigFile = flag.String("f", "config.json", "Configuration file")
)
/*
Load configuration file
*/
func LoadConf() {
conf := struct {
ThreadGitlab string
ThreadAppCenter string
ThreadTuleap string
ThreadGitlabGroup []GitlabGroup
PushIcon string
MergeIcon string
BuildIcon string
BotStartMessage string
FbAPIUrl string
Verbose bool
ShowAllCommits bool
HTTPTimeout float64
ChatType string
TuleapURL string
Port string
URLNoteHookFunction string
TimeZone string
}{}
content, err := ioutil.ReadFile(*ConfigFile)
if err != nil {
l.Critical("Error: Read config file error: " + err.Error())
}
err = json.Unmarshal(content, &conf)
if err != nil {
l.Critical("Error: Parse config file error: " + err.Error())
}
PushIcon = conf.PushIcon
MergeIcon = conf.MergeIcon
BuildIcon = conf.BuildIcon
BotStartMessage = conf.BotStartMessage
FbAPIUrl = conf.FbAPIUrl
Verbose = conf.Verbose
ShowAllCommits = conf.ShowAllCommits
HTTPTimeout = int(conf.HTTPTimeout)
ChatType = conf.ChatType
TuleapURL = conf.TuleapURL
Port = conf.Port
ThreadGitlab = conf.ThreadGitlab
ThreadAppCenter = conf.ThreadAppCenter
ThreadTuleap = conf.ThreadTuleap
URLNoteHookFunction = conf.URLNoteHookFunction
TimeZone = conf.TimeZone
ThreadGitlabGroup = conf.ThreadGitlabGroup
}
/*
HTTP POST request
target: url target
payload: payload to send
Returned values:
int: HTTP response status code
string: HTTP response body
*/
func Post(target string, payload string) (int, string) {
// Variables
var err error // Error catching
var res *http.Response // HTTP response
var req *http.Request // HTTP request
var body []byte // Body response
// Build request
l.Debug(bytes.NewBufferString(payload))
req, _ = http.NewRequest("POST", target, bytes.NewBufferString(payload))
req.Header.Set("Content-Type", "application/json")
// Do request
client := &http.Client{}
client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: time.Duration(HTTPTimeout) * time.Second,
KeepAlive: time.Duration(HTTPTimeout) * time.Second,
}).Dial,
TLSHandshakeTimeout: time.Duration(HTTPTimeout) * time.Second,
}
res, err = client.Do(req)
if err != nil {
l.Error("Error : Curl POST : " + err.Error())
if res != nil {
return res.StatusCode, ""
}
return 0, ""
}
defer res.Body.Close()
// Read body
body, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
l.Error("Error : Curl POST body read : " + err.Error())
}
return res.StatusCode, string(body)
}
/*
Encode the git commit message with replacing some special characters not allowed by the Fb API
@param origin Git message to encode
*/
func MessageEncodeX(origin string) string {
return strings.Replace(origin, "%5CnX", "\\n\\n", -1)
}
func MessageEncode(origin string) string {
var result string
for _, e := range strings.Split(origin, "") {
switch e {
case "\n":
result += "%5CnX"
case "&":
result += " and "
default:
result += e
}
}
return result
}
/*
Send a message on WorkChat
@param channel : Targeted channel (could be personal or group)
*/
func SendWorkchatMessage(channel, message string, chattype string) {
// Variables
var payload string // POST data sent to Fb
// var icon string // Fb emoji
// toLower(channel)
l.Silly("toLower =", channel)
channel = strings.ToLower(channel)
l.Silly("toLower =", channel)
// POST Payload formating
payload = ""
if chattype == "group" {
payload += `{"recipient": { "thread_key": "` + strings.ToLower(channel) + `"} , "message": { "text": "` + message + `"}}`
} else {
payload += `{"recipient": { "id": "` + strings.ToLower(channel) + `"} , "message": { "text": "` + message + `"}}`
}
// Debug information
if Verbose {
l.Debug("payload =", payload)
}
code, body := Post(FbAPIUrl, MessageEncodeX(payload))
if code != 200 {
l.Error("Error post, Fb API returned:", body)
}
// Debug information
if Verbose {
l.Debug("Fb API returned:", body)
}
}
/*
Handler function to handle http requests for push
@param w http.ResponseWriter
@param r *http.Request
*/
func (s *GitlabServ) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var buffer bytes.Buffer // Buffer to get request body
var body string // Request body (it's a json)
// Log
l.Info("Request")
// Read http request header
gitlabEvent := r.Header.Get("X-Gitlab-Event")
if Verbose {
l.Debug("Gitlab Event =", gitlabEvent)
}
// Read service params
serviceParam := r.URL.Query().Get("service")
if Verbose {
l.Debug("Service =", serviceParam)
}
// Read http request body and put it in a string
if _, err := buffer.ReadFrom(r.Body); err != nil {
l.Error("Error : Read http request body failed :", err)
}
body = buffer.String()
// Debug information
if Verbose {
l.Debug("JsonString receive =", body)
}
switch serviceParam {
case "tuleap":
TaskHandler(body)
case "appcenter":
AppCenterHandler(body)
default:
switch gitlabEvent {
case "Push Hook":
PushHandler(body)
case "Merge Request Hook":
MergeHandler(body)
case "Build Hook":
BuildHandler(body)
case "Note Hook":
CommentHandler(body)
}
}
}
// CommentHandler call cloud function which handle comment event on gitlab
// and send to workplace bot
func CommentHandler(body string) {
// whether UrlNoteHookFunction has been set #see on config.json
if URLNoteHookFunction == "" {
l.Error("url comment service not ")
return
}
var json = []byte(body)
req, _ := http.NewRequest("POST", URLNoteHookFunction, bytes.NewBuffer(json))
req.Header.Set("X-Gitlab-Event", "Note Hook")
req.Header.Set("Content-Type", "application/json")
l.Info("Call service note hook")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
l.Error("Error : call [POST] microservice failed :", err)
}
defer resp.Body.Close()
l.Info("Response status :", resp.Status)
l.Info("Response header :", resp.Header)
}
func PushHandler(body string) {
var j data.Push
var err error // Error catching
var message string // Bot's message
var dateString string // Time of the last commit
// Parse json and put it in a the data.Build structure
err = json.Unmarshal([]byte(body), &j)
if err != nil {
// Error
l.Error("Error : Json parser failed :", err)
} else {
// Ok
// Debug information
if Verbose {
l.Debug("JsonObject =", j)
}
// Build the message
// Date parsing (parsing result example : 16 Jun 19 20:18)
dateString, _ = helper.ConvertTimeToZone(j.Commits[0].Timestamp, TimeZone)
// Message
lastCommit := j.Commits[len(j.Commits)-1]
commitCount := strconv.FormatFloat(j.TotalCommitsCount, 'f', 0, 64)
if ShowAllCommits {
message += "Push on *" + j.Repository.Name + "* by *" + j.UserName + "* at *" + dateString + "* on branch *" + j.Ref + "*:" + n // First line
message += commitCount + " commits :" // Second line
for i := range j.Commits {
c := j.Commits[i]
message += n + "< " + c.URL + " | " + c.ID[0:7] + " >: " + "_" + MessageEncode(c.Message) + "_"
}
} else {
// First line
message += "[PUSH] " + n
message += fmt.Sprintf("Push on *%s* by *%s* at *%s* on branch *%s*: ",
j.Repository.Name,
j.UserName,
dateString,
j.Ref) + n
// Second line
message += "Last commit : < " + lastCommit.URL + " | " + lastCommit.ID + " > :" + n
// Third line (last commit message)
message += "```" + MessageEncode(lastCommit.Message) + "```"
}
SendWorkChatGroupMessage(j.Repository.URL, message)
SendWorkchatMessage(ThreadGitlab, message, ChatType)
}
}
/*
Handler function to handle http requests for merge
@param body string
*/
func MergeHandler(body string) {
var j data.Merge
var err error // Error catching
var message string // Bot's message
var dateString string // Time of the last commit
// Parse json and put it in a the data.Build structure
err = json.Unmarshal([]byte(body), &j)
if err != nil {
// Error
l.Error("Error : Json parser failed :", err)
} else {
// Ok
// Debug information
if Verbose {
l.Debug("JsonObject =", j)
}
// Build the message
// Date parsing (parsing result example : 16 Jun 19 20:18)
dateString, _ = helper.ConvertTimeToZone(j.ObjectAttributes.CreatedAt, TimeZone)
// Message
// First line
message += fmt.Sprintf("[MERGE REQUEST %s] ", strings.ToUpper(j.ObjectAttributes.State)) + n
message += fmt.Sprintf("Target : *%s/%s* Source : *%s/%s* at *%s* ",
j.ObjectAttributes.Target.Name,
j.ObjectAttributes.TargetBranch,
j.ObjectAttributes.Source.Name,
j.ObjectAttributes.SourceBranch,
dateString) + n
// Second line (URL link for merge request location)
message += fmt.Sprintf("Link : *%s*", j.ObjectAttributes.URL) + n
// Third Line (Description of merge request)
message += "Description: " + MessageEncode(j.ObjectAttributes.Description)
if len(j.Changes.Labels.Current) > 0 || len(j.Changes.Labels.Previous) > 0 {
message += n + " [LABELS] "
for _, currentLabel := range j.Changes.Labels.Current {
added := true
for _, previousLabel := range j.Changes.Labels.Previous {
if currentLabel.ID == previousLabel.ID {
added = false
break
}
}
if added {
message += n + "`" + currentLabel.Title + "`" + " " + "*Added*"
}
}
for _, previousLabel := range j.Changes.Labels.Previous {
removed := true
for _, currentLabel := range j.Changes.Labels.Current {
if previousLabel.ID == currentLabel.ID {
removed = false
break
}
}
if removed {
message += n + "`" + previousLabel.Title + "`" + " " + "*Removed*"
}
}
}
SendWorkChatGroupMessage(j.ObjectAttributes.Source.SSHURL, message)
SendWorkchatMessage(ThreadGitlab, message, ChatType)
}
}
/*
Handler function to handle send message to gitlab grup
@param repourl string, message string
*/
func SendWorkChatGroupMessage(repourl string, message string) {
for _, val := range ThreadGitlabGroup {
if strings.Contains(repourl, val.Link) {
SendWorkchatMessage(val.Channel, message, ChatType)
}
}
}
/*
Handler function to handle http requests for build
@param body string
*/
func BuildHandler(body string) {
var j data.Build
var err error // Error catching
var message string // Bot's message
var date time.Time // Time of the last commit
// Parse json and put it in a the data.Build structure
err = json.Unmarshal([]byte(body), &j)
if err != nil {
// Error
l.Error("Error : Json parser failed :", err)
} else {
// Ok
// Debug information
if Verbose {
l.Debug("JsonObject =", j)
}
// Test if the message is already sent
if currentBuildID < j.BuildID {
// Not sent
currentBuildID = j.BuildID // Update current build ID
// Send the message
// Date parsing (parsing result example : 18 November 2014 - 14:34)
date, _ = time.Parse("2006-01-02T15:04:05Z07:00", j.PushData.Commits[0].Timestamp)
var dateString = strconv.Itoa(date.Day()) + " " + date.Month().String() + " " + strconv.Itoa(date.Year()) +
" - " + strconv.Itoa(date.Hour()) + ":" + strconv.Itoa(date.Minute())
// Message
lastCommit := j.PushData.Commits[len(j.PushData.Commits)-1]
// First line
message += "[BUILD] " + n
message += fmt.Sprintf("%s : Push on *%s* by *%s* at *%s* on branch *%s*:",
strings.ToUpper(j.BuildStatus),
j.PushData.Repository.Name,
j.PushData.UserName,
dateString,
j.Ref) + n
// Second line
message += "Last commit : <" + lastCommit.URL + "|" + lastCommit.ID + "> :" + n
// Third line (last commit message)
message += "```" + MessageEncode(lastCommit.Message) + "```"
SendWorkchatMessage(ThreadGitlab, message, ChatType)
}
}
}
/*
Handler function to handle http requests for build
@param body string
*/
func TaskHandler(body string) {
var j data.Tptask
var Task data.TuleapTask
var err error // Error catching
var message string // Bot's message
var date time.Time // Time of the last commit
// Parse json and put it in a the data.Build structure
payload := strings.Split(body, "payload=")
parsedValue, _ := url.QueryUnescape(payload[1])
err = json.Unmarshal([]byte(parsedValue), &j)
if err != nil {
// Error
l.Error("Error : Json parser failed :", err)
} else {
// Ok
// Debug information
if Verbose {
l.Debug("JsonObject =", j)
}
Task.Name = j.User.RealName
for _, val := range j.Current.Values {
switch val.Label {
case "Task title":
Task.TaskTitle = val.Value.(string)
case "Status":
Task.Status = val.VValues[0].Label
case "Links":
if len(val.ReverseLinks) > 0 {
Task.ProjectURL = TuleapURL + "projects/" + string(val.ReverseLinks[0].Tracker.Project.ID)
Task.ProjectName = val.ReverseLinks[0].Tracker.Project.Label
}
case "Artifact ID":
Task.TaskID = strconv.FormatFloat(val.Value.(float64), 'f', 0, 64)
Task.TrackerURL = TuleapURL + "plugins/tracker/?aid=" + Task.TaskID
case "Submitted on":
Task.SubmittedOn = val.Value.(string)
case "Details":
Task.Details = strip.StripTags(val.Value.(string))
case "Type":
Task.Type = val.VValues[0].Label
}
}
for _, val := range j.Previous.Values {
if val.Label == "Status" {
Task.OldStatus = val.VValues[0].Label
}
}
if Task.Status != Task.OldStatus {
date, _ = time.Parse(time.RFC3339, Task.SubmittedOn)
var dateString = date.Format("02 Jan 06 15:04")
// Message
// First line
message += fmt.Sprintf("Move Task *#%s* [%s] on Project *%s* by *%s* at *%s* from *%s* to *%s*",
Task.TaskID,
Task.TaskTitle,
Task.ProjectName,
Task.Name,
dateString,
Task.OldStatus,
Task.Status) + n
// Third line (last commit message)
message += "Description: " + MessageEncode(Task.Details) + n
message += "Task URL : " + Task.TrackerURL
SendWorkchatMessage(ThreadTuleap, message, ChatType)
}
}
}
/*
Handler function to handle http requests for appcenter
@param body string
*/
func AppCenterHandler(body string) {
var j data.AppCenter
var err error // Error catching
var message string // Bot's message
var date time.Time // Time of the last commit
// Parse json and put it in a the data.Build structure
err = json.Unmarshal([]byte(body), &j)
if err != nil {
// Error
l.Error("Error : Json parser failed :", err)
} else {
// Ok
// Debug information
if Verbose {
l.Debug("JsonObject =", j)
}
// Send the message
// Date parsing (parsing result example : 18 November 2014 - 14:34)
date, _ = time.Parse(time.RFC3339, j.SentAt)
var dateString = date.Format("02 Jan 06 15:04")
// Message
message = ""
if j.DistributionGroupID != "" {
message += "*Distributed [" + j.AppDisplayName + "]*" + n // First line
message += "Group ID *" + j.DistributionGroupID + "* on " + dateString + n
message += "Install Link: " + j.InstallLink // Third line (last commit message)
} else if j.Reason == "" {
message += "*" + j.AppName + "* (" + j.OS + ") Branch *" + j.Branch + "*" + n // First line
message += "Build *#" + j.BuildID + "* [" + j.BuildStatus + "] on " + dateString + n
message += "URL: " + j.BuildLink // Third line (last commit message)
} else {
message += "*Crash!!! [" + j.AppDisplayName + "]*" + n // First line
message += "Reason *" + j.Reason + "* [" + j.Name + "] on " + dateString + n
message += "URL: " + j.URL // Third line (last commit message)
}
SendWorkchatMessage(ThreadAppCenter, message, ChatType)
}
}
/*
Main function
*/
func main() {
flag.Parse() // Parse flags
l.AddTransport(logo.Console).AddColor(logo.ConsoleColor) // Configure Logger
l.EnableAllLevels() // Configure Logger
LoadConf() // Load configuration
l.Info(BotStartMessage) // Logging
l.Error(http.ListenAndServe(":"+Port, &GitlabServ{})) // Run HTTP server for push hook
}