1
0
mirror of https://git.sr.ht/~cadence/cloudtube synced 2024-12-22 05:06:57 +00:00

Refactor instance list fetcher

This commit is contained in:
Cadence Ember 2021-03-01 23:35:09 +13:00
parent 295fac6268
commit fd854ec222
No known key found for this signature in database
GPG Key ID: BC1C2C61CF521B17
2 changed files with 41 additions and 19 deletions

View File

@ -2,7 +2,7 @@ const {render, redirect} = require("pinski/plugins")
const db = require("../utils/db")
const {getToken, getUser} = require("../utils/getuser")
const constants = require("../utils/constants")
const {getInstances} = require("../background/instances")
const {instancesList} = require("../background/instances")
const validate = require("../utils/validate")
const V = validate.V
@ -11,7 +11,7 @@ module.exports = [
route: "/settings", methods: ["GET"], code: async ({req}) => {
const user = getUser(req)
const settings = user.getSettings()
const instances = getInstances()
const instances = instancesList.get()
return render(200, "pug/settings.pug", {constants, user, settings, instances})
}
},

View File

@ -1,23 +1,45 @@
const {request} = require("../utils/request")
let globalList = []
class InstancesList {
constructor() {
this.list = []
this.inflight = null
this.update()
setInterval(() => {
this.update()
}, 60*60*1000)
}
function execute() {
return request("https://api.invidious.io/instances.json?sort_by=health").then(res => res.json()).then(list => {
list = list.filter(i => i[1].type === "https").map(i => i[1].uri.replace(/\/+$/, ""))
globalList = list
}).catch(error => {
console.error(error)
})
/**
* Updates the list. Returns a promise of the new list. Called
* automatically.
*/
update() {
return this.inflight = request("https://api.invidious.io/instances.json?sort_by=health").then(res => res.json()).then(list => {
list = list.filter(i => i[1].type === "https").map(i => i[1].uri.replace(/\/+$/, ""))
this.list = list
this.inflight = null
return this.list
})
}
/**
* Return a promise of the list. If updates are in progress, wait
* for them.
*/
fetch() {
if (this.inflight) return this.inflight
else return Promise.resolve(this.list)
}
/**
* Return the current list, no matter whether it's been updated at all.
*/
get() {
return this.list
}
}
function getInstances() {
return globalList
}
const instancesList = new InstancesList()
execute()
setInterval(() => {
execute()
}, 60*60*1000)
module.exports.getInstances = getInstances
module.exports.instancesList = instancesList