-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·220 lines (196 loc) · 7.52 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
import express from 'express';
import bodyParser from 'body-parser';
import { execSync, spawnSync } from 'child_process';
import fetch from 'node-fetch';
import os from 'os';
import path from 'path';
import fs from 'fs';
import 'dotenv/config';
import { initializeApp, applicationDefault, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';
import serviceAccount from './firebase-key.json' assert { type: 'json' };
initializeApp({
credential: cert(serviceAccount),
});
const db = getFirestore();
const log = (...args) => {
if (process.env.PRINTDEV == 'true') console.log(...args);
};
const getCurrentTime = () => {
const currentDate = new Date(
new Date().toLocaleString('en-US', { timeZone: 'America/New_York' })
);
const year = currentDate.getFullYear().toString().padStart(4, '0');
const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
const day = currentDate.getDate().toString().padStart(2, '0');
const hours = currentDate.getHours().toString().padStart(2, '0');
const minutes = currentDate.getMinutes().toString().padStart(2, '0');
return `${month}/${day}/${year} ${hours}:${minutes}`;
};
const extractLatestCommit = (s) => {
return s.match(/(?<=[ \t]+[a-z0-9]+\.\.)[a-z0-9]+/)?.[0];
};
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const homeDir = os.homedir();
const resourceDir = process.env.RESOURCEDIR
? path.join(homeDir, process.env.RESOURCEDIR)
: path.join(homeDir, 'leetcode-server', 'public');
app.use('/public', express.static('public')); // works
const authenticate = (req, res, next) => {
const { apiKey } = req.body;
const expectedKey = process.env.PASSWORD;
if (apiKey === expectedKey) {
next();
} else {
console.log('unauth request', req.body);
return res.status(401).send('Unauthorized');
}
};
const getRandomImage = (key) => {
const files = fs.readdirSync(resourceDir);
key = key && key < 1 ? key : Math.random();
const randomIndex = Math.floor(key * files.length);
return files[randomIndex];
};
app.get('/randomimage', (req, res) => {
const randomImage = getRandomImage(req.query.key);
const imagePath = path.join(resourceDir, randomImage);
res.sendFile(imagePath);
});
app.get('/', (req, res) => res.send('hi'));
// body should look like:
// body: JSON.stringify({
// difficulty,
// formattedTitle,
// fileText,
// apiKey: password,
// }),
app.post('/updateGithub', authenticate, (req, res) => {
const { difficulty, formattedTitle, suffix, fileText, url } = req.body;
const titleWithSuffix =
suffix.length > 0 ? `${formattedTitle}-${suffix}` : formattedTitle;
// check the title looks right
if (/[^a-zA-Z0-9\-]/.test(titleWithSuffix)) {
res.status(501).send('Bad title');
return;
}
let basePath = homeDir;
if (process.env.WORKDIR) {
basePath = path.join(homeDir, process.env.WORKDIR);
} else {
basePath = path.join(homeDir, 'leetcode');
}
let filePath = path.join(basePath, difficulty, `${titleWithSuffix}.py`);
try {
const fileExists = fs.existsSync(filePath);
fs.writeFileSync(filePath, fileText);
log('File written successfully.');
const options = {
cwd: basePath,
encoding: 'UTF-8',
};
spawnSync('git', ['pull'], {
...options,
maxBuffer: 1024 * 1024 * 100,
});
log('execute pull');
execSync('git add .', options);
log('added files');
const commitMessage = `[jasbob-leetcode-bot] automated upload of <${difficulty}> ${titleWithSuffix}`;
execSync(`git commit -m '${commitMessage}'`, options);
log('committed files');
const execOutput = spawnSync('git', ['push'], {
...options,
maxBuffer: 1024 * 1024 * 100,
});
const output = execOutput.output.join(' ');
log('pushed files');
log(`output from git push: %${output}%`);
const commit = extractLatestCommit(output);
log('commit', commit);
const url_ending = commit ? `commit/${commit}` : '';
const docRef = db.collection('leetcode_actions').doc();
const splitName = formattedTitle.split('-');
const problemNumber = splitName[0];
const problemName = splitName
.slice(1)
.join(' ')
.replace(/^\w|\s\w/g, (x) => x.toUpperCase());
(async () => {
if (!formattedTitle.startsWith('99999')) {
await docRef.set({
formattedTitle,
problemNumber,
problemName,
suffix,
url,
difficulty,
action: suffix.length > 0 ? 'write_alt_sol' : 'write_sol',
rewrite: fileExists,
timestamp: new Date(),
});
} else {
console.log('test case... skipping upload');
}
const collectionRef = db.collection('leetcode_actions');
const snapshot = await collectionRef.count().get();
const cnt = snapshot.data().count;
const uniqueValuesSet = new Set();
const collectionSnapshot = await collectionRef.get();
collectionSnapshot.forEach((doc) => {
// Access the field value and add it to the Set
const fieldValue = doc.data()['problemNumber'];
if (fieldValue == undefined) {
console.log(doc.id);
}
if (fieldValue != '99999') {
uniqueValuesSet.add(fieldValue);
}
});
const data = {
embeds: [
{
color: '2484902',
fields: [
{
name: `[jasbob-leetcode-bot] Automated Upload Triggered!`,
value: `Uploaded <${difficulty}> ${titleWithSuffix} [(here)](https://github.com/jason-tung/leetcode/${url_ending})
Total entries stored: ${cnt}
Unique problems solved: ${uniqueValuesSet.size}
`,
},
],
thumbnail: {
url: `http://jasontung.me:3001/randomimage?key=${Math.random()}`,
},
footer: {
text: `powered by jasbob-bot ・ ${getCurrentTime()}`,
icon_url:
'https://avatars.githubusercontent.com/u/153464167?v=4',
},
},
],
};
fetch(process.env.WEBHOOK, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
console.log('finished upload', titleWithSuffix, commit);
res.status(200).send(
`https://github.com/jason-tung/leetcode/${url_ending}`
);
})();
} catch (err) {
console.error('Error writing file:', err);
res.status(500).send('Error executing command');
}
});
const PORT = 3001;
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on port ${PORT}`);
});