Files
ytdlp-site/static/script/save-media-progress.js
2025-05-01 05:56:04 -06:00

100 lines
2.9 KiB
JavaScript

// Get all video and audio elements
const mediaElements = document.querySelectorAll('video, audio');
// Get the video ID from the hidden input
const videoId = document.getElementById('video-id').value;
// Get the initial timestamp from the hidden input
const initialTimestamp = parseFloat(document.getElementById('video-timestamp').value || 0);
// Track which media element is currently playing
let activeMedia = null;
let updateTimer = null;
const UPDATE_INTERVAL = 5000; // 5 seconds in milliseconds
// Function to send the current time to the server
function sendTimestampToServer(timestamp) {
console.log(videoId, "->", timestamp)
fetch(`/video/${videoId}/set_timestamp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "timestamp": timestamp })
}).catch(error => {
console.error('Error sending timestamp to server:', error);
});
}
// Function to start the update timer
function startUpdateTimer() {
// Clear any existing timer
stopUpdateTimer();
// Start a new timer that sends updates every 5 seconds
updateTimer = setInterval(() => {
if (activeMedia && !activeMedia.paused) {
sendTimestampToServer(activeMedia.currentTime);
}
}, UPDATE_INTERVAL);
}
// Function to stop the update timer
function stopUpdateTimer() {
if (updateTimer) {
clearInterval(updateTimer);
updateTimer = null;
}
}
// Set up event listeners for each media element
mediaElements.forEach(media => {
// Set initial timestamp when media is ready
media.addEventListener('loadedmetadata', () => {
// Only set if the initial timestamp is within the media duration
if (initialTimestamp > 0 && initialTimestamp < media.duration) {
media.currentTime = initialTimestamp;
}
});
// When media starts playing
media.addEventListener('play', () => {
// Set this as the active media
activeMedia = media;
// Start the update timer
startUpdateTimer();
});
// When media is paused
media.addEventListener('pause', () => {
// Send the current timestamp
sendTimestampToServer(media.currentTime);
// If this is the active media, stop the timer
if (activeMedia === media) {
stopUpdateTimer();
activeMedia = null;
}
});
// Reset timestamp when media ends
media.addEventListener('ended', () => {
sendTimestampToServer(0);
// If this is the active media, stop the timer
if (activeMedia === media) {
stopUpdateTimer();
activeMedia = null;
}
});
});
// Clean up when the page is unloaded
window.addEventListener('beforeunload', () => {
// Send final timestamp if media is playing
if (activeMedia && !activeMedia.paused) {
sendTimestampToServer(activeMedia.currentTime);
}
stopUpdateTimer();
});