Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions api/main_endpoints/routes/Printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const fs = require('fs');
const path = require('path');
const { MetricsHandler, register } = require('../../util/metrics.js');
const { cleanUpChunks, cleanUpExpiredChunks, recordPrintingFolderSize } = require('../util/Printer.js');
const { PDFDocument, StandardFonts } = require('pdf-lib');
const {subtractUserPages} = require('../util/userHelpers');

const {
decodeToken,
Expand All @@ -17,6 +19,7 @@ const {
UNAUTHORIZED,
NOT_FOUND,
SERVER_ERROR,
BAD_REQUEST
} = require('../../util/constants').STATUS_CODES;
const {
PRINTING = {}
Expand Down Expand Up @@ -113,16 +116,25 @@ router.post('/sendPrintRequest', upload.single('chunk'), async (req, res) => {
return res.sendStatus(SERVER_ERROR);
}
}

const stream = await fs.createReadStream(assembledPdfFromChunks);
const stream = await fs.promises.readFile(assembledPdfFromChunks); // Buffer
const data = new FormData();
data.append('file', stream, {filename: id, type: 'application/pdf'});
data.append('copies', copies);
data.append('sides', sides);

try {
const pdfDoc = await PDFDocument.load(stream); // load PDF
const numpages = pdfDoc.getPages().length; // get number of pages
const copiesInt = parseInt(copies || 1, 10);
const totalPages = numpages * copiesInt; // updates users printcount
const success = await subtractUserPages(user.id, totalPages);
if (!success) {
await cleanUpChunks(dir, id);
return res.status(BAD_REQUEST).json({ error: 'Page limit exceeded or user not found' });
}
// full pdf can be sent to quasar no problem
const printRes = await axios.post(PRINTER_URL + '/print', data, {

headers: {
...data.getHeaders(),
},
Expand Down
21 changes: 21 additions & 0 deletions api/main_endpoints/util/userHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,26 @@ function checkIfPageCountResets(lastLogin) {

return lastLoginWasOverOneWeekAgo || aSundayHasPassedSinceLastLogin;
}
// updates users available pages
async function subtractUserPages(userId, pagesToPrint){
const user = await User.findById(userId);
if(!user){
logger.error(`User not found ID: ${userId}`);
return false; // checks user
}
if(!Number.isInteger(pagesToPrint) || pagesToPrint <= 0){
logger.error(`Invalid pagesToPrint value: ${pagesToPrint}.`);
return false;
}
if (user.pagesPrinted < pagesToPrint) {
logger.error(`User has insufficient pages remaining. Requested: ${pagesToPrint}. Available:${user.pagesPrinted}`);
return false;
}

user.pagesPrinted -= pagesToPrint;
await user.save();
return true;
}

module.exports = {
registerUser,
Expand All @@ -211,4 +231,5 @@ module.exports = {
userWithEmailExists,
checkIfPageCountResets,
findPasswordReset,
subtractUserPages,
};
80 changes: 80 additions & 0 deletions api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"nodemon": "^2.0.4",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"pdf-lib": "^1.17.1",
"prom-client": "^15.1.3"
},
"devDependencies": {
Expand Down