[enh] Watch ww and ww2 diff

This commit is contained in:
2019-08-31 17:43:29 +02:00
parent f71fe39271
commit 10925352ab
7 changed files with 130 additions and 16 deletions

View File

@@ -0,0 +1,90 @@
import {watcherLoop} from "../../watcherLoop";
import {Conf, ConfBMA, ConfWebDiff} from "../../types/conf";
import Axios from "axios";
import {mail} from "../../mail";
import {diffChars} from "diff";
import * as fs from "fs";
import * as path from "path";
import {moment} from "duniter/app/lib/common-libs/moment";
export function webDiffWatcher(conf: Conf) {
return async (webDiffConf: ConfWebDiff) => {
const target = `${webDiffConf.file1} <-> ${webDiffConf.file2}`
let nodeDownRes: () => void
let nodeDownPromise: Promise<void> = new Promise(res => nodeDownRes = res)
let htmlDiff = ''
function handleData(data1: { data: any }, data2: { data: any }) {
const json1 = JSON.stringify(data1.data, null, ' ')
const json2 = JSON.stringify(data2.data, null, ' ')
if (json1 !== json2) {
const diff = diffChars(json1, json2)
htmlDiff = ''
diff.forEach(function (part) {
// green for additions, red for deletions
// grey for common parts
const htmlStripped = part.value
.replace(/\n/g, '<br/>')
.replace(/ /g, '&nbsp;')
const color = part.added ? 'green' :
part.removed ? 'red' : 'grey';
htmlDiff += `<span style="color: ${color};">${htmlStripped}</span>`
});
if (htmlDiff) {
fs.writeFileSync(path.join(__dirname, 'diff.html'), htmlDiff, 'utf8')
}
console.log('Diff done')
}
}
await watcherLoop(
async () => {
const data1 = await Axios.get(webDiffConf.file1)
const data2 = await Axios.get(webDiffConf.file2)
handleData(data1, data2)
let interval = setInterval(async () => {
try {
const data1 = await Axios.get(webDiffConf.file1)
const data2 = await Axios.get(webDiffConf.file2)
handleData(data1, data2)
} catch (e) {
clearInterval(interval)
nodeDownRes()
// Re-create down promise for future connection trial
nodeDownPromise = new Promise(res => nodeDownRes = res)
}
}, webDiffConf.frequency)
},
() => nodeDownPromise,
conf.reconnectionDelays,
mail.onEstablished(conf, target, 'webdiff successfully started'),
// When a disconnection is detected
mail.onDisconnect(conf, target, 'Diff detected', (waitingDelay: number) => `
${htmlDiff}
<p>
Waiting ${(waitingDelay / 1000).toFixed(0)} seconds before trying to reconnect.
</p>
`),
async () => {
console.log('Trying to connect to %s', target)
},
mail.onRestartSuccess(conf, target),
async (e) => {
console.error(e.message)
}
)
}
}