-
Notifications
You must be signed in to change notification settings - Fork 4
/
webhook.go
565 lines (458 loc) Β· 17.8 KB
/
webhook.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
package bitbucket
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"time"
api "github.com/integram-org/bitbucket/api"
"github.com/requilence/integram"
)
type oldWebhook struct {
CanonURL string `json:"canon_url"`
Commits []struct {
Author string `json:"author"`
Branch string `json:"branch"`
Files []struct {
File string `json:"file"`
Type string `json:"type"`
} `json:"files"`
Message string `json:"message"`
Node string `json:"node"`
Parents []string `json:"parents"`
RawAuthor string `json:"raw_author"`
RawNode string `json:"raw_node"`
Revision int `json:"revision"`
Size int `json:"size"`
Timestamp string `json:"timestamp"`
Utctimestamp string `json:"utctimestamp"`
} `json:"commits"`
Repository struct {
AbsoluteURL string `json:"absolute_url"`
Fork bool `json:"fork"`
IsPrivate bool `json:"is_private"`
Name string `json:"name"`
Owner string `json:"owner"`
Scm string `json:"scm"`
Slug string `json:"slug"`
Website string `json:"website"`
} `json:"repository"`
User string `json:"user"`
}
// map of webhook events to the payload type
var eventTypeMap = map[string]interface{}{
"repo:push": api.RepoPushEvent{},
"repo:fork": api.RepoForkEvent{},
"repo:commit_comment_created": api.RepoCommitCommentCreatedEvent{},
"repo:commit_status_created": api.RepoCommitStatusCreatedEvent{},
"repo:commit_status_updated": api.RepoCommitStatusUpdatedEvent{},
"issue:created": api.IssueCreatedEvent{},
"issue:updated": api.IssueUpdatedEvent{},
"issue:comment_created": api.IssueCommentCreatedEvent{},
"pullrequest:created": api.PullRequestCreatedEvent{},
"pullrequest:updated": api.PullRequestUpdatedEvent{},
"pullrequest:approved": api.PullRequestApprovedEvent{},
"pullrequest:unapproved": api.PullRequestApprovalRemovedEvent{},
"pullrequest:fulfilled": api.PullRequestMergedEvent{},
"pullrequest:rejected": api.PullRequestDeclinedEvent{},
"pullrequest:comment_created": api.PullRequestCommentCreatedEvent{},
"pullrequest:comment_updated": api.PullRequestCommentUpdatedEvent{},
"pull_request:comment_deleted": api.PullRequestCommentDeletedEvent{},
}
func commitUniqueID(commitHash string) string {
return "commit_" + commitHash
}
func commitCommentUniqueID(commitHash string, commentID int) string {
return "commit_" + commitHash + "_" + strconv.Itoa(commentID)
}
func issueUniqueID(fullRepo string, issueID int) string {
return "issue_" + fullRepo + "_" + strconv.Itoa(issueID)
}
func prUniqueID(fullRepo string, prID int) string {
return "pr_" + fullRepo + "_" + strconv.Itoa(prID)
}
func prCommentUniqueID(fullRepo string, prID int, commentID int) string {
return "pr_" + fullRepo + "_" + strconv.Itoa(prID) + "_" + strconv.Itoa(commentID)
}
func issueCommentUniqueID(fullRepo string, issueID int, commentID int) string {
return "issue_" + fullRepo + "_" + strconv.Itoa(issueID) + "_" + strconv.Itoa(commentID)
}
var issueStates = map[string]string{"new": "set as new", "open": "opened", "on hold": "put on hold", "resolved": "marked as resolved", "duplicate": "marked as duplicate", "invalid": "marked as invalid", "wontfix": "marked as won't fix", "closed": "closed"}
func issueDecentState(state string) string {
if v, exists := issueStates[state]; exists {
return v
}
return state
}
var reRepoFullNameFromURL = regexp.MustCompile("repositories/([^/]*/[^/]*)")
func prText(c *integram.Context, pr *api.PullRequest) string {
r := reRepoFullNameFromURL.FindStringSubmatch(pr.Links.Self.Href)
repo := ""
if len(r) == 2 {
repo = r[1]
}
if pr.Description == pr.Title {
pr.Description = ""
}
text := fmt.Sprintf("%s %s\n%s",
m.Bold(pr.Title),
m.URL("β", c.WebPreview("Pull Request", repo, "by "+pr.Author.DisplayName, pr.Links.HTML.String(), "")),
pr.Description)
if len(pr.Reviewers) > 0 {
text += "\nΒ Β π€ "
for i, reviewer := range pr.Reviewers {
text += mention(c, &reviewer)
if i < len(pr.Reviewers)-1 {
text += ", "
}
}
}
return text
}
func issueText(c *integram.Context, issue *api.Issue) string {
r := reRepoFullNameFromURL.FindStringSubmatch(issue.Links.Self.Href)
repo := ""
if len(r) == 2 {
repo = r[1]
}
return fmt.Sprintf("%s %s\n%s\n%s",
m.Bold(issue.Title),
m.URL("β", c.WebPreview("by "+issue.Reporter.DisplayName, repo, "", issue.Links.HTML.String(), "")),
issue.Content.Raw,
"#"+issue.Priority+" #"+issue.Type)
}
func prInlineKeyboard(pr *api.PullRequest) integram.InlineKeyboard {
but := integram.InlineButtons{}
but.Append("assign", "Assign")
but.Append("commits", "Commits")
return but.Markup(4, "actions")
}
func commitInlineKeyboard(commit *api.Commit) integram.InlineKeyboard {
but := integram.InlineButtons{}
// wating for api endpoints..
if len(commit.ApprovedActorsUUID) > 0 {
but.Append("vote", fmt.Sprintf("β
Approved (%d)", len(commit.ApprovedActorsUUID)))
} else {
but.Append("vote", "β
Approve")
}
return but.Markup(4, "actions")
}
func issueInlineKeyboard(issue *api.Issue) integram.InlineKeyboard {
but := integram.InlineButtons{}
// wating for api endpoints..
if issue.Votes > 0 {
but.Append("vote", fmt.Sprintf("π %d", issue.Votes))
} else {
but.Append("vote", "π")
}
return but.Markup(4, "actions")
}
func commitShort(hash string) string {
if len(hash) > 10 {
return hash[0:10]
}
return hash
}
func oldWebhookHandler(c *integram.Context, wc *integram.WebhookContext) (err error) {
wh := oldWebhook{}
payload := wc.FormValue("payload")
if payload == "" {
return errors.New("X-Event-Key header missed and old-style webhook data not found")
}
json.Unmarshal([]byte(payload), &wh)
if wh.CanonURL == "" {
return errors.New("Error decoding payload for old webhook")
}
msg := c.NewMessage()
commits := 0
text := ""
wp := ""
if len(wh.Commits) == 0 {
return nil
}
headCommit := wh.Commits[len(wh.Commits)-1]
if len(wh.Commits) > 1 {
wp = c.WebPreview(fmt.Sprintf("%d commits", len(wh.Commits)), "@"+wh.Commits[0].Node[0:10]+" ... @"+headCommit.Node[0:10], "", wh.CanonURL+wh.Repository.AbsoluteURL+"/compare/"+headCommit.Node+".."+wh.Commits[0].Parents[0], "")
anyOherPersonCommits := false
for _, commit := range wh.Commits {
if commit.Author != wh.User {
anyOherPersonCommits = true
break
}
}
for _, commit := range wh.Commits {
commits++
if anyOherPersonCommits {
text += m.Bold(commit.Author) + ": "
}
text += m.URL(commit.Message, wh.CanonURL+wh.Repository.AbsoluteURL+"commits/"+headCommit.Node[0:10]) + "\n"
}
} else if len(wh.Commits) == 1 {
wp = c.WebPreview("Commit", "@"+headCommit.Node[0:10], "", wh.CanonURL+wh.Repository.AbsoluteURL+"commits/"+headCommit.Node[0:10], "")
commit := &wh.Commits[0]
if commit.Author != wh.User {
text += m.Bold(commit.Author) + ": "
}
text += commit.Message + "\n"
}
if len(wh.Commits) > 0 {
return msg.SetTextFmt("%s %s to %s/%s\n%s",
m.Bold(wh.User),
m.URL("pushed", wp),
m.URL(wh.Repository.Name, wh.CanonURL+wh.Repository.AbsoluteURL),
m.URL(headCommit.Branch, wh.CanonURL+wh.Repository.AbsoluteURL+"branch/"+headCommit.Branch),
text).
EnableHTML().
Send()
}
return nil
}
func webhookHandler(c *integram.Context, wc *integram.WebhookContext) (err error) {
eventKey := wc.Header("X-Event-Key")
if eventKey == "" {
// try the old one Bitbucket POST service
return oldWebhookHandler(c, wc)
}
if _, ok := eventTypeMap[eventKey]; !ok {
return errors.New("Bad X-Event-Key: " + eventKey)
}
c.Log().Debugf("eventKey=%v", eventKey)
if err != nil {
return errors.New("JSON deserialization error: " + err.Error())
}
switch eventKey {
case "repo:push":
event := api.RepoPushEvent{}
wc.JSON(&event)
for _, change := range event.Push.Changes {
msg := c.NewMessage()
commits := 0
text := ""
if len(change.Commits) > 1 {
anyOherPersonCommits := false
for _, commit := range change.Commits {
if commit.Author.User.UUID != event.Actor.UUID {
anyOherPersonCommits = true
break
}
}
for _, commit := range change.Commits {
commits++
if anyOherPersonCommits {
text += mention(c, &commit.Author.User) + ": "
}
text += m.URL(commit.Message, commit.Links.HTML.Href) + "\n"
}
if change.Truncated {
text += m.URL("... See all", change.Links.Commits.Href) + "\n"
}
} else if len(change.Commits) == 1 {
commits++
commit := &change.Commits[0]
if commit.Author.User.UUID != event.Actor.UUID {
text += mention(c, &commit.Author.User) + ": "
}
text += commit.Message + "\n"
}
wp := ""
if change.Truncated {
wp = c.WebPreview("> 5 commits", "@"+commitShort(change.Old.Target.Hash)+" ... @"+commitShort(change.New.Target.Hash), "", change.Links.HTML.Href, "")
} else if commits > 1 {
wp = c.WebPreview(fmt.Sprintf("%d commits", commits), "@"+commitShort(change.Old.Target.Hash)+" ... @"+commitShort(change.New.Target.Hash), "", change.Links.HTML.Href, "")
} else if commits == 1 {
wp = c.WebPreview("Commit", "@"+commitShort(change.New.Target.Hash), "", change.Commits[0].Links.HTML.Href, "")
}
if commits > 0 {
pushedText := ""
if change.Forced {
pushedText = m.URL("βοΈ forcibly pushed", wp)
} else {
pushedText = m.URL("pushed", wp)
}
err = msg.SetTextFmt("%s %s to %s/%s\n%s",
mention(c, &change.New.Target.Author.User),
pushedText,
m.URL(event.Repository.Name, event.Repository.Links.HTML.Href),
m.URL(change.New.Name, change.New.Links.HTML.Href),
text).
AddEventID(commitUniqueID(change.Commits[0].Hash)).
EnableHTML().
Send()
}
}
case "issue:created":
event := api.IssueCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
event.Issue.Repository = &event.Repository
c.SetServiceCache(issueUniqueID(event.Repository.FullName, event.Issue.ID), event.Issue, time.Hour*24*365)
return c.NewMessage().AddEventID(issueUniqueID(event.Repository.FullName, event.Issue.ID)).
SetInlineKeyboard(issueInlineKeyboard(&event.Issue)).
SetText(issueText(c, &event.Issue)).
SetCallbackAction(issueInlineButtonPressed, event.Repository.FullName, event.Issue.ID).
EnableHTML().Send()
case "issue:comment_created":
event := api.IssueCommentCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
var rm *integram.Message
if event.Comment.Parent.ID > 0 {
// actually bitbucket doesn't provide parent id for issue comments for now
rm, _ = c.FindMessageByEventID(issueCommentUniqueID(event.Repository.FullName, event.Issue.ID, event.Comment.Parent.ID))
}
if rm == nil {
rm, _ = c.FindMessageByEventID(issueUniqueID(event.Repository.FullName, event.Issue.ID))
}
msg := c.NewMessage().AddEventID(issueCommentUniqueID(event.Repository.FullName, event.Issue.ID, event.Comment.ID)).EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("%s: %s", mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
}
wp := c.WebPreview("Issue", event.Issue.Title, event.Repository.FullName, event.Comment.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("%s %s: %s", m.URL("π¬", wp), mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
case "repo:commit_comment_created":
event := api.RepoCommitCommentCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
var rm *integram.Message
if event.Comment.Parent.ID > 0 {
// actually bitbucket doesn't provide parent id for issue comments for now
rm, _ = c.FindMessageByEventID(commitCommentUniqueID(event.Commit.Hash, event.Comment.Parent.ID))
}
if rm == nil {
rm, _ = c.FindMessageByEventID(commitUniqueID(event.Commit.Hash))
}
msg := c.NewMessage().AddEventID(commitCommentUniqueID(event.Commit.Hash, event.Comment.Parent.ID)).EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("%s: %s", mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
}
wp := c.WebPreview("Commit", "@"+event.Commit.Hash[0:10], event.Repository.FullName, event.Comment.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("%s %s: %s", m.URL("π¬", wp), mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
case "issue:updated":
event := api.IssueUpdatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
eventID := issueUniqueID(event.Repository.FullName, event.Issue.ID)
rm, _ := c.FindMessageByEventID(eventID)
msg := c.NewMessage().AddEventID(issueCommentUniqueID(event.Repository.FullName, event.Issue.ID, event.Comment.ID)).EnableHTML()
if event.Comment.Content.Raw != "" {
event.Comment.Content.Raw = ": " + event.Comment.Content.Raw
}
if rm != nil {
c.EditMessagesTextWithEventID(eventID, issueText(c, &event.Issue))
// if last Issue message just posted
if err == nil && time.Now().Sub(rm.Date).Seconds() < 60 {
return nil
}
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("%s update the issue%s", mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
}
return msg.SetText(fmt.Sprintf("%s updated an issue%s\n%s", mention(c, &event.Actor), event.Comment.Content.Raw, issueText(c, &event.Issue))).Send()
case "pullrequest:updated":
event := api.PullRequestCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
prText := prText(c, &event.PullRequest)
eventID := prUniqueID(event.Repository.FullName, event.PullRequest.ID)
rm, _ := c.FindMessageByEventID(eventID)
msg := c.NewMessage()
if rm != nil {
c.EditMessagesTextWithEventID(eventID, prText)
// if last PR message just posted
if err == nil && time.Now().Sub(rm.Date).Seconds() < 60 {
return nil
}
msg.SetReplyToMsgID(rm.MsgID)
} else {
msg.AddEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
}
return msg.
SetText("βοΈ " + prText).
EnableHTML().Send()
case "pullrequest:created":
event := api.PullRequestCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
c.SetServiceCache(prUniqueID(event.Repository.FullName, event.PullRequest.ID), event.PullRequest, time.Hour*24*365)
return c.NewMessage().AddEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID)).
SetText(prText(c, &event.PullRequest)).
EnableHTML().Send()
case "pullrequest:approved":
event := api.PullRequestApprovedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
rm, _ := c.FindMessageByEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
msg := c.NewMessage().EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("β
Approved by %s", mention(c, &event.Actor))).Send()
}
wp := c.WebPreview("Pull Request", event.PullRequest.Title, "by "+event.PullRequest.Author.DisplayName+" in "+event.Repository.FullName, event.PullRequest.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("β
%s by %s", m.URL("Approved", wp), mention(c, &event.Actor))).Send()
case "pullrequest:unapproved":
event := api.PullRequestApprovalRemovedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
rm, _ := c.FindMessageByEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
msg := c.NewMessage().EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("β %s removed approval", mention(c, &event.Actor))).Send()
}
wp := c.WebPreview("Pull Request", event.PullRequest.Title, "by "+event.PullRequest.Author.DisplayName+" in "+event.Repository.FullName, event.PullRequest.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("β %s %s", mention(c, &event.Actor), m.URL("removed approval", wp))).Send()
case "pullrequest:fulfilled":
event := api.PullRequestMergedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
rm, _ := c.FindMessageByEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
msg := c.NewMessage().EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("β
Merged by %s", mention(c, &event.Actor))).Send()
}
wp := c.WebPreview("Pull Request", event.PullRequest.Title, "by "+event.PullRequest.Author.DisplayName+" in "+event.Repository.FullName, event.PullRequest.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("β
%s by %s", m.URL("Merged", wp), mention(c, &event.Actor))).Send()
case "pullrequest:rejected":
event := api.PullRequestDeclinedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
rm, _ := c.FindMessageByEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
msg := c.NewMessage().EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("β Declined by %s: %s", mention(c, &event.Actor), event.PullRequest.Reason)).Send()
}
wp := c.WebPreview("Pull Request", event.PullRequest.Title, "by "+event.PullRequest.Author.DisplayName+" in "+event.Repository.FullName, event.PullRequest.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("β %s by %s", m.URL("Declined", wp), mention(c, &event.Actor))).Send()
case "pullrequest:comment_created":
event := api.PullRequestCommentCreatedEvent{}
err := wc.JSON(&event)
if err != nil {
return err
}
rm, _ := c.FindMessageByEventID(prUniqueID(event.Repository.FullName, event.PullRequest.ID))
msg := c.NewMessage().AddEventID(prCommentUniqueID(event.Repository.FullName, event.PullRequest.ID, event.Comment.ID)).EnableHTML()
if rm != nil {
return msg.SetReplyToMsgID(rm.MsgID).SetText(fmt.Sprintf("%s: %s", mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
}
wp := c.WebPreview("Pull Request", event.PullRequest.Title, event.Repository.FullName, event.PullRequest.Links.HTML.Href, "")
return msg.SetText(fmt.Sprintf("%s %s: %s", m.URL("π¬", wp), mention(c, &event.Actor), event.Comment.Content.Raw)).Send()
}
return err
}