Skip to content

Commit c21cb9d

Browse files
committed
add print for hydro
1 parent 1efd7c6 commit c21cb9d

File tree

5 files changed

+50
-5
lines changed

5 files changed

+50
-5
lines changed

packages/server/handler/client.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ class ClientPrintDoneHandler extends Handler {
8181
if (!code) throw new ValidationError('Code', null, 'Code not found');
8282
if (code.printer !== params.cid) throw new BadRequestError('Client', null, 'Client not match');
8383
await this.ctx.db.code.updateOne({ _id: params.tid }, { $set: { done: 1, doneAt: new Date().getTime() } });
84+
await this.ctx.fetcher.setPrintDone(code.id!);
8485
await this.ctx.parallel('print/doneTask', client._id, `${client._id}#${params.printer || 'unknown'}`);
8586
this.response.body = { code: 1 };
8687
logger.info(`Client ${client.name} connected, print task ${code.tid}#${code._id} completed.`);

packages/server/handler/printer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ class CodeHandler extends Handler {
9191
fs.writeFileSync(path.resolve(process.cwd(), 'data/codes', `${team}#${res._id}`), codeFile);
9292
this.response.body = `The code has been submitted. Code Print ID: ${team}#${res._id}`;
9393
logger.info(`Team(${team}): ${tname} submitted code. Code Print ID: ${team}#${res._id}`);
94-
await this.ctx.parallel('print/newTask');
94+
await this.ctx.parallel('print/newTask', 1);
9595
if (tname.length > 40) {
9696
logger.warn(`Team ${tname} name is too long, may cause overflow!`);
9797
this.response.body += ', your team name is too long, may cause print failed!';

packages/server/service/fetcher.ts

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import { Context, Service } from 'cordis';
33
import superagent from 'superagent';
44
import { config } from '../config';
5-
import { Logger, mongoId, sleep } from '../utils';
5+
import { fs, Logger, mongoId, sleep } from '../utils';
6+
import path from 'node:path';
67

78
const logger = new Logger('fetcher');
89
const fetch = (url: string, type: 'get' | 'post' = 'get') => {
@@ -57,6 +58,7 @@ class BasicFetcher extends Service implements IBasicFetcher {
5758
const first = await this.contestInfo();
5859
if (first) await this.teamInfo();
5960
await this.balloonInfo(first);
61+
await this.printInfo(first);
6062
}
6163

6264
async contestInfo() {
@@ -81,6 +83,14 @@ class BasicFetcher extends Service implements IBasicFetcher {
8183
async setBalloonDone(bid) {
8284
this.logger.debug(`Balloon ${bid} set done`);
8385
}
86+
87+
async printInfo(all) {
88+
this.logger.debug('Found 0 prints in Server Mode');
89+
}
90+
91+
async setPrintDone(pid) {
92+
this.logger.debug(`Print ${pid} set done`);
93+
}
8494
}
8595

8696
class DOMjudgeFetcher extends BasicFetcher {
@@ -177,6 +187,7 @@ class HydroFetcher extends BasicFetcher {
177187
}
178188
const contest = body.tdoc;
179189
contest.freeze_time = contest.lockAt;
190+
delete contest.content;
180191
const old = this?.contest?.id;
181192
this.contest = {
182193
info: contest, id: contest._id, name: contest.title, domainId,
@@ -252,6 +263,39 @@ class HydroFetcher extends BasicFetcher {
252263
await fetch(`/d/${this.contest.domainId}/contest/${this.contest.id}/balloon`, 'post').send({ operation: 'done', balloon: bid });
253264
this.logger.debug(`Balloon ${bid} set done`);
254265
}
266+
267+
async printInfo(all) {
268+
const doFetch = async () => {
269+
const { body } = await fetch(`/d/${this.contest.domainId}/contest/${this.contest.id}/print`, 'post').send({ operation: 'allocate_print_task' });
270+
return body;
271+
}
272+
let { task, udoc } = await doFetch();
273+
let cnt = 0;
274+
while (task) {
275+
const res = await this.ctx.db.code.insert({
276+
id: task._id,
277+
tid: task.owner,
278+
team: `${udoc.school ? `${udoc.school}: ` : ''}${udoc.displayName || udoc.uname}`,
279+
location: udoc.studentId,
280+
filename: task.title,
281+
lang: task.title.split('.').pop() || 'txt',
282+
createdAt: new Date(parseInt(task._id.substring(0, 8), 16) * 1000).getTime(),
283+
printer: '',
284+
done: task.status === 'printed' ? 1 : 0,
285+
});
286+
await fs.ensureDir(path.resolve(process.cwd(), 'data/codes'));
287+
await fs.writeFile(path.resolve(process.cwd(), 'data/codes', `${task.owner}#${res._id}`), task.content);
288+
logger.info(`Team(${task.owner}): ${udoc.displayName || udoc.uname} submitted code. Code Print ID: ${task.owner}#${res._id}`);
289+
cnt++;
290+
({ task, udoc } = await doFetch());
291+
}
292+
await this.ctx.parallel('print/newTask', cnt);
293+
}
294+
295+
async setPrintDone(pid) {
296+
await fetch(`/d/${this.contest.domainId}/contest/${this.contest.id}/print`, 'post').send({ operation: 'update_print_task', taskId: pid, status: 'printed' });
297+
this.logger.debug(`Print ${pid} set done`);
298+
}
255299
}
256300

257301
const fetcherList = {

packages/server/utils/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export * as yaml from 'js-yaml';
1919

2020
export function StaticHTML(context, randomHash) {
2121
// eslint-disable-next-line max-len
22-
return `<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>@Hydro/XCPC-TOOLS</title></head><body><div id="root"></div><script>window.Context=JSON.parse('${JSON.stringify(context)}')</script><script src="/main.js?${randomHash}"></script></body></html>`;
22+
return `<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>@Hydro/XCPC-TOOLS</title></head><body><div id="root"></div><script>window.Context=JSON.parse('${JSON.stringify(context).replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}')</script><script src="/main.js?${randomHash}"></script></body></html>`;
2323
}
2424

2525
export function decodeBinary(file: string, name: string) {

packages/server/utils/metrics.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ declare module 'cordis' {
88
metrics: Registry;
99
}
1010
interface Events {
11-
'print/newTask': () => void;
11+
'print/newTask': (count: number) => void;
1212
'print/sendTask': (client: string) => void;
1313
'print/doneTask': (client: string, printer: string) => void;
1414
'balloon/newTask': (count: number) => void;
@@ -41,7 +41,7 @@ export function createMetricsRegistry(ctx: Context) {
4141
const printTaskCounter = createMetric(Counter, 'xcpc_printcount', 'printcount', {
4242
labelNames: ['status', 'client', 'printer'],
4343
});
44-
ctx.on('print/newTask', () => printTaskCounter.inc({ status: 'new' }));
44+
ctx.on('print/newTask', (count) => printTaskCounter.inc({ status: 'new' }, count));
4545

4646
ctx.on('print/sendTask', (client) => printTaskCounter.inc({ status: 'sent', client }));
4747

0 commit comments

Comments
 (0)