webfast 0.1.75 → 0.1.77

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,424 +1,428 @@
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`);
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);
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
- 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
-
178
+ const dirPath = program.path.join(program.set.contentPath,dirItem);
179
+ // Now read the dir
180
+ // Create app.get
88
181
  try {
89
- app[routeData.type](route, async (req, res) => {
182
+ const theRoute = `/inc/${dirItem}/*`;
183
+ app.get(theRoute, async (req, res) => {
184
+ const params = req.params;
185
+
90
186
  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);
187
+ const fullPath = program.path.join(dirPath,req.params[0]);
188
+ res.sendFile(fullPath);
98
189
  } catch (err) {
99
- console.error(`Error With Route:`, route);
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
- state = true;
196
+
104
197
  } catch (err) {
105
- console.error(err);
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
- 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`);
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.log(`${fileName} does not end with -min.js`);
283
+ console.error('Received data is outdated');
156
284
  }
157
-
158
- res.sendFile(contentFolder);
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
- // 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
- const dirPath = program.path.join(program.set.contentPath,dirItem);
176
- // Now read the dir
177
- // Create app.get
178
- try {
179
- const theRoute = `git pu${dirItem}/*`;
180
- app.get(theRoute, async (req, res) => {
181
- const params = req.params;
182
-
183
- try {
184
- const fullPath = program.path.join(dirPath,req.params[0]);
185
- res.sendFile(fullPath);
186
- } catch (err) {
187
- console.error(`Error Responding with route`);
188
- console.error(err);
189
- res.status(500);
190
- }
191
- console.log(`The Route is there`, theRoute);
192
- });
193
-
194
- } catch (err) {
195
- console.error(`Errro for path read dir including something`, diritem);
196
- }
197
- }
198
- console.log(`We have directory`);
199
- }
200
-
201
- app.listen(port, () => {
202
- console.log(`Server Listening`, port, basePath);
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
- program.express.url = {
206
- adaptive: {
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webfast",
3
- "version": "0.1.75",
3
+ "version": "0.1.77",
4
4
  "description": "WebFast! Bot Application, including TON mini-apps for makign it easy and fast to build ini-apps",
5
5
  "main": "index.js",
6
6
  "repository": {