first commit

This commit is contained in:
CN-JS-HuiBai
2026-04-02 16:43:22 +08:00
commit ac01354b59
7 changed files with 717 additions and 0 deletions

146
public/js/main.js Normal file
View File

@@ -0,0 +1,146 @@
document.addEventListener('DOMContentLoaded', () => {
const videoListEl = document.getElementById('video-list');
const loadingSpinner = document.getElementById('loading-spinner');
const refreshBtn = document.getElementById('refresh-btn');
const playerOverlay = document.getElementById('player-overlay');
const transcodingOverlay = document.getElementById('transcoding-overlay');
const videoPlayer = document.getElementById('video-player');
const nowPlaying = document.getElementById('now-playing');
const currentVideoTitle = document.getElementById('current-video-title');
let currentPollInterval = null;
// Fetch list of videos from the backend
const fetchVideos = async () => {
videoListEl.classList.add('hidden');
loadingSpinner.classList.remove('hidden');
videoListEl.innerHTML = '';
try {
const res = await fetch('/api/videos');
if (!res.ok) throw new Error('Failed to fetch videos. Check S3 Config.');
const data = await res.json();
loadingSpinner.classList.add('hidden');
videoListEl.classList.remove('hidden');
if (data.videos.length === 0) {
videoListEl.innerHTML = '<p style="color: var(--text-secondary); text-align: center; padding: 2rem;">No MP4 videos found in the S3 bucket.</p>';
return;
}
data.videos.forEach(key => {
const li = document.createElement('li');
li.className = 'video-item';
li.innerHTML = `
<div class="video-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 8-6 4 6 4V8Z"/><rect width="14" height="12" x="2" y="6" rx="2" ry="2"/></svg>
</div>
<div class="video-info">
<div class="video-title" title="${key}">${key.split('/').pop()}</div>
<div class="video-meta">H264 / AAC</div>
</div>
`;
li.addEventListener('click', () => selectVideo(key, li));
videoListEl.appendChild(li);
});
} catch (err) {
console.error(err);
loadingSpinner.innerHTML = `<p style="color: #ef4444;">Error: ${err.message}</p>`;
}
};
// Handle video selection and trigger transcode
const selectVideo = async (key, listItemNode) => {
// Update UI
document.querySelectorAll('.video-item').forEach(n => n.classList.remove('active'));
listItemNode.classList.add('active');
// Reset player UI
stopPolling();
playerOverlay.classList.add('hidden');
videoPlayer.classList.add('hidden');
videoPlayer.pause();
nowPlaying.classList.remove('hidden');
currentVideoTitle.textContent = key.split('/').pop();
transcodingOverlay.classList.remove('hidden');
try {
const res = await fetch('/api/transcode', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
// Wait/Poll for HLS playlist to be ready
pollForHlsReady(key, data.hlsUrl);
} catch (err) {
console.error(err);
transcodingOverlay.innerHTML = `<p style="color: #ef4444;">Transcode Failed: ${err.message}</p>`;
}
};
// Poll the backend to check if the generated m3u8 file is accessible
const pollForHlsReady = (key, hlsUrl) => {
let attempts = 0;
const maxAttempts = 60; // 60 seconds max wait for first segment
currentPollInterval = setInterval(async () => {
attempts++;
try {
const res = await fetch(`/api/status?key=${encodeURIComponent(key)}`);
const data = await res.json();
if (data.ready) {
stopPolling();
playHlsStream(data.hlsUrl);
} else if (attempts >= maxAttempts) {
stopPolling();
transcodingOverlay.innerHTML = `<p style="color: #ef4444;">Timeout waiting for HLS segments.</p>`;
}
} catch (err) {
console.error("Poll Error:", err);
}
}, 1000);
};
const stopPolling = () => {
if (currentPollInterval) {
clearInterval(currentPollInterval);
currentPollInterval = null;
}
};
// Initialize HLS Player
const playHlsStream = (url) => {
transcodingOverlay.classList.add('hidden');
videoPlayer.classList.remove('hidden');
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(url);
hls.attachMedia(videoPlayer);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
videoPlayer.play().catch(e => console.log('Auto-play blocked'));
});
} else if (videoPlayer.canPlayType('application/vnd.apple.mpegurl')) {
// Safari uses native HLS
videoPlayer.src = url;
videoPlayer.addEventListener('loadedmetadata', () => {
videoPlayer.play().catch(e => console.log('Auto-play blocked'));
});
}
};
// Bind events
refreshBtn.addEventListener('click', fetchVideos);
// Initial load
fetchVideos();
});