syncthing-hooks/index.js

82 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-03-17 22:11:02 +01:00
const { fetchNewEvents } = require('./api');
2020-03-18 18:57:56 +01:00
const { collectHooks, runHook } = require('./hooks');
2020-03-17 22:11:02 +01:00
require('dotenv').config();
2020-03-18 00:30:56 +01:00
const state = {
seenIds: null,
mostRecentEventForFolder: null,
2020-03-18 18:57:56 +01:00
promisesForHooks: new Map(),
2020-03-18 00:30:56 +01:00
};
const getMostRecentEvents = (events, monitoredFolders) => {
const mostRecentEventForFolder = events
.filter(x => x.data && x.data.folder)
.filter(x => monitoredFolders.has(x.data.folder))
.reduce(
(acc, x) => {
const date = new Date(x.time);
const existingDate = acc[x.data.folder];
acc[x.data.folder] =
existingDate && existingDate > date ? existingDate : date;
return acc;
},
state.mostRecentEventForFolder
? { ...state.mostRecentEventForFolder }
: {}
);
state.mostRecentEventForFolder = mostRecentEventForFolder;
return mostRecentEventForFolder;
};
const convertRecentEventDatesToDelta = () => {
const now = new Date().getTime();
return Object.entries(state.mostRecentEventForFolder)
.map(([folder, date]) => [folder, now - date.getTime()])
.reduce((acc, [path, delta]) => {
acc[path] = delta;
return acc;
}, {});
};
2020-03-17 22:11:02 +01:00
setInterval(async () => {
const { events, seenIds } = await fetchNewEvents(state.seenIds);
2020-03-18 00:30:56 +01:00
const hooks = await collectHooks();
const monitoredFolders = new Set(hooks.map(x => x.folder));
const deltaForFolders =
getMostRecentEvents(events, monitoredFolders) &&
convertRecentEventDatesToDelta();
hooks
.filter(x => deltaForFolders[x.folder])
.forEach(hook => {
const timeToWait = hook.time - deltaForFolders[hook.folder];
2020-03-18 18:57:56 +01:00
console.log(`scheduled hook "${hook.path}" to run in ${timeToWait}ms`);
2020-03-18 00:30:56 +01:00
if (timeToWait < 0) {
2020-03-18 18:57:56 +01:00
const existingPromise = state.promisesForHooks[hook.path];
if (existingPromise) {
console.log(
`hook "${hook.path}" was skipped because it is already running`
);
} else {
delete state.mostRecentEventForFolder[hook.folder];
console.log(`running hook "${hook.path}"`);
const promise = runHook(hook);
state.promisesForHooks[hook.path] = promise;
promise
.then(() => {
console.log(`successfully ran hook "${hook.path}"`);
})
.catch(error => {
console.error(`failed to run hook "${hook.path}": ${error}`);
})
.finally(() => {
delete state.promisesForHooks[hook.path];
});
}
2020-03-18 00:30:56 +01:00
}
});
2020-03-17 22:11:02 +01:00
state.seenIds = seenIds;
2020-03-18 18:57:56 +01:00
}, 30000);