// 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 the last time we sent an update to avoid excessive requests let lastUpdateTime = 0; const UPDATE_INTERVAL = 5000; // 5 seconds in milliseconds // Function to send the current time to the server function sendTimestampToServer(timestamp) { console.log(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 handle periodic updates while playing function handleTimeUpdate(media) { // Only send updates every 5 seconds while playing const now = Date.now(); if (!media.paused && now - lastUpdateTime >= UPDATE_INTERVAL) { sendTimestampToServer(media.currentTime); lastUpdateTime = now; } } // 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; } }); // Send updates periodically while playing media.addEventListener('timeupdate', () => handleTimeUpdate(media)); // Send update when media is paused media.addEventListener('pause', () => { sendTimestampToServer(media.currentTime); }); // Reset timestamp when media ends media.addEventListener('ended', () => { sendTimestampToServer(0); }); });