-
Notifications
You must be signed in to change notification settings - Fork 38
/
vm-inject.js
227 lines (190 loc) · 6.17 KB
/
vm-inject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
module.exports = (async () => {
//##INJECTED_HEADER
// Imports npm packages for this .gbdialog conversational application.
require('isomorphic-fetch');
const YAML = require('yaml');
const http = require('node:http');
const retry = require('async-retry');
const createRpcClient = require('@push-rpc/core').createRpcClient;
const createHttpClient = require('@push-rpc/http').createHttpClient;
// Unmarshalls Local variables from server VM.
const pid = this.pid;
let id = this.id;
let username = this.username;
let mobile = this.mobile;
let from = this.from;
const channel = this.channel;
const ENTER = this.ENTER;
const headers = this.headers;
let httpUsername = this.httpUsername;
let httpPs = this.httpPs;
let today = this.today;
let now = this.now;
let date = new Date();
let page = null;
const files = [];
let col = 1;
let index = 1;
const mid = (arr, start, length) => {
if (length === undefined) {
return arr.slice(start);
}
return arr.slice(start, start + length);
};
// Makes objects in BASIC insensitive.
const caseInsensitive = listOrRow => {
if (!listOrRow) {
return listOrRow;
}
const lowercase = oldKey => (typeof oldKey === 'string' ? oldKey.toLowerCase() : oldKey);
const createCaseInsensitiveProxy = obj => {
const propertiesMap = new Map(Object.keys(obj).map(propKey => [lowercase(propKey), obj[propKey]]));
const caseInsensitiveGetHandler = {
get: (target, property) => propertiesMap.get(lowercase(property))
};
return new Proxy(obj, caseInsensitiveGetHandler);
};
if (listOrRow.length) {
return listOrRow.map(row => createCaseInsensitiveProxy(row));
} else {
return createCaseInsensitiveProxy(listOrRow);
}
};
// Transfers auto variables into global object.
for (const key of Object.keys(this.variables)) {
global[key] = this.variables[key];
console.log('Defining global variable: ' + key);
}
// Defines local utility BASIC functions.
const ubound = gbarray => {
let length = 0;
if (gbarray) {
length = gbarray.length;
if (length > 0) {
if (gbarray[0].gbarray) {
return length - 1;
}
}
}
return length;
};
const isarray = gbarray => {
return Array.isArray(gbarray);
};
// Proxies remote functions as BASIC functions.
const weekday = v => {
return (async () => {
return await dk.getWeekFromDate({ v });
})();
};
const hour = v => {
return (async () => {
return await dk.getHourFromDate({ v });
})();
};
const base64 = v => {
return (async () => {
return await dk.getCoded({ v });
})();
};
const tolist = v => {
return (async () => {
return await dk.getToLst({ v });
})();
};
const uuid = () => {
var dt = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
return uuid;
};
const random = () => {
return Number.parseInt(((Math.random() * 8) % 8) * 100000000);
};
// Setups interprocess communication from .gbdialog run-time to the BotServer API.
const optsRPC = {
callTimeout: this.callTimeout,
messageParser: data => {
return JSON.parse(data);
}
};
let url;
const agent = http.Agent({ keepAlive: true });
url = `http://localhost:${port}/${botId}/dk`;
const dk = (await createRpcClient(() => createHttpClient(url, { agent: agent }), optsRPC)).remote;
url = `http://localhost:${port}/${botId}/sys`;
const sys = (await createRpcClient(() => createHttpClient(url, { agent: agent }), optsRPC)).remote;
url = `http://localhost:${port}/${botId}/wa`;
const wa = (await createRpcClient(() => createHttpClient(url, { agent: agent }), optsRPC)).remote;
url = `http://localhost:${port}/${botId}/img`;
const img = (await createRpcClient(() => createHttpClient(url, { agent: agent }), optsRPC)).remote;
const timeout = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const ensureTokens = async firstTime => {
const REFRESH_THRESHOLD_MS = 10 * 60 * 1000; // 10 minutes in milliseconds
const tokens = this.tokens ? this.tokens.split(',') : [];
for (let i = 0; i < tokens.length; i++) {
const tokenName = tokens[i];
// Auto update Bearer authentication for the first token.
const expiresOn = new Date(global[tokenName + '_expiresOn']);
const expiration = expiresOn.getTime() - REFRESH_THRESHOLD_MS;
// Expires token 10min. before or if it the first time, load it.
if (expiration < Date.now() || firstTime) {
console.log('Expired. Refreshing token...' + expiration);
try {
const result = await sys.getCustomToken({ pid: this.pid, tokenName: tokenName });
global[tokenName] = result.token;
global[tokenName + '_expiresOn'] = result.expiresOn;
console.log('DONE:' + new Date(global[tokenName + '_expiresOn']));
} catch (error) {
console.error('Failed to refresh token for ' + tokenName + ':', error);
continue;
}
}
if (i == 0) {
headers['Authorization'] = 'Bearer ' + global[tokenName];
}
}
};
const sleep = async ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
const TOYAML = json => {
const doc = new YAML.Document();
doc.contents = json;
return doc.toString();
};
// Line of Business logic.
let __reportMerge = { adds: 0, updates: 0, skipped: 0 };
let __report = () => {
return (
__reportMerge.title +
' adds: ' +
__reportMerge.adds +
', updates: ' +
__reportMerge.updates +
' and skipped: ' +
__reportMerge.skipped +
'.'
);
};
let REPORT = 'No report yet';
try {
await ensureTokens(true);
//##INJECTED_CODE_HERE
} catch (e) {
console.log(e);
reject({ message: e.message, name: e.name });
} finally {
// Closes handles if any.
await wa.closeHandles({ pid: pid });
await sys.closeHandles({ pid: pid });
resolve(true);
}
})();