Skip to content

Commit

Permalink
Merge branch 'dev' into feature/new-frontend
Browse files Browse the repository at this point in the history
# Conflicts:
#	package-lock.json
#	package.json
  • Loading branch information
Frenkii committed Oct 22, 2023
2 parents 9377ba4 + e553577 commit 036fe67
Show file tree
Hide file tree
Showing 10 changed files with 367 additions and 58 deletions.
295 changes: 287 additions & 8 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
"jsonwebtoken": "^8.5.1",
"module-alias": "^2.2.2",
"mongoose": "^6.5.0",
"morgan": "1.10.0",
"point-in-polygon": "^1.1.0",
"winston": "3.11.0"
"point-in-polygon": "^1.1.0",
"primeflex": "^3.3.1",
"primeicons": "^6.0.1",
Expand All @@ -48,6 +51,7 @@
"@types/express": "^4.17.13",
"@types/jest": "^27.5.2",
"@types/jsonwebtoken": "^8.5.8",
"@types/morgan": "1.9.7",
"@types/node": "^18.6.2",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
Expand Down
17 changes: 8 additions & 9 deletions src/backend/app.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import Logger from '@dotfionn/logger';
import bodyparser from 'body-parser';
import cookieParser from 'cookie-parser';
import express from 'express';
import mongoose from 'mongoose';

import config from './config';
import logger from './logger';
import router from './router';
import cdmService from './services/cdm.service';
import ecfmpService from './services/ecfmp.service';

import errors from '@/shared/errors';

const logger = new Logger('vACDM:app');

(async () => {
logger.info('starting up');

if (!config().mongoUri) {
throw new Error('MONGO_URI has to be set!');
}

// TODO: default from mongoose7 will be false, needs to be checked
mongoose.set('strictQuery', true);
await mongoose.connect(config().mongoUri);

if (config().role == 'WORKER') {
Expand All @@ -30,7 +30,7 @@ const logger = new Logger('vACDM:app');
try {
await cdmService.cleanupPilots();
} catch (error) {
logger.error('error occurred when cleaning up pilots', error);
logger.error('error occurred when cleaning up pilots %o', error);
}
}, 10000);

Expand All @@ -49,10 +49,9 @@ const logger = new Logger('vACDM:app');
try {
await cdmService.cleanupUsers();
} catch (error) {
logger.error('error occurred when cleaning up users', error);
logger.error('error occurred when cleaning up users %o', error);
}
}, 6 * 60 * 60 * 1000); /* 6h */
console.log(6 * 60 * 60 * 1000);

// eslint-disable-next-line no-constant-condition
while (true) {
Expand All @@ -62,7 +61,7 @@ const logger = new Logger('vACDM:app');
try {
await cdmService.optimizeBlockAssignments();
} catch (error) {
logger.error('error occurred when optimizing block assignments', error);
logger.error('error occurred when optimizing block assignments %o', error);
}
}

Expand All @@ -89,7 +88,7 @@ const logger = new Logger('vACDM:app');
res: express.Response,
next: express.NextFunction,
) => {
console.log(err);
logger.warn(err);

if (err instanceof errors.APIError) {
return res.status(err.responseCode).json(err);
Expand All @@ -105,6 +104,6 @@ const logger = new Logger('vACDM:app');

const port = config().port;
app.listen(port, () => {
logger.info('listening on port', port);
logger.info('listening on port %d', port);
});
})();
10 changes: 10 additions & 0 deletions src/backend/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ interface VacdmConfig {
timeSinceLastLogin: number;
};

logging: {
levelConsole: string;
levelFile: string;
};

eventUrl: string;
eventPrio: number;
eventPullInterval: number;
Expand Down Expand Up @@ -62,6 +67,11 @@ export default function config(): VacdmConfig {
timeSinceLastLogin: Number(process.env.TIME_LAST_LOGIN || 48) * 60 * 60 * 1000,
},

logging: {
levelConsole: process.env.LOG_LEVEL_CONSOLE || 'http',
levelFile: process.env.LOG_LEVEL_FILE || 'info',
},

eventUrl: process.env.EVENT_URL || 'https://slots.vatsim-germany.org/api/events/',
eventPrio: Number(process.env.EVENT_PRIO) || 5,
eventPullInterval: Number(process.env.EVENT_PULL_INTERVAL || 5),
Expand Down
7 changes: 4 additions & 3 deletions src/backend/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextFunction, Request, Response } from 'express';

import logger from '../logger';
import authService from '../services/auth.service';

import { UserDocument } from './../models/user.model';
Expand All @@ -23,7 +24,7 @@ export async function authUser(
});

const user: UserDocument = await authService.getUserFromToken(response);
console.log('User is: ', user);
logger.debug('User is: %o', user);

if (user.vacdm.atc || user.vacdm.admin) {
return res.redirect('/atc');
Expand All @@ -42,7 +43,7 @@ export async function authUser(
export async function getProfile(
req: Request,
res: Response,
next: NextFunction,
// next: NextFunction,
) {
if (req.user) {
req.user.access_token = '';
Expand All @@ -54,7 +55,7 @@ export async function getProfile(
export async function logoutUser(
req: Request,
res: Response,
next: NextFunction,
// next: NextFunction,
) {
res.clearCookie('vacdm_token');
res.json({ success: true });
Expand Down
42 changes: 42 additions & 0 deletions src/backend/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import winston from 'winston';

import getConfig from './config';

const { logging } = getConfig();

const transports = [
new winston.transports.File({
filename: 'app.log',
level: logging.levelFile,
}),
new winston.transports.Console({
level: logging.levelConsole,
format: winston.format.colorize({ all: true }),
}),
];

const logger = winston.createLogger({
exitOnError: false,
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.splat(),
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`),
),
transports,
});

winston.addColors({
error: 'brightRed',
warn: 'yellow',
info: 'green',
http: 'magenta',
verbose: 'brightBlue',
debug: 'brightCyan',
silly: 'gray',
});

process.on('warning', e => logger.warn('%o', e));
process.on('uncaughtException', e => logger.error('%o', e));
process.on('unhandledRejection', e => logger.error('%o', e));

export default logger;
5 changes: 3 additions & 2 deletions src/backend/router.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { NextFunction, Request, Response, Router } from 'express';
import morgan from 'morgan';

import airportController from './controllers/airport.controller';
import authController from './controllers/auth.controller';
import flowController from './controllers/flow.controller';
import metaController from './controllers/meta.controller';
import miscController from './controllers/misc.controller';
import pilotController from './controllers/pilot.controller';
import logger from './logger';
import authMiddleware from './middleware/auth.middleware';
import requestloggerUtils from './utils/requestlogger.utils';

import { APIError } from '@/shared/errors';

const router = Router();

router.use(requestloggerUtils);
router.use(morgan('short', { stream: { write: m => logger.http(m.trim()) } }));

router.get('/version', metaController.getVersion);
router.get('/config', metaController.getPluginConfig);
Expand Down
8 changes: 3 additions & 5 deletions src/backend/services/bookings.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import Logger from '@dotfionn/logger';
import axios from 'axios';
import dayjs from 'dayjs';

import config from '../config';

const logger = new Logger('vACDM:services:booking');
import logger from '../logger';

let lastPull: Date | null = null;
let relevantBookings: any[] | null = null;
Expand Down Expand Up @@ -40,7 +38,7 @@ export async function getAllBookings() {

return relevantBookings;
} catch (e) {
console.log('error getting all bookings', e);
logger.warn('error getting all bookings %o', e);
throw e;
}
}
Expand All @@ -51,7 +49,7 @@ export async function pilotHasBooking(cid: number): Promise<boolean> {

return bookings.findIndex((b) => b.user === cid) != -1;
} catch (e) {
console.log('error checking if pilot has booking', cid, e);
logger.warn('error checking if pilot has booking %s %o', cid, e);
throw e;
}
}
Expand Down
15 changes: 6 additions & 9 deletions src/backend/services/cdm.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Logger from '@dotfionn/logger';
import dayjs from 'dayjs';

import config from '../config';
import logger from '../logger';
import pilotModel, { PilotDocument } from '../models/pilot.model';
import userModel from '../models/user.model';
import blockUtils from '../utils/block.utils';
Expand All @@ -12,10 +12,7 @@ import bookingsService from './bookings.service';
import datafeedService from './datafeed.service';
import pilotService from './pilot.service';



import { AirportCapacity } from '@/shared/interfaces/airport.interface';
const logger = new Logger('vACDM:services:cdm');

export function determineInitialBlock(pilot: PilotDocument): {
initialBlock: number;
Expand Down Expand Up @@ -183,11 +180,11 @@ export async function cleanupPilots() {
})
.exec();

logger.debug('pilotsToBeDeleted', pilotsToBeDeleted);
logger.debug('pilotsToBeDeleted %o', pilotsToBeDeleted);

for (const pilot of pilotsToBeDeleted) {
pilotService.deletePilot(pilot.callsign);
logger.debug('deleted inactive pilot', pilot.callsign);
logger.debug('deleted inactive pilot %o', pilot.callsign);
}

// deactivate long not seen pilots
Expand All @@ -202,7 +199,7 @@ export async function cleanupPilots() {
})
.exec();

logger.debug('pilotsToBeDeactivated', pilotsToBeDeactivated);
logger.debug('pilotsToBeDeactivated %o', pilotsToBeDeactivated);

for (const pilot of pilotsToBeDeactivated) {
pilot.inactive = true;
Expand All @@ -216,7 +213,7 @@ export async function cleanupPilots() {
},
});

logger.debug('deactivating pilot', pilot.callsign);
logger.debug('deactivating pilot %o', pilot.callsign);

await pilot.save();
}
Expand Down Expand Up @@ -325,7 +322,7 @@ export async function optimizeBlockAssignments() {
pilot.vacdm.delay -= (144 + pilot.vacdm.blockId - firstBlockId) % 144;
pilot.vacdm.blockId = firstBlockId;

console.log('==========>> setting pilot times', pilot.callsign);
logger.debug('==========>> setting pilot times %o', pilot.callsign);

await setTime(pilot);
}
Expand Down
22 changes: 0 additions & 22 deletions src/backend/utils/requestlogger.utils.ts

This file was deleted.

0 comments on commit 036fe67

Please sign in to comment.