const amqp = require('amqplib/callback_api'); const debug = require('debug')('agm:satloc'); const fs = require('fs'); const path = require('path'); const satlocUtil = require('./satloc-util'); const satlocApi = require('./satloc-api'); const MongoClient = require('mongodb').MongoClient const env = process.env; const errLogPath = path.join(__dirname, 'error.log'); let queueChannel; async function main() { try { const job1 = 'Job - Simple.job'; const job2 = 'Job - Complex.job'; const job3 = '500.job'; const jobPath = path.join(__dirname, 'job_files', job3); // const area = satlocUtil.convertJobFileToArea(jobPath); // await updateJobAreas(20, area.sprayAreas, area.excludedAreas); // satlocUtil.writeFile(path.join(__dirname, 'output_data', job3), satlocUtil.convertToJobFile(job3.split('.')[0], area.sprayAreas, area.excludedAreas)); await testSatlocApi(env.SATLOC_USERNME, env.SATLOC_PASSWORD); process.exit(); } catch (error) { debug(error); satlocUtil.writeFile(errLogPath, error); } } async function updateJobAreas(jobId, sprayAreas, excludedAreas) { const db = await connectDb(); const filter = { _id: jobId }; const update = { $set: { sprayAreas, excludedAreas } }; const collection = db.collection('jobs'); const result = await collection.updateOne(filter, update); debug(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`); } async function connectDb() { const ops = { db: env.DB_NAME, user: env.DB_USR, pass: env.DB_PWD, hosts: env.DB_HOSTS, replicaSet: env.DB_REPLSET }; let _uri = ops.url; if (!_uri) { _uri = `mongodb://${ops.user}:${ops.pass}@${ops.hosts}/${ops.db}?authSource=${ops.authSource || ops.db}`; ops.replicaSet && (_uri += '&replicaSet=' + ops.replicaSet); } const conn = await MongoClient.connect(_uri, { family: 4, keepAlive: true }); return conn.db(); } async function testSatlocApi(username, password) { const isAlive = await satlocApi.checkApiAlive(); if (isAlive) { const authResponse = await satlocApi.auth(username.replace('@', '%40'), password.replace('{', '%7B')); const aircraftList = await satlocApi.getAircraftList(authResponse.userId, authResponse.companyId); const aircraftLogs = await satlocApi.getAircraftLogs(authResponse.userId, aircraftList[0].id); const aircraftLogData = await satlocApi.getAircraftLogData(authResponse.userId, aircraftLogs[0].id); await satlocUtil.writeSatlocLogData(aircraftLogData.id, aircraftLogData.logFile); // Test upload job data functionality // await testUploadJobData(authResponse.userId, authResponse.companyId, aircraftList[0].id); // const msg = JSON.stringify({ jobId: aircraftLogData.id, data: aircraftLogData.logFile }); debug(`Successfully retrieved aircraft log data: ${aircraftLogData.id}`); } } async function testUploadJobData(userId, companyId, aircraftId) { try { const jobFilePath = path.join(__dirname, 'job_files', '500.job'); const fileName = '500.job'; const notes = 'Test job upload from Node.js'; // Read the job file content const jobFileContent = fs.readFileSync(jobFilePath, 'utf8'); // Create job data model const jobDataModel = satlocApi.createJobDataModel( aircraftId, fileName, jobFileContent, notes ); // Create job package const jobPackage = satlocApi.createJobPackage( companyId, userId, [jobDataModel] ); // Upload the job data const uploadResult = await satlocApi.uploadJobData(jobPackage); debug(`Successfully uploaded job data: ${fileName}`, uploadResult); return uploadResult; } catch (error) { debug(`Error uploading job data:`, error); satlocUtil.writeFile(errLogPath, error); throw error; } } function startRabbitMQ() { const conOps = { protocol: 'amqp', hostname: env.QUEUE_HOST || 'localhost', port: env.QUEUE_PORT || 5672, username: env.QUEUE_USR || 'agmuser', password: env.QUEUE_PWD, vhost: env.QUEUE_VHOST || '/', heartbeat: env.QUEUE_HEARTBEAT || 0, frameMax: 0, }; amqp.connect(conOps, function (err, conn) { if (err) { debug(err); satlocUtil.writeFile(errLogPath, err); return process.exit(); } conn.on("error", function (err) { debug(err); satlocUtil.writeFile(errLogPath, err); return process.exit(); }); conn.on("close", function () { debug("Connection closed"); return process.exit(); }); debug("Connected to RabbitMQ"); createQueue(conn); }); } function createQueue(conn) { conn.createChannel(function (err, ch) { if (err) { debug("[AMQP] Channel error", err.message); satlocUtil.writeFile(errLogPath, err); return process.exit(); } const queue = env.QUEUE_NAME_JOBS || 'satloc_logs'; queueChannel = ch; ch.checkQueue(queue, function (err, ok) { if (err) { ch.assertQueue(queue, { durable: true }, function (err) { if (err) { debug("[AMQP] Queue assertion error", err.message); satlocUtil.writeFile(errLogPath, err); return process.exit(); } debug(`[AMQP] Queue '${queue}' created`); }); } else { debug(`[AMQP] Queue '${queue}' exists`); } }); }); } function sendMessage(ch, queue, msg) { ch.sendToQueue(queue, Buffer.from(msg), { persistent: true }); debug(" [x] Sent '%s'", msg); } (async () => { await main(); })();