lbry-desktop/lbrytv/middleware/redirect.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-11-07 20:39:22 +01:00
const config = require('../../config');
const PAGES = require('../../ui/constants/pages');
2019-11-07 20:39:22 +01:00
async function redirectMiddleware(ctx, next) {
const requestHost = ctx.host;
const path = ctx.path;
const url = ctx.url;
2019-11-11 19:19:31 +01:00
if (path.endsWith('/') && path.length > 1) {
2019-11-07 20:39:22 +01:00
ctx.redirect(url.replace(/\/$/, ''));
return;
}
if (!path.startsWith('/$/') && path.match(/^([^@/:]+)\/([^:/]+)$/)) {
ctx.redirect(url.replace(/^([^@/:]+)\/([^:/]+)(:(\/.*))/, '$1:$2')); // test against path, but use ctx.url to retain parameters
return;
}
if (requestHost === 'open.lbry.com') {
let redirectUrl = config.URL;
const openQuery = '?src=open';
const matches = /(\/\?)([a-z]*)(.*)/.exec(url);
if (matches && matches.length) {
[, , page, queryString] = matches;
// This is a lbry app page. Make sure to add the leading `/$/`
if (page && Object.values(PAGES).includes(page)) {
redirectUrl += '/$/' + page;
}
redirectUrl += openQuery + queryString;
} else {
redirectUrl += path + openQuery;
}
2019-11-07 20:39:22 +01:00
ctx.redirect(redirectUrl);
return;
}
// No redirects needed
await next();
}
module.exports = redirectMiddleware;