webfast 0.1.87 → 0.1.88

Sign up to get free protection for your applications and to get access to all the features.
@@ -5,14 +5,64 @@ 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) {
8
+ getCookieValue : function(cookieName) {
9
+ let allCookies = document.cookie;
10
+ let cookies = document.cookie.split("; ");
11
+ for (let i = 0; i < cookies.length; i++) {
12
+ let cookie = cookies[i].split("=");
13
+ if (cookie[0] === cookieName) {
14
+ return decodeURIComponent(cookie[1]);
15
+ }
16
+ }
17
+ return null; // Cookie not found
18
+ },
19
+ redirect :async function(data) {
20
+ console.log(`Received Redirect`,data.event);
21
+ const state = data.event.type;
22
+ if (state == true && web.fast.redirected == undefined) {
12
23
  // Redirect
13
- window.location.replace(event.url);
24
+ console.log(`Replace to : `, data.event.url);
25
+ web.fast.redirected = Date.now();
26
+
27
+ let replacedURL = data.event.url.replace(`https://`,``);
28
+ if (data.event.full == true) {
29
+ replacedURL = data.event.url;
30
+
31
+ }
32
+ // check if new hash
33
+ const sendData = telegram.initData.replace(`__order`,``)
34
+
35
+ const id = data.event.requestID;
36
+ if (web.fast.user != undefined && jQuery(`[wbfst-frame="${id}"]`).length == 0 && data.event.full != true) {
37
+ //const myUrl = new URL(data.event.url);
38
+ //history.pushState({}, null, myUrl); // Update the URL without reloading the page
39
+ //window.location.hash = window.location.hash.replace(`__order`,``);
40
+ window.Telegram.WebView.onEvent(`back_button_pressed`, function(event){
41
+ console.log(`Back Button Event Pressed`,event);
42
+ const frame = jQuery(`[wbfst-frame="${id}"]`);
43
+ jQuery(frame).animate({ opacity:0 }, 600,function(){
44
+ jQuery(this).remove();
45
+ });
46
+ window.Telegram.WebApp.BackButton.hide();
47
+ })
48
+ await web.fast.telegram(`frame`).set(id,replacedURL,async function(id){
49
+ console.log(`Clicked Close`,id);
50
+ const frame = jQuery(`[wbfst-frame="${id}"]`);
51
+ console.log(`The Frame`,frame);
52
+ jQuery(frame).animate({ opacity:0 }, 600,function(){
53
+ jQuery(this).remove();
54
+ });
55
+
56
+ });
57
+ }else if (data.event.full == true && web.fast.user != undefined) {
58
+ // typeof order.state
59
+ window.Telegram.WebApp.disableClosingConfirmation(false);
60
+ window.Telegram.WebApp.close();
61
+ } else {
62
+ window.location.replace(data.event.url);
63
+ }
14
64
  } else {
15
- console.error(`Something wrong redirect`,event);
65
+ //console.error(`Something wrong redirect`,data.event);
16
66
  }
17
67
  },
18
68
  functions : {
@@ -182,11 +232,18 @@ if (webfastSocket == undefined) {
182
232
  }
183
233
 
184
234
  let setData;
235
+ // Split hash
236
+ const locSplit = window.location.hash.split(`__`);
237
+
238
+ //alert(locSplit);
185
239
  if (telegram.initData == ``) {
186
240
  setData = `hybrid.institute.anonymous`
241
+ } else if (locSplit.length > 1 && locSplit[1] == `redirected`) {
242
+ setData = telegram.initData.replace(`__order&`,`&`);
187
243
  } else {
188
244
  setData = telegram.initData;
189
245
  }
246
+ //alert(setData);
190
247
 
191
248
  const socketURL = `wss://${webfastSocket.replace(`https://`,``)}socket.io/?qbt=${setData}`;
192
249
 
@@ -1,4 +1,4 @@
1
- module.exports = async function(program,message,id,buttons) {
1
+ module.exports = async function(program,message,id,buttons,messageID) {
2
2
  console.log(`Telegram Send`);
3
3
  // Create Request for send
4
4
  let telegramURL = `https://api.telegram.org/bot${process.env.telegram}`;
@@ -20,7 +20,7 @@ module.exports = async function(program,message,id,buttons) {
20
20
  }
21
21
 
22
22
 
23
- const body = {
23
+ let body = {
24
24
  text: message,
25
25
  disable_web_page_preview: false,
26
26
  disable_notification: false,
@@ -30,7 +30,7 @@ module.exports = async function(program,message,id,buttons) {
30
30
  }
31
31
 
32
32
  // Check if object
33
- if (typeof message == `object`) {
33
+ if (typeof message == `object` && messageID == undefined) {
34
34
  if (message.text != undefined && message.image == undefined) {
35
35
  body.text = message.text;
36
36
  telegramURL = `${telegramURL}/sendMessage`;
@@ -44,6 +44,14 @@ module.exports = async function(program,message,id,buttons) {
44
44
  delete body.reply_to_message_id;
45
45
  telegramURL = `${telegramURL}/sendPhoto`;
46
46
  }
47
+ } else if (messageID != undefined) {
48
+ body = {
49
+ chat_id : id,
50
+ message_id : messageID,
51
+ text : message,
52
+ parse_mode : `HTML`
53
+ }
54
+ telegramURL = `${telegramURL}/editMessageText`;
47
55
  } else {
48
56
  telegramURL = `${telegramURL}/sendMessage`;
49
57
  }
@@ -365,15 +365,20 @@ wss.on('connection', async (ws, req) => {
365
365
  if (parsedQuery.start_param != undefined) {
366
366
  const startSplit = parsedQuery.start_param.split(`__`);
367
367
  const uuid = startSplit[0];
368
- const action = startSplit[1];
369
368
 
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);
374
- } catch (err) {
375
- // Error for params
376
- console.error(`Error for program params start_param`);
369
+ if (startSplit.length <= 1) {
370
+ console.log(`Start split is one`);
371
+ } else {
372
+ const action = startSplit[1];
373
+
374
+ // Check action and if we have this action in custom routes thingy
375
+ try {
376
+ const userJSON = JSON.parse(JSON.parse(parsedQuery.user));
377
+ await program.express.process.params(program,ws,action,uuid,parsedQuery,clientId,userJSON);
378
+ } catch (err) {
379
+ // Error for params
380
+ console.error(`Error for program params start_param`);
381
+ }
377
382
  }
378
383
  }
379
384
 
@@ -409,7 +414,7 @@ wss.on('connection', async (ws, req) => {
409
414
  // Check if function is running in program modules that you can add in the init scirpt when using remote
410
415
  if (program.express.process != undefined) {
411
416
  try {
412
- let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId,ws);
417
+ let resp = await program.express.process[split[0]][split[1]][split[2]](program,ws,json,data,path,clientId,ws,parsedQuery);
413
418
  if (resp != false) {
414
419
  ws.send(JSON.stringify(resp));
415
420
  }
@@ -0,0 +1,132 @@
1
+ module.exports = async function(program,json) {
2
+ console.log(`Init Create with json data`);
3
+ return async function(program,order,payment,price,currency) {
4
+ console.log(`Create Payment`);
5
+ //const price = Number(order.price).toFixed(2);
6
+ // Get order info data
7
+ let pipeline = [
8
+ {
9
+ $match: {
10
+ uuid: order.package
11
+ }
12
+ }
13
+ ];
14
+ let package = await program.modules.data.aggregate(program,process.env.dbName, 'pricing', pipeline);
15
+ if (package.length == 0) {
16
+ throw new Error(`No Package found for payment`);
17
+ } else {
18
+ package = package[0];
19
+ }
20
+
21
+ // create redirect url
22
+ let webhookURL = program.modules.payment.mollie.webhookURL;
23
+ // create new payment uuid
24
+ const paymentUUID = program.uuid.v4();
25
+
26
+ const redirectURL = webhookURL.replace(`:orderId`,paymentUUID).replace(`:action`,`redirect`);
27
+ const cancelURL = webhookURL.replace(`:orderId`,paymentUUID).replace(`:action`,`cancel`);
28
+ const pageRedirect = webhookURL.replace(`:orderId`,paymentUUID).replace(`:action`,`page-redirect`);
29
+ webhookURL = webhookURL.replace(`:orderId`,paymentUUID).replace(`:action`,`update`);
30
+
31
+ const paramsArray = {
32
+ amount : {
33
+ currency : String(currency).toUpperCase(),
34
+ value : String(Number(price/100).toFixed(2))
35
+ },
36
+ description : `eSimCo. ${package.name.toUpperCase()}`,
37
+ redirectUrl : redirectURL,
38
+ cancelUrl : cancelURL,
39
+ webhookUrl : webhookURL,
40
+ locale : 'en_US',
41
+ method : payment.provider
42
+ }
43
+
44
+ // We have now method etc. let's build up the call
45
+ const getURL = `${json.url}/v2/payments`
46
+ const request = await program.modules.payment.mollie.post(program,getURL,paramsArray,{
47
+ 'Authorization': `Bearer ${json.key}`,
48
+ 'content-type': 'application/json'
49
+ })
50
+
51
+ // WE made request
52
+ request.uuid = paymentUUID;
53
+ request.package = order.package;
54
+ request.user = order.user;
55
+ request.order = order.uuid;
56
+
57
+ // Now save to request DB
58
+ const create = await program.modules.data.insert(process.env.dbName,`payment`,request);
59
+
60
+ // Now upate
61
+ let newState = order.state;
62
+ newState[`waiting`] = Date.now();
63
+
64
+ console.log(`Updated`);
65
+
66
+ console.log(`Made Request`,request);
67
+
68
+ // Now send response
69
+ let redirect = {
70
+ type : true,
71
+ url : request._links.checkout.href,
72
+ requestID : program.uuid.v4(),
73
+ full : true
74
+ }
75
+
76
+ // Check url
77
+ redirect.url = pageRedirect;
78
+
79
+ // Send Payment info per bot and link for order
80
+ console.log(`Send Payment info link per bot`);
81
+ // create payment url
82
+ const orderURL = `${process.env.webURL.slice(0,-1)}/concepts/esimco/order#${request.order}__redirect`;
83
+ // create order url redirect url
84
+ const paymentRedirect = `${process.env.url.slice(0,-1)}/webhooks/orders/${request.uuid}/bot-redirect`;
85
+
86
+ // Create message
87
+ let payIcon = `!`;
88
+ if (request.amount.currency.toUpperCase() == `USD`) {
89
+ payIcon = `$`;
90
+ }
91
+ if (request.amount.currency.toUpperCase() == `EUR`) {
92
+ payIcon = `€`;
93
+ }
94
+ const textMessage = `<b>⚠️ Your order is created but unpaid!</b>\n<span class="tg-spoiler">Order ID: <b>${request.order}</b></span>\n\nTo receive your order we would like to ask you to fullfill the payment for the remaining amount of <span class="tg-spoiler"><b>${payIcon} ${request.amount.value}</b></span>.\n\nClick on <u>Pay Now</u> to fullfill your payment or click <u>view order</u> to view your order.`
95
+ try {
96
+ let telegramSend = await program.modules.telegram.functions.send(program,textMessage,request.user,[
97
+ [
98
+ //{ text: 'View Order', web_app : { url : orderURL}},
99
+ { text: 'Pay Order', web_app : { url : paymentRedirect}}
100
+ ]
101
+ ]);
102
+
103
+ // Now we have message id set that to the order
104
+
105
+ // Add update to message order thingy
106
+
107
+ const updated =await program.modules.data.update(process.env.dbName,`order`,{
108
+ uuid : order.uuid
109
+ },{
110
+ $set: {
111
+ state : newState,
112
+ payment : paymentUUID,
113
+ messages : [telegramSend.result.uuid]
114
+ }
115
+ });
116
+ console.log(`Telegram Send`);
117
+ } catch (err) {
118
+ console.error(err);
119
+ console.error(`Error with sending to client`);
120
+ }
121
+
122
+
123
+ const sendArray = {
124
+ func : `redirect`,
125
+ data : {
126
+ event : redirect
127
+ },
128
+ js : `delete web.fast.tmp.sending;`
129
+ };
130
+ return sendArray;
131
+ }
132
+ }
@@ -13,6 +13,7 @@ module.exports = async function(program,json) {
13
13
  const functionPath = program.path.join(json.path,`functions`);
14
14
  console.log(`Function Path`);
15
15
  let restArray = {
16
+ create : await require(program.path.join(__dirname,`create.js`))(program,json),
16
17
  get : async function(url,params) {
17
18
  console.log(`GET`);
18
19
 
@@ -35,9 +36,11 @@ module.exports = async function(program,json) {
35
36
 
36
37
  return data;
37
38
  },
38
- post : async function(url,params) {
39
+ post : async function(program,url,body,headers) {
39
40
  console.log(`POST`);
40
-
41
+
42
+ const requestPOST = await program.modules.request.post(program,url,body,headers);
43
+ return requestPOST;
41
44
  }
42
45
  }
43
46
 
@@ -64,13 +67,15 @@ module.exports = async function(program,json) {
64
67
  const requestUSD = await restArray.get(getURL,{
65
68
  locale : "en_US",
66
69
  'amount[value]' : "100.00",
67
- 'amount[currency]' : "USD"
70
+ 'amount[currency]' : "USD",
71
+ "include" : "pricing"
68
72
  })
69
73
 
70
74
  const requestEU = await restArray.get(getURL,{
71
75
  locale : "en_US",
72
76
  'amount[value]' : "100.00",
73
- 'amount[currency]' : "EUR"
77
+ 'amount[currency]' : "EUR",
78
+ "include" : "pricing"
74
79
  })
75
80
 
76
81
  // Process both
@@ -106,10 +111,78 @@ module.exports = async function(program,json) {
106
111
  status : itemData.status,
107
112
  res : itemData.resource,
108
113
  images : itemData.image,
109
- currency : {}
114
+ currency : {},
115
+ pricing : {
116
+ items : itemData.pricing
117
+ }
110
118
  }
111
119
  }
112
120
 
121
+ // Now loop through pricing to see max and min
122
+ let allPricing = [];
123
+
124
+ let maxPers = 0;
125
+ let minPers = 0;
126
+ let maxFix = 0;
127
+ let minFix = 0;
128
+ let pricingCurrency = [];
129
+ for (let prI in itemData.pricing) {
130
+ // get item
131
+ const pricing = itemData.pricing[prI];
132
+
133
+ let setPricing = {};
134
+
135
+ for (let key in pricing) {
136
+ switch (key) {
137
+ case `variable`:
138
+ const thePerc = Number(pricing[key]);
139
+ if (thePerc > maxPers) {
140
+ maxPers = thePerc;
141
+ }
142
+ if (thePerc < minPers || minPers == 0) {
143
+ minPers = thePerc;
144
+ }
145
+ setPricing.percentage = thePerc;
146
+ break;
147
+ case `fixed`:
148
+ const fixPrice = Number(pricing[key].value);
149
+ // Set fix price
150
+ if (fixPrice > maxFix) {
151
+ maxFix = fixPrice;
152
+ }
153
+ if (fixPrice < minFix || minFix == 0) {
154
+ minFix = fixPrice;
155
+ }
156
+ pricing[key].value = Number(pricing[key].value);
157
+ setPricing[key] = pricing[key];
158
+
159
+ // check if in array
160
+ if (pricingCurrency.indexOf(pricing[key].currency) == -1) {
161
+ pricingCurrency.push(pricing[key].currency)
162
+ }
163
+ break;
164
+ default:
165
+ console.log(`Set Just: ${key}`);
166
+ setPricing[key] = pricing[key];
167
+ }
168
+ }
169
+ allPricing.push(setPricing);
170
+ }
171
+ console.log(`We have all pricing per item now`);
172
+ itemData.pricing = {
173
+ all : allPricing,
174
+ perc : {
175
+ min : minPers,
176
+ max : maxPers
177
+ },
178
+ fix : {
179
+ min : minFix,
180
+ max : maxFix
181
+ },
182
+ currencies : pricingCurrency
183
+ }
184
+ payar[itemData.id].pricing = itemData.pricing;
185
+
113
186
  // Now grab currency
114
187
  const currency = {
115
188
  max : itemData.maximumAmount.value,
@@ -126,5 +199,162 @@ module.exports = async function(program,json) {
126
199
 
127
200
  restArray.methods = payar;
128
201
 
202
+ // Create dynamic app get for receiving data
203
+ const fullPath = `${process.env.url.slice(0,-1)}/webhooks/orders/:orderId/:action`;
204
+ // setup dynamic routing
205
+ restArray.webhookURL = fullPath;
206
+ async function functionRequest(req,res,type) {
207
+ const orderId = req.params.orderId;
208
+ const action = req.params.action;
209
+ console.log(`Received data for payment`,type);
210
+
211
+ // Get body Data
212
+ const body = req.body;
213
+
214
+ // First grab order
215
+ let pipeline = [
216
+ {
217
+ $match: {
218
+ uuid: orderId
219
+ }
220
+ }
221
+ ];
222
+
223
+ let payment = await program.modules.data.aggregate(program,process.env.dbName, 'payment', pipeline);
224
+ if (payment.length == 0) {
225
+ res.status(500);
226
+ res.send(`FALSE`);
227
+ } else {
228
+ payment = payment[0];
229
+ }
230
+
231
+ console.log(`We have payment data`);
232
+
233
+ // Check if cancel
234
+ let order = await program.modules.data.aggregate(program,process.env.dbName, 'order', [
235
+ {
236
+ $match: {
237
+ uuid: payment.order
238
+ }
239
+ }
240
+ ]);
241
+ order = order[0];
242
+
243
+ // We have order add action to state
244
+ const typeOf = typeof order.state;
245
+ if (typeOf != `object`) {
246
+ order.state = [];
247
+ }
248
+ order.state[action] = Date.now();
249
+
250
+
251
+ // Get id
252
+ if (type == `post`) {
253
+ const paymentID = body.id;
254
+
255
+ // Now check payment
256
+ const getURL = `${json.url}/v2/payments/${paymentID}`
257
+ const validate = await restArray.get(getURL);
258
+
259
+ // Okay we have new data
260
+ const status = validate.status;
261
+
262
+ order.state[status] = Date.now();
263
+
264
+ console.log(`To Validate Payment`);
265
+
266
+ // Add completed to state if finished
267
+ if (status == `paid`) {
268
+ const paidDate = new Date(validate.paidAt);
269
+ const unixTimestamp = Math.floor(paidDate.getTime() / 1000);
270
+ order.state[`completed`] = unixTimestamp;
271
+
272
+ // Update
273
+ const updatedFinal =await program.modules.data.update(process.env.dbName,`order`,{
274
+ uuid : orderId
275
+ },{
276
+ $set: {
277
+ payed : unixTimestamp,
278
+ paymentDetails : validate.details,
279
+ countryCode : validate.countryCode,
280
+ mode : validate.mode,
281
+ state : true,
282
+ paid : Date.now()
283
+ }
284
+ });
285
+ console.log(`Final Update`,updatedFinal);
286
+
287
+ // Check also for message now
288
+ // Grab message
289
+ try {
290
+ const lastMessageId = order.messages[0];
291
+ let messageData = await program.modules.data.aggregate(program,process.env.dbName, 'send', [{$match: {uuid: lastMessageId}}]);
292
+ if (messageData.length == 0) {
293
+ // No message send
294
+ console.error(`No Message Send`);
295
+ } else {
296
+ messageData = messageData[0];
297
+ }
298
+
299
+ const packageID = order.package;
300
+
301
+ let packageLine = [{$match: {uuid:packageID}},{$project: {name: 1,description: 1, price:1}}];
302
+ let packageData = await program.modules.data.aggregate(program,process.env.dbName, 'pricing', packageLine);
303
+
304
+ // Okay we have message data
305
+ const orderURL = `${process.env.webURL.slice(0,-1)}/concepts/esimco/order#${payment.uuid}__redirect`;
306
+ const howToURL = `${process.env.webURL.slice(0,-1)}/concepts/esimco/order#${payment.uuid}__how-to`;
307
+ const referralURL = `${process.env.webURL.slice(0,-1)}/concepts/esimco/order#${payment.uuid}__referral`;
308
+
309
+ const textMessage = `<b>✅ Your payment is received!</b>\n<span class="tg-spoiler">Order ID: <b>${order.uuid}</b></span>\n\nWe are now matching your order and payment. You will receive your ordered prodcut in a few minutes: <b>${String(packageData[0].description).toUpperCase()}</b>`
310
+ try {
311
+ let telegramSend = await program.modules.telegram.functions.send(program,textMessage,order.user,[
312
+ [
313
+ { text: 'View Order', web_app : { url : orderURL}},
314
+ { text: 'How to?', web_app : { url : howToURL}},
315
+ { text: 'Referral', web_app : { url : referralURL}}
316
+ ]
317
+ ],messageData.message_id);
318
+
319
+ console.log(`Sending telegram`);
320
+ } catch(err) {
321
+ console.error(err);
322
+ console.error(`Error updating message`);
323
+ }
324
+
325
+ } catch (err) {
326
+ console.error(err);
327
+ console.error(`Something with message`);
328
+ }
329
+ }
330
+ }
331
+
332
+
333
+ const updated =await program.modules.data.update(process.env.dbName,`order`,{
334
+ uuid : order.uuid
335
+ },{
336
+ $set: {
337
+ state : order.state
338
+ }
339
+ });
340
+
341
+ // Updated state in order
342
+ // Now redirect doesn't matter in what
343
+ const fullPath = `${process.env.webURL.slice(0,-1)}/concepts/esimco/order#${order.uuid}__redirect`;
344
+ if (type == `post`) {
345
+ res.send(`OK`);
346
+ res.status(200);
347
+ } else if (action == `page-redirect` || action == `bot-redirect`) {
348
+ res.redirect(payment._links.checkout.href)
349
+ } else {
350
+ res.redirect(fullPath);
351
+ }
352
+ }
353
+ program.express.app.get(`/webhooks/orders/:orderId/:action`, async function(req,res){
354
+ return await functionRequest(req,res,`get`);
355
+ })
356
+ program.express.app.post(`/webhooks/orders/:orderId/:action`, async function(req,res){
357
+ return await functionRequest(req,res,`post`);
358
+ })
129
359
  return restArray;
130
360
  }
@@ -24,7 +24,17 @@ module.exports = async function(program, url, body,headers) {
24
24
  const respHeaders = response.headers;
25
25
 
26
26
  if (!response.ok) {
27
+ if (respBody.parameters != undefined) {
28
+ // Probably some wait
29
+ if (respBody.parameters.retry_after != undefined) {
30
+ const timeOUtAmount = respBody.parameters.retry_after * 1000*60; // for 1 minute if retry_ is 1 minute
31
+ await setTimeout(async function(){
32
+ return await program.modules.request.post(program,url,body,headers);
33
+ },timeOUtAmount);
34
+ }
35
+ } else {
27
36
  throw new Error(`HTTP error! Status: ${response.status}`);
37
+ }
28
38
  }
29
39
 
30
40
  const responseData = respBody;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webfast",
3
- "version": "0.1.87",
3
+ "version": "0.1.88",
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": {
@@ -41,7 +41,9 @@
41
41
  "ideal",
42
42
  "creditcard",
43
43
  "applepay",
44
- "googlepay"
44
+ "googlepay",
45
+ "mollie pay",
46
+ "payments"
45
47
  ],
46
48
  "author": "Kai Gartner",
47
49
  "license": "ISC",