BangleApps/apps/ftclock/mkFourTwentyTz.js

75 lines
2.5 KiB
JavaScript

let fs = require('fs');
let csv = require('csv');
let countries = {},
zones = {},
offsdict = {},
now = Date.now(); // we need this to find zone's current DST state
function handleWrite(err,bytes) {
if (err) {
console.log(`Error writing to file ${err}`);
}
}
console.log("Generating fourTwentyTz.js...");
fs.createReadStream(__dirname+'/country.csv')
.pipe(csv.parse())
.on('data', (r) => {
countries[r[0]] = r[1];
})
.on('end', () => {
fs.createReadStream(__dirname+'/zone.csv')
.pipe(csv.parse())
.on('data', (r) => {
let parts = r[2].replace('_',' ').split('/');
let city = parts[parts.length-1];
let country ='';
if (parts.length>2) { // e.g. America/North_Dakota/New_Salem
country = parts[1]; // e.g. North Dakota
} else {
country = countries[r[1]]; // e.g. United States
}
zones[parseInt(r[0])] = {"name": `${city}, ${country}`};
})
.on('end', () => {
fs.createReadStream(__dirname+'/timezone.csv')
.pipe(csv.parse())
.on('data', (r) => {
code = parseInt(r[0]);
if (!(code in zones)) return;
starttime = parseInt(r[2] || "0"); // Bugger. They're feeding us blanks for UTC now
offs = parseInt(r[3]);
if (offs<0) {
offs += 60*60*24;
}
zone = zones[code];
if (starttime<now && (!("starttime" in zone) || zone.starttime<starttime)) {
zone.starttime = starttime;
zone.offs = Math.floor(offs/60);
}
})
.on('end', () => {
for (z in zones) {
zone = zones[z];
if (zone.offs%60) continue; // One a dem funky timezones. Ignore.
zonelist = offsdict[zone.offs] || [];
zonelist.push(zone.name);
offsdict[zone.offs] = zonelist;
}
fs.open("fourTwentyTz.js","w", (err, fd) => {
if (err) {
console.log("Can't open output file");
return;
}
fs.write(fd, "// Generated by mkFourTwentyTz.js\n", handleWrite);
fs.write(fd, `// ${Date()}\n`, handleWrite);
fs.write(fd, "// Data source: https://timezonedb.com/files/timezonedb.csv.zip\n", handleWrite);
fs.write(fd, "exports.timezones = ", handleWrite);
fs.write(fd, JSON.stringify(offsdict, null, 4), handleWrite);
console.log('Done.');
});
})
})
});