webfast 0.1.31 → 0.1.32

Sign up to get free protection for your applications and to get access to all the features.
package/example.js ADDED
@@ -0,0 +1,5 @@
1
+ const path = require(`path`);
2
+ let program = require(path.join(__dirname,`index.js`))({
3
+ wget : '/usr/local/bin/wget'
4
+ });
5
+ console.log(`Required`);
package/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  module.exports = function (array) {
2
2
  const { readdirSync } = require("fs");
3
3
 
4
- // Need to walk through array for specific things
5
4
  console.log(`WebFast!! Program`);
6
5
  let program = {
7
6
  ts : Date.now(),
@@ -11,17 +10,18 @@ module.exports = function (array) {
11
10
  }
12
11
 
13
12
  for (let key in array) {
14
- program.set[key] = array[key];
13
+ program.set[key]=array[key]
15
14
  }
16
15
 
17
16
  // Setup The Requirements
18
- async function set(program) {
19
- program.path = await require(`path`);
20
- program.fs = await require(`fs`);
21
- program.uuid = require(`uuid`);
22
- program.fetch = require(`fetch`);
23
-
24
- return program;
17
+ program.path = require(`path`);
18
+ program.fs = require(`fs`);
19
+ program.uuid = require(`uuid`);
20
+ program.fetch = require(`fetch`);
21
+ program.util = require(`util`);
22
+ program.exec = program.util.promisify(require('child_process').exec);
23
+ program.image = {
24
+ size : require('image-size')
25
25
  }
26
26
 
27
27
  // Program Fetch
@@ -127,11 +127,8 @@ module.exports = function (array) {
127
127
  }
128
128
  }
129
129
 
130
- program.modules.fetch = async function(folder,program,fetch) {
130
+ program.modules.fetch = async function(folder,program) {
131
131
  // TO Fetch folder modules
132
- if (fetch == undefined) {
133
- program = await set(program);
134
- }
135
132
  try {
136
133
  // Loop through folder and run module if js
137
134
  const readPath = program.path.join(__dirname,folder);
@@ -252,5 +249,26 @@ module.exports = function (array) {
252
249
 
253
250
  // Run program fetch
254
251
  program.modules.fetch(`modules`,program);
252
+
253
+ // Check if program.set.path is set
254
+ if (program.set.path != undefined) {
255
+ // We have the path for normal path so check for the folder app
256
+ try {
257
+ const appFolder = program.path.join(program.set.path,`app`,`init.js`);
258
+ // Now include this appFolder // set app
259
+ program.app = require(appFolder)(program);
260
+ console.log(`Include App`);
261
+ } catch (err) {
262
+ console.error(err);
263
+ console.error(`Error with program set folder`);
264
+ }
265
+ }
255
266
  return program;
267
+ }
268
+
269
+ // to cut the log
270
+ if (process.env.log == undefined) {
271
+ console.log = function() {
272
+
273
+ }
256
274
  }
@@ -0,0 +1,124 @@
1
+ module.exports = {
2
+ UserProfilePhotos : async function(program,user,callback) {
3
+ console.log(`Get User Profile Photos`);
4
+ // Save user photo when first time
5
+ // Create call
6
+ const userPhotos = await program.modules.telegram.functions.get.request(`getUserProfilePhotos`,{
7
+ user_id : user.id
8
+ },program,callback);
9
+ console.log(`The User Photo`);
10
+ // convert base64 and save to database
11
+ const uuid = program.uuid.v4();
12
+ for (let userI in userPhotos.result.photos) {
13
+ // Make request for file
14
+ let profilePictures = userPhotos.result.photos[userI]
15
+ // Telegram will give back an array
16
+ for (let profileI in profilePictures) {
17
+ const profilePictureData = profilePictures[profileI];
18
+ const fileID = profilePictureData.file_id;
19
+ const fileUnique = profilePictureData.file_unique_id;
20
+
21
+ try {
22
+ const userPhotoURL = await program.modules.telegram.functions.get.file(program,fileID);
23
+
24
+ // create url
25
+ const photoURL = `https://api.telegram.org/file/bot${process.env.telegram}/${userPhotoURL.result.file_path}`;;
26
+
27
+ // Now do the fetch process thingy
28
+ await program.modules.telegram.functions.get.downloadAndConvertToBase64(program,photoURL,async function(program,response){
29
+ console.log(`We have now file data`);
30
+ // Create id for file that is unique uuid
31
+ const meta = {
32
+ user : response.data.user.id,
33
+ type : response.imageData.type,
34
+ size : {
35
+ width : response.imageData.width,
36
+ height : response.imageData.height
37
+ }
38
+ }
39
+ await program.modules.data.file.uploadBuffer(program,response.buffer,uuid,meta,async function(progam,upload,meta){
40
+ console.log(`Uploaded Buffer`);
41
+ // Save to membe
42
+ await program.modules.telegram.functions.set.profilePhoto(progam,upload,meta);
43
+ });
44
+
45
+ },{
46
+ user : user,
47
+ data : profilePictureData
48
+ });
49
+ } catch (err) {
50
+ console.error(`Error For Downloading file`);
51
+ }
52
+ }
53
+ }
54
+ },
55
+ file : async function(program,fileID,callback) {
56
+ // TO get the file from telegram
57
+ const getFile = await program.modules.telegram.functions.get.request(`getFile`,{
58
+ file_id : fileID
59
+ },program,callback);
60
+ return getFile;
61
+ },
62
+ downloadAndConvertToBase64 : async (program, photoURL, callback,data) => {
63
+ try {
64
+ // Use wget to download the image
65
+ const { stdout, stderr } = await program.exec(`${program.set.wget} -O - ${photoURL}`, { encoding: 'buffer' });
66
+
67
+ // Check if the download was successful
68
+ const errBuf = Buffer.from(stderr);
69
+ const errorText = errBuf.toString('utf-8');
70
+ // Check if the errorText contains "200 OK"
71
+ if (errorText.includes('200 OK')) {
72
+ // The request was successful
73
+ console.log('Download successful');
74
+ } else {
75
+ // The request encountered an error
76
+ console.error('Download failed:', errorText);
77
+ throw new Error(`Failed to download image. Error: ${stderr}`);
78
+ }
79
+
80
+ // Convert the downloaded buffer to base64
81
+ const buffer = Buffer.from(stdout);
82
+ const base64 = buffer.toString('base64');
83
+
84
+ // Determine the MIME type and dimensions of the image
85
+ const dimensions = program.image.size(buffer);
86
+ const { width, height, type } = dimensions;
87
+
88
+ // Log the details
89
+ console.log('MIME Type:', type);
90
+ console.log('Dimensions:', `${width}x${height}`);
91
+
92
+ // Now you can use the base64 encoded string
93
+ //console.log('Base64:', base64);
94
+
95
+ // Call the callback with the result
96
+ callback(program,{
97
+ base: base64,
98
+ imageData: dimensions,
99
+ type: type,
100
+ data : data,
101
+ buffer : buffer
102
+ });
103
+
104
+ return true;
105
+ } catch (error) {
106
+ console.error('Error:', error.message);
107
+ return false;
108
+ }
109
+ },
110
+ request : async function(path, body,program,callback) {
111
+ // Make request with url
112
+ console.log(`Make Telegram Get Request`);
113
+ let respData = {}
114
+ const url = `https://api.telegram.org/bot${process.env.telegram}/${path}`;
115
+ // We have url make request
116
+ respData = await program.modules.request.post(program,url,body)
117
+
118
+ if (callback != undefined) {
119
+ return callback(madeRequest);
120
+ } else {
121
+ return respData;
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,38 @@
1
+ const { MongoClient } = require('mongodb');
2
+ const uri = process.env.mongo;
3
+ const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
4
+
5
+ module.exports = {
6
+ profilePhoto : async function(program,content,meta) {
7
+ console.log(`Set User Profile Pic`);
8
+ const added = await program.modules.telegram.functions.set.addToCollection(program,`telegram`, `profileImage`, meta.name,{
9
+ id : meta.user
10
+ });
11
+ console.log(`Added`);
12
+ },
13
+ addToCollection : async function (program,collectionName, fieldName, data,search) {
14
+ try {
15
+ await client.connect();
16
+ const db = client.db('eventgo');
17
+ const collection = db.collection(collectionName);
18
+
19
+ // Check if the field is an array in the existing document
20
+ const existingDocument = await collection.findOne(search);
21
+ const isFieldArray = Array.isArray(existingDocument[fieldName]);
22
+
23
+ if (isFieldArray) {
24
+ // Field is an array, push the data
25
+ await collection.updateOne({}, { $addToSet: { [fieldName]: { $each: data } } });
26
+ } else {
27
+ // Field is not an array, save the array
28
+ await collection.updateOne({}, { $set: { [fieldName]: data } }, { upsert: true });
29
+ }
30
+
31
+ console.log('Data added to the collection successfully.');
32
+ } catch (error) {
33
+ console.error('Error:', error.message);
34
+ } finally {
35
+ await client.close();
36
+ }
37
+ }
38
+ }
@@ -48,8 +48,13 @@ module.exports = async function(program,folder) {
48
48
  id : middleValue.chat.id
49
49
  },middleValue.chat);
50
50
  let typeOFF = typeof user;
51
- if (middleValue.chat.uuid == user.uuid) {
51
+ if (middleValue.chat.uuid == user.uuid || user.profileImage == undefined) {
52
52
  user.new = true;
53
+
54
+ // do the process for downloading the users profile image
55
+ console.log(`Process Image`);
56
+ //getUserProfilePhotos
57
+ program.modules.telegram.functions.get.UserProfilePhotos(program,user);
53
58
  }
54
59
 
55
60
  middleValue.chat.uuid = user.uuid;
@@ -351,7 +356,7 @@ module.exports = async function(program,folder) {
351
356
  int : {}
352
357
  }
353
358
  for (let scriptIndex in scriptsData) {
354
- let script = [scriptIndex];
359
+ let script = scriptsData[scriptIndex];
355
360
  // We now have the specific script check if folder
356
361
  if (!script.extension) {
357
362
  // It's folder create the function and read folder
@@ -0,0 +1,60 @@
1
+ const { MongoClient, GridFSBucket } = require('mongodb');
2
+ const fs = require('fs');
3
+
4
+ // Define the MongoDB URI
5
+ const uri = process.env.mongo;
6
+ const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
7
+
8
+ module.exports = {
9
+ uploadBuffer: async function (progam,buffer, filename, metadata = {}, callback) {
10
+ const dbName = 'eventgo';
11
+ await client.connect();
12
+
13
+ const db = client.db(dbName);
14
+ const bucket = new GridFSBucket(db);
15
+
16
+ const uploadStream = bucket.openUploadStream(filename, { metadata });
17
+
18
+ uploadStream.end(buffer); // Write the buffer directly to the upload stream
19
+
20
+ new Promise((resolve, reject) => {
21
+ uploadStream.on('finish', () => {
22
+ // Access the ObjectId assigned to the stored file
23
+ const fileId = uploadStream.id;
24
+ let objectID = resolve(fileId);
25
+ console.log(`File ID hing`);
26
+ metadata.name = filename;
27
+ callback(progam,uploadStream,metadata);
28
+ });
29
+
30
+ uploadStream.on('error', reject);
31
+ });
32
+ },
33
+
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 });
55
+ });
56
+
57
+ downloadStream.on('error', reject);
58
+ });
59
+ }
60
+ };
@@ -36,7 +36,7 @@ module.exports = function(db,collection) {
36
36
 
37
37
  // Process the result
38
38
  console.log('Query result:', result);
39
-
39
+ return result;
40
40
  } finally {
41
41
  // Close the MongoClient
42
42
  await client.close();
@@ -0,0 +1,57 @@
1
+ const { MongoClient } = require('mongodb');
2
+
3
+ module.exports = async function (db, collection, condition, dataToUpdate) {
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
+ async function main() {
18
+ // Create a new MongoClient
19
+ const client = new MongoClient(uri);
20
+
21
+ try {
22
+ // Connect to the MongoDB server
23
+ await client.connect();
24
+ console.log('Connected to the MongoDB server');
25
+
26
+ // Select the database
27
+ const database = client.db(dbName);
28
+
29
+ // Select the collection
30
+ const collection = database.collection(collectionName);
31
+
32
+ // Perform the update or create operation
33
+ const result = await collection.updateOne(condition, { $set: dataToUpdate }, { upsert: true });
34
+
35
+ // If a document was upserted, retrieve the upserted document
36
+ const upsertedDocument = result.upsertedId
37
+ ? await collection.findOne({ _id: result.upsertedId })
38
+ : null;
39
+
40
+ // Process the result
41
+ if (upsertedDocument) {
42
+ console.log('Document upserted:', upsertedDocument);
43
+ return upsertedDocument;
44
+ } else {
45
+ console.log('Document updated.');
46
+ return dataToUpdate;
47
+ }
48
+ } finally {
49
+ // Close the MongoClient
50
+ await client.close();
51
+ console.log('Connection closed.');
52
+ }
53
+ }
54
+
55
+ // Execute the main function
56
+ return main().catch(console.error);
57
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "webfast",
3
- "version": "0.1.31",
4
- "description": "WebFast! Bot Application, including TON mini-apps",
3
+ "version": "0.1.32",
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": {
7
7
  "type": "git",
@@ -44,6 +44,7 @@
44
44
  "express": "^4.18.2",
45
45
  "fetch": "^1.1.0",
46
46
  "fs": "^0.0.1-security",
47
+ "image-size": "^1.1.1",
47
48
  "js": "^0.1.0",
48
49
  "mongodb": "^6.3.0",
49
50
  "node-fetch": "^3.3.2",