-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
360 lines (302 loc) · 11.1 KB
/
Copy pathpopup.js
File metadata and controls
360 lines (302 loc) · 11.1 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
const fileInput = document.getElementById("srtFile");
const urlInput = document.getElementById("videoUrl");
const status = document.getElementById("status");
const uploadBtn = document.getElementById("uploadBtn");
const toggleSubsCheckbox = document.getElementById("toggleSubsCheckbox");
const viewSubsBtn = document.getElementById("viewSubsBtn");
const subsModal = document.getElementById("subsModal");
const closeModal = document.querySelector(".close");
const videoList = document.getElementById("videoList");
const fontLabel = document.getElementById("fontSizeLabel");
const fontSizeSlider = document.getElementById("fontSizeSlider");
const shadowToggle = document.getElementById("shadowToggle");
const shadowSettings = document.getElementById("shadowSettings");
const shadowOpacity = document.getElementById("shadowOpacity");
const shadowOpacityLabel = document.getElementById("shadowOpacityLabel");
const bgToggle = document.getElementById("bgToggle");
const bgSettings = document.getElementById("bgSettings");
const bgOpacity = document.getElementById("bgOpacity");
const bgOpacityLabel = document.getElementById("bgOpacityLabel");
let settings = { fontSize: 1.3, shadow: true, opacity: 80, background: true, bgOpacity: 60, enabled: true };
// Extract Video ID from various sources
function extractVideoId(input) {
if (!input) return null;
// Try to extract from URL
try {
const url = new URL(input);
if (url.searchParams.has("v")) {
return url.searchParams.get("v");
}
// Check for youtu.be short links
if (url.hostname === "youtu.be") {
return url.pathname.slice(1).split("?")[0];
}
} catch {}
// Try regex pattern for video ID in URL
const urlPattern = /(?:v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
const urlMatch = input.match(urlPattern);
if (urlMatch) return urlMatch[1];
// Try to extract from filename (if it looks like a video ID)
const filenamePattern = /([a-zA-Z0-9_-]{11})/;
const filenameMatch = input.match(filenamePattern);
if (filenameMatch) return filenameMatch[1];
return null;
}
// Upload Subtitle
uploadBtn.addEventListener("click", async () => {
if (!fileInput.files.length) {
showStatus("Please select an SRT file.", "error");
return;
}
const file = fileInput.files[0];
const text = await file.text();
let videoId = "";
const url = urlInput.value.trim();
// Priority 1: Manual URL input (if provided and valid)
if (url) {
videoId = extractVideoId(url);
if (!videoId) {
showStatus("Invalid YouTube URL. Trying filename...", "error");
}
}
// Priority 2: Extract from filename
if (!videoId) {
const filename = file.name.replace(".srt", "");
videoId = extractVideoId(filename);
}
// Priority 3: Get from current active tab
if (!videoId) {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab.url.includes("youtube.com/watch") || tab.url.includes("youtu.be")) {
videoId = extractVideoId(tab.url);
}
} catch (e) {
console.log("Could not access current tab");
}
}
if (!videoId) {
showStatus("Unable to detect video ID. Please enter the YouTube link or name the file with video ID.", "error");
return;
}
// Try to get video title
let videoTitle = "";
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab && (tab.url.includes("youtube.com/watch") || tab.url.includes("youtu.be"))) {
// Extract title from YouTube page title (format: "Video Title - YouTube")
videoTitle = tab.title.replace(" - YouTube", "").trim();
}
} catch (e) {
console.log("Could not get video title from tab");
}
// If no title from tab, try to fetch from YouTube oEmbed API
if (!videoTitle) {
try {
const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);
if (response.ok) {
const data = await response.json();
videoTitle = data.title;
}
} catch (e) {
console.log("Could not fetch video title from API");
}
}
// Fallback to video ID if no title found
if (!videoTitle) {
videoTitle = videoId;
}
// Store subtitle with video ID and metadata
const subsData = await chrome.storage.local.get("subtitlesList") || {};
const subtitlesList = subsData.subtitlesList || {};
subtitlesList[videoId] = {
text: text,
filename: file.name,
title: videoTitle,
date: new Date().toISOString()
};
await chrome.storage.local.set({
[videoId]: text,
subtitlesList: subtitlesList
});
showStatus(`✅ Subtitle saved successfully!<br><a href="https://www.youtube.com/watch?v=${videoId}" target="_blank">Open video</a>`, "success");
// Clear inputs
fileInput.value = "";
urlInput.value = "";
});
// Toggle Subtitles Enable/Disable
toggleSubsCheckbox.addEventListener("change", () => {
settings.enabled = toggleSubsCheckbox.checked;
saveSettings();
// Notify content script
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: "toggleSubtitles",
enabled: settings.enabled
}).catch(() => {});
}
});
});
// Helper function to fetch video title from YouTube
async function fetchVideoTitle(videoId) {
try {
const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);
if (response.ok) {
const data = await response.json();
return data.title;
}
} catch (e) {
console.log("Could not fetch video title:", e);
}
return null;
}
// View Subtitles List
viewSubsBtn.addEventListener("click", async () => {
const data = await chrome.storage.local.get("subtitlesList");
const subtitlesList = data.subtitlesList || {};
videoList.innerHTML = '<div class="empty-state">Loading...</div>';
const videoIds = Object.keys(subtitlesList);
if (videoIds.length === 0) {
videoList.innerHTML = '<div class="empty-state">No subtitles saved yet</div>';
} else {
videoList.innerHTML = "";
// Fetch titles for all videos
for (const videoId of videoIds) {
const sub = subtitlesList[videoId];
// Try to get title from storage first, if not available fetch from API
let videoTitle = sub.title;
if (!videoTitle || videoTitle === videoId) {
videoTitle = await fetchVideoTitle(videoId);
// Update storage with fetched title
if (videoTitle) {
subtitlesList[videoId].title = videoTitle;
await chrome.storage.local.set({ subtitlesList: subtitlesList });
}
}
const li = document.createElement("li");
li.className = "video-item";
const displayTitle = videoTitle || videoId;
const displayFilename = sub.filename || videoId;
// Format date and time
const dateObj = new Date(sub.date);
const formattedDate = dateObj.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
const formattedTime = dateObj.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: true
});
li.innerHTML = `
<a href="https://www.youtube.com/watch?v=${videoId}" target="_blank">
<strong title="${displayTitle}">${displayTitle}</strong><br>
<small style="color: #777; display: block; margin-top: 3px;">${displayFilename}</small><br>
<small style="color: #999; display: block; margin-top: 2px;">📅 ${formattedDate} • 🕐 ${formattedTime}</small>
</a>
<button class="delete-btn" data-id="${videoId}">🗑️ Delete</button>
`;
videoList.appendChild(li);
}
// Add delete handlers
document.querySelectorAll(".delete-btn").forEach(btn => {
btn.addEventListener("click", async (e) => {
e.preventDefault();
const videoId = btn.getAttribute("data-id");
if (confirm("Are you sure you want to delete this subtitle?")) {
const data = await chrome.storage.local.get("subtitlesList");
const subtitlesList = data.subtitlesList || {};
delete subtitlesList[videoId];
await chrome.storage.local.remove(videoId);
await chrome.storage.local.set({ subtitlesList: subtitlesList });
// Refresh the list
viewSubsBtn.click();
}
});
});
}
subsModal.style.display = "block";
});
// Close Modal
closeModal.addEventListener("click", () => {
subsModal.style.display = "none";
});
window.addEventListener("click", (e) => {
if (e.target === subsModal) {
subsModal.style.display = "none";
}
});
// Helper function to show status messages
function showStatus(message, type = "") {
if (message) {
status.innerHTML = message;
status.className = type;
setTimeout(() => {
status.innerHTML = "";
status.className = "";
}, 5000);
} else {
status.innerHTML = "";
status.className = "";
}
}
// Load Settings
chrome.storage.local.get("subtitleSettings", (res) => {
if (res.subtitleSettings) {
settings = { ...settings, ...res.subtitleSettings };
}
updateUI();
toggleSubsCheckbox.checked = settings.enabled;
});
fontSizeSlider.oninput = () => {
const size = parseInt(fontSizeSlider.value);
settings.fontSize = size / 10; // Convert to vw units
fontLabel.innerText = size + "px";
saveSettings();
};
shadowToggle.onchange = () => {
settings.shadow = shadowToggle.checked;
shadowSettings.style.display = settings.shadow ? "block" : "none";
saveSettings();
};
shadowOpacity.oninput = () => {
settings.opacity = parseInt(shadowOpacity.value);
shadowOpacityLabel.innerText = settings.opacity + "%";
updateSliderProgress(shadowOpacity, settings.opacity);
saveSettings();
};
bgToggle.onchange = () => {
settings.background = bgToggle.checked;
bgSettings.style.display = settings.background ? "block" : "none";
saveSettings();
};
bgOpacity.oninput = () => {
settings.bgOpacity = parseInt(bgOpacity.value);
bgOpacityLabel.innerText = settings.bgOpacity + "%";
updateSliderProgress(bgOpacity, settings.bgOpacity);
saveSettings();
};
function saveSettings() {
chrome.storage.local.set({ subtitleSettings: settings });
}
function updateSliderProgress(slider, value) {
const percentage = value + "%";
slider.style.setProperty('--value', percentage);
}
function updateUI() {
const fontSize = Math.round(settings.fontSize * 10);
fontLabel.innerText = fontSize + "px";
fontSizeSlider.value = fontSize;
shadowToggle.checked = settings.shadow;
shadowSettings.style.display = settings.shadow ? "block" : "none";
shadowOpacity.value = settings.opacity;
shadowOpacityLabel.innerText = settings.opacity + "%";
updateSliderProgress(shadowOpacity, settings.opacity);
bgToggle.checked = settings.background;
bgSettings.style.display = settings.background ? "block" : "none";
bgOpacity.value = settings.bgOpacity;
bgOpacityLabel.innerText = settings.bgOpacity + "%";
updateSliderProgress(bgOpacity, settings.bgOpacity);
}