Skip to content

Commit

Permalink
Merge pull request #58 from vnma0/src-code
Browse files Browse the repository at this point in the history
Add feature to read submission's source
  • Loading branch information
dungwinux authored Mar 9, 2019
2 parents 28c4467 + a33ef07 commit 1817872
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/data/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,32 @@ async function readUserSubmission(user_id, page, size, count) {
});
}

/**
* Read Submission's source
* @param {String} sub_id Submission's ID
*/
function readSubmissionSrc(sub_id) {
return new Promise((resolve, reject) => {
db.submissions.findOne(
{ _id: sub_id },
{ ext: 1, user_id: 1, source_code: 1 },
(err, docs) => {
if (err) reject(err);
else if (docs === null)
reject(new Error(`Invalid Submission's ID: ${sub_id}`));
else
readUserByID(docs.user_id)
.then((res) => {
docs.username = res.username;
})
.finally(() => {
resolve(docs);
});
}
);
});
}

/**
* Add submission to database
* @param {String} source_code Source Code
Expand Down Expand Up @@ -579,6 +605,7 @@ module.exports = {
readAllSubmissions,
readSubmission,
readUserSubmission,
readSubmissionSrc,
newSubmission,
updateSubmission,
readLastSatisfy,
Expand Down
21 changes: 20 additions & 1 deletion src/routes/subs.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"use strict";

const express = require("express");
const { existsSync } = require("fs");

const { sendCode } = require("../controller/submitCode");
const {
readSubmission,
readAllSubmissions,
readUserSubmission
readUserSubmission,
readSubmissionSrc
} = require("../data/database");
const auth = require("../middleware/auth");
const bruteForce = require("../middleware/bruteForce");
Expand Down Expand Up @@ -66,4 +68,21 @@ router.get("/:id", (req, res) => {
);
});

router.get("/:id/source", (req, res) => {
readSubmissionSrc(req.params.id)
.then((docs) => {
if (docs.user_id === req.user._id || req.user.isAdmin) {
if (!existsSync(docs.source_code)) res.sendStatus(404);
else
res.download(
docs.source_code,
"".concat(docs._id, docs.ext.toLowerCase())
);
} else res.sendStatus(401);
})
.catch((err) => {
res.status(400).json(err.message);
});
});

module.exports = router;
2 changes: 1 addition & 1 deletion src/util/config/contestConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function parseContainer(container) {
if (!Array.isArray(container)) throw new Error("Invalid Container");
let parsedContainer = container
.filter((x) => typeof x === "string")
.map((x) => x.trim().toUpperCase())
.map((x) => x.replace(/\s/g, "").toUpperCase())
.sort((a, b) => a.localeCompare(b));
return [...new Set(parsedContainer)];
}
Expand Down

0 comments on commit 1817872

Please sign in to comment.