89 lines
2.2 KiB
JavaScript
89 lines
2.2 KiB
JavaScript
// vim: set sw=2 ts=2 sts=2 et :
|
|
const fs = require('node:fs/promises');
|
|
const http = require('node:http');
|
|
const https = require('node:https');
|
|
const path = require('node:path');
|
|
|
|
const HANDLERS = {
|
|
'http': http,
|
|
'https': https,
|
|
}
|
|
|
|
async function get_token() {
|
|
const buf = await fs.readFile(
|
|
process.env['PAPERLESS_TOKEN_FILE'],
|
|
'utf-8',
|
|
);
|
|
return buf.trimEnd();
|
|
}
|
|
|
|
async function paperless_send(filepath) {
|
|
if (!'PAPERLESS_URL' in process.env) {
|
|
return
|
|
}
|
|
|
|
const filename = path.basename(filepath);
|
|
const boundary = `------------------------${Math.random() * 1e16}`;
|
|
const token = await get_token();
|
|
const options = {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
|
'Authorization': `Token ${token}`,
|
|
},
|
|
};
|
|
const url = new URL(
|
|
process.env['PAPERLESS_URL'] + '/api/documents/post_document/'
|
|
);
|
|
console.log('Uploading', filename, 'to', url.toString());
|
|
const handler = HANDLERS[url.protocol.slice(0, -1)];
|
|
const req = handler.request(url, options, (res) => {
|
|
console.log('Received HTTP status code', res.statusCode, 'from Paperless');
|
|
});
|
|
|
|
req.on('error', (e) => {
|
|
console.error(e);
|
|
});
|
|
|
|
const header = `--${boundary}\r\n` +
|
|
`Content-Disposition: form-data; name="document"; filename="${filename}"\r\n` +
|
|
`\r\n`
|
|
const trailer = `\r\n--${boundary}--\r\n`
|
|
const f = await fs.open(filepath);
|
|
const st = await f.stat();
|
|
const length = header.length + st.size + trailer.length;
|
|
req.setHeader('Content-Length', length.toString());
|
|
req.write(header)
|
|
while (1) {
|
|
const d = await f.read();
|
|
if (!d.bytesRead) {
|
|
break;
|
|
}
|
|
req.write(d.buffer.slice(0, d.bytesRead));
|
|
};
|
|
await f.close();
|
|
|
|
req.write(trailer);
|
|
req.end();
|
|
console.log('Upload complete');
|
|
}
|
|
|
|
module.exports = {
|
|
async afterScan(fileInfo) {
|
|
if (fileInfo.name.endsWith('.pdf')) {
|
|
await paperless_send(fileInfo.fullname);
|
|
}
|
|
},
|
|
|
|
afterDevices(devices) {
|
|
devices
|
|
.filter(d => d.id == 'escl:https://172.30.0.235:443')
|
|
.forEach(device => {
|
|
device.name = 'Canon PIXMA G7020';
|
|
device.features['-x'].limits = [0, 216];
|
|
device.features['-y'].limits = [0, 432];
|
|
device.features['-y'].default = 279.4;
|
|
});
|
|
}
|
|
}
|