'use strict'; const https = require("https"), ObjectId = require('mongodb').ObjectId, os = require('os'), path = require('path'), Settings = require('../model/setting'), env = require('../helpers/env'), { UserTypes, DEFAULT_TRIAL_DAYS } = require('../helpers/constants'), { AppAuthError } = require("../helpers/app_error"), { version } = require('../package.json'), WorkerPool = require('../workers/worker_pool'), utils = require('../helpers/utils'), debug = require('debug')('agm:main'); let wkPool; async function pingAPI_get(req, res) { res.json(`AGM API Endpoint is working. Version - ${version}`); } function isSysAdmin(kind) { return (UserTypes.ADMIN === kind); } async function getAppConfig_get(req, res) { const userInfo = req.userInfo; if (!userInfo) AppAuthError.throw(); const masterUserSettings = await Settings.findOne({ userId: isSysAdmin(userInfo.kind) ? null : ObjectId(userInfo.puid) }).lean(); const isNormalUser = (userInfo.kind > UserTypes.APP); const userSettings = (isNormalUser ? await Settings.findOne({ userId: ObjectId(userInfo.id) }).lean() : masterUserSettings) || {}; // Apply global applicator's settings to non-applicator user's if (isNormalUser && masterUserSettings) { userSettings.jobsByPilot = !!(masterUserSettings.jobsByPilot); } delete userSettings.userId; if (isSysAdmin(userInfo.kind)) { if (utils.isEmptyArray(userSettings.trialDays)) userSettings.trialDays = DEFAULT_TRIAL_DAYS; } return res.send(userSettings); } async function setAppConfig_post(req, res) { const userInfo = req.userInfo; if (!userInfo) AppAuthError.throw(); const updatedUserSettings = await setConfig((UserTypes.ADMIN === userInfo.kind) ? null : ObjectId(req.uid), req.body?.settings || req.body); res.json(updatedUserSettings); } async function setConfig(userId, newConfig) { const newConf = newConfig || {}; if (utils.isObjectId(userId)) newConf.userId = ObjectId(userId); return await Settings.findOneAndUpdate( { userId: newConf.userId }, // find a document with that filter { $set: newConf }, // document to insert when nothing was found { upsert: true, new: true, runValidators: true, lean: true }); } function getSiteVer_post(req, res) { const ops = req.body; // Verify the reCaptcha token with GG at https://www.google.com/recaptcha/api/siteverify // Ref: https://developers.google.com/recaptcha/docs/verify const options = { protoco: 'https', hostname: 'www.google.com', path: `/recaptcha/api/siteverify?secret=${env.CAPTCHA_SITESEC}&response=${ops.tk}`, method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" } }; let data = ''; const vReq = https.request(options, resp => { resp.on('data', d => data += d); resp.on('end', () => { let vresult = JSON.parse(data); res.send(vresult).end(); }); }); vReq.on('error', error => { debug(error); res.json(null).end(); }); vReq.end(); } function doLongOp_post(req, res, next) { const a = req.query.a; const b = req.query.b; console.log(req.query); if (wkPool) wkPool = new WorkerPool(os.cpus().length / 2, path.resolve(__dirname, '../workers/test_worker.js')); console.log("Num of free worker:", wkPool.freeWorkers.length); wkPool.runTask({ a, b }, (err, result) => { if (err) return next(err); res.json({ result: result }); console.log("Num of free worker:", wkPool.freeWorkers.length); }); /** Test with SYNC version const multiply = (a, b) => { let output = 0 for (let i = 0; i < b; i++) output += a return output } let result = multiply(parseInt(a), parseInt(b)); res.json({ result: result }).end(); */ } module.exports = { pingAPI_get, getAppConfig_get, setAppConfig_post, getSiteVer_post, doLongOp_post }