bibliogram/src/site/api/instances.js

79 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-01-28 11:41:38 +00:00
const constants = require("../../lib/constants")
const {RequestCache} = require("../../lib/cache")
const {request} = require("../../lib/utils/request")
const {Parser} = require("../../lib/utils/parser/parser")
const instanceListCache = new RequestCache(constants.caching.instance_list_cache_time)
module.exports = [
{
route: "/api/instances", methods: ["GET"], code: () => {
return instanceListCache.getOrFetch("instances", () => {
return request(constants.resources.instances_wiki_raw).text().then(text => {
2020-01-28 11:41:38 +00:00
const result = (() => {
const instances = []
const parser = new Parser(text)
parser.seek("# Instance list", {moveToMatch: true, useEnd: true})
let inTable = false
while (!inTable && parser.hasRemaining()) {
parser.store()
const line = parser.get({split: "\n"})
if (line.startsWith("|")) {
inTable = true
parser.restore()
}
}
if (!parser.hasRemaining()) return null
while (parser.hasRemaining()) {
2020-01-28 11:41:38 +00:00
const line = parser.get({split: "\n"})
if (line.startsWith("|")) {
/** [empty, address, country, rss, privacy policy, cloudflare] */
2020-01-28 11:41:38 +00:00
const parts = line.split("|")
if (parts.length >= 6 && parts[1].includes("://")) {
2020-06-19 08:21:29 +00:00
let address = parts[1].trim().split(" ")[0]
let match
if (match = address.match(/^\[\S+\]\((\S+)\)$/)) address = match[1]
2020-01-28 11:41:38 +00:00
instances.push({
address,
country: parts[2].match(/[A-Z]{2,}|$/)[0] || null,
official: address === "https://bibliogram.art", // yeah we're just gonna hard code this
2020-05-17 12:29:01 +00:00
rss_enabled: parts[3].trim() !== "",
has_privacy_policy: parts[4].trim() !== "",
2020-06-19 08:21:29 +00:00
using_cloudflare: parts[5].trim() !== "",
onion_site: address.endsWith(".onion")
2020-01-28 11:41:38 +00:00
})
}
} else {
inTable = false
}
}
return instances
})()
if (Array.isArray(result) && result.length) {
2020-01-28 11:41:38 +00:00
return {
statusCode: 200,
contentType: "application/json",
content: {
status: "ok",
2020-06-19 08:21:29 +00:00
version: "2.1",
2020-01-28 11:41:38 +00:00
generatedAt: Date.now(),
data: result
}
}
} else {
return {
statusCode: 503,
contentType: "application/json",
content: {
status: "fail",
generatedAt: Date.now(),
2020-07-13 13:27:42 +00:00
message: `Unable to parse the table from the instances page at ${constants.resources.instances_wiki_raw}`
2020-01-28 11:41:38 +00:00
}
}
}
})
2020-07-29 12:12:19 +00:00
}).then(cacheResult => cacheResult.result)
2020-01-28 11:41:38 +00:00
}
}
]