2018-04-08 23:21:50 +00:00
|
|
|
import { delay, requestIdleCallback } from "./Utils"
|
2018-04-08 11:31:58 +00:00
|
|
|
import StatusMessage from "./StatusMessage"
|
|
|
|
|
2018-07-07 15:44:24 +00:00
|
|
|
const newVersionCheckDelay = location.hostname === "notify.moe" ? 60000 : 3000
|
|
|
|
|
2018-04-08 11:31:58 +00:00
|
|
|
let etags = new Map<string, string>()
|
|
|
|
let hasNewVersion = false
|
|
|
|
|
2018-04-08 11:51:12 +00:00
|
|
|
async function checkNewVersion(url: string, statusMessage: StatusMessage) {
|
2018-04-08 11:31:58 +00:00
|
|
|
if(hasNewVersion) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2018-04-08 11:51:12 +00:00
|
|
|
let headers = {}
|
|
|
|
|
|
|
|
if(etags.has(url)) {
|
|
|
|
headers["If-None-Match"] = etags.get(url)
|
|
|
|
}
|
|
|
|
|
|
|
|
let response = await fetch(url, {
|
2018-07-06 16:10:34 +00:00
|
|
|
headers,
|
2018-07-06 16:10:46 +00:00
|
|
|
credentials: "omit"
|
2018-04-08 11:51:12 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// Not modified response
|
|
|
|
if(response.status === 304) {
|
|
|
|
return
|
|
|
|
}
|
2018-04-08 11:31:58 +00:00
|
|
|
|
|
|
|
if(!response.ok) {
|
2018-04-08 11:51:12 +00:00
|
|
|
console.warn("Error fetching", url, response.status)
|
2018-04-08 11:31:58 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let newETag = response.headers.get("ETag")
|
|
|
|
let oldETag = etags.get(url)
|
|
|
|
|
|
|
|
if(newETag) {
|
|
|
|
etags.set(url, newETag)
|
|
|
|
}
|
|
|
|
|
|
|
|
if(oldETag && newETag && oldETag !== newETag) {
|
|
|
|
statusMessage.showInfo("A new version of the website is available. Please refresh the page.", -1)
|
|
|
|
|
|
|
|
// Do not check for new versions again.
|
|
|
|
hasNewVersion = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} catch(err) {
|
|
|
|
console.warn("Error fetching", url + "\n", err)
|
2018-04-08 11:51:12 +00:00
|
|
|
} finally {
|
|
|
|
checkNewVersionDelayed(url, statusMessage)
|
2018-04-08 11:31:58 +00:00
|
|
|
}
|
2018-04-08 11:51:12 +00:00
|
|
|
}
|
2018-04-08 11:31:58 +00:00
|
|
|
|
2018-04-08 23:21:50 +00:00
|
|
|
export function checkNewVersionDelayed(url: string, statusMessage: StatusMessage) {
|
|
|
|
return delay(newVersionCheckDelay).then(() => {
|
|
|
|
requestIdleCallback(() => checkNewVersion(url, statusMessage))
|
|
|
|
})
|
2018-04-08 11:31:58 +00:00
|
|
|
}
|