This commit is contained in:
2023-10-19 01:50:10 +02:00
parent b37d5417b7
commit 428b042fe9
3 changed files with 63 additions and 52 deletions

View File

@@ -1,11 +1,4 @@
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js', {
type: 'module'
})
.then(() => console.log('sw ok'))
.catch(() => console.log('sw not ok'))
}
const storageType = 'sessionStorage'
var data = {}
@@ -14,8 +7,8 @@ const formEl = document.getElementById('search')
// Register event listeners
formEl.addEventListener('submit', (event) => {
event.preventDefault()
if ('instances' in data && data.instances.length > 0) {
event.preventDefault()
// Random instance
const n = Math.floor(Math.random() * data.instances.length)
const instanceURL = data.instances[n]
@@ -28,15 +21,53 @@ formEl.addEventListener('submit', (event) => {
}
})
// Fetch data
await fetch('./data.json')
.then(req => req.json())
.then(newData => { data = newData })
.then(() => {
infoEl.textContent = `${data.instances.length} instances`
})
.catch(err => {
console.error(err)
infoEl.textContent = err.toString()
infoEl.classList.add('error')
})
function locallyGetInstances () {
if (!(storageType in window)) return []
const item = window[storageType].getItem('instances')
try {
return JSON.parse(item)
} finally {
return []
}
}
function locallySetInstances () {
if (!(storageType in window)) return
if (!('instances' in data)) return
if (data.instances.length === 0) return
window[storageType].setItem(
'instances',
JSON.stringify(data.instances)
)
}
async function remotelyGetInstances () {
const instances = await fetch('https://searx.space/data/instances.json')
.then((req) => req.json())
.then((json) => Object.entries(json.instances))
.then((entries) => entries.filter(([_url, details]) => {
if (details.network_type !== 'normal') return
if (details.uptime.uptimeDay !== 100) return
return true
}))
.then((entries) => entries.map(([url]) => url))
.catch((err) => {
console.error(err)
return []
})
return instances
}
data.instances = locallyGetInstances()
const remoteInstances = await remotelyGetInstances()
if (remoteInstances.length > 0) {
data.instances = remoteInstances
locallySetInstances()
}
if (data.instances.length > 0) {
infoEl.textContent = `${data.instances.length} instances`
} else {
infoEl.classList.add('error')
infoEl.textContent = '0 instances'
}