const axios = require('axios');
const queryString = require('query-string');
const atob = require('atob')
const MAX_REDIRECTS = 10;
const landing_regex = /https:\/\/web\.epifany\.com\/([^?\/]*)($|\?(.*))/;
const new_regex = /https:\/\/web\.epifany\.com\/([^\/]*)\/new?[^#]*#(.*)/;
const redirectUrl = async (url) => {
const options = { method: 'GET', maxRedirects: 0 }
const result = await axios.request({ url, ...options }).then(_ => undefined).catch((error) => {
if (error.response.status === 301 || error.response.status === 302) {
return error.response.headers.location;
}
});
return result;
};
const evaluateUrl = async bar => {
const urls = [bar]
let newMatch = undefined;
let landingMatch = undefined;
let newUrl = bar
let i = 1;
do {
newUrl = await redirectUrl(newUrl);
if (newUrl !== undefined) {
urls.push(newUrl)
let match = newUrl.match(landing_regex);
if (match !== null) {
landingMatch = match;
}
newMatch = newUrl.match(new_regex);
i++;
}
} while (newUrl !== undefined && !newMatch && i < MAX_REDIRECTS);
const landingParams = landingMatch && queryString.parse(landingMatch[3]);
const newParams = newMatch && queryString.parse(newMatch[2]);
const result = {
landing: landingParams !== undefined,
urls,
email: {
requested: landingParams && landingParams['email'],
served: newParams && atob(newParams['id']),
},
major: {
requested: landingParams && landingParams['major'],
served: newParams && atob(newParams['major']),
},
type: {
requested: landingParams && landingParams['type'],
served: newParams && atob(newParams['type']),
},
};
return result;
};