linkylinky/src/server.js

156 lines
4.3 KiB
JavaScript

const fastify = require('fastify')({ logger: true })
var uniqid = require('uniqid');
require('dotenv').config()
let config = {
domain: process.env.DOMAIN || "localhost:3000",
https: (process.env.SSL === 'true') || false,
recognizeProviders: true,
getBaseUrl(){
if(config.https){
return `https://${config.domain}`;
}
return `http://${config.domain}`;
}
}
const knex = require('knex')({
client: 'sqlite3',
connection: {
filename: "./dev.sqlite3"
}
});
//Basic home route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
//Automagic Amazn redirects on /a/
fastify.get('/a/:id', async (req, res) => {
res.redirect(302, `https://amazon.de/dp/${req.params.id}`)
})
//Automagic Youtube redirects on /yt/
fastify.get('/yt/:id', async (req, res) => {
res.redirect(302, `https://youtu.be/${req.params.id}`)
})
//Normal shorturls
fastify.get('/:shortcode', async (req, res) => {
const shortcode = req.params.shortcode;
//This should never happen but better safe than 500
if (!shortcode) {
return 404;
}
const target = await knex.select('target')
.from('urls')
.where('shortcode', '=', shortcode)
.limit(1);
if (!target[0]) {
return 404
}
res.redirect(302, target[0].target)
})
//Create new url schema
const newUrlSchema = {
body: {
type: 'object',
properties: {
target: { type: 'string' },
shortcode: { type: 'string' },
}
}
};
//Create new url route
fastify.post('/new', { newUrlSchema }, async (req, res) => {
const target = req.body?.target;
let shortcode = req.body?.shortcode;
//Check if the user provided a target
if (!target) {
res.statusCode = 400;
return "Missing target";
}
/**
* If no custom shortcode is provided: Check if a code for the target already exists.
* If it exists: No new get's generated => The existing code get's used.
* If it doesn't exist: Generate a new code and proceed to creating a new db entry.
*/
if (!shortcode) {
if(config.recognizeProviders){
const response = checkKnownProviders(target);
if(response){
return response;
}
}
const exists = await knex.select('shortcode')
.from('urls')
.where('target', '=', target)
.limit(1);
if (exists.length != 0) {
shortcode = exists[0].shortcode;
return {
url: `${config.getBaseUrl()}/${shortcode}`,
shortcode,
target
}
}
shortcode = uniqid();
}
/**
* If a custom shortcode is provided: Check for collisions.
* Collision detected: Warn user
* No collision: Proceed to db entry creation
*/
else {
const exists = await knex.select('shortcode')
.from('urls')
.where('shortcode', '=', shortcode)
.limit(1);
if (exists.length != 0) {
res.statusCode = 400;
return "Shortcode already exists, please choose another code";
}
}
//Create a new db entry
await knex('urls').insert({target, shortcode});
return {
url: `${config.getBaseUrl()}/${shortcode}`,
shortcode,
target
}
});
/**
* Checks for some default providers with custom url schemes (amazon and youtube r/n)
* @param {string} target The target URL
* @returns Standard shortening response if provider recognized or null
*/
function checkKnownProviders(target){
if(/^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/.test(target)){
const shortcode = `yt/${target.match(/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/)[1]}`
return {
url: `${config.getBaseUrl()}/${shortcode}`,
shortcode,
target
}
}
}
// Run the server!
const start = async () => {
try {
await fastify.listen(3000)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()