-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
391 lines (361 loc) · 9.74 KB
/
lib.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
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
const VALID_CONFIG = 10;
const BAD_CONFIG = 11;
const INVALID_TOKEN = 12;
const ALARM_ICON_INDICATOR = "iconIndicator";
const GITHUB_URI = "https://github.com";
let IS_DEBUG_ENABLED = false;
let params = {
owner: undefined,
repository: undefined,
oauthToken: undefined,
labels: undefined
};
/**
* pingAPI will test if user params are ok and disable icon if not
*/
const pingAPI = (success, error) => {
getParameters(config => {
call(
getQuery(config.owner, config.repository),
config.oauthToken,
response => {
if (!response.errors) {
success(VALID_CONFIG);
} else {
error(BAD_CONFIG);
}
},
errorReason => {
log("[pingAPI] error with reason: ", errorReason);
error(errorReason);
}
);
});
};
const getFilteredLabels = callback => {
getParameters(config => {
call(
getQuery(config.owner, config.repository),
config.oauthToken,
response => {
const orderedPRByLabel = orderPRByLabel(response);
const filteredPRByLabel = filterPRByLabel(
config.labels,
orderedPRByLabel
);
log("[getFilteredLabels] filteredPRByLabel: ", filteredPRByLabel);
log(
"[getFilteredLabels] filteredPRByLabel.length: ",
filteredPRByLabel.length
);
// if no object found
!filteredPRByLabel.length
? callback(null)
: callback(filteredPRByLabel);
},
errorReason => {
log("[getFilteredLabels] error with reason: ", errorReason);
callback(errorReason);
}
);
});
};
const updateIconIndicator = () => {
getParameters(config => {
call(
getQuery(config.owner, config.repository),
config.oauthToken,
response => {
log("[updateIconIndicator] success with response: ", response);
const orderedPRByLabel = orderPRByLabel(response);
const filteredPRByLabel = filterPRByLabel(
config.labels,
orderedPRByLabel
);
// if no object found
if (!filteredPRByLabel.length) {
return;
}
const topLabel = filteredPRByLabel[0];
chrome.browserAction.setBadgeText({
text: topLabel.pullRequests.length.toString()
});
chrome.browserAction.setBadgeBackgroundColor({
color: "#" + topLabel.color
});
},
errorReason => {
log("[updateIconIndicator] error with reason: ", errorReason);
}
);
});
};
/**
* getFilteredLabels is used to format data by regrouping PR name by labels and
* sorting by Pull Request number
*
* labels: [
* {
* name: string,
* color: string,
* pullRequests: [
* {
* title: string,
* url: string,
* reviews: [
* author: string,
* state: string,
* ],
* }
* ]
* }
* ]
*/
const orderPRByLabel = data => {
let orderedPRByLabel = [];
// loop over each PR
data.data.repository.pullRequests.nodes.forEach(pr => {
const currentPullRequest = {
id: pr.id,
title: pr.title,
url: pr.url,
author: pr.author,
reviews: pr.reviews.nodes.map(review => {
return {
author: review.author.login,
state: review.state
};
})
};
// loop over each labels
pr.labels.nodes.forEach(label => {
const foundLabelId = orderedPRByLabel.findIndex(
el => label.name === el.name
);
foundLabelId > -1
? orderedPRByLabel[foundLabelId].pullRequests.push(currentPullRequest)
: orderedPRByLabel.push({
name: label.name,
color: label.color,
url: getLabelUrl(label.name),
pullRequests: [currentPullRequest]
});
});
});
// sorting by pull request number
orderedPRByLabel = orderedPRByLabel.sort(
(a, b) => b.pullRequests.length - a.pullRequests.length
);
return orderedPRByLabel;
};
/**
* filterPRByLabel will return data for watched labels
*/
const filterPRByLabel = (watchedLabels, sortedLabels) => {
const arrayLabels = watchedLabels
.split(",")
.map(label => label.trim().toLowerCase());
const filteredLabels = sortedLabels.filter(sortedLabel =>
arrayLabels.includes(sortedLabel.name.toLowerCase())
);
// saving data in local storage
saveData(filteredLabels, status => {
log("[filterPRByLabel] data saved with status: ", status);
});
return filteredLabels;
};
const getQuery = (owner, repository) => {
return `{
repository(owner:"${owner}", name:"${repository}") {
pullRequests(first: 100, states: OPEN) {
nodes {
id
title
url
author {
login
avatarUrl
}
labels(last: 10) {
nodes {
name
color
}
}
reviews(last: 10, states: APPROVED) {
nodes {
author {
login
}
state
}
}
}
}
}
}`;
};
const getRateLimitQuery = () => `query {
viewer {
login
}
rateLimit {
limit
cost
remaining
resetAt
}
}`;
const githubMock = JSON.parse(`
[{"name":"need QA validation","color":"cc317c","pullRequests":[{"id":"MDExOlB1bGxSZXF1ZXN0MTYxMTU2Mzk5","title":"[POC] Veery SDK","url":"https://github.com/CanalTP/ADM/pull/594","reviews":[{"author":"staifn","state":"APPROVED"},{"author":"jbcrestot","state":"APPROVED"},{"author":"MoOx","state":"APPROVED"}]},{"id":"MDExOlB1bGxSZXF1ZXN0MTYyOTkwNjk2","title":"Rcu 778 center button","url":"https://github.com/CanalTP/ADM/pull/615","reviews":[{"author":"MoOx","state":"APPROVED"},{"author":"staifn","state":"APPROVED"},{"author":"VincentCATILLON","state":"APPROVED"},{"author":"jbcrestot","state":"APPROVED"}]}]},{"name":"need reviews","color":"fbca04","pullRequests":[{"id":"MDExOlB1bGxSZXF1ZXN0MTY0MDMwNDQx","title":"RCU-866 track events with a minimal edit in files","url":"https://github.com/CanalTP/ADM/pull/626","reviews":[{"author":"staifn","state":"APPROVED"}]},
{"id":"MDExOlB1bGxSZXF1ZXN0MTY0MDMwNDQjb","title":"RCU-866 track events with a minimal edit in files","url":"https://github.com/CanalTP/ADM/pull/626","reviews":[{"author":"staifn","state":"APPROVED"}]}
]}]
`);
const call = (query, token, success, error) => {
const url = "https://api.github.com/graphql";
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status === 200) {
log("[call] success with response: ", xhr.response);
success(xhr.response);
} else {
log(
`[call] fail with state: ${xhr.readyState}, status: ${
xhr.status
}, response: ${xhr.response}`
);
// probably bad token
error(INVALID_TOKEN);
}
} else {
// here are the not done state, if need to debug
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.timeout = 5000;
xhr.send(JSON.stringify({ query: query }));
};
const saveData = (data, callback) => {
chrome.storage.sync.set(
{
data: data
},
() => {
log("[saveData] saving data: ", data);
callback("ok");
}
);
};
const getData = callback => {
chrome.storage.sync.get(
{
data: ""
},
items => {
log("[getData] retrieved data: ", items.data);
callback(items.data);
}
);
};
const clearData = () => {
chrome.storage.sync.clear(() => {
log("[clearData] data have been cleared");
});
};
const addPullRequestToNotificationStack = (pullRequest, callback) => {
log("[addPullRequestToNotificationStack] incoming - pr: ", pullRequest);
chrome.storage.sync.get(
{
notifs: []
},
items => {
log("[addPullRequestToNotificationStack] getData notifs: ", items.notifs);
items.notifs.push(pullRequest);
// save
chrome.storage.sync.set(
{
notifs: items.notifs
},
() => {
log(
"[addPullRequestToNotificationStack] saving notifs: ",
items.notifs
);
callback && callback("ok");
}
);
}
);
};
/**
* Return the next notification data to display
*/
const getNextNotif = callback => {
log("[getNextNotif] incoming - cb: ", callback);
chrome.storage.sync.get(
{
notifs: []
},
items => {
log("[getNextNotif] getData notifs: ", items.notifs);
const firstPullRequest = items.notifs.shift();
// now we save back the notifications
chrome.storage.sync.set(
{
notifs: items.notifs
},
() => {
log("[getNextNotif] saving notifs: ", items.notifs);
}
);
callback && callback(firstPullRequest);
}
);
};
const getParameters = callback => {
chrome.storage.sync.get(
{
labels: "",
owner: "",
repository: "",
oauthToken: "",
debug: ""
},
items => {
params = { ...params, ...items };
IS_DEBUG_ENABLED = items.debug;
callback(params);
}
);
};
const log = function() {
if (!params.oauthToken) {
getParameters(config => log(...arguments));
return;
}
if (IS_DEBUG_ENABLED) {
console.log(...arguments);
}
};
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x)
});
const getLabelUrl = labelName =>
Box(labelName)
.map(encodeURI)
.fold(encodedLabel =>
GITHUB_URI.concat(
"/",
params.owner,
"/",
params.repository,
"/pulls?q=is%3Apr+is%3Aopen+label%3A%22",
encodedLabel,
"%22"
)
);