let pendingDownloads = new Map();
let downloadNotifications = new Map();
let suggestCallbacks = new Map();
let contentAnalysisResults = new Map(); // Store content analysis results
function callSuggestSafely(downloadId, suggestion) {
const suggest = suggestCallbacks.get(downloadId);
if (suggest) {
if (!suggestion.filename) {
console.warn("Suggesting with an empty filename. Using default behavior.");
suggestion = {}; // Ensure default behavior
}
suggest(suggestion);
suggestCallbacks.delete(downloadId);
} else {
console.warn(No suggest callback found for download ID ${downloadId});
}
}
// --- 1. Analyze Filename FIRST ---
const filenameResults = analyzeFilename(downloadItem.filename, parsedConfigs);
const highFilenameMatch = filenameResults.find(r => r.filenameMatchPercentage >= MATCH_THRESHOLD);
if (highFilenameMatch) {
console.log(`High filename match detected for ${highFilenameMatch.name} (${Math.round(highFilenameMatch.filenameMatchPercentage)}%), skipping further analysis.`);
filenameResults.sort((a, b) => b.filenameMatchPercentage - a.filenameMatchPercentage);
return filenameResults; // Return immediately if high filename match
}
// --- 2. Try to get tab information ---
let tabInfo = null;
if (downloadItem.initiator) {
try {
tabInfo = await getTabInfo(downloadItem.initiator);
console.log("Tab Info:", tabInfo);
} catch (error) {
console.error("Error getting tab info:", error);
// Fallback to history
}
}
// --- 3. Analyze based on tab info or history ---
let historyItems = [];
if (!tabInfo) {
historyItems = await getRecentHistory(MAX_HISTORY_ITEMS);
console.log("History Items:", historyItems); // Log the history items
}
// --- 4. Analyze URLs and Titles ---
const urlResults = await analyzeUrls(downloadItem.url, downloadItem.referrer, tabInfo, historyItems, parsedConfigs);
const highTitleMatchResult = urlResults.find(r => r.titleMatchPercentage >= TITLE_MATCH_THRESHOLD);
if (highTitleMatchResult) {
console.log(`High title match detected for ${highTitleMatchResult.name} (${Math.round(highTitleMatchResult.titleMatchPercentage)}%), skipping content analysis if content threshold not also met.`);
// DON'T return yet, we need to check content and combine results
}
// --- 5. Analyze Page Content (Always, but give priority to tabInfo) ---
let contentResults = [];
if (tabInfo) {
// Use content analysis result if available, otherwise, request it
if (contentAnalysisResults.has(tabInfo.id)) {
const content = contentAnalysisResults.get(tabInfo.id);
// Parse the content string back into a DOM tree.
const doc = parseHtmlContent(content);
contentResults = await analyzePageContent([{ title: tabInfo.title, url: tabInfo.url, doc: doc }], parsedConfigs);
contentAnalysisResults.delete(tabInfo.id); //consume it
} else {
// Inject content script to get the content (if not already retrieved)
try {
await injectContentScript(tabInfo.id, downloadItem.initiator); // Inject and wait
} catch (error) {
console.error("Failed to inject content script:", error);
}
if (contentAnalysisResults.has(tabInfo.id)) {
const content = contentAnalysisResults.get(tabInfo.id);
// Parse the content string back into a DOM tree.
const doc = parseHtmlContent(content);
contentResults = await analyzePageContent([{ title: tabInfo.title, url: tabInfo.url, doc: doc }], parsedConfigs);
contentAnalysisResults.delete(tabInfo.id);
} else {
console.warn("Content analysis not available for tab:", tabInfo.id);
contentResults = await analyzePageContent([], parsedConfigs); // Use empty array as fallback
}
}
} else {
// Use history and content analysis results
const itemsToAnalyze = [];
for (let i = 0; i < historyItems.length && i < MAX_HISTORY_ITEMS; i++) {
const item = historyItems[i];
console.log(`Analyzing history item ${i + 1}:`, item); // Log each history item being analyzed
if (contentAnalysisResults.has(item.id)) {
const content = contentAnalysisResults.get(item.id);
// Parse the content string back into a DOM tree.
const doc = parseHtmlContent(content);
console.log(`Content found for history item ${i + 1}, length: ${content.length}`); // Log content length
itemsToAnalyze.push({ ...item, doc: doc }); //Store the doc
contentAnalysisResults.delete(item.id);
} else {
itemsToAnalyze.push(item); //If no content, use the item. analyzePageContent will handle.
}
}
console.log("Items to Analyze (Content):", itemsToAnalyze); // Log the items prepared for content analysis
contentResults = await analyzePageContent(itemsToAnalyze, parsedConfigs);
}
const highContentMatchResult = contentResults.find(r => r.contentMatchPercentage >= CONTENT_MATCH_THRESHOLD);
// --- 6. Combine Results ---
let combinedResults = combineResults(filenameResults, urlResults); // Combine filename and URL/Title
combinedResults = combineResults(combinedResults, contentResults); // Combine with content results
if (highContentMatchResult) {
console.log(`High content match detected for ${highContentMatchResult.name} (${Math.round(highContentMatchResult.contentMatchPercentage)}%).`);
}
combinedResults.sort((a, b) => b.matchPercentage - a.matchPercentage);
return combinedResults;
}
// Helper function to safely parse HTML content
function parseHtmlContent(htmlString) {
const parser = new DOMParser();
try {
const doc = parser.parseFromString(htmlString, "text/html");
return doc;
} catch (error) {
console.error("Error parsing HTML content:", error);
return null; // Return null on error
}
}
// UPDATED: In analyzeFilename, add debug logging by passing "filename" as the source.
function analyzeFilename(filename, parsedConfigs) {
const normalizedFilename = filename.toLowerCase();
const results = [];
for (const config of parsedConfigs) {
let matchCount = 0;
for (const keyword of config.keywordList) {
if (normalizedFilename.includes(keyword)) {
console.debug(Match found: Keyword "${keyword}" found in filename: ${filename} (direct match));
matchCount++;
}
}
const filenameMatchPercentage = config.keywordList.length > 0 ? Math.min(100, (matchCount / config.keywordList.length) * 100) : 0;
results.push({
name: config.name,
downloadPath: config.downloadPath,
filenameMatchPercentage,
matchPercentage: filenameMatchPercentage,
urlMatchPercentage: 0,
titleMatchPercentage: 0,
contentMatchPercentage: 0
});
}
return results;
}
//Combine Filename and Other results
function combineResults(filenameResults, otherResults) {
const combined = [...filenameResults]; // Start with filename results
code
// Merge other results, updating matchPercentage if necessary
for (const otherResult of otherResults) {
const existing = combined.find(r => r.name === otherResult.name);
if (existing) {
// Update URL and title percentages, and recalculate overall matchPercentage
existing.urlMatchPercentage = Math.max(existing.urlMatchPercentage, otherResult.urlMatchPercentage || 0); // Ensure 0 if undefined
existing.titleMatchPercentage = Math.max(existing.titleMatchPercentage, otherResult.titleMatchPercentage || 0);
existing.contentMatchPercentage = Math.max(existing.contentMatchPercentage, otherResult.contentMatchPercentage || 0); // Take max of content percentages
existing.matchPercentage = Math.max(existing.filenameMatchPercentage, existing.urlMatchPercentage, existing.titleMatchPercentage, existing.contentMatchPercentage); // Include content in overall max
} else {
//This part should never happen as filename should contain every name
combined.push(otherResult);
}
}
return combined;
}
async function getTabInfo(initiator) {
return new Promise((resolve, reject) => {
// Try to find the tab based on the initiator URL
chrome.tabs.query({}, (tabs) => { // Query ALL tabs
const matchedTab = tabs.find(tab => tab.url && initiator && tab.url.startsWith(initiator.split('?')[0])); //Basic URL Matching
code
if (!matchedTab) {
reject(new Error("No matching tab found."));
return;
}
// Inject content script to get the title
chrome.scripting.executeScript({
target: { tabId: matchedTab.id },
func: () => document.title, // Get the title directly
}, (results) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
return;
}
if (results && results[0] && results[0].result) {
resolve({ title: results[0].result, url: matchedTab.url, id: matchedTab.id });
} else {
reject(new Error("Failed to get tab title."));
}
});
});
});
}
async function injectContentScript(tabId, initiator) {
return new Promise((resolve, reject) => {
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['content-script.js']
}, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
// Send initiator information to content script
chrome.tabs.sendMessage(tabId, { action: "setInitiator", initiator: initiator }).catch(err => {
console.warn("Tab might have closed before message could be sent:", err); //This is not critical
});
resolve(); //Resolve after injection, not after analysis
}
});
});
}
async function getRecentHistory(count) {
return new Promise((resolve) => {
chrome.history.search({
text: '',
maxResults: count * 3, // Fetch more to filter effectively
startTime: Date.now() - (7 * 24 * 60 * 60 * 1000) // Last 7 days
}, (historyItems) => {
const filteredItems = historyItems
.filter(item => !item.url.startsWith('chrome://') &&
!item.url.startsWith('edge://') &&
!item.url.startsWith('about:') &&
item.url !== 'about:blank')
.slice(0, count);
code
// Add tab ID for content analysis lookup
const itemsWithIds = filteredItems.map(item => ({ ...item, id: `history-${String(item.visitId)}` })); //Unique ID
resolve(itemsWithIds);
});
});
}
// UPDATED: In analyzeUrls, pass the URL and title as source for debug logging.
async function analyzeUrls(url, referrer, tabInfo, historyItems, parsedConfigs) {
const urls = [url, referrer];
if (tabInfo) {
urls.push(tabInfo.url);
} else {
// Only add the last 3 history items' URLs
urls.push(...historyItems.slice(0,MAX_HISTORY_ITEMS).map(item => item.url));
}
const filteredUrls = urls.filter(Boolean);
code
const titles = [];
if (tabInfo) {
titles.push(tabInfo.title);
} else {
// Only add the last 3 history items' titles
titles.push(...historyItems.slice(0,MAX_HISTORY_ITEMS).map(item => item.title));
}
const filteredTitles = titles.filter(Boolean);
const results = [];
for (const config of parsedConfigs) {
let urlMatchCount = 0;
let titleMatchCount = 0;
for (const urlToCheck of filteredUrls) {
const normalizedUrl = urlToCheck.toLowerCase();
for (const keyword of config.keywordList) {
if (normalizedUrl.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in url: ${urlToCheck} (direct match)`);
urlMatchCount++;
break; // Only count each URL once per config
}
}
}
for (const titleToCheck of filteredTitles) {
const normalizedTitle = titleToCheck.toLowerCase();
for (const keyword of config.keywordList) {
if (normalizedTitle.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in title: ${titleToCheck} (direct match)`);
titleMatchCount++;
// Count all title matches per keyword
}
}
}
const urlMatchPercentage = filteredUrls.length > 0 ? Math.min(100, (urlMatchCount / filteredUrls.length) * 100) : 0;
const titleMatchPercentage = filteredTitles.length > 0 ? Math.min(100, (titleMatchCount / (filteredTitles.length * config.keywordList.length)) * 100) : 0;
console.log(`Match Percentage for ${config.name} - URLs: ${urlMatchPercentage}% (Match Count: ${urlMatchCount}, URLs Checked: ${filteredUrls.length}), Titles: ${titleMatchPercentage}% (Match Count: ${titleMatchCount}, Titles Checked: ${filteredTitles.length})`);
results.push({
name: config.name,
downloadPath: config.downloadPath,
urlMatchPercentage,
urlMatchCount,
titleMatchPercentage,
titleMatchCount,
matchPercentage: Math.max(urlMatchPercentage, titleMatchPercentage),
contentMatchPercentage: 0
});
}
return results;
}
// Recursive function to traverse the DOM and check for keywords.
function traverseAndCheck(node, keywordList, source, matchCounts) {
if (!node) {
return;
}
code
// Check the node's text content (if it's a text node).
if (node.nodeType === Node.TEXT_NODE) {
const normalizedText = node.textContent.toLowerCase();
for (const keyword of keywordList) {
if (normalizedText.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in ${source} text content`);
matchCounts.totalContentMatches++;
matchCounts.matchingItemsCount = 1; //Mark as matched
}
}
}
// Check element attributes (if it's an element node).
if (node.nodeType === Node.ELEMENT_NODE) {
for (const attr of node.attributes) {
const normalizedAttrValue = attr.value.toLowerCase();
for (const keyword of keywordList) {
if (normalizedAttrValue.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in ${source} attribute ${attr.name}`);
matchCounts.totalContentMatches++;
matchCounts.matchingItemsCount = 1;//Mark as matched
}
}
}
}
// Recursively check child nodes.
for (const child of node.childNodes) {
traverseAndCheck(child, keywordList, source, matchCounts);
}
}
// UPDATED: analyzePageContent now uses traverseAndCheck
async function analyzePageContent(items, parsedConfigs) {
const results = [];
for (const config of parsedConfigs) {
let totalContentMatches = 0;
let matchingItemsCount = 0; // Number of items that had at least one match
code
for (const item of items) {
if(!item.doc) continue; //Skip if no doc
const matchCounts = { totalContentMatches: 0, matchingItemsCount: 0 }; //Counts per item
traverseAndCheck(item.doc.documentElement, config.keywordList, `content from item with title: ${item.title}`, matchCounts);
totalContentMatches += matchCounts.totalContentMatches;
if(matchCounts.matchingItemsCount > 0) matchingItemsCount++; //Increment if any matches were found
}
const contentMatchPercentage = items.length > 0 ? Math.min(100, (matchingItemsCount / items.length) * 100) : 0;
results.push({
name: config.name,
downloadPath: config.downloadPath,
contentMatchPercentage,
contentMatchCount: totalContentMatches,
matchPercentage: contentMatchPercentage,
urlMatchPercentage: 0,
titleMatchPercentage: 0,
filenameMatchPercentage: 0
});
}
return results;
}
function showDownloadPathNotification(downloadItem, options) {
if (options.length > 0 && (options[0].matchPercentage >= MATCH_THRESHOLD)) {
// No notification if a high match.
processDownloadChoice(downloadItem.id, 0);
return;
}
async function processDownloadChoice(downloadId, chosenIndex) {
const pendingDownload = pendingDownloads.get(downloadId);
if (!pendingDownload) {
console.log(Pending download with ID ${downloadId} not found.);
return;
}
// content-script.js
// Content script to analyze page content for game-related keywords
(function() {
// Extract text content from the page
function extractPageContent() {
// Get all text from relevant elements, avoiding scripts and styles
const elements = document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, a, li, span, div, td, th'); // Added table elements
let textContent = '';
code
elements.forEach(element => {
// Skip hidden elements
if (element.offsetParent === null) return;
// Get text and remove extra whitespace
const text = element.textContent.trim();
if (text) {
textContent += ' ' + text;
}
});
// Clean up the text (remove excessive whitespace)
textContent = textContent.replace(/\s+/g, ' ').trim();
// Get page title as well
const pageTitle = document.title;
return {
text: textContent,
title: pageTitle
};
Para resolver esse problema e melhorar a implementação, sugiro o seguinte:
Revise a lógica da função de análise recursiva para garantir que ela esteja percorrendo corretamente todas as subpáginas e elementos dentro das 3 páginas principais.
Verifique se a extração do texto de cada página está sendo feita de forma adequada, considerando diferentes elementos HTML que possam conter texto relevante, como parágrafos, cabeçalhos, listas, etc.
Aperfeiçoe o algoritmo de busca das palavras-chave, levando em consideração possíveis variações de capitalização, pontuação e espaçamento. Utilize expressões regulares para uma busca mais flexível e abrangente.
Certifique-se de que o cálculo da porcentagem de cobertura esteja correto, dividindo o número de ocorrências da palavra-chave pelo total de palavras na página e multiplicando por 100.
Considere implementar um sistema de cache para armazenar os resultados da análise de cada página, evitando processamento desnecessário em chamadas subsequentes para a mesma página.
Realize testes extensivos com diferentes páginas e palavras-chave para garantir que a análise recursiva esteja funcionando corretamente e fornecendo resultados precisos.
Ao seguir essas etapas, você poderá corrigir os problemas existentes na análise recursiva do conteúdo das páginas e obter resultados mais precisos e confiáveis na busca por palavras-chave e cálculo da porcentagem de cobertura. o funcionamento dele ser muito semelhante com o do notification no quesito de analise
Based on your description, it seems you're looking to improve the content analysis functionality in your Chrome extension. Here's a revised approach that addresses the issues you've mentioned and aligns the content analysis more closely with the notification analysis:
Update the analyzePageContent function:
javascript
async function analyzePageContent(items, parsedConfigs) {
const results = [];
for (const config of parsedConfigs) {
let totalContentMatches = 0;
let matchingItemsCount = 0; // Number of items that had at least one match
for (const item of items) {
if(!item.doc) continue; //Skip if no doc
const matchCounts = { totalContentMatches: 0, matchingItemsCount: 0 }; //Counts per item
traverseAndCheck(item.doc.documentElement, config.keywordList, `content from item with title: ${item.title}`, matchCounts);
totalContentMatches += matchCounts.totalContentMatches;
if(matchCounts.matchingItemsCount > 0) matchingItemsCount++; //Increment if any matches were found
}
const contentMatchPercentage = items.length > 0 ? Math.min(100, (matchingItemsCount / items.length) * 100) : 0;
results.push({
name: config.name,
downloadPath: config.downloadPath,
contentMatchPercentage,
contentMatchCount: totalContentMatches,
matchPercentage: contentMatchPercentage,
urlMatchPercentage: 0,
titleMatchPercentage: 0,
filenameMatchPercentage: 0
});
}
return results;
}
Add a recursive DOM traversal function:
javascript
function traverseAndCheck(node, keywordList, source, matchCounts) {
if (!node) {
return;
}
// Check the node's text content (if it's a text node).
if (node.nodeType === Node.TEXT_NODE) {
const normalizedText = node.textContent.toLowerCase();
for (const keyword of keywordList) {
if (normalizedText.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in ${source} text content`);
matchCounts.totalContentMatches++;
matchCounts.matchingItemsCount = 1; //Mark as matched
}
}
}
// Check element attributes (if it's an element node).
if (node.nodeType === Node.ELEMENT_NODE) {
for (const attr of node.attributes) {
const normalizedAttrValue = attr.value.toLowerCase();
for (const keyword of keywordList) {
if (normalizedAttrValue.includes(keyword)) {
console.debug(`Match found: Keyword "${keyword}" found in ${source} attribute ${attr.name}`);
matchCounts.totalContentMatches++;
matchCounts.matchingItemsCount = 1;//Mark as matched
}
}
}
}
// Recursively check child nodes.
for (const child of node.childNodes) {
traverseAndCheck(child, keywordList, source, matchCounts);
}
}
Update the content script to send the entire DOM structure:
// In the background script, where you process the content analysis message
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "contentAnalysis") {
const parser = new DOMParser();
const doc = parser.parseFromString(message.content, "text/html");
contentAnalysisResults.set(sender.tab ? sender.tab.id : message.initiator, doc);
}
});
These changes will make the content analysis more thorough and consistent with the notification analysis. The traverseAndCheck function recursively checks all nodes in the DOM, including text nodes and element attributes, for keyword matches. This approach should provide more accurate results and better alignment with the notification functionality.
Remember to adjust the CONTENT_MATCH_THRESHOLD in your background script to fine-tune when content matches are considered significant:
javascript
const CONTENT_MATCH_THRESHOLD = 50; // Adjust as needed
This implementation should address the issues you've mentioned and provide a more robust content analysis that's similar to the notification analysis in terms of thoroughness and accuracy.