printservant/index.js

88 lines
2.2 KiB
JavaScript

const ipp = require('ipp')
const express = require('express')
const bodyParser = require('body-parser')
// TODO:
// - multiple printers
// - take printer name, other params by query string
const PORT = Number(process.env.PRINTSERVANT_PORT) || 3199
const PRINTER_URL = process.env.PRINTSERVANT_IPP_PRINTER_URL
if (!(PORT && PRINTER_URL)) {
console.error("PRINTSERVANT_PORT and PRINTSERVANT_IPP_PRINTER_URL environment variables must be set")
process.exit(1)
}
const app = express()
const printer = ipp.Printer(PRINTER_URL)
app.get('/', (req, res) => {
res.send('Hello World! I am printservant.')
})
app.get('/api/1/health', (req, res) => {
res.send("I'm cool, I think. I'm not sure. Thanks for asking though.")
})
function executeSimpleCommand(command, res) {
printer.execute(command, null, function(error, result){
if (error) {
console.log(error);
res.status(500)
} else if (result.statusCode !== 'successful-ok') {
res.status(500)
}
res.send({ result, error })
});
}
app.get('/api/1/printer/attributes', (req, res) => {
console.log('Getting printer attributes')
executeSimpleCommand("Get-Printer-Attributes", res)
})
app.get('/api/1/printer/jobs', (req, res) => {
console.log('Getting printer jobs')
executeSimpleCommand("Get-Jobs", res)
})
app.post('/api/1/print', bodyParser.raw({ type: '*/*' }), (req, res) => {
const { body, query } = req
console.log("Received print job: ", { body, query })
if (!body || !body.length) {
res.status(400).send("No data received, please send a PDF")
return
}
const msg = {
"operation-attributes-tag": {
"document-format": "application/pdf",
},
"job-attributes-tag": {
// FIXME: This should work, but does not
// "copies": 2,
},
data: body
};
console.log("Sending print job: ", msg)
printer.execute("Print-Job", msg, function(error, result){
console.log({ result, error });
if (error) {
res.status(500)
} else if (result.statusCode !== 'successful-ok') {
res.status(400) // not sure, depends lol
}
res.send({ result, error })
});
})
app.listen(PORT, () => {
console.log(`printservant listening on port ${PORT}`)
})