webfast 0.1.52 → 0.1.54

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.
@@ -127,8 +127,52 @@ web.fast.connectWebSocket = function(socketURL,maxRetries = 40, retries = 0) {
127
127
  };
128
128
 
129
129
  ws.onmessage = (event) => {
130
- //console.log('Received:', event.data);
130
+ console.log('Received:', event.data);
131
131
  // Handle received data
132
+ // Check if type user then we will walk through the data to set the data for the user
133
+ const json = JSON.parse(event.data);
134
+ if (json.type == `user`) {
135
+ // We have user data
136
+ console.log(`Set User Data`);
137
+ // Now go Through to set all data
138
+ // Get all webfast client
139
+ jQuery(`[webfast-client]`).each(function(){
140
+ // Get type
141
+ const clientType = jQuery(this).attr(`webfast-client`);
142
+ console.log(`Client Type`);
143
+ // Check split
144
+ const split = clientType.replace(/ /g,``).split(`||`);
145
+
146
+ // set check
147
+ let setted = false;
148
+ for (let s in split) {
149
+ // Get value
150
+ let getValue = split[s];
151
+ // Get value from json.data
152
+ if (json.data[getValue] != undefined && setted == false) {
153
+ const toSetValue = json.data[getValue];
154
+ console.log(`Set Value`,toSetValue);
155
+ jQuery(this).html(toSetValue)
156
+ setted = true;
157
+ }
158
+ }
159
+ })
160
+
161
+ if (json.data.images != undefined) {
162
+ console.log(`Set Images`,json.data.images);
163
+ const oneImage = json.data.images[json.data.images.length-1];
164
+ console.log(oneImage);
165
+ jQuery(`[webfast-client="image"]`).each(function(){
166
+ console.log(`Setted`);
167
+ jQuery(this).css({
168
+ 'background-image': `url(${oneImage})`,
169
+ 'background-size': 'cover',
170
+ 'background-position': 'center'
171
+ });
172
+ });
173
+ }
174
+ }
175
+
132
176
  web.fast.que.state = Date.now();
133
177
  web.fast.receive(`socket`,event.data); // Placeholder for processing response
134
178
  };
@@ -62,7 +62,7 @@ module.exports = {
62
62
  downloadAndConvertToBase64 : async (program, photoURL, callback,data) => {
63
63
  try {
64
64
  // Use wget to download the image
65
- const { stdout, stderr } = await program.exec(`${program.set.wget} -O - ${photoURL}`, { encoding: 'buffer' });
65
+ const { stdout, stderr } = await program.exec(`${program.set.wget} -O - "${photoURL}"`, { encoding: 'buffer' });
66
66
 
67
67
  // Check if the download was successful
68
68
  const errBuf = Buffer.from(stderr);
@@ -14,7 +14,7 @@ module.exports = {
14
14
  try {
15
15
  await client.connect();
16
16
  const db = client.db('eventgo');
17
- const collection = db.collection(collectionName);
17
+ const collection = await db.collection(collectionName);
18
18
 
19
19
  // Check if the field is an array in the existing document
20
20
  const existingDocument = await collection.findOne(search);
@@ -22,17 +22,16 @@ module.exports = {
22
22
 
23
23
  if (isFieldArray) {
24
24
  // Field is an array, push the data
25
- await collection.updateOne({}, { $addToSet: { [fieldName]: { $each: data } } });
25
+ await collection.updateOne(search, { $addToSet: { [fieldName]: { $each: data } } });
26
26
  } else {
27
27
  // Field is not an array, save the array
28
- await collection.updateOne({}, { $set: { [fieldName]: data } }, { upsert: true });
28
+ await collection.updateOne(search, { $set: { [fieldName]: data } }, { upsert: true });
29
29
  }
30
30
 
31
31
  console.log('Data added to the collection successfully.');
32
32
  } catch (error) {
33
33
  console.error('Error:', error.message);
34
34
  } finally {
35
- await client.close();
36
35
  }
37
36
  }
38
37
  }
@@ -32,29 +32,51 @@ module.exports = {
32
32
  },
33
33
 
34
34
  downloadBuffer: async function (filename, dbName = 'media') {
35
- await client.connect();
36
-
37
- const db = client.db(dbName);
38
- const bucket = new GridFSBucket(db);
39
-
40
- const downloadStream = bucket.openDownloadStreamByName(filename);
41
-
42
- return new Promise((resolve, reject) => {
43
- const chunks = [];
44
-
45
- // Accumulate chunks as they arrive
46
- downloadStream.on('data', (chunk) => {
47
- chunks.push(chunk);
48
- });
49
-
50
- // Resolve with the concatenated buffer and metadata when the download is complete
51
- downloadStream.on('end', () => {
52
- const buffer = Buffer.concat(chunks);
53
- const metadata = downloadStream.s.file.metadata;
54
- resolve({ buffer, metadata });
35
+ try {
36
+ await client.connect();
37
+ const db = client.db(dbName);
38
+
39
+ // Find all files with the given filename
40
+ const filesCollection = db.collection('fs.files');
41
+ const files = await filesCollection.find({ filename: filename }).toArray();
42
+
43
+ // If no files found, return null
44
+ if (files.length === 0) {
45
+ return null;
46
+ }
47
+
48
+ // Initialize an array to store download promises
49
+ const downloadPromises = [];
50
+
51
+ // Loop through each file and download it
52
+ files.forEach(file => {
53
+ const bucket = new GridFSBucket(db);
54
+ const downloadStream = bucket.openDownloadStreamByName(filename);
55
+ downloadPromises.push(new Promise((resolve, reject) => {
56
+ const chunks = [];
57
+ downloadStream.on('data', (chunk) => {
58
+ chunks.push(chunk);
59
+ });
60
+ downloadStream.on('end', () => {
61
+ const buffer = Buffer.concat(chunks);
62
+ const metadata = downloadStream.s.file.metadata;
63
+ resolve({ buffer, metadata });
64
+ });
65
+ downloadStream.on('error', reject);
66
+ }));
55
67
  });
56
-
57
- downloadStream.on('error', reject);
58
- });
68
+
69
+ // Wait for all download promises to resolve
70
+ const results = await Promise.all(downloadPromises);
71
+
72
+ return results;
73
+ } catch (error) {
74
+ console.error('Error downloading file:', error);
75
+ throw error;
76
+ } finally {
77
+ // Close the MongoDB connection
78
+ await client.close();
79
+ }
59
80
  }
81
+
60
82
  };
@@ -1,11 +1,25 @@
1
1
  const { MongoClient } = require('mongodb');
2
- module.exports = function(db,collection) {
2
+ module.exports = async function(db,collection,query,one = false,array) {
3
3
  // Ensure the MongoDB connection string is provided
4
+ const program = array.program;
5
+ let callback;
6
+ if (array.function != undefined) {
7
+ callback = array.function;
8
+ }
4
9
  if (!process.env.mongo) {
5
10
  console.error('MongoDB connection string not provided. Set process.env.mongo.');
6
11
  process.exit(1);
7
12
  }
8
13
 
14
+ function routeExists(path) {
15
+ return program.express.app._router.stack.some(layer => {
16
+ if (layer.route) {
17
+ return layer.route.path === path;
18
+ }
19
+ return false;
20
+ });
21
+ }
22
+
9
23
  // Define the MongoDB URI
10
24
  const uri = process.env.mongo;
11
25
 
@@ -14,11 +28,10 @@ module.exports = function(db,collection) {
14
28
  const collectionName = collection;
15
29
 
16
30
  // Define the query you want to perform
17
- const query = { /* Your query goes here */ };
18
31
 
19
32
  async function main() {
20
33
  // Create a new MongoClient
21
- const client = new MongoClient(uri);
34
+ const client = await new MongoClient(uri);
22
35
 
23
36
  try {
24
37
  // Connect to the MongoDB server
@@ -26,17 +39,88 @@ module.exports = function(db,collection) {
26
39
  console.log('Connected to the MongoDB server');
27
40
 
28
41
  // Select the database
29
- const database = client.db(dbName);
42
+ const database = await client.db(dbName);
30
43
 
31
44
  // Select the collection
32
- const collection = database.collection(collectionName);
45
+ const collection = await database.collection(collectionName);
33
46
 
34
47
  // Perform the find query
35
- const result = await collection.find(query).toArray();
48
+ result = await collection.find(query).toArray();
36
49
 
50
+ if (one == true) {
51
+ result = result[0];
52
+ }
37
53
  // Process the result
38
54
  console.log('Query result:', result);
39
- return result;
55
+
56
+ // Check if profile image to get it from db
57
+ if (result.profileImage != undefined && array.image == true) {
58
+ const profileImage = await program.modules.data.file.downloadBuffer(result.profileImage,`eventgo`);
59
+
60
+ // Set in dynamic routing for serving
61
+ let sizeMeta = {};
62
+ let other = {}
63
+ for (let pi in profileImage) {
64
+ // Profile image
65
+ const theImage = profileImage[pi];
66
+
67
+ // Get the meta
68
+ const imageMeta = theImage.metadata;
69
+
70
+ // Sizes
71
+ const size = imageMeta.size;
72
+
73
+ const sizeKey = `${size.width}x${size.height}`;
74
+ const setUUID = program.uuid.v4();
75
+ sizeMeta[setUUID] = {
76
+ buffer : theImage.buffer,
77
+ meta : imageMeta
78
+ }
79
+ console.log(`The Size Meta`);
80
+ }
81
+
82
+ // Now we have sizes thingy so create a route for this specific uuid
83
+ const dynamicLink = `/dynamic/${result.profileImage}/list`;
84
+ result.imageList = `${process.env.url}${dynamicLink.slice(1)}`;
85
+ result.images = sizeMeta;
86
+
87
+ const routeCheck = await routeExists(dynamicLink);
88
+ if (!routeCheck) {
89
+ program.express.app.get(dynamicLink, async (req, res) => {
90
+ // Requesting image
91
+ console.log(`Requesting dynamic link`);
92
+ // Send buffer image as image
93
+ // Set content type header to indicate that you're sending an image
94
+ res.setHeader('Content-Type', 'application/json');
95
+
96
+ // Send the image buffer as the response body
97
+ for (let sizeKey in sizeMeta) {
98
+ const item = sizeMeta[sizeKey];
99
+ other[sizeKey] = item.meta;
100
+
101
+ // Create dynamic url for this on
102
+ const imageDynamicPath = `/dynamic/${sizeKey}.${item.meta.type}`;
103
+ const imageLinkURL = `https://${process.env.url}${imageDynamicPath.slice(1)}`
104
+ //other[sizeKey].link = imageLinkURL;
105
+
106
+ // generate dynamic url
107
+
108
+ }
109
+
110
+ res.send(JSON.stringify(other, null, 2));
111
+ });
112
+ }
113
+ console.log(`Profile Image`);
114
+
115
+ // generate paths
116
+ }
117
+
118
+ if (callback != undefined) {
119
+
120
+ callback(program,result);
121
+ } else {
122
+ return result;
123
+ }
40
124
  } finally {
41
125
  // Close the MongoClient
42
126
  await client.close();
@@ -45,6 +129,6 @@ module.exports = function(db,collection) {
45
129
  }
46
130
 
47
131
  // Execute the main function
48
- main().catch(console.error);
132
+ await main().catch(console.error);
49
133
 
50
134
  }
@@ -224,7 +224,7 @@ module.exports = async function (program) {
224
224
  const wss = new WebSocket.Server({ port: PORT });
225
225
 
226
226
 
227
- wss.on('connection', (ws, req) => {
227
+ wss.on('connection', async (ws, req) => {
228
228
  console.log(`Socket Connected`);
229
229
 
230
230
  // Generate a unique ID for the WebSocket connection
@@ -283,13 +283,75 @@ module.exports = async function (program) {
283
283
  console.error('Received data has been tampered with');
284
284
  }
285
285
 
286
- console.log(parsedQuery);
287
286
 
288
287
  // Store the WebSocket connection with its ID in the map
289
288
  clients.set(clientId, ws);
290
289
 
291
290
  // Send the client ID to the connected client
292
- ws.send(JSON.stringify({ type: 'clientId', id: clientId, params: parsedQuery }));
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(`eventgo`,`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
+ ws.send(JSON.stringify({ type: 'user', clientId: clientId, data : sendData }));
351
+
352
+ }});
353
+ }
354
+ //ws.send(JSON.stringify({ type: 'clientId', id: clientId, params: parsedQuery }));
293
355
 
294
356
  // Set up a ping interval to keep the connection alive
295
357
  const pingInterval = setInterval(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webfast",
3
- "version": "0.1.52",
3
+ "version": "0.1.54",
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": {