Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active October 2, 2018 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/d8891a6c2108bf1f86bb0cc0988287ea to your computer and use it in GitHub Desktop.
Save Noitidart/d8891a6c2108bf1f86bb0cc0988287ea to your computer and use it in GitHub Desktop.
/**
* Returns UNIX time in milliseconds.
*/
async function fetchUTC({
timeout = 10000,
shouldCompensate = true // subtracts half of the xhr request time from the time extracted from page
}={}) {
const servers = [
{
name: 'trigger-community',
fetchArgs: [
'https://trigger-community.sundayschoolonline.org/unixtime.php'
],
getUTCFromResponse: async res => {
if (res.status !== 200) throw `Unhandled Status (${res.status})`;
const replyJSON = await res.json();
const utc = replyJSON.unixtime * 1000;
return utc;
}
},
{
name: 'CurrentTimestamp.com',
fetchArgs: [
'http://currenttimestamp.com/'
],
getUTCFromResponse: async res => {
if (res.status !== 200) throw new Error(`Unhandled Status (${res.status})`);
const replyHTML = await res.text();
const utcMatch = /current_time = (\d+);/.exec(replyHTML);
if (!utcMatch) throw new Error('Extraction Failed');
const utc = utcMatch[1] * 1000;
return utc;
}
},
{
name: 'convert-unix-time.com',
fetchArgs: [
'http://convert-unix-time.com/'
],
getUTCFromResponse: async res => {
if (res.status !== 200) throw `Unhandled Status (${res.status})`;
const replyHTML = await res.text();
const utcMatch = /currentTimeLink.*?(\d{10,})/.exec(replyHTML);
if (!utcMatch) throw new Error('Extraction Failed');
const utc = utcMatch[1] * 1000;
return utc;
}
}
];
const errors = [];
for (const { fetchArgs, name, getUTCFromResponse } of servers) {
try {
const fetchStart = Date.now();
const res = await Promise.race([
fetch(...fetchArgs),
new Promise((_, reject) => setTimeout(()=>reject('Timed Out'), timeout))
]);
const fetchDuration = Date.now() - fetchStart;
const fetchDurationHalf = Math.round(fetchDuration / 2);
let utc = await getUTCFromResponse(res);
if (shouldCompensate) utc -= fetchDurationHalf;
return utc;
} catch(err) {
errors.push(`Server "${name}" Error: ${err.message}`);
}
}
throw new Error(errors.join('\n'));
}
fetchUTC().then(console.log).catch(console.warn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment