-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
208 lines (179 loc) · 7.82 KB
/
popup.js
File metadata and controls
208 lines (179 loc) · 7.82 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
const episodeNumberInput = document.getElementById('episodeNumber');
const animeNameInput = document.getElementById('animeName');
const checkButton = document.getElementById('checkButton');
const buttonText = document.getElementById('buttonText');
const loader = document.getElementById('loader');
const resultDiv = document.getElementById('result');
const CACHE_TTL = 1000 * 60 * 60 * 24; // 24 hours in ms
document.addEventListener('DOMContentLoaded', async () => {
// Attempt to load previous state
chrome.storage.local.get(['lastAnime', 'lastEpisode'], (data) => {
if (data.lastAnime) {
animeNameInput.value = data.lastAnime;
}
if (data.lastEpisode) {
// Auto-increment episode number for convenience
episodeNumberInput.value = parseInt(data.lastEpisode, 10) + 1;
}
});
// Auto-detect from active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs && tabs.length > 0) {
const currentTab = tabs[0];
if (currentTab.url && (currentTab.url.includes('crunchyroll.com') || currentTab.url.includes('netflix.com'))) {
const title = currentTab.title;
// Basic heuristic for extracting episode numbers: "Anime Name - Episode 12 - Watch..."
// or "Watch Anime - Ep 12"
const epMatch = title.match(/(?:episode|ep|e)\s*0*(\d+)/i);
if (epMatch && epMatch[1]) {
episodeNumberInput.value = epMatch[1];
}
// For Crunchyroll, title often starts with Anime Name
if (currentTab.url.includes('crunchyroll.com')) {
const parts = title.split('-');
if (parts.length > 1) {
const potentialAnime = parts[0].trim().replace(/Watch\s+/i, '');
if (potentialAnime && !animeNameInput.value) {
animeNameInput.value = potentialAnime;
}
}
}
}
}
});
});
function isEpisodeInRange(episodeNumber, rangeString) {
if (!rangeString) return false;
if (rangeString.includes('-')) {
const [start, end] = rangeString.split('-').map(Number);
if (!isNaN(start) && !isNaN(end)) {
return episodeNumber >= start && episodeNumber <= end;
}
} else {
const singleEpisode = Number(rangeString);
if (!isNaN(singleEpisode)) {
return episodeNumber === singleEpisode;
}
}
return false;
}
function getMainTypeFromClass(className) {
if (!className) return 'unknown';
const lowerClassName = className.toLowerCase();
if (lowerClassName.includes('manga_canon')) return 'canon';
if (lowerClassName.includes('filler')) return 'filler';
if (lowerClassName.includes('mixed_canon/filler')) return 'mixed';
if (lowerClassName.includes('anime_canon')) return 'mixed';
if (lowerClassName.trim() !== '') return 'unknown';
return 'unknown';
}
async function fetchAFLDataCached(animeName) {
const slug = animeName.toLowerCase().trim().replace(/[\s_]+/g, '-').replace(/[^a-z0-9\-]/g, '');
const cacheKey = `afl_cache_${slug}`;
return new Promise((resolve) => {
chrome.storage.local.get([cacheKey], async (result) => {
const cached = result[cacheKey];
const now = Date.now();
if (cached && (now - cached.timestamp < CACHE_TTL)) {
console.log('Using cached data for', slug);
resolve(cached.episodes);
return;
}
console.log('Fetching fresh data for', slug);
const url = `https://www.animefillerlist.com/shows/${slug}`;
try {
const response = await fetch(url, { mode: 'cors' });
if (!response.ok) {
if (response.status === 404) {
resolve({ error: `Anime "${animeName}" not found on Anime Filler List.` });
return;
}
throw new Error(`Network response was not ok! status: ${response.status}`);
}
const htmlText = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const episodeRows = doc.querySelectorAll('.EpisodeList tbody tr');
if (!episodeRows || episodeRows.length === 0) {
resolve({ error: `Could not find episode list for "${animeName}". AFL website layout might have changed.` });
return;
}
const episodesData = [];
for (const row of episodeRows) {
const episodeCell = row.querySelector('td:nth-child(1)');
const typeCell = row.querySelector('td:nth-child(3)');
if (episodeCell) {
episodesData.push({
range: episodeCell.textContent.trim(),
className: row.className.trim(),
typeText: typeCell ? typeCell.textContent.trim() : row.className.trim()
});
}
}
if (episodesData.length > 0) {
const dataToCache = {
timestamp: now,
episodes: episodesData
};
chrome.storage.local.set({ [cacheKey]: dataToCache });
resolve(episodesData);
} else {
resolve({ error: `No valid episodes found for "${animeName}".` });
}
} catch (error) {
console.error("Error fetching or parsing filler data:", error);
resolve({ error: `Failed to fetch data. Check console for details.` });
}
});
});
}
async function fetchAndCheckFiller(animeName, episodeNumber) {
const data = await fetchAFLDataCached(animeName);
if (data.error) {
return { type: "unknown", message: data.error };
}
for (const ep of data) {
if (isEpisodeInRange(episodeNumber, ep.range)) {
const mainType = getMainTypeFromClass(ep.className);
return {
type: mainType,
message: `${animeName} Episode ${episodeNumber}: ${ep.typeText}`
};
}
}
return { type: "unknown", message: `Episode ${episodeNumber} not found in the list for "${animeName}".` };
}
function showLoading() {
buttonText.textContent = 'Checking...';
loader.classList.remove('hidden');
checkButton.disabled = true;
resultDiv.classList.remove('show');
}
function hideLoading() {
buttonText.textContent = 'Check !';
loader.classList.add('hidden');
checkButton.disabled = false;
resultDiv.classList.add('show');
}
checkButton.addEventListener('click', async () => {
const animeName = animeNameInput.value.trim();
const episodeNumberStr = episodeNumberInput.value;
if (!animeName || !episodeNumberStr) {
resultDiv.textContent = 'Please enter both Anime Name and Episode #.';
resultDiv.className = 'result-unknown show';
return;
}
const episodeNumber = parseInt(episodeNumberStr, 10);
if (isNaN(episodeNumber) || episodeNumber < 1) {
resultDiv.textContent = 'Invalid Episode Number.';
resultDiv.className = 'result-unknown show';
return;
}
showLoading();
const result = await fetchAndCheckFiller(animeName, episodeNumber);
resultDiv.textContent = result.message;
resultDiv.className = `show result-${result.type || 'unknown'}`;
// Save successful query
chrome.storage.local.set({ lastAnime: animeName, lastEpisode: episodeNumber });
hideLoading();
});