-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
138 lines (117 loc) · 4.36 KB
/
content.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Function to scrape video information from the Watch Later playlist
async function scrapeWatchLater() {
console.log('scraping watch later videos...')
try{
const videos = [];
const videoElements = await waitForElements("ytd-playlist-video-renderer");
console.log(`Found ${videoElements.length} videos`);
videoElements.forEach((el) => {
const titleElement = el.querySelector("#video-title");
const thumbnailElement = el.querySelector("img#img");
videos.push({
title: titleElement?.textContent.trim(),
url: `https://www.youtube.com${titleElement?.getAttribute("href")}`,
thumbnail: thumbnailElement?.getAttribute("src"),
});
});
return videos;
}catch(error){
console.error('error scraping videos', error);
return [];
}
}
//waiting for dynamic content loading
function waitForElements(selector, timeout = 5000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
function checkElements() {
const elements = document.querySelectorAll(selector);
if (elements.length > 0) {
resolve(elements);
} else if (Date.now() - startTime >= timeout) {
reject(new Error(`Timeout waiting for ${selector}`));
} else {
setTimeout(checkElements, 500);
}
}
checkElements();
});
}
// wait for page load then execute
window.addEventListener('load', async() =>{
console.log('page fully loaded');
const videos = await scrapeWatchLater();
if (videos.length > 0){
// Send scraped data to the background script
chrome.runtime.sendMessage({ type: "WATCH_LATER_VIDEOS", videos}, (response) => {
if (chrome.runtime.lastError){
console.log('error sending msg',chrome.runtime.lastError);
}else if (response?.success) {
console.log('Videos stored successfully:', response);
} else {
console.error('Error from background script:', response?.error);
}
});
}
});
//runs automatically when script loads
(async function() {
console.log('Starting video fetch...');
try {
// Check last reminder date
const data = await new Promise(resolve => {
chrome.storage.local.get("lastReminderDate", resolve);
});
const today = new Date().toDateString();
if (data.lastReminderDate !== today) {
// Update last reminder date
await new Promise(resolve => {
chrome.storage.local.set({ lastReminderDate: today }, resolve);
});
// Fetch and process videos
const videos = await getStoredVideos();
console.log('Fetched videos:', videos.length);
if (videos.length > 0) {
const video = getWeightedRandomVideo(videos);
console.log('Selected random video:', video);
chrome.runtime.sendMessage({
type: "SHOW_REMINDER",
video
});
}
} else {
console.log('Already reminded today');
}
} catch (error) {
console.error('Error in reminder process:', error);
}
})();
// Helper function to get videos from storage
function getStoredVideos() {
return new Promise((resolve, reject) => {
chrome.storage.local.get(['watchLaterVideos'], (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result.watchLaterVideos || []);
}
});
});
}
// weighted random function
function getWeightedRandomVideo(videos) {
if (!videos || videos.length === 0) return null;
// Calculate weights (newer videos get higher weights)
const weights = videos.map((_, index) => {
return Math.exp(index / videos.length * 2);
});
const totalWeight = weights.reduce((sum, w) => sum + w, 0);
let random = Math.random() * totalWeight;
for (let i = 0; i < weights.length; i++) {
random -= weights[i];
if (random <= 0) {
return videos[i];
}
}
return videos[videos.length - 1];
}