Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 34 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,23 +129,27 @@ async function shortenURL(url) {
}

function buildAmazonUrl(asin) {
return `https://www.amazon.${amazon_tld}/dp/${asin}?tag=${amazon_tag}`;
return `https://www.amazon.${amazon_tld}/dp/${asin.trim()}?tag=${amazon_tag}`.replace(/\s+/g, '');
}

function buildRawAmazonUrl(element) {
const url = element.expanded_url ? element.expanded_url : element.fullURL;
const strucutredURL = new URL(url);
strucutredURL.searchParams.set("tag", amazon_tag);
const structuredURL = new URL(url.trim());
structuredURL.searchParams.set("tag", amazon_tag);

return strucutredURL.toString();
return structuredURL.toString().replace(/\s+/g, '');
}

async function getAmazonURL(element) {
const url =
element.asin != null
? buildAmazonUrl(element.asin)
: buildRawAmazonUrl(element);
return shorten_links ? await shortenURL(url) : url;
return shorten_links ? await shortenURL(url.replace(/\s+/g, '')) : url.replace(/\s+/g, '');
}

function removeSpaces(url) {
return url.replace(/\s+/g, '');
}

function buildMention(user) {
Expand All @@ -161,7 +165,7 @@ async function buildMessage(chat, message, replacements, user) {
const sponsored_url = await getAmazonURL(element);
affiliate_message = affiliate_message.replace(
element.fullURL,
sponsored_url
removeSpaces(sponsored_url)
);
}

Expand Down Expand Up @@ -282,6 +286,8 @@ function replaceTextLinks(msg) {
return msg.text;
}
}
// capture the amzn.eu format
const amznEuRegex = /https?:\/\/(www\.)?amzn\.eu\/d\/([A-Za-z0-9]+)/gi;

bot.on("message", async (msg) => {
try {
Expand Down Expand Up @@ -364,6 +370,28 @@ bot.on("message", async (msg) => {
}
}

// Handle amzn.eu short links in the message
amznEuRegex.lastIndex = 0;
while ((match = amznEuRegex.exec(msg.text)) !== null) {
const shortURL = match[0];
const url = await getLongUrl(shortURL);

if (url != null) {
if (raw_links) {
replacements.push({
asin: null,
expanded_url: url.fullURL,
fullURL: shortURL,
});
} else {
replacements.push({
asin: getASINFromFullUrl(url.fullURL),
fullURL: shortURL,
});
}
}
}

if (replacements.length > 0) {
const text = await buildMessage(
msg.chat,
Expand Down