Skip to content

Instantly share code, notes, and snippets.

@tigattack
Last active March 16, 2025 22:55
Show Gist options
  • Save tigattack/9c5910781618ae0dee74d1054e88e1b3 to your computer and use it in GitHub Desktop.
Save tigattack/9c5910781618ae0dee74d1054e88e1b3 to your computer and use it in GitHub Desktop.
scanservjs Paperless-ngx recipe. Thanks to @chkpwd for initial version & bulk of the work on this.
const options = { paths: ['/usr/lib/scanservjs'] };
const fs = require(require.resolve('fs', options));
const { Blob } = require(require.resolve('buffer'), options);
const PAPERLESS_DELETE_AFTER_UPLOAD = process.env.PAPERLESS_DELETE_AFTER_UPLOAD || false
// Must be tag ID, not name.
const PAPERLESS_DOCUMENT_TAG_IDS = process.env.PAPERLESS_DOCUMENT_TAG_IDS || null
module.exports = {
afterConfig(config) {
const paperlessPipeline = [
{
extension: 'pdf',
description: 'PDF | Scan to Paperless',
commands: [
'convert @- -quality 92 converted-$(date +%s.%N).jpg && ls converted-*.jpg',
`convert @- -quality 96 scan_paperless-0000.pdf`,
`ls scan_paperless-*.*`
],
afterAction: 'Upload to Paperless'
}
];
// Insert Paperless pipeline at the top of the list
config.pipelines.splice(0, 0, ...paperlessPipeline);
// Debug logging
// config.log.level = 'DEBUG';
},
actions: [
{
name: 'Upload to Paperless',
async execute(fileInfo) {
if (!process.env.PAPERLESS_URL) {
throw new Error('Missing PAPERLESS_URL');
}
if (!process.env.PAPERLESS_API_TOKEN) {
throw new Error('Missing PAPERLESS_API_TOKEN');
}
const buffer = await fs.promises.readFile(fileInfo.fullname);
const blob = new Blob([buffer]);
const formData = new FormData();
formData.append('document', blob, fileInfo.name);
if (PAPERLESS_DOCUMENT_TAG_IDS) {
const tag_ids = PAPERLESS_DOCUMENT_TAG_IDS.split(",")
tag_ids.forEach(tag => formData.append('tags', tag))
}
// Errors aren't shown in the frontend. Would be nice if they were.
// Tried throw and return (both str & false), didn't work.
// Probably need to patch "app-server/src/scan-controller.js:116" upstream.
return fetch(`${process.env.PAPERLESS_URL}/api/documents/post_document/`, {
method: 'POST',
headers: {
'Authorization': `Token ${process.env.PAPERLESS_API_TOKEN}`,
},
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error(`Response did not return a successful status: ${response.statusText}`);
}
console.log(`Uploaded ${fileInfo.name} to Paperless successfully.`);
if (PAPERLESS_DELETE_AFTER_UPLOAD) {
fs.unlink(fileInfo.fullname,
(err => {
if (err) console.log(err);
else { console.log(`\nDeleted file: ${fileInfo.name}`); }
}));
}
return response.json();
})
.then(result => {
return result;
})
.catch(error => {
console.error('Error uploading document to Paperless:', error.message);
});
}
}
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment