-
Notifications
You must be signed in to change notification settings - Fork 59
/
leetcode.js
1078 lines (984 loc) · 35.7 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Enum for languages supported by LeetCode. */
const languages = {
C: '.c',
'C++': '.cpp',
'C#': '.cs',
Dart: '.dart',
Elixir: '.ex',
Erlang: '.erl',
Go: '.go',
Java: '.java',
JavaScript: '.js',
Javascript: '.js',
Kotlin: '.kt',
MySQL: '.sql',
'MS SQL Server': '.sql',
Oracle: '.sql',
PHP: '.php',
Python: '.py',
Python3: '.py',
Racket: '.rkt',
Ruby: '.rb',
Rust: '.rs',
Scala: '.scala',
Swift: '.swift',
TypeScript: '.ts',
}
/* Commit messages */
const readmeMsg = 'Create README - LeetHub';
const discussionMsg = 'Prepend discussion post - LeetHub';
const createNotesMsg = 'Attach NOTES - LeetHub';
// problem types
const NORMAL_PROBLEM = 0;
const EXPLORE_SECTION_PROBLEM = 1;
/* Difficulty of most recenty submitted question */
let difficulty = '';
/* state of upload for progress */
let uploadState = { uploading: false };
/* Main function for uploading code to GitHub repo, and callback cb is called if success */
const upload = (token, hook, code, problem, filename, sha, commitMsg, cb = undefined) => {
const URL = `https://api.github.com/repos/${hook}/contents/${problem}/${filename}`;
/* Define Payload */
let data = {
message: commitMsg,
content: code,
sha,
};
data = JSON.stringify(data);
let options = {
method: 'PUT',
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
},
body: data,
};
let updatedSha;
return fetch(URL, options)
.then(res => {
if (res.status === 200 || res.status === 201) {
return res.json();
} else if (res.status === 409) {
throw new Error('409');
}
})
.then(async body => {
updatedSha = body.content.sha; // get updated SHA.
stats = await getAndInitializeStats(problem);
stats.shas[problem][filename] = updatedSha;
return chrome.storage.local.set({ stats });
})
.then(() => {
console.log(`Successfully committed ${filename} to github`);
if (cb != undefined) {
cb();
}
});
};
const getAndInitializeStats = problem => {
return chrome.storage.local.get('stats').then(({ stats }) => {
if (stats == null || stats === {}) {
// create stats object
stats = {};
stats.solved = 0;
stats.easy = 0;
stats.medium = 0;
stats.hard = 0;
stats.shas = {};
}
if (stats.shas[problem] == null) {
stats.shas[problem] = {};
}
return stats;
});
};
const incrementStats = () => {
return chrome.storage.local.get('stats').then(({ stats }) => {
stats.solved += 1;
stats.easy += difficulty === 'Easy' ? 1 : 0;
stats.medium += difficulty === 'Medium' ? 1 : 0;
stats.hard += difficulty === 'Hard' ? 1 : 0;
return chrome.storage.local.set({ stats });
});
};
const checkAlreadyCompleted = problemName => {
return chrome.storage.local.get('stats').then(({ stats }) => {
if (stats?.shas?.[problemName] == null) {
return false;
}
return true;
});
};
/* Main function for updating code on GitHub Repo */
/* Read from existing file on GitHub */
/* Discussion posts prepended at top of README */
/* Future implementations may require appending to bottom of file */
const update = (
token,
hook,
addition,
directory,
filename,
commitMsg,
shouldPreprendDiscussionPosts,
cb = undefined,
) => {
let responseSHA;
return getUpdatedData(token, hook, directory, filename)
.then(data => {
responseSHA = data.sha;
return decodeURIComponent(escape(atob(data.content)));
})
.then(existingContent =>
shouldPreprendDiscussionPosts
? // https://web.archive.org/web/20190623091645/https://monsur.hossa.in/2012/07/20/utf-8-in-javascript.html
// In order to preserve mutation of the data, we have to encode it, which is usually done in base64.
// But btoa only accepts ASCII 7 bit chars (0-127) while Javascript uses 16-bit minimum chars (0-65535).
// EncodeURIComponent converts the Unicode Points UTF-8 bits to hex UTF-8.
// Unescape converts percent-encoded hex values into regular ASCII (optional; it shrinks string size).
// btoa converts ASCII to base64.
btoa(unescape(encodeURIComponent(addition + existingContent)))
: btoa(unescape(encodeURIComponent(existingContent))),
)
.then(newContent =>
upload(token, hook, newContent, directory, filename, responseSHA, commitMsg, cb),
);
};
function uploadGit(
code,
problemName,
fileName,
commitMsg,
action,
shouldPrependDiscussionPosts = false,
cb = undefined,
_diff = undefined,
) {
// Assign difficulty
if (_diff && _diff !== undefined) {
difficulty = _diff.trim();
}
let token;
let hook;
return chrome.storage.local
.get('leethub_token')
.then(({ leethub_token }) => {
token = leethub_token;
if (leethub_token == undefined) {
throw new Error('leethub token is undefined');
}
return chrome.storage.local.get('mode_type');
})
.then(({ mode_type }) => {
if (mode_type !== 'commit') {
throw new Error('leethub mode is not commit');
}
return chrome.storage.local.get('leethub_hook');
})
.then(({ leethub_hook }) => {
hook = leethub_hook;
if (!hook) {
throw new Error('leethub hook not defined');
}
return chrome.storage.local.get('stats');
})
.then(({ stats }) => {
if (action === 'upload') {
/* Get SHA, if it exists */
const sha =
stats?.shas?.[problemName]?.[fileName] !== undefined
? stats.shas[problemName][fileName]
: '';
return upload(token, hook, code, problemName, fileName, sha, commitMsg, cb);
} else if (action === 'update') {
return update(
token,
hook,
code,
problemName,
fileName,
commitMsg,
shouldPrependDiscussionPosts,
cb,
);
}
})
.catch(err => {
if (err.message === '409') {
return getUpdatedData(token, hook, problemName, fileName);
} else {
throw err;
}
})
.then(data =>
data != null
? upload(token, hook, code, problemName, fileName, data.sha, commitMsg, cb)
: undefined,
);
}
/* Gets updated GitHub data for the specific file in repo in question */
async function getUpdatedData(token, hook, directory, filename) {
const URL = `https://api.github.com/repos/${hook}/contents/${directory}/${filename}`;
let options = {
method: 'GET',
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
},
};
return fetch(URL, options).then(res => {
if (res.status === 200 || res.status === 201) {
return res.json();
} else {
throw new Error('' + res.status);
}
});
}
/* Checks if an elem/array exists and has length */
function checkElem(elem) {
return elem && elem.length > 0;
}
function convertToSlug(string) {
const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;';
const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------';
const p = new RegExp(a.split('').join('|'), 'g');
return string
.toString()
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word characters
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
function addLeadingZeros(title) {
const maxTitlePrefixLength = 4;
var len = title.split('-')[0].length;
if (len < maxTitlePrefixLength) {
return '0'.repeat(4 - len) + title;
}
return title;
}
function formatStats(time, timePercentile, space, spacePercentile) {
return `Time: ${time} (${timePercentile}%), Space: ${space} (${spacePercentile}%) - LeetHub`;
}
/* Discussion Link - When a user makes a new post, the link is prepended to the README for that problem.*/
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 != null && (
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', true);
}
}, 1000);
}
});
function LeetCodeV1() {
this.progressSpinnerElementId = 'leethub_progress_elem';
this.progressSpinnerElementClass = 'leethub_progress';
this.injectSpinnerStyle();
}
LeetCodeV1.prototype.init = async function () { };
/* Function for finding and parsing the full code. */
/* - At first find the submission details url. */
/* - Then send a request for the details page. */
/* - Parse the code from the html reponse. */
/* - Parse the stats from the html response (explore section) */
LeetCodeV1.prototype.findAndUploadCode = function (
problemName,
fileName,
commitMsg,
action,
cb = undefined,
) {
/* Get the submission details url from the submission page. */
let submissionURL;
const e = document.getElementsByClassName('status-column__3SUg');
if (checkElem(e)) {
// for normal problem submisson
const submissionRef = e[1].innerHTML.split(' ')[1];
submissionURL = 'https://leetcode.com' + submissionRef.split('=')[1].slice(1, -1);
} else {
// for a submission in explore section
const submissionRef = document.getElementById('result-state');
submissionURL = submissionRef.href;
}
if (submissionURL == undefined) {
return;
}
/* Request for the submission details page */
return fetch(submissionURL)
.then(res => {
if (res.status == 200) {
return res.text();
} else {
throw new Error('' + res.status);
}
})
.then(responseText => {
const doc = new DOMParser().parseFromString(responseText, 'text/html');
/* the response has a js object called pageData. */
/* Pagedata has the details data with code about that submission */
const scripts = doc.getElementsByTagName('script');
for (let i = 0; i < scripts.length; i++) {
const text = scripts[i].innerText;
if (text.includes('pageData')) {
/* Extract the full code */
const firstIndex = text.indexOf('submissionCode');
const lastIndex = text.indexOf('editCodeUrl');
let slicedText = text.slice(firstIndex, lastIndex);
/* slicedText has form "submissionCode: 'Details code'" */
/* Find the index of first and last single inverted coma. */
const firstInverted = slicedText.indexOf("'");
const lastInverted = slicedText.lastIndexOf("'");
/* Extract only the code */
const codeUnicoded = slicedText.slice(firstInverted + 1, lastInverted);
/* The code has some unicode. Replacing all unicode with actual characters */
const code = codeUnicoded.replace(/\\u[\dA-F]{4}/gi, function (match) {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
});
/* For a submission in explore section we do not get probStat beforehand.
So, parse statistics from submisson page */
if (!commitMsg) {
slicedText = text.slice(text.indexOf('runtime'), text.indexOf('memory'));
const resultRuntime = slicedText.slice(
slicedText.indexOf("'") + 1,
slicedText.lastIndexOf("'"),
);
slicedText = text.slice(text.indexOf('memory'), text.indexOf('total_correct'));
const resultMemory = slicedText.slice(
slicedText.indexOf("'") + 1,
slicedText.lastIndexOf("'"),
);
commitMsg = `Time: ${resultRuntime}, Memory: ${resultMemory} - LeetHub`;
}
if (code != null) {
return uploadGit(
btoa(unescape(encodeURIComponent(code))),
problemName,
fileName,
commitMsg,
action,
false,
cb,
);
}
}
}
});
};
// Returns the language extension
LeetCodeV1.prototype.getLanguageExtension = function () {
const tag = [
...document.getElementsByClassName('ant-select-selection-selected-value'),
...document.getElementsByClassName('Select-value-label'),
];
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];
}
}
}
return null;
};
/* function to get the notes if there is any
the note should be opened atleast once for this to work
this is because the dom is populated after data is fetched by opening the note */
LeetCodeV1.prototype.getNotesIfAny = function () {
// there are no notes on expore
if (document.URL.startsWith('https://leetcode.com/explore/')) return '';
notes = '';
if (
checkElem(document.getElementsByClassName('notewrap__eHkN')) &&
checkElem(
document
.getElementsByClassName('notewrap__eHkN')[0]
.getElementsByClassName('CodeMirror-code'),
)
) {
notesdiv = document
.getElementsByClassName('notewrap__eHkN')[0]
.getElementsByClassName('CodeMirror-code')[0];
if (notesdiv) {
for (i = 0; i < notesdiv.childNodes.length; i++) {
if (notesdiv.childNodes[i].childNodes.length == 0) continue;
text = notesdiv.childNodes[i].childNodes[0].innerText;
if (text) {
notes = `${notes}\n${text.trim()}`.trim();
}
}
}
}
return notes.trim();
};
// Returns a slugged num+title variation e.g. 0001-two-sum
LeetCodeV1.prototype.getProblemNameSlug = function () {
const questionElem = document.getElementsByClassName('content__u3I1 question-content__JfgR');
const questionDescriptionElem = document.getElementsByClassName('question-description__3U1T');
let questionTitle = 'unknown-problem';
if (checkElem(questionElem)) {
let qtitle = document.getElementsByClassName('css-v3d350');
if (checkElem(qtitle)) {
questionTitle = qtitle[0].innerHTML;
}
} else if (checkElem(questionDescriptionElem)) {
let qtitle = document.getElementsByClassName('question-title');
if (checkElem(qtitle)) {
questionTitle = qtitle[0].innerText;
}
}
return addLeadingZeros(convertToSlug(questionTitle));
};
/* Gets the success state of the solution and updates html elements with new classes */
LeetCodeV1.prototype.getSuccessStateAndUpdate = function () {
const successTag = document.getElementsByClassName('success__3Ai7');
const resultState = document.getElementById('result-state');
// check success state for a normal problem
if (
checkElem(successTag) &&
successTag[0].className === 'success__3Ai7' &&
successTag[0].innerText.trim() === 'Success'
) {
console.log(successTag[0]);
successTag[0].classList.add('marked_as_success');
return true;
}
// check success state for a explore section problem
else if (
resultState &&
resultState.className === 'text-success' &&
resultState.innerText === 'Accepted'
) {
resultState.classList.add('marked_as_success');
return true;
}
return false;
};
/* Parser function for time/space stats */
LeetCodeV1.prototype.parseStats = function () {
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;
return `Time: ${time} (${timePercentile}), Space: ${space} (${spacePercentile}) - LeetHub`;
};
/* Parser function for the question, question title, question difficulty, and tags */
LeetCodeV1.prototype.parseQuestion = function () {
let questionUrl = window.location.href;
if (questionUrl.endsWith('/submissions/')) {
questionUrl = questionUrl.substring(0, questionUrl.lastIndexOf('/submissions/') + 1);
}
const questionElem = document.getElementsByClassName('content__u3I1 question-content__JfgR');
const questionDescriptionElem = document.getElementsByClassName('question-description__3U1T');
if (checkElem(questionElem)) {
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><a href="${questionUrl}">${qtitle}</a></h2><h3>${difficulty}</h3><hr>${qbody}`;
return markdown;
} else if (checkElem(questionDescriptionElem)) {
let questionTitle = document.getElementsByClassName('question-title');
if (checkElem(questionTitle)) {
questionTitle = questionTitle[0].innerText;
} else {
questionTitle = 'unknown-problem';
}
const questionBody = questionDescriptionElem[0].innerHTML;
const markdown = `<h2>${questionTitle}</h2><hr>${questionBody}`;
return markdown;
}
};
/* Injects a spinner on left side to the "Run Code" button */
LeetCodeV1.prototype.startSpinner = function () {
try {
elem = document.getElementById('leethub_progress_anchor_element');
if (!elem) {
elem = document.createElement('span');
elem.id = 'leethub_progress_anchor_element';
elem.style = 'margin-right: 20px;padding-top: 2px;';
}
elem.innerHTML = `<div id="${this.progressSpinnerElementId}" class="${this.progressSpinnerElementClass}"></div>`;
target = this.insertToAnchorElement(elem);
uploadState.uploading = true;
} catch (error) {
console.log(error);
}
};
/* Injects css style required for the upload progress indicator */
LeetCodeV1.prototype.injectSpinnerStyle = function () {
const style = document.createElement('style');
style.textContent = `.${this.progressSpinnerElementClass} {pointer-events: none;width: 2.0em;height: 2.0em;border: 0.4em solid transparent;border-color: #eee;border-top-color: #3E67EC;border-radius: 50%;animation: loadingspin 1s linear infinite;} @keyframes loadingspin { 100% { transform: rotate(360deg) }}`;
document.head.append(style);
};
/* Inserts an anchor element that is specific to the page you are on (e.g. Explore) */
LeetCodeV1.prototype.insertToAnchorElement = function (elem) {
if (document.URL.startsWith('https://leetcode.com/explore/')) {
action = document.getElementsByClassName('action');
if (
checkElem(action) &&
checkElem(action[0].getElementsByClassName('row')) &&
checkElem(action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6')) &&
action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6').length > 1
) {
target = action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6')[1];
elem.className = 'pull-left';
if (target.childNodes.length > 0) target.childNodes[0].prepend(elem);
}
} else {
if (checkElem(document.getElementsByClassName('action__38Xc'))) {
target = document.getElementsByClassName('action__38Xc')[0];
elem.className = 'runcode-wrapper__8rXm';
if (target.childNodes.length > 0) target.childNodes[0].prepend(elem);
}
}
};
/* Creates a ✔️ tick mark before "Run Code" button signaling LeetHub has done its job */
LeetCodeV1.prototype.markUploaded = function () {
elem = document.getElementById(this.progressSpinnerElementId);
if (elem) {
elem.className = '';
style =
'display: inline-block;transform: rotate(45deg);height:24px;width:12px;border-bottom:7px solid #78b13f;border-right:7px solid #78b13f;';
elem.style = style;
}
};
/* Creates a ❌ failed tick mark before "Run Code" button signaling that upload failed */
LeetCodeV1.prototype.markUploadFailed = function () {
elem = document.getElementById(this.progressSpinnerElementId);
if (elem) {
elem.className = '';
style =
'display: inline-block;transform: rotate(45deg);height:24px;width:12px;border-bottom:7px solid red;border-right:7px solid red;';
elem.style = style;
}
};
function LeetCodeV2() {
this.submissionData;
this.progressSpinnerElementId = 'leethub_progress_elem';
this.progressSpinnerElementClass = 'leethub_progress';
this.injectSpinnerStyle();
}
LeetCodeV2.prototype.init = async function () {
async function getSubmissionId() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const submissionsId = document.URL.match(/\/(\d+)(\/|\?|$)/);
if (submissionsId !== null){
resolve(submissionsId[1]); // '/problems/two-sum/post-solution?submissionId/999594717
}}, 4000);
});
}
const submissionId = await getSubmissionId();
// Query for getting the solution runtime and memory stats, the code, the coding language, the question id, question title and question difficulty
const submissionDetailsQuery = {
query:
'\n query submissionDetails($submissionId: Int!) {\n submissionDetails(submissionId: $submissionId) {\n runtime\n runtimeDisplay\n runtimePercentile\n runtimeDistribution\n memory\n memoryDisplay\n memoryPercentile\n memoryDistribution\n code\n timestamp\n statusCode\n lang {\n name\n verboseName\n }\n question {\n questionId\n title\n titleSlug\n content\n difficulty\n }\n notes\n topicTags {\n tagId\n slug\n name\n }\n runtimeError\n }\n}\n ',
variables: { submissionId: submissionId },
operationName: 'submissionDetails',
};
const options = {
method: 'POST',
headers: {
cookie: document.cookie, // required to authorize the API request
'content-type': 'application/json',
},
body: JSON.stringify(submissionDetailsQuery),
};
const data = await fetch('https://leetcode.com/graphql/', options)
.then(res => res.json())
.then(res => res.data.submissionDetails);
this.submissionData = data;
};
LeetCodeV2.prototype.findAndUploadCode = function (
problemName,
fileName,
commitMsg,
action,
cb = undefined,
) {
const code = this.getCode();
if (!code) {
throw new Error('No solution code found');
}
return uploadGit(
btoa(unescape(encodeURIComponent(code))),
problemName,
fileName,
commitMsg,
action,
false,
cb,
);
};
LeetCodeV2.prototype.getCode = function () {
if (this.submissionData != null) {
return this.submissionData.code;
}
const code = document.getElementsByTagName('code');
if (!checkElem(code)) {
return null;
}
return code[0].innerText;
};
LeetCodeV2.prototype.getLanguageExtension = function () {
if (this.submissionData != null) {
return languages[this.submissionData.lang.verboseName];
}
const tag = document.querySelector('button[id^="headlessui-listbox-button"]');
if (!tag) {
throw new Error('No language button found');
}
const lang = tag.innerText;
if (languages[lang] === undefined) {
throw new Error('Unknown Language: ' + { lang });
}
return languages[lang];
};
LeetCodeV2.prototype.getNotesIfAny = function () { };
LeetCodeV2.prototype.extractQuestionNumber = function() {
let qNum = this.submissionData.question.questionId; // Default to questionId
const content = document.getElementById("qd-content");
if (content) {
const elementSelector = 'a[href^="/problems/' + window.location.pathname.split('/')[2] + '/"]';
const titleElement = content.querySelector(elementSelector);
if (titleElement) {
const numbersMatch = titleElement.textContent.match(/(\d+)\./);
if (numbersMatch) {
qNum = numbersMatch[1]; // Update qNum if a number is found
}
} else {
console.log("Element for number not found in the specified container.");
}
} else {
console.log("Content div not found.");
}
return qNum;
};
/**
* Gets a formatted problem name slug from the LeetCodeV2 instance.
* @returns {string} A string combining the problem number and the slug title.
*/
LeetCodeV2.prototype.getProblemNameSlug = function () {
const slugTitle = this.submissionData.question.titleSlug;
const qNum = this.extractQuestionNumber();
return addLeadingZeros(qNum + '-' + slugTitle);
};
LeetCodeV2.prototype.getSuccessStateAndUpdate = function () {
const successTag = document.querySelectorAll('[data-e2e-locator="submission-result"]');
if (checkElem(successTag)) {
console.log(successTag[0]);
successTag[0].classList.add('marked_as_success');
return true;
}
return false;
};
LeetCodeV2.prototype.parseStats = function () {
if (this.submissionData != null) {
const runtimePercentile =
Math.round((this.submissionData.runtimePercentile + Number.EPSILON) * 100) / 100;
const spacePercentile =
Math.round((this.submissionData.memoryPercentile + Number.EPSILON) * 100) / 100;
return formatStats(
this.submissionData.runtimeDisplay,
runtimePercentile,
this.submissionData.memoryDisplay,
spacePercentile,
);
}
// Doesn't work unless we wait for page to finish loading.
setTimeout(() => { }, 1000);
const probStats = document.getElementsByClassName('flex w-full pb-4')[0].innerText.split('\n');
if (!checkElem(probStats)) {
return null;
}
const time = probStats[1];
const timePercentile = probStats[3];
const space = probStats[5];
const spacePercentile = probStats[7];
return formatStats(time, timePercentile, space, spacePercentile);
};
LeetCodeV2.prototype.parseQuestion = function () {
let markdown;
if (this.submissionData != null) {
const questionUrl = window.location.href.split('/submissions')[0];
const qTitle = `${this.extractQuestionNumber()}. ${this.submissionData.question.title}`;
const qBody = this.parseQuestionDescription();
difficulty = this.submissionData.question.difficulty;
// Final formatting of the contents of the README for each problem
markdown = `<h2><a href="${questionUrl}">${qTitle}</a></h2><h3>${difficulty}</h3><hr>${qBody}`;
} else {
// TODO: get the README markdown via scraping. Right now this isn't possible.
markdown = null;
}
return markdown;
};
LeetCodeV2.prototype.parseQuestionTitle = function () {
if (this.submissionData != null) {
return this.submissionData.question.title;
}
let questionTitle = document
.getElementsByTagName('title')[0]
.innerText.split(' ')
.slice(0, -2)
.join(' ');
if (questionTitle === '') {
questionTitle = 'unknown-problem';
}
return questionTitle;
};
LeetCodeV2.prototype.parseQuestionDescription = function () {
if (this.submissionData != null) {
return this.submissionData.question.content;
}
const description = document.getElementsByName('description');
if (!checkElem(description)) {
return null;
}
return description[0].content;
};
LeetCodeV2.prototype.parseDifficulty = function () {
if (this.submissionData != null) {
return this.submissionData.question.difficulty;
}
const diffElement = document.getElementsByClassName('mt-3 flex space-x-4');
if (checkElem(diffElement)) {
return diffElement[0].children[0].innerText;
}
// Else, we're not on the description page. Nothing we can do.
return 'unknown';
};
LeetCodeV2.prototype.startSpinner = function () {
let elem = document.getElementById('leethub_progress_anchor_element');
if (!elem) {
elem = document.createElement('span');
elem.id = 'leethub_progress_anchor_element';
elem.style = 'margin-right: 20px;padding-top: 2px;';
}
elem.innerHTML = `<div id="${this.progressSpinnerElementId}" class="${this.progressSpinnerElementClass}"></div>`;
this.insertToAnchorElement(elem);
uploadState.uploading = true;
};
LeetCodeV2.prototype.injectSpinnerStyle = function () {
const style = document.createElement('style');
style.textContent = `.${this.progressSpinnerElementClass} {pointer-events: none;width: 2.0em;height: 2.0em;border: 0.4em solid transparent;border-color: #eee;border-top-color: #3E67EC;border-radius: 50%;animation: loadingspin 1s linear infinite;} @keyframes loadingspin { 100% { transform: rotate(360deg) }}`;
document.head.append(style);
};
LeetCodeV2.prototype.insertToAnchorElement = function (elem) {
if (document.URL.startsWith('https://leetcode.com/explore/')) {
// TODO: support spinner when answering problems on Explore pages
// action = document.getElementsByClassName('action');
// if (
// checkElem(action) &&
// checkElem(action[0].getElementsByClassName('row')) &&
// checkElem(action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6')) &&
// action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6').length > 1
// ) {
// target = action[0].getElementsByClassName('row')[0].getElementsByClassName('col-sm-6')[1];
// elem.className = 'pull-left';
// if (target.childNodes.length > 0) target.childNodes[0].prepend(elem);
// }
return;
}
if (checkElem(document.getElementsByClassName('ml-auto flex items-center space-x-4'))) {
const target = document.getElementsByClassName('ml-auto flex items-center space-x-4')[0];
elem.className = 'runcode-wrapper__8rXm';
if (target.childNodes.length > 0) target.childNodes[0].prepend(elem);
}
};
LeetCodeV2.prototype.markUploaded = function () {
let elem = document.getElementById(this.progressSpinnerElementId);
if (elem) {
elem.className = '';
style =
'display: inline-block;transform: rotate(45deg);height:24px;width:12px;border-bottom:7px solid #78b13f;border-right:7px solid #78b13f;';
elem.style = style;
}
};
LeetCodeV2.prototype.markUploadFailed = function () {
let elem = document.getElementById(this.progressSpinnerElementId);
if (elem) {
elem.className = '';
style =
'display: inline-block;transform: rotate(45deg);height:24px;width:12px;border-bottom:7px solid red;border-right:7px solid red;';
elem.style = style;
}
};
/* Sync to local storage */
chrome.storage.local.get('isSync', data => {
keys = [
'leethub_token',
'leethub_username',
'pipe_leethub',
'stats',
'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!');
}
});
const loader = (leetCode) => {
let iterations = 0;
const intervalId = setInterval(async () => {
try {
const isSuccessfulSubmission = leetCode.getSuccessStateAndUpdate();
if (!isSuccessfulSubmission) {
iterations++;
if (iterations > 9) {
clearInterval(intervalId); // poll for max 10 attempts (10 seconds)
}
return;
}
// If successful, stop polling
clearInterval(intervalId);
// For v2, query LeetCode API for submission results
await leetCode.init();
const probStats = leetCode.parseStats();
if (!probStats) {
throw new Error('Could not get submission stats');
}
const probStatement = leetCode.parseQuestion();
if (!probStatement) {
throw new Error('Could not find problem statement');
}
const problemName = leetCode.getProblemNameSlug();
const alreadyCompleted = await checkAlreadyCompleted(problemName);
const language = leetCode.getLanguageExtension();
if (!language) {
throw new Error('Could not find language');
}
// start upload indicator here
leetCode.startSpinner();
/* Upload README */
const updateReadMe = await chrome.storage.local.get('stats').then(({ stats }) => {
const shaExists = stats?.shas?.[problemName]?.['README.md'] !== undefined;
if (!shaExists) {
return uploadGit(
btoa(unescape(encodeURIComponent(probStatement))),
problemName,
'README.md',
readmeMsg,
'upload',
false,
);
}
});
/* Upload Notes if any*/