Skip to content

Commit 6df2b73

Browse files
committed
Added functionality for auto-summarisation (premium plus only)
1 parent 306ed04 commit 6df2b73

File tree

3 files changed

+78
-54
lines changed

3 files changed

+78
-54
lines changed

background.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,8 @@ function summarizeDocument(document, url, sectionTitle, pageURL) {
398398
if (response.status === 429) {
399399
if (data.error === "You've exceeded your monthly summary limit for the FREE plan") {
400400
message = `You've exceeded your monthly summary limit for the FREE plan. Please <a id="premium-subscribe-txt-sums" href="#" class="underline">subscribe</a> for unlimited summaries.`;
401+
} else if (data.error === "You've exceeded your monthly summary limit for the PREMIUM plan") {
402+
message = `You've exceeded your monthly summary limit of 15 for the premium plan.`;
401403
} else {
402404
message = "Please slow down, you've made too many requests in a short amount of time. Please wait an hour and try again. If you're still seeing this message, please contact us at [email protected].";
403405
}

content.js

Lines changed: 73 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -21,104 +21,124 @@ function findPotentialLabelForCheckbox(checkbox) {
2121
}
2222

2323
function detectCheckboxes() {
24-
// Select all checkboxes on the page.
2524
let checkboxes = document.querySelectorAll('input[type="checkbox"]');
26-
27-
// Check if at least one checkbox is present on the page.
2825
if (checkboxes.length > 0) {
2926
for (let checkbox of checkboxes) {
3027
if (!checkbox.checked) {
3128
let label = document.querySelector(`label[for="${checkbox.id}"]`) || findPotentialLabelForCheckbox(checkbox);
3229
if (label) {
3330
sendNotification();
34-
break; // Exit after finding the first unlabeled checkbox
31+
break;
3532
}
3633
}
3734
}
3835
}
3936
}
4037

4138
function detectTextConsent() {
42-
// Scan the page for text containing "by" and "agree".
4339
const bodyText = document.body.textContent || "";
4440
const consentPattern = /\bby\b.*?\bagree\b/;
4541
if (consentPattern.test(bodyText)) {
4642
sendNotification();
4743
}
4844
}
4945

50-
// Run immediately on page load
46+
47+
function displayPreloader(sectionTitle, domain) {
48+
chrome.storage.local.get(['loadingSummaries'], function (result) {
49+
let loadingSummaries = result.loadingSummaries || [];
50+
loadingSummaries.push({ title: sectionTitle, domain: domain });
51+
chrome.storage.local.set({ loadingSummaries: loadingSummaries });
52+
53+
console.log("Displaying preloader for " + sectionTitle);
54+
});
55+
}
56+
57+
58+
59+
function handlePolicyLinks() {
60+
const keywords = ['privacy', 'terms', 'return', 'shipping', 'legal', 'cookie'];
61+
const currentDomain = rootDomain(new URL(window.location.href).hostname);
62+
let linksMap = {};
63+
let summarizedLinks = JSON.parse(localStorage.getItem('summarizedLinks') || '{}');
64+
65+
keywords.forEach(keyword => {
66+
const foundLinks = Array.from(document.querySelectorAll('a')).filter(link => {
67+
return (link.href.toLowerCase().includes(keyword) || link.innerText.toLowerCase().includes(keyword));
68+
});
69+
70+
foundLinks.forEach(link => {
71+
const linkDomain = rootDomain(new URL(link.href, window.location.origin).hostname);
72+
if (linkDomain === currentDomain) {
73+
if (!linksMap[keyword]) { // Ensure only the first match for each keyword is used
74+
linksMap[keyword] = { href: link.href, text: link.innerText.trim() };
75+
76+
// Check if not already summarized
77+
if (!summarizedLinks[link.href] && link.innerText.trim() !== "") {
78+
const summaryRequestData = {
79+
action: "generateSummary",
80+
url: link.href,
81+
policyName: link.innerText.trim()
82+
};
83+
chrome.runtime.sendMessage(summaryRequestData);
84+
displayPreloader(link.innerText.trim(), currentDomain);
85+
console.log("Sent summary request for " + link.innerText.trim());
86+
summarizedLinks[link.href] = true; // Mark as summarized
87+
localStorage.setItem('summarizedLinks', JSON.stringify(summarizedLinks)); // Save to local storage
88+
}
89+
}
90+
}
91+
});
92+
});
93+
94+
// Always return links that match the keywords, regardless of whether they've been summarized
95+
if (Object.keys(linksMap).length > 0) {
96+
return Object.values(linksMap); // Return the links found for use in popup.js
97+
} else {
98+
return [];
99+
}
100+
}
101+
102+
// This function is called from popup.js to fetch links
103+
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
104+
if (request.action === "findLinks") {
105+
const links = handlePolicyLinks(); // Assume this function is synchronous, adjust if not
106+
sendResponse({ links: links });
107+
return true; // Indicates an asynchronous response is expected
108+
}
109+
});
110+
111+
// Run initial detection on page load
51112
detectCheckboxes();
52113
detectTextConsent();
114+
handlePolicyLinks();
53115

54-
// Set up an interval to run the function every 5 seconds
116+
// Periodically check for updates without resending notifications or summary requests unnecessarily
55117
let consentCheckInterval = setInterval(() => {
56118
if (!notificationSent) {
57119
detectCheckboxes();
58120
detectTextConsent();
59121
}
60122
}, 5000);
61123

62-
// Clear the interval after 30 seconds to stop checking
124+
// Cleanup
63125
setTimeout(() => {
64126
clearInterval(consentCheckInterval);
65127
}, 30000);
66128

67-
68-
69-
70129
function rootDomain(hostname) {
71-
// this function was copied from Aaron Peterson on GitHub: https://gist.github.com/aaronpeterson/8c481deafa549b3614d3d8c9192e3908
72130
let parts = hostname.split(".");
73131
if (parts.length <= 2)
74-
return hostname;
132+
return hostname;
75133

76134
parts = parts.slice(-3);
77135
if (['co', 'com'].indexOf(parts[1]) > -1)
78-
return parts.join('.');
136+
return parts.join('.');
79137

80138
return parts.slice(-2).join('.');
81139
}
82140

83141

84142

85143

86-
87-
88-
89-
// FOR SUGGESTED LINKS
90-
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
91-
if (request.action === "findLinks") {
92-
const keywords = ['privacy', 'term', 'return', 'shipping', 'legal', 'cookie']; // Add more keywords as needed
93-
let linksMap = {};
94-
const currentDomain = rootDomain(new URL(window.location.href).hostname);
95-
96-
// Helper function to check if domains match considering subdomains
97-
const isDomainMatch = (linkDomain, currentDomain) => {
98-
return linkDomain.includes(currentDomain) || currentDomain.includes(linkDomain);
99-
};
100-
101-
keywords.forEach(keyword => {
102-
const foundLinks = Array.from(document.querySelectorAll('a')).filter(link => {
103-
return (link.href.toLowerCase().includes(keyword) || link.innerText.toLowerCase().includes(keyword));
104-
});
105-
106-
for (let i = foundLinks.length - 1; i >= 0; i--) {
107-
const linkDomain = rootDomain(new URL(foundLinks[i].href, window.location.origin).hostname);
108-
if (isDomainMatch(linkDomain, currentDomain)) {
109-
// Store the first link found that matches the domain condition
110-
linksMap[keyword] = { href: foundLinks[i].href, text: foundLinks[i].innerText.trim() };
111-
break; // Exit the loop once a match is found
112-
}
113-
}
114-
});
115-
116-
let links = Object.keys(linksMap).map(keyword => ({
117-
keyword: keyword,
118-
href: linksMap[keyword].href,
119-
text: linksMap[keyword].text
120-
}));
121-
sendResponse({links: links});
122-
}
123-
});
124-
144+
// works now, but why suggested links are not showing up in the popup???? cry face emoji

popup.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -532,8 +532,10 @@ function updatePremiumFeaturesVisibility() {
532532
chrome.storage.local.get(['summariesCount'], function (result) {
533533
console.log(result.summariesCount);
534534
if (result.summariesCount >= 0) {
535-
if (isPremiumUser) {
535+
if (isPremiumUser && userPlan != 'premium') {
536536
document.getElementById('welcomeContainer').innerHTML = `You've used <span class="font-semibold">${result.summariesCount}</span> <span class="tooltip"><span id="sumtokenexplainer">summary tokens</span><span class="tooltiptext">Summary tokens can be spent on generating your own summaries for policies that we've not yet summarised. One token is worth one summary.</span></span> so far this month!`;
537+
} else if (isPremiumUser && userPlan === 'premium') {
538+
document.getElementById('welcomeContainer').innerHTML = `You've used <span class="font-semibold">${result.summariesCount}/15</span> <span class="tooltip"><span id="sumtokenexplainer">summary tokens</span><span class="tooltiptext">Summary tokens can be spent on generating your own summaries for policies that we've not yet summarised. One token is worth one summary.</span></span> this month!`;
537539
} else if (!isPremiumUser) {
538540
document.getElementById('welcomeContainer').innerHTML = `You've used <span class="font-semibold">${result.summariesCount}/2</span> <span class="tooltip"><span id="sumtokenexplainer">summary tokens</span><span class="tooltiptext">Summary tokens can be spent on generating your own summaries for policies that we've not yet summarised. One token is worth one summary.</span></span> this month.`;
539541
}

0 commit comments

Comments
 (0)