mailtrain/server/services/tzupdate.js

52 lines
1.6 KiB
JavaScript
Raw Normal View History

2016-04-29 16:13:51 +00:00
'use strict';
2016-04-30 15:19:48 +00:00
// This script re-calculates timezone offsets once a day.
// We need this to be able to send messages using subscriber's local time
// The best option would be to use built-in timezone data of MySQL but
// the availability of timezone data is not guaranteed as it's an optional add on.
// So instead we keep a list of timezone offsets in a table that we can use to
// JOIN with subscription table. Subscription table includes timezone name for
// a subscriber and tzoffset table includes offset from UTC in minutes
2016-04-29 16:13:51 +00:00
2018-04-29 16:13:40 +00:00
const moment = require('moment-timezone');
const knex = require('../lib/knex');
2018-09-27 19:32:35 +00:00
const log = require('../lib/log');
2016-04-30 15:19:48 +00:00
let lastCheck = false;
const timezone_timeout = 60 * 60 * 1000;
2018-04-29 16:13:40 +00:00
async function updateTimezoneOffsets() {
2016-04-29 17:31:25 +00:00
log.verbose('UTC', 'Updating timezone offsets');
2018-04-29 16:13:40 +00:00
const values = [];
for (const tz of moment.tz.names()) {
values.push({
tz: tz.toLowerCase().trim(),
offset: moment.tz(tz).utcOffset()
2016-04-29 16:13:51 +00:00
});
2018-04-29 16:13:40 +00:00
}
2016-04-29 16:13:51 +00:00
2018-04-29 16:13:40 +00:00
await knex.transaction(async tx => {
await tx('tzoffset').del();
await tx('tzoffset').insert(values);
2016-04-29 16:13:51 +00:00
});
}
2018-04-29 16:13:40 +00:00
function start() {
let curUtcDate = new Date().toISOString().split('T').shift();
if (curUtcDate !== lastCheck) {
updateTimezoneOffsets()
.then(() => {
setTimeout(start, timezone_timeout)
})
.catch(err => {
log.error('UTC', err);
setTimeout(start, timezone_timeout);
});
} else {
setTimeout(start, timezone_timeout);
}
lastCheck = curUtcDate;
}
2019-05-25 19:18:18 +00:00
module.exports.start = start;