webfast 0.1.86 → 0.1.88

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.
@@ -1,428 +1,449 @@
1
1
  module.exports = async function (program) {
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`);
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;
34
110
  }
35
-
36
- let exprs = {};
37
-
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
38
136
  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;
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;
177
+ }
178
+ const dirPath = program.path.join(program.set.contentPath,dirItem);
179
+ // Now read the dir
180
+ // Create app.get
181
+ try {
182
+ const theRoute = `/inc/${dirItem}/*`;
183
+ app.get(theRoute, async (req, res) => {
184
+ const params = req.params;
185
+
186
+ try {
187
+ const fullPath = program.path.join(dirPath,req.params[0]);
188
+ res.sendFile(fullPath);
189
+ } catch (err) {
190
+ console.error(`Error Responding with route`);
191
+ console.error(err);
192
+ res.status(500);
193
+ }
194
+ console.log(`The Route is there`, theRoute);
195
+ });
196
+
197
+ } catch (err) {
198
+ console.error(`Errro for path read dir including something`, diritem);
199
+ }
200
+ }
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');
282
+ } else {
283
+ console.error('Received data is outdated');
284
+ }
285
+ } else {
286
+ console.error('Received data has been tampered with');
287
+ }
288
+
289
+ // Store the WebSocket connection with its ID in the map
290
+ clients.set(clientId, ws);
291
+
292
+ // Send the client ID to the connected client
293
+ let getUser;
294
+ if (parsedQuery.user != undefined) {
295
+ // Get user
296
+ const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
297
+ getUser = await program.modules.data.find(process.env.dbName,`telegram`,{
298
+ id : userJSON.id
299
+ },true,{image:true,program,async function(program,json){
300
+ // Get firs timage
301
+ console.log(`User JSON`);
302
+ let image;
303
+ let allImages = [];
304
+ if (json.images != undefined) {
305
+ image = json.images[Object.keys(json.images)[0]];
306
+
307
+ // Create path if not exists
308
+ async function routeExists(path) {
309
+ return program.express.app._router.stack.some(layer => {
310
+ if (layer.route) {
311
+ return layer.route.path === path;
68
312
  }
313
+ return false;
314
+ });
315
+ }
316
+
317
+ for (const image in json.images) {
318
+ console.log(`Set image url's`);
319
+
320
+ const imagePath = `/user/dynamic/image/${image}.${json.images[image].meta.type}`;
321
+ const routeCheck = await routeExists(imagePath);
322
+ const fullPath = `${process.env.url}${imagePath.slice(1)}`;
323
+ allImages.push(fullPath);
324
+ if (!routeCheck) {
325
+ // Create route
326
+ const fullImageData = json.images[image];
327
+ program.express.app.get(imagePath, async (req,res) => {
328
+ console.log(`Request for`,imagePath);
329
+ // set headers
330
+ res.set('Content-Type', `image/${fullImageData.meta.type}`);
331
+ res.send(fullImageData.buffer);
332
+ })
69
333
  }
70
- } else {
71
- routeData.func = require(routeData.path);
72
- exprs[routePath] = routeData;
73
334
  }
74
- } catch (err) {
75
- console.error(`Error Route Func`, routePath);
76
- console.error(err);
77
335
  }
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
-
336
+ // Now we have the image data
337
+ console.log(`Image Data`);
338
+ // Further more we want to send some data
339
+ const sendKeys = [`id`,`first_name`,`username`,`uuid`];
340
+
341
+ // Crerate little loop for the data to be send in json format to be processed
342
+ let sendData = {};
343
+ for (let sd in sendKeys) {
344
+ let key = sendKeys[sd];
345
+ // Get object
346
+ if (json[key] != undefined) {
347
+ sendData[key] = json[key];
348
+ }
349
+ }
350
+ console.log(`Preparing for sending`);
351
+ sendData.images = allImages;
352
+
353
+ // TODO ADD OTHER DATA
354
+ //program.express.process.socket.api.
355
+ // TODO location
356
+ ws.send(JSON.stringify({ type: 'user', clientId: clientId, data : sendData }));
357
+ }});
358
+ }
359
+ //ws.send(JSON.stringify({ type: 'clientId', id: clientId, params: parsedQuery }));
360
+
361
+
362
+ // Check if data has order
363
+ // Check if action in this params and also if action order if user order
364
+ // otherwise who error
365
+ if (parsedQuery.start_param != undefined) {
366
+ const startSplit = parsedQuery.start_param.split(`__`);
367
+ const uuid = startSplit[0];
368
+
369
+ if (startSplit.length <= 1) {
370
+ console.log(`Start split is one`);
371
+ } else {
372
+ const action = startSplit[1];
373
+
374
+ // Check action and if we have this action in custom routes thingy
88
375
  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;
376
+ const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
377
+ await program.express.process.params(program,ws,action,uuid,parsedQuery,clientId,userJSON);
104
378
  } catch (err) {
105
- console.error(err);
106
- console.error(`Error Setting Up Route`);
379
+ // Error for params
380
+ console.error(`Error for program params start_param`);
107
381
  }
108
-
109
- exprs[route].state = state;
110
382
  }
111
-
112
- console.log(`Routes are set up successfully`);
113
- } catch (err) {
114
- console.error(err);
115
- console.error(`Error Setting Up Routes`);
116
383
  }
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);
384
+
385
+ // Set up a ping interval to keep the connection alive
386
+ const pingInterval = setInterval(() => {
387
+ if (ws.readyState === WebSocket.OPEN) {
388
+ ws.ping();
389
+ } else {
390
+ // If the connection is closed, remove it from the map
391
+ clearInterval(pingInterval);
392
+ clients.delete(clientId);
393
+ console.log(`Removed disconnected socket with ID: ${clientId}`);
394
+ }
395
+ }, 5000); // Adjust the interval as needed
396
+
397
+ ws.on('close', () => {
398
+ console.log(`Socket Disconnected`);
399
+ clearInterval(pingInterval);
400
+ clients.delete(clientId);
131
401
  });
132
-
133
- app.get(`/app/content/:type/:file`, async (req, res) => {
134
- console.log(`Content Get`);
135
- // Try To get file from content folder
402
+
403
+ // WebSocket on message event
404
+ ws.on('message', async (message) => {
405
+ //console.log(`Received message from ${clientId}: ${message}`);
406
+
136
407
  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`);
408
+ // Check for function
409
+ const json = JSON.parse(message.toString(`utf-8`));
410
+ const data = json.message;
411
+ const path = json.path;
412
+ const split = path.split(".")
413
+
414
+ // Check if function is running in program modules that you can add in the init scirpt when using remote
415
+ if (program.express.process != undefined) {
416
+ try {
417
+ let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId,ws,parsedQuery);
418
+ if (resp != false) {
419
+ ws.send(JSON.stringify(resp));
420
+ }
421
+ } catch (err) {
422
+ console.error(`Error Running program.express.process for `,split[0],split[1],split[2]);
423
+ ws.send(JSON.stringify({
424
+ ts : Date.now(),
425
+ error : true,
426
+ message : `Error Event Program receive`
427
+ }));
428
+ }
156
429
  }
157
-
158
- res.sendFile(contentFolder);
159
- } catch (err) {
160
- console.error(err);
161
- console.error(`Error Getting : ${req.params.type}`, req.params.file);
430
+
431
+ // Add your custom on message logic here
432
+ // For example, you can broadcast the message to all connected clients
433
+ clients.forEach((client, id) => {
434
+ if (client.readyState === WebSocket.OPEN && id !== clientId) {
435
+ //ws.send(`Broadcast from ${clientId}: ${message}`);
436
+ }
437
+ });
438
+
439
+ // Check if
440
+ } catch(err) {
441
+ console.error(`Error Something`);
442
+
162
443
  }
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;
177
- }
178
- const dirPath = program.path.join(program.set.contentPath,dirItem);
179
- // Now read the dir
180
- // Create app.get
181
- try {
182
- const theRoute = `/inc/${dirItem}/*`;
183
- app.get(theRoute, async (req, res) => {
184
- const params = req.params;
185
-
186
- try {
187
- const fullPath = program.path.join(dirPath,req.params[0]);
188
- res.sendFile(fullPath);
189
- } catch (err) {
190
- console.error(`Error Responding with route`);
191
- console.error(err);
192
- res.status(500);
193
- }
194
- console.log(`The Route is there`, theRoute);
195
- });
196
-
197
- } catch (err) {
198
- console.error(`Errro for path read dir including something`, diritem);
199
- }
200
- }
201
- console.log(`We have directory`);
202
- }
203
-
204
- app.listen(port, () => {
205
- console.log(`Server Listening`, port, basePath);
206
444
  });
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');
282
- } else {
283
- console.error('Received data is outdated');
284
- }
285
- } else {
286
- console.error('Received data has been tampered with');
287
- }
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,ws);
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
- });
423
- });
424
-
425
-
426
- return program;
427
- };
428
-
445
+ });
446
+
447
+
448
+ return program;
449
+ };