Compare commits

...

1 commit

Author SHA1 Message Date
Erin 5104d3b568 apply patch "Rose's hubris" 2023-07-01 18:20:15 -04:00

View file

@ -1,30 +1,44 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import express from 'express'; import http from 'node:http';
const sites = fs.readFileSync('./webring.txt', 'utf-8')
// split lines
.split(/\r?\n/)
// trim whitespace from each line
.map(site => site.trim())
// exclude empty lines and lines that start with # because why not
.filter(site => site && !site.startsWith('#'));
// modulo that does the right thing with negatives
// https://stackoverflow.com/a/4467559
const mod = (n, m) => ((n % m) + m) % m; const mod = (n, m) => ((n % m) + m) % m;
const stripURL = s => s.replace(/(^https?:\/\/|\/$)/g, '')
function handle (offset, request, response) { const sitesArray = fs.readFileSync('./webring.txt', 'utf-8')
const from = request.query.from; .match(/(?<!#.*)https?:\/\/[^\s]+(?=\s*$)/gmi)
const index = sites.findIndex(site => site === from);
if (!from || index === -1) { const sitesLookup = sitesArray.map(stripURL).reduce((acc, current, index) => ({
response.status(400).send('the provided site is not in the webring'); ...acc, [current]: {
return; '/next': sitesArray[mod(index + 1, sitesArray.length)],
'/prev': sitesArray[mod(index - 1, sitesArray.length)],
} }
response.redirect(301, sites[mod(index + offset, sites.length)]); }), {})
const redirect = (response, url) => {
response.setHeader('Location', url)
response.statusCode = 301
response.end()
} }
express() const handle = (direction, from, response) => {
.get('/prev', (request, response) => handle(-1, request, response)) const destination = sitesLookup[stripURL(from)]?.[direction]
.get('/next', (request, response) => handle(+1, request, response))
.get('/list', (_, response) => response.type('txt').send(sites.join('\n'))) if (destination)
.listen(process.env.PORT || 8080); return redirect(response, destination)
response.statusCode = 400
response.end('the provided site is not in the webring')
}
http.createServer((request, response) => {
const url = new URL(request.url, `http://${request.headers.host}`);
if (url.pathname === '/prev' || url.pathname === '/next') {
return handle(url.pathname, url.searchParams.get('from'), response)
} else if (url.pathname === '/list') {
return response.setHeader('Content-Type', 'text/plain').end(sitesArray.join('\n'))
}
response.statusCode = 404
response.end('not found')
}).listen(process.env.PORT || 8080)