forked from joshcai/leetcode-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
263 lines (236 loc) · 7.47 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
const axios = require('axios');
const core = require('@actions/core');
const { context } = require('@actions/github');
const { Octokit } = require('@octokit/rest');
const COMMIT_MESSAGE = 'Sync LeetCode submission';
const LANG_TO_EXTENSION = {
'bash': 'sh',
'c': 'c',
'cpp': 'cpp',
'csharp': 'cs',
'dart': 'dart',
'golang': 'go',
'java': 'java',
'javascript': 'js',
'kotlin': 'kt',
'mssql': 'sql',
'mysql': 'sql',
'oraclesql': 'sql',
'php': 'php',
'python': 'py',
'python3': 'py',
'ruby': 'rb',
'rust': 'rs',
'scala': 'scala',
'swift': 'swift',
'typescript': 'ts',
};
const delay = ms => new Promise(res => setTimeout(res, ms));
function log(message) {
console.log(`[${new Date().toUTCString()}] ${message}`);
}
function normalizeName(problemName) {
return problemName.toLowerCase().replace(/\s/g, '_');
}
async function commit(params) {
const {
octokit,
owner,
repo,
defaultBranch,
commitInfo,
treeSHA,
latestCommitSHA,
submission,
destinationFolder
} = params;
const name = normalizeName(submission.title);
log(`Committing solution for ${name}...`);
if (!LANG_TO_EXTENSION[submission.lang]) {
throw `Language ${submission.lang} does not have a registered extension.`;
}
const prefix = !!destinationFolder ? `${destinationFolder}/` : '';
const path = `${prefix}problems/${name}/solution.${LANG_TO_EXTENSION[submission.lang]}`
const treeData = [
{
path,
mode: '100644',
content: submission.code,
}
];
const treeResponse = await octokit.git.createTree({
owner: owner,
repo: repo,
base_tree: treeSHA,
tree: treeData,
})
const date = new Date(submission.timestamp * 1000).toISOString();
const commitResponse = await octokit.git.createCommit({
owner: owner,
repo: repo,
message: `${COMMIT_MESSAGE} - ${submission.title} (${submission.lang})`,
tree: treeResponse.data.sha,
parents: [latestCommitSHA],
author: {
email: commitInfo.email,
name: commitInfo.name,
date: date,
},
committer: {
email: commitInfo.email,
name: commitInfo.name,
date: date,
},
})
await octokit.git.updateRef({
owner: owner,
repo: repo,
sha: commitResponse.data.sha,
ref: 'heads/' + defaultBranch,
force: true
});
log(`Committed solution for ${name}`);
return [treeResponse.data.sha, commitResponse.data.sha];
}
// Returns false if no more submissions should be added.
function addToSubmissions(params) {
const {
response,
lastTimestamp,
filterDuplicateSecs,
submissions_dict,
submissions
} = params;
for (const submission of response.data.submissions_dump) {
if (submission.timestamp <= lastTimestamp) {
return false;
}
if (submission.status_display !== 'Accepted') {
continue;
}
const name = normalizeName(submission.title);
const lang = submission.lang;
if (!submissions_dict[name]) {
submissions_dict[name] = {};
}
// Filter out other accepted solutions less than one day from the most recent one.
if (submissions_dict[name][lang] && submissions_dict[name][lang] - submission.timestamp < filterDuplicateSecs) {
continue;
}
submissions_dict[name][lang] = submission.timestamp;
submissions.push(submission);
}
return true;
}
async function sync(inputs) {
const {
githubToken,
owner,
repo,
filterDuplicateSecs,
leetcodeCSRFToken,
leetcodeSession,
destinationFolder
} = inputs;
const octokit = new Octokit({
auth: githubToken,
userAgent: 'LeetCode sync to GitHub - GitHub Action',
});
// First, get the time the timestamp for when the syncer last ran.
const commits = await octokit.repos.listCommits({
owner: owner,
repo: repo,
per_page: 100,
});
let lastTimestamp = 0;
// commitInfo is used to get the original name / email to use for the author / committer.
// Since we need to modify the commit time, we can't use the default settings for the
// authenticated user.
let commitInfo = commits.data[commits.data.length - 1].commit.author;
for (const commit of commits.data) {
if (!commit.commit.message.startsWith(COMMIT_MESSAGE)) {
continue
}
commitInfo = commit.commit.author;
lastTimestamp = Date.parse(commit.commit.committer.date) / 1000;
break;
}
// Get all Accepted submissions from LeetCode greater than the timestamp.
let response = null;
let offset = 0;
const submissions = [];
const submissions_dict = {};
do {
const config = {
params: {
offset: offset,
limit: 20,
lastkey: (response === null ? '' : response.data.last_key),
},
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': leetcodeCSRFToken,
'Cookie': `csrftoken=${leetcodeCSRFToken};LEETCODE_SESSION=${leetcodeSession};`,
},
};
log(`Getting submission from LeetCode, offset ${offset}`);
const getSubmissions = async (maxRetries, retryCount = 0) => {
try {
const response = await axios.get('https://leetcode.com/api/submissions/', config);
return response;
} catch (exception) {
if (retryCount >= maxRetries) {
throw exception;
}
log('Error fetching submissions, retrying in ' + 3 ** retryCount + ' seconds...');
// There's a rate limit on LeetCode API, so wait with backoff before retrying.
await delay(3 ** retryCount * 1000);
return getSubmissions(maxRetries, retryCount + 1);
}
};
// On the first attempt, there should be no rate limiting issues, so we fail immediately in case
// the tokens are configured incorrectly.
const maxRetries = (response === null) ? 0 : 5;
if (response !== null) {
// Add a 1 second delay before all requests after the initial request.
await delay(1000);
}
response = await getSubmissions(maxRetries);
if (!addToSubmissions({ response, lastTimestamp, filterDuplicateSecs, submissions_dict, submissions })) {
break;
}
offset += 20;
} while (response.data.has_next);
// We have all submissions we want to write to GitHub now.
// First, get the default branch to write to.
const repoInfo = await octokit.repos.get({
owner: owner,
repo: repo,
});
const defaultBranch = repoInfo.data.default_branch;
log(`Default branch for ${owner}/${repo}: ${defaultBranch}`);
// Write in reverse order (oldest first), so that if there's errors, the last sync time
// is still valid.
log(`Syncing ${submissions.length} submissions...`);
let latestCommitSHA = commits.data[0].sha;
let treeSHA = commits.data[0].commit.tree.sha;
for (i = submissions.length - 1; i >= 0; i--) {
submission = submissions[i];
[treeSHA, latestCommitSHA] = await commit({ octokit, owner, repo, defaultBranch, commitInfo, treeSHA, latestCommitSHA, submission, destinationFolder });
}
log('Done syncing all submissions.');
}
async function main() {
const githubToken = core.getInput('github-token');
const owner = context.repo.owner;
const repo = context.repo.repo;
const leetcodeCSRFToken = core.getInput('leetcode-csrf-token');
const leetcodeSession = core.getInput('leetcode-session');
const filterDuplicateSecs = core.getInput('filter-duplicate-secs');
const destinationFolder = core.getInput('destination-folder');
await sync({ githubToken, owner, repo, filterDuplicateSecs, leetcodeCSRFToken, leetcodeSession, destinationFolder });
}
main().catch((error) => {
log(error.stack);
core.setFailed(error)
});