webfast 0.1.75 → 0.1.78
Sign up to get free protection for your applications and to get access to all the features.
- package/modules/bots/applications/telegram/set.js +1 -1
- package/modules/express/init.js +412 -408
- package/package.json +1 -1
- package/example.js +0 -68
@@ -13,7 +13,7 @@ module.exports = {
|
|
13
13
|
addToCollection : async function (program,collectionName, fieldName, data,search) {
|
14
14
|
try {
|
15
15
|
await client.connect();
|
16
|
-
const db = client.db(
|
16
|
+
const db = client.db(process.env.dbName);
|
17
17
|
const collection = await db.collection(collectionName);
|
18
18
|
|
19
19
|
// Check if the field is an array in the existing document
|
package/modules/express/init.js
CHANGED
@@ -1,424 +1,428 @@
|
|
1
1
|
module.exports = async function (program) {
|
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
|
-
|
2
|
+
console.log(`Starting UP Express`);
|
3
|
+
program.express = {
|
4
|
+
ts: Date.now(),
|
5
|
+
process : program.set.process
|
6
|
+
};
|
7
|
+
|
8
|
+
const express = require('express');
|
9
|
+
const cors = require('cors');
|
10
|
+
const bodyParser = require('body-parser');
|
11
|
+
const WebSocket = require('ws');
|
12
|
+
const crypto = require(`crypto`)
|
13
|
+
const port = process.env.port;
|
14
|
+
const basePath = `/api`;
|
15
|
+
|
16
|
+
const app = express();
|
17
|
+
|
18
|
+
const corsOptions = {
|
19
|
+
origin: '*',
|
20
|
+
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
|
21
|
+
credentials: true,
|
22
|
+
optionsSuccessStatus: 204,
|
23
|
+
};
|
24
|
+
|
25
|
+
app.use(cors(corsOptions));
|
26
|
+
app.use(bodyParser.json());
|
27
|
+
app.use(bodyParser.urlencoded({ extended: true }));
|
28
|
+
app.set('view engine', 'ejs');
|
29
|
+
|
30
|
+
let routesPath = program.path.join(__dirname, `routes`);
|
31
|
+
// Check if custom routes path
|
32
|
+
if (program.set.path != undefined) {
|
33
|
+
routesPath = program.path.join(program.set.path, `routes`);
|
34
|
+
}
|
35
|
+
|
36
|
+
let exprs = {};
|
37
|
+
|
38
|
+
try {
|
39
|
+
let routesData = await program.modules.walkDirectory(routesPath);
|
40
|
+
|
41
|
+
for (let routeData of routesData) {
|
42
|
+
let routePath = `${basePath}/${routeData.name}`;
|
43
|
+
|
44
|
+
const split = routeData.name.split('.');
|
45
|
+
routeData.type = split.length > 1 ? split[split.length - 1] : 'get';
|
46
|
+
routeData.name = split.length > 1 ? split[0] : routeData.name;
|
47
|
+
|
48
|
+
const routeID = program.uuid.v4();
|
49
|
+
routeData.tempID = routeID;
|
50
|
+
|
51
|
+
try {
|
52
|
+
const stats = await program.fs.statSync(routeData.path);
|
53
|
+
const isDirectory = stats.isDirectory();
|
54
|
+
|
55
|
+
if (isDirectory) {
|
56
|
+
for (let subData of routeData.sub) {
|
57
|
+
if (subData !== undefined) {
|
58
|
+
const routeName = subData.name.replace('.get', '').replace('.post', '');
|
59
|
+
const subDataSplit = subData.path.split('.');
|
60
|
+
const type = subDataSplit[subDataSplit.length - 2];
|
61
|
+
|
62
|
+
subData.name = routeName;
|
63
|
+
delete subData.sub;
|
64
|
+
subData.type = type;
|
65
|
+
|
66
|
+
subData.func = require(subData.path);
|
67
|
+
exprs[routePath + '/' + routeName] = subData;
|
68
|
+
}
|
69
|
+
}
|
70
|
+
} else {
|
71
|
+
routeData.func = require(routeData.path);
|
72
|
+
exprs[routePath] = routeData;
|
73
|
+
}
|
74
|
+
} catch (err) {
|
75
|
+
console.error(`Error Route Func`, routePath);
|
76
|
+
console.error(err);
|
77
|
+
}
|
78
|
+
|
79
|
+
routeData.webwalk = 0;
|
80
|
+
}
|
81
|
+
|
82
|
+
program.express.routes = exprs;
|
83
|
+
|
84
|
+
for (let route in exprs) {
|
85
|
+
let routeData = exprs[route];
|
86
|
+
let state = false;
|
87
|
+
|
88
|
+
try {
|
89
|
+
app[routeData.type](route, async (req, res) => {
|
90
|
+
try {
|
91
|
+
exprs[route].webwalk++;
|
92
|
+
|
93
|
+
// Get body
|
94
|
+
const requestBody = req.body;
|
95
|
+
const reqParams = req.params;
|
96
|
+
|
97
|
+
await routeData.func(program, req, res, route, requestBody, reqParams);
|
98
|
+
} catch (err) {
|
99
|
+
console.error(`Error With Route:`, route);
|
100
|
+
console.error(err);
|
101
|
+
}
|
102
|
+
});
|
103
|
+
state = true;
|
104
|
+
} catch (err) {
|
105
|
+
console.error(err);
|
106
|
+
console.error(`Error Setting Up Route`);
|
107
|
+
}
|
108
|
+
|
109
|
+
exprs[route].state = state;
|
110
|
+
}
|
111
|
+
|
112
|
+
console.log(`Routes are set up successfully`);
|
113
|
+
} catch (err) {
|
114
|
+
console.error(err);
|
115
|
+
console.error(`Error Setting Up Routes`);
|
116
|
+
}
|
117
|
+
|
118
|
+
program.express.app = app;
|
119
|
+
|
120
|
+
// Let app listen for content
|
121
|
+
app.get(`/app/content/ton/manifest.json`, async (req, res) => {
|
122
|
+
// Let's create a json
|
123
|
+
const manifest = {
|
124
|
+
url: process.env.url,
|
125
|
+
name: process.env.name,
|
126
|
+
iconUrl: process.env.image
|
127
|
+
};
|
128
|
+
|
129
|
+
res.setHeader('Content-Type', 'application/json');
|
130
|
+
res.json(manifest);
|
131
|
+
});
|
132
|
+
|
133
|
+
app.get(`/app/content/:type/:file`, async (req, res) => {
|
134
|
+
console.log(`Content Get`);
|
135
|
+
// Try To get file from content folder
|
136
|
+
try {
|
137
|
+
const filePath = program.path.join(__dirname, `..`, `..`, `app`, `content`, req.params.type, req.params.file);
|
138
|
+
let contentFolder = filePath;
|
139
|
+
|
140
|
+
// Check if minify at the end
|
141
|
+
const fileName = req.params.file;
|
142
|
+
const isExtend = /-extend\.js$/.test(fileName);
|
143
|
+
|
144
|
+
// Check if extending
|
145
|
+
if (isExtend) {
|
146
|
+
console.log(`${fileName} ends with -extend.js`);
|
147
|
+
// IS extended file include loading in
|
148
|
+
|
149
|
+
const toRequestFile = req.params.file.replace(`-extend.js`, `.js`);
|
150
|
+
contentFolder = program.path.join(__dirname, `..`, `..`, `app`, `content`, req.params.type, toRequestFile);
|
151
|
+
// check if file exists in process, if not make it before giving out
|
152
|
+
// Check i
|
153
|
+
console.log(`Content Folder`);
|
154
|
+
} else {
|
155
|
+
console.log(`${fileName} does not end with -min.js`);
|
156
|
+
}
|
157
|
+
|
158
|
+
res.sendFile(contentFolder);
|
159
|
+
} catch (err) {
|
160
|
+
console.error(err);
|
161
|
+
console.error(`Error Getting : ${req.params.type}`, req.params.file);
|
162
|
+
}
|
163
|
+
})
|
164
|
+
|
165
|
+
// Walkt through for paths to be open
|
166
|
+
if (program.set.contentPath != undefined) {
|
167
|
+
// Loop Through
|
168
|
+
const readDir = program.fs.readdirSync(program.set.contentPath);
|
169
|
+
|
170
|
+
// Create request app path for it
|
171
|
+
//loop through
|
172
|
+
for (let rdi in readDir) {
|
173
|
+
// Loop
|
174
|
+
const dirItem = readDir[rdi];
|
175
|
+
if (dirItem == `.DS_store`) {
|
176
|
+
continue;
|
77
177
|
}
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
|
82
|
-
program.express.routes = exprs;
|
83
|
-
|
84
|
-
for (let route in exprs) {
|
85
|
-
let routeData = exprs[route];
|
86
|
-
let state = false;
|
87
|
-
|
178
|
+
const dirPath = program.path.join(program.set.contentPath,dirItem);
|
179
|
+
// Now read the dir
|
180
|
+
// Create app.get
|
88
181
|
try {
|
89
|
-
|
182
|
+
const theRoute = `/inc/${dirItem}/*`;
|
183
|
+
app.get(theRoute, async (req, res) => {
|
184
|
+
const params = req.params;
|
185
|
+
|
90
186
|
try {
|
91
|
-
|
92
|
-
|
93
|
-
// Get body
|
94
|
-
const requestBody = req.body;
|
95
|
-
const reqParams = req.params;
|
96
|
-
|
97
|
-
await routeData.func(program, req, res, route, requestBody, reqParams);
|
187
|
+
const fullPath = program.path.join(dirPath,req.params[0]);
|
188
|
+
res.sendFile(fullPath);
|
98
189
|
} catch (err) {
|
99
|
-
console.error(`Error
|
190
|
+
console.error(`Error Responding with route`);
|
100
191
|
console.error(err);
|
192
|
+
res.status(500);
|
101
193
|
}
|
194
|
+
console.log(`The Route is there`, theRoute);
|
102
195
|
});
|
103
|
-
|
196
|
+
|
104
197
|
} catch (err) {
|
105
|
-
console.error(
|
106
|
-
console.error(`Error Setting Up Route`);
|
198
|
+
console.error(`Errro for path read dir including something`, diritem);
|
107
199
|
}
|
108
|
-
|
109
|
-
exprs[route].state = state;
|
110
200
|
}
|
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
|
-
|
201
|
+
console.log(`We have directory`);
|
202
|
+
}
|
203
|
+
|
204
|
+
app.listen(port, () => {
|
205
|
+
console.log(`Server Listening`, port, basePath);
|
206
|
+
});
|
207
|
+
|
208
|
+
program.express.url = {
|
209
|
+
adaptive: {
|
210
|
+
get: [],
|
211
|
+
post: [],
|
212
|
+
},
|
213
|
+
set: function (requestPath, actionType, callback) {
|
214
|
+
program.express.url.adaptive[actionType] = app[actionType](requestPath, async (req, res) => {
|
215
|
+
let run = await callback(req, res, req.body, req.params);
|
216
|
+
return run;
|
217
|
+
});
|
218
|
+
return true;
|
219
|
+
},
|
220
|
+
};
|
221
|
+
|
222
|
+
program.express.setted = true;
|
223
|
+
|
224
|
+
let clients = new Map();
|
225
|
+
// Start socket thingy
|
226
|
+
const PORT = process.env.socket || 3000;
|
227
|
+
const wss = new WebSocket.Server({ port: PORT });
|
228
|
+
|
229
|
+
|
230
|
+
wss.on('connection', async (ws, req) => {
|
231
|
+
console.log(`Socket Connected`);
|
232
|
+
|
233
|
+
// Generate a unique ID for the WebSocket connection
|
234
|
+
const clientId = program.uuid.v4();
|
235
|
+
const reqURL = req.url;
|
236
|
+
console.log(`We have some data`, reqURL);
|
237
|
+
const queryStringWithoutQBT = reqURL.replace('/socket.io/?qbt=', '');
|
238
|
+
const queryParamsArray = queryStringWithoutQBT.split('&');
|
239
|
+
|
240
|
+
const parsedQuery = queryParamsArray.reduce((acc, param) => {
|
241
|
+
const [key, value] = param.split('=');
|
242
|
+
acc[key] = decodeURIComponent(value);
|
243
|
+
return acc;
|
244
|
+
}, {});
|
245
|
+
|
246
|
+
// Extract data from the parsed query
|
247
|
+
const { auth_date, query_id, user, hash } = parsedQuery;
|
248
|
+
|
249
|
+
// Stringify the 'user' field if it contains JSON data
|
250
|
+
if (user != undefined) {
|
251
|
+
try {
|
252
|
+
parsedQuery.user = JSON.stringify(parsedQuery.user);
|
253
|
+
} catch (error) {
|
254
|
+
console.error('Error parsing JSON in user field:', error);
|
255
|
+
}
|
256
|
+
}
|
257
|
+
|
258
|
+
// Construct the data check string
|
259
|
+
const sortedKeys = Object.keys(parsedQuery).sort();
|
260
|
+
const data_check_string = sortedKeys.map(key => `${key}=${String(parsedQuery[key])}`).join('\n');
|
261
|
+
|
262
|
+
function HMAC_SHA256(data, key) {
|
263
|
+
const hmac = crypto.createHmac('sha256', key);
|
264
|
+
hmac.update(data);
|
265
|
+
return hmac.digest('hex');
|
266
|
+
}
|
267
|
+
|
268
|
+
const bot_token = process.env.telegram; // replace with your actual bot token
|
269
|
+
const secret_key = HMAC_SHA256(bot_token, 'WebAppData');
|
270
|
+
const calculated_hash = HMAC_SHA256(data_check_string, secret_key);
|
271
|
+
|
272
|
+
const received_hash = hash; // replace with the actual received hash
|
273
|
+
|
274
|
+
if (calculated_hash === received_hash) {
|
275
|
+
// Data is from Telegram and has not been tampered with
|
276
|
+
// Additional check for auth_date if needed
|
277
|
+
const currentUnixTimestamp = Math.floor(new Date().getTime() / 1000);
|
278
|
+
if (parseInt(auth_date, 10) <= currentUnixTimestamp) {
|
279
|
+
// Data is not outdated
|
280
|
+
// Use the validated data as needed
|
281
|
+
console.log('Data from Telegram is valid');
|
154
282
|
} else {
|
155
|
-
console.
|
283
|
+
console.error('Received data is outdated');
|
156
284
|
}
|
157
|
-
|
158
|
-
|
159
|
-
} catch (err) {
|
160
|
-
console.error(err);
|
161
|
-
console.error(`Error Getting : ${req.params.type}`, req.params.file);
|
285
|
+
} else {
|
286
|
+
console.error('Received data has been tampered with');
|
162
287
|
}
|
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
|
-
|
288
|
+
|
289
|
+
|
290
|
+
// Store the WebSocket connection with its ID in the map
|
291
|
+
clients.set(clientId, ws);
|
292
|
+
|
293
|
+
// Send the client ID to the connected client
|
294
|
+
let getUser;
|
295
|
+
if (parsedQuery.user != undefined) {
|
296
|
+
// Get user
|
297
|
+
const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
|
298
|
+
getUser = await program.modules.data.find(process.env.dbName,`telegram`,{
|
299
|
+
id : userJSON.id
|
300
|
+
},true,{image:true,program,async function(program,json){
|
301
|
+
// Get firs timage
|
302
|
+
console.log(`User JSON`);
|
303
|
+
let image;
|
304
|
+
let allImages = [];
|
305
|
+
if (json.images != undefined) {
|
306
|
+
image = json.images[Object.keys(json.images)[0]];
|
307
|
+
|
308
|
+
// Create path if not exists
|
309
|
+
async function routeExists(path) {
|
310
|
+
return program.express.app._router.stack.some(layer => {
|
311
|
+
if (layer.route) {
|
312
|
+
return layer.route.path === path;
|
313
|
+
}
|
314
|
+
return false;
|
315
|
+
});
|
316
|
+
}
|
317
|
+
|
318
|
+
for (const image in json.images) {
|
319
|
+
console.log(`Set image url's`);
|
320
|
+
|
321
|
+
const imagePath = `/user/dynamic/image/${image}.${json.images[image].meta.type}`;
|
322
|
+
const routeCheck = await routeExists(imagePath);
|
323
|
+
const fullPath = `${process.env.url}${imagePath.slice(1)}`;
|
324
|
+
allImages.push(fullPath);
|
325
|
+
if (!routeCheck) {
|
326
|
+
// Create route
|
327
|
+
const fullImageData = json.images[image];
|
328
|
+
program.express.app.get(imagePath, async (req,res) => {
|
329
|
+
console.log(`Request for`,imagePath);
|
330
|
+
// set headers
|
331
|
+
res.set('Content-Type', `image/${fullImageData.meta.type}`);
|
332
|
+
res.send(fullImageData.buffer);
|
333
|
+
})
|
334
|
+
}
|
335
|
+
}
|
336
|
+
}
|
337
|
+
// Now we have the image data
|
338
|
+
console.log(`Image Data`);
|
339
|
+
// Further more we want to send some data
|
340
|
+
const sendKeys = [`id`,`first_name`,`username`,`uuid`];
|
341
|
+
|
342
|
+
// Crerate little loop for the data to be send in json format to be processed
|
343
|
+
let sendData = {};
|
344
|
+
for (let sd in sendKeys) {
|
345
|
+
let key = sendKeys[sd];
|
346
|
+
// Get object
|
347
|
+
if (json[key] != undefined) {
|
348
|
+
sendData[key] = json[key];
|
349
|
+
}
|
350
|
+
}
|
351
|
+
console.log(`Preparing for sending`);
|
352
|
+
sendData.images = allImages;
|
353
|
+
|
354
|
+
// TODO ADD OTHER DATA
|
355
|
+
//program.express.process.socket.api.
|
356
|
+
// TODO location
|
357
|
+
ws.send(JSON.stringify({ type: 'user', clientId: clientId, data : sendData }));
|
358
|
+
|
359
|
+
}});
|
360
|
+
}
|
361
|
+
//ws.send(JSON.stringify({ type: 'clientId', id: clientId, params: parsedQuery }));
|
362
|
+
|
363
|
+
// Set up a ping interval to keep the connection alive
|
364
|
+
const pingInterval = setInterval(() => {
|
365
|
+
if (ws.readyState === WebSocket.OPEN) {
|
366
|
+
ws.ping();
|
367
|
+
} else {
|
368
|
+
// If the connection is closed, remove it from the map
|
369
|
+
clearInterval(pingInterval);
|
370
|
+
clients.delete(clientId);
|
371
|
+
console.log(`Removed disconnected socket with ID: ${clientId}`);
|
372
|
+
}
|
373
|
+
}, 5000); // Adjust the interval as needed
|
374
|
+
|
375
|
+
ws.on('close', () => {
|
376
|
+
console.log(`Socket Disconnected`);
|
377
|
+
clearInterval(pingInterval);
|
378
|
+
clients.delete(clientId);
|
379
|
+
});
|
380
|
+
|
381
|
+
// WebSocket on message event
|
382
|
+
ws.on('message', async (message) => {
|
383
|
+
//console.log(`Received message from ${clientId}: ${message}`);
|
384
|
+
|
385
|
+
try {
|
386
|
+
// Check for function
|
387
|
+
const json = JSON.parse(message.toString(`utf-8`));
|
388
|
+
const data = json.message;
|
389
|
+
const path = json.path;
|
390
|
+
const split = path.split(".")
|
391
|
+
|
392
|
+
// Check if function is running in program modules that you can add in the init scirpt when using remote
|
393
|
+
if (program.express.process != undefined) {
|
394
|
+
try {
|
395
|
+
let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId);
|
396
|
+
if (resp != false) {
|
397
|
+
ws.send(JSON.stringify(resp));
|
398
|
+
}
|
399
|
+
} catch (err) {
|
400
|
+
console.error(`Error Running program.express.process for `,split[0],split[1],split[2]);
|
401
|
+
ws.send(JSON.stringify({
|
402
|
+
ts : Date.now(),
|
403
|
+
error : true,
|
404
|
+
message : `Error Event Program receive`
|
405
|
+
}));
|
406
|
+
}
|
407
|
+
}
|
408
|
+
|
409
|
+
// Add your custom on message logic here
|
410
|
+
// For example, you can broadcast the message to all connected clients
|
411
|
+
clients.forEach((client, id) => {
|
412
|
+
if (client.readyState === WebSocket.OPEN && id !== clientId) {
|
413
|
+
//ws.send(`Broadcast from ${clientId}: ${message}`);
|
414
|
+
}
|
415
|
+
});
|
416
|
+
|
417
|
+
// Check if
|
418
|
+
} catch(err) {
|
419
|
+
console.error(`Error Something`);
|
420
|
+
|
421
|
+
}
|
422
|
+
});
|
203
423
|
});
|
204
|
-
|
205
|
-
|
206
|
-
|
207
|
-
get: [],
|
208
|
-
post: [],
|
209
|
-
},
|
210
|
-
set: function (requestPath, actionType, callback) {
|
211
|
-
program.express.url.adaptive[actionType] = app[actionType](requestPath, async (req, res) => {
|
212
|
-
let run = await callback(req, res, req.body, req.params);
|
213
|
-
return run;
|
214
|
-
});
|
215
|
-
return true;
|
216
|
-
},
|
424
|
+
|
425
|
+
|
426
|
+
return program;
|
217
427
|
};
|
218
|
-
|
219
|
-
program.express.setted = true;
|
220
|
-
|
221
|
-
let clients = new Map();
|
222
|
-
// Start socket thingy
|
223
|
-
const PORT = process.env.socket || 3000;
|
224
|
-
const wss = new WebSocket.Server({ port: PORT });
|
225
|
-
|
226
|
-
|
227
|
-
wss.on('connection', async (ws, req) => {
|
228
|
-
console.log(`Socket Connected`);
|
229
|
-
|
230
|
-
// Generate a unique ID for the WebSocket connection
|
231
|
-
const clientId = program.uuid.v4();
|
232
|
-
const reqURL = req.url;
|
233
|
-
console.log(`We have some data`, reqURL);
|
234
|
-
const queryStringWithoutQBT = reqURL.replace('/socket.io/?qbt=', '');
|
235
|
-
const queryParamsArray = queryStringWithoutQBT.split('&');
|
236
|
-
|
237
|
-
const parsedQuery = queryParamsArray.reduce((acc, param) => {
|
238
|
-
const [key, value] = param.split('=');
|
239
|
-
acc[key] = decodeURIComponent(value);
|
240
|
-
return acc;
|
241
|
-
}, {});
|
242
|
-
|
243
|
-
// Extract data from the parsed query
|
244
|
-
const { auth_date, query_id, user, hash } = parsedQuery;
|
245
|
-
|
246
|
-
// Stringify the 'user' field if it contains JSON data
|
247
|
-
if (user != undefined) {
|
248
|
-
try {
|
249
|
-
parsedQuery.user = JSON.stringify(parsedQuery.user);
|
250
|
-
} catch (error) {
|
251
|
-
console.error('Error parsing JSON in user field:', error);
|
252
|
-
}
|
253
|
-
}
|
254
|
-
|
255
|
-
// Construct the data check string
|
256
|
-
const sortedKeys = Object.keys(parsedQuery).sort();
|
257
|
-
const data_check_string = sortedKeys.map(key => `${key}=${String(parsedQuery[key])}`).join('\n');
|
258
|
-
|
259
|
-
function HMAC_SHA256(data, key) {
|
260
|
-
const hmac = crypto.createHmac('sha256', key);
|
261
|
-
hmac.update(data);
|
262
|
-
return hmac.digest('hex');
|
263
|
-
}
|
264
|
-
|
265
|
-
const bot_token = process.env.telegram; // replace with your actual bot token
|
266
|
-
const secret_key = HMAC_SHA256(bot_token, 'WebAppData');
|
267
|
-
const calculated_hash = HMAC_SHA256(data_check_string, secret_key);
|
268
|
-
|
269
|
-
const received_hash = hash; // replace with the actual received hash
|
270
|
-
|
271
|
-
if (calculated_hash === received_hash) {
|
272
|
-
// Data is from Telegram and has not been tampered with
|
273
|
-
// Additional check for auth_date if needed
|
274
|
-
const currentUnixTimestamp = Math.floor(new Date().getTime() / 1000);
|
275
|
-
if (parseInt(auth_date, 10) <= currentUnixTimestamp) {
|
276
|
-
// Data is not outdated
|
277
|
-
// Use the validated data as needed
|
278
|
-
console.log('Data from Telegram is valid');
|
279
|
-
} else {
|
280
|
-
console.error('Received data is outdated');
|
281
|
-
}
|
282
|
-
} else {
|
283
|
-
console.error('Received data has been tampered with');
|
284
|
-
}
|
285
|
-
|
286
|
-
|
287
|
-
// Store the WebSocket connection with its ID in the map
|
288
|
-
clients.set(clientId, ws);
|
289
|
-
|
290
|
-
// Send the client ID to the connected client
|
291
|
-
let getUser;
|
292
|
-
if (parsedQuery.user != undefined) {
|
293
|
-
// Get user
|
294
|
-
const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
|
295
|
-
getUser = await program.modules.data.find(process.env.dbName,`telegram`,{
|
296
|
-
id : userJSON.id
|
297
|
-
},true,{image:true,program,async function(program,json){
|
298
|
-
// Get firs timage
|
299
|
-
console.log(`User JSON`);
|
300
|
-
let image;
|
301
|
-
let allImages = [];
|
302
|
-
if (json.images != undefined) {
|
303
|
-
image = json.images[Object.keys(json.images)[0]];
|
304
|
-
|
305
|
-
// Create path if not exists
|
306
|
-
async function routeExists(path) {
|
307
|
-
return program.express.app._router.stack.some(layer => {
|
308
|
-
if (layer.route) {
|
309
|
-
return layer.route.path === path;
|
310
|
-
}
|
311
|
-
return false;
|
312
|
-
});
|
313
|
-
}
|
314
|
-
|
315
|
-
for (const image in json.images) {
|
316
|
-
console.log(`Set image url's`);
|
317
|
-
|
318
|
-
const imagePath = `/user/dynamic/image/${image}.${json.images[image].meta.type}`;
|
319
|
-
const routeCheck = await routeExists(imagePath);
|
320
|
-
const fullPath = `${process.env.url}${imagePath.slice(1)}`;
|
321
|
-
allImages.push(fullPath);
|
322
|
-
if (!routeCheck) {
|
323
|
-
// Create route
|
324
|
-
const fullImageData = json.images[image];
|
325
|
-
program.express.app.get(imagePath, async (req,res) => {
|
326
|
-
console.log(`Request for`,imagePath);
|
327
|
-
// set headers
|
328
|
-
res.set('Content-Type', `image/${fullImageData.meta.type}`);
|
329
|
-
res.send(fullImageData.buffer);
|
330
|
-
})
|
331
|
-
}
|
332
|
-
}
|
333
|
-
}
|
334
|
-
// Now we have the image data
|
335
|
-
console.log(`Image Data`);
|
336
|
-
// Further more we want to send some data
|
337
|
-
const sendKeys = [`id`,`first_name`,`username`,`uuid`];
|
338
|
-
|
339
|
-
// Crerate little loop for the data to be send in json format to be processed
|
340
|
-
let sendData = {};
|
341
|
-
for (let sd in sendKeys) {
|
342
|
-
let key = sendKeys[sd];
|
343
|
-
// Get object
|
344
|
-
if (json[key] != undefined) {
|
345
|
-
sendData[key] = json[key];
|
346
|
-
}
|
347
|
-
}
|
348
|
-
console.log(`Preparing for sending`);
|
349
|
-
sendData.images = allImages;
|
350
|
-
|
351
|
-
// TODO ADD OTHER DATA
|
352
|
-
//program.express.process.socket.api.
|
353
|
-
// TODO location
|
354
|
-
ws.send(JSON.stringify({ type: 'user', clientId: clientId, data : sendData }));
|
355
|
-
|
356
|
-
}});
|
357
|
-
}
|
358
|
-
//ws.send(JSON.stringify({ type: 'clientId', id: clientId, params: parsedQuery }));
|
359
|
-
|
360
|
-
// Set up a ping interval to keep the connection alive
|
361
|
-
const pingInterval = setInterval(() => {
|
362
|
-
if (ws.readyState === WebSocket.OPEN) {
|
363
|
-
ws.ping();
|
364
|
-
} else {
|
365
|
-
// If the connection is closed, remove it from the map
|
366
|
-
clearInterval(pingInterval);
|
367
|
-
clients.delete(clientId);
|
368
|
-
console.log(`Removed disconnected socket with ID: ${clientId}`);
|
369
|
-
}
|
370
|
-
}, 5000); // Adjust the interval as needed
|
371
|
-
|
372
|
-
ws.on('close', () => {
|
373
|
-
console.log(`Socket Disconnected`);
|
374
|
-
clearInterval(pingInterval);
|
375
|
-
clients.delete(clientId);
|
376
|
-
});
|
377
|
-
|
378
|
-
// WebSocket on message event
|
379
|
-
ws.on('message', async (message) => {
|
380
|
-
//console.log(`Received message from ${clientId}: ${message}`);
|
381
|
-
|
382
|
-
try {
|
383
|
-
// Check for function
|
384
|
-
const json = JSON.parse(message.toString(`utf-8`));
|
385
|
-
const data = json.message;
|
386
|
-
const path = json.path;
|
387
|
-
const split = path.split(".")
|
388
|
-
|
389
|
-
// Check if function is running in program modules that you can add in the init scirpt when using remote
|
390
|
-
if (program.express.process != undefined) {
|
391
|
-
try {
|
392
|
-
let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId);
|
393
|
-
if (resp != false) {
|
394
|
-
ws.send(JSON.stringify(resp));
|
395
|
-
}
|
396
|
-
} catch (err) {
|
397
|
-
console.error(`Error Running program.express.process for `,split[0],split[1],split[2]);
|
398
|
-
ws.send(JSON.stringify({
|
399
|
-
ts : Date.now(),
|
400
|
-
error : true,
|
401
|
-
message : `Error Event Program receive`
|
402
|
-
}));
|
403
|
-
}
|
404
|
-
}
|
405
|
-
|
406
|
-
// Add your custom on message logic here
|
407
|
-
// For example, you can broadcast the message to all connected clients
|
408
|
-
clients.forEach((client, id) => {
|
409
|
-
if (client.readyState === WebSocket.OPEN && id !== clientId) {
|
410
|
-
//ws.send(`Broadcast from ${clientId}: ${message}`);
|
411
|
-
}
|
412
|
-
});
|
413
|
-
|
414
|
-
// Check if
|
415
|
-
} catch(err) {
|
416
|
-
console.error(`Error Something`);
|
417
|
-
|
418
|
-
}
|
419
|
-
});
|
420
|
-
});
|
421
|
-
|
422
|
-
|
423
|
-
return program;
|
424
|
-
};
|
428
|
+
|
package/package.json
CHANGED
package/example.js
DELETED
@@ -1,68 +0,0 @@
|
|
1
|
-
const path = require(`path`);
|
2
|
-
const contentPath = path.join(__dirname,`example`,`content`)
|
3
|
-
let setArray = {
|
4
|
-
wget : '/usr/local/bin/wget',
|
5
|
-
process : {
|
6
|
-
ts : Date.now(),
|
7
|
-
socket : {
|
8
|
-
api : {
|
9
|
-
list : function(program,ws,json,data,path) {
|
10
|
-
// Example to create process for websocket path action and process data
|
11
|
-
console.log(`Example of list process`);
|
12
|
-
|
13
|
-
function generateRandomText(length) {
|
14
|
-
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
15
|
-
let result = '';
|
16
|
-
|
17
|
-
for (let i = 0; i < length; i++) {
|
18
|
-
result += characters.charAt(Math.floor(Math.random() * characters.length));
|
19
|
-
}
|
20
|
-
|
21
|
-
return result;
|
22
|
-
}
|
23
|
-
|
24
|
-
|
25
|
-
// Loop for example through
|
26
|
-
let exampleData = {
|
27
|
-
list : [],
|
28
|
-
ell : data.ell,
|
29
|
-
action : data.action
|
30
|
-
}
|
31
|
-
|
32
|
-
const pushData = {};
|
33
|
-
for (let i in data.other.items) {
|
34
|
-
const item = data.other.items[i];
|
35
|
-
// We have itme
|
36
|
-
const id = item.id;
|
37
|
-
const key = item.name;
|
38
|
-
|
39
|
-
pushData[key] = {
|
40
|
-
id : id,
|
41
|
-
text : generateRandomText(10)
|
42
|
-
}
|
43
|
-
}
|
44
|
-
|
45
|
-
pushData.uuid = program.uuid.v4();
|
46
|
-
exampleData.list.push(pushData);
|
47
|
-
|
48
|
-
// Send websocket message create standard
|
49
|
-
const sendObject = {
|
50
|
-
func : data.function,
|
51
|
-
data : exampleData,
|
52
|
-
js : `console.log("RUN FROM BACKEND")`
|
53
|
-
}
|
54
|
-
|
55
|
-
// Sedn back to front-end
|
56
|
-
//ws.send();
|
57
|
-
|
58
|
-
return sendObject;
|
59
|
-
}
|
60
|
-
}
|
61
|
-
}
|
62
|
-
},
|
63
|
-
contentPath : contentPath
|
64
|
-
};
|
65
|
-
|
66
|
-
|
67
|
-
let program = require(path.join(__dirname,`index.js`))(setArray);
|
68
|
-
console.log(`Required`);
|