Code simplification, move to wizard style UI, JSON file cache (scans every 15 mins)
This commit is contained in:
parent
75a7c9a13b
commit
92362efd47
11 changed files with 1027 additions and 438 deletions
|
|
@ -118,8 +118,55 @@ h1 {
|
|||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.wizard-panel {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.wizard-step {
|
||||
font-family: 'Orbitron', sans-serif;
|
||||
font-size: 0.8rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--accent-primary);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.wizard-section {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.wizard-toolbar {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.wizard-toolbar .btn {
|
||||
padding: 0.55rem 0.4rem;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.wizard-library {
|
||||
font-family: 'Orbitron', sans-serif;
|
||||
font-size: 0.78rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.wizard-path {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
font-size: 0.82rem;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.tab-btn {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-color);
|
||||
|
|
@ -222,6 +269,10 @@ h1 {
|
|||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.file-item.folder-entry {
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
.file-item:hover {
|
||||
border-color: var(--accent-primary);
|
||||
background: var(--bg-tertiary);
|
||||
|
|
|
|||
786
assets/js/app.js
786
assets/js/app.js
|
|
@ -1,32 +1,81 @@
|
|||
function showLogin(message = '') {
|
||||
document.getElementById('loginOverlay').style.display = 'flex';
|
||||
document.getElementById('logoutBtn').style.display = 'none';
|
||||
// Freax Media Player - Wizard Frontend
|
||||
|
||||
const err = document.getElementById('loginError');
|
||||
if (message) {
|
||||
err.textContent = message;
|
||||
err.style.display = 'block';
|
||||
} else {
|
||||
err.textContent = '';
|
||||
err.style.display = 'none';
|
||||
const VIDEO_EXTENSIONS = ['mp4', 'mkv', 'avi', 'mov', 'wmv', 'flv', 'webm', 'm4v'];
|
||||
const LIBRARY_LABELS = { videos: 'Videos', music: 'Music' };
|
||||
|
||||
const state = {
|
||||
step: 1,
|
||||
currentType: null,
|
||||
filesByType: { videos: null, music: null },
|
||||
currentNode: null,
|
||||
currentPathParts: [],
|
||||
selectedFilePath: null
|
||||
};
|
||||
|
||||
const mediaDebugEnabled = (() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get('debug') === '1') return true;
|
||||
try {
|
||||
return window.localStorage.getItem('MEDIA_DEBUG') === '1';
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
function logMediaDebug(details) {
|
||||
if (!mediaDebugEnabled) return;
|
||||
|
||||
const {
|
||||
type,
|
||||
source,
|
||||
url,
|
||||
status,
|
||||
cacheStatus,
|
||||
backendMs,
|
||||
frontendFetchMs,
|
||||
frontendParseMs,
|
||||
renderMs,
|
||||
payloadBytes,
|
||||
forceRefresh,
|
||||
cacheGeneratedAt,
|
||||
error
|
||||
} = details;
|
||||
|
||||
console.groupCollapsed(`[media-debug] ${type}`);
|
||||
if (source) console.log('source:', source);
|
||||
if (url) console.log('url:', url);
|
||||
if (typeof status !== 'undefined') console.log('status:', status);
|
||||
if (cacheStatus) console.log('cache:', cacheStatus);
|
||||
if (backendMs) console.log('backend_ms:', backendMs);
|
||||
if (typeof frontendFetchMs === 'number') console.log('frontend_fetch_ms:', Math.round(frontendFetchMs));
|
||||
if (typeof frontendParseMs === 'number') console.log('frontend_parse_ms:', Math.round(frontendParseMs));
|
||||
if (typeof renderMs === 'number') console.log('render_ms:', Math.round(renderMs));
|
||||
if (typeof payloadBytes === 'number') console.log('payload_bytes:', payloadBytes);
|
||||
if (forceRefresh) console.log('force_refresh:', forceRefresh);
|
||||
if (cacheGeneratedAt) console.log('cache_generated_at:', cacheGeneratedAt);
|
||||
if (error) console.log('error:', error);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
function showLogin(message = '') {
|
||||
$('loginOverlay').style.display = 'flex';
|
||||
$('logoutBtn').style.display = 'none';
|
||||
$('loginError').textContent = message;
|
||||
$('loginError').style.display = message ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function hideLogin() {
|
||||
document.getElementById('loginOverlay').style.display = 'none';
|
||||
document.getElementById('loginError').style.display = 'none';
|
||||
document.getElementById('logoutBtn').style.display = 'inline-block';
|
||||
$('loginOverlay').style.display = 'none';
|
||||
$('loginError').style.display = 'none';
|
||||
$('logoutBtn').style.display = 'inline-block';
|
||||
}
|
||||
|
||||
async function authedFetch(url, options = {}) {
|
||||
// Ensure cookies (session) are sent
|
||||
const resp = await fetch(url, {
|
||||
...options,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const resp = await fetch(url, { ...options, credentials: 'same-origin' });
|
||||
|
||||
if (resp.status === 401) {
|
||||
// Session missing/expired
|
||||
showLogin('Please log in to continue.');
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
|
@ -34,39 +83,20 @@ async function authedFetch(url, options = {}) {
|
|||
return resp;
|
||||
}
|
||||
|
||||
const state = {
|
||||
currentType: 'videos',
|
||||
currentFile: null,
|
||||
filesData: null,
|
||||
currentItemEl: null
|
||||
};
|
||||
|
||||
// Initialize
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
setupTabListeners();
|
||||
setupLoginHandlers();
|
||||
|
||||
// Try loading files; if 401, overlay will appear.
|
||||
loadFiles('videos');
|
||||
setupWizardListeners();
|
||||
initApp();
|
||||
});
|
||||
|
||||
function setupLoginHandlers() {
|
||||
const form = document.getElementById('loginForm');
|
||||
const spinner = document.getElementById('loginSpinner');
|
||||
const err = document.getElementById('loginError');
|
||||
const logoutBtn = document.getElementById('logoutBtn');
|
||||
|
||||
// Show overlay until proven authed
|
||||
showLogin('');
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
$('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
err.style.display = 'none';
|
||||
spinner.style.display = 'inline-block';
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const username = $('username').value.trim();
|
||||
const password = $('password').value;
|
||||
$('loginError').style.display = 'none';
|
||||
$('loginSpinner').style.display = 'inline-block';
|
||||
|
||||
try {
|
||||
const resp = await fetch('login.php', {
|
||||
|
|
@ -77,352 +107,458 @@ function setupLoginHandlers() {
|
|||
});
|
||||
|
||||
const data = await resp.json().catch(() => ({}));
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(data.error || `Login failed (${resp.status})`);
|
||||
throw new Error(data.error || 'Login failed');
|
||||
}
|
||||
|
||||
hideLogin();
|
||||
|
||||
// Reload file browser after login
|
||||
loadFiles(state.currentType);
|
||||
initApp();
|
||||
} catch (ex) {
|
||||
err.textContent = ex.message || 'Login failed';
|
||||
err.style.display = 'block';
|
||||
$('loginError').textContent = ex.message || 'Login failed';
|
||||
$('loginError').style.display = 'block';
|
||||
} finally {
|
||||
spinner.style.display = 'none';
|
||||
$('loginSpinner').style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
logoutBtn.addEventListener('click', async () => {
|
||||
$('logoutBtn').addEventListener('click', async () => {
|
||||
try {
|
||||
await fetch('logout.php', { method: 'POST', credentials: 'same-origin' });
|
||||
} catch (_) {
|
||||
// ignore
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
state.step = 1;
|
||||
state.currentType = null;
|
||||
state.currentNode = null;
|
||||
state.currentPathParts = [];
|
||||
state.selectedFilePath = null;
|
||||
state.filesByType = { videos: null, music: null };
|
||||
updateWizardStep();
|
||||
showLibraryPicker();
|
||||
$('fileBrowser').innerHTML = '<p style="color: var(--text-secondary); padding: 1rem;">Choose a library to browse files.</p>';
|
||||
|
||||
showLogin('Logged out.');
|
||||
// Clear UI
|
||||
document.getElementById('fileBrowser').innerHTML = '';
|
||||
document.getElementById('playerContainer').innerHTML = `
|
||||
$('playerContainer').innerHTML = `
|
||||
<div class="player-placeholder">
|
||||
<div class="player-placeholder-icon">🎵</div>
|
||||
<p>Select a file to start playing</p>
|
||||
</div>
|
||||
`;
|
||||
document.getElementById('nowPlaying').style.display = 'none';
|
||||
$('nowPlaying').style.display = 'none';
|
||||
resetAudioTrackUI();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function setupTabListeners() {
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
||||
function setupWizardListeners() {
|
||||
document.querySelectorAll('[data-library]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const type = btn.dataset.type;
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
state.currentType = type;
|
||||
loadFiles(type);
|
||||
selectLibrary(btn.dataset.library).catch(() => {});
|
||||
});
|
||||
});
|
||||
|
||||
$('backBtn').addEventListener('click', () => {
|
||||
if (state.currentPathParts.length === 0) {
|
||||
showLibraryPicker();
|
||||
return;
|
||||
}
|
||||
|
||||
state.currentPathParts.pop();
|
||||
state.currentNode = getNodeAtPath(state.currentType, state.currentPathParts);
|
||||
renderCurrentDirectory();
|
||||
});
|
||||
|
||||
$('rootBtn').addEventListener('click', () => {
|
||||
if (!state.currentType) return;
|
||||
goToLibraryRoot();
|
||||
});
|
||||
|
||||
$('refreshBtn').addEventListener('click', () => {
|
||||
if (!state.currentType) return;
|
||||
selectLibrary(state.currentType, { forceRefresh: true }).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function loadFiles(type) {
|
||||
const browser = document.getElementById('fileBrowser');
|
||||
function initApp() {
|
||||
updateWizardStep();
|
||||
showLibraryPicker();
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const playPath = urlParams.get('play');
|
||||
if (!playPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ext = playPath.toLowerCase().split('.').pop();
|
||||
const type = VIDEO_EXTENSIONS.includes(ext) ? 'videos' : 'music';
|
||||
|
||||
selectLibrary(type).then(() => {
|
||||
navigateToFile(playPath);
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
async function selectLibrary(type, options = {}) {
|
||||
const { forceRefresh = false } = options;
|
||||
if (!LIBRARY_LABELS[type]) return;
|
||||
|
||||
setLibraryButtonActive(type);
|
||||
showBrowserStep();
|
||||
|
||||
const loaded = await ensureLibraryData(type, forceRefresh);
|
||||
if (!loaded) return;
|
||||
|
||||
state.currentType = type;
|
||||
goToLibraryRoot();
|
||||
}
|
||||
|
||||
function goToLibraryRoot() {
|
||||
state.currentPathParts = [];
|
||||
state.currentNode = getNodeAtPath(state.currentType, state.currentPathParts);
|
||||
renderCurrentDirectory();
|
||||
}
|
||||
|
||||
async function ensureLibraryData(type, forceRefresh = false) {
|
||||
if (!forceRefresh && state.filesByType[type] !== null) {
|
||||
logMediaDebug({ type, source: 'memory' });
|
||||
hideLogin();
|
||||
return true;
|
||||
}
|
||||
|
||||
const browser = $('fileBrowser');
|
||||
browser.innerHTML = '<div class="loading"></div>';
|
||||
|
||||
const url = `get_files.php?type=${encodeURIComponent(type)}${forceRefresh ? '&refresh=1' : ''}`;
|
||||
const startedAt = performance.now();
|
||||
|
||||
try {
|
||||
const response = await authedFetch(`get_files.php?type=${type}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
const text = await response.text();
|
||||
console.error('Non-JSON response:', text);
|
||||
throw new Error('Server returned non-JSON response');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Loaded files:', data);
|
||||
|
||||
const resp = await authedFetch(url);
|
||||
const fetchedAt = performance.now();
|
||||
|
||||
const debugHeaders = {
|
||||
cacheStatus: resp.headers.get('X-Media-Cache'),
|
||||
backendMs: resp.headers.get('X-Media-Time-Ms'),
|
||||
forceRefresh: resp.headers.get('X-Media-Force-Refresh'),
|
||||
cacheGeneratedAt: resp.headers.get('X-Media-Cache-Generated-At')
|
||||
};
|
||||
|
||||
const data = await resp.json();
|
||||
const parsedAt = performance.now();
|
||||
|
||||
if (data.error) {
|
||||
browser.innerHTML = `<p style="color: #ff6b6b; padding: 1rem;">${data.error}</p>`;
|
||||
return;
|
||||
logMediaDebug({
|
||||
type,
|
||||
source: 'network',
|
||||
url,
|
||||
status: resp.status,
|
||||
cacheStatus: debugHeaders.cacheStatus,
|
||||
backendMs: debugHeaders.backendMs,
|
||||
frontendFetchMs: fetchedAt - startedAt,
|
||||
frontendParseMs: parsedAt - fetchedAt,
|
||||
forceRefresh: debugHeaders.forceRefresh,
|
||||
cacheGeneratedAt: debugHeaders.cacheGeneratedAt,
|
||||
error: data.error
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (data.message) {
|
||||
browser.innerHTML = `<p style="color: var(--text-secondary); padding: 1rem;">${data.message}</p>`;
|
||||
return;
|
||||
|
||||
const normalizedTree = data.message ? {} : data;
|
||||
state.filesByType[type] = normalizedTree;
|
||||
hideLogin();
|
||||
|
||||
let payloadBytes = null;
|
||||
try {
|
||||
payloadBytes = JSON.stringify(data).length;
|
||||
} catch (_) {
|
||||
payloadBytes = null;
|
||||
}
|
||||
|
||||
state.filesData = data;
|
||||
renderFileTree(data);
|
||||
|
||||
logMediaDebug({
|
||||
type,
|
||||
source: 'network',
|
||||
url,
|
||||
status: resp.status,
|
||||
cacheStatus: debugHeaders.cacheStatus,
|
||||
backendMs: debugHeaders.backendMs,
|
||||
frontendFetchMs: fetchedAt - startedAt,
|
||||
frontendParseMs: parsedAt - fetchedAt,
|
||||
payloadBytes,
|
||||
forceRefresh: debugHeaders.forceRefresh,
|
||||
cacheGeneratedAt: debugHeaders.cacheGeneratedAt
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error loading files:', error);
|
||||
browser.innerHTML = `<p style="color: #ff6b6b; padding: 1rem;">Error loading files: ${error.message}</p>`;
|
||||
logMediaDebug({
|
||||
type,
|
||||
source: 'network',
|
||||
url,
|
||||
frontendFetchMs: performance.now() - startedAt,
|
||||
error: error.message || String(error)
|
||||
});
|
||||
|
||||
if (error.message !== 'Unauthorized') {
|
||||
browser.innerHTML = '<p style="color: #ff6b6b; padding: 1rem;">Error loading files</p>';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function setActiveFileItem(fileItemEl) {
|
||||
// Clear existing "active" state
|
||||
document.querySelectorAll('.file-item').forEach(f => f.classList.remove('active'));
|
||||
|
||||
// Set new "active"
|
||||
if (fileItemEl) {
|
||||
fileItemEl.classList.add('active');
|
||||
fileItemEl.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}
|
||||
|
||||
state.currentItemEl = fileItemEl || null;
|
||||
function getNodeAtPath(type, pathParts) {
|
||||
let node = state.filesByType[type] || {};
|
||||
for (const part of pathParts) {
|
||||
if (!node || typeof node !== 'object' || Array.isArray(node)) {
|
||||
return {};
|
||||
}
|
||||
const next = node[part];
|
||||
if (!next || typeof next !== 'object' || Array.isArray(next)) {
|
||||
return {};
|
||||
}
|
||||
node = next;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the "next" file-item in UI order, preferring the same folder/div
|
||||
* the current item is in. If there's no next sibling, it walks up the DOM
|
||||
* and continues searching.
|
||||
*/
|
||||
function findNextFileItem(currentEl) {
|
||||
if (!currentEl) return null;
|
||||
function renderCurrentDirectory() {
|
||||
const renderStartedAt = performance.now();
|
||||
const browser = $('fileBrowser');
|
||||
const node = state.currentNode;
|
||||
|
||||
// 1) Prefer "next siblings" within the same container
|
||||
let n = currentEl.nextElementSibling;
|
||||
while (n) {
|
||||
if (n.classList && n.classList.contains('file-item')) return n;
|
||||
n = n.nextElementSibling;
|
||||
}
|
||||
updateWizardStep();
|
||||
updateWizardPath();
|
||||
|
||||
// 2) If none, walk upward and look for the next file-item after the
|
||||
// parent container (e.g., next folder section)
|
||||
let parent = currentEl.parentElement;
|
||||
while (parent) {
|
||||
// Stop at the file browser root
|
||||
if (parent.id === 'fileBrowser') break;
|
||||
browser.innerHTML = '';
|
||||
|
||||
let pNext = parent.nextElementSibling;
|
||||
while (pNext) {
|
||||
// If the next sibling is a file-item, play it
|
||||
if (pNext.classList && pNext.classList.contains('file-item')) return pNext;
|
||||
if (!node || typeof node !== 'object' || Array.isArray(node)) {
|
||||
browser.innerHTML = '<p style="color: var(--text-secondary); padding: 1rem;">No entries found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// If it's a folder, search inside it for the first file-item
|
||||
const inside = pNext.querySelector && pNext.querySelector('.file-item');
|
||||
if (inside) return inside;
|
||||
const entries = Object.entries(node);
|
||||
if (entries.length === 0) {
|
||||
browser.innerHTML = '<p style="color: var(--text-secondary); padding: 1rem;">No media files found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
pNext = pNext.nextElementSibling;
|
||||
}
|
||||
for (const [name, content] of entries) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'file-item';
|
||||
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
if (typeof content === 'object' && !Array.isArray(content)) {
|
||||
item.classList.add('folder-entry');
|
||||
item.innerHTML = `<span class="file-icon">📁</span><span>${name}</span>`;
|
||||
item.addEventListener('click', () => {
|
||||
state.currentPathParts.push(name);
|
||||
state.currentNode = content;
|
||||
renderCurrentDirectory();
|
||||
});
|
||||
} else if (typeof content === 'string') {
|
||||
item.dataset.kind = 'file';
|
||||
item.dataset.path = content;
|
||||
item.dataset.name = name;
|
||||
item.innerHTML = `<span class="file-icon">${state.currentType === 'videos' ? '🎬' : '🎵'}</span><span>${name}</span>`;
|
||||
|
||||
// No next item found
|
||||
return null;
|
||||
if (content === state.selectedFilePath) {
|
||||
item.classList.add('active');
|
||||
}
|
||||
|
||||
item.addEventListener('click', () => {
|
||||
navigateToPlayback(content);
|
||||
});
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
browser.appendChild(item);
|
||||
}
|
||||
|
||||
logMediaDebug({
|
||||
type: state.currentType,
|
||||
source: 'memory',
|
||||
renderMs: performance.now() - renderStartedAt
|
||||
});
|
||||
}
|
||||
|
||||
function navigateToFile(filePath) {
|
||||
if (!state.currentType) return;
|
||||
|
||||
const parts = filePath.split('/').filter(Boolean);
|
||||
const rootName = state.currentType === 'videos' ? 'Videos' : 'Music';
|
||||
if (parts[0] && parts[0].toLowerCase() === rootName.toLowerCase()) {
|
||||
parts.shift();
|
||||
}
|
||||
|
||||
const fileName = parts.pop();
|
||||
if (!fileName) return;
|
||||
|
||||
let node = state.filesByType[state.currentType] || {};
|
||||
const folderParts = [];
|
||||
|
||||
for (const part of parts) {
|
||||
if (!node || typeof node !== 'object' || Array.isArray(node)) {
|
||||
break;
|
||||
}
|
||||
const next = node[part];
|
||||
if (!next || typeof next !== 'object' || Array.isArray(next)) {
|
||||
break;
|
||||
}
|
||||
folderParts.push(part);
|
||||
node = next;
|
||||
}
|
||||
|
||||
state.currentPathParts = folderParts;
|
||||
state.currentNode = node;
|
||||
|
||||
const fileValue = node[fileName];
|
||||
if (typeof fileValue === 'string') {
|
||||
state.selectedFilePath = fileValue;
|
||||
playFile(fileValue, fileName);
|
||||
requestAnimationFrame(() => {
|
||||
renderCurrentDirectory();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
renderCurrentDirectory();
|
||||
}
|
||||
|
||||
function updateWizardStep() {
|
||||
const stepText = {
|
||||
1: 'Step 1 - Choose Library',
|
||||
2: 'Step 2 - Browse',
|
||||
3: 'Step 3 - Play'
|
||||
}[state.step] || 'Step 1 - Choose Library';
|
||||
$('wizardStep').textContent = stepText;
|
||||
}
|
||||
|
||||
function showLibraryPicker() {
|
||||
state.step = 1;
|
||||
updateWizardStep();
|
||||
$('libraryPicker').style.display = 'grid';
|
||||
$('browserStep').style.display = 'none';
|
||||
document.querySelectorAll('[data-library]').forEach(btn => btn.classList.remove('active'));
|
||||
}
|
||||
|
||||
function showBrowserStep() {
|
||||
state.step = 2;
|
||||
updateWizardStep();
|
||||
$('libraryPicker').style.display = 'none';
|
||||
$('browserStep').style.display = 'grid';
|
||||
}
|
||||
|
||||
function updateWizardPath() {
|
||||
if (!state.currentType) return;
|
||||
|
||||
const label = LIBRARY_LABELS[state.currentType] || state.currentType;
|
||||
const path = state.currentPathParts.length ? `/${state.currentPathParts.join('/')}` : '/';
|
||||
|
||||
$('currentLibraryLabel').textContent = label;
|
||||
$('breadcrumb').textContent = path;
|
||||
$('backBtn').disabled = state.currentPathParts.length === 0;
|
||||
$('rootBtn').disabled = state.currentPathParts.length === 0;
|
||||
}
|
||||
|
||||
function setLibraryButtonActive(type) {
|
||||
document.querySelectorAll('[data-library]').forEach(btn => {
|
||||
btn.classList.toggle('active', btn.dataset.library === type);
|
||||
});
|
||||
}
|
||||
|
||||
function navigateToPlayback(path) {
|
||||
const params = new URLSearchParams();
|
||||
params.set('play', path);
|
||||
|
||||
const currentParams = new URLSearchParams(window.location.search);
|
||||
if (currentParams.get('debug') === '1') {
|
||||
params.set('debug', '1');
|
||||
}
|
||||
|
||||
window.location.href = `index.php?${params.toString()}`;
|
||||
}
|
||||
|
||||
function playFile(path, name) {
|
||||
const container = $('playerContainer');
|
||||
const ext = path.toLowerCase().split('.').pop();
|
||||
const isVideo = VIDEO_EXTENSIONS.includes(ext);
|
||||
|
||||
const media = document.createElement(isVideo ? 'video' : 'audio');
|
||||
media.controls = true;
|
||||
media.autoplay = true;
|
||||
media.src = `serve_media.php?file=${encodeURIComponent(path)}`;
|
||||
|
||||
media.addEventListener('error', () => {
|
||||
container.innerHTML = `
|
||||
<div class="player-placeholder">
|
||||
<div class="player-placeholder-icon">⚠️</div>
|
||||
<p style="color: #ff6b6b;">Error playing: ${name}</p>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
media.addEventListener('ended', playNextItem);
|
||||
if (isVideo) {
|
||||
media.addEventListener('loadedmetadata', () => setupAudioTrackSelector(media));
|
||||
}
|
||||
|
||||
container.innerHTML = '';
|
||||
container.appendChild(media);
|
||||
|
||||
$('nowPlayingTitle').textContent = name;
|
||||
$('nowPlaying').style.display = 'block';
|
||||
|
||||
state.step = 3;
|
||||
updateWizardStep();
|
||||
resetAudioTrackUI();
|
||||
}
|
||||
|
||||
function playNextItem() {
|
||||
const next = findNextFileItem(state.currentItemEl);
|
||||
if (!next) {
|
||||
console.log('Reached end of list; no next item.');
|
||||
return;
|
||||
}
|
||||
const files = Array.from($('fileBrowser').querySelectorAll('.file-item[data-kind="file"]'));
|
||||
if (files.length === 0) return;
|
||||
|
||||
// Trigger the same behavior as clicking it
|
||||
next.click();
|
||||
}
|
||||
const currentIdx = files.findIndex(el => el.classList.contains('active'));
|
||||
if (currentIdx < 0) return;
|
||||
|
||||
|
||||
function renderFileTree(files, container = document.getElementById('fileBrowser'), depth = 0) {
|
||||
if (depth === 0) {
|
||||
container.innerHTML = '';
|
||||
}
|
||||
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
if (typeof content === 'object' && !Array.isArray(content)) {
|
||||
// It's a folder
|
||||
const folder = document.createElement('div');
|
||||
folder.className = 'folder';
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.className = 'folder-header';
|
||||
header.innerHTML = `<span class="folder-icon">▶</span><span>${name}</span>`;
|
||||
|
||||
const folderContent = document.createElement('div');
|
||||
folderContent.className = 'folder-content';
|
||||
|
||||
header.addEventListener('click', () => {
|
||||
folder.classList.toggle('open');
|
||||
});
|
||||
|
||||
folder.appendChild(header);
|
||||
folder.appendChild(folderContent);
|
||||
container.appendChild(folder);
|
||||
|
||||
renderFileTree(content, folderContent, depth + 1);
|
||||
} else if (typeof content === 'string') {
|
||||
// It's a file
|
||||
const fileItem = document.createElement('div');
|
||||
fileItem.className = 'file-item';
|
||||
|
||||
const icon = state.currentType === 'videos' ? '🎬' : '🎵';
|
||||
fileItem.innerHTML = `<span class="file-icon">${icon}</span><span>${name}</span>`;
|
||||
|
||||
fileItem.dataset.path = content;
|
||||
fileItem.dataset.name = name;
|
||||
|
||||
fileItem.addEventListener('click', () => {
|
||||
// Play and mark active
|
||||
playFile(content, name, fileItem);
|
||||
setActiveFileItem(fileItem);
|
||||
});
|
||||
|
||||
|
||||
container.appendChild(fileItem);
|
||||
}
|
||||
const next = files[currentIdx + 1];
|
||||
if (next) {
|
||||
next.click();
|
||||
}
|
||||
}
|
||||
|
||||
function resetAudioTrackUI() {
|
||||
const audioControls = document.getElementById('audioControls');
|
||||
const audioSelect = document.getElementById('audioSelect');
|
||||
const audioHint = document.getElementById('audioHint');
|
||||
|
||||
audioControls.style.display = 'none';
|
||||
audioHint.style.display = 'none';
|
||||
audioHint.textContent = '';
|
||||
audioSelect.innerHTML = '';
|
||||
$('audioControls').style.display = 'none';
|
||||
$('audioHint').style.display = 'none';
|
||||
$('audioHint').textContent = '';
|
||||
$('audioSelect').innerHTML = '';
|
||||
}
|
||||
|
||||
function setupAudioTrackSelector(videoEl) {
|
||||
const audioControls = document.getElementById('audioControls');
|
||||
const audioSelect = document.getElementById('audioSelect');
|
||||
const audioHint = document.getElementById('audioHint');
|
||||
|
||||
// Not all browsers expose audioTracks (and MKV often won't)
|
||||
const tracks = videoEl.audioTracks;
|
||||
|
||||
if (!tracks) {
|
||||
audioControls.style.display = 'none';
|
||||
audioHint.style.display = 'block';
|
||||
audioHint.textContent = 'Audio track switching not supported for this file/browser, open in VLC to change audio track if needed.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (tracks.length <= 1) {
|
||||
audioControls.style.display = 'none';
|
||||
audioHint.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Build dropdown
|
||||
audioSelect.innerHTML = '';
|
||||
for (let i = 0; i < tracks.length; i++) {
|
||||
const t = tracks[i];
|
||||
const opt = document.createElement('option');
|
||||
opt.value = String(i);
|
||||
|
||||
// label is often empty; language may exist depending on browser/container
|
||||
const label = (t.label && t.label.trim()) ? t.label.trim() : null;
|
||||
const lang = (t.language && t.language.trim()) ? t.language.trim() : null;
|
||||
|
||||
opt.textContent = label || (lang ? `Track ${i + 1} (${lang})` : `Track ${i + 1}`);
|
||||
audioSelect.appendChild(opt);
|
||||
|
||||
// Set currently enabled track as selected
|
||||
if (t.enabled) {
|
||||
audioSelect.value = String(i);
|
||||
if (!tracks || tracks.length <= 1) {
|
||||
if (!tracks) {
|
||||
$('audioHint').textContent = 'Audio track switching not supported for this browser.';
|
||||
$('audioHint').style.display = 'block';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
audioSelect.onchange = () => {
|
||||
const idx = parseInt(audioSelect.value, 10);
|
||||
$('audioSelect').innerHTML = '';
|
||||
for (let i = 0; i < tracks.length; i++) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = i;
|
||||
const label = tracks[i].label?.trim() || `Track ${i + 1}`;
|
||||
opt.textContent = label;
|
||||
$('audioSelect').appendChild(opt);
|
||||
|
||||
if (tracks[i].enabled) opt.selected = true;
|
||||
}
|
||||
|
||||
$('audioSelect').onchange = () => {
|
||||
const idx = parseInt($('audioSelect').value, 10);
|
||||
for (let i = 0; i < tracks.length; i++) {
|
||||
tracks[i].enabled = (i === idx);
|
||||
}
|
||||
};
|
||||
|
||||
audioHint.style.display = 'none';
|
||||
audioControls.style.display = 'flex';
|
||||
$('audioHint').style.display = 'none';
|
||||
$('audioControls').style.display = 'flex';
|
||||
}
|
||||
|
||||
|
||||
function playFile(path, name, sourceItemEl = null) {
|
||||
const playerContainer = document.getElementById('playerContainer');
|
||||
const nowPlaying = document.getElementById('nowPlaying');
|
||||
const nowPlayingTitle = document.getElementById('nowPlayingTitle');
|
||||
|
||||
state.currentFile = { path, name };
|
||||
resetAudioTrackUI();
|
||||
|
||||
|
||||
const isVideo = state.currentType === 'videos';
|
||||
const mediaElement = document.createElement(isVideo ? 'video' : 'audio');
|
||||
|
||||
mediaElement.controls = true;
|
||||
mediaElement.autoplay = true;
|
||||
|
||||
// Keep track of which UI element launched playback (used for "next")
|
||||
if (sourceItemEl) {
|
||||
state.currentItemEl = sourceItemEl;
|
||||
}
|
||||
|
||||
if (isVideo) {
|
||||
// Some browsers only populate audioTracks after metadata is available
|
||||
mediaElement.addEventListener('loadedmetadata', () => {
|
||||
setupAudioTrackSelector(mediaElement);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Add error handling
|
||||
mediaElement.addEventListener('error', (e) => {
|
||||
console.error('Media playback error:', {
|
||||
error: mediaElement.error,
|
||||
code: mediaElement.error?.code,
|
||||
message: mediaElement.error?.message,
|
||||
path: path,
|
||||
name: name
|
||||
});
|
||||
|
||||
playerContainer.innerHTML = `
|
||||
<div class="player-placeholder">
|
||||
<div class="player-placeholder-icon">⚠️</div>
|
||||
<p style="color: #ff6b6b;">Error playing: ${name}</p>
|
||||
<p style="color: var(--text-secondary); font-size: 0.8rem; margin-top: 0.5rem;">
|
||||
${mediaElement.error?.message || 'Unknown error'}
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
// Add loading state
|
||||
mediaElement.addEventListener('loadstart', () => {
|
||||
console.log('Loading media:', name);
|
||||
});
|
||||
|
||||
mediaElement.addEventListener('canplay', () => {
|
||||
console.log('Media ready to play:', name);
|
||||
});
|
||||
|
||||
mediaElement.addEventListener('ended', () => {
|
||||
// Auto-advance to next item when current finishes
|
||||
playNextItem();
|
||||
});
|
||||
|
||||
|
||||
// URL encode the path properly
|
||||
const encodedPath = encodeURIComponent(path);
|
||||
mediaElement.src = `serve_media.php?file=${encodedPath}`;
|
||||
|
||||
console.log('Playing file:', {
|
||||
name: name,
|
||||
path: path,
|
||||
encodedPath: encodedPath,
|
||||
fullUrl: `serve_media.php?file=${encodedPath}`
|
||||
});
|
||||
|
||||
playerContainer.innerHTML = '';
|
||||
playerContainer.appendChild(mediaElement);
|
||||
|
||||
nowPlayingTitle.textContent = name;
|
||||
nowPlaying.style.display = 'block';
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue