Files
dwatcher/src/lib/watchers/wotwizard/json-watcher.ts
2023-09-29 13:28:41 +02:00

49 lines
1.3 KiB
TypeScript

import {Conf, ConfWWMeta} from "../../types/conf";
import {urlWatcher, UrlWatcherResult} from '../abstract/url-watcher'
import * as moment from 'moment'
function handleLateness(confHead: ConfWWMeta, data: WWMetaJson) {
const diff = Math.round(Date.now()/1000 - data.now)
if (diff >= confHead.maxLate) {
return UrlWatcherResult.ko(`WWData is late by ${diff}s (>= ${confHead.maxLate})`)
}
return UrlWatcherResult.ok()
}
export function jsonWatcher(conf: Conf) {
const URL_PATH = '/00wwView'
return async (confWWMeta: ConfWWMeta) => {
return urlWatcher(conf, async (html) => {
const data = parseData(html)
return handleLateness(confWWMeta, data)
})({
name: `WWData watcher ${confWWMeta.name}`,
address: confWWMeta.address + URL_PATH,
frequency: confWWMeta.frequency
},
() => `State OK WWMeta.json is up-to-date`,
() => `State FAILURE WWMeta.json`,
() => `State RECOVERED WWMeta.json`)
}
}
function parseData(html: string): WWMetaJson {
const h3 = html.match(/<h3>([\s\S]*)<\/h3>/)
if (!h3) {
throw `Could not parse H3 from WW`
}
const data = h3[1].match(/Bloc (\d+)\s(.+)\s(.+)/)
if (!data) {
throw `Could not parse datetime from H3`
}
const now = moment(`${data[2]}`, 'DD/MM/YYYY HH:mm:ss')
return { now: now.unix() }
}
interface WWMetaJson {
now: number
}