carvent/index.js

103 lines
3.6 KiB
JavaScript
Raw Normal View History

2023-02-24 23:09:16 +00:00
const SETTINGS = require("./settings.js")
const { churchtoolsClient, activateLogging, LOG_LEVEL_INFO, errorHelper } = require('@churchtools/churchtools-client');
const axiosCookieJarSupport = require('axios-cookiejar-support');
const tough = require('tough-cookie');
const fs = require('fs');
function initChurchToolsClient() {
churchtoolsClient.setCookieJar(axiosCookieJarSupport.wrapper, new tough.CookieJar());
churchtoolsClient.setBaseUrl(SETTINGS.BASEURL);
// Logging can be activated to either LOG_LEVEL_NONE (no logging at all, default),
// LOG_LEVEL_DEBUG (outputs every request and response including request/response data)
// LOG_LEVEL_INFO (outputs every request and response, but only method and URL) or
// LOG_LEVEL_ERROR (outputs only errors).
activateLogging(LOG_LEVEL_INFO);
}
//
function login() {
// if we have a login token, we use this
if (SETTINGS.TOKEN) {
churchtoolsClient.setUnauthorizedInterceptor(SETTINGS.TOKEN);
// we call /api/contactlabels here, as an example. Any api call will trigger an automatic login with TOKEN
return churchtoolsClient.get('/contactlabels')
.then(() => {
console.log('Login with token successful.');
return true;
});
}
// no login token => use username / password
return churchtoolsClient.post('/login', {
username: SETTINGS.USERNAME,
password: SETTINGS.PASSWORD
}).then(() => {
console.log('Login successful.');
return true;
});
}
async function mergeEventSongs(event) {
const dt = event.startDate
const date = dt.substring(0, dt.indexOf('T'))
try {
fs.mkdirSync(date)
} catch(e) { console.log(e); }
return churchtoolsClient.get(`/events/${event.id}/agenda`)
.then(agenda =>
agenda.items
.map(item => item.song)
.filter(Boolean)
).then(songs =>
songs.map(songItem =>
churchtoolsClient.get(`/songs/${songItem.songId}`)
.then(song => song.arrangements.find(a => a.id == songItem.arrangementId))
)
).then(result =>
Promise.allSettled(result)
).then(result =>
result.map(song => song.value.files.find(f => f.name.includes("Akkorde")))
.map(f =>
churchtoolsClient.get(f.fileUrl).then(file => {
filename = `${date}/${f.name}`
fs.createWriteStream(filename).write(file)
return filename
})
)
).then(result =>
Promise.allSettled(result)
).then(result => {
const PDFMerger = require('pdf-merger-js');
const merger = new PDFMerger();
return new Promise(async (resolve) => {
for(const file of result) {
await merger.add(file.value);
}
const merged = `${date}/${date}-songs-akkorde.pdf`
await merger.save(merged);
const mergedPdfBuffer = await merger.saveAsBuffer();
var data = new FormData();
data.append("files", [mergedPdfBuffer])
resolve(await churchtoolsClient.post(`/files/service/${event.id}`, data))
})
})
}
initChurchToolsClient();
login().then(() => {
churchtoolsClient.get('/whoami').then(whoAmI => {
console.log(`Hello ${whoAmI.firstName}!`);
});
return churchtoolsClient.get('/events')
}).then(events => {
const event = events[3];
return mergeEventSongs(event);
}).then(result => {
console.log(result)
}).catch(error => {
// getTranslatedErrorMessage returns a human readable translated error message
// from either a full response object, response data or Exception or Error instances.
console.error(errorHelper.getTranslatedErrorMessage(error));
});