-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathWebhook.java
463 lines (403 loc) · 19.3 KB
/
Webhook.java
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
/**
* Yobi, Project Hosting SW
*
* Copyright 2015 NAVER Corp.
* http://yobi.io
*
* @author Jihwan Chun
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package models;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.enumeration.EventType;
import models.enumeration.PullRequestReviewAction;
import models.enumeration.ResourceType;
import models.resource.GlobalResource;
import models.resource.Resource;
import models.resource.ResourceConvertible;
import org.eclipse.jgit.revwalk.RevCommit;
import play.Logger;
import play.api.i18n.Lang;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
import play.i18n.Messages;
import play.libs.F.Function;
import play.libs.Json;
import play.libs.ws.WS;
import play.libs.ws.WSRequestHolder;
import play.libs.ws.WSResponse;
import playRepository.GitCommit;
import utils.RouteUtil;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Size;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* A webhook to be sent by events in project
*/
@Entity
public class Webhook extends Model implements ResourceConvertible {
private static final long serialVersionUID = 1L;
public static final Finder<Long, Webhook> find = new Finder<>(Long.class, Webhook.class);
/**
* Primary Key.
*/
@Id
public Long id;
/**
* Project which have this webhook.
*/
@ManyToOne
public Project project;
/**
* Payload URL of webhook.
*/
@Required
@Size(max=2000, message="project.webhook.payloadUrl.tooLong")
public String payloadUrl;
/**
* Secret token for server identity.
*/
@Size(max=250, message="project.webhook.secret.tooLong")
public String secret;
/**
* Type of webhook (true = git only push, false = all cases)
*/
public Boolean gitPushOnly;
/**
* Payload URL of webhook.
*/
public Date createdAt;
/**
* Construct a webhook by the given {@code payloadUrl} and {@code secret}.
*
* @param projectId the ID of project which will have this webhook
* @param payloadUrl the payload URL for this webhook
* @param gitPushOnly type of webhook (true = git only push, false = all cases)
* @param secret the secret token for server identity
*/
public Webhook(Long projectId, String payloadUrl, String secret, Boolean gitPushOnly) {
if (secret == null) {
secret = "";
}
this.project = Project.find.byId(projectId);
this.payloadUrl = payloadUrl;
this.secret = secret;
this.gitPushOnly = gitPushOnly;
this.createdAt = new Date();
}
/**
* Returns a {@link Resource} representation of this webhook.
*
* {@link utils.AccessControl}.may use this method to check if an user has
* a permission to access this label.
*
* @return a {@link Resource} representation of this webhook
*/
@Override
public Resource asResource() {
return new GlobalResource() {
@Override
public String getId() {
return id.toString();
}
@Override
public ResourceType getType() {
return ResourceType.WEBHOOK;
}
};
}
public static List<Webhook> findByProject(Long projectId) {
return find.where().eq("project.id", projectId).findList();
}
public static void create(Long projectId, String payloadUrl, String secret, Boolean gitPushOnly) {
if (!payloadUrl.isEmpty()) {
Webhook webhook = new Webhook(projectId, payloadUrl, secret, gitPushOnly);
webhook.save();
}
// TODO : Raise appropriate error when required field is empty
}
public static void delete(Long webhookId, Long projectId) {
Webhook.findByIds(webhookId, projectId).delete();
}
public static Webhook findByIds(Long webhookId, Long projectId) {
return find.where()
.eq("webhook.id", webhookId)
.eq("project.id", projectId)
.findUnique();
}
private void sendRequest(String payload) {
try {
WSRequestHolder requestHolder = WS.url(this.payloadUrl);
requestHolder
.setHeader("Content-Type", "application/json")
.setHeader("User-Agent", "Yobi-Hookshot")
.setHeader("Authorization", "token " + this.secret)
.post(payload)
.map(
new Function<WSResponse, Integer>() {
public Integer apply(WSResponse response) {
int statusCode = response.getStatus();
String statusText = response.getStatusText();
if (statusCode < 200 || statusCode >= 300) {
// Unsuccessful status code - log some information in server.
Logger.info("[Webhook] Request responded code " + Integer.toString(statusCode) + ": " + statusText);
Logger.info("[Webhook] Request payload: " + payload);
}
return 0;
}
}
);
} catch (Exception e) {
// Request failed (Dead end point or invalid payload URL) - log some information in server.
Logger.info("[Webhook] Request failed at given payload URL: " + this.payloadUrl);
}
}
public void sendRequestToPayloadUrl(List<RevCommit> commits, List<String> refNames, User sender, String title) {
String requestBodyString = buildRequestBody(commits, refNames, sender, title);
sendRequest(requestBodyString);
}
public void sendRequestToPayloadUrl(EventType eventType, User sender, Issue eventIssue) {
String requestBodyString = buildRequestBody(eventType, sender, eventIssue);
sendRequest(requestBodyString);
}
public void sendRequestToPayloadUrl(EventType eventType, User sender, PullRequest eventPullRequest) {
String requestBodyString = buildRequestBody(eventType, sender, eventPullRequest);
sendRequest(requestBodyString);
}
public void sendRequestToPayloadUrl(EventType eventType, User sender, PullRequest eventPullRequest, PullRequestReviewAction reviewAction) {
String requestBodyString = buildRequestBody(eventType, sender, eventPullRequest, reviewAction);
sendRequest(requestBodyString);
}
public void sendRequestToPayloadUrl(EventType eventType, User sender, Comment eventComment) {
String requestBodyString = buildRequestBody(eventType, sender, eventComment);
sendRequest(requestBodyString);
}
private String buildRequestBody(List<RevCommit> commits, List<String> refNames, User sender, String title) {
ObjectNode requestBody = Json.newObject();
ObjectMapper mapper = new ObjectMapper();
ArrayNode refNamesNodes = mapper.createArrayNode();
ArrayNode commitsNodes = mapper.createArrayNode();
for (String refName : refNames) {
refNamesNodes.add(refName);
}
requestBody.put("ref", refNamesNodes);
for (RevCommit commit : commits) {
commitsNodes.add(buildJSONFromCommit(project, commit));
}
requestBody.put("commits", commitsNodes);
requestBody.put("head_commit", commitsNodes.get(0));
requestBody.put("sender", buildSenderJSON(sender));
requestBody.put("pusher", buildPusherJSON(sender));
requestBody.put("repository", buildRepositoryJSON());
return Json.stringify(requestBody);
}
private String buildRequestBody(EventType eventType, User sender, PullRequest eventPullRequest) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode detailFields = mapper.createArrayNode();
ArrayNode attachments = mapper.createArrayNode();
String requestMessage = "[" + project.name + "] "+ sender.name + " ";
switch (eventType) {
case NEW_PULL_REQUEST:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.new.pullrequest");
break;
case PULL_REQUEST_STATE_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.pullrequest.state.changed");
break;
case PULL_REQUEST_MERGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.pullrequest.merged");
break;
case PULL_REQUEST_COMMIT_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.pullrequest.commit.changed");
break;
}
requestMessage += " <" + utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(eventPullRequest) + "|#" + eventPullRequest.number + ": " + eventPullRequest.title + ">";
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.sender"), eventPullRequest.contributor.name, false));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.from"), eventPullRequest.fromBranch, true));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.to"), eventPullRequest.toBranch,true));
attachments.add(buildAttachmentJSON(eventPullRequest.body, detailFields));
return Json.stringify(buildRequestJSON(requestMessage, attachments));
}
private String buildRequestBody(EventType eventType, User sender, PullRequest eventPullRequest, PullRequestReviewAction reviewAction) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode detailFields = mapper.createArrayNode();
ArrayNode attachments = mapper.createArrayNode();
String requestMessage = "[" + project.name + "] ";
switch (eventType) {
case PULL_REQUEST_REVIEW_STATE_CHANGED:
if (PullRequestReviewAction.DONE.equals(reviewAction)) {
requestMessage += Messages.get(Lang.defaultLang(), "notification.pullrequest.reviewed", sender.name);
} else {
requestMessage += Messages.get(Lang.defaultLang(), "notification.pullrequest.unreviewed", sender.name);;
}
break;
}
requestMessage += " <" + utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(eventPullRequest) + "|#" + eventPullRequest.number + ": " + eventPullRequest.title + ">";
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.sender"), eventPullRequest.contributor.name, false));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.from"), eventPullRequest.fromBranch, true));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "pullRequest.to"), eventPullRequest.toBranch, true));
attachments.add(buildAttachmentJSON(eventPullRequest.body, detailFields));
return Json.stringify(buildRequestJSON(requestMessage, attachments));
}
private String buildRequestBody(EventType eventType, User sender, Issue eventIssue) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode detailFields = mapper.createArrayNode();
ArrayNode attachments = mapper.createArrayNode();
String requestMessage = "[" + project.name + "] "+ sender.name + " ";
switch (eventType) {
case NEW_ISSUE:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.new.issue");
break;
case ISSUE_STATE_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.issue.state.changed");
break;
case ISSUE_ASSIGNEE_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.issue.assignee.changed");
break;
case ISSUE_BODY_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.issue.body.changed");
break;
case ISSUE_MOVED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.issue.moved");
break;
case ISSUE_MILESTONE_CHANGED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.milestone.changed");
break;
default:
play.Logger.warn("Unknown webhook event: " + eventType);
}
requestMessage += " <" + utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(eventIssue) + "|#" + eventIssue.number + ": " + eventIssue.title + ">";
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "notification.type.milestone.changed"), eventIssue.milestoneId().toString(), true));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), ""), eventIssue.assigneeName(), true));
detailFields.add(buildTitleValueJSON(Messages.get(Lang.defaultLang(), "issue.state"), eventIssue.state.toString(), true));
attachments.add(buildAttachmentJSON(eventIssue.body, detailFields));
return Json.stringify(buildRequestJSON(requestMessage, attachments));
}
private String buildRequestBody(EventType eventType, User sender, Comment eventComment) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode attachments = mapper.createArrayNode();
String requestMessage = "[" + project.name + "] "+ sender.name + " ";
switch (eventType) {
case NEW_COMMENT:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.new.comment");
break;
case COMMENT_UPDATED:
requestMessage += Messages.get(Lang.defaultLang(), "notification.type.comment.updated");
break;
}
switch (eventComment.asResource().getType()) {
case ISSUE_COMMENT:
requestMessage += " <" + utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(eventComment) + "|#" + eventComment.getParent().number + ": " + eventComment.getParent().title + ">";
break;
case NONISSUE_COMMENT:
requestMessage += " <" + utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(eventComment) + "|#" + eventComment.getParent().number + ": " + eventComment.getParent().title + ">";
break;
}
attachments.add(buildAttachmentJSON(eventComment.contents, null));
return Json.stringify(buildRequestJSON(requestMessage, attachments));
}
private ObjectNode buildJSONFromCommit(Project project, RevCommit commit) {
GitCommit gitCommit = new GitCommit(commit);
ObjectNode commitJSON = Json.newObject();
ObjectNode authorJSON = Json.newObject();
ObjectNode committerJSON = Json.newObject();
commitJSON.put("id", gitCommit.getFullId());
commitJSON.put("message", gitCommit.getMessage());
commitJSON.put("timestamp",
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").
format(new Date(gitCommit.getCommitTime() * 1000L)));
commitJSON.put("url", utils.Config.getScheme() + "://" + utils.Config.getHostport("localhost:9000") + RouteUtil.getUrl(project) + "/commit/"+gitCommit.getFullId());
authorJSON.put("name", gitCommit.getAuthorName());
authorJSON.put("email", gitCommit.getAuthorEmail());
committerJSON.put("name", gitCommit.getCommitterName());
committerJSON.put("email", gitCommit.getCommitterEmail());
// TODO : Add 'username' property (howto?)
commitJSON.put("author", authorJSON);
commitJSON.put("committer", committerJSON);
// TODO : Add added, removed, modified file list (not supported by JGit?)
return commitJSON;
}
private ObjectNode buildTitleValueJSON(String title, String value, Boolean shorten) {
ObjectNode outputJSON = Json.newObject();
outputJSON.put("title", title);
outputJSON.put("value", value);
outputJSON.put("short", shorten);
return outputJSON;
}
private ObjectNode buildAttachmentJSON(String text, ArrayNode detailFields) {
ObjectNode attachmentsJSON = Json.newObject();
attachmentsJSON.put("text", text);
attachmentsJSON.put("fields", detailFields);
return attachmentsJSON;
}
private ObjectNode buildRequestJSON(String requestMessage, ArrayNode attachments) {
ObjectNode requestBody = Json.newObject();
requestBody.put("text", requestMessage);
requestBody.put("username", "YonaBot");
requestBody.put("attachments", attachments);
return requestBody;
}
private ObjectNode buildSenderJSON(User sender) {
ObjectNode senderJSON = Json.newObject();
senderJSON.put("login", sender.loginId);
senderJSON.put("id", sender.id);
senderJSON.put("avatar_url", sender.avatarUrl());
senderJSON.put("type", "User");
senderJSON.put("site_admin", sender.isSiteManager());
return senderJSON;
}
private ObjectNode buildPusherJSON(User sender) {
ObjectNode pusherJSON = Json.newObject();
pusherJSON.put("name", sender.name);
pusherJSON.put("email", sender.email);
return pusherJSON;
}
private ObjectNode buildRepositoryJSON() {
ObjectNode repositoryJSON = Json.newObject();
repositoryJSON.put("id", project.id);
repositoryJSON.put("name", project.name);
repositoryJSON.put("owner", project.owner);
repositoryJSON.put("html_url", RouteUtil.getUrl(project));
repositoryJSON.put("overview", project.overview); // Description.
repositoryJSON.put("private", project.isPrivate());
return repositoryJSON;
}
/**
* Remove this webhook from a project.
*
* @param projectId ID of the project from which this webhook is removed
*/
public void delete(Long projectId) {
Project targetProject = Project.find.byId(projectId);
targetProject.webhooks.remove(this);
targetProject.update();
super.delete();
}
@Override
public String toString() {
return "Webhook{" +
"id=" + id +
", project=" + project +
", payloadUrl='" + payloadUrl + '\'' +
", secret='" + secret + '\'' +
", gitPushOnly=" + gitPushOnly +
", createdAt=" + createdAt +
'}';
}
}