-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
270 lines (234 loc) · 7.26 KB
/
index.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
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
import { Octokit } from '@octokit/rest'
import { Buffer } from 'buffer'
const octokit = new Octokit({ auth: ACCESS_TOKEN })
const corsHeaders = {
'Access-Control-Allow-Origin': ORIGIN,
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
addEventListener('fetch', event => {
event.respondWith(handle(event.request))
})
// cors handling based on: https://developers.cloudflare.com/workers/examples/cors-header-proxy
async function handle(request) {
if (request.method === 'OPTIONS') {
return handleOptions(request)
} else if (request.method === 'POST') {
return handleRequest(request)
} else {
return new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
})
}
}
/**
* Handles OPTIONS requests.
* @param {Request} request
*/
function handleOptions(request) {
const { headers } = request
if (
headers.get('Origin') !== null &&
headers.get('Access-Control-Request-Method') !== null &&
headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
Allow: 'POST, OPTIONS',
},
})
}
}
/**
* Makes POST request to GitHub API to create a PR and returns the url of the PR.
* @param {Request} request
*/
async function handleRequest(request) {
if (request.headers.get('Content-Type') !== 'application/json') {
return new Response(null, {
status: 415,
statusText: 'Unsupported Media Type',
headers: corsHeaders,
})
}
// Detect parse failures by setting `json` to null.
const json = await request.json().catch(e => null)
if (json === null) {
return new Response('JSON parse failure', {
status: 400,
statusText: 'Bad Request',
headers: corsHeaders,
})
}
// verify reCAPTCHA token
const { success, errors } = await verifyToken(json.recaptcha.token)
// return error response if reCAPTCHA token is invalid
if (!success) {
return new Response(JSON.stringify({ errors }), {
status: 400,
statusText: 'Bad Request',
headers: corsHeaders,
})
}
// create yaml string for the course review and PR body
const { course, user, review, reference, difficulty, quality, sessionTaken, email } = json.details
const title = `New review for ${course} by ${user}`
let body = `> ${review}\n>\n`
const parsedDifficulty = parseFloat(difficulty)
let clampedDifficulty = 0
if (!isNaN(parsedDifficulty)) {
clampedDifficulty = Math.min(Math.max(1, parsedDifficulty), 5)
body += `> Difficulty: ${clampedDifficulty}/5\n`
}
const parsedQuality = parseFloat(quality)
let clampedQuality = 0
if (!isNaN(parsedQuality)) {
clampedQuality = Math.min(Math.max(1, parsedQuality), 5)
body += `> Quality: ${clampedQuality}/5\n`
}
body += `> <cite><a href='${reference}'>${user}</a>, ${new Date()
.toDateString()
.split(' ')
.slice(1)
.join(' ')}, course taken during ${sessionTaken}</cite>`
let yaml = ` - author: ${user}\n authorLink: ${reference}\n date: ${new Date().getUTCFullYear()}-${(
new Date().getUTCMonth() + 1
)
.toString()
.padStart(2, '0')}-${new Date()
.getUTCDate()
.toString()
.padStart(2, '0')}\n review: |\n ${review.replaceAll('\n', '\n ')}`
if (clampedDifficulty) {
yaml += `\n difficulty: ${clampedDifficulty}`
}
if (clampedQuality) {
yaml += `\n quality: ${clampedQuality}`
}
yaml += `\n sessionTaken: ${sessionTaken}\n`
body += `\n<details><summary>View YAML for new review</summary>\n<pre>\n${yaml}\n<\pre>\n</details>`
if (email) {
body += `\n<details><summary>View raffle email</summary>\n${email}\nRemember to edit this out (… > 'Edit') after processing the review.\n</details>`
}
body = body + 'This is an auto-generated PR made using: https://github.com/ubccsss/course-review-worker\n'
try {
// new branch name for the PR
const newBranchName = `new-review-${Date.now()}`
// get ref for base branch
const baseBranchRef = await octokit.git.getRef({
owner: OWNER,
repo: REPO,
ref: `heads/${BASE_BRANCH}`,
})
// hash of last commit on base branch
const lastCommitSha = baseBranchRef.data.object.sha
// make a new branch from last commit on base branch
await octokit.rest.git.createRef({
owner: OWNER,
repo: REPO,
ref: `refs/heads/${newBranchName}`,
sha: lastCommitSha,
})
let fileSha = {}
try {
// get the file contents for the course review file
const existingReviews = await octokit.rest.repos.getContent({
owner: OWNER,
repo: REPO,
path: `data/courseReviews/${course.toLowerCase().replace(' ', '-')}.yaml`,
ref: `refs/heads/${newBranchName}`,
})
// if the file exists, we need to update it and to do that we need to get the sha of the file
fileSha = { sha: existingReviews.data.sha }
// if the file exists, we will append the new review to the existing reviews
// otherwise, we will create a new file with the new review
const existingReviewsContent = Buffer.from(existingReviews.data.content, 'base64')
.toString()
.replace('reviews:\n', '')
yaml = 'reviews:\n' + yaml + existingReviewsContent
} catch (e) {
// if the file doesn't exist, we will create a new file with the new review
yaml = 'reviews:\n' + yaml
}
// update or create the yaml file with the new review
await octokit.rest.repos.createOrUpdateFileContents({
owner: OWNER,
repo: REPO,
path: `data/courseReviews/${course.toLowerCase().replace(' ', '-')}.yaml`,
branch: newBranchName,
message: `Added new review for ${course}`,
content: Buffer.from(yaml).toString('base64'),
...fileSha,
})
// make a PR to merge the new branch into the base branch
const newPR = await octokit.rest.pulls.create({
owner: OWNER,
repo: REPO,
title: title,
body: body,
head: newBranchName,
base: BASE_BRANCH,
})
// add label to PR
await octokit.rest.issues.addLabels({
owner: OWNER,
repo: REPO,
issue_number: newPR.data.number,
labels: LABELS.split(','),
})
if (TEAMS.split(',').length != 0) {
// request a review from the reviewers
await octokit.rest.pulls.requestReviewers({
owner: OWNER,
repo: REPO,
pull_number: newPR.data.number,
reviewers: USERS.split(','),
team_reviewers: TEAMS.split(','),
})
}
// return the url of the new PR
return new Response(JSON.stringify({ url: newPR.data.html_url }), {
headers: {
status: 201,
statusText: 'Created',
'Content-Type': 'application/json',
...corsHeaders,
},
})
} catch (error) {
console.error(error.message)
return new Response(JSON.stringify(error), {
status: 500,
statusText: 'Internal Server Error',
'Content-Type': 'application/json',
...corsHeaders,
})
}
}
/**
* Verifies the reCAPTCHA token with Google.
* @param {string} token
*/
async function verifyToken(token) {
try {
// add URL params
const url = new URL('https://www.google.com/recaptcha/api/siteverify')
url.searchParams.append('secret', RECAPTCHA_SECRET_KEY)
url.searchParams.append('response', token)
// return verification result
const response = await fetch(url, {
method: 'POST',
})
const json = await response.json()
return { success: json.success, errors: json['error-codes'] }
} catch (e) {
return { success: false, errors: ['JSON parse failure'] }
}
}