webfast 0.1.85 → 0.1.87

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/README.md CHANGED
@@ -130,6 +130,19 @@ program.modules.dependOn({REQUIRE},program,`{UNIQUE_NAME}-sync`,function(){
130
130
  console.log(`Depend On CallBack`);
131
131
  });
132
132
  ```
133
+ ## NEW BETA FEATURE
134
+ Feature where youo can add a special frame for multiple views through telegram without reloading
135
+ ````
136
+ await web.fast.telegram(`frame`).set(id,`https://${window.location.hostname}/concepts/esimco/package#${id}`,async function(id){
137
+ console.log(`Clicked Close`,id);
138
+ const frame = jQuery(`[wbfst-frame="${id}"]`);
139
+ console.log(`The Frame`,frame);
140
+ jQuery(frame).animate({ opacity:0 }, 600,function(){
141
+ jQuery(this).remove();
142
+ });
143
+
144
+ });
145
+ ````
133
146
 
134
147
  ## License
135
148
 
@@ -5,6 +5,16 @@ web.fast = {
5
5
  action : function(data,ell) {
6
6
  console.log(`Action Function`,data,ell);
7
7
  },
8
+ redirect :function(event) {
9
+ console.log(`Received Redirect`,event);
10
+ const state = event.type;
11
+ if (state == true) {
12
+ // Redirect
13
+ window.location.replace(event.url);
14
+ } else {
15
+ console.error(`Something wrong redirect`,event);
16
+ }
17
+ },
8
18
  functions : {
9
19
  isURL : function(str) {
10
20
  // Regular expression to check if a string is a URL
@@ -99,15 +109,68 @@ web.fast = {
99
109
  }
100
110
  },
101
111
  telegram : function(action){
102
- try {
103
- const telegram = window.Telegram;
104
- const actionFunction = telegram[action];
105
- console.log(`TELEGRAM`,action);
106
- return actionFunction;
107
- } catch (err) {
108
- //console.error(Err);
109
- console.error(`NO TELEGRAM`,action);
110
- return false;
112
+ // check if action is to set frame
113
+ if (action == `frame`) {
114
+ return {
115
+ get : async function(id) {
116
+ console.log(`Get Frame for ID`,id);
117
+ },
118
+ close : async function(id) {
119
+ console.log(`Close Frame`);
120
+ },
121
+ set : async function(id,url,closeAction,zIndex = 9990) {
122
+ if (web.fast.user != undefined) {
123
+ //console.error(`NO USER`);
124
+ //return window.location.href = url;
125
+ window.Telegram.WebApp.HapticFeedback.impactOccurred('medium');
126
+ }
127
+ console.log(`Telegram Frame Set`,id,url,closeAction);
128
+ let iframe = document.createElement('iframe');
129
+ iframe.src = url; // Replace with your desired URL
130
+
131
+ const settedID = ``+id;
132
+ // Set additional attributes (optional)
133
+ iframe.style.border = 'none'; // Remove the border
134
+ iframe.style.width = '100vw'; // Set width to 100vw
135
+ iframe.style.height = '100vh'; // Set height to 100vh
136
+ iframe.style.top = '0'; // Set height to 100vh
137
+ iframe.style.left = '0'; // Set height to 100vh
138
+ iframe.style[`z-index`] = zIndex; // Set height to 100vh
139
+ iframe.id = settedID;
140
+
141
+ iframe.style.position = 'fixed';
142
+
143
+ // Append the iframe to the body
144
+ document.body.appendChild(iframe);
145
+ jQuery(iframe).attr(`id`,settedID);
146
+ jQuery(iframe).attr(`wbfst-frame`,settedID);
147
+
148
+ try {
149
+ //window.Telegram.WebApp.web_app_open_link(url);
150
+ if (web.fast.user != undefined) {
151
+ window.closeIframe = function() {
152
+ console.log(`Close Iframe`,id);
153
+ //jQuery(`#${id}`).hide();
154
+ closeAction(id);
155
+ }
156
+ } else {
157
+ // Set on click event
158
+ if (closeAction != undefined) {
159
+ console.log(`Set Close Action`);
160
+ window.closeIframe = function() {
161
+ console.log(`Close Iframe`,id);
162
+ //jQuery(`#${id}`).hide();
163
+ closeAction(id);
164
+ }
165
+ }
166
+ }
167
+
168
+ } catch (err) {
169
+ console.error(err);
170
+ console.error(`Error opening link`,url);
171
+ }
172
+ }
173
+ }
111
174
  }
112
175
  }
113
176
  }
package/index.js CHANGED
@@ -112,7 +112,7 @@ module.exports = async function (array) {
112
112
 
113
113
  // Now include this thing then
114
114
  try {
115
- program.modules[reqFunc.name] = await reqFunc.run(program,reqFunc.name,reqFunc.functions);
115
+ program.modules[reqFunc.name.replace(`-sync`,``)] = await reqFunc.run(program,reqFunc.name,reqFunc.functions);
116
116
  if (callback != undefined) {
117
117
  return callback(program,name)
118
118
  } else {
@@ -0,0 +1,42 @@
1
+ const { MongoClient } = require('mongodb');
2
+
3
+ module.exports = async function(db, collection, dataToInsert) {
4
+ // Ensure the MongoDB connection string is provided
5
+ if (!process.env.mongo) {
6
+ console.error('MongoDB connection string not provided. Set process.env.mongo.');
7
+ process.exit(1);
8
+ }
9
+
10
+ // Define the MongoDB URI
11
+ const uri = process.env.mongo;
12
+
13
+ // Define the database and collection name
14
+ const dbName = db;
15
+ const collectionName = collection;
16
+
17
+ // Function to insert data
18
+ async function insertData() {
19
+ const client = new MongoClient(uri);
20
+
21
+ try {
22
+ await client.connect();
23
+ console.log('Connected to MongoDB server');
24
+
25
+ const database = client.db(dbName);
26
+ const collection = database.collection(collectionName);
27
+
28
+ // Insert the data
29
+ const result = await collection.insertOne(dataToInsert);
30
+ console.log(`Document inserted with _id: ${result.insertedId}`);
31
+ return result;
32
+ } catch (error) {
33
+ console.error('Error inserting document:', error);
34
+ } finally {
35
+ // Close the connection
36
+ await client.close();
37
+ }
38
+ }
39
+
40
+ // Execute the main function
41
+ return insertData().catch(console.error);
42
+ };
@@ -1,428 +1,444 @@
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
- }
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;
69
68
  }
70
- } else {
71
- routeData.func = require(routeData.path);
72
- exprs[routePath] = routeData;
73
69
  }
74
- } catch (err) {
75
- console.error(`Error Route Func`, routePath);
76
- console.error(err);
70
+ } else {
71
+ routeData.func = require(routeData.path);
72
+ exprs[routePath] = routeData;
77
73
  }
78
-
79
- routeData.webwalk = 0;
74
+ } catch (err) {
75
+ console.error(`Error Route Func`, routePath);
76
+ console.error(err);
80
77
  }
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;
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`);
110
156
  }
111
-
112
- console.log(`Routes are set up successfully`);
157
+
158
+ res.sendFile(contentFolder);
113
159
  } catch (err) {
114
160
  console.error(err);
115
- console.error(`Error Setting Up Routes`);
161
+ console.error(`Error Getting : ${req.params.type}`, req.params.file);
116
162
  }
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
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
136
181
  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`);
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;
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
+ })
333
+ }
334
+ }
335
+ }
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
+ }
156
349
  }
157
-
158
- res.sendFile(contentFolder);
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
+ const action = startSplit[1];
369
+
370
+ // Check action and if we have this action in custom routes thingy
371
+ try {
372
+ const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
373
+ await program.express.process.params(program,ws,action,uuid,parsedQuery,clientId,userJSON);
159
374
  } catch (err) {
160
- console.error(err);
161
- console.error(`Error Getting : ${req.params.type}`, req.params.file);
375
+ // Error for params
376
+ console.error(`Error for program params start_param`);
162
377
  }
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
378
  }
203
-
204
- app.listen(port, () => {
205
- console.log(`Server Listening`, port, basePath);
379
+
380
+ // Set up a ping interval to keep the connection alive
381
+ const pingInterval = setInterval(() => {
382
+ if (ws.readyState === WebSocket.OPEN) {
383
+ ws.ping();
384
+ } else {
385
+ // If the connection is closed, remove it from the map
386
+ clearInterval(pingInterval);
387
+ clients.delete(clientId);
388
+ console.log(`Removed disconnected socket with ID: ${clientId}`);
389
+ }
390
+ }, 5000); // Adjust the interval as needed
391
+
392
+ ws.on('close', () => {
393
+ console.log(`Socket Disconnected`);
394
+ clearInterval(pingInterval);
395
+ clients.delete(clientId);
206
396
  });
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;
397
+
398
+ // WebSocket on message event
399
+ ws.on('message', async (message) => {
400
+ //console.log(`Received message from ${clientId}: ${message}`);
401
+
402
+ try {
403
+ // Check for function
404
+ const json = JSON.parse(message.toString(`utf-8`));
405
+ const data = json.message;
406
+ const path = json.path;
407
+ const split = path.split(".")
408
+
409
+ // Check if function is running in program modules that you can add in the init scirpt when using remote
410
+ if (program.express.process != undefined) {
411
+ try {
412
+ let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId,ws);
413
+ if (resp != false) {
414
+ ws.send(JSON.stringify(resp));
415
+ }
416
+ } catch (err) {
417
+ console.error(`Error Running program.express.process for `,split[0],split[1],split[2]);
418
+ ws.send(JSON.stringify({
419
+ ts : Date.now(),
420
+ error : true,
421
+ message : `Error Event Program receive`
422
+ }));
423
+ }
424
+ }
425
+
426
+ // Add your custom on message logic here
427
+ // For example, you can broadcast the message to all connected clients
428
+ clients.forEach((client, id) => {
429
+ if (client.readyState === WebSocket.OPEN && id !== clientId) {
430
+ //ws.send(`Broadcast from ${clientId}: ${message}`);
431
+ }
217
432
  });
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
-
433
+
434
+ // Check if
435
+ } catch(err) {
436
+ console.error(`Error Something`);
437
+
438
+ }
439
+ });
440
+ });
441
+
442
+
443
+ return program;
444
+ };
@@ -0,0 +1,52 @@
1
+ module.exports = {
2
+ dependOn : [`modules.request.get`],
3
+ name : 'payment-sync',
4
+ run : async function(program,name) {
5
+ console.log(`Running ${name}`);
6
+
7
+ // Lets make a mockup for providers
8
+ const routesPath = program.path.join(__dirname,`providers`);
9
+ let moduleData = await program.modules.walkDirectory(routesPath);
10
+
11
+ // Set Module
12
+ let setModule = {
13
+ ts : Date.now()
14
+ }
15
+
16
+ // loop Throuh module data
17
+ for (let moduleIndex in moduleData) {
18
+ // Get the module
19
+ let module = moduleData[moduleIndex];
20
+ // Create module in setModule
21
+ try {
22
+ // We have set module
23
+ // read startup file
24
+ const mainModulePath = program.path.join(routesPath,`${module.name}`);
25
+ const startupPath = program.path.join(mainModulePath,`startup.js`);
26
+
27
+ // Check if program set path
28
+ if (program.set.path == undefined) {
29
+ continue;
30
+ }
31
+ const configRead = JSON.parse(program.fs.readFileSync(program.path.join(program.set.path,`payment.config.json`),`UTF-8`));
32
+ // Read
33
+ const json = configRead[module.name];
34
+ if (json == undefined) {
35
+ throw new Error(`NO JSON data found payment config ${module.name}`);
36
+ }
37
+ json.path = mainModulePath;
38
+ json.name = module.name;
39
+ setModule[module.name] = await require(startupPath)(program,json);
40
+ } catch (err) {
41
+ console.error(`Error Setting Module Data`,module.name);
42
+ console.error(err);
43
+ }
44
+ }
45
+
46
+ // Put in program modules
47
+ //program.modules.request = setModule;
48
+
49
+ // Here we can do whatever like grab modules for generator and represent them here
50
+ return setModule;
51
+ }
52
+ }
@@ -0,0 +1,130 @@
1
+ module.exports = async function(program,json) {
2
+ console.log(`Pocess Startup`);
3
+ // Process startup for mollie
4
+ if (!json.active) {
5
+ return false;
6
+ }
7
+
8
+ if (json.url[json.url.length-1] == `/`) {
9
+ json.url = json.url.slice(0, -1)
10
+ }
11
+
12
+ // When active startup process by indexing functions
13
+ const functionPath = program.path.join(json.path,`functions`);
14
+ console.log(`Function Path`);
15
+ let restArray = {
16
+ get : async function(url,params) {
17
+ console.log(`GET`);
18
+
19
+ // Process params for url
20
+ let count = 0;
21
+ for (let param in params) {
22
+ console.log(`Param ${param}`);
23
+ if (count == 0) {
24
+ url += `?`;
25
+ } else {
26
+ url += `&`
27
+ }
28
+ url += `${param}=${params[param]}`;
29
+ count++;
30
+ }
31
+
32
+ const data = await program.modules.request.get(program, url, undefined, {
33
+ 'Authorization': `Bearer ${json.key}`
34
+ })
35
+
36
+ return data;
37
+ },
38
+ post : async function(url,params) {
39
+ console.log(`POST`);
40
+
41
+ }
42
+ }
43
+
44
+ // Start sync
45
+ //https://api.frankfurter.app/latest?to=EUR%2CUSD
46
+ restArray.currencySync = async function() {
47
+ const data = await program.modules.request.get(program, `https://api.frankfurter.app/latest`);
48
+ // process
49
+ console.log(`Process Data`);
50
+ data.ts = Date.now();
51
+ program.tmp.currency = data;
52
+ }
53
+ restArray.int = setInterval(function(){
54
+ console.log(`Set INterval`);
55
+ restArray.currencySync();
56
+ console.log(Date.now(),program.tmp.currency);
57
+ },14 * 60 * 1000)
58
+
59
+ // Sync Onces
60
+ await restArray.currencySync();
61
+
62
+ // In init we want to do the get request
63
+ const getURL = `${json.url}/v2/methods/all`
64
+ const requestUSD = await restArray.get(getURL,{
65
+ locale : "en_US",
66
+ 'amount[value]' : "100.00",
67
+ 'amount[currency]' : "USD"
68
+ })
69
+
70
+ const requestEU = await restArray.get(getURL,{
71
+ locale : "en_US",
72
+ 'amount[value]' : "100.00",
73
+ 'amount[currency]' : "EUR"
74
+ })
75
+
76
+ // Process both
77
+ // Check who bigger then other
78
+ let mainLoop;
79
+ let subLoop;
80
+ if (requestEU.count > requestUSD.count) {
81
+ mainLoop = requestEU._embedded.methods;
82
+ subLoop = requestUSD._embedded.methods;
83
+ } else {
84
+ mainLoop = requestUSD._embedded.methods;
85
+ subLoop = requestEU._embedded.methods;
86
+ }
87
+
88
+ // Make paymentArray
89
+ let payar = {}
90
+
91
+ // Set to arrays
92
+ // Loop Through main
93
+ const loopthrough = [mainLoop,subLoop];
94
+ for (let l in loopthrough) {
95
+ let currentLoop = loopthrough[l];
96
+ for (let nm in currentLoop) {
97
+ const itemData = currentLoop[nm];
98
+
99
+ // Set data
100
+ if (itemData.status == undefined) {
101
+ continue;
102
+ }
103
+ if (payar[itemData.id] == undefined) {
104
+ payar[itemData.id] = {
105
+ desc : itemData.description,
106
+ status : itemData.status,
107
+ res : itemData.resource,
108
+ images : itemData.image,
109
+ currency : {}
110
+ }
111
+ }
112
+
113
+ // Now grab currency
114
+ const currency = {
115
+ max : itemData.maximumAmount.value,
116
+ min : itemData.minimumAmount.value
117
+ };
118
+
119
+ if (payar[itemData.id].currency[itemData.minimumAmount.currency] == undefined) {
120
+ payar[itemData.id].currency[itemData.minimumAmount.currency] = currency;
121
+ } else {
122
+ console.error(`Currency already set`);
123
+ }
124
+ }
125
+ }
126
+
127
+ restArray.methods = payar;
128
+
129
+ return restArray;
130
+ }
@@ -15,6 +15,10 @@ module.exports = async function(program, url, body,headers) {
15
15
  body: JSON.stringify(body),
16
16
  };
17
17
 
18
+ if (body == undefined) {
19
+ delete theOptions.body;
20
+ }
21
+
18
22
  // Using standard fetch function
19
23
  const response = await fetch(url, theOptions);
20
24
  // Get response body
@@ -24,7 +28,7 @@ module.exports = async function(program, url, body,headers) {
24
28
  const respHeaders = response.headers;
25
29
 
26
30
  if (!response.ok) {
27
- throw new Error(`HTTP error! Status: ${response.status}`);
31
+ throw new Error(respBody);
28
32
  }
29
33
 
30
34
  const responseData = respBody;
@@ -33,7 +37,7 @@ module.exports = async function(program, url, body,headers) {
33
37
  // Return response data or true to indicate success
34
38
  return responseData || true;
35
39
  } catch (err) {
36
- console.error('Error in post:', err.message);
40
+ console.error('Error in get:', err.message);
37
41
  return false;
38
42
  }
39
43
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webfast",
3
- "version": "0.1.85",
3
+ "version": "0.1.87",
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": {
@@ -35,7 +35,13 @@
35
35
  "model",
36
36
  "mini app",
37
37
  "webflow",
38
- "lowcode"
38
+ "lowcode",
39
+ "mollie",
40
+ "payment",
41
+ "ideal",
42
+ "creditcard",
43
+ "applepay",
44
+ "googlepay"
39
45
  ],
40
46
  "author": "Kai Gartner",
41
47
  "license": "ISC",