lts-stats-api/app/controllers/sessionsController.js

210 lines
6.8 KiB
JavaScript
Raw Permalink Normal View History

2023-01-06 00:58:55 +01:00
const moment = require('moment');
2023-09-09 18:24:57 +02:00
const { getUserFromReferenceTable, getAllUsersFromReferenceTable } = require('../db/mongo/mongoPilots');
const { getSessions, updateSessionCalculatedTime, getSessionsTotalCalculatedTimeByPilot } = require('../db/mongo/mongoSessions');
const { getSessionTracks, updateSessionTracks, insertOneSessionTracks } = require('../db/mongo/mongoSessionTracks');
2023-01-06 19:12:43 +01:00
const { RedisClient } = require('../db/redis/redis');
2023-01-15 18:42:26 +01:00
const { getHistoricalSessions, getIvaoSessionTracks, getIvaoPilotsNow, getIvaoLatestSessionFlightPlan, getIvaoSessionLatestTrack } = require('../requests/ivao/session');
const { getAirTime } = require('./trackerAnalizer');
2023-01-06 00:58:55 +01:00
async function getTodaySessionsFromIvao(callsign, incompletes) {
const from = moment().utc().startOf('day').format();
const to = moment().utc().endOf('day').format();
const params = {
callsign,
from,
to,
};
const data = await getHistoricalSessions(params);
if (!incompletes) {
return data.filter(d => d.isCompleted);
}
return data;
}
2023-01-06 19:12:43 +01:00
async function checkUsername(user, key, usersList) {
2023-01-06 00:58:55 +01:00
const u = {...user };
if (!u.name) {
2023-01-06 19:12:43 +01:00
const ref1 = await getUserFromReferenceTable(key) || {};
2023-09-09 18:24:57 +02:00
const ref2 = (usersList || []).find(d => key === d.vid) || {};
2023-01-06 19:12:43 +01:00
let ref;
if (ref2.name) {
ref = ref2;
if (!ref1.name) {
// TODO: update mongo
}
} else if (ref1.name) {
ref = ref1
}
2023-01-06 00:58:55 +01:00
if (ref) {
u.name = ref.name;
} else {
console.log(`Couldn't find info for ${key}`);
}
}
return u;
}
2023-01-06 19:12:43 +01:00
async function getWhitelist() {
const redisUsers = await RedisClient.getPair('users_whitelist');
return redisUsers.sort((a, b) => b.flightTime - a.flightTime);
}
2023-09-09 18:24:57 +02:00
async function getSessionCalculatedTime(session) {
const sessionId = session.id;
2023-01-15 18:42:26 +01:00
let tracks = await getSessionTracks(sessionId);
2023-09-09 18:24:57 +02:00
let calculatedTime;
2023-01-15 18:42:26 +01:00
if (tracks && !Number.isInteger(tracks.calculatedTime)) {
2023-09-09 18:24:57 +02:00
calculatedTime = getAirTime(tracks);
tracks.calculatedTime = calculatedTime;
try {
await updateSessionTracks(tracks);
} catch (err) {
console.log('Error updateSessionTracks');
}
2023-01-15 18:42:26 +01:00
} else if (!tracks) {
const t = await getIvaoSessionTracks(sessionId);
2023-09-09 18:24:57 +02:00
calculatedTime = getAirTime(t);
2023-01-15 18:42:26 +01:00
tracks = {
sessionId,
tracks: t,
2023-09-09 18:24:57 +02:00
calculatedTime,
2023-01-15 18:42:26 +01:00
};
2023-09-09 18:24:57 +02:00
try {
await insertOneSessionTracks(tracks);
} catch (err) {
console.log('Error insertOneSessionTracks');
}
2023-01-15 18:42:26 +01:00
}
2023-09-09 18:24:57 +02:00
await setSessionCalculatedTime(session, tracks, calculatedTime);
2023-01-15 18:42:26 +01:00
return tracks.calculatedTime;
}
2023-09-09 18:24:57 +02:00
async function setSessionCalculatedTime(session, tracks, calculatedTime) {
if (!Number.isInteger(session.calculatedTime)) {
session.calculatedTime = calculatedTime ? calculatedTime : tracks.calculatedTime;
await updateSessionCalculatedTime(session);
}
}
function obfuscate(name, isAuthenticated, from = 1) {
if (isAuthenticated) {
return name;
}
if (typeof name === 'undefined') {
return '';
}
const arr = name.split(' ');
const obfuscated = arr.map((token, i) => {
if (i < from) {
return token;
}
const xs = Array.apply(null, Array(token.length ? token.length - 1 : 0)).map(() => '*');
return token.charAt(0).toUpperCase() + xs.join('');
});
return obfuscated.join(' ');
}
async function getList(callsign, isAuthenticated) {
2023-01-15 18:42:26 +01:00
const from = moment().startOf('month').format('YYYY-MM-DD');
const to = moment().subtract(1, 'day').endOf('day').format('YYYY-MM-DD');
2023-01-06 00:58:55 +01:00
const todayData = await getTodaySessionsFromIvao(callsign);
const monthData = await getSessions(from, to);
const allData = [...todayData, ...monthData];
2023-01-06 19:12:43 +01:00
const redisUsers = await RedisClient.getPair('users');
2023-01-15 18:42:26 +01:00
const totalsByUserId = {};
2023-01-06 00:58:55 +01:00
2023-01-15 18:42:26 +01:00
for (let index = 0; index < allData.length; index++) {
const session = allData[index];
const userId = session.userId;
const flightPlan = session.flightPlans[session.flightPlans.length - 1];
const date = moment(session.completedAt);
2023-09-09 18:24:57 +02:00
const calculated = await getSessionCalculatedTime(session);
2023-01-15 18:42:26 +01:00
if (!totalsByUserId[userId]) {
totalsByUserId[userId] = {
2023-01-06 00:58:55 +01:00
time: 0,
2023-01-15 18:42:26 +01:00
flights: 0,
sessionsTime: 0,
2023-01-06 00:58:55 +01:00
};
}
2023-01-15 18:42:26 +01:00
totalsByUserId[userId].time += calculated;
totalsByUserId[userId].sessionsTime += session.time || 0;
totalsByUserId[userId].flights++;
2023-01-06 00:58:55 +01:00
2023-01-15 18:42:26 +01:00
if (!totalsByUserId[userId].lastFlight || date.isAfter(totalsByUserId[userId].lastFlightDate)) {
totalsByUserId[userId].lastFlight = {...flightPlan };
totalsByUserId[userId].lastFlightDate = date;
totalsByUserId[userId].lastCallsign = session.callsign;
2023-01-06 00:58:55 +01:00
2023-01-15 18:42:26 +01:00
delete totalsByUserId[userId].lastFlight.id;
if (session.user.firstName) {
totalsByUserId[userId].name = `${session.user.firstName} ${session.user.lastName || ''}`;
2023-01-06 00:58:55 +01:00
}
2023-01-15 18:42:26 +01:00
totalsByUserId[userId].division = session.user.divisionId;
2023-01-06 00:58:55 +01:00
}
2023-01-15 18:42:26 +01:00
}
2023-01-06 00:58:55 +01:00
const array = [];
for (const key in totalsByUserId) {
if (Object.hasOwnProperty.call(totalsByUserId, key)) {
2023-01-06 19:12:43 +01:00
const user = await checkUsername(totalsByUserId[key], key, redisUsers);
2023-01-06 00:58:55 +01:00
user.vid = key;
2023-09-09 18:24:57 +02:00
user.name = obfuscate(user.name, isAuthenticated);
2023-01-06 00:58:55 +01:00
array.push(user);
}
}
2023-01-15 18:42:26 +01:00
return array.filter(d => d.time > 0);
}
2023-01-06 00:58:55 +01:00
2023-01-15 18:42:26 +01:00
async function getLatestSessions() {
return await getIvaoPilotsNow();
}
async function getLatestsFlightPlans() {
const sessionsNow = await getLatestSessions();
const response = [];
for (let index = 0; index < sessionsNow.length; index++) {
const session = sessionsNow[index];
const sessionFlightplan = await getIvaoLatestSessionFlightPlan(session.id);
const track = await getIvaoSessionLatestTrack(session.id);
const fplan = {};
fplan.sessionId = session.id;
fplan.callsign = session.callsign;
fplan.arrival = sessionFlightplan.arrival;
fplan.departure = sessionFlightplan.departure;
fplan.departureTime = sessionFlightplan.departureTime;
fplan.eet = sessionFlightplan.eet;
fplan.eta = track.groundSpeed === 0 ? 0 : Math.round((track.arrivalDistance / track.groundSpeed) * 3600);
fplan.arrivalDistance = track.arrivalDistance;
fplan.groundSpeed = track.groundSpeed;
response.push(fplan);
}
return response;
2023-01-06 00:58:55 +01:00
}
2023-09-09 18:24:57 +02:00
async function getPilotInfoInTime(req) {
const { start, end } = req.params;
const redisUsers = await RedisClient.getPair('users');
const pilots = await getAllUsersFromReferenceTable();
const data = await getSessionsTotalCalculatedTimeByPilot(start, end);
for (let index = 0; index < data.length; index++) {
const row = data[index];
const user = (redisUsers || pilots).find(d => Number(d.vid) === row._id) || { name: '657396' };
user.name = obfuscate(user.name, req.isAuthenticated());
row.user = user;
}
return data.sort((a, b) => b.time - a.time);
}
2023-01-06 00:58:55 +01:00
module.exports = {
getList,
2023-01-06 19:12:43 +01:00
getWhitelist,
2023-01-15 18:42:26 +01:00
getLatestSessions,
getLatestsFlightPlans,
2023-09-09 18:24:57 +02:00
getPilotInfoInTime,
2023-01-06 00:58:55 +01:00
};