1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-24 10:27:10 +02:00
joplin/ReactNativeClient/lib/ntpDate.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

const ntpClient = require('lib/vendor/ntp-client');
const Logger = require('lib/Logger').default;
const Mutex = require('async-mutex').Mutex;
2020-09-09 01:34:27 +02:00
let nextSyncTime = 0;
let timeOffset = 0;
2020-09-09 11:56:17 +02:00
let logger = new Logger();
const fetchingTimeMutex = new Mutex();
const server = {
domain: 'pool.ntp.org',
port: 123,
};
async function networkTime():Promise<Date> {
return new Promise(function(resolve:Function, reject:Function) {
ntpClient.getNetworkTime(server.domain, server.port, function(error:any, date:Date) {
if (error) {
reject(error);
return;
}
resolve(date);
});
});
}
function shouldSyncTime() {
2020-09-09 01:34:27 +02:00
return !nextSyncTime || Date.now() > nextSyncTime;
}
2020-09-09 11:56:17 +02:00
export function setLogger(v:any) {
logger = v;
}
export default async function():Promise<Date> {
if (shouldSyncTime()) {
const release = await fetchingTimeMutex.acquire();
try {
if (shouldSyncTime()) {
const date = await networkTime();
2020-09-09 01:34:27 +02:00
nextSyncTime = Date.now() + 60 * 1000;
timeOffset = date.getTime() - Date.now();
}
2020-09-09 01:34:27 +02:00
} catch (error) {
2020-09-09 11:56:17 +02:00
logger.warn('Could not get NTP time - falling back to device time:', error);
// Fallback to device time since
2020-09-09 01:34:27 +02:00
// most of the time it's actually correct
nextSyncTime = Date.now() + 20 * 1000;
timeOffset = 0;
} finally {
release();
}
}
return new Date(Date.now() + timeOffset);
}