forked from QasimWani/LeetHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode.js
471 lines (438 loc) · 14.2 KB
/
leetcode.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
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
/* Enum for languages supported by LeetCode. */
const languages = {
Python: '.py',
Python3: '.py',
'C++': '.cpp',
C: '.c',
Java: '.java',
'C#': '.cs',
JavaScript: '.js',
Ruby: '.rb',
Swift: '.swift',
Go: '.go',
Kotlin: '.kt',
Scala: '.scala',
Rust: '.rs',
PHP: '.php',
TypeScript: '.ts',
MySQL: '.sql',
'MS SQL Server': '.sql',
Oracle: '.sql',
};
/* Commit messages */
const readmeMsg = 'Create README - LeetHub';
const discussionMsg = 'Prepend discussion post - LeetHub';
/* Difficulty of most recenty submitted question */
let difficulty = '';
/* Get file extension for submission */
function findLanguage() {
const tag = [
...document.getElementsByClassName(
'ant-select-selection-selected-value',
),
];
if (tag && tag.length > 0) {
for (let i = 0; i < tag.length; i += 1) {
const elem = tag[i].textContent;
if (elem !== undefined && languages[elem] !== undefined) {
return languages[elem]; // should generate respective file extension
}
}
}
return null;
}
/* Main function for uploading code to GitHub repo */
const upload = (token, hook, code, directory, filename, sha, msg) => {
// To validate user, load user object from GitHub.
const URL = `https://api.github.com/repos/${hook}/contents/${directory}/${filename}`;
/* Define Payload */
let data = {
message: msg,
content: code,
sha,
};
data = JSON.stringify(data);
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 201) {
const updatedSha = JSON.parse(xhr.responseText).content.sha; // get updated SHA.
chrome.storage.local.get('stats', (data2) => {
let { stats } = data2;
if (stats === null || stats === {} || stats === undefined) {
// create stats object
stats = {};
stats.solved = 0;
stats.easy = 0;
stats.medium = 0;
stats.hard = 0;
stats.sha = {};
}
const filePath = directory + filename;
// Only increment solved problems statistics once
// New submission commits twice (README and problem)
if (filename === 'README.md' && sha === null) {
stats.solved += 1;
stats.easy += difficulty === 'Easy' ? 1 : 0;
stats.medium += difficulty === 'Medium' ? 1 : 0;
stats.hard += difficulty === 'Hard' ? 1 : 0;
}
stats.sha[filePath] = updatedSha; // update sha key.
chrome.storage.local.set({ stats }, () => {
console.log(
`Successfully committed ${filename} to github`,
);
});
});
}
}
});
xhr.open('PUT', URL, true);
xhr.setRequestHeader('Authorization', `token ${token}`);
xhr.setRequestHeader('Accept', 'application/vnd.github.v3+json');
xhr.send(data);
};
/* Main function for updating code on GitHub Repo */
/* Currently only used for prepending discussion posts to README */
const update = (token, hook, addition, directory, msg, prepend) => {
const URL = `https://api.github.com/repos/${hook}/contents/${directory}/README.md`;
/* Read from existing file on GitHub */
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 201) {
const response = JSON.parse(xhr.responseText);
const existingContent = decodeURIComponent(
escape(atob(response.content)),
);
let newContent = '';
/* Discussion posts prepended at top of README */
/* Future implementations may require appending to bottom of file */
if (prepend) {
newContent = btoa(
unescape(encodeURIComponent(addition + existingContent)),
);
}
/* Write file with new content to GitHub */
upload(
token,
hook,
newContent,
directory,
'README.md',
response.sha,
msg,
);
}
}
});
xhr.open('GET', URL, true);
xhr.setRequestHeader('Authorization', `token ${token}`);
xhr.setRequestHeader('Accept', 'application/vnd.github.v3+json');
xhr.send();
};
function uploadGit(
code,
problemName,
fileName,
msg,
action,
prepend = true,
) {
/* Get necessary payload data */
chrome.storage.local.get('leethub_token', (t) => {
const token = t.leethub_token;
if (token) {
chrome.storage.local.get('mode_type', (m) => {
const mode = m.mode_type;
if (mode === 'commit') {
/* Get hook */
chrome.storage.local.get('leethub_hook', (h) => {
const hook = h.leethub_hook;
if (hook) {
/* Get SHA, if it exists */
/* to get unique key */
const filePath = problemName + fileName;
chrome.storage.local.get('stats', (s) => {
const { stats } = s;
let sha = null;
if (
stats !== undefined &&
stats.sha !== undefined &&
stats.sha[filePath] !== undefined
) {
sha = stats.sha[filePath];
}
if (action === 'upload') {
/* Upload to git. */
upload(
token,
hook,
code,
problemName,
fileName,
sha,
msg,
);
} else if (action === 'update') {
/* Update on git */
update(
token,
hook,
code,
problemName,
msg,
prepend,
);
}
});
}
});
}
});
}
});
}
/* Function for finding and parsing the full code. */
/* - At first find the submission details url. */
/* - Then send a request for the details page. */
/* - Finally, parse the code from the html reponse. */
function findCode(uploadGit, problemName, fileName, msg, action) {
const e = document.getElementsByClassName('status-column__3SUg');
if (e != undefined && e.length > 1) {
/* Get the submission details url from the submission page. */
const submissionRef = e[1].innerHTML.split(' ')[1];
const submissionURL = submissionRef.split('=')[1].slice(1, -1);
/* Request for the submission details page */
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
/* received submission details as html reponse. */
var doc = new DOMParser().parseFromString(
this.responseText,
'text/html',
);
/* the response has a js object called pageData. */
/* Pagedata has the details data with code about that submission */
var scripts = doc.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var text = scripts[i].innerText;
if (text.includes('pageData')) {
/* Considering the pageData as text and extract the sbustring
which has the full code */
var firstIndex = text.indexOf('submissionCode');
var lastIndex = text.indexOf('editCodeUrl');
var sclicedText = text.slice(firstIndex, lastIndex);
/* slicedText has code as like as. (submissionCode: 'Details code'). */
/* So finding the index of first and last single inverted coma. */
var firstInverted = sclicedText.indexOf("'");
var lastInverted = sclicedText.lastIndexOf("'");
/* Extract only the code */
var codeUnicoded = sclicedText.slice(
firstInverted + 1,
lastInverted,
);
/* The code has some unicode. Replacing all unicode with actual characters */
var code = codeUnicoded.replace(
/\\u[\dA-F]{4}/gi,
function (match) {
return String.fromCharCode(
parseInt(match.replace(/\\u/g, ''), 16),
);
},
);
if (code != null) {
setTimeout(function () {
uploadGit(
btoa(unescape(encodeURIComponent(code))),
problemName,
fileName,
msg,
action,
);
}, 2000);
}
}
}
}
};
xhttp.open('GET', `https://leetcode.com${submissionURL}`, true);
xhttp.send();
}
}
/* Main parser function for the code */
function parseCode() {
const e = document.getElementsByClassName('CodeMirror-code');
if (e !== undefined && e.length > 0) {
const elem = e[0];
let parsedCode = '';
const textArr = elem.innerText.split('\n');
for (let i = 1; i < textArr.length; i += 2) {
parsedCode += `${textArr[i]}\n`;
}
return parsedCode;
}
return null;
}
/* Util function to check if an element exists */
function checkElem(elem) {
return elem && elem.length > 0;
}
/* Parser function for the question and tags */
function parseQuestion() {
const questionElem = document.getElementsByClassName(
'content__u3I1 question-content__JfgR',
);
if (!checkElem(questionElem)) {
return null;
}
const qbody = questionElem[0].innerHTML;
// Problem title.
let qtitle = document.getElementsByClassName('css-v3d350');
if (checkElem(qtitle)) {
qtitle = qtitle[0].innerHTML;
} else {
qtitle = 'unknown-problem';
}
// Problem difficulty, each problem difficulty has its own class.
const isHard = document.getElementsByClassName('css-t42afm');
const isMedium = document.getElementsByClassName('css-dcmtd5');
const isEasy = document.getElementsByClassName('css-14oi08n');
if (checkElem(isEasy)) {
difficulty = 'Easy';
} else if (checkElem(isMedium)) {
difficulty = 'Medium';
} else if (checkElem(isHard)) {
difficulty = 'Hard';
}
// Final formatting of the contents of the README for each problem
const markdown = `<h2>${qtitle}</h2><h3>${difficulty}</h3><hr>${qbody}`;
return markdown;
}
/* Parser function for time/space stats */
function parseStats() {
const probStats = document.getElementsByClassName('data__HC-i');
if (!checkElem(probStats)) {
return null;
}
const time = probStats[0].textContent;
const timePercentile = probStats[1].textContent;
const space = probStats[2].textContent;
const spacePercentile = probStats[3].textContent;
// Format commit message
return `Time: ${time} (${timePercentile}), Space: ${space} (${spacePercentile}) - LeetHub`;
}
document.addEventListener('click', (event) => {
const element = event.target;
const oldPath = window.location.pathname;
/* Act on Post button click */
/* Complex since "New" button shares many of the same properties as "Post button */
if (
element.classList.contains('icon__3Su4') ||
element.parentElement.classList.contains('icon__3Su4') ||
element.parentElement.classList.contains(
'btn-content-container__214G',
) ||
element.parentElement.classList.contains('header-right__2UzF')
) {
setTimeout(function () {
/* Only post if post button was clicked and url changed */
if (
oldPath !== window.location.pathname &&
oldPath ===
window.location.pathname.substring(0, oldPath.length) &&
!Number.isNaN(window.location.pathname.charAt(oldPath.length))
) {
const date = new Date();
const currentDate = `${date.getDate()}/${date.getMonth()}/${date.getFullYear()} at ${date.getHours()}:${date.getMinutes()}`;
const addition = `[Discussion Post (created on ${currentDate})](${window.location}) \n`;
const problemName = window.location.pathname.split('/')[2]; // must be true.
uploadGit(
addition,
problemName,
'README.md',
discussionMsg,
'update',
);
}
}, 1000);
}
});
const loader = setInterval(() => {
let code = null;
let probStatement = null;
let probStats = null;
const successTag = document.getElementsByClassName('success__3Ai7');
if (
successTag !== undefined &&
successTag.length > 0 &&
successTag[0].innerText.trim() === 'Success'
) {
probStatement = parseQuestion();
probStats = parseStats();
}
if (probStatement !== null && probStats !== null) {
clearTimeout(loader);
const problemName = window.location.pathname.split('/')[2]; // must be true.
const language = findLanguage();
if (language !== null) {
chrome.storage.local.get('stats', (s) => {
const { stats } = s;
const filePath = problemName + problemName + language;
let sha = null;
if (
stats !== undefined &&
stats.sha !== undefined &&
stats.sha[filePath] !== undefined
) {
sha = stats.sha[filePath];
}
/* Only create README if not already created */
if (sha === null) {
/* @TODO: Change this setTimeout to Promise */
uploadGit(
btoa(unescape(encodeURIComponent(probStatement))),
problemName,
'README.md',
readmeMsg,
'upload',
);
}
});
/* Upload code to Git */
setTimeout(function () {
findCode(
uploadGit,
problemName,
problemName + language,
probStats,
'upload',
); // Encode `code` to base64
}, 2000);
}
}
}, 1000);
/* Sync to local storage */
chrome.storage.local.get('isSync', (data) => {
keys = [
'leethub_token',
'leethub_username',
'pipe_leethub',
'stats',
'mode_type',
'leethub_hook',
'mode_type',
];
if (!data || !data.isSync) {
keys.forEach((key) => {
chrome.storage.sync.get(key, (data) => {
chrome.storage.local.set({ [key]: data[key] });
});
});
chrome.storage.local.set({ isSync: true }, (data) => {
console.log('LeetHub Synced to local values');
});
} else {
console.log('LeetHub Local storage already synced!');
}
});