latest changes and fixes

This commit is contained in:
José Conde 2023-09-09 18:24:57 +02:00
parent 15f012530e
commit ed51c02ddc
18 changed files with 470 additions and 132 deletions

1
.gitignore vendored
View File

@ -5,4 +5,5 @@ node_modules
.env.local
.env.*.local
testData/
test.js
.notes

View File

@ -1 +1,23 @@
# README
# README
## Env properties
- **PORT**: `3000`
- **IVAO_APIKEY**: Airline's IVAO API Key
- **TOKEN_AIRPORTDB**: AirportDB API Key
- **MONGO_HOST**: MongoDB host IP or domain name
- **MONGO_PORT**: MongoDB port
- **MONGO_USER**: MongoDB user
- **MONGO_PASS**: MongoDB password
- **MONGO_DB**: MongoDB database name
- **LSA_MYSQL_HOST**: 167.114.57.177
- **LSA_MYSQL_PORT**: 3306
- **LSA_MYSQL_USER**: latinstr_arhuako
- **LSA_MYSQL_PASS**: 7iNuE[Fbwopi
- **LSA_MYSQL_DB**: latinstr_crew
- **LSA_MYSQL_CONN_LIMIT**: 20
- **HOSTS_WHITELIST**: Hosts CORS whitelist
- **REDIS_HOST**: Redis IP or domain name
- **EXECUTE_TASKS_ON_START**: `false`
- **SYNC_TASK_SCHEDULE**: `'10 3 * * *'`
- **USERS_TASK_SCHEDULE**: `'* * */1 * *'`

View File

@ -0,0 +1,18 @@
const { RedisClient } = require('../db/redis/redis');
const USER_POSITION_DATA = 'user_position_data';
function updatePosition(req) {
RedisClient.setPair(USER_POSITION_DATA, JSON.stringify([req.body]));
}
async function getPosition() {
const data = await RedisClient.getPair(USER_POSITION_DATA);
return data;
}
module.exports = {
updatePosition,
getPosition,
};

View File

@ -2,9 +2,10 @@ const moment = require('moment');
const bcrypt = require('bcryptjs');
const crypto = require("crypto");
const { insertSessions, insertSessionTracks } = require("../db/mongo/mongoSessions");
const { createUserMongo, getUserMongo } = require('../db/mongo/mongoUsers');
const { insertSessions } = require("../db/mongo/mongoSessions");
const { createUserMongo, getUserMongo, updateUserHash } = require('../db/mongo/mongoUsers');
const { getHistoricalSessions, getIvaoSessionTracks } = require("../requests/ivao/session");
const { insertSessionTracks } = require('../db/mongo/mongoSessionTracks');
const saltRounds = 10;
@ -80,10 +81,22 @@ async function authenticate(username, password) {
}
}
async function changePassword(req) {
const { username } = req.user;
const { currentPassword, newPassword } = req.body;
console.log('currentPassword, newPassword :>> ', currentPassword, newPassword);
const user = await getUserMongo(username);
if (bcrypt.compareSync(currentPassword, user.hash)) {
const newHash = getHashedPassword(newPassword);
return await updateUserHash(user.id, newHash);
} else {
throw new Error('wrong-password');
}
}
module.exports = {
initSessionsData,
createUser,
authenticate,
getHashedPassword,
changePassword,
}

View File

@ -1,6 +1,7 @@
const moment = require('moment');
const { getUserFromReferenceTable } = require('../db/mongo/mongoPilots');
const { getSessions, getSessionTracks, updateSessionTracks, insertOneSessionTracks } = require('../db/mongo/mongoSessions');
const { getUserFromReferenceTable, getAllUsersFromReferenceTable } = require('../db/mongo/mongoPilots');
const { getSessions, updateSessionCalculatedTime, getSessionsTotalCalculatedTimeByPilot } = require('../db/mongo/mongoSessions');
const { getSessionTracks, updateSessionTracks, insertOneSessionTracks } = require('../db/mongo/mongoSessionTracks');
const { RedisClient } = require('../db/redis/redis');
const { getHistoricalSessions, getIvaoSessionTracks, getIvaoPilotsNow, getIvaoLatestSessionFlightPlan, getIvaoSessionLatestTrack } = require('../requests/ivao/session');
const { getAirTime } = require('./trackerAnalizer');
@ -26,7 +27,7 @@ async function checkUsername(user, key, usersList) {
if (!u.name) {
const ref1 = await getUserFromReferenceTable(key) || {};
const ref2 = usersList.find(d => key === d.vid) || {};
const ref2 = (usersList || []).find(d => key === d.vid) || {};
let ref;
if (ref2.name) {
ref = ref2;
@ -51,32 +52,69 @@ async function getWhitelist() {
}
async function getSessionCalculatedTime(sessionId) {
async function getSessionCalculatedTime(session) {
const sessionId = session.id;
let tracks = await getSessionTracks(sessionId);
let calculatedTime;
if (tracks && !Number.isInteger(tracks.calculatedTime)) {
tracks.calculatedTime = getAirTime(tracks);
await updateSessionTracks(tracks);
calculatedTime = getAirTime(tracks);
tracks.calculatedTime = calculatedTime;
try {
await updateSessionTracks(tracks);
} catch (err) {
console.log('Error updateSessionTracks');
}
} else if (!tracks) {
const t = await getIvaoSessionTracks(sessionId);
calculatedTime = getAirTime(t);
tracks = {
sessionId,
tracks: t,
calculatedTime: getAirTime(t)
calculatedTime,
};
await insertOneSessionTracks(tracks);
try {
await insertOneSessionTracks(tracks);
} catch (err) {
console.log('Error insertOneSessionTracks');
}
}
await setSessionCalculatedTime(session, tracks, calculatedTime);
return tracks.calculatedTime;
}
async function getList(callsign) {
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) {
const from = moment().startOf('month').format('YYYY-MM-DD');
const to = moment().subtract(1, 'day').endOf('day').format('YYYY-MM-DD');
const todayData = await getTodaySessionsFromIvao(callsign);
const monthData = await getSessions(from, to);
const allData = [...todayData, ...monthData];
const redisUsers = await RedisClient.getPair('users');
const totalsByUserId = {};
for (let index = 0; index < allData.length; index++) {
@ -84,7 +122,7 @@ async function getList(callsign) {
const userId = session.userId;
const flightPlan = session.flightPlans[session.flightPlans.length - 1];
const date = moment(session.completedAt);
const calculated = await getSessionCalculatedTime(session.id);
const calculated = await getSessionCalculatedTime(session);
if (!totalsByUserId[userId]) {
totalsByUserId[userId] = {
time: 0,
@ -107,7 +145,6 @@ async function getList(callsign) {
}
totalsByUserId[userId].division = session.user.divisionId;
}
}
const array = [];
@ -115,6 +152,7 @@ async function getList(callsign) {
if (Object.hasOwnProperty.call(totalsByUserId, key)) {
const user = await checkUsername(totalsByUserId[key], key, redisUsers);
user.vid = key;
user.name = obfuscate(user.name, isAuthenticated);
array.push(user);
}
}
@ -149,9 +187,24 @@ async function getLatestsFlightPlans() {
return response;
}
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);
}
module.exports = {
getList,
getWhitelist,
getLatestSessions,
getLatestsFlightPlans,
getPilotInfoInTime,
};

View File

@ -0,0 +1 @@
// var ip = req['x-forwarded-for] || req.socket.remoteAddress

View File

@ -31,8 +31,9 @@ const mongoExecute = async function(fn, opts) {
}
return await fn({ database, connection });
} catch (err) {
console.log('err :>> ', err);
// console.log('err :>> ', err);
console.log('MOMGODB ERROR:', err.message);
throw err;
} finally {
if (connection) {
await connection.close();

View File

@ -1,24 +1,20 @@
const { getMongoConnection } = require("./mongoDBPool");
const {
MONGO_DB,
} = process.env;
const { mongoExecute } = require("./mongoDBPool");
const DB = MONGO_DB || 'lts';
const colName = 'pilots_ref';
async function getUserFromReferenceTable(vid) {
const conn = await getMongoConnection();
try {
const db = conn.db(DB);
const col = db.collection('pilots_ref');
const user = await col.findOne({ vid }, {});
return user;
} catch (err) {
console.error(err);
} finally {
await conn.close();
}
return await mongoExecute(async({ collection }) => {
return await collection.findOne({ vid });
}, { colName });
}
async function getAllUsersFromReferenceTable() {
return await mongoExecute(async({ collection }) => {
return await collection.find({}).toArray();
}, { colName });
}
module.exports = {
getUserFromReferenceTable
getUserFromReferenceTable,
getAllUsersFromReferenceTable,
};

View File

@ -0,0 +1,42 @@
const { mongoExecute } = require("./mongoDBPool");
const colName = 'sessionTracks';
async function insertSessionTracks(sessionTracks, clear) {
return await mongoExecute(async({ collection }) => {
if (clear) {
collection.deleteMany({});
}
await collection.insertMany(sessionTracks);
}, { colName });
}
async function insertOneSessionTracks(sessionTracks) {
return await mongoExecute(async({ collection }) => {
await collection.insertOne(sessionTracks);
}, { colName });
}
async function getSessionTracks(sessionId) {
return await mongoExecute(
async({ collection }) => {
return await collection.findOne({ sessionId });
}, { colName }
);
}
async function updateSessionTracks(tracks) {
return await mongoExecute(async({ database }) => {
const tracksCollection = database.collection('sessionTracks');
await tracksCollection.updateOne({ _id: tracks._id }, { $set: { calculatedTime: tracks.calculatedTime } });
});
}
module.exports = {
insertSessionTracks,
getSessionTracks,
updateSessionTracks,
insertOneSessionTracks,
};

View File

@ -1,46 +1,21 @@
const { mongoExecute } = require("./mongoDBPool");
const colName = 'sessions';
async function insertSessions(sessions, clear) {
return await mongoExecute(async({ database }) => {
const sessionsCollection = database.collection('sessions');
return await mongoExecute(async({ collection }) => {
if (clear) {
sessionsCollection.deleteMany({});
collection.deleteMany({});
}
await sessionsCollection.insertMany(sessions);
});
}
async function insertOneSessionTracks(sessionTracks) {
return await mongoExecute(async({ database }) => {
const sessionsCollection = database.collection('sessionTracks');
await sessionsCollection.insertOne(sessionTracks);
});
}
async function insertSessionTracks(sessionTracks, clear) {
return await mongoExecute(async({ database }) => {
const sessionsCollection = database.collection('sessionTracks');
if (clear) {
sessionsCollection.deleteMany({});
}
await sessionsCollection.insertMany(sessionTracks);
});
await collection.insertMany(sessions);
}, { colName });
}
async function getSessions(start, end) {
return await mongoExecute(async({ database }) => {
const sessionsCollection = database.collection('sessions');
return await mongoExecute(async({ collection }) => {
const startDate = start + 'T00:00:00.000Z';
const endDate = end + 'T23:59:59.999Z';
const result = await sessionsCollection.aggregate([{
const result = await collection.aggregate([{
$addFields: {
completedDate: {
$dateFromString: {
@ -67,33 +42,62 @@ async function getSessions(start, end) {
}
}]).toArray();
return result;
});
}, { colName });
}
async function getSessionTracks(sessionId) {
return await mongoExecute(
async({ database }) => {
const tracksCollection = database.collection('sessionTracks');
const tracks = await tracksCollection.findOne({ sessionId });
return tracks;
}
);
async function getSession(sessionId) {
return await mongoExecute(async({ collection }) => {
const session = await collection.findOne({ id: sessionId });
return session;
}, { colName: 'sessions' });
}
async function updateSessionTracks(tracks) {
return await mongoExecute(async({ database }) => {
const tracksCollection = database.collection('sessionTracks');
await tracksCollection.updateOne({ _id: tracks._id }, { $set: { calculatedTime: tracks.calculatedTime } });
});
async function updateSessionCalculatedTime(session) {
return await mongoExecute(async({ collection }) => {
await collection.updateOne({ _id: session._id }, { $set: { calculatedTime: session.calculatedTime } });
}, { colName: 'sessions' });
}
async function getSessionsTotalCalculatedTimeByPilot(start, end) {
const startDate = start + 'T00:00:00.000Z';
const endDate = end + 'T23:59:59.999Z';
return await mongoExecute(async({ collection }) => {
return await collection.aggregate([{
$addFields: {
createdDate: {
$dateFromString: {
dateString: "$createdAt",
},
},
},
}, {
$match: {
createdDate: {
$gt: new Date(startDate),
$lte: new Date(endDate)
}
}
}, {
$group: {
_id: "$userId",
total: {
$count: {},
},
time: {
$sum: "$calculatedTime",
},
},
}, ]).toArray();
}, { colName });
}
module.exports = {
insertSessions,
insertSessionTracks,
insertOneSessionTracks,
getSession,
getSessions,
getSessionTracks,
updateSessionTracks,
getSessionsTotalCalculatedTimeByPilot,
updateSessionCalculatedTime,
};
//http://localhost:3001/api/v1/ivao/init-sessions?callsign=LTS&from=2023-01-05T00:00:00&to=2023-01-05T23:59:59

View File

@ -4,11 +4,13 @@ async function createUserMongo({ id, username, hash, roles = [], firstname, last
return await mongoExecute(async({ database }) => {
const usersCol = database.collection('users');
const createdOn = new Date();
const updatedOn = new Date();
await usersCol.insertOne({
id,
username,
hash,
createdOn,
updatedOn,
roles,
firstname,
lastname,
@ -17,6 +19,20 @@ async function createUserMongo({ id, username, hash, roles = [], firstname, last
});
}
async function updateUserHash(id, hash) {
return await mongoExecute(async({ collection }) => {
return await collection.updateOne({
id
}, {
$set: {
hash,
updatedOn: new Date()
}
})
}, { colName: 'users' });
}
async function getUserMongo(username) {
return await mongoExecute(async({ collection }) => {
return await collection.findOne({ username });
@ -26,4 +42,5 @@ async function getUserMongo(username) {
module.exports = {
createUserMongo,
getUserMongo,
updateUserHash
};

View File

@ -26,7 +26,6 @@ const getHistoricalSessions = async({ callsign, userId, from, to }) => {
},
params,
};
return await _requestHistoricalRecursive([], url, options);
};
@ -71,9 +70,7 @@ async function getIvaoPilotsNow(all = false) {
apiKey: process.env.IVAO_APIKEY,
},
};
const redisUsers = await RedisClient.getPair('users');
const pilots = await request(url, options);
// console.log('redisUsers :>> ', redisUsers);
return all ? pilots : pilots.filter(d => d.callsign.startsWith('LTS'));
}

14
app/routes/acars.js Normal file
View File

@ -0,0 +1,14 @@
const express = require('express');
const { updatePosition, getPosition } = require('../controllers/acarsController');
const router = express.Router();
router.post(`/report`, (req, res) => {
updatePosition(req);
res.status(200).send();
});
router.get(`/position`, async(req, res) => {
res.status(200).send(await getPosition(req));
});
module.exports = router;

View File

@ -1,9 +1,17 @@
const express = require('express');
const passport = require('passport')
const LocalStrategy = require('passport-local');
const { initSessionsData, createUser, authenticate } = require('../controllers/adminController');
const { initSessionsData, createUser, authenticate, changePassword } = require('../controllers/adminController');
const router = express.Router();
const NOT_AUTHENTICATED = 'not-authenticated';
const WRONG_PASSWORD = 'wrong-password';
const checkAuthenticated = (req) => {
if (!req.isAuthenticated()) {
throw new Error(NOT_AUTHENTICATED);
}
};
passport.use(new LocalStrategy(async function verify(username, password, cb) {
try {
const user = await authenticate(username, password);
@ -49,10 +57,28 @@ router.post('/user/create', async(req, res) => {
router.post('/user/authenticate',
passport.authenticate('local'),
function(req, res) {
console.log('req.user :>> ', req.isAuthenticated(), req.user);
res.json(req.user);
});
router.post('/user/password-change',
async function(req, res, next) {
try {
checkAuthenticated(req);
await changePassword(req);
console.log('pasword changed');
res.status(200).send();
} catch (err) {
if (err.message === NOT_AUTHENTICATED || err.message === WRONG_PASSWORD) {
res.status(401).json({
error: err.message
});
next();
} else {
res.status(500).send();
}
}
});
router.get('/user/alive',
function(req, res) {
console.log('req.user :>> ', req.isAuthenticated());

View File

@ -1,7 +1,7 @@
const express = require('express');
const router = express.Router();
const { getList, getWhitelist } = require('../controllers/sessionsController');
const { getList, getWhitelist, getPilotInfoInTime } = require('../controllers/sessionsController');
const { getSessions } = require('../db/mongo/mongoSessions');
@ -17,7 +17,7 @@ router.get('/sessions', async(req, res) => {
router.get('/list/today', async(req, res) => {
try {
const data = await getList('LTS');
const data = await getList('LTS', req.isAuthenticated());
res.status(200).json(data);
} catch (err) {
console.log(err);
@ -31,6 +31,15 @@ router.get('/whitelist', async(req, res) => {
} catch (err) {
console.log(err);
}
})
});
router.get('/list/previous/:start/:end', async(req, res) => {
try {
const data = await getPilotInfoInTime(req, );
res.status(200).json(data);
} catch (err) {
console.log(err);
}
});
module.exports = router;

View File

@ -18,6 +18,7 @@ async function taskSyncLSAUsers() {
['users_whitelist', whitelist],
]);
} catch (err) {
console.log('err :>> ', err);
console.log('ERR executing taskSyncLSAUsers');
}
}
@ -40,16 +41,21 @@ async function taskSyncPrevioudDaySessions(callsign) {
}
module.exports = function() {
if (canRunTasks) {
cron.schedule(process.env.SYNC_TASK_SCHEDULE, () => {
taskSyncPrevioudDaySessions('LTS');
});
cron.schedule(process.env.USERS_TASK_SCHEDULE, async() => {
taskSyncLSAUsers();
});
console.log('Tasks started.');
} else {
console.log('Tasks skipped.');
}
}
module.exports = {
sync: function() {
console.log('canRunTasks :>> ', canRunTasks);
if (canRunTasks) {
cron.schedule(process.env.SYNC_TASK_SCHEDULE, () => {
taskSyncPrevioudDaySessions('LTS');
});
// cron.schedule(process.env.USERS_TASK_SCHEDULE, async() => {
// taskSyncLSAUsers();
// });
console.log('Tasks started.');
} else {
console.log('Tasks skipped.');
}
},
taskSyncLSAUsers,
taskSyncPrevioudDaySessions,
};

View File

@ -1,7 +1,6 @@
require('dotenv').config();
require('./app/tasks/sync')();
const sync = require('./app/tasks/sync');
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
@ -15,7 +14,9 @@ const RedisStore = require("connect-redis")(session);
const ivaoRoutes = require('./app/routes/ivao');
const ltsRoutes = require('./app/routes/lts');
const adminRoutes = require('./app/routes/admin');
const acarsRoutes = require('./app/routes/acars');
sync.sync();
const app = express();
@ -28,7 +29,7 @@ app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
var corsOptions = {
origin: function(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
if (origin === undefined || whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
@ -68,6 +69,7 @@ app.use(passport.authenticate('session'));
app.use('/api/v1/ivao', ivaoRoutes);
app.use('/api/v1', ltsRoutes);
app.use('/api/v1/admin', adminRoutes);
app.use('/api/v1/acars', acarsRoutes);
// app.use(function(req, res, next) {
// var msgs = req.session.messages || [];

162
test.js
View File

@ -4,10 +4,14 @@ const data = require('./testData/short.json');
const { analize, getShortStates, getAirTime } = require('./app/controllers/trackerAnalizer');
const { getSessions, getSessionTracks, updateSessionTracks } = require('./app/db/mongo/mongoSessions');
const { getIvaoPilotsNow } = require('./app/requests/ivao/session');
const { createUserMongo } = require('./app/db/mongo/mongoUsers');
const { getHashedPassword } = require('./app/controllers/adminController');
const { getSessions, getSession, updateSessionCalculatedTime, } = require('./app/db/mongo/mongoSessions');
const { getIvaoPilotsNow, getIvaoSessionTracks } = require('./app/requests/ivao/session');
const { createUserMongo, updateUserHash } = require('./app/db/mongo/mongoUsers');
const { getUserFromReferenceTable } = require('./app/db/mongo/mongoPilots');
const { getHashedPassword, changePassword } = require('./app/controllers/adminController');
const { mongoExecute } = require('./app/db/mongo/mongoDBPool');
const { getSessionTracks, updateSessionTracks, insertOneSessionTracks } = require('./app/db/mongo/mongoSessionTracks');
const { RedisClient } = require('./app/db/redis/redis');
// const { getHistoricalSessions, getSessionTracks } = require('./app/requests/ivao/session');
@ -46,28 +50,140 @@ async function recalculateTime() {
}
}
async function f() {
function g() {
const data = mongoExecute(async({ collection }) => {
return await collection.aggregate([{
$addFields: {
createdDate: {
$dateFromString: {
dateString: "$createdAt",
},
},
},
},
{
$match: {
createdDate: {
$gt: new Date("2023-01-01T00:00:00.000Z"),
$lte: new Date("2023-01-31T23:59:59.999Z"),
},
},
},
{
$lookup: {
from: "sessionTracks",
localField: "id",
foreignField: "sessionId",
as: "track",
},
},
{
$unwind: {
path: "$track",
},
},
{
$group: {
_id: "$userId",
totalTime: {
$sum: "$track.calculatedTime",
},
},
},
]).toArray();
}, { colName: 'sessions' });
const crypto = require('crypto');
await createUserMongo({
id: crypto.randomBytes(16).toString("hex"),
username: 'admin',
hash: getHashedPassword('nevada98'),
roles: ['admin']
});
await createUserMongo({
id: crypto.randomBytes(16).toString("hex"),
username: 'capcabal',
hash: getHashedPassword('Kpitan123'),
roles: ['cabal'],
firstname: 'Carlos',
lastname: 'Cabal',
vid: 665507
});
data.then(async(d) => {
const final = [];
for (let index = 0; index < d.length; index++) {
const pilot = d[index];
const ref = await getUserFromReferenceTable(String(pilot._id));
final.push({
vid: pilot._id,
name: ref.name,
hours: Number((pilot.totalTime / 3600).toFixed(2)),
});
}
console.log('horas\tvid\tNombre');
console.log('======================================');
final.sort((a, b) => b.hours - a.hours).forEach(d => {
console.log(`${d.hours}\t${d.vid}\t${d.name}`);
})
})
}
f();
async function f() {
// changePassword('admin', 'qwerty123', 'qwerty123');
// const crypto = require('crypto');
// await createUserMongo({
// id: crypto.randomBytes(16).toString("hex"),
// username: 'admin',
// hash: getHashedPassword('nevada98'),
// roles: ['admin']
// });
// await createUserMongo({
// id: crypto.randomBytes(16).toString("hex"),
// username: 'capcabal',
// hash: getHashedPassword('Kpitan123'),
// roles: ['cabal'],
// firstname: 'Carlos',
// lastname: 'Cabal',
// vid: 665507
// });
}
async function updateCalculated() {
const tracks = await mongoExecute(async({ collection }) => {
const res = await collection.find({}).toArray();
return res;
}, { colName: 'sessionTracks' });
for (let index = 0; index < tracks.length; index++) {
const track = tracks[index];
if (Number.isInteger(track.calculatedTime)) {
const session = await getSession(track.sessionId);
if (session) {
session.calculatedTime = track.calculatedTime;
await updateSessionCalculatedTime(session);
console.log('updatet session :>> ', session.id);
}
}
}
console.log('updated total: ', tracks.length);
}
// updateCalculated()
(async function() {
// await require('./app/tasks/sync').taskSyncLSAUsers();
// const redisUsers = await RedisClient.getPair('users');
// console.log('redisUsers :>> ', redisUsers);
// const data = await getSessionsTotalCalculatedTimeByPilot('2023-01-01', '2023-01-31');
// for (let index = 0; index < data.length; index++) {
// const row = data[index];
// const user = redisUsers.find(d => Number(d.vid) === row._id);
// row.user = user;
// }
// console.log('data :>> ', data);
const sessionId = 51777503;
const t = await getIvaoSessionTracks(sessionId);
console.log('tracks :>> ', t);
const calculatedTime = getAirTime(t);
console.log('calculatedTime :>> ', calculatedTime);
const tracks = {
sessionId,
tracks: t,
calculatedTime,
};
console.log('tracks :>> ', tracks);
await insertOneSessionTracks(tracks);
})();
// require('./app/tasks/sync')();