require('dotenv').config();

const log = require('../utils/Log');
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const RateLimit = require('express-rate-limit');
const bodyParser = require('body-parser');
const jetpack = require('fs-jetpack');
const path = require('path');

const rateLimiter = new RateLimit({
	windowMs: parseInt(process.env.RATE_LIMIT_WINDOW, 10),
	max: parseInt(process.env.RATE_LIMIT_MAX, 10),
	delayMs: 0
});

class Server {
	constructor() {
		this.port = parseInt(process.env.SERVER_PORT, 10);
		this.server = express();
		this.server.set('trust proxy', 1);
		this.server.use(helmet());
		this.server.use(cors({ allowedHeaders: ['Accept', 'Authorization', 'Cache-Control', 'X-Requested-With', 'Content-Type', 'albumId'] }));
		this.server.use((req, res, next) => {
			// This bypasses the headers.accept for album download, since it's accesed directly through the browser.
			if ((req.url.includes('/api/album/') || req.url.includes('/zip')) && req.method === 'GET') return next();
			// This bypasses the headers.accept if we are accessing the frontend
			if (!req.url.includes('/api/') && req.method === 'GET') return next();
			if (req.headers.accept && req.headers.accept.includes('application/vnd.lolisafe.json')) return next();
			return res.status(405).json({ message: 'Incorrect `Accept` header provided' });
		});
		this.server.use(bodyParser.urlencoded({ extended: true }));
		this.server.use(bodyParser.json());
		// this.server.use(rateLimiter);

		// Serve the frontend if we are in production mode
		if (process.env.NODE_ENV === 'production') {
			this.server.use(express.static(path.join(__dirname, '..', '..', '..', 'dist')));
		}
		// Serve the uploads
		this.server.use(express.static(path.join(__dirname, '..', '..', '..', 'uploads')));

		this.routesFolder = path.join(__dirname, '..', 'routes');
	}

	registerAllTheRoutes() {
		jetpack.find(this.routesFolder, { matching: '*.js' }).forEach(routeFile => {
			const RouteClass = require(path.join('..', '..', '..', routeFile));
			let routes = [RouteClass];
			if (Array.isArray(RouteClass)) routes = RouteClass;
			for (const File of routes) {
				const route = new File();
				this.server[route.method](process.env.ROUTE_PREFIX + route.path, route.authorize.bind(route));
				log.info(`Found route ${route.method.toUpperCase()} ${process.env.ROUTE_PREFIX}${route.path}`);
			}
		});
	}

	start() {
		jetpack.dir('uploads/chunks');
		jetpack.dir('uploads/thumbs/square');
		this.registerAllTheRoutes();
		this.server.listen(this.port, () => {
			log.success(`Backend ready and listening on port ${this.port}`);
		});
	}
}

new Server().start();

@@ -1532,196 +1532,8 @@
 );%0A%0A
-%09%09// Serve the frontend if we are in production mode%0A%09%09if (process.env.NODE_ENV === 'production') %7B%0A%09%09%09this.server.use(express.static(path.join(__dirname, '..', '..', '..', 'dist')));%0A%09%09%7D%0A
 %09%09//
@@ -1551,16 +1551,16 @@
 uploads%0A
+
 %09%09this.s
@@ -1637,17 +1637,16 @@
 ds')));%0A
-%0A
 %09%09this.r
@@ -2238,16 +2238,747 @@
 %7D);%0A%09%7D%0A%0A
+%09serveNuxt() %7B%0A%09%09// Serve the frontend if we are in production mode%0A%09%09if (process.env.NODE_ENV === 'production') %7B%0A%09%09%09this.server.use(express.static(path.join(__dirname, '..', '..', '..', 'dist')));%0A%09%09%7D%0A%0A%09%09/*%0A%09%09%09For vue router to work with express we need this fallback.%0A%09%09%09After all the routes are loaded and the static files handled and if the%0A%09%09%09user is trying to access a non-mapped route we serve the website instead%0A%09%09%09since it has routes of it's own that don't work if accessed directly%0A%09%09*/%0A%09%09this.server.all('*', (_req, res) =%3E %7B%0A%09%09%09try %7B%0A%09%09%09%09res.sendFile(path.join(__dirname, '..', '..', '..', 'dist', 'index.html'));%0A%09%09%09%7D catch (error) %7B%0A%09%09%09%09res.json(%7B success: false, message: 'Something went wrong' %7D);%0A%09%09%09%7D%0A%09%09%7D);%0A%09%7D%0A%0A
 %09start()
@@ -3053,16 +3053,16 @@
 uare');%0A
-
 %09%09this.r
@@ -3080,24 +3080,44 @@
 heRoutes();%0A
+%09%09this.serveNuxt();%0A
 %09%09this.serve

Handle nuxt routes on page load