Skip to content

Commit 6b02876

Browse files
committed
Improve performance
Merge all users tracking same produt to reduce the load
1 parent c67f039 commit 6b02876

File tree

3 files changed

+72
-26
lines changed

3 files changed

+72
-26
lines changed

bot.js

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,10 @@ bot.command("users", async (ctx) => {
184184
bot.command("stats", async (ctx) => {
185185
const users = await manageUsers({}, "read");
186186
const products = await manageProducts({}, "read");
187+
let userCount = 0;
188+
products.result.map((p) => (p += item.users.length));
187189
ctx.reply(
188-
`Total Users: ${users.result.length}\nTotal Products: ${products.result.length}`
190+
`Total Users: ${users.result.length}\nTotal Products: ${userCount}`
189191
);
190192
});
191193

@@ -222,23 +224,25 @@ const track = async () => {
222224
const details = await getProductDetails(product.link, product.merchant);
223225
if (details.ok && !isNaN(details.price) && details.price !== product.price) {
224226
try {
225-
await manageProducts({ tracking_id: product.tracking_id, userId: product.userId, merchant: product.merchant, title: details.title, link: product.link, initPrice: product.price, price: details.price, }, "update");
226-
bot.api.sendMessage(
227-
product.userId,
228-
`<a href="${details.image}"> </a><b>Price has been ${details.price > product.price ? "increased" : "decreased"
229-
} by ${Math.abs(product.price - details.price)}</b>. \n\n<b>${details.title
230-
}</b>\n\nCurrent Price: <b>${details.price}</b>\nLink: <a href="${details.link
231-
}">${product.merchant}</a>\n\nTo stop tracking send /stop_${product.tracking_id
232-
}`,
233-
{
234-
parse_mode: "HTML",
235-
reply_markup: {
236-
inline_keyboard: details?.link ? [
237-
[{ text: "Buy Now", url: details.link }],
238-
[{ text: "Stop Tracking - " + product.tracking_id, callback_data: `stopTracking`, }]]
239-
: []
240-
}
241-
});
227+
await manageProducts({ tracking_id: product.tracking_id, userId: product.userId, merchant: product.merchant, title: details.title, link: product.link, initPrice: product.price, price: details.price, users: product.users}, "update");
228+
await Promise.all(product.users.map(async user => {
229+
bot.api.sendMessage(
230+
user.userId,
231+
`<a href="${details.image}"> </a><b>Price has been ${details.price > product.price ? "increased" : "decreased"
232+
} by ${Math.abs(product.price - details.price)}</b>. \n\n<b>${details.title
233+
}</b>\n\nCurrent Price: <b>${details.price}</b>\nLink: <a href="${details.link
234+
}">${product.merchant}</a>\n\nTo stop tracking send /stop_${user.tracking_id
235+
}`,
236+
{
237+
parse_mode: "HTML",
238+
reply_markup: {
239+
inline_keyboard: details?.link ? [
240+
[{ text: "Buy Now", url: details.link }],
241+
[{ text: "Stop Tracking - " + user.tracking_id, callback_data: `stopTracking`, }]]
242+
: []
243+
}
244+
});
245+
}))
242246
} catch (e) { bot.start() }
243247
}
244248
})

db.js

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,26 @@ const manageProducts = async(data, action) => {
4848
const collection = db.collection('tasks');
4949
switch(action) {
5050
case 'delete':
51-
await collection.deleteOne({tracking_id: data.tracking_id, userId: data.userId});
51+
await collection.updateOne(
52+
{ users: {userId: data.userId, tracking_id: data.tracking_id } },
53+
{ $pull: { users : {userId: data.userId, tracking_id: data.tracking_id } }, }
54+
);
5255
return {ok: true}
5356
case 'update':
54-
const res = await collection.updateOne({tracking_id: data.tracking_id}, {$set: data}, {upsert: true});
57+
await collection.updateOne(
58+
{ link: data.link },
59+
{
60+
$set: {
61+
link: data.link,
62+
merchant: data.merchant,
63+
initPrice: data.initPrice,
64+
price: data.price,
65+
title: data.title,
66+
},
67+
$addToSet: {users : Array.isArray(data.users) ? {$each: data.users} : data.users},
68+
},
69+
{ upsert: true }
70+
);
5571
return {ok: true, tracking_id: data.tracking_id}
5672
case 'read':
5773
const result = await collection.find(data).toArray();
@@ -65,4 +81,10 @@ const manageProducts = async(data, action) => {
6581
}
6682
}
6783

84+
// manageProducts({}, 'read').then(data => {
85+
// console.log(data);
86+
// fs.writeFileSync('products.json', JSON.stringify(data.result));
87+
// }).catch(e => {
88+
// })
89+
6890
export {manageProducts, manageUsers};

utils.js

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,30 +28,50 @@ const selectors = {
2828
}
2929
}
3030

31+
const productCommonUrl = (link) => {
32+
const url = new URL(link?.replace("www.", ""));
33+
const merchant = url.hostname.split(".")[0];
34+
let id, commonUrl;
35+
switch (merchant) {
36+
case "amazon":
37+
id = link.match(
38+
/https?:\/\/(www\.)?(.*)amazon\.([a-z\.]{2,6})(\/d\/(.*)|\/(.*)\/?(?:dp|o|gp|-)\/)(aw\/d\/|product\/)?(B[0-9]{1}[0-9A-Z]{8}|[0-9]{9}(?:X|[0-9]))/i
39+
).splice(-1)[0];
40+
commonUrl = "https://www.amazon.in/dp/" + id + "?tag=asloot-21";
41+
break;
42+
case "flipkart":
43+
id = url.searchParams.get("pid");
44+
commonUrl = id ? "https://www.flipkart.com/product/p/itme?pid=" + id : link.includes('/p/itm') ?link.split('?')[0] : link;
45+
break;
46+
default:
47+
null;
48+
}
49+
50+
return commonUrl;
51+
};
52+
3153
const getProductDetails = async(url, merchant) => {
3254
try{
33-
const res = await axios.get(`${WORKER_URL}/?url=${encodeURIComponent(url)}`, {
55+
const commonUrl = productCommonUrl(url);
56+
const res = await axios.get(`${WORKER_URL}/?url=${encodeURIComponent(commonUrl)}`, {
3457
headers: {
3558
"User-Agent":
3659
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36",
3760
},
3861
});
3962
const $ = cheerio.load(res.data);
4063
const selector = selectors[merchant];
41-
let link = new URL(url);
42-
if(merchant == 'amazon') link.searchParams.set('tag', 'asloot-21');
43-
link = link.toString();
4464
const price = parseInt($(selector.price1).text().trim().replace(/^\D+|[^0-9.]/g, '')) || parseInt($(selector.price2).text().trim().replace(/^\D+|[^0-9.]/g, ''));
4565
const title = $(selector.title).text().trim();
4666
const image = $(selector.image1).attr('src');
4767
if(!title || !price) {
4868
return {ok: false}
4969
}
50-
return {ok: true, title, price, image, link}
70+
return {ok: true, title, price, image, link: commonUrl}
5171
}catch(e){
5272
console.log(e);
5373
return {ok: false}
5474
}
5575
}
5676

57-
export { isUrl, getRandomId, getProductDetails };
77+
export { isUrl, getRandomId, getProductDetails, productCommonUrl };

0 commit comments

Comments
 (0)