Skip to content

Commit

Permalink
07 14 leetcode UI bug fix (QasimWani#18)
Browse files Browse the repository at this point in the history
* fixes an issue with leetcode solutions not submitting due to leetcode change to submissionId

* pulls in new languages from sanjai0py

* removes comments, formats with prettier
  • Loading branch information
arunbhardwaj authored Jul 24, 2023
1 parent 1fbacf0 commit c5534ef
Showing 1 changed file with 74 additions and 65 deletions.
139 changes: 74 additions & 65 deletions scripts/leetcode.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ const languages = {
MySQL: '.sql',
'MS SQL Server': '.sql',
Oracle: '.sql',
Racket: '.rkt',
Erlang: '.erl',
Elixir: '.ex',
Dart: '.dart',
};

/* Commit messages */
Expand Down Expand Up @@ -81,46 +85,44 @@ const upload = (token, hook, code, problem, filename, sha, commitMsg, cb = undef
});
};

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 = {};
}
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] = {};
}
if (stats.shas[problem] == null) {
stats.shas[problem] = {};
}

return stats
})
}
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 })
})
}
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
})
}
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 */
Expand Down Expand Up @@ -155,12 +157,12 @@ const update = (
.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)))
// 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 =>
Expand Down Expand Up @@ -237,7 +239,11 @@ function uploadGit(
throw err;
}
})
.then(data => (data != null) ? upload(token, hook, code, problemName, fileName, data.sha, commitMsg, cb) : undefined)
.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 */
Expand All @@ -252,14 +258,13 @@ async function getUpdatedData(token, hook, directory, filename) {
},
};

return fetch(URL, options)
.then(res => {
if (res.status === 200 || res.status === 201) {
return res.json();
} else {
throw new Error('' + res.status);
}
});
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 */
Expand Down Expand Up @@ -333,7 +338,7 @@ function LeetCodeV1() {
this.progressSpinnerElementClass = 'leethub_progress';
this.injectSpinnerStyle();
}
LeetCodeV1.prototype.init = async function () { };
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. */
Expand Down Expand Up @@ -651,8 +656,18 @@ function LeetCodeV2() {
}
LeetCodeV2.prototype.init = async function () {
// Get submission ID
const submissionUrl = window.location.href;
const submissionId = parseInt(submissionUrl.split('/submissions/')[1].slice(0, -1));
async function getSubmissionId() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const submissionNode = document.getElementsByClassName(
'text-label-r flex items-center justify-center gap-1 rounded px-3 py-1 text-xs font-medium leading-[16px]',
)[0].parentNode;
const submissionId = submissionNode.getAttribute('href').split('=')[1]; // '/problems/two-sum/post-solution?submissionId=999594717'
resolve(submissionId);
}, 100);
});
}
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 = {
Expand Down Expand Up @@ -726,7 +741,7 @@ LeetCodeV2.prototype.getLanguageExtension = function () {

return languages[lang];
};
LeetCodeV2.prototype.getNotesIfAny = function () { };
LeetCodeV2.prototype.getNotesIfAny = function () {};
LeetCodeV2.prototype.getProblemNameSlug = function () {
const slugTitle = this.submissionData.question.titleSlug;
const qNum = this.submissionData.question.questionId;
Expand Down Expand Up @@ -757,7 +772,7 @@ LeetCodeV2.prototype.parseStats = function () {
}

// Doesn't work unless we wait for page to finish loading.
setTimeout(() => { }, 1000);
setTimeout(() => {}, 1000);
const probStats = document.getElementsByClassName('flex w-full pb-4')[0].innerText.split('\n');
if (!checkElem(probStats)) {
return null;
Expand Down Expand Up @@ -807,7 +822,7 @@ LeetCodeV2.prototype.parseQuestionTitle = function () {
};
LeetCodeV2.prototype.parseQuestionDescription = function () {
if (this.submissionData != null) {
return this.submissionData.question.content
return this.submissionData.question.content;
}

const description = document.getElementsByName('description');
Expand Down Expand Up @@ -919,20 +934,20 @@ if (!isLeetCodeV2) {
}

const loader = () => {
let iterations = 0
let iterations = 0;
const intervalId = setInterval(async () => {
try {
const isSuccessfulSubmission = leetCode.getSuccessStateAndUpdate();
if (!isSuccessfulSubmission) {
iterations++
iterations++;
if (iterations > 9) {
clearInterval(intervalId) // poll for max 10 attempts (10 seconds)
clearInterval(intervalId); // poll for max 10 attempts (10 seconds)
}
return;
}

// If successful, stop polling
clearInterval(intervalId)
clearInterval(intervalId);

// For v2, query LeetCode API for submission results
await leetCode.init();
Expand All @@ -948,7 +963,7 @@ const loader = () => {
}

const problemName = leetCode.getProblemNameSlug();
const alreadyCompleted = await checkAlreadyCompleted(problemName)
const alreadyCompleted = await checkAlreadyCompleted(problemName);
const language = leetCode.getLanguageExtension();
if (!language) {
throw new Error('Could not find language');
Expand All @@ -959,7 +974,7 @@ const loader = () => {

/* Upload README */
const updateReadMe = await chrome.storage.local.get('stats').then(({ stats }) => {
const shaExists = stats?.shas?.[problemName]?.["README.md"] !== undefined;
const shaExists = stats?.shas?.[problemName]?.['README.md'] !== undefined;

if (!shaExists) {
return uploadGit(
Expand Down Expand Up @@ -995,20 +1010,14 @@ const loader = () => {
'upload',
);

await Promise.all([
updateReadMe,
updateNotes,
updateCode,
])
await Promise.all([updateReadMe, updateNotes, updateCode]);

uploadState.uploading = false;
leetCode.markUploaded();

if (!alreadyCompleted) {
incrementStats()
incrementStats();
}


} catch (err) {
uploadState.uploading = false;
leetCode.markUploadFailed();
Expand Down

0 comments on commit c5534ef

Please sign in to comment.