-
-
Notifications
You must be signed in to change notification settings - Fork 263
/
import.syzoj.ts
265 lines (258 loc) · 10.4 KB
/
import.syzoj.ts
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
import fs from 'fs';
import path from 'path';
import os from 'os';
import assert from 'assert';
import superagent from 'superagent';
import { filter } from 'lodash';
import { PassThrough } from 'stream';
import AdmZip from 'adm-zip';
import yaml from 'js-yaml';
import { ValidationError, RemoteOnlineJudgeError } from '../error';
import { Logger } from '../logger';
import type { ContentNode } from '../interface';
import * as problem from '../model/problem';
import { PERM } from '../model/builtin';
import {
Route, Handler, Types, post,
} from '../service/server';
import { isPid } from '../lib/validator';
import download from '../lib/download';
const RE_SYZOJ = /(https?):\/\/([^/]+)\/(problem|p)\/([0-9]+)\/?/i;
const logger = new Logger('import.syzoj');
class ProblemImportSYZOJHandler extends Handler {
async get() {
this.response.template = 'problem_import_syzoj.html';
this.response.body = {
path: [
['Hydro', 'homepage'],
['problem_main', 'problem_main'],
['problem_import_syzoj', null],
],
};
}
async v2(domainId: string, target: string, hidden = false, url: string) {
const res = await superagent.get(`${url}export`);
assert(res.status === 200, new RemoteOnlineJudgeError('Cannot connect to target server'));
assert(res.body.success, new RemoteOnlineJudgeError((res.body.error || {}).message));
const p = res.body.obj;
const content: ContentNode[] = [];
if (p.description) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Problem Description'),
text: p.description,
});
}
if (p.input_format) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Input Format'),
text: p.input_format,
});
}
if (p.output_format) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Output Format'),
text: p.output_format,
});
}
if (p.example) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Sample'),
text: p.example,
});
}
if (p.hint) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Hint'),
text: p.hint,
});
}
if (p.limit_and_hint) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Limit And Hint'),
text: p.output_format,
});
}
if (p.have_additional_file) {
content.push({
type: 'Text',
subType: 'markdown',
sectionTitle: this.translate('Additional File'),
text: `${url}download/additional_file`,
});
}
const docId = await problem.add(
domainId, target, p.title, content, this.user._id,
p.tags || [], [], hidden,
);
const r = download(`${url}testdata/download`);
const file = path.resolve(os.tmpdir(), 'hydro', `import_${domainId}_${docId}.zip`);
const w = fs.createWriteStream(file);
try {
await new Promise((resolve, reject) => {
w.on('finish', resolve);
w.on('error', reject);
r.pipe(w);
});
const zip = new AdmZip(file);
const entries = zip.getEntries();
for (const entry of entries) {
// eslint-disable-next-line no-await-in-loop
await problem.addTestdata(domainId, docId, entry.entryName, entry.getData());
}
const filename = p.file_io_input_name ? p.file_io_input_name?.split('.')[0] : null;
const config = {
time: `${p.time_limit}ms`,
memory: `${p.memory_limit}m`,
filename,
type: p.type === 'traditional' ? 'default' : p.type,
};
await problem.addTestdata(domainId, docId, 'config.yaml', Buffer.from(yaml.dump(config)));
} finally {
fs.unlinkSync(file);
}
return docId;
}
async v3(
domainId: string, target: string, hidden: boolean,
protocol: string, host: string, pid: string | number,
wait = false,
) {
const result = await superagent.post(`${protocol}://${host === 'loj.ac' ? 'api.loj.ac.cn' : host}/api/problem/getProblem`)
.send({
displayId: +pid,
localizedContentsOfAllLocales: true,
tagsOfLocale: this.user.viewLang || this.session.viewLang,
samples: true,
testData: true,
additionalFiles: true,
});
const content = {};
for (const c of result.body.localizedContentsOfAllLocales) {
const sections = c.contentSections;
for (const section of sections) {
section.subType = 'markdown';
if (section.type === 'Sample') {
section.payload = [
result.body.samples[section.sampleId].inputData,
result.body.samples[section.sampleId].outputData,
];
delete section.sampleId;
}
}
content[c.locale] = sections;
}
const tags = result.body.tagsOfLocale.map((node) => node.name);
const title = [
...filter(
result.body.localizedContentsOfAllLocales,
(node) => node.locale === (this.user.viewLang || this.session.viewLang),
),
...result.body.localizedContentsOfAllLocales,
][0].title;
const docId = await problem.add(
domainId, target, title, content, this.user._id,
tags || [], [], hidden,
);
const syncFiles = async () => {
const judge = result.body.judgeInfo;
const r = await superagent.post(`${protocol}://${host === 'loj.ac' ? 'api.loj.ac.cn' : host}/api/problem/downloadProblemFiles`)
.send({
problemId: +pid,
type: 'TestData',
filenameList: result.body.testData.map((node) => node.filename),
});
const urls = {};
if (r.body.error) return;
for (const t of r.body.downloadInfo) urls[t.filename] = t.downloadUrl;
for (const f of result.body.testData) {
const p = new PassThrough();
superagent.get(urls[f.filename]).pipe(p);
// eslint-disable-next-line no-await-in-loop
await problem.addTestdata(domainId, docId, f.filename, p);
}
if (judge) {
const config = {
time: `${judge.timeLimit}ms`,
memory: `${judge.memoryLimit}m`,
// TODO other config
};
await problem.addTestdata(domainId, docId, 'config.yaml', Buffer.from(yaml.dump(config)));
}
const a = await superagent.post(`${protocol}://${host === 'loj.ac' ? 'api.loj.ac.cn' : host}/api/problem/downloadProblemFiles`)
.send({
problemId: +pid,
type: 'AdditionalFile',
filenameList: result.body.additionalFiles.map((node) => node.filename),
});
const aurls = {};
if (a.body.error) return;
for (const t of a.body.downloadInfo) aurls[t.filename] = t.downloadUrl;
for (const f of result.body.additionalFiles) {
const p = new PassThrough();
superagent.get(aurls[f.filename]).pipe(p);
// eslint-disable-next-line no-await-in-loop
await problem.addAdditionalFile(domainId, docId, f.filename, p);
}
};
if (wait) await syncFiles();
else syncFiles().catch(logger.error);
return docId;
}
@post('url', Types.String, true)
@post('pid', Types.String, true, isPid)
@post('hidden', Types.Boolean)
@post('prefix', Types.String, true)
@post('start', Types.UnsignedInt, true)
@post('end', Types.UnsignedInt, true)
async post(
domainId: string, url: string, targetPid: string, hidden = false,
prefix: string, start: number, end: number,
) {
if (prefix) {
if (!prefix.endsWith('/')) prefix += '/';
const base = `${prefix}${start}/`;
assert(base.match(RE_SYZOJ), new ValidationError('prefix'));
const [, protocol, host] = RE_SYZOJ.exec(base);
(async () => {
for (let i = start; i <= end; i++) {
// eslint-disable-next-line no-await-in-loop
await this.v3(domainId, undefined, hidden, protocol, host, i, true);
logger.info('%s %d-%d-%d', prefix, start, i, end);
}
})().catch(logger.error);
this.response.redirect = this.url('problem_main');
} else {
assert(url.match(RE_SYZOJ), new ValidationError('url'));
if (!url.endsWith('/')) url += '/';
const [, protocol, host, n, pid] = RE_SYZOJ.exec(url);
if (n === 'p') {
const docId = await this.v3(
domainId, targetPid, hidden,
protocol, host, pid, false,
);
this.response.body = { pid: targetPid || docId };
this.response.redirect = this.url('problem_settings', { pid: targetPid || docId });
} else {
const docId = await this.v2(domainId, targetPid, hidden, url);
this.response.body = { pid: targetPid || docId };
this.response.redirect = this.url('problem_settings', { pid: targetPid || docId });
}
}
}
}
export async function apply() {
Route('problem_import_syzoj', '/problem/import/syzoj', ProblemImportSYZOJHandler, PERM.PERM_CREATE_PROBLEM);
}
global.Hydro.handler['import.syzoj'] = apply;