biz-a-cli 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/hub.js CHANGED
@@ -1,14 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import yargs from 'yargs';
4
- import net from 'node:net';
5
- import io from "socket.io-client";
6
-
7
- import { createRequire } from "module";
8
- const require = createRequire(import.meta.url);
9
- const ss = require('socket.io-stream'); //SCY: Temporary, next will be replaced with import
10
-
11
- const IDLE_SOCKET_TIMEOUT_MILLISECONDS = 1000 * 30;
4
+ import { io as ioc } from "socket.io-client";
5
+ import hubEvent from './hubEvent.js'
12
6
 
13
7
  const argv = yargs(process.argv.slice(2))
14
8
  .usage('Usage: $0 [options]')
@@ -39,6 +33,13 @@ const argv = yargs(process.argv.slice(2))
39
33
  type: 'number',
40
34
  demandOption: true
41
35
  })
36
+ .options('sp', {
37
+ alias: 'serverport',
38
+ default: 3002,
39
+ describe: 'Server Port',
40
+ type: 'number',
41
+ demandOption: false
42
+ })
42
43
  .argv;
43
44
 
44
45
  if (argv.help) {
@@ -57,59 +58,22 @@ if (!argv['server'] || !argv['subdomain'] || !argv['port']) {
57
58
  }
58
59
  }
59
60
 
60
- // return new Promise((resolve, reject) => {
61
- (() => new Promise((resolve, reject) => {
62
- let socket = io(argv['server']);
63
-
64
- socket.on('connect', () => {
65
- console.log(new Date() + ': connected to socket server');
66
- console.log(new Date() + ': requesting subdomain ' + argv['subdomain'] + ' via ' + argv['server']);
67
-
68
- socket.emit('createTunnel', argv['subdomain'], (err) => {
69
- if (err) {
70
- console.log(new Date() + ': [error] ' + err);
71
- reject(err);
72
- } else {
73
- console.log(new Date() + ': registered with server successfully');
74
-
75
- // clean and concat requested url
76
- let url;
77
- // let subdomain = argv['subdomain'].toString();
78
- let server = argv['server'].toString();
79
-
80
- url = server;
81
-
82
- // resolve promise with requested URL
83
- resolve(url);
84
- }
85
- });
86
- });
87
- socket.on('incomingClient', (clientId) => {
88
- console.log(clientId, 'incoming clientId')
89
- let client = net.connect(argv['port'], argv['hostname']);
61
+ //
62
+ import express from 'express';
63
+ import cors from 'cors';
64
+ const app = express();
65
+ import { runCliScript } from '../callbackController.js'
90
66
 
91
- client.on('connect', () => {
92
- console.log(`client connected to ${argv['hostname']}:${argv['port']}`)
93
- let s = ss.createStream();
94
- s.pipe(client).pipe(s);
67
+ app.use(cors());
68
+ app.use(express.json());
95
69
 
96
- s.on('end', () => {
97
- client.destroy();
98
- });
99
- ss(socket).emit(clientId, s);
100
- })
70
+ app.use('/cb', runCliScript);
71
+ const port = 3002;
101
72
 
102
- client.setTimeout(IDLE_SOCKET_TIMEOUT_MILLISECONDS);
103
- client.on('timeout', () => {
104
- client.end();
105
- });
73
+ app.listen((argv.serverport || port), () => {
74
+ console.log(`Biz-A is listening at ${process.env.HOST || 'http://localhost'}:${argv.serverport || port} `);
75
+ });
76
+ //
106
77
 
107
- client.on('error', () => {
108
- // handle connection refusal (create a stream and immediately close it)
109
- let s = ss.createStream();
110
- ss(socket).emit(clientId, s);
111
- s.end();
112
- });
113
- });
114
- // })
115
- }))()
78
+ let socket = ioc(argv['server']);
79
+ hubEvent(socket, argv);
@@ -0,0 +1,72 @@
1
+ import { Axios } from 'axios-observable';
2
+ import net from 'node:net';
3
+ import { createRequire } from "module";
4
+ const require = createRequire(import.meta.url);
5
+ const ss = require('socket.io-stream'); //SCY: Temporary, next will be replaced with import
6
+
7
+ const IDLE_SOCKET_TIMEOUT_MILLISECONDS = 1000 * 30;
8
+
9
+ // export default (argv) => {
10
+ export default async (socket, argv) => new Promise((resolve, reject) => {
11
+ socket.on('connect', () => {
12
+ console.log(new Date() + ': connected to socket server');
13
+ console.log(new Date() + ': requesting subdomain ' + argv['subdomain'] + ' via ' + argv['server']);
14
+
15
+ socket.emit('createTunnel', argv['subdomain'], (err) => {
16
+ if (err) {
17
+ console.log(new Date() + ': [error] ' + err);
18
+ reject(err);
19
+ } else {
20
+ console.log(new Date() + ': registered with server successfully');
21
+
22
+ // clean and concat requested url
23
+ let url;
24
+ // let subdomain = argv['subdomain'].toString();
25
+ let server = argv['server'].toString();
26
+
27
+ url = server;
28
+
29
+ // resolve promise with requested URL
30
+ resolve(url);
31
+ }
32
+ });
33
+ });
34
+
35
+ socket.on('incomingClient', (clientId) => {
36
+ console.log(clientId, 'incoming clientId')
37
+ let client = net.connect(argv['port'], argv['hostname']);
38
+
39
+ client.on('connect', () => {
40
+ console.log(`client connected to ${argv['hostname']}:${argv['port']}`)
41
+ let s = ss.createStream();
42
+ s.pipe(client).pipe(s);
43
+
44
+ s.on('end', () => {
45
+ client.destroy();
46
+ });
47
+ ss(socket).emit(clientId, s);
48
+ })
49
+
50
+ client.setTimeout(IDLE_SOCKET_TIMEOUT_MILLISECONDS);
51
+ client.on('timeout', () => {
52
+ client.end();
53
+ });
54
+
55
+ client.on('error', () => {
56
+ // handle connection refusal (create a stream and immediately close it)
57
+ let s = ss.createStream();
58
+ ss(socket).emit(clientId, s);
59
+ s.end();
60
+ });
61
+ })
62
+
63
+ socket.on('cli-req', (data, callback) => {
64
+ const { path, method, ...remainData } = data;
65
+
66
+ Axios.request({
67
+ method: data.method,
68
+ url: `${process.env.HOST || 'http://localhost'}:${argv.serverport}/cb${path}`,
69
+ data: remainData
70
+ }).subscribe(result => callback(result.data));
71
+ });
72
+ })
package/bin/watcher.js ADDED
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+
3
+ import express from 'express';
4
+ import cors from 'cors';
5
+ const app = express();
6
+ import yargs from 'yargs';
7
+
8
+ import * as timer from '../scheduler/timer.js'
9
+
10
+ process.on('uncaughtException', (err) => { //debug
11
+ console.log('Unhandled Exception:', err);
12
+ });
13
+
14
+ process.on('unhandledRejection', (err) => { //debug
15
+ console.log('Unhandled Rejection:', err);
16
+ });
17
+
18
+ const options = yargs(process.argv.slice(2))
19
+ .option('c', {
20
+ alias: 'company',
21
+ describe: 'Company',
22
+ type: 'string',
23
+ demandOption: true
24
+ })
25
+ .option('p', {
26
+ alias: 'port',
27
+ describe: 'Port to use',
28
+ type: 'string',
29
+ demandOption: false
30
+ })
31
+ // .option('m', {
32
+ // alias: 'mode',
33
+ // describe: 'Fill with "prod" / "dev"',
34
+ // type: 'string',
35
+ // demandOption: false
36
+ // })
37
+ .argv;
38
+
39
+
40
+ app.use(cors());
41
+ timer.runScheduler(options.company);
42
+
43
+ const port = 3001;
44
+
45
+ app.listen((options.port || port), () => {
46
+ console.log(`Biz-A CLI is listening at ${process.env.HOST || 'http://localhost'}:${options.port || port} `);
47
+ });
48
+
49
+ // export const MODE = (options.mode == 'prod') ? 'production' : 'development';
@@ -0,0 +1,19 @@
1
+ import { loadCliScript, extractFunctionScript } from "./scheduler/datalib.js";
2
+ import { getCompanyObjectId, getSelectedConfig } from "./scheduler/configController.js";
3
+
4
+ export async function runCliScript(req, res) {
5
+ const data = req.body;
6
+ const company = await getCompanyObjectId(data.query.companyId);
7
+ const config = await getSelectedConfig(company._id);
8
+ const selectedConfig = config[0];
9
+
10
+ loadCliScript(selectedConfig, data.query).subscribe({
11
+ next: data => {
12
+ let functions = extractFunctionScript(data);
13
+ res.send(functions.onInit(selectedConfig, data.body));
14
+
15
+ console.log(`Run Callback Successfully!`);
16
+ },
17
+ error: error => console.log(error.response.data || error)
18
+ })
19
+ }
package/constanta.js ADDED
@@ -0,0 +1,8 @@
1
+ export const ECODE = {
2
+ API: 'EAPI',
3
+ FULL: 'full'
4
+ }
5
+ export const MSG = {
6
+ E_USER_PASS_IN_API: 'Username or password is not valid. Check database no:1 in API',
7
+ E_LICENSE_FULL: 'The license is full.',
8
+ }
@@ -0,0 +1,10 @@
1
+ export const envDev = {
2
+ production: false,
3
+ cdmUrl: 'https://imm-cdm-dev.herokuapp.com',
4
+ BIZA_MONGO_LINK: 'mongodb+srv://imm_biza:' +
5
+ encodeURIComponent('imm@2023') + '@cluster0.z2yr8kp.mongodb.net/?retryWrites=true&w=majority',
6
+ CDM_MONGO_LINK: 'mongodb+srv://imm_cdm:' +
7
+ encodeURIComponent('imm@2019') + '@imm-cdm-dev.rf6wr.mongodb.net/?retryWrites=true&w=majority',
8
+ COMPANY_REGISTER: 'companyregister-dev',
9
+ BIZA_SERVER_LINK: 'https://biz-a-dev-41e7c93a25e5.herokuapp.com'
10
+ };
package/envs/env.js ADDED
@@ -0,0 +1,10 @@
1
+ export const env = {
2
+ production: true,
3
+ cdmUrl: 'https://imm-cdm.herokuapp.com',
4
+ BIZA_MONGO_LINK: 'mongodb+srv://imm_biza:' +
5
+ encodeURIComponent('imm@2023') + '@cluster0.lezywmk.mongodb.net/?retryWrites=true&w=majority',
6
+ CDM_MONGO_LINK: 'mongodb+srv://imm_cdm:' +
7
+ encodeURIComponent('imm@2019') + '@imm-cdm.ohcqt.mongodb.net/?retryWrites=true&w=majority',
8
+ COMPANY_REGISTER: 'companyregister',
9
+ BIZA_SERVER_LINK: 'https://biz-a.herokuapp.com'
10
+ };
@@ -0,0 +1,26 @@
1
+ import * as nodemailer from "nodemailer";
2
+
3
+ function createEmailTransport(req, config) {
4
+ return nodemailer.createTransport(
5
+ req.body.smtpConfig ? req.body.smtpConfig : config.smtp
6
+ );
7
+ }
8
+
9
+ export function sendMailWatcher(req) {
10
+ try {
11
+ let config = req.body.config;
12
+ const transporter = createEmailTransport(req, config);
13
+ transporter.sendMail(req.body.mailOptions, (err, info) => {
14
+ if (err) {
15
+ console.log(err.message);
16
+ return err.message;
17
+ } else {
18
+ console.log(info);
19
+ return info;
20
+ }
21
+ })
22
+ } catch (err) {
23
+ console.log(err.message);
24
+ return err.message;
25
+ }
26
+ }
package/package.json CHANGED
@@ -1,26 +1,46 @@
1
1
  {
2
2
  "name": "biz-a-cli",
3
- "version": "2.3.2",
3
+ "nameDev": "biz-a-cli-dev",
4
+ "version": "2.3.3",
5
+ "versionDev": "0.0.20",
4
6
  "description": "",
5
7
  "main": "bin/index.js",
6
8
  "type": "module",
9
+ "engines": {
10
+ "node": "20.9.0",
11
+ "npm": "10.1.0"
12
+ },
7
13
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
14
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch a",
15
+ "test1": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
16
+ "dev": "node --watch server.js"
9
17
  },
10
18
  "author": "Imamatek",
11
19
  "license": "ISC",
12
20
  "bin": {
13
21
  "uploadbiza": "bin/index.js",
14
22
  "proxy": "bin/proxy.js",
15
- "hub": "bin/hub.js"
23
+ "hub": "bin/hub.js",
24
+ "watcher": "bin/watcher.js"
16
25
  },
17
26
  "dependencies": {
18
- "axios": "^1.6.2",
27
+ "axios": "^1.6.8",
28
+ "axios-observable": "^2.0.0",
19
29
  "cors": "^2.8.5",
20
- "express": "^4.18.2",
30
+ "dayjs": "^1.11.10",
31
+ "express": "^4.18.3",
32
+ "mongodb": "^6.5.0",
21
33
  "net": "^1.0.2",
22
- "socket.io-client": "^4.7.2",
34
+ "nodemailer": "^6.9.12",
35
+ "socket.io-client": "^4.7.5",
23
36
  "socket.io-stream": "^0.9.1",
24
37
  "yargs": "^17.7.2"
38
+ },
39
+ "devDependencies": {
40
+ "jest": "^29.7.0",
41
+ "socket.io": "^4.7.5"
42
+ },
43
+ "jest": {
44
+ "transform": {}
25
45
  }
26
- }
46
+ }
@@ -0,0 +1,106 @@
1
+ import { MongoClient, ObjectId } from 'mongodb';
2
+ import { envDev } from '../envs/env.dev.js';
3
+ import { env } from '../envs/env.js';
4
+
5
+ let BIZA_MONGO_LINK;
6
+ let CDM_MONGO_LINK;
7
+ let COMPANY_REGISTER;
8
+
9
+ // if ((process.env.NODE_ENV == undefined) || (process.env.NODE_ENV == 'development')) {
10
+ // BIZA_MONGO_LINK = envDev.BIZA_MONGO_LINK;
11
+ // CDM_MONGO_LINK = envDev.CDM_MONGO_LINK;
12
+ // COMPANY_REGISTER = envDev.COMPANY_REGISTER;
13
+
14
+ // console.log('BIZA_MONGO_LINK =>', BIZA_MONGO_LINK);
15
+ // console.log('CDM_MONGO_LINK =>', CDM_MONGO_LINK);
16
+ // console.log('COMPANY_REGISTER =>', COMPANY_REGISTER);
17
+ // } else {
18
+ BIZA_MONGO_LINK = env.BIZA_MONGO_LINK;
19
+ CDM_MONGO_LINK = env.CDM_MONGO_LINK;
20
+ COMPANY_REGISTER = env.COMPANY_REGISTER;
21
+ // }
22
+
23
+ async function fetchSelectedConfig(aggregateField) {
24
+ const client = new MongoClient(BIZA_MONGO_LINK);
25
+ try {
26
+ await client.connect();
27
+ const db = client.db('biz-a');
28
+ const config = db.collection('configuration');
29
+
30
+ return await config.aggregate(aggregateField).toArray();
31
+ } catch (error) {
32
+ console.error(error);
33
+ throw new Error(error);
34
+ } finally {
35
+ client.close()
36
+ }
37
+ }
38
+
39
+ function getSelectedConfigAggregateField(companyObjectId) {
40
+ let configAggregate = [];
41
+ if (companyObjectId) {
42
+ configAggregate.push({ "$match": { companyObjectId: new ObjectId(companyObjectId) } });
43
+ };
44
+ configAggregate.push({
45
+ $lookup: {
46
+ from: 'smtp',
47
+ localField: '_id',
48
+ foreignField: 'configObjectId',
49
+ as: 'smtp'
50
+ }
51
+ });
52
+ configAggregate.push({ $unwind: { path: "$smtp" } });
53
+
54
+ return configAggregate;
55
+ }
56
+
57
+ async function getSelectedConfig(companyObjectId) {
58
+ return await fetchSelectedConfig(getSelectedConfigAggregateField(companyObjectId));
59
+ }
60
+
61
+ function getCompanyObjectIdFindOneField(companyName) {
62
+ return [
63
+ { companyID: { $regex: new RegExp(`^${companyName}$`, 'i') } },
64
+ {
65
+ projection: {
66
+ _id: 1,
67
+ companyID: 1
68
+ }
69
+ }
70
+ ]
71
+ }
72
+
73
+ async function fetchCompanyObjectId(findOneField) {
74
+ const client = new MongoClient(CDM_MONGO_LINK);
75
+ try {
76
+ await client.connect();
77
+ const db = client.db(COMPANY_REGISTER);
78
+ const company = db.collection('companies');
79
+
80
+ return await company.findOne(findOneField[0], findOneField[1]);
81
+ } catch (error) {
82
+ console.error(error);
83
+ throw new Error(error);
84
+ } finally {
85
+ client.close()
86
+ }
87
+ }
88
+
89
+ function validateCompanyObjectId(companyObjectId) {
90
+ if (companyObjectId?._id) {
91
+ return companyObjectId;
92
+ } else {
93
+ throw { code: 'ENOENT' };
94
+ }
95
+ };
96
+
97
+ async function getCompanyObjectId(companyName) {
98
+ const companyObjectId = await fetchCompanyObjectId(getCompanyObjectIdFindOneField(companyName));
99
+ return validateCompanyObjectId(companyObjectId);
100
+ };
101
+
102
+ export {
103
+ BIZA_MONGO_LINK,
104
+ getSelectedConfig,
105
+ getCompanyObjectId
106
+ };
@@ -0,0 +1,84 @@
1
+ export function historyRecordToJson(data) {
2
+ let dataJson = [];
3
+ data.map(history => {
4
+ dataJson.push({
5
+ _id: parseInt(history.history_id),
6
+ timerObjectId: parseInt(history.timer_id),
7
+ latestRun: new Date(history.latest_run)
8
+ })
9
+ })
10
+
11
+ return dataJson;
12
+ }
13
+
14
+ function addTimer(timer, timerData) {
15
+ let timerIdx = (timerData) ? timerData.findIndex(value => value._id == timer.timer_id) : -1;
16
+ if (timerIdx > -1) {
17
+ if (timer.hourly_hours) {
18
+ timerData[timerIdx].hourly = timer.hourly_hours.split(',').map(String);
19
+ }
20
+ } else {
21
+ let timerObj = {
22
+ _id: parseInt(timer.timer_id),
23
+ watcherObjectId: parseInt(timer.timer_watcher_id),
24
+ name: timer.name,
25
+ active: (timer.active == 1),
26
+ timezone: timer.timezone,
27
+ templateName: timer.templateName,
28
+ seq: parseInt(timer.seq),
29
+ scriptId: parseInt(timer.scriptId),
30
+ script: (timer.cli_script) ? JSON.stringify(timer.cli_script) : ''
31
+ };
32
+ if ((timer.daily_days)) {
33
+ timerObj.daily = timer.daily_days.split(',').map(Number);
34
+ }
35
+ if (timer.weekly_ordinal && timer.weekly_days) {
36
+ timerObj.weekly = {
37
+ ordinal: timer.weekly_ordinal.split(',').map(Number),
38
+ days: timer.weekly_days.split(',').map(Number)
39
+ }
40
+ }
41
+ if ((timer.monthly_days)) {
42
+ timerObj.monthly = timer.monthly_days.split(',')
43
+ .map(value => (!isNaN(value)) ? Number(value) : value);
44
+ }
45
+ if (timer.minutely_everymin &&
46
+ timer.minutely_time_from && timer.minutely_time_to) {
47
+ timerObj.minutely = {
48
+ everyMin: parseInt(timer.minutely_everymin),
49
+ from: timer.minutely_time_from,
50
+ to: timer.minutely_time_to,
51
+ }
52
+ }
53
+ timerData.push(timerObj);
54
+
55
+ timerIdx = timerData.length - 1;
56
+
57
+ if (timer.hourly_hours) {
58
+ timerData[timerIdx].hourly = timer.hourly_hours.split(',').map(String);
59
+ }
60
+ }
61
+ return timerData;
62
+ }
63
+
64
+ export function watcherRecordToJson(data) {
65
+ let dataJson = [];
66
+ data.map(timer => {
67
+ let watcherIdx = (dataJson) ? dataJson.findIndex(value => value._id == timer.watcher_id) : -1;
68
+
69
+ if (watcherIdx > -1) {
70
+ addTimer(timer, dataJson[watcherIdx].timer);
71
+ } else {
72
+ dataJson.push({
73
+ _id: parseInt(timer.watcher_id),
74
+ companyObjectId: timer.company_id,
75
+ timer: []
76
+ })
77
+
78
+ watcherIdx = dataJson.length - 1;
79
+ addTimer(timer, dataJson[watcherIdx].timer);
80
+ }
81
+ })
82
+
83
+ return dataJson;
84
+ }