-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver.js
97 lines (82 loc) · 2.66 KB
/
server.js
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
// External dependencies
const fs = require("fs")
const yaml = require("js-yaml")
const express = require("express")
const { createWebhooksApi } = require("@octokit/webhooks")
const { createAppAuth } = require("@octokit/auth-app")
const { graphql } = require("@octokit/graphql")
// Local dependencies
const smeeClient = require("./smee")
const emojify = require("./emojify")
const hasCommand = require("./command")
const updateBodyMutationFor = require("./mutations")
// Setup
const port = 64897
const app = express()
const privateKey = fs.readFileSync("gh-app.pem", "utf8")
const config = require('../config.json')
var emojifierConfig = yaml.safeLoad(fs.readFileSync("emojifier-default.yml", "utf8"))
const smee = smeeClient(config.webproxy_url, port)
smee.start()
const webhooks = new createWebhooksApi({ secret: "mysecret", path: "/webhooks" })
app.use(webhooks.middleware)
// App
webhooks.on(["issue_comment.created", "issues.opened", "pull_request.opened"], async (event) => {
const { payload } = event
const auth = createAppAuth({
id: config.github_app_id,
privateKey: privateKey,
installationId: payload.installation.id
})
const { token } = await auth({ type: "installation" });
const graphqlWithAuth = graphql.defaults({
headers: {
authorization: `token ${token}`
}
})
const { comment, issue, pullRequest } = payload
const body = (comment || issue || pullRequest).body
const nodeId = (comment || issue || pullRequest).node_id
const getEmojifierConfig = `
query($repoName:String!, $repoOwner:String!) {
repository(name: $repoName, owner: $repoOwner) {
object(expression: "master:.emojifier.yml") {
... on Blob {
text
}
}
}
}
`
try {
const queryResponse = await graphqlWithAuth(getEmojifierConfig, {
repoName: payload.repository.name,
repoOwner: payload.repository.owner.login
})
if (queryResponse.repository.object != null) {
emojifierConfig = yaml.safeLoad(queryResponse.repository.object.text)
}
} catch (e) {
console.log(e)
}
if (hasCommand("emojify", body)) {
const newBody = emojify(body, emojifierConfig.editMode, emojifierConfig.emojiLimit)
try {
await graphqlWithAuth(updateBodyMutationFor(event.name), {
newBody: newBody,
id: nodeId
})
return
} catch (err) {
console.log(err)
}
} else {
console.log("Command not found in body")
}
})
webhooks.on("error", (error) => {
console.log(`Error occured in "${error.event.name} handler: ${error.stack}"`)
})
const listener = app.listen(port, () => {
console.log("Your app is listening on port " + listener.address().port)
})