Files
media-player-server/media_server/static/index.html
alexei.dolgolyov a0af855846 Add callback management API/UI and theme support
- Add callback CRUD endpoints (create, update, delete, list)
- Add callback management UI with all 11 callback events support
- Add light/dark theme switcher with localStorage persistence
- Improve button styling (wider buttons, simplified text)
- Extend ConfigManager with callback operations

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 04:11:57 +03:00

1851 lines
64 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Media Server</title>
<style>
:root {
--bg-primary: #121212;
--bg-secondary: #1e1e1e;
--bg-tertiary: #282828;
--text-primary: #ffffff;
--text-secondary: #b3b3b3;
--text-muted: #6a6a6a;
--accent: #1db954;
--accent-hover: #1ed760;
--border: #404040;
--error: #e74c3c;
}
:root[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--bg-tertiary: #e8e8e8;
--text-primary: #1a1a1a;
--text-secondary: #4a4a4a;
--text-muted: #888888;
--accent: #1db954;
--accent-hover: #1ed760;
--border: #d0d0d0;
--error: #e74c3c;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border);
}
h1 {
font-size: 1.5rem;
font-weight: 600;
}
.status-indicator {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: var(--text-secondary);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--error);
transition: background 0.3s;
}
.status-dot.connected {
background: var(--accent);
}
.theme-toggle {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.5rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s;
width: 40px;
height: 40px;
}
.theme-toggle:hover {
background: var(--border);
}
.theme-toggle svg {
width: 20px;
height: 20px;
fill: var(--text-primary);
}
.player-container {
background: var(--bg-secondary);
border-radius: 12px;
padding: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
.album-art-container {
display: flex;
justify-content: center;
margin-bottom: 2rem;
}
#album-art {
width: 300px;
height: 300px;
object-fit: cover;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
background: var(--bg-tertiary);
}
.track-info {
text-align: center;
margin-bottom: 2rem;
}
#track-title {
font-size: 1.75rem;
font-weight: 600;
margin-bottom: 0.5rem;
color: var(--text-primary);
}
#artist {
font-size: 1.125rem;
color: var(--text-secondary);
margin-bottom: 0.25rem;
}
#album {
font-size: 0.875rem;
color: var(--text-muted);
}
.playback-state {
display: flex;
justify-content: center;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: var(--text-secondary);
margin-top: 0.5rem;
}
.state-icon {
width: 16px;
height: 16px;
}
.progress-container {
margin-bottom: 2rem;
}
.time-display {
display: flex;
justify-content: space-between;
font-size: 0.75rem;
color: var(--text-secondary);
margin-bottom: 0.5rem;
}
.progress-bar {
width: 100%;
height: 6px;
background: var(--bg-tertiary);
border-radius: 3px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: var(--accent);
border-radius: 3px;
width: 0;
transition: width 0.1s linear;
}
.controls {
display: flex;
gap: 1rem;
justify-content: center;
align-items: center;
margin-bottom: 2rem;
}
button {
background: var(--bg-tertiary);
border: none;
color: var(--text-primary);
cursor: pointer;
border-radius: 50%;
width: 48px;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
}
button:hover:not(:disabled) {
background: var(--accent);
transform: scale(1.05);
}
button:disabled {
opacity: 0.3;
cursor: not-allowed;
}
button.primary {
width: 56px;
height: 56px;
background: var(--accent);
}
button.primary:hover:not(:disabled) {
background: var(--accent-hover);
transform: scale(1.1);
}
.volume-container {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem;
background: var(--bg-tertiary);
border-radius: 8px;
margin-bottom: 1rem;
}
#volume-slider {
flex: 1;
height: 6px;
-webkit-appearance: none;
appearance: none;
background: var(--bg-primary);
border-radius: 3px;
outline: none;
}
#volume-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
background: var(--accent);
border-radius: 50%;
cursor: pointer;
}
#volume-slider::-moz-range-thumb {
width: 16px;
height: 16px;
background: var(--accent);
border-radius: 50%;
cursor: pointer;
border: none;
}
.volume-display {
font-size: 0.875rem;
color: var(--text-secondary);
min-width: 40px;
text-align: right;
}
.mute-btn {
width: 40px;
height: 40px;
}
.source-info {
text-align: center;
font-size: 0.75rem;
color: var(--text-muted);
padding-top: 1rem;
border-top: 1px solid var(--border);
}
/* Scripts Section */
.scripts-container {
background: var(--bg-secondary);
border-radius: 12px;
padding: 2rem;
margin-top: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
.scripts-container h2 {
font-size: 1.25rem;
margin-bottom: 1rem;
color: var(--text-primary);
}
.scripts-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 1rem;
}
.script-btn {
width: 100%;
height: auto;
min-height: 80px;
padding: 1rem;
border-radius: 8px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
color: var(--text-primary);
cursor: pointer;
transition: all 0.2s;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
.script-btn:hover:not(:disabled) {
background: var(--accent);
border-color: var(--accent);
transform: translateY(-2px);
}
.script-btn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.script-btn .script-label {
font-weight: 600;
font-size: 0.875rem;
}
.script-btn .script-description {
font-size: 0.75rem;
color: var(--text-secondary);
text-align: center;
}
.script-btn.executing {
opacity: 0.6;
pointer-events: none;
}
/* Script Management Styles */
.script-management {
background: var(--bg-secondary);
border-radius: 12px;
padding: 2rem;
margin-top: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
.script-management h2 {
font-size: 1.25rem;
margin-bottom: 1rem;
color: var(--text-primary);
}
.script-management-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.add-script-btn {
padding: 0.5rem 1.5rem;
border-radius: 6px;
background: var(--accent);
border: none;
color: var(--text-primary);
cursor: pointer;
font-size: 0.875rem;
font-weight: 600;
transition: background 0.2s;
min-width: 140px;
}
.add-script-btn:hover {
background: var(--accent-hover);
}
.scripts-table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
}
.scripts-table th {
text-align: left;
padding: 0.75rem;
border-bottom: 2px solid var(--border);
color: var(--text-secondary);
font-weight: 600;
font-size: 0.75rem;
text-transform: uppercase;
}
.scripts-table td {
padding: 0.75rem;
border-bottom: 1px solid var(--border);
}
.scripts-table tr:hover {
background: var(--bg-tertiary);
}
.scripts-table code {
background: var(--bg-tertiary);
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
color: var(--accent);
}
.action-btn {
padding: 0.25rem 0.75rem;
margin-right: 0.5rem;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--bg-tertiary);
color: var(--text-primary);
cursor: pointer;
font-size: 0.75rem;
transition: all 0.2s;
}
.action-btn:hover {
background: var(--accent);
border-color: var(--accent);
}
.action-btn.delete:hover {
background: var(--error);
border-color: var(--error);
}
/* Dialog Styles */
dialog {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
padding: 0;
max-width: 500px;
width: 90%;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.8);
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.8);
}
.dialog-header {
padding: 1.5rem;
border-bottom: 1px solid var(--border);
}
.dialog-header h3 {
margin: 0;
font-size: 1.25rem;
}
.dialog-body {
padding: 1.5rem;
}
.dialog-body label {
display: block;
margin-bottom: 1rem;
color: var(--text-secondary);
font-size: 0.875rem;
}
.dialog-body input,
.dialog-body textarea,
.dialog-body select {
display: block;
width: 100%;
padding: 0.5rem;
margin-top: 0.25rem;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
font-family: inherit;
font-size: 0.875rem;
}
.dialog-body textarea {
min-height: 80px;
resize: vertical;
}
.dialog-body input:focus,
.dialog-body textarea:focus,
.dialog-body select:focus {
outline: none;
border-color: var(--accent);
}
.dialog-footer {
padding: 1.5rem;
border-top: 1px solid var(--border);
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.dialog-footer button {
padding: 0.5rem 1rem;
border-radius: 6px;
border: none;
font-size: 0.875rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
.dialog-footer .btn-primary {
background: var(--accent);
color: var(--text-primary);
}
.dialog-footer .btn-primary:hover {
background: var(--accent-hover);
}
.dialog-footer .btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border);
}
.dialog-footer .btn-secondary:hover {
background: var(--border);
}
.empty-state {
text-align: center;
padding: 2rem;
color: var(--text-muted);
}
.scripts-empty {
text-align: center;
color: var(--text-muted);
padding: 2rem;
font-size: 0.875rem;
}
.toast {
position: fixed;
bottom: 2rem;
right: 2rem;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1rem 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
opacity: 0;
transform: translateY(20px);
transition: all 0.3s;
pointer-events: none;
z-index: 1000;
}
.toast.show {
opacity: 1;
transform: translateY(0);
}
.toast.success {
border-color: var(--accent);
}
.toast.error {
border-color: var(--error);
}
/* Auth Modal */
#auth-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
#auth-overlay.hidden {
display: none;
}
.auth-modal {
background: var(--bg-secondary);
padding: 2rem;
border-radius: 12px;
max-width: 400px;
width: 90%;
}
.auth-modal h2 {
margin-bottom: 1rem;
font-size: 1.5rem;
}
.auth-modal p {
margin-bottom: 1rem;
color: var(--text-secondary);
font-size: 0.875rem;
}
#token-input {
width: 100%;
padding: 0.75rem;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
font-size: 0.875rem;
margin-bottom: 1rem;
}
#token-input:focus {
outline: none;
border-color: var(--accent);
}
.btn-connect {
width: 100%;
height: auto;
padding: 0.75rem;
border-radius: 6px;
background: var(--accent);
font-weight: 600;
}
.btn-connect:hover {
background: var(--accent-hover);
transform: none;
}
.help-text {
background: var(--bg-tertiary);
padding: 0.75rem;
border-radius: 6px;
margin-top: 1rem;
}
.help-text code {
background: var(--bg-primary);
padding: 0.25rem 0.5rem;
border-radius: 3px;
font-family: monospace;
font-size: 0.875rem;
}
.error-message {
color: var(--error);
font-size: 0.875rem;
margin-top: 0.5rem;
display: none;
}
.error-message.visible {
display: block;
}
.clear-token-btn {
position: fixed;
top: 1rem;
right: 1rem;
width: auto;
height: auto;
padding: 0.5rem 1rem;
border-radius: 6px;
font-size: 0.75rem;
background: var(--bg-tertiary);
opacity: 0.7;
}
.clear-token-btn:hover {
opacity: 1;
background: var(--error);
}
/* SVG Icons */
svg {
width: 24px;
height: 24px;
fill: currentColor;
}
button.primary svg {
width: 28px;
height: 28px;
}
@media (max-width: 600px) {
.container {
padding: 1rem;
}
#album-art {
width: 250px;
height: 250px;
}
#track-title {
font-size: 1.5rem;
}
}
</style>
</head>
<body>
<!-- Clear Token Button -->
<button class="clear-token-btn" onclick="clearToken()" title="Clear saved token">Logout</button>
<!-- Auth Modal -->
<div id="auth-overlay">
<div class="auth-modal">
<h2>Media Server</h2>
<p>Enter your API token to connect to the media server.</p>
<input type="text" id="token-input" placeholder="Enter API Token" autocomplete="off">
<button class="btn-connect" onclick="authenticate()">Connect</button>
<div class="help-text">
<p>To get your token, run:</p>
<code>media-server --show-token</code>
</div>
<div class="error-message" id="auth-error"></div>
</div>
</div>
<div class="container">
<header>
<h1>Media Server</h1>
<div style="display: flex; align-items: center; gap: 1rem;">
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme" id="theme-toggle">
<svg id="theme-icon-sun" viewBox="0 0 24 24" style="display: none;">
<path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zM2 13h2c.55 0 1-.45 1-1s-.45-1-1-1H2c-.55 0-1 .45-1 1s.45 1 1 1zm18 0h2c.55 0 1-.45 1-1s-.45-1-1-1h-2c-.55 0-1 .45-1 1s.45 1 1 1zM11 2v2c0 .55.45 1 1 1s1-.45 1-1V2c0-.55-.45-1-1-1s-1 .45-1 1zm0 18v2c0 .55.45 1 1 1s1-.45 1-1v-2c0-.55-.45-1-1-1s-1 .45-1 1zM5.99 4.58c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0s.39-1.03 0-1.41L5.99 4.58zm12.37 12.37c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0 .39-.39.39-1.03 0-1.41l-1.06-1.06zm1.06-10.96c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41s1.03.39 1.41 0l1.06-1.06zM7.05 18.36c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41s1.03.39 1.41 0l1.06-1.06z"/>
</svg>
<svg id="theme-icon-moon" viewBox="0 0 24 24">
<path d="M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54 0 4.48-2.94 8.27-7 9.54.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2z"/>
</svg>
</button>
<div class="status-indicator">
<span class="status-dot" id="status-dot"></span>
<span id="status-text">Disconnected</span>
</div>
</div>
</header>
<div class="player-container">
<div class="album-art-container">
<img id="album-art" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 300 300'%3E%3Crect fill='%23282828' width='300' height='300'/%3E%3Cpath fill='%236a6a6a' d='M150 80c-38.66 0-70 31.34-70 70s31.34 70 70 70 70-31.34 70-70-31.34-70-70-70zm0 20c27.614 0 50 22.386 50 50s-22.386 50-50 50-50-22.386-50-50 22.386-50 50-50zm0 30a20 20 0 100 40 20 20 0 000-40z'/%3E%3C/svg%3E" alt="Album Art">
</div>
<div class="track-info">
<div id="track-title">No media playing</div>
<div id="artist"></div>
<div id="album"></div>
<div class="playback-state">
<svg class="state-icon" id="state-icon" viewBox="0 0 24 24">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/>
</svg>
<span id="playback-state">Idle</span>
</div>
</div>
<div class="progress-container">
<div class="time-display">
<span id="current-time">0:00</span>
<span id="total-time">0:00</span>
</div>
<div class="progress-bar" id="progress-bar" data-duration="0">
<div class="progress-fill" id="progress-fill"></div>
</div>
</div>
<div class="controls">
<button onclick="previousTrack()" title="Previous" id="btn-previous">
<svg viewBox="0 0 24 24">
<path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/>
</svg>
</button>
<button class="primary" onclick="togglePlayPause()" title="Play/Pause" id="btn-play-pause">
<svg viewBox="0 0 24 24" id="play-pause-icon">
<path d="M8 5v14l11-7z"/>
</svg>
</button>
<button onclick="nextTrack()" title="Next" id="btn-next">
<svg viewBox="0 0 24 24">
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/>
</svg>
</button>
</div>
<div class="volume-container">
<button class="mute-btn" onclick="toggleMute()" title="Mute" id="btn-mute">
<svg viewBox="0 0 24 24" id="mute-icon">
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/>
</svg>
</button>
<input type="range" id="volume-slider" min="0" max="100" value="50">
<div class="volume-display" id="volume-display">50%</div>
</div>
<div class="source-info">
Source: <span id="source">Unknown</span>
</div>
</div>
<!-- Scripts Section -->
<div class="scripts-container" id="scripts-container" style="display: none;">
<h2>Quick Actions</h2>
<div class="scripts-grid" id="scripts-grid">
<div class="scripts-empty">No scripts configured</div>
</div>
</div>
<!-- Script Management Section -->
<div class="script-management">
<div class="script-management-header">
<h2>Script Management</h2>
<button class="add-script-btn" onclick="showAddScriptDialog()">+ Add</button>
</div>
<table class="scripts-table">
<thead>
<tr>
<th>Name</th>
<th>Label</th>
<th>Command</th>
<th>Timeout</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scriptsTableBody">
<tr>
<td colspan="5" class="empty-state">No scripts configured. Click "Add Script" to create one.</td>
</tr>
</tbody>
</table>
</div>
<!-- Callback Management Section -->
<div class="script-management">
<div class="script-management-header">
<h2>Callback Management</h2>
<button class="add-script-btn" onclick="showAddCallbackDialog()">+ Add</button>
</div>
<p style="color: var(--text-secondary); font-size: 0.875rem; margin-bottom: 1rem;">
Callbacks are scripts triggered automatically by media control events (play, pause, volume, etc.)
</p>
<table class="scripts-table">
<thead>
<tr>
<th>Event</th>
<th>Command</th>
<th>Timeout</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="callbacksTableBody">
<tr>
<td colspan="4" class="empty-state">No callbacks configured. Click "Add Callback" to create one.</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Add/Edit Script Dialog -->
<dialog id="scriptDialog">
<div class="dialog-header">
<h3 id="dialogTitle">Add Script</h3>
</div>
<form id="scriptForm" onsubmit="saveScript(event)">
<div class="dialog-body">
<input type="hidden" id="scriptOriginalName">
<input type="hidden" id="scriptIsEdit">
<label>
Script Name *
<input type="text" id="scriptName" required pattern="[a-zA-Z0-9_]+"
title="Only letters, numbers, and underscores allowed" maxlength="64">
</label>
<label>
Label
<input type="text" id="scriptLabel" placeholder="Human-readable name">
</label>
<label>
Command *
<input type="text" id="scriptCommand" required placeholder="e.g., shutdown /s /t 0">
</label>
<label>
Description
<textarea id="scriptDescription" placeholder="What does this script do?"></textarea>
</label>
<label>
Icon (MDI)
<input type="text" id="scriptIcon" placeholder="e.g., mdi:power">
</label>
<label>
Timeout (seconds)
<input type="number" id="scriptTimeout" value="30" min="1" max="300">
</label>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" onclick="closeScriptDialog()">Cancel</button>
<button type="submit" class="btn-primary">Save</button>
</div>
</form>
</dialog>
<!-- Add/Edit Callback Dialog -->
<dialog id="callbackDialog">
<div class="dialog-header">
<h3 id="callbackDialogTitle">Add Callback</h3>
</div>
<form id="callbackForm" onsubmit="saveCallback(event)">
<div class="dialog-body">
<input type="hidden" id="callbackIsEdit">
<label>
Event *
<select id="callbackName" required>
<option value="">Select event...</option>
<option value="on_play">on_play - After play succeeds</option>
<option value="on_pause">on_pause - After pause succeeds</option>
<option value="on_stop">on_stop - After stop succeeds</option>
<option value="on_next">on_next - After next track succeeds</option>
<option value="on_previous">on_previous - After previous track succeeds</option>
<option value="on_volume">on_volume - After volume change</option>
<option value="on_mute">on_mute - After mute toggle</option>
<option value="on_seek">on_seek - After seek succeeds</option>
<option value="on_turn_on">on_turn_on - Callback-only action</option>
<option value="on_turn_off">on_turn_off - Callback-only action</option>
<option value="on_toggle">on_toggle - Callback-only action</option>
</select>
</label>
<label>
Command *
<input type="text" id="callbackCommand" required placeholder="e.g., shutdown /s /t 0">
</label>
<label>
Timeout (seconds)
<input type="number" id="callbackTimeout" value="30" min="1" max="300">
</label>
<label>
Working Directory
<input type="text" id="callbackWorkingDir" placeholder="Optional">
</label>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" onclick="closeCallbackDialog()">Cancel</button>
<button type="submit" class="btn-primary">Save</button>
</div>
</form>
</dialog>
<!-- Toast Notification -->
<div class="toast" id="toast"></div>
<script>
// Theme management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'dark';
setTheme(savedTheme);
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
const sunIcon = document.getElementById('theme-icon-sun');
const moonIcon = document.getElementById('theme-icon-moon');
if (theme === 'light') {
sunIcon.style.display = 'none';
moonIcon.style.display = 'block';
} else {
sunIcon.style.display = 'block';
moonIcon.style.display = 'none';
}
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'dark';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
setTheme(newTheme);
}
let ws = null;
let reconnectTimeout = null;
let currentState = 'idle';
let currentDuration = 0;
let currentPosition = 0;
let isUserAdjustingVolume = false;
let scripts = [];
// Position interpolation
let lastPositionUpdate = 0;
let lastPositionValue = 0;
let interpolationInterval = null;
// Initialize on page load
window.addEventListener('DOMContentLoaded', () => {
// Initialize theme
initTheme();
const token = localStorage.getItem('media_server_token');
if (token) {
connectWebSocket(token);
loadScripts();
loadScriptsTable();
loadCallbacksTable();
} else {
showAuthForm();
}
// Volume slider event
const volumeSlider = document.getElementById('volume-slider');
volumeSlider.addEventListener('input', (e) => {
isUserAdjustingVolume = true;
const volume = parseInt(e.target.value);
document.getElementById('volume-display').textContent = `${volume}%`;
});
volumeSlider.addEventListener('change', (e) => {
const volume = parseInt(e.target.value);
setVolume(volume);
setTimeout(() => { isUserAdjustingVolume = false; }, 500);
});
// Progress bar click to seek
const progressBar = document.getElementById('progress-bar');
progressBar.addEventListener('click', (e) => {
if (currentDuration > 0) {
const rect = progressBar.getBoundingClientRect();
const x = e.clientX - rect.left;
const percent = x / rect.width;
const seekPos = percent * currentDuration;
seek(seekPos);
}
});
// Enter key in token input
document.getElementById('token-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
authenticate();
}
});
});
function showAuthForm(errorMessage = '') {
const overlay = document.getElementById('auth-overlay');
overlay.classList.remove('hidden');
const errorEl = document.getElementById('auth-error');
if (errorMessage) {
errorEl.textContent = errorMessage;
errorEl.classList.add('visible');
} else {
errorEl.classList.remove('visible');
}
}
function hideAuthForm() {
document.getElementById('auth-overlay').classList.add('hidden');
}
function authenticate() {
const token = document.getElementById('token-input').value.trim();
if (!token) {
showAuthForm('Please enter a token');
return;
}
localStorage.setItem('media_server_token', token);
connectWebSocket(token);
}
function clearToken() {
localStorage.removeItem('media_server_token');
if (ws) {
ws.close();
}
showAuthForm('Token cleared. Please enter a new token.');
}
function connectWebSocket(token) {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/api/media/ws?token=${encodeURIComponent(token)}`;
ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('WebSocket connected');
updateConnectionStatus(true);
hideAuthForm();
loadScripts();
loadScriptsTable();
loadCallbacksTable();
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'status' || msg.type === 'status_update') {
updateUI(msg.data);
} else if (msg.type === 'scripts_changed') {
console.log('Scripts changed, reloading...');
loadScripts(); // Reload Quick Actions
loadScriptsTable(); // Reload Script Management table
} else if (msg.type === 'error') {
console.error('WebSocket error:', msg.message);
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
updateConnectionStatus(false);
};
ws.onclose = (event) => {
console.log('WebSocket closed:', event.code);
updateConnectionStatus(false);
stopPositionInterpolation();
if (event.code === 4001) {
// Invalid token
localStorage.removeItem('media_server_token');
showAuthForm('Invalid token. Please try again.');
} else if (event.code !== 1000) {
// Abnormal closure - attempt reconnect
reconnectTimeout = setTimeout(() => {
const savedToken = localStorage.getItem('media_server_token');
if (savedToken) {
console.log('Attempting to reconnect...');
connectWebSocket(savedToken);
}
}, 3000);
}
};
// Send keepalive ping every 30 seconds
setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
}
function updateConnectionStatus(connected) {
const dot = document.getElementById('status-dot');
const text = document.getElementById('status-text');
if (connected) {
dot.classList.add('connected');
text.textContent = 'Connected';
} else {
dot.classList.remove('connected');
text.textContent = 'Disconnected';
}
}
function updateUI(status) {
// Update track info
document.getElementById('track-title').textContent = status.title || 'No media playing';
document.getElementById('artist').textContent = status.artist || '';
document.getElementById('album').textContent = status.album || '';
// Update state
const previousState = currentState;
currentState = status.state;
updatePlaybackState(status.state);
// Update album art
const artImg = document.getElementById('album-art');
if (status.album_art_url) {
const token = localStorage.getItem('media_server_token');
artImg.src = `/api/media/artwork?token=${encodeURIComponent(token)}&_=${Date.now()}`;
} else {
artImg.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 300 300'%3E%3Crect fill='%23282828' width='300' height='300'/%3E%3Cpath fill='%236a6a6a' d='M150 80c-38.66 0-70 31.34-70 70s31.34 70 70 70 70-31.34 70-70-31.34-70-70-70zm0 20c27.614 0 50 22.386 50 50s-22.386 50-50 50-50-22.386-50-50 22.386-50 50-50zm0 30a20 20 0 100 40 20 20 0 000-40z'/%3E%3C/svg%3E";
}
// Update progress
if (status.duration && status.position !== null) {
currentDuration = status.duration;
currentPosition = status.position;
// Track position update for interpolation
lastPositionUpdate = Date.now();
lastPositionValue = status.position;
updateProgress(status.position, status.duration);
}
// Update volume
if (!isUserAdjustingVolume) {
document.getElementById('volume-slider').value = status.volume;
document.getElementById('volume-display').textContent = `${status.volume}%`;
}
// Update mute state
updateMuteIcon(status.muted);
// Update source
document.getElementById('source').textContent = status.source || 'Unknown';
// Enable/disable controls based on state
const hasMedia = status.state !== 'idle';
document.getElementById('btn-play-pause').disabled = !hasMedia;
document.getElementById('btn-next').disabled = !hasMedia;
document.getElementById('btn-previous').disabled = !hasMedia;
// Start/stop position interpolation based on playback state
if (status.state === 'playing' && previousState !== 'playing') {
startPositionInterpolation();
} else if (status.state !== 'playing' && previousState === 'playing') {
stopPositionInterpolation();
}
}
function updatePlaybackState(state) {
const stateText = document.getElementById('playback-state');
const stateIcon = document.getElementById('state-icon');
const playPauseIcon = document.getElementById('play-pause-icon');
switch(state) {
case 'playing':
stateText.textContent = 'Playing';
stateIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
playPauseIcon.innerHTML = '<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>';
break;
case 'paused':
stateText.textContent = 'Paused';
stateIcon.innerHTML = '<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>';
playPauseIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
break;
case 'stopped':
stateText.textContent = 'Stopped';
stateIcon.innerHTML = '<path d="M6 6h12v12H6z"/>';
playPauseIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
break;
default:
stateText.textContent = 'Idle';
stateIcon.innerHTML = '<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/>';
playPauseIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
}
}
function updateProgress(position, duration) {
const percent = (position / duration) * 100;
document.getElementById('progress-fill').style.width = `${percent}%`;
document.getElementById('current-time').textContent = formatTime(position);
document.getElementById('total-time').textContent = formatTime(duration);
document.getElementById('progress-bar').dataset.duration = duration;
}
function startPositionInterpolation() {
// Clear any existing interval
if (interpolationInterval) {
clearInterval(interpolationInterval);
}
// Update position every 100ms for smooth animation
interpolationInterval = setInterval(() => {
if (currentState === 'playing' && currentDuration > 0 && lastPositionUpdate > 0) {
// Calculate elapsed time since last position update
const elapsed = (Date.now() - lastPositionUpdate) / 1000;
const interpolatedPosition = Math.min(lastPositionValue + elapsed, currentDuration);
// Update UI with interpolated position
updateProgress(interpolatedPosition, currentDuration);
}
}, 100);
}
function stopPositionInterpolation() {
if (interpolationInterval) {
clearInterval(interpolationInterval);
interpolationInterval = null;
}
}
function updateMuteIcon(muted) {
const muteIcon = document.getElementById('mute-icon');
if (muted) {
muteIcon.innerHTML = '<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/>';
} else {
muteIcon.innerHTML = '<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/>';
}
}
function formatTime(seconds) {
if (!seconds || seconds < 0) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
}
// API Commands
async function sendCommand(endpoint, body = null) {
const token = localStorage.getItem('media_server_token');
const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
if (body) {
options.body = JSON.stringify(body);
}
try {
const response = await fetch(`/api/media/${endpoint}`, options);
if (!response.ok) {
console.error(`Command ${endpoint} failed:`, response.status);
}
} catch (error) {
console.error(`Error sending command ${endpoint}:`, error);
}
}
function togglePlayPause() {
if (currentState === 'playing') {
sendCommand('pause');
} else {
sendCommand('play');
}
}
function nextTrack() {
sendCommand('next');
}
function previousTrack() {
sendCommand('previous');
}
function setVolume(volume) {
sendCommand('volume', { volume: volume });
}
function toggleMute() {
sendCommand('mute');
}
function seek(position) {
sendCommand('seek', { position: position });
}
// Scripts functionality
async function loadScripts() {
const token = localStorage.getItem('media_server_token');
try {
const response = await fetch('/api/scripts/list', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
scripts = await response.json();
displayScripts();
}
} catch (error) {
console.error('Error loading scripts:', error);
}
}
function displayScripts() {
const container = document.getElementById('scripts-container');
const grid = document.getElementById('scripts-grid');
if (scripts.length === 0) {
container.style.display = 'none';
return;
}
container.style.display = 'block';
grid.innerHTML = '';
scripts.forEach(script => {
const button = document.createElement('button');
button.className = 'script-btn';
button.onclick = () => executeScript(script.name, button);
const label = document.createElement('div');
label.className = 'script-label';
label.textContent = script.label || script.name;
button.appendChild(label);
if (script.description) {
const description = document.createElement('div');
description.className = 'script-description';
description.textContent = script.description;
button.appendChild(description);
}
grid.appendChild(button);
});
}
async function executeScript(scriptName, buttonElement) {
const token = localStorage.getItem('media_server_token');
// Add executing state
buttonElement.classList.add('executing');
try {
const response = await fetch(`/api/scripts/execute/${scriptName}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ args: [] })
});
const result = await response.json();
if (response.ok && result.success) {
showToast(`${scriptName} executed successfully`, 'success');
} else {
showToast(`Failed to execute ${scriptName}`, 'error');
}
} catch (error) {
console.error(`Error executing script ${scriptName}:`, error);
showToast(`Error executing ${scriptName}`, 'error');
} finally {
// Remove executing state
buttonElement.classList.remove('executing');
}
}
function showToast(message, type = 'success') {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.className = `toast ${type} show`;
setTimeout(() => {
toast.classList.remove('show');
}, 3000);
}
// Script Management Functions
async function loadScriptsTable() {
const token = localStorage.getItem('media_server_token');
const tbody = document.getElementById('scriptsTableBody');
try {
const response = await fetch('/api/scripts/list', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) {
throw new Error('Failed to fetch scripts');
}
const scriptsList = await response.json();
if (scriptsList.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="empty-state">No scripts configured. Click "Add Script" to create one.</td></tr>';
return;
}
tbody.innerHTML = scriptsList.map(script => `
<tr>
<td><code>${script.name}</code></td>
<td>${script.label || script.name}</td>
<td style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
title="${escapeHtml(script.command || 'N/A')}">${escapeHtml(script.command || 'N/A')}</td>
<td>${script.timeout}s</td>
<td>
<button class="action-btn" onclick="showEditScriptDialog('${script.name}')">Edit</button>
<button class="action-btn delete" onclick="deleteScriptConfirm('${script.name}')">Delete</button>
</td>
</tr>
`).join('');
} catch (error) {
console.error('Error loading scripts:', error);
tbody.innerHTML = '<tr><td colspan="5" class="empty-state" style="color: var(--error);">Failed to load scripts</td></tr>';
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function showAddScriptDialog() {
const dialog = document.getElementById('scriptDialog');
const form = document.getElementById('scriptForm');
const title = document.getElementById('dialogTitle');
// Reset form
form.reset();
document.getElementById('scriptOriginalName').value = '';
document.getElementById('scriptIsEdit').value = 'false';
document.getElementById('scriptName').disabled = false;
title.textContent = 'Add Script';
dialog.showModal();
}
async function showEditScriptDialog(scriptName) {
const token = localStorage.getItem('media_server_token');
const dialog = document.getElementById('scriptDialog');
const title = document.getElementById('dialogTitle');
try {
// Fetch current script details
const response = await fetch('/api/scripts/list', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) {
throw new Error('Failed to fetch script details');
}
const scriptsList = await response.json();
const script = scriptsList.find(s => s.name === scriptName);
if (!script) {
showToast('Script not found', 'error');
return;
}
// Populate form
document.getElementById('scriptOriginalName').value = scriptName;
document.getElementById('scriptIsEdit').value = 'true';
document.getElementById('scriptName').value = scriptName;
document.getElementById('scriptName').disabled = true; // Can't change name
document.getElementById('scriptLabel').value = script.label || '';
document.getElementById('scriptCommand').value = script.command || '';
document.getElementById('scriptDescription').value = script.description || '';
document.getElementById('scriptIcon').value = script.icon || '';
document.getElementById('scriptTimeout').value = script.timeout || 30;
title.textContent = 'Edit Script';
dialog.showModal();
} catch (error) {
console.error('Error loading script for edit:', error);
showToast('Failed to load script details', 'error');
}
}
function closeScriptDialog() {
const dialog = document.getElementById('scriptDialog');
dialog.close();
}
async function saveScript(event) {
event.preventDefault();
const token = localStorage.getItem('media_server_token');
const isEdit = document.getElementById('scriptIsEdit').value === 'true';
const scriptName = isEdit ?
document.getElementById('scriptOriginalName').value :
document.getElementById('scriptName').value;
const data = {
command: document.getElementById('scriptCommand').value,
label: document.getElementById('scriptLabel').value || null,
description: document.getElementById('scriptDescription').value || '',
icon: document.getElementById('scriptIcon').value || null,
timeout: parseInt(document.getElementById('scriptTimeout').value) || 30,
shell: true
};
const endpoint = isEdit ?
`/api/scripts/update/${scriptName}` :
`/api/scripts/create/${scriptName}`;
const method = isEdit ? 'PUT' : 'POST';
try {
const response = await fetch(endpoint, {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
showToast(`Script ${isEdit ? 'updated' : 'created'} successfully`, 'success');
closeScriptDialog();
// Don't reload manually - WebSocket will trigger it
} else {
showToast(result.detail || `Failed to ${isEdit ? 'update' : 'create'} script`, 'error');
}
} catch (error) {
console.error('Error saving script:', error);
showToast(`Error ${isEdit ? 'updating' : 'creating'} script`, 'error');
}
}
async function deleteScriptConfirm(scriptName) {
if (!confirm(`Are you sure you want to delete the script "${scriptName}"?`)) {
return;
}
const token = localStorage.getItem('media_server_token');
try {
const response = await fetch(`/api/scripts/delete/${scriptName}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
const result = await response.json();
if (response.ok && result.success) {
showToast('Script deleted successfully', 'success');
// Don't reload manually - WebSocket will trigger it
} else {
showToast(result.detail || 'Failed to delete script', 'error');
}
} catch (error) {
console.error('Error deleting script:', error);
showToast('Error deleting script', 'error');
}
}
// Callback Management Functions
async function loadCallbacksTable() {
const token = localStorage.getItem('media_server_token');
const tbody = document.getElementById('callbacksTableBody');
try {
const response = await fetch('/api/callbacks/list', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) {
throw new Error('Failed to fetch callbacks');
}
const callbacksList = await response.json();
if (callbacksList.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" class="empty-state">No callbacks configured. Click "Add Callback" to create one.</td></tr>';
return;
}
tbody.innerHTML = callbacksList.map(callback => `
<tr>
<td><code>${callback.name}</code></td>
<td style="max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
title="${escapeHtml(callback.command)}">${escapeHtml(callback.command)}</td>
<td>${callback.timeout}s</td>
<td>
<button class="action-btn" onclick="showEditCallbackDialog('${callback.name}')">Edit</button>
<button class="action-btn delete" onclick="deleteCallbackConfirm('${callback.name}')">Delete</button>
</td>
</tr>
`).join('');
} catch (error) {
console.error('Error loading callbacks:', error);
tbody.innerHTML = '<tr><td colspan="4" class="empty-state" style="color: var(--error);">Failed to load callbacks</td></tr>';
}
}
function showAddCallbackDialog() {
const dialog = document.getElementById('callbackDialog');
const form = document.getElementById('callbackForm');
const title = document.getElementById('callbackDialogTitle');
// Reset form
form.reset();
document.getElementById('callbackIsEdit').value = 'false';
document.getElementById('callbackName').disabled = false;
title.textContent = 'Add Callback';
dialog.showModal();
}
async function showEditCallbackDialog(callbackName) {
const token = localStorage.getItem('media_server_token');
const dialog = document.getElementById('callbackDialog');
const title = document.getElementById('callbackDialogTitle');
try {
// Fetch current callback details
const response = await fetch('/api/callbacks/list', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) {
throw new Error('Failed to fetch callback details');
}
const callbacksList = await response.json();
const callback = callbacksList.find(c => c.name === callbackName);
if (!callback) {
showToast('Callback not found', 'error');
return;
}
// Populate form
document.getElementById('callbackIsEdit').value = 'true';
document.getElementById('callbackName').value = callbackName;
document.getElementById('callbackName').disabled = true; // Can't change event name
document.getElementById('callbackCommand').value = callback.command;
document.getElementById('callbackTimeout').value = callback.timeout;
document.getElementById('callbackWorkingDir').value = callback.working_dir || '';
title.textContent = 'Edit Callback';
dialog.showModal();
} catch (error) {
console.error('Error loading callback for edit:', error);
showToast('Failed to load callback details', 'error');
}
}
function closeCallbackDialog() {
const dialog = document.getElementById('callbackDialog');
dialog.close();
}
async function saveCallback(event) {
event.preventDefault();
const token = localStorage.getItem('media_server_token');
const isEdit = document.getElementById('callbackIsEdit').value === 'true';
const callbackName = document.getElementById('callbackName').value;
const data = {
command: document.getElementById('callbackCommand').value,
timeout: parseInt(document.getElementById('callbackTimeout').value) || 30,
working_dir: document.getElementById('callbackWorkingDir').value || null,
shell: true
};
const endpoint = isEdit ?
`/api/callbacks/update/${callbackName}` :
`/api/callbacks/create/${callbackName}`;
const method = isEdit ? 'PUT' : 'POST';
try {
const response = await fetch(endpoint, {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
showToast(`Callback ${isEdit ? 'updated' : 'created'} successfully`, 'success');
closeCallbackDialog();
loadCallbacksTable();
} else {
showToast(result.detail || `Failed to ${isEdit ? 'update' : 'create'} callback`, 'error');
}
} catch (error) {
console.error('Error saving callback:', error);
showToast(`Error ${isEdit ? 'updating' : 'creating'} callback`, 'error');
}
}
async function deleteCallbackConfirm(callbackName) {
if (!confirm(`Are you sure you want to delete the callback "${callbackName}"?`)) {
return;
}
const token = localStorage.getItem('media_server_token');
try {
const response = await fetch(`/api/callbacks/delete/${callbackName}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
const result = await response.json();
if (response.ok && result.success) {
showToast('Callback deleted successfully', 'success');
loadCallbacksTable();
} else {
showToast(result.detail || 'Failed to delete callback', 'error');
}
} catch (error) {
console.error('Error deleting callback:', error);
showToast('Error deleting callback', 'error');
}
}
</script>
</body>
</html>