Compare commits

..

33 Commits

Author SHA1 Message Date
babdb61791 Update media-server: Vinyl record mode and accent color picker
- Vinyl mode: album art as center label with grooves, spindle hole, vignette
- Smooth transition between normal and vinyl modes
- Accent color picker with 9 preset colors in header
- Fix progress bar hover layout shift (use scaleY instead of height)
- Fix glow position jump when toggling vinyl mode

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-23 23:46:24 +03:00
65b513ca17 Update media-server: UI polish and bug fixes
- Compact header and footer (reduced padding, margins, font sizes)
- Remove separator borders from header and footer
- Fix color contrast on hover states (white text on accent backgrounds)
- Fix album art not updating on track change (composite cache key)
- Slow vinyl spin animation (4s → 12s)
- Replace Add buttons with dashed-border add-cards
- Fix dialog header text color
- Make theme toggle button transparent

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-23 23:16:53 +03:00
84b985e6df Backend optimizations, frontend optimizations, and UI design improvements
Backend optimizations:
- GZip middleware for compressed responses
- Concurrent WebSocket broadcast
- Skip status polling when no clients connected
- Deduplicated token validation with caching
- Fire-and-forget HA state callbacks
- Single stat() per browser item
- Metadata caching (LRU)
- M3U playlist optimization
- Autostart setup (Task Scheduler + hidden VBS launcher)

Frontend code optimizations:
- Fix thumbnail blob URL memory leak
- Fix WebSocket ping interval leak on reconnect
- Skip artwork re-fetch when same track playing
- Deduplicate volume slider logic
- Extract magic numbers into named constants
- Standardize error handling with toast notifications
- Cache play/pause SVG constants
- Loading state management for async buttons
- Request deduplication for rapid clicks
- Cache 30+ DOM element references
- Deduplicate volume updates over WebSocket

Frontend design improvements:
- Progress bar seek thumb and hover expansion
- Custom themed scrollbars
- Toast notification accent border strips
- Keyboard focus-visible states
- Album art ambient glow effect
- Animated sliding tab indicator
- Mini-player top progress line
- Empty state SVG illustrations
- Responsive tablet breakpoint (601-900px)
- Horizontal player layout on wide screens (>900px)
- Glassmorphism mini-player with backdrop blur
- Vinyl spin animation (toggleable)
- Table horizontal scroll on narrow screens

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 20:38:35 +03:00
d1ec27cb7b Improve error handling for unavailable network shares
- Add OSError/PermissionError handling in browse endpoint
- Return 503 status code when folders are temporarily unavailable
- Display user-friendly error messages in the UI
- Enhance error logging with exception type information

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 12:03:25 +03:00
13df69adb4 Show media title (Artist – Title) instead of filename when available
- Extract title and artist tags via mutagen easy=True in get_media_info
- Display "Artist – Title" in both grid and list views, fall back to filename
- Show original filename in tooltip on hover

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 03:42:32 +03:00
4c13322936 Show bitrate in browser, remove type labels and Play All text
- Extract bitrate alongside duration in browse_directory via get_media_info
- Display bitrate in large card view metadata (duration · bitrate · size)
- Replace Audio/Video type badge with bitrate column in list view
- Remove Play All button text, keep icon only
- Add formatBitrate helper function

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 03:37:13 +03:00
5f474d6c9f Add browser search/filter for media items
- Search bar appears when browsing inside a folder
- Client-side filtering with 200ms debounce
- Clear button and search icon
- Hides at root level, resets on navigation
- Localized placeholder (en/ru)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 02:44:31 +03:00
98a33bca54 Tabbed UI, browse caching, and bottom mini player
- Convert stacked sections to tabbed interface (Player, Browser, Actions, Scripts, Callbacks) with localStorage persistence
- Add in-memory directory listing cache (5-min TTL) with nocache bypass for refresh
- Defer stat()/duration calls to paginated items only for faster browse
- Move mini player from top to bottom with footer padding fix
- Always show scrollbar to prevent layout shift between tabs
- Add tab localization keys (en/ru)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 02:34:29 +03:00
8db40d3ee9 UI polish: refresh button, negative thumbnail cache, and style fixes
- Add refresh button to browser toolbar to re-fetch current folder
- Cache "no thumbnail" results to avoid repeated slow SMB lookups
- Fix list view fallback icon sizing for files without album art
- Fix view toggle button hover (no background/scale on hover)
- Skip re-render when clicking already-active view mode button

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 02:10:22 +03:00
f275240e59 Add Play All, home navigation, and UI improvements
- Add Play All button with M3U playlist generation (local temp file with absolute paths)
- Replace folder combobox with root folder cards and home icon breadcrumb
- Fix compact grid card sizing (64x64 thumbnails, align-items: start)
- Add loading spinner when browsing folders
- Cache browse items to avoid re-fetching on view mode switch
- Remove unused browser-controls CSS
- Add localization keys for Play All and Home (en/ru)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 01:57:32 +03:00
e16674c658 Add media browser with grid/compact/list views and single-click playback
- Add browser UI with three view modes (grid, compact, list) and pagination
- Add file browsing, thumbnail loading, download, and play endpoints
- Add duration extraction via mutagen for media files
- Single-click plays media or navigates folders, with play overlay on hover
- Add type badges, file size display, and duration metadata
- Add localization keys for browser UI (en/ru)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 23:34:38 +03:00
32b058c5fb Add low-latency volume control via WebSocket
- Send volume updates through WebSocket instead of HTTP POST
- Reduce throttle from 50ms to 16ms (~60 updates/sec)
- Fall back to HTTP if WebSocket is disconnected

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 13:19:58 +03:00
c5f8c7a092 Fix HTTPException handling in folder endpoints and install script path
- Add missing `except HTTPException: raise` in create_folder and
  update_folder endpoints to prevent 400 errors being masked as 500s
- Fix install_task_windows.ps1 working directory to point to
  media-server root instead of parent project root

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 13:09:47 +03:00
8d15a2a54b Update Web UI: Header redesign, thumbnail fix, and title fallback
- Add version label next to Media Server header (fetched from /api/health)
- Move connection status dot before title, remove status text
- Move logout button into header after language selector
- Return 204 instead of 404 for missing thumbnails (eliminates console errors)
- Show "Title unavailable" when media is playing but title is empty
- Add player.title_unavailable translation key for en/ru locales

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 20:03:43 +03:00
1cb83eac1c Add screenshots to README
- Web UI media player screenshot
- Media Browser screenshot
- Script and Callback Management screenshot

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 18:03:59 +03:00
62c42f70d1 Move install_task_windows.ps1 to scripts folder
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 12:26:45 +03:00
eb2aed40c1 Update media browser UI with fade-in animations and improvements
- Add fade-in animation for thumbnail loading to prevent layout shifts
- Add loading state indicators for thumbnails
- Improve media browser CSS styling
- Enhance JavaScript for smoother thumbnail loading experience

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 22:24:20 +03:00
7c631d09f6 Add media browser feature with UI improvements
- Refactored index.html: Split into separate HTML (309 lines), CSS (908 lines), and JS (1,286 lines) files
- Implemented media browser with folder configuration, recursive navigation, and thumbnail display
- Added metadata extraction using mutagen library (title, artist, album, duration, bitrate, codec)
- Implemented thumbnail generation and caching with SHA256 hash-based keys and LRU eviction
- Added platform-specific file playback (os.startfile on Windows, xdg-open on Linux, open on macOS)
- Implemented path validation security to prevent directory traversal attacks
- Added smooth thumbnail loading with fade-in animation and loading spinner
- Added i18n support for browser (English and Russian)
- Updated dependencies: mutagen>=1.47.0, pillow>=10.0.0
- Added comprehensive media browser documentation to README

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 21:31:02 +03:00
d5ec5c611f Update Web UI: Improve volume slider responsiveness
- Add real-time volume updates while dragging slider
- Throttle updates to 50ms for smooth, responsive feedback
- Prevent overwhelming server with excessive API calls
- Update volume immediately on mouse release for final value

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:22:57 +03:00
29e0618b9f Update Web UI: Add server management scripts and improve UX
UI improvements:
- Add icon-based Execute/Edit/Delete buttons for scripts and callbacks
- Add execution result dialog with stdout/stderr and execution time
- Add favicon with media player icon
- Disable background scrolling when dialogs are open
- Add footer with author information and source code link

Backend enhancements:
- Add execution time tracking to script and callback execution
- Add /api/callbacks/execute endpoint for debugging callbacks
- Return detailed execution results (stdout, stderr, exit_code, execution_time)

Server management:
- Add scripts/start-server.bat - Start server with console window
- Add scripts/start-server-background.vbs - Start server silently
- Add scripts/stop-server.bat - Stop running server instances
- Add scripts/restart-server.bat - Restart the server

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:18:59 +03:00
4f8f59dc89 Update media-server: Fix FOUC (Flash of Untranslated Content) issues
- Add CSS to hide page content during translation load (opacity transition)
- Hide dialogs explicitly until opened with showModal()
- Hide auth overlay by default in HTML (shown only when needed)
- Prevents flash of English text, dialogs, and auth overlay on page load
- Smooth fade-in after translations are loaded

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 17:52:44 +03:00
40c2c11c85 Update media-server: Improve script/callback table layout and command editor UX
- Reduce command column max-width from 300px/400px to 200px for better table fit
- Change command input from single-line text to multiline textarea (3 rows)
- Apply changes to both script and callback dialogs
- Prevents table overflow and makes editing long commands easier

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 17:34:11 +03:00
0470a17a0c Update CLAUDE.md: Add server restart guidelines for development
- Add new "Development Workflow" section
- Document when server restart is required (Python/API changes)
- Document when restart is NOT needed (static files, docs)
- Provide step-by-step restart instructions for Windows and Linux/macOS
- Add best practice to verify changes after restart before pushing

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 17:24:30 +03:00
4635caca98 Update media-server: Add execution timing and improve script/callback execution UI
Backend improvements:
- Add execution_time tracking for script execution
- Add execution_time tracking for callback execution
- Add /api/callbacks/execute/{callback_name} endpoint for debugging callbacks

Frontend improvements:
- Fix duration display showing N/A for fast scripts (0 is falsy in JS)
- Increase duration precision to 3 decimal places (0.001s)
- Always show output section with "(no output)" message when empty
- Improve output formatting with italic gray text for empty output

Documentation:
- Add localization section to README
- Document available languages (English, Russian)
- Add guide for contributing new translations

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 17:20:51 +03:00
957a177b72 Update media-server: Add backdrop click-to-close for dialogs
- Add dirty state tracking for script and callback forms
- Add backdrop click event listeners to detect clicks outside dialogs
- Add unsaved changes confirmation when closing dialogs with modifications
- Reset dirty state when opening dialogs or after successful save
- Add localized confirmation messages (EN/RU) for unsaved changes

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 14:54:42 +03:00
8077181dce Fix Windows Task Scheduler auto-start
- Auto-detect Python executable path instead of hardcoded "python"
- Add error handling if Python not found in PATH
- Add ErrorAction to prevent errors on unregister
- Fixes "file not found" error (0x80070002) on system startup

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 13:51:43 +03:00
9bbb8e1bd7 Add internationalization (i18n) support with English and Russian locales
- Add translation JSON files (en.json, ru.json) with 110+ strings each
- Implement locale auto-detection from browser settings
- Add locale toggle button (EN/RU) with localStorage persistence
- Translate all user-facing text: auth, player, scripts, callbacks
- Fix dynamic content translation on locale switch (playback state, track title)
- Add comprehensive i18n documentation to CLAUDE.md
- Follow existing theme toggle pattern for consistency

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 04:27:50 +03:00
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
d7c5994e56 Add runtime script management with Home Assistant integration
Features:
- Runtime script CRUD operations (create, update, delete)
- Thread-safe ConfigManager for YAML updates
- WebSocket notifications for script changes
- Web UI script management interface with full CRUD
- Home Assistant auto-reload on script changes
- Client-side position interpolation for smooth playback
- Include command field in script list API response

Technical improvements:
- Added broadcast_scripts_changed() to WebSocket manager
- Enhanced HA integration to handle scripts_changed messages
- Implemented smooth position updates in Web UI (100ms interval)
- Thread-safe configuration updates with file locking

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 03:53:23 +03:00
71a0a6e6d1 Add multi-token authentication with client labels
- Replace single api_token with api_tokens dict (label: token pairs)
- Add context-aware logging to track which client made each request
- Implement token label lookup with secure comparison
- Add logging middleware to inject token labels into request context
- Update logging format to display [label] in all log messages
- Fix WebSocket authentication to use new multi-token system
- Update CLI --show-token to display all tokens with labels
- Update config generation to use api_tokens format
- Update README with multi-token documentation
- Update config.example.yaml with multiple token examples

Benefits:
- Easy identification of clients in logs (Home Assistant, mobile, web UI, etc.)
- Per-client token management and revocation
- Better security and auditability

Example log output:
2026-02-06 03:36:20,806 - [home_assistant] - WebSocket client connected

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 03:37:35 +03:00
5342cffac7 Add script execution to Web UI
- Add "Quick Actions" section to display configured scripts
- Load scripts from /api/scripts/list on connection
- Display scripts in responsive grid layout
- Execute scripts with single click via /api/scripts/execute
- Show toast notifications for execution feedback
- Visual feedback during script execution
- Auto-hide section if no scripts configured

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 03:28:54 +03:00
a0d138bb93 Add built-in Web UI for media control and monitoring
- Add static file serving to FastAPI application
- Create responsive web interface with real-time updates
- Features:
  - Real-time status updates via WebSocket
  - Album artwork display with automatic updates
  - Playback controls (play, pause, next, previous)
  - Volume control with mute toggle
  - Seekable progress bar
  - Token authentication with localStorage persistence
  - Dark theme and responsive design
  - Auto-reconnect WebSocket support
- Update README with Web UI documentation
- Zero dependencies (vanilla HTML/CSS/JavaScript)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 03:25:08 +03:00
1a1cfbaafb Add callbacks support for all media actions
- Add CallbackConfig model for callback scripts
- Add callbacks section to config for optional command execution
- Add turn_on/turn_off/toggle endpoints (callback-only)
- Add callbacks for all media actions (play, pause, stop, next, previous, volume, mute, seek)
- Update README with callbacks documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 03:44:18 +03:00
39 changed files with 9234 additions and 104 deletions

3
.gitignore vendored
View File

@@ -46,3 +46,6 @@ logs/
# OS
.DS_Store
Thumbs.db
# Thumbnail cache
.cache/

View File

@@ -26,6 +26,57 @@ To remove the scheduled task:
Unregister-ScheduledTask -TaskName "MediaServer" -Confirm:$false
```
## Development Workflow
### Server Restart After Code Changes
**CRITICAL:** When making changes to backend code (Python files, API routes, service logic), the media server MUST be restarted for changes to take effect.
**When to restart:**
- Changes to any Python files (`*.py`) in the media_server directory
- Changes to API endpoints, routes, or request/response models
- Changes to service logic, callbacks, or script execution
- Changes to configuration handling or startup logic
**When restart is NOT needed:**
- Static file changes (`*.html`, `*.css`, `*.js`, `*.json`) - browser refresh is enough
- README or documentation updates
- Changes to install/service scripts (only affects new installations)
**How to restart during development:**
1. Find the running server process:
```bash
# Windows
netstat -ano | findstr :8765
# Linux/macOS
lsof -i :8765
```
2. Stop the server:
```bash
# Windows
taskkill //F //PID <process_id>
# Linux/macOS
kill <process_id>
```
3. Start the server again:
```bash
python -m media_server.main
```
**Best Practice:** Always restart the server immediately after committing backend changes to verify they work correctly before pushing.
**CRITICAL** Always check acccessibility of WebUI after server restart to ensure that server has started without issues
## Configuration
Copy `config.example.yaml` to `config.yaml` and customize.
@@ -34,6 +85,43 @@ The API token is generated on first run and displayed in the console output.
Default port: `8765`
## Internationalization (i18n)
The Web UI supports multiple languages with translations stored in separate JSON files.
### Locale Files
Translation files are located in:
- `media_server/static/locales/en.json` - English (default)
- `media_server/static/locales/ru.json` - Russian
### Maintaining Translations
**IMPORTANT:** When adding or modifying user-facing text in the Web UI:
1. **Update all locale files** - Add or update the translation key in **both** `en.json` and `ru.json`
2. **Use consistent keys** - Follow the existing key naming pattern (e.g., `section.element`, `scripts.button.save`)
3. **Test both locales** - Verify translations appear correctly by switching between EN/RU
### Adding New Text
When adding new UI elements:
1. Add the English text to `static/locales/en.json`
2. Add the Russian translation to `static/locales/ru.json`
3. In HTML: use `data-i18n="key.name"` for text content
4. In HTML: use `data-i18n-placeholder="key.name"` for input placeholders
5. In HTML: use `data-i18n-title="key.name"` for title attributes
6. In JavaScript: use `t('key.name')` or `t('key.name', {param: value})` for dynamic text
### Adding New Locales
To add support for a new language:
1. Create `media_server/static/locales/{lang_code}.json` (copy from `en.json`)
2. Translate all strings to the new language
3. Add the language code to `supportedLocales` array in `index.html`
## Versioning
Version is tracked in two files that must be kept in sync:

317
README.md
View File

@@ -4,14 +4,183 @@ A REST API server for controlling system media playback on Windows, Linux, macOS
## Features
- **Built-in Web UI** for real-time media control and monitoring
- Control any media player via system-wide media transport controls
- Play/Pause/Stop/Next/Previous track
- Volume control and mute
- Seek within tracks
- Get current track info (title, artist, album, artwork)
- WebSocket support for real-time updates
- Token-based authentication
- Cross-platform support
## Web UI
The media server includes a built-in web interface for controlling and monitoring media playback.
![Web UI](docs/web-ui.PNG)
### Features
- **Real-time status updates** via WebSocket connection
- **Album artwork display** with automatic updates
- **Playback controls** - Play, pause, next, previous
- **Volume control** with mute toggle
- **Seekable progress bar** - Click to jump to any position
- **Connection status indicator** - Know when you're connected
- **Token authentication** - Saved in browser localStorage
- **Responsive design** - Works on desktop and mobile
- **Dark theme** - Easy on the eyes
- **Multi-language support** - English and Russian locales with automatic detection
### Accessing the Web UI
1. Start the media server:
```bash
python -m media_server.main
```
2. Open your browser and navigate to:
```
http://localhost:8765/
```
3. Enter your API token when prompted (get it with `media-server --show-token`)
4. Start playing media in any supported player and watch the UI update in real-time!
### Remote Access
To access the Web UI from other devices on your network:
1. Find your computer's IP address (e.g., `192.168.1.100`)
2. Navigate to `http://192.168.1.100:8765/` from any device on the same network
3. Enter your API token
**Security Note:** For remote access over the internet, use a reverse proxy with HTTPS (nginx, Caddy) to encrypt traffic.
### Localization
The Web UI supports multiple languages with automatic browser locale detection:
**Available Languages:**
- **English (en)** - Default
- **Русский (ru)** - Russian
The interface automatically detects your browser language on first visit. You can manually switch languages using the dropdown in the top-right corner of the Web UI.
**Contributing New Locales:**
We welcome translations for additional languages! To contribute a new locale:
1. Copy `media_server/static/locales/en.json` to a new file named with your language code (e.g., `de.json` for German)
2. Translate all strings to your language, keeping the same JSON structure
3. Add your language to the `supportedLocales` object in `media_server/static/index.html`:
```javascript
const supportedLocales = {
'en': 'English',
'ru': 'Русский',
'de': 'Deutsch' // Add your language here
};
```
4. Test the translation by switching to your language in the Web UI
5. Submit a pull request with your changes
See [CLAUDE.md](CLAUDE.md#internationalization-i18n) for detailed translation guidelines.
## Media Browser
The Media Browser feature allows you to browse and play media files from configured folders directly through the Web UI.
![Media Browser](docs/media-browser.PNG)
### Browser Features
- **Folder Configuration** - Mount multiple media folders (music/video directories)
- **Recursive Navigation** - Browse through folder hierarchies with breadcrumb navigation
- **Thumbnail Display** - Automatically generated thumbnails from album art
- **Metadata Extraction** - View title, artist, album, duration, bitrate, and more
- **Remote Playback** - Play files on the PC running the media server (not in the browser)
- **Last Path Memory** - Automatically returns to your last browsed location
- **Lazy Loading** - Thumbnails load only when visible for better performance
### Configuration
Add media folders in your `config.yaml`:
```yaml
# Media folders for browser
media_folders:
music:
path: "C:\\Users\\YourUsername\\Music"
label: "My Music"
enabled: true
videos:
path: "C:\\Users\\YourUsername\\Videos"
label: "My Videos"
enabled: true
# Thumbnail size: "small" (150x150), "medium" (300x300), or "both"
thumbnail_size: "medium"
```
### How Playback Works
When you play a file from the Media Browser:
1. The file is opened using the **default system media player** on the PC running the media server
2. This is designed for **remote control scenarios** where you browse media from one device (e.g., Home Assistant dashboard, phone) but want audio to play on the PC
3. The media player must support the **Windows Media Session API** for playback tracking
### Media Player Compatibility
**⚠️ Important Limitation:** Not all media players expose their playback information to the Windows Media Session API. This means some players will open and play the file, but the Media Server UI won't show playback status, track information, or allow remote control.
**✅ Compatible Players** (work with playback tracking):
- **VLC Media Player** - Full support
- **Groove Music** (Windows 10/11 built-in) - Full support
- **Spotify** - Full support (if already running)
- **Chrome/Edge/Firefox** - Full support for web players
- **foobar2000** - Full support (with proper configuration/plugins)
**❌ Limited/No Support:**
- **Windows Media Player Classic** - Opens files but doesn't expose session info
- **Windows Media Player** (classic version) - Limited session support
**Recommendation:** Set **VLC Media Player** or **Groove Music** as your default audio player for the best experience with the Media Browser.
#### Changing Your Default Media Player (Windows)
1. Open Windows Settings → Apps → Default apps
2. Search for "Music player" or "Video player"
3. Select VLC Media Player or Groove Music
4. Files opened from Media Browser will now use the selected player
### API Endpoints
The Media Browser exposes several REST API endpoints:
| Endpoint | Method | Description |
|--------------------------|--------|-----------------------------------|
| `/api/browser/folders` | GET | List configured media folders |
| `/api/browser/browse` | GET | Browse directory contents |
| `/api/browser/metadata` | GET | Get media file metadata |
| `/api/browser/thumbnail` | GET | Get thumbnail image |
| `/api/browser/play` | POST | Open file with default player |
All endpoints require bearer token authentication.
### Security Notes
- **Path Traversal Protection** - All paths are validated to prevent directory traversal attacks
- **Folder Restrictions** - Only configured folders are accessible
- **Authentication Required** - All endpoints require a valid API token
## Requirements
- Python 3.10+
@@ -71,13 +240,17 @@ Requires Termux and Termux:API apps from F-Droid.
python -m media_server.main
```
4. Test the connection:
```bash
curl http://localhost:8765/api/health
```
4. **Open the Web UI** (recommended):
- Navigate to `http://localhost:8765/` in your browser
- Enter your API token from step 2
- Start playing media and control it from the web interface!
5. Test with authentication:
5. Or test via API:
```bash
# Health check (no auth required)
curl http://localhost:8765/api/health
# Get media status
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:8765/api/media/status
```
@@ -92,11 +265,46 @@ Configuration file locations:
```yaml
host: 0.0.0.0
port: 8765
api_token: your-secret-token-here
# API Tokens - Multiple tokens with labels for client identification
api_tokens:
home_assistant: "your-home-assistant-token-here"
mobile: "your-mobile-app-token-here"
web_ui: "your-web-ui-token-here"
poll_interval: 1.0
log_level: INFO
```
### Authentication
The media server supports multiple API tokens with friendly labels. This allows you to:
- Issue different tokens for different clients (Home Assistant, mobile apps, web UI, etc.)
- Identify which client is making requests in the server logs
- Revoke individual tokens without affecting other clients
**Token labels** appear in all server logs, making it easy to track and debug client connections:
```
2026-02-06 03:36:20,806 - media_server.services.websocket_manager - [home_assistant] - INFO - WebSocket client connected
2026-02-06 03:28:24,258 - media_server.routes.scripts - [mobile] - INFO - Executing script: lock_screen
```
**Viewing your tokens:**
```bash
python -m media_server.main --show-token
```
Output:
```
Config directory: C:\Users\...\AppData\Roaming\media-server
API Tokens:
home_assistant B04zhGDjnxH6LIwxL3VOT0F4qORwaipD7LoDyeAG4EU
mobile xyz123...
web_ui abc456...
```
### Environment Variables
All settings can be overridden with environment variables (prefix: `MEDIA_SERVER_`):
@@ -104,10 +312,11 @@ All settings can be overridden with environment variables (prefix: `MEDIA_SERVER
```bash
export MEDIA_SERVER_HOST=0.0.0.0
export MEDIA_SERVER_PORT=8765
export MEDIA_SERVER_API_TOKEN=your-token
export MEDIA_SERVER_LOG_LEVEL=DEBUG
```
**Note:** For multi-token configuration, use the config.yaml file. Environment variables only support single-token mode.
## API Reference
### Health Check
@@ -164,11 +373,16 @@ All control endpoints require authentication and return `{"success": true}` on s
| `/api/media/volume` | POST | `{"volume": 75}` | Set volume (0-100) |
| `/api/media/mute` | POST | - | Toggle mute |
| `/api/media/seek` | POST | `{"position": 60.0}` | Seek to position (seconds) |
| `/api/media/turn_on` | POST | - | Execute on_turn_on callback |
| `/api/media/turn_off` | POST | - | Execute on_turn_off callback |
| `/api/media/toggle` | POST | - | Execute on_toggle callback |
### Script Execution
The server supports executing pre-defined scripts via API.
![Script and Callback Management](docs/scripts-management.PNG)
#### List Scripts
```
@@ -263,6 +477,95 @@ Script configuration options:
| `working_dir` | No | Working directory for the command |
| `shell` | No | Run in shell (default: true) |
### Configuring Callbacks
Callbacks are optional commands executed after media actions. Add them in your `config.yaml`:
```yaml
callbacks:
# Media control callbacks (run after successful action)
on_play:
command: "echo Play triggered"
timeout: 10
shell: true
on_pause:
command: "echo Pause triggered"
timeout: 10
shell: true
on_stop:
command: "echo Stop triggered"
timeout: 10
shell: true
on_next:
command: "echo Next track"
timeout: 10
shell: true
on_previous:
command: "echo Previous track"
timeout: 10
shell: true
on_volume:
command: "echo Volume changed"
timeout: 10
shell: true
on_mute:
command: "echo Mute toggled"
timeout: 10
shell: true
on_seek:
command: "echo Seek triggered"
timeout: 10
shell: true
# Turn on/off/toggle (callback-only actions, no default behavior)
on_turn_on:
command: "echo PC turned on"
timeout: 10
shell: true
on_turn_off:
command: "rundll32.exe user32.dll,LockWorkStation"
timeout: 5
shell: true
on_toggle:
command: "echo Toggle triggered"
timeout: 10
shell: true
```
Available callbacks:
| Callback | Triggered by | Description |
|----------|--------------|-------------|
| `on_play` | `/api/media/play` | After play succeeds |
| `on_pause` | `/api/media/pause` | After pause succeeds |
| `on_stop` | `/api/media/stop` | After stop succeeds |
| `on_next` | `/api/media/next` | After next track succeeds |
| `on_previous` | `/api/media/previous` | After previous track succeeds |
| `on_volume` | `/api/media/volume` | After volume change succeeds |
| `on_mute` | `/api/media/mute` | After mute toggle |
| `on_seek` | `/api/media/seek` | After seek succeeds |
| `on_turn_on` | `/api/media/turn_on` | Callback-only action |
| `on_turn_off` | `/api/media/turn_off` | Callback-only action |
| `on_toggle` | `/api/media/toggle` | Callback-only action |
Callback configuration options:
| Field | Required | Description |
|-------|----------|-------------|
| `command` | Yes | Command to execute |
| `timeout` | No | Execution timeout in seconds (default: 30, max: 300) |
| `working_dir` | No | Working directory for the command |
| `shell` | No | Run in shell (default: true) |
## Running as a Service
### Windows Task Scheduler (Recommended)

View File

@@ -2,8 +2,12 @@
# Copy this file to config.yaml and customize as needed.
# A secure token will be auto-generated on first run if not specified.
# API Token (generate a secure random token)
api_token: "your-secure-token-here"
# API Tokens - Multiple tokens with friendly labels
# This allows you to identify which client is making requests in the logs
api_tokens:
home_assistant: "your-home-assistant-token-here"
mobile: "your-mobile-app-token-here"
web_ui: "your-web-ui-token-here"
# Server settings
host: "0.0.0.0"
@@ -44,4 +48,64 @@ scripts:
label: "Restart"
description: "Restart the PC immediately"
timeout: 10
shell: true
# Callback scripts (executed after media actions)
# All callbacks are optional - if not defined, the action runs without callback
callbacks:
# Media control callbacks (run after successful action)
on_play:
command: "echo Play triggered"
timeout: 10
shell: true
on_pause:
command: "echo Pause triggered"
timeout: 10
shell: true
on_stop:
command: "echo Stop triggered"
timeout: 10
shell: true
on_next:
command: "echo Next track"
timeout: 10
shell: true
on_previous:
command: "echo Previous track"
timeout: 10
shell: true
on_volume:
command: "echo Volume changed"
timeout: 10
shell: true
on_mute:
command: "echo Mute toggled"
timeout: 10
shell: true
on_seek:
command: "echo Seek triggered"
timeout: 10
shell: true
# Turn on/off/toggle (callback-only actions, no default behavior)
on_turn_on:
command: "echo Turn on callback"
timeout: 10
shell: true
on_turn_off:
command: "rundll32.exe user32.dll,LockWorkStation"
timeout: 5
shell: true
on_toggle:
command: "echo Toggle callback"
timeout: 10
shell: true

BIN
docs/media-browser.PNG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
docs/scripts-management.PNG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

BIN
docs/web-ui.PNG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 303 KiB

View File

@@ -1,5 +1,7 @@
"""Authentication middleware and utilities."""
import secrets
from contextvars import ContextVar
from typing import Optional
from fastapi import Depends, HTTPException, Query, Request, status
@@ -9,6 +11,24 @@ from .config import settings
security = HTTPBearer(auto_error=False)
# Context variable to store current request's token label
token_label_var: ContextVar[str] = ContextVar("token_label", default="unknown")
def get_token_label(token: str) -> Optional[str]:
"""Get the label for a token. Returns None if token is invalid.
Args:
token: The token to look up
Returns:
The label for the token, or None if invalid
"""
for label, stored_token in settings.api_tokens.items():
if secrets.compare_digest(stored_token, token):
return label
return None
async def verify_token(
request: Request,
@@ -16,16 +36,19 @@ async def verify_token(
) -> str:
"""Verify the API token from the Authorization header.
Args:
request: The incoming request
credentials: The bearer token credentials
Reuses the label from middleware context when already validated.
Returns:
The validated token
The token label
Raises:
HTTPException: If the token is missing or invalid
"""
# Reuse label already set by middleware to avoid redundant O(n) scan
existing = token_label_var.get("unknown")
if existing != "unknown":
return existing
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -33,14 +56,16 @@ async def verify_token(
headers={"WWW-Authenticate": "Bearer"},
)
if credentials.credentials != settings.api_token:
label = get_token_label(credentials.credentials)
if label is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
return credentials.credentials
token_label_var.set(label)
return label
class TokenAuth:
@@ -54,7 +79,7 @@ class TokenAuth:
request: Request,
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> str | None:
"""Verify the token and return it or raise an exception."""
"""Verify the token and return the label or raise an exception."""
if credentials is None:
if self.auto_error:
raise HTTPException(
@@ -64,7 +89,8 @@ class TokenAuth:
)
return None
if credentials.credentials != settings.api_token:
label = get_token_label(credentials.credentials)
if label is None:
if self.auto_error:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -73,7 +99,9 @@ class TokenAuth:
)
return None
return credentials.credentials
# Set label in context for logging
token_label_var.set(label)
return label
async def verify_token_or_query(
@@ -89,23 +117,32 @@ async def verify_token_or_query(
token: Token from query parameter
Returns:
The validated token
The token label
Raises:
HTTPException: If the token is missing or invalid
"""
# Reuse label already set by middleware
existing = token_label_var.get("unknown")
if existing != "unknown":
return existing
label = None
# Try header first
if credentials is not None:
if credentials.credentials == settings.api_token:
return credentials.credentials
label = get_token_label(credentials.credentials)
# Try query parameter
if token is not None:
if token == settings.api_token:
return token
if label is None and token is not None:
label = get_token_label(token)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing or invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
if label is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing or invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
token_label_var.set(label)
return label

View File

@@ -10,6 +10,23 @@ from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class MediaFolderConfig(BaseModel):
"""Configuration for a media folder."""
path: str = Field(..., description="Absolute path to media folder")
label: str = Field(..., description="Human-readable display label")
enabled: bool = Field(default=True, description="Whether this folder is active")
class CallbackConfig(BaseModel):
"""Configuration for a callback script (no label/description needed)."""
command: str = Field(..., description="Command or script to execute")
timeout: int = Field(default=30, description="Execution timeout in seconds", ge=1, le=300)
working_dir: Optional[str] = Field(default=None, description="Working directory")
shell: bool = Field(default=True, description="Run command in shell")
class ScriptConfig(BaseModel):
"""Configuration for a custom script."""
@@ -37,9 +54,9 @@ class Settings(BaseSettings):
port: int = Field(default=8765, description="Server port")
# Authentication
api_token: str = Field(
default_factory=lambda: secrets.token_urlsafe(32),
description="API authentication token",
api_tokens: dict[str, str] = Field(
default_factory=lambda: {"default": secrets.token_urlsafe(32)},
description="Named API tokens for access control (label: token pairs)",
)
# Media controller settings
@@ -47,6 +64,12 @@ class Settings(BaseSettings):
default=1.0, description="Media status poll interval in seconds"
)
# Audio device settings
audio_device: Optional[str] = Field(
default=None,
description="Audio device name to control (None = default device). Use /api/audio/devices to list available devices.",
)
# Logging
log_level: str = Field(default="INFO", description="Logging level")
@@ -56,6 +79,24 @@ class Settings(BaseSettings):
description="Custom scripts that can be executed via API",
)
# Callback scripts (executed by integration events, not shown in UI)
callbacks: dict[str, CallbackConfig] = Field(
default_factory=dict,
description="Callback scripts executed by integration events (on_turn_on, on_turn_off, on_toggle)",
)
# Media folders for browsing
media_folders: dict[str, MediaFolderConfig] = Field(
default_factory=dict,
description="Media folders available for browsing in the media browser",
)
# Thumbnail settings
thumbnail_size: str = Field(
default="medium",
description='Thumbnail size: "small" (150x150), "medium" (300x300), or "both"',
)
@classmethod
def load_from_yaml(cls, path: Optional[Path] = None) -> "Settings":
"""Load settings from a YAML configuration file."""
@@ -107,9 +148,14 @@ def generate_default_config(path: Optional[Path] = None) -> Path:
config = {
"host": "0.0.0.0",
"port": 8765,
"api_token": secrets.token_urlsafe(32),
"api_tokens": {
"default": secrets.token_urlsafe(32),
},
"poll_interval": 1.0,
"log_level": "INFO",
# Audio device to control (use GET /api/audio/devices to list available devices)
# Set to null or remove to use default device
# "audio_device": "Speakers (Realtek",
"scripts": {
"example_script": {
"command": "echo Hello from Media Server!",

View File

@@ -0,0 +1,392 @@
"""Thread-safe configuration file manager for runtime script updates."""
import logging
import os
import threading
from pathlib import Path
from typing import Optional
import yaml
from .config import CallbackConfig, MediaFolderConfig, ScriptConfig, settings
logger = logging.getLogger(__name__)
class ConfigManager:
"""Thread-safe configuration file manager."""
def __init__(self, config_path: Optional[Path] = None):
"""Initialize the config manager.
Args:
config_path: Path to config file. If None, will search standard locations.
"""
self._lock = threading.Lock()
self._config_path = config_path or self._find_config_path()
logger.info(f"ConfigManager initialized with path: {self._config_path}")
def _find_config_path(self) -> Path:
"""Find the active config file path.
Returns:
Path to the config file.
Raises:
FileNotFoundError: If no config file is found.
"""
# Same search logic as Settings.load_from_yaml()
search_paths = [
Path("config.yaml"),
Path("config.yml"),
]
# Add platform-specific config directory
if os.name == "nt": # Windows
appdata = os.environ.get("APPDATA", "")
if appdata:
search_paths.append(Path(appdata) / "media-server" / "config.yaml")
else: # Linux/Unix/macOS
search_paths.append(Path.home() / ".config" / "media-server" / "config.yaml")
search_paths.append(Path("/etc/media-server/config.yaml"))
for search_path in search_paths:
if search_path.exists():
return search_path
# If not found, use the default location
if os.name == "nt":
default_path = Path(os.environ.get("APPDATA", "")) / "media-server" / "config.yaml"
else:
default_path = Path.home() / ".config" / "media-server" / "config.yaml"
logger.warning(f"No config file found, using default path: {default_path}")
return default_path
def add_script(self, name: str, config: ScriptConfig) -> None:
"""Add a new script to config.
Args:
name: Script name (must be unique).
config: Script configuration.
Raises:
ValueError: If script already exists.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
data = {}
else:
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if script already exists
if "scripts" in data and name in data["scripts"]:
raise ValueError(f"Script '{name}' already exists")
# Add script
if "scripts" not in data:
data["scripts"] = {}
data["scripts"][name] = config.model_dump(exclude_none=True)
# Write YAML
self._config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.scripts[name] = config
logger.info(f"Script '{name}' added to config")
def update_script(self, name: str, config: ScriptConfig) -> None:
"""Update an existing script.
Args:
name: Script name.
config: New script configuration.
Raises:
ValueError: If script does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if script exists
if "scripts" not in data or name not in data["scripts"]:
raise ValueError(f"Script '{name}' does not exist")
# Update script
data["scripts"][name] = config.model_dump(exclude_none=True)
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.scripts[name] = config
logger.info(f"Script '{name}' updated in config")
def delete_script(self, name: str) -> None:
"""Delete a script from config.
Args:
name: Script name.
Raises:
ValueError: If script does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if script exists
if "scripts" not in data or name not in data["scripts"]:
raise ValueError(f"Script '{name}' does not exist")
# Delete script
del data["scripts"][name]
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
if name in settings.scripts:
del settings.scripts[name]
logger.info(f"Script '{name}' deleted from config")
def add_callback(self, name: str, config: CallbackConfig) -> None:
"""Add a new callback to config.
Args:
name: Callback name (must be unique).
config: Callback configuration.
Raises:
ValueError: If callback already exists.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
data = {}
else:
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if callback already exists
if "callbacks" in data and name in data["callbacks"]:
raise ValueError(f"Callback '{name}' already exists")
# Add callback
if "callbacks" not in data:
data["callbacks"] = {}
data["callbacks"][name] = config.model_dump(exclude_none=True)
# Write YAML
self._config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.callbacks[name] = config
logger.info(f"Callback '{name}' added to config")
def update_callback(self, name: str, config: CallbackConfig) -> None:
"""Update an existing callback.
Args:
name: Callback name.
config: New callback configuration.
Raises:
ValueError: If callback does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if callback exists
if "callbacks" not in data or name not in data["callbacks"]:
raise ValueError(f"Callback '{name}' does not exist")
# Update callback
data["callbacks"][name] = config.model_dump(exclude_none=True)
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.callbacks[name] = config
logger.info(f"Callback '{name}' updated in config")
def delete_callback(self, name: str) -> None:
"""Delete a callback from config.
Args:
name: Callback name.
Raises:
ValueError: If callback does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if callback exists
if "callbacks" not in data or name not in data["callbacks"]:
raise ValueError(f"Callback '{name}' does not exist")
# Delete callback
del data["callbacks"][name]
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
if name in settings.callbacks:
del settings.callbacks[name]
logger.info(f"Callback '{name}' deleted from config")
def add_media_folder(self, folder_id: str, config: MediaFolderConfig) -> None:
"""Add a new media folder to config.
Args:
folder_id: Folder ID (must be unique).
config: Media folder configuration.
Raises:
ValueError: If folder already exists.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
data = {}
else:
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if folder already exists
if "media_folders" in data and folder_id in data["media_folders"]:
raise ValueError(f"Media folder '{folder_id}' already exists")
# Add folder
if "media_folders" not in data:
data["media_folders"] = {}
data["media_folders"][folder_id] = config.model_dump(exclude_none=True)
# Write YAML
self._config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.media_folders[folder_id] = config
logger.info(f"Media folder '{folder_id}' added to config")
def update_media_folder(self, folder_id: str, config: MediaFolderConfig) -> None:
"""Update an existing media folder.
Args:
folder_id: Folder ID.
config: New media folder configuration.
Raises:
ValueError: If folder does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if folder exists
if "media_folders" not in data or folder_id not in data["media_folders"]:
raise ValueError(f"Media folder '{folder_id}' does not exist")
# Update folder
data["media_folders"][folder_id] = config.model_dump(exclude_none=True)
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
settings.media_folders[folder_id] = config
logger.info(f"Media folder '{folder_id}' updated in config")
def delete_media_folder(self, folder_id: str) -> None:
"""Delete a media folder from config.
Args:
folder_id: Folder ID.
Raises:
ValueError: If folder does not exist.
IOError: If config file cannot be written.
"""
with self._lock:
# Read YAML
if not self._config_path.exists():
raise ValueError(f"Config file not found: {self._config_path}")
with open(self._config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# Check if folder exists
if "media_folders" not in data or folder_id not in data["media_folders"]:
raise ValueError(f"Media folder '{folder_id}' does not exist")
# Delete folder
del data["media_folders"][folder_id]
# Write YAML
with open(self._config_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
# Update in-memory settings
if folder_id in settings.media_folders:
del settings.media_folders[folder_id]
logger.info(f"Media folder '{folder_id}' deleted from config")
# Global config manager instance
config_manager = ConfigManager()

View File

@@ -4,24 +4,42 @@ import argparse
import logging
import sys
from contextlib import asynccontextmanager
from pathlib import Path
import uvicorn
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from . import __version__
from .auth import get_token_label, token_label_var
from .config import settings, generate_default_config, get_config_dir
from .routes import health_router, media_router, scripts_router
from .routes import audio_router, browser_router, callbacks_router, health_router, media_router, scripts_router
from .services import get_media_controller
from .services.websocket_manager import ws_manager
class TokenLabelFilter(logging.Filter):
"""Add token label to log records."""
def filter(self, record):
record.token_label = token_label_var.get("unknown")
return True
def setup_logging():
"""Configure application logging."""
"""Configure application logging with token labels."""
# Create filter and handler
token_filter = TokenLabelFilter()
handler = logging.StreamHandler(sys.stdout)
handler.addFilter(token_filter)
logging.basicConfig(
level=getattr(logging, settings.log_level.upper()),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
format="%(asctime)s - %(name)s - [%(token_label)s] - %(levelname)s - %(message)s",
handlers=[handler],
)
@@ -31,7 +49,10 @@ async def lifespan(app: FastAPI):
setup_logging()
logger = logging.getLogger(__name__)
logger.info(f"Media Server starting on {settings.host}:{settings.port}")
logger.info(f"API Token: {settings.api_token[:8]}...")
# Log all configured tokens
for label, token in settings.api_tokens.items():
logger.info(f"API Token [{label}]: {token[:8]}...")
# Start WebSocket status monitor
controller = get_media_controller()
@@ -54,6 +75,9 @@ def create_app() -> FastAPI:
lifespan=lifespan,
)
# Compress responses > 1KB
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Add CORS middleware for cross-origin requests
app.add_middleware(
CORSMiddleware,
@@ -63,11 +87,49 @@ def create_app() -> FastAPI:
allow_headers=["*"],
)
# Add token logging middleware
@app.middleware("http")
async def token_logging_middleware(request: Request, call_next):
"""Extract token label and set in context for logging."""
token_label = "unknown"
# Try Authorization header
auth_header = request.headers.get("authorization", "")
if auth_header.startswith("Bearer "):
token = auth_header[7:]
label = get_token_label(token)
if label:
token_label = label
# Try query parameter (for artwork endpoint)
elif "token" in request.query_params:
token = request.query_params["token"]
label = get_token_label(token)
if label:
token_label = label
token_label_var.set(token_label)
response = await call_next(request)
return response
# Register routers
app.include_router(audio_router)
app.include_router(browser_router)
app.include_router(callbacks_router)
app.include_router(health_router)
app.include_router(media_router)
app.include_router(scripts_router)
# Mount static files and serve UI at root
static_dir = Path(__file__).parent / "static"
if static_dir.exists():
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
@app.get("/", include_in_schema=False)
async def serve_ui():
"""Serve the Web UI."""
return FileResponse(static_dir / "index.html")
return app
@@ -108,8 +170,10 @@ def main():
return
if args.show_token:
print(f"API Token: {settings.api_token}")
print(f"Config directory: {get_config_dir()}")
print(f"\nAPI Tokens:")
for label, token in settings.api_tokens.items():
print(f" {label:20} {token}")
return
uvicorn.run(

View File

@@ -1,7 +1,10 @@
"""API route modules."""
from .audio import router as audio_router
from .browser import router as browser_router
from .callbacks import router as callbacks_router
from .health import router as health_router
from .media import router as media_router
from .scripts import router as scripts_router
__all__ = ["health_router", "media_router", "scripts_router"]
__all__ = ["audio_router", "browser_router", "callbacks_router", "health_router", "media_router", "scripts_router"]

View File

@@ -0,0 +1,28 @@
"""Audio device API endpoints."""
import logging
from fastapi import APIRouter, Depends
from ..auth import verify_token
from ..services import get_audio_devices
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/audio", tags=["audio"])
@router.get("/devices")
async def list_audio_devices(_: str = Depends(verify_token)) -> list[dict[str, str]]:
"""List available audio output devices.
Returns a list of audio devices with their IDs and friendly names.
Use the device name in the `audio_device` config option to control
a specific device instead of the default one.
Returns:
List of audio devices with id and name
"""
devices = get_audio_devices()
logger.debug("Found %d audio devices", len(devices))
return devices

View File

@@ -0,0 +1,567 @@
"""Browser API routes for media file browsing."""
import asyncio
import logging
import tempfile
from pathlib import Path
from typing import Optional
from urllib.parse import unquote
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field
from ..auth import verify_token, verify_token_or_query
from ..config import MediaFolderConfig, settings
from ..config_manager import config_manager
from ..services.browser_service import BrowserService
from ..services.metadata_service import MetadataService
from ..services.thumbnail_service import ThumbnailService
from ..services import get_media_controller
from ..services.websocket_manager import ws_manager
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/browser", tags=["browser"])
async def _broadcast_after_open(controller, label: str, max_wait: float = 2.0) -> None:
"""Poll until media session registers, then broadcast status update.
Fires as a background task so the HTTP response returns immediately.
"""
try:
interval = 0.3
elapsed = 0.0
while elapsed < max_wait:
await asyncio.sleep(interval)
elapsed += interval
status = await controller.get_status()
if status.state in ("playing", "paused"):
break
status_dict = status.model_dump()
await ws_manager.broadcast({"type": "status", "data": status_dict})
logger.info(f"Broadcasted status update after opening: {label}")
except Exception as e:
logger.warning(f"Failed to broadcast status after opening {label}: {e}")
# Request/Response Models
class FolderCreateRequest(BaseModel):
"""Request model for creating a media folder."""
folder_id: str = Field(..., description="Unique folder ID")
label: str = Field(..., description="Display label")
path: str = Field(..., description="Absolute path to media folder")
enabled: bool = Field(default=True, description="Whether folder is enabled")
class FolderUpdateRequest(BaseModel):
"""Request model for updating a media folder."""
label: str = Field(..., description="Display label")
path: str = Field(..., description="Absolute path to media folder")
enabled: bool = Field(default=True, description="Whether folder is enabled")
class PlayRequest(BaseModel):
"""Request model for playing a media file."""
path: str = Field(..., description="Full path to the media file")
class PlayFolderRequest(BaseModel):
"""Request model for playing all media files in a folder."""
folder_id: str = Field(..., description="Media folder ID")
path: str = Field(default="", description="Path relative to folder root")
# Folder Management Endpoints
@router.get("/folders")
async def list_folders(_: str = Depends(verify_token)):
"""List all configured media folders.
Returns:
Dictionary of folder configurations.
"""
folders = {}
for folder_id, config in settings.media_folders.items():
folders[folder_id] = {
"id": folder_id,
"label": config.label,
"path": config.path,
"enabled": config.enabled,
}
return folders
@router.post("/folders/create")
async def create_folder(
request: FolderCreateRequest,
_: str = Depends(verify_token),
):
"""Create a new media folder configuration.
Args:
request: Folder creation request.
Returns:
Success message.
Raises:
HTTPException: If folder already exists or validation fails.
"""
try:
# Validate folder_id format (alphanumeric and underscore only)
if not request.folder_id.replace("_", "").isalnum():
raise HTTPException(
status_code=400,
detail="Folder ID must contain only alphanumeric characters and underscores",
)
# Validate path exists
path = Path(request.path)
if not path.exists():
raise HTTPException(status_code=400, detail=f"Path does not exist: {request.path}")
if not path.is_dir():
raise HTTPException(status_code=400, detail=f"Path is not a directory: {request.path}")
# Create config
config = MediaFolderConfig(
path=request.path,
label=request.label,
enabled=request.enabled,
)
# Add to config manager
config_manager.add_media_folder(request.folder_id, config)
return {
"success": True,
"message": f"Media folder '{request.folder_id}' created successfully",
}
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error creating media folder: {e}")
raise HTTPException(status_code=500, detail="Failed to create media folder")
@router.put("/folders/update/{folder_id}")
async def update_folder(
folder_id: str,
request: FolderUpdateRequest,
_: str = Depends(verify_token),
):
"""Update an existing media folder configuration.
Args:
folder_id: ID of the folder to update.
request: Folder update request.
Returns:
Success message.
Raises:
HTTPException: If folder doesn't exist or validation fails.
"""
try:
# Validate path exists
path = Path(request.path)
if not path.exists():
raise HTTPException(status_code=400, detail=f"Path does not exist: {request.path}")
if not path.is_dir():
raise HTTPException(status_code=400, detail=f"Path is not a directory: {request.path}")
# Create config
config = MediaFolderConfig(
path=request.path,
label=request.label,
enabled=request.enabled,
)
# Update config manager
config_manager.update_media_folder(folder_id, config)
return {
"success": True,
"message": f"Media folder '{folder_id}' updated successfully",
}
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error updating media folder: {e}")
raise HTTPException(status_code=500, detail="Failed to update media folder")
@router.delete("/folders/delete/{folder_id}")
async def delete_folder(
folder_id: str,
_: str = Depends(verify_token),
):
"""Delete a media folder configuration.
Args:
folder_id: ID of the folder to delete.
Returns:
Success message.
Raises:
HTTPException: If folder doesn't exist.
"""
try:
config_manager.delete_media_folder(folder_id)
return {
"success": True,
"message": f"Media folder '{folder_id}' deleted successfully",
}
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"Error deleting media folder: {e}")
raise HTTPException(status_code=500, detail="Failed to delete media folder")
# Browse Endpoints
@router.get("/browse")
async def browse(
folder_id: str = Query(..., description="Media folder ID"),
path: str = Query(default="", description="Path relative to folder root"),
offset: int = Query(default=0, ge=0, description="Pagination offset"),
limit: int = Query(default=100, ge=1, le=1000, description="Pagination limit"),
nocache: bool = Query(default=False, description="Bypass directory cache"),
_: str = Depends(verify_token),
):
"""Browse a directory and list files/folders.
Args:
folder_id: ID of the media folder.
path: Path to browse (URL-encoded, relative to folder root).
offset: Pagination offset.
limit: Maximum items to return.
Returns:
Directory listing with items and metadata.
Raises:
HTTPException: If path validation fails or directory not accessible.
"""
try:
# URL decode the path
decoded_path = unquote(path)
# Browse directory
result = BrowserService.browse_directory(
folder_id=folder_id,
path=decoded_path,
offset=offset,
limit=limit,
nocache=nocache,
)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=str(e))
except (OSError, PermissionError) as e:
# Network share unavailable or access denied
logger.warning(f"Folder temporarily unavailable: {e}")
raise HTTPException(
status_code=503,
detail=f"Folder is temporarily unavailable. It may be a network share that is not accessible at the moment."
)
except Exception as e:
logger.error(f"Error browsing directory (type: {type(e).__name__}): {e}")
raise HTTPException(status_code=500, detail="Failed to browse directory")
# Metadata Endpoint
@router.get("/metadata")
async def get_metadata(
path: str = Query(..., description="Full path to media file (URL-encoded)"),
_: str = Depends(verify_token),
):
"""Get metadata for a media file.
Args:
path: Full path to the media file (URL-encoded).
Returns:
Media file metadata.
Raises:
HTTPException: If file not found or metadata extraction fails.
"""
try:
# URL decode the path
decoded_path = unquote(path)
file_path = Path(decoded_path)
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found")
if not file_path.is_file():
raise HTTPException(status_code=400, detail="Path is not a file")
# Extract metadata in executor (blocking operation)
loop = asyncio.get_event_loop()
metadata = await loop.run_in_executor(
None,
MetadataService.extract_metadata,
file_path,
)
return metadata
except HTTPException:
raise
except Exception as e:
logger.error(f"Error extracting metadata: {e}")
raise HTTPException(status_code=500, detail="Failed to extract metadata")
# Thumbnail Endpoint
@router.get("/thumbnail")
async def get_thumbnail(
path: str = Query(..., description="Full path to media file (URL-encoded)"),
size: str = Query(default="medium", description='Thumbnail size: "small" or "medium"'),
_: str = Depends(verify_token),
):
"""Get thumbnail for a media file.
Args:
path: Full path to the media file (URL-encoded).
size: Thumbnail size ("small" or "medium").
Returns:
JPEG image bytes.
Raises:
HTTPException: If file not found or thumbnail generation fails.
"""
try:
# URL decode the path
decoded_path = unquote(path)
file_path = Path(decoded_path)
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found")
if not file_path.is_file():
raise HTTPException(status_code=400, detail="Path is not a file")
# Validate size
if size not in ("small", "medium"):
size = "medium"
# Get thumbnail
thumbnail_data = await ThumbnailService.get_thumbnail(file_path, size)
if thumbnail_data is None:
return Response(status_code=204)
# Calculate ETag (hash of path + mtime)
import hashlib
stat = file_path.stat()
etag_data = f"{file_path}:{stat.st_mtime}:{size}".encode()
etag = hashlib.md5(etag_data).hexdigest()
# Return image with caching headers
return Response(
content=thumbnail_data,
media_type="image/jpeg",
headers={
"ETag": f'"{etag}"',
"Cache-Control": "public, max-age=86400", # 24 hours
},
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error generating thumbnail: {e}")
raise HTTPException(status_code=500, detail="Failed to generate thumbnail")
# Playback Endpoint
@router.post("/play")
async def play_file(
request: PlayRequest,
_: str = Depends(verify_token),
):
"""Open a media file with the default system player.
Args:
request: Play request with file path.
Returns:
Success message.
Raises:
HTTPException: If file not found or playback fails.
"""
try:
file_path = Path(request.path)
# Validate file exists
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found")
if not file_path.is_file():
raise HTTPException(status_code=400, detail="Path is not a file")
# Validate file is a media file
if not BrowserService.is_media_file(file_path):
raise HTTPException(status_code=400, detail="File is not a media file")
# Get media controller and open file
controller = get_media_controller()
success = await controller.open_file(str(file_path))
if not success:
raise HTTPException(status_code=500, detail="Failed to open file")
# Poll until player registers with media session API (up to 2s)
asyncio.create_task(_broadcast_after_open(controller, file_path.name))
return {
"success": True,
"message": f"Playing {file_path.name}",
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error playing file: {e}")
raise HTTPException(status_code=500, detail="Failed to play file")
# Play Folder Endpoint (M3U playlist)
@router.post("/play-folder")
async def play_folder(
request: PlayFolderRequest,
_: str = Depends(verify_token),
):
"""Play all media files in a folder by generating an M3U playlist.
Args:
request: Play folder request with folder_id and path.
Returns:
Success message with file count.
Raises:
HTTPException: If folder not found or playback fails.
"""
try:
decoded_path = unquote(request.path)
full_path = BrowserService.validate_path(request.folder_id, decoded_path)
if not full_path.is_dir():
raise HTTPException(status_code=400, detail="Path is not a directory")
# Collect all media files sorted by name
media_files = sorted(
[f for f in full_path.iterdir() if f.is_file() and BrowserService.is_media_file(f)],
key=lambda f: f.name.lower(),
)
if not media_files:
raise HTTPException(status_code=404, detail="No media files found in this folder")
# Generate M3U playlist with absolute paths and EXTINF entries
# Written to local temp dir to avoid extra SMB file handle on network shares
# Uses utf-8-sig (BOM) so players detect encoding properly
lines = ["#EXTM3U"]
for f in media_files:
lines.append(f"#EXTINF:-1,{f.stem}")
lines.append(str(f))
m3u_content = "\r\n".join(lines) + "\r\n"
playlist_path = Path(tempfile.gettempdir()) / ".media_server_playlist.m3u"
playlist_path.write_text(m3u_content, encoding="utf-8-sig")
# Open playlist with default player
controller = get_media_controller()
success = await controller.open_file(playlist_path)
if not success:
raise HTTPException(status_code=500, detail="Failed to open playlist")
# Poll until player registers with media session API (up to 2s)
asyncio.create_task(_broadcast_after_open(controller, f"playlist ({len(media_files)} files)"))
return {
"success": True,
"message": f"Playing {len(media_files)} files",
"count": len(media_files),
}
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"Error playing folder: {e}")
raise HTTPException(status_code=500, detail="Failed to play folder")
# Download Endpoint
@router.get("/download")
async def download_file(
folder_id: str = Query(..., description="Media folder ID"),
path: str = Query(..., description="File path relative to folder root (URL-encoded)"),
_: str = Depends(verify_token_or_query),
):
"""Download a media file.
Args:
folder_id: ID of the media folder.
path: Path to the file (URL-encoded, relative to folder root).
Returns:
File download response.
Raises:
HTTPException: If file not found or not a media file.
"""
try:
decoded_path = unquote(path)
file_path = BrowserService.validate_path(folder_id, decoded_path)
if not file_path.is_file():
raise HTTPException(status_code=400, detail="Path is not a file")
if not BrowserService.is_media_file(file_path):
raise HTTPException(status_code=400, detail="File is not a media file")
return FileResponse(
path=file_path,
filename=file_path.name,
media_type="application/octet-stream",
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except FileNotFoundError as e:
raise HTTPException(status_code=404, detail=str(e))
except HTTPException:
raise
except Exception as e:
logger.error(f"Error downloading file: {e}")
raise HTTPException(status_code=500, detail="Failed to download file")

View File

@@ -0,0 +1,339 @@
"""Callback management API endpoints."""
import asyncio
import logging
import re
import subprocess
import time
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from ..auth import verify_token
from ..config import CallbackConfig, settings
from ..config_manager import config_manager
router = APIRouter(prefix="/api/callbacks", tags=["callbacks"])
logger = logging.getLogger(__name__)
class CallbackInfo(BaseModel):
"""Information about a configured callback."""
name: str
command: str
timeout: int
working_dir: str | None = None
shell: bool
class CallbackCreateRequest(BaseModel):
"""Request model for creating or updating a callback."""
command: str = Field(..., description="Command to execute", min_length=1)
timeout: int = Field(default=30, description="Execution timeout in seconds", ge=1, le=300)
working_dir: str | None = Field(default=None, description="Working directory")
shell: bool = Field(default=True, description="Run command in shell")
class CallbackExecuteResponse(BaseModel):
"""Response model for callback execution."""
success: bool
callback: str
exit_code: int | None = None
stdout: str = ""
stderr: str = ""
error: str | None = None
execution_time: float | None = None
def _validate_callback_name(name: str) -> None:
"""Validate callback name.
Args:
name: Callback name to validate.
Raises:
HTTPException: If name is invalid.
"""
# All available callback events
valid_names = {
"on_play",
"on_pause",
"on_stop",
"on_next",
"on_previous",
"on_volume",
"on_mute",
"on_seek",
"on_turn_on",
"on_turn_off",
"on_toggle",
}
if name not in valid_names:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Callback name must be one of: {', '.join(sorted(valid_names))}",
)
@router.get("/list")
async def list_callbacks(_: str = Depends(verify_token)) -> list[CallbackInfo]:
"""List all configured callbacks.
Returns:
List of configured callbacks.
"""
return [
CallbackInfo(
name=name,
command=config.command,
timeout=config.timeout,
working_dir=config.working_dir,
shell=config.shell,
)
for name, config in settings.callbacks.items()
]
@router.post("/execute/{callback_name}")
async def execute_callback(
callback_name: str,
_: str = Depends(verify_token),
) -> CallbackExecuteResponse:
"""Execute a callback for debugging purposes.
Args:
callback_name: Name of the callback to execute
Returns:
Execution result including stdout, stderr, and exit code
"""
# Validate callback name
_validate_callback_name(callback_name)
# Check if callback exists
if callback_name not in settings.callbacks:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Callback '{callback_name}' not found. Use /api/callbacks/list to see configured callbacks.",
)
callback_config = settings.callbacks[callback_name]
logger.info(f"Executing callback for debugging: {callback_name}")
try:
# Execute in thread pool to not block
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None,
lambda: _run_callback(
command=callback_config.command,
timeout=callback_config.timeout,
shell=callback_config.shell,
working_dir=callback_config.working_dir,
),
)
return CallbackExecuteResponse(
success=result["exit_code"] == 0,
callback=callback_name,
exit_code=result["exit_code"],
stdout=result["stdout"],
stderr=result["stderr"],
execution_time=result.get("execution_time"),
)
except Exception as e:
logger.error(f"Callback execution error: {e}")
return CallbackExecuteResponse(
success=False,
callback=callback_name,
error=str(e),
)
def _run_callback(
command: str,
timeout: int,
shell: bool,
working_dir: str | None,
) -> dict[str, Any]:
"""Run a callback synchronously.
Args:
command: Command to execute
timeout: Timeout in seconds
shell: Whether to run in shell
working_dir: Working directory
Returns:
Dict with exit_code, stdout, stderr, execution_time
"""
start_time = time.time()
try:
result = subprocess.run(
command,
shell=shell,
cwd=working_dir,
capture_output=True,
text=True,
timeout=timeout,
)
execution_time = time.time() - start_time
return {
"exit_code": result.returncode,
"stdout": result.stdout[:10000], # Limit output size
"stderr": result.stderr[:10000],
"execution_time": execution_time,
}
except subprocess.TimeoutExpired:
execution_time = time.time() - start_time
return {
"exit_code": -1,
"stdout": "",
"stderr": f"Callback timed out after {timeout} seconds",
"execution_time": execution_time,
}
except Exception as e:
execution_time = time.time() - start_time
return {
"exit_code": -1,
"stdout": "",
"stderr": str(e),
"execution_time": execution_time,
}
@router.post("/create/{callback_name}")
async def create_callback(
callback_name: str,
request: CallbackCreateRequest,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Create a new callback.
Args:
callback_name: Callback event name (on_turn_on, on_turn_off, on_toggle).
request: Callback configuration.
Returns:
Success response with callback name.
Raises:
HTTPException: If callback already exists or name is invalid.
"""
# Validate name
_validate_callback_name(callback_name)
# Check if callback already exists
if callback_name in settings.callbacks:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Callback '{callback_name}' already exists. Use PUT /api/callbacks/update/{callback_name} to update it.",
)
# Create callback config
callback_config = CallbackConfig(**request.model_dump())
# Add to config file and in-memory
try:
config_manager.add_callback(callback_name, callback_config)
except Exception as e:
logger.error(f"Failed to add callback '{callback_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to add callback: {str(e)}",
)
logger.info(f"Callback '{callback_name}' created successfully")
return {"success": True, "callback": callback_name}
@router.put("/update/{callback_name}")
async def update_callback(
callback_name: str,
request: CallbackCreateRequest,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Update an existing callback.
Args:
callback_name: Callback event name.
request: Updated callback configuration.
Returns:
Success response with callback name.
Raises:
HTTPException: If callback does not exist.
"""
# Validate name
_validate_callback_name(callback_name)
# Check if callback exists
if callback_name not in settings.callbacks:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Callback '{callback_name}' not found. Use POST /api/callbacks/create/{callback_name} to create it.",
)
# Create updated callback config
callback_config = CallbackConfig(**request.model_dump())
# Update config file and in-memory
try:
config_manager.update_callback(callback_name, callback_config)
except Exception as e:
logger.error(f"Failed to update callback '{callback_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to update callback: {str(e)}",
)
logger.info(f"Callback '{callback_name}' updated successfully")
return {"success": True, "callback": callback_name}
@router.delete("/delete/{callback_name}")
async def delete_callback(
callback_name: str,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Delete a callback.
Args:
callback_name: Callback event name.
Returns:
Success response with callback name.
Raises:
HTTPException: If callback does not exist.
"""
# Validate name
_validate_callback_name(callback_name)
# Check if callback exists
if callback_name not in settings.callbacks:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Callback '{callback_name}' not found",
)
# Delete from config file and in-memory
try:
config_manager.delete_callback(callback_name)
except Exception as e:
logger.error(f"Failed to delete callback '{callback_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to delete callback: {str(e)}",
)
logger.info(f"Callback '{callback_name}' deleted successfully")
return {"success": True, "callback": callback_name}

View File

@@ -1,5 +1,6 @@
"""Media control API endpoints."""
import asyncio
import logging
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
@@ -17,6 +18,39 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/media", tags=["media"])
def _run_callback(callback_name: str) -> None:
"""Fire-and-forget a callback if configured. Failures are logged but don't block."""
if not settings.callbacks or callback_name not in settings.callbacks:
return
async def _execute():
from .scripts import _run_script
try:
callback = settings.callbacks[callback_name]
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None,
lambda: _run_script(
command=callback.command,
timeout=callback.timeout,
shell=callback.shell,
working_dir=callback.working_dir,
),
)
if result["exit_code"] != 0:
logger.warning(
"Callback %s failed with exit code %s: %s",
callback_name,
result["exit_code"],
result["stderr"],
)
except Exception as e:
logger.error("Callback %s error: %s", callback_name, e)
asyncio.create_task(_execute())
@router.get("/status", response_model=MediaStatus)
async def get_media_status(_: str = Depends(verify_token)) -> MediaStatus:
"""Get current media playback status.
@@ -42,6 +76,7 @@ async def play(_: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to start playback - no active media session",
)
_run_callback("on_play")
return {"success": True}
@@ -59,6 +94,7 @@ async def pause(_: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to pause - no active media session",
)
_run_callback("on_pause")
return {"success": True}
@@ -76,6 +112,7 @@ async def stop(_: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to stop - no active media session",
)
_run_callback("on_stop")
return {"success": True}
@@ -93,6 +130,7 @@ async def next_track(_: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to skip - no active media session",
)
_run_callback("on_next")
return {"success": True}
@@ -110,6 +148,7 @@ async def previous_track(_: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to go back - no active media session",
)
_run_callback("on_previous")
return {"success": True}
@@ -132,6 +171,7 @@ async def set_volume(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to set volume",
)
_run_callback("on_volume")
return {"success": True, "volume": request.volume}
@@ -144,6 +184,7 @@ async def toggle_mute(_: str = Depends(verify_token)) -> dict:
"""
controller = get_media_controller()
muted = await controller.toggle_mute()
_run_callback("on_mute")
return {"success": True, "muted": muted}
@@ -164,9 +205,43 @@ async def seek(request: SeekRequest, _: str = Depends(verify_token)) -> dict:
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to seek - no active media session or seek not supported",
)
_run_callback("on_seek")
return {"success": True, "position": request.position}
@router.post("/turn_on")
async def turn_on(_: str = Depends(verify_token)) -> dict:
"""Execute turn on callback if configured.
Returns:
Success status
"""
_run_callback("on_turn_on")
return {"success": True}
@router.post("/turn_off")
async def turn_off(_: str = Depends(verify_token)) -> dict:
"""Execute turn off callback if configured.
Returns:
Success status
"""
_run_callback("on_turn_off")
return {"success": True}
@router.post("/toggle")
async def toggle(_: str = Depends(verify_token)) -> dict:
"""Execute toggle callback if configured.
Returns:
Success status
"""
_run_callback("on_toggle")
return {"success": True}
@router.get("/artwork")
async def get_artwork(_: str = Depends(verify_token_or_query)) -> Response:
"""Get the current album artwork.
@@ -213,10 +288,16 @@ async def websocket_endpoint(
- {"type": "get_status"} - Request current status
"""
# Verify token
if token != settings.api_token:
from ..auth import get_token_label, token_label_var
label = get_token_label(token) if token else None
if label is None:
await websocket.close(code=4001, reason="Invalid authentication token")
return
# Set label in context for logging
token_label_var.set(label)
await ws_manager.connect(websocket)
try:
@@ -234,6 +315,12 @@ async def websocket_endpoint(
"type": "status",
"data": status_data.model_dump(),
})
elif data.get("type") == "volume":
# Low-latency volume control via WebSocket
volume = data.get("volume")
if volume is not None:
controller = get_media_controller()
await controller.set_volume(int(volume))
except WebSocketDisconnect:
await ws_manager.disconnect(websocket)

View File

@@ -2,14 +2,18 @@
import asyncio
import logging
import re
import subprocess
import time
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from ..auth import verify_token
from ..config import settings
from ..config import ScriptConfig, settings
from ..config_manager import config_manager
from ..services.websocket_manager import ws_manager
router = APIRouter(prefix="/api/scripts", tags=["scripts"])
logger = logging.getLogger(__name__)
@@ -30,6 +34,7 @@ class ScriptExecuteResponse(BaseModel):
stdout: str = ""
stderr: str = ""
error: str | None = None
execution_time: float | None = None
class ScriptInfo(BaseModel):
@@ -37,6 +42,7 @@ class ScriptInfo(BaseModel):
name: str
label: str
command: str
description: str
icon: str | None = None
timeout: int
@@ -53,6 +59,7 @@ async def list_scripts(_: str = Depends(verify_token)) -> list[ScriptInfo]:
ScriptInfo(
name=name,
label=config.label or name.replace("_", " ").title(),
command=config.command,
description=config.description,
icon=config.icon,
timeout=config.timeout,
@@ -82,7 +89,6 @@ async def execute_script(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Script '{script_name}' not found. Use /api/scripts/list to see available scripts.",
)
script_config = settings.scripts[script_name]
args = request.args if request else []
@@ -113,6 +119,7 @@ async def execute_script(
exit_code=result["exit_code"],
stdout=result["stdout"],
stderr=result["stderr"],
execution_time=result.get("execution_time"),
)
except Exception as e:
@@ -139,8 +146,9 @@ def _run_script(
working_dir: Working directory
Returns:
Dict with exit_code, stdout, stderr
Dict with exit_code, stdout, stderr, execution_time
"""
start_time = time.time()
try:
result = subprocess.run(
command,
@@ -150,20 +158,208 @@ def _run_script(
text=True,
timeout=timeout,
)
execution_time = time.time() - start_time
return {
"exit_code": result.returncode,
"stdout": result.stdout[:10000], # Limit output size
"stderr": result.stderr[:10000],
"execution_time": execution_time,
}
except subprocess.TimeoutExpired:
execution_time = time.time() - start_time
return {
"exit_code": -1,
"stdout": "",
"stderr": f"Script timed out after {timeout} seconds",
"execution_time": execution_time,
}
except Exception as e:
execution_time = time.time() - start_time
return {
"exit_code": -1,
"stdout": "",
"stderr": str(e),
"execution_time": execution_time,
}
# Script management endpoints
class ScriptCreateRequest(BaseModel):
"""Request model for creating or updating a script."""
command: str = Field(..., description="Command to execute", min_length=1)
label: str | None = Field(default=None, description="User-friendly label")
description: str = Field(default="", description="Script description")
icon: str | None = Field(default=None, description="Custom MDI icon (e.g., 'mdi:power')")
timeout: int = Field(default=30, description="Execution timeout in seconds", ge=1, le=300)
working_dir: str | None = Field(default=None, description="Working directory")
shell: bool = Field(default=True, description="Run command in shell")
def _validate_script_name(name: str) -> None:
"""Validate script name.
Args:
name: Script name to validate.
Raises:
HTTPException: If name is invalid.
"""
if not name:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Script name cannot be empty",
)
if not re.match(r"^[a-zA-Z0-9_]+$", name):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Script name must contain only alphanumeric characters and underscores",
)
if len(name) > 64:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Script name must be 64 characters or less",
)
@router.post("/create/{script_name}")
async def create_script(
script_name: str,
request: ScriptCreateRequest,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Create a new script.
Args:
script_name: Name for the new script (alphanumeric + underscore only).
request: Script configuration.
Returns:
Success response with script name.
Raises:
HTTPException: If script already exists or name is invalid.
"""
# Validate name
_validate_script_name(script_name)
# Check if script already exists
if script_name in settings.scripts:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Script '{script_name}' already exists. Use PUT /api/scripts/update/{script_name} to update it.",
)
# Create script config
script_config = ScriptConfig(**request.model_dump())
# Add to config file and in-memory
try:
config_manager.add_script(script_name, script_config)
except Exception as e:
logger.error(f"Failed to add script '{script_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to add script: {str(e)}",
)
# Notify WebSocket clients
await ws_manager.broadcast_scripts_changed()
logger.info(f"Script '{script_name}' created successfully")
return {"success": True, "script": script_name}
@router.put("/update/{script_name}")
async def update_script(
script_name: str,
request: ScriptCreateRequest,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Update an existing script.
Args:
script_name: Name of the script to update.
request: Updated script configuration.
Returns:
Success response with script name.
Raises:
HTTPException: If script does not exist.
"""
# Validate name
_validate_script_name(script_name)
# Check if script exists
if script_name not in settings.scripts:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Script '{script_name}' not found. Use POST /api/scripts/create/{script_name} to create it.",
)
# Create updated script config
script_config = ScriptConfig(**request.model_dump())
# Update config file and in-memory
try:
config_manager.update_script(script_name, script_config)
except Exception as e:
logger.error(f"Failed to update script '{script_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to update script: {str(e)}",
)
# Notify WebSocket clients
await ws_manager.broadcast_scripts_changed()
logger.info(f"Script '{script_name}' updated successfully")
return {"success": True, "script": script_name}
@router.delete("/delete/{script_name}")
async def delete_script(
script_name: str,
_: str = Depends(verify_token),
) -> dict[str, Any]:
"""Delete a script.
Args:
script_name: Name of the script to delete.
Returns:
Success response with script name.
Raises:
HTTPException: If script does not exist.
"""
# Validate name
_validate_script_name(script_name)
# Check if script exists
if script_name not in settings.scripts:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Script '{script_name}' not found",
)
# Delete from config file and in-memory
try:
config_manager.delete_script(script_name)
except Exception as e:
logger.error(f"Failed to delete script '{script_name}': {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to delete script: {str(e)}",
)
# Notify WebSocket clients
await ws_manager.broadcast_scripts_changed()
logger.info(f"Script '{script_name}' deleted successfully")
return {"success": True, "script": script_name}

View File

@@ -1,10 +0,0 @@
# Get the project root directory (two levels up from this script)
$projectRoot = (Get-Item $PSScriptRoot).Parent.Parent.FullName
$action = New-ScheduledTaskAction -Execute "python" -Argument "-m media_server.main" -WorkingDirectory $projectRoot
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -LogonType S4U -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
Register-ScheduledTask -TaskName "MediaServer" -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Media Server for Home Assistant"
Write-Host "Scheduled task 'MediaServer' created with working directory: $projectRoot"

View File

@@ -41,8 +41,9 @@ def get_media_controller() -> "MediaController":
if system == "Windows":
from .windows_media import WindowsMediaController
from ..config import settings
_controller_instance = WindowsMediaController()
_controller_instance = WindowsMediaController(audio_device=settings.audio_device)
elif system == "Linux":
# Check if running on Android
if _is_android():
@@ -72,4 +73,13 @@ def get_current_album_art() -> bytes | None:
return None
__all__ = ["get_media_controller", "get_current_album_art"]
def get_audio_devices() -> list[dict[str, str]]:
"""Get list of available audio output devices (Windows only for now)."""
system = platform.system()
if system == "Windows":
from .windows_media import WindowsMediaController
return WindowsMediaController.get_audio_devices()
return []
__all__ = ["get_media_controller", "get_current_album_art", "get_audio_devices"]

View File

@@ -0,0 +1,329 @@
"""Browser service for media file browsing and path validation."""
import logging
import os
import stat as stat_module
import time
from datetime import datetime
from pathlib import Path
from typing import Optional
from ..config import settings
# Directory listing cache: {resolved_path_str: (timestamp, all_items)}
_dir_cache: dict[str, tuple[float, list[dict]]] = {}
DIR_CACHE_TTL = 300 # 5 minutes
# Media info cache: {(file_path_str, mtime): {duration, bitrate, title}}
_media_info_cache: dict[tuple[str, float], dict] = {}
_MEDIA_INFO_CACHE_MAX = 5000
try:
from mutagen import File as MutagenFile
HAS_MUTAGEN = True
except ImportError:
HAS_MUTAGEN = False
logger = logging.getLogger(__name__)
# Media file extensions
AUDIO_EXTENSIONS = {".mp3", ".m4a", ".flac", ".wav", ".ogg", ".aac", ".wma", ".opus"}
VIDEO_EXTENSIONS = {".mp4", ".mkv", ".avi", ".mov", ".wmv", ".webm", ".flv"}
MEDIA_EXTENSIONS = AUDIO_EXTENSIONS | VIDEO_EXTENSIONS
class BrowserService:
"""Service for browsing media files with path validation."""
@staticmethod
def validate_path(folder_id: str, requested_path: str) -> Path:
"""Validate and resolve a path within an allowed folder.
Args:
folder_id: ID of the configured media folder.
requested_path: Path to validate (relative to folder root or absolute).
Returns:
Resolved absolute Path object.
Raises:
ValueError: If folder_id invalid or path traversal attempted.
FileNotFoundError: If path does not exist.
"""
# Get folder config
if folder_id not in settings.media_folders:
raise ValueError(f"Media folder '{folder_id}' not configured")
folder_config = settings.media_folders[folder_id]
if not folder_config.enabled:
raise ValueError(f"Media folder '{folder_id}' is disabled")
# Get base path
base_path = Path(folder_config.path).resolve()
if not base_path.exists():
raise FileNotFoundError(f"Media folder path does not exist: {base_path}")
if not base_path.is_dir():
raise ValueError(f"Media folder path is not a directory: {base_path}")
# Handle relative vs absolute paths
if requested_path.startswith("/") or requested_path.startswith("\\"):
# Relative to folder root (remove leading slash)
requested_path = requested_path.lstrip("/\\")
# Build and resolve full path
if requested_path:
full_path = (base_path / requested_path).resolve()
else:
full_path = base_path
# Security check: Ensure resolved path is within base path
try:
full_path.relative_to(base_path)
except ValueError:
logger.warning(
f"Path traversal attempt detected: {requested_path} "
f"(resolved to {full_path}, base: {base_path})"
)
raise ValueError("Path traversal not allowed")
# Check if path exists
if not full_path.exists():
raise FileNotFoundError(f"Path does not exist: {requested_path}")
return full_path
@staticmethod
def is_media_file(path: Path) -> bool:
"""Check if a file is a media file based on extension.
Args:
path: Path to check.
Returns:
True if file is a media file, False otherwise.
"""
return path.suffix.lower() in MEDIA_EXTENSIONS
@staticmethod
def get_file_type(path: Path) -> str:
"""Get the file type (folder, audio, video, other).
Args:
path: Path to check.
Returns:
File type string: "folder", "audio", "video", or "other".
"""
if path.is_dir():
return "folder"
suffix = path.suffix.lower()
if suffix in AUDIO_EXTENSIONS:
return "audio"
elif suffix in VIDEO_EXTENSIONS:
return "video"
else:
return "other"
@staticmethod
def get_media_info(file_path: Path, mtime: float | None = None) -> dict:
"""Get duration, bitrate, and title of a media file (header-only read).
Results are cached by (path, mtime) to avoid re-reading unchanged files.
Args:
file_path: Path to the media file.
mtime: File modification time (avoids an extra stat call).
Returns:
Dict with 'duration' (float or None), 'bitrate' (int or None),
and 'title' (str or None).
"""
result = {"duration": None, "bitrate": None, "title": None}
if not HAS_MUTAGEN:
return result
# Use mtime-based cache to skip mutagen reads for unchanged files
if mtime is None:
try:
mtime = file_path.stat().st_mtime
except (OSError, PermissionError):
pass
if mtime is not None:
cache_key = (str(file_path), mtime)
cached = _media_info_cache.get(cache_key)
if cached is not None:
return cached
try:
audio = MutagenFile(str(file_path), easy=True)
if audio is not None and hasattr(audio, "info"):
if hasattr(audio.info, "length"):
result["duration"] = round(audio.info.length, 2)
if hasattr(audio.info, "bitrate") and audio.info.bitrate:
result["bitrate"] = audio.info.bitrate
if audio is not None and hasattr(audio, "tags") and audio.tags:
tags = audio.tags
title = None
artist = None
if "title" in tags:
title = tags["title"][0] if isinstance(tags["title"], list) else tags["title"]
if "artist" in tags:
artist = tags["artist"][0] if isinstance(tags["artist"], list) else tags["artist"]
if artist and title:
result["title"] = f"{artist} \u2013 {title}"
elif title:
result["title"] = title
except Exception:
pass
# Cache result (evict oldest entries if cache is full)
if mtime is not None:
if len(_media_info_cache) >= _MEDIA_INFO_CACHE_MAX:
# Remove oldest ~20% of entries
to_remove = list(_media_info_cache.keys())[:_MEDIA_INFO_CACHE_MAX // 5]
for k in to_remove:
del _media_info_cache[k]
_media_info_cache[(str(file_path), mtime)] = result
return result
@staticmethod
def browse_directory(
folder_id: str,
path: str = "",
offset: int = 0,
limit: int = 100,
nocache: bool = False,
) -> dict:
"""Browse a directory and return items with metadata.
Args:
folder_id: ID of the configured media folder.
path: Path to browse (relative to folder root).
offset: Pagination offset (default: 0).
limit: Maximum items to return (default: 100).
Returns:
Dictionary with:
- current_path: Current path (relative to folder root)
- parent_path: Parent path (None if at root)
- items: List of file/folder items
- total: Total number of items
- offset: Current offset
- limit: Current limit
- folder_id: Folder ID
Raises:
ValueError: If path validation fails.
FileNotFoundError: If path does not exist.
"""
# Validate path
full_path = BrowserService.validate_path(folder_id, path)
# Get base path for relative path calculation
folder_config = settings.media_folders[folder_id]
base_path = Path(folder_config.path).resolve()
# Check if it's a directory
if not full_path.is_dir():
raise ValueError(f"Path is not a directory: {path}")
# Calculate relative path
try:
relative_path = full_path.relative_to(base_path)
current_path = "/" + str(relative_path).replace("\\", "/") if str(relative_path) != "." else "/"
except ValueError:
current_path = "/"
# Calculate parent path
if full_path == base_path:
parent_path = None
else:
parent_relative = full_path.parent.relative_to(base_path)
parent_path = "/" + str(parent_relative).replace("\\", "/") if str(parent_relative) != "." else "/"
# List directory contents (with caching)
try:
cache_key = str(full_path)
now = time.monotonic()
# Check cache
if not nocache and cache_key in _dir_cache:
cached_time, cached_items = _dir_cache[cache_key]
if now - cached_time < DIR_CACHE_TTL:
all_items = cached_items
else:
del _dir_cache[cache_key]
all_items = None
else:
all_items = None
# Enumerate directory if not cached
if all_items is None:
all_items = []
for item in full_path.iterdir():
if item.name.startswith("."):
continue
# Single stat() call per item — reuse for type check and metadata
try:
st = item.stat()
except (OSError, PermissionError):
continue
if stat_module.S_ISDIR(st.st_mode):
file_type = "folder"
else:
suffix = item.suffix.lower()
if suffix in AUDIO_EXTENSIONS:
file_type = "audio"
elif suffix in VIDEO_EXTENSIONS:
file_type = "video"
else:
continue
all_items.append({
"name": item.name,
"type": file_type,
"is_media": file_type in ("audio", "video"),
"_size": st.st_size,
"_mtime": st.st_mtime,
})
all_items.sort(key=lambda x: (x["type"] != "folder", x["name"].lower()))
_dir_cache[cache_key] = (now, all_items)
# Apply pagination
total = len(all_items)
items = all_items[offset:offset + limit]
# Enrich items on the current page with metadata
for item in items:
item["size"] = item["_size"] if item["type"] != "folder" else None
item["modified"] = datetime.fromtimestamp(item["_mtime"]).isoformat()
if item["is_media"]:
item_path = full_path / item["name"]
info = BrowserService.get_media_info(item_path, item["_mtime"])
item["duration"] = info["duration"]
item["bitrate"] = info["bitrate"]
item["title"] = info["title"]
else:
item["duration"] = None
item["bitrate"] = None
item["title"] = None
return {
"folder_id": folder_id,
"current_path": current_path,
"parent_path": parent_path,
"items": items,
"total": total,
"offset": offset,
"limit": limit,
}
except PermissionError:
raise ValueError(f"Permission denied accessing path: {path}")

View File

@@ -293,3 +293,27 @@ class LinuxMediaController(MediaController):
except Exception as e:
logger.error(f"Failed to seek: {e}")
return False
async def open_file(self, file_path: str) -> bool:
"""Open a media file with the default system player (Linux).
Uses xdg-open to open the file with the default application.
Args:
file_path: Absolute path to the media file
Returns:
True if successful, False otherwise
"""
try:
process = await asyncio.create_subprocess_exec(
'xdg-open', file_path,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL
)
await process.wait()
logger.info(f"Opened file with default player: {file_path}")
return True
except Exception as e:
logger.error(f"Failed to open file {file_path}: {e}")
return False

View File

@@ -294,3 +294,27 @@ class MacOSMediaController(MediaController):
)
return True
return False
async def open_file(self, file_path: str) -> bool:
"""Open a media file with the default system player (macOS).
Uses the 'open' command to open the file with the default application.
Args:
file_path: Absolute path to the media file
Returns:
True if successful, False otherwise
"""
try:
process = await asyncio.create_subprocess_exec(
'open', file_path,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL
)
await process.wait()
logger.info(f"Opened file with default player: {file_path}")
return True
except Exception as e:
logger.error(f"Failed to open file {file_path}: {e}")
return False

View File

@@ -94,3 +94,15 @@ class MediaController(ABC):
True if successful, False otherwise
"""
pass
@abstractmethod
async def open_file(self, file_path: str) -> bool:
"""Open a media file with the default system player.
Args:
file_path: Absolute path to the media file
Returns:
True if successful, False otherwise
"""
pass

View File

@@ -0,0 +1,194 @@
"""Metadata extraction service for media files."""
import logging
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
class MetadataService:
"""Service for extracting metadata from media files."""
@staticmethod
def extract_audio_metadata(file_path: Path) -> dict:
"""Extract metadata from an audio file.
Args:
file_path: Path to the audio file.
Returns:
Dictionary with audio metadata.
"""
try:
import mutagen
from mutagen import File as MutagenFile
audio = MutagenFile(str(file_path), easy=True)
if audio is None:
return {"error": "Unable to read audio file"}
metadata = {
"type": "audio",
"filename": file_path.name,
"path": str(file_path),
}
# Extract duration
if hasattr(audio.info, "length"):
metadata["duration"] = round(audio.info.length, 2)
# Extract bitrate
if hasattr(audio.info, "bitrate"):
metadata["bitrate"] = audio.info.bitrate
# Extract sample rate
if hasattr(audio.info, "sample_rate"):
metadata["sample_rate"] = audio.info.sample_rate
elif hasattr(audio.info, "samplerate"):
metadata["sample_rate"] = audio.info.samplerate
# Extract channels
if hasattr(audio.info, "channels"):
metadata["channels"] = audio.info.channels
# Extract tags (use easy=True for consistent tag names)
if audio is not None and hasattr(audio, "tags") and audio.tags:
# Easy tags provide lists, so we take the first item
tags = audio.tags
if "title" in tags:
metadata["title"] = tags["title"][0] if isinstance(tags["title"], list) else tags["title"]
if "artist" in tags:
metadata["artist"] = tags["artist"][0] if isinstance(tags["artist"], list) else tags["artist"]
if "album" in tags:
metadata["album"] = tags["album"][0] if isinstance(tags["album"], list) else tags["album"]
if "albumartist" in tags:
metadata["album_artist"] = tags["albumartist"][0] if isinstance(tags["albumartist"], list) else tags["albumartist"]
if "date" in tags:
metadata["date"] = tags["date"][0] if isinstance(tags["date"], list) else tags["date"]
if "genre" in tags:
metadata["genre"] = tags["genre"][0] if isinstance(tags["genre"], list) else tags["genre"]
if "tracknumber" in tags:
metadata["track_number"] = tags["tracknumber"][0] if isinstance(tags["tracknumber"], list) else tags["tracknumber"]
# If no title tag, use filename
if "title" not in metadata:
metadata["title"] = file_path.stem
return metadata
except ImportError:
logger.error("mutagen library not installed, cannot extract metadata")
return {"error": "mutagen library not installed"}
except Exception as e:
logger.error(f"Error extracting audio metadata from {file_path}: {e}")
return {
"error": str(e),
"filename": file_path.name,
"title": file_path.stem,
}
@staticmethod
def extract_video_metadata(file_path: Path) -> dict:
"""Extract basic metadata from a video file.
Args:
file_path: Path to the video file.
Returns:
Dictionary with video metadata.
"""
try:
import mutagen
from mutagen import File as MutagenFile
video = MutagenFile(str(file_path))
if video is None:
return {
"type": "video",
"filename": file_path.name,
"title": file_path.stem,
}
metadata = {
"type": "video",
"filename": file_path.name,
"path": str(file_path),
}
# Extract duration
if hasattr(video.info, "length"):
metadata["duration"] = round(video.info.length, 2)
# Extract bitrate
if hasattr(video.info, "bitrate"):
metadata["bitrate"] = video.info.bitrate
# Extract video-specific properties if available
if hasattr(video.info, "width"):
metadata["width"] = video.info.width
if hasattr(video.info, "height"):
metadata["height"] = video.info.height
# Try to extract title from tags
if hasattr(video, "tags") and video.tags:
tags = video.tags
if hasattr(tags, "get"):
title = tags.get("title") or tags.get("TITLE") or tags.get("\xa9nam")
if title:
metadata["title"] = title[0] if isinstance(title, list) else str(title)
# If no title tag, use filename
if "title" not in metadata:
metadata["title"] = file_path.stem
return metadata
except ImportError:
logger.error("mutagen library not installed, cannot extract metadata")
return {
"error": "mutagen library not installed",
"type": "video",
"filename": file_path.name,
"title": file_path.stem,
}
except Exception as e:
logger.debug(f"Error extracting video metadata from {file_path}: {e}")
# Return basic metadata
return {
"type": "video",
"filename": file_path.name,
"title": file_path.stem,
}
@staticmethod
def extract_metadata(file_path: Path) -> dict:
"""Extract metadata from a media file (auto-detect type).
Args:
file_path: Path to the media file.
Returns:
Dictionary with media metadata.
"""
from .browser_service import AUDIO_EXTENSIONS, VIDEO_EXTENSIONS
suffix = file_path.suffix.lower()
if suffix in AUDIO_EXTENSIONS:
return MetadataService.extract_audio_metadata(file_path)
elif suffix in VIDEO_EXTENSIONS:
return MetadataService.extract_video_metadata(file_path)
else:
return {
"error": "Unsupported file type",
"filename": file_path.name,
}

View File

@@ -0,0 +1,391 @@
"""Thumbnail generation and caching service."""
import asyncio
import hashlib
import logging
import os
import shutil
import subprocess
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
# Thumbnail sizes
THUMBNAIL_SIZES = {
"small": (150, 150),
"medium": (300, 300),
}
# Cache size limit (500MB)
CACHE_SIZE_LIMIT = 500 * 1024 * 1024 # 500MB in bytes
class ThumbnailService:
"""Service for generating and caching thumbnails."""
@staticmethod
def get_cache_dir() -> Path:
"""Get the thumbnail cache directory path.
Returns:
Path to the cache directory (project-local).
"""
# Store cache in project directory: media-server/.cache/thumbnails/
project_root = Path(__file__).parent.parent.parent
cache_dir = project_root / ".cache" / "thumbnails"
cache_dir.mkdir(parents=True, exist_ok=True)
return cache_dir
@staticmethod
def get_cache_key(file_path: Path) -> str:
"""Generate cache key from file path.
Args:
file_path: Path to the media file.
Returns:
SHA256 hash of the absolute file path.
"""
absolute_path = str(file_path.resolve())
return hashlib.sha256(absolute_path.encode()).hexdigest()
# Sentinel value indicating "no thumbnail available" is cached
NO_THUMBNAIL = b""
@staticmethod
def get_cached_thumbnail(file_path: Path, size: str) -> Optional[bytes]:
"""Get cached thumbnail if valid.
Args:
file_path: Path to the media file.
size: Thumbnail size ("small" or "medium").
Returns:
Thumbnail bytes if cached, empty bytes if cached as "no thumbnail",
None if not cached.
"""
cache_dir = ThumbnailService.get_cache_dir()
cache_key = ThumbnailService.get_cache_key(file_path)
cache_folder = cache_dir / cache_key
cache_path = cache_folder / f"{size}.jpg"
no_thumb_path = cache_folder / ".no_thumbnail"
# Check negative cache first (no thumbnail available)
if no_thumb_path.exists():
try:
file_mtime = file_path.stat().st_mtime
cache_mtime = no_thumb_path.stat().st_mtime
if file_mtime <= cache_mtime:
return ThumbnailService.NO_THUMBNAIL
except (OSError, PermissionError):
pass
if not cache_path.exists():
return None
# Check if file has been modified since cache was created
try:
file_mtime = file_path.stat().st_mtime
cache_mtime = cache_path.stat().st_mtime
if file_mtime > cache_mtime:
logger.debug(f"Cache invalidated for {file_path.name} (file modified)")
return None
# Read cached thumbnail
with open(cache_path, "rb") as f:
return f.read()
except (OSError, PermissionError) as e:
logger.error(f"Error reading cached thumbnail: {e}")
return None
@staticmethod
def cache_thumbnail(file_path: Path, size: str, image_data: bytes) -> None:
"""Cache a thumbnail.
Args:
file_path: Path to the media file.
size: Thumbnail size ("small" or "medium").
image_data: Thumbnail image data (JPEG bytes).
"""
cache_dir = ThumbnailService.get_cache_dir()
cache_key = ThumbnailService.get_cache_key(file_path)
cache_folder = cache_dir / cache_key
cache_folder.mkdir(parents=True, exist_ok=True)
cache_path = cache_folder / f"{size}.jpg"
try:
with open(cache_path, "wb") as f:
f.write(image_data)
logger.debug(f"Cached thumbnail for {file_path.name} ({size})")
except (OSError, PermissionError) as e:
logger.error(f"Error caching thumbnail: {e}")
@staticmethod
def cache_no_thumbnail(file_path: Path) -> None:
"""Cache that a file has no thumbnail (negative cache)."""
cache_dir = ThumbnailService.get_cache_dir()
cache_key = ThumbnailService.get_cache_key(file_path)
cache_folder = cache_dir / cache_key
cache_folder.mkdir(parents=True, exist_ok=True)
try:
(cache_folder / ".no_thumbnail").touch()
logger.debug(f"Cached no-thumbnail for {file_path.name}")
except (OSError, PermissionError) as e:
logger.error(f"Error caching no-thumbnail marker: {e}")
@staticmethod
def generate_audio_thumbnail(file_path: Path, size: str) -> Optional[bytes]:
"""Generate thumbnail from audio file (extract album art).
Args:
file_path: Path to the audio file.
size: Thumbnail size ("small" or "medium").
Returns:
Thumbnail bytes (JPEG) or None if no album art.
"""
try:
import mutagen
from mutagen import File as MutagenFile
from PIL import Image
from io import BytesIO
audio = MutagenFile(str(file_path))
if audio is None:
return None
# Extract album art
art_data = None
# Try different tag types for album art
if hasattr(audio, "pictures") and audio.pictures:
# FLAC, Ogg Vorbis
art_data = audio.pictures[0].data
elif hasattr(audio, "tags"):
tags = audio.tags
if tags is not None:
# MP3 (ID3)
if hasattr(tags, "getall"):
apic_frames = tags.getall("APIC")
if apic_frames:
art_data = apic_frames[0].data
# MP4/M4A
elif "covr" in tags:
art_data = bytes(tags["covr"][0])
# Try other common keys
elif "APIC:" in tags:
art_data = tags["APIC:"].data
if art_data is None:
return None
# Resize image
img = Image.open(BytesIO(art_data))
# Convert to RGB if necessary (handle RGBA, grayscale, etc.)
if img.mode not in ("RGB", "L"):
img = img.convert("RGB")
# Resize with maintaining aspect ratio and center crop
target_size = THUMBNAIL_SIZES[size]
img.thumbnail((target_size[0] * 2, target_size[1] * 2), Image.Resampling.LANCZOS)
# Center crop to square
width, height = img.size
min_dim = min(width, height)
left = (width - min_dim) // 2
top = (height - min_dim) // 2
right = left + min_dim
bottom = top + min_dim
img = img.crop((left, top, right, bottom))
# Final resize
img = img.resize(target_size, Image.Resampling.LANCZOS)
# Save as JPEG
output = BytesIO()
img.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue()
except ImportError:
logger.error("Required libraries (mutagen, Pillow) not installed")
return None
except Exception as e:
logger.debug(f"Error generating audio thumbnail for {file_path.name}: {e}")
return None
@staticmethod
async def generate_video_thumbnail(file_path: Path, size: str) -> Optional[bytes]:
"""Generate thumbnail from video file using ffmpeg.
Args:
file_path: Path to the video file.
size: Thumbnail size ("small" or "medium").
Returns:
Thumbnail bytes (JPEG) or None if ffmpeg not available.
"""
try:
from PIL import Image
from io import BytesIO
# Check if ffmpeg is available
if not shutil.which("ffmpeg"):
logger.debug("ffmpeg not available, cannot generate video thumbnail")
return None
# Extract frame at 10% duration
target_size = THUMBNAIL_SIZES[size]
# Use ffmpeg to extract a frame
cmd = [
"ffmpeg",
"-i", str(file_path),
"-vf", f"thumbnail,scale={target_size[0]}:{target_size[1]}:force_original_aspect_ratio=increase,crop={target_size[0]}:{target_size[1]}",
"-frames:v", "1",
"-f", "image2pipe",
"-vcodec", "mjpeg",
"-"
]
# Run ffmpeg with timeout
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
try:
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=10.0)
if process.returncode == 0 and stdout:
# ffmpeg output is already JPEG, but let's ensure proper quality
img = Image.open(BytesIO(stdout))
# Convert to RGB if necessary
if img.mode != "RGB":
img = img.convert("RGB")
# Save as JPEG with consistent quality
output = BytesIO()
img.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue()
except asyncio.TimeoutError:
logger.warning(f"ffmpeg timeout for {file_path.name}")
process.kill()
await process.wait()
return None
except ImportError:
logger.error("Pillow library not installed")
return None
except Exception as e:
logger.debug(f"Error generating video thumbnail for {file_path.name}: {e}")
return None
@staticmethod
async def get_thumbnail(file_path: Path, size: str = "medium") -> Optional[bytes]:
"""Get thumbnail for a media file (from cache or generate).
Args:
file_path: Path to the media file.
size: Thumbnail size ("small" or "medium").
Returns:
Thumbnail bytes (JPEG) or None if unavailable.
"""
from .browser_service import AUDIO_EXTENSIONS, VIDEO_EXTENSIONS
# Validate size
if size not in THUMBNAIL_SIZES:
size = "medium"
# Check cache first (returns bytes, empty bytes for negative cache, or None)
cached = ThumbnailService.get_cached_thumbnail(file_path, size)
if cached is not None:
return cached if cached else None
# Generate thumbnail based on file type
suffix = file_path.suffix.lower()
thumbnail_data = None
if suffix in AUDIO_EXTENSIONS:
# Audio files - run in executor (sync operation)
loop = asyncio.get_event_loop()
thumbnail_data = await loop.run_in_executor(
None,
ThumbnailService.generate_audio_thumbnail,
file_path,
size,
)
elif suffix in VIDEO_EXTENSIONS:
# Video files - already async
thumbnail_data = await ThumbnailService.generate_video_thumbnail(file_path, size)
# Cache result (positive or negative)
if thumbnail_data:
ThumbnailService.cache_thumbnail(file_path, size, thumbnail_data)
else:
ThumbnailService.cache_no_thumbnail(file_path)
return thumbnail_data
@staticmethod
def cleanup_cache() -> None:
"""Clean up cache if it exceeds size limit.
Removes oldest thumbnails by access time.
"""
cache_dir = ThumbnailService.get_cache_dir()
try:
# Calculate total cache size
total_size = 0
cache_items = []
for folder in cache_dir.iterdir():
if folder.is_dir():
for file in folder.iterdir():
if file.is_file():
stat = file.stat()
total_size += stat.st_size
cache_items.append((file, stat.st_atime, stat.st_size))
# If cache is within limit, no cleanup needed
if total_size <= CACHE_SIZE_LIMIT:
return
logger.info(f"Cache size {total_size / 1024 / 1024:.2f}MB exceeds limit, cleaning up...")
# Sort by access time (oldest first)
cache_items.sort(key=lambda x: x[1])
# Remove oldest items until under limit
for file, _, size in cache_items:
if total_size <= CACHE_SIZE_LIMIT:
break
try:
file.unlink()
total_size -= size
logger.debug(f"Removed cached thumbnail: {file}")
# Remove empty parent folder
parent = file.parent
if parent != cache_dir and not any(parent.iterdir()):
parent.rmdir()
except (OSError, PermissionError) as e:
logger.error(f"Error removing cache file: {e}")
logger.info(f"Cache cleanup complete, new size: {total_size / 1024 / 1024:.2f}MB")
except Exception as e:
logger.error(f"Error during cache cleanup: {e}")

View File

@@ -49,24 +49,33 @@ class ConnectionManager:
)
async def broadcast(self, message: dict[str, Any]) -> None:
"""Broadcast a message to all connected clients."""
"""Broadcast a message to all connected clients concurrently."""
async with self._lock:
connections = list(self._active_connections)
if not connections:
return
disconnected = []
for websocket in connections:
async def _send(ws: WebSocket) -> WebSocket | None:
try:
await websocket.send_json(message)
await ws.send_json(message)
return None
except Exception as e:
logger.debug("Failed to send to client: %s", e)
disconnected.append(websocket)
return ws
results = await asyncio.gather(*(_send(ws) for ws in connections))
# Clean up disconnected clients
for ws in disconnected:
await self.disconnect(ws)
for ws in results:
if ws is not None:
await self.disconnect(ws)
async def broadcast_scripts_changed(self) -> None:
"""Notify all connected clients that scripts have changed."""
message = {"type": "scripts_changed", "data": {}}
await self.broadcast(message)
logger.info("Broadcast sent: scripts_changed")
def status_changed(
self, old: dict[str, Any] | None, new: dict[str, Any]
@@ -150,26 +159,25 @@ class ConnectionManager:
async with self._lock:
has_clients = len(self._active_connections) > 0
if has_clients:
status = await get_status_func()
status_dict = status.model_dump()
if not has_clients:
await asyncio.sleep(self._poll_interval)
continue
# Only broadcast on actual state changes
# Let HA handle position interpolation during playback
if self.status_changed(self._last_status, status_dict):
self._last_status = status_dict
self._last_broadcast_time = time.time()
await self.broadcast(
{"type": "status_update", "data": status_dict}
)
logger.debug("Broadcast sent: status change")
else:
# Update cached status even without broadcast
self._last_status = status_dict
status = await get_status_func()
status_dict = status.model_dump()
# Only broadcast on actual state changes
# Let HA handle position interpolation during playback
if self.status_changed(self._last_status, status_dict):
self._last_status = status_dict
self._last_broadcast_time = time.time()
await self.broadcast(
{"type": "status_update", "data": status_dict}
)
logger.debug("Broadcast sent: status change")
else:
# Still update cache for when clients connect
status = await get_status_func()
self._last_status = status.model_dump()
# Update cached status even without broadcast
self._last_status = status_dict
await asyncio.sleep(self._poll_interval)

View File

@@ -54,41 +54,100 @@ except ImportError:
# Volume control imports
PYCAW_AVAILABLE = False
_volume_control = None
_configured_device_name: str | None = None
try:
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL, CoInitialize, CoUninitialize
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
def _init_volume_control():
"""Initialize volume control interface."""
global _volume_control
if _volume_control is not None:
return _volume_control
import warnings
# Suppress pycaw warnings about missing device properties
warnings.filterwarnings("ignore", category=UserWarning, module="pycaw")
def _get_all_audio_devices() -> list[dict[str, str]]:
"""Get list of all audio output devices."""
devices = []
try:
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
# Use pycaw's GetAllDevices which handles property retrieval
all_devices = AudioUtilities.GetAllDevices()
for device in all_devices:
# Only include render (output) devices with valid names
# Render devices have IDs starting with {0.0.0
if device.FriendlyName and device.id and device.id.startswith("{0.0.0"):
devices.append({
"id": device.id,
"name": device.FriendlyName,
})
except Exception as e:
logger.error(f"Error enumerating audio devices: {e}")
return devices
def _find_device_by_name(device_name: str):
"""Find an audio device by its friendly name (partial match).
Returns the AudioDevice wrapper for the matched device.
"""
try:
# Get all devices and find matching one
all_devices = AudioUtilities.GetAllDevices()
for device in all_devices:
if device.FriendlyName and device_name.lower() in device.FriendlyName.lower():
logger.info(f"Found audio device: {device.FriendlyName}")
return device
except Exception as e:
logger.error(f"Error finding device by name: {e}")
return None
def _init_volume_control(device_name: str | None = None):
"""Initialize volume control interface.
Args:
device_name: Name of the audio device to control (partial match).
If None, uses the default audio device.
"""
global _volume_control, _configured_device_name
if _volume_control is not None and device_name == _configured_device_name:
return _volume_control
_configured_device_name = device_name
try:
if device_name:
# Find specific device by name
device = _find_device_by_name(device_name)
if device is None:
logger.warning(f"Audio device '{device_name}' not found, using default")
device = AudioUtilities.GetSpeakers()
else:
# Use default device
device = AudioUtilities.GetSpeakers()
if hasattr(device, 'Activate'):
interface = device.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
elif hasattr(device, '_dev'):
interface = device._dev.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
else:
logger.warning("Could not activate audio device")
return None
_volume_control = cast(interface, POINTER(IAudioEndpointVolume))
return _volume_control
except AttributeError:
# Try accessing the underlying device
try:
devices = AudioUtilities.GetSpeakers()
if hasattr(devices, '_dev'):
interface = devices._dev.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
_volume_control = cast(interface, POINTER(IAudioEndpointVolume))
return _volume_control
except Exception as e:
logger.debug(f"Volume control init failed: {e}")
except Exception as e:
logger.debug(f"Volume control init error: {e}")
logger.error(f"Volume control init error: {e}")
return None
PYCAW_AVAILABLE = True
except ImportError as e:
logger.warning(f"pycaw not available: {e}")
def _init_volume_control():
def _get_all_audio_devices() -> list[dict[str, str]]:
return []
def _find_device_by_name(device_name: str):
return None
def _init_volume_control(device_name: str | None = None):
return None
WINDOWS_AVAILABLE = WINSDK_AVAILABLE
@@ -427,25 +486,38 @@ def _sync_seek(position: float) -> bool:
class WindowsMediaController(MediaController):
"""Media controller for Windows using WinRT and pycaw."""
def __init__(self):
def __init__(self, audio_device: str | None = None):
"""Initialize the Windows media controller.
Args:
audio_device: Name of the audio device to control (partial match).
If None, uses the default audio device.
"""
if not WINDOWS_AVAILABLE:
raise RuntimeError(
"Windows media control requires winsdk, pycaw, and comtypes packages"
)
self._volume_interface = None
self._volume_init_attempted = False
self._audio_device = audio_device
def _get_volume_interface(self):
"""Get the audio endpoint volume interface."""
if not self._volume_init_attempted:
self._volume_init_attempted = True
self._volume_interface = _init_volume_control()
self._volume_interface = _init_volume_control(self._audio_device)
if self._volume_interface:
logger.info("Volume control initialized successfully")
device_info = f" (device: {self._audio_device})" if self._audio_device else " (default device)"
logger.info(f"Volume control initialized successfully{device_info}")
else:
logger.warning("Volume control not available")
return self._volume_interface
@staticmethod
def get_audio_devices() -> list[dict[str, str]]:
"""Get list of available audio output devices."""
return _get_all_audio_devices()
async def get_status(self) -> MediaStatus:
"""Get current media playback status."""
status = MediaStatus()
@@ -594,3 +666,24 @@ class WindowsMediaController(MediaController):
except Exception as e:
logger.error(f"Failed to seek: {e}")
return False
async def open_file(self, file_path: str) -> bool:
"""Open a media file with the default system player (Windows).
Uses os.startfile() to open the file with the default application.
Args:
file_path: Absolute path to the media file
Returns:
True if successful, False otherwise
"""
try:
import os
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, lambda: os.startfile(file_path))
logger.info(f"Opened file with default player: {file_path}")
return True
except Exception as e:
logger.error(f"Failed to open file {file_path}: {e}")
return False

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,499 @@
<!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>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='grad' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' style='stop-color:%231db954;stop-opacity:1' /%3E%3Cstop offset='100%25' style='stop-color:%231ed760;stop-opacity:1' /%3E%3C/linearGradient%3E%3C/defs%3E%3Ccircle cx='50' cy='50' r='45' fill='url(%23grad)'/%3E%3Cpath fill='white' d='M35 25 L35 75 L75 50 Z'/%3E%3C/svg%3E">
<link rel="stylesheet" href="/static/css/styles.css">
</head>
<body class="loading-translations">
<!-- Mini Player (sticky) -->
<div class="mini-player hidden" id="mini-player">
<div class="mini-player-info">
<img id="mini-album-art" class="mini-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 class="mini-track-details">
<div id="mini-track-title" class="mini-track-title">No media playing</div>
<div id="mini-artist" class="mini-artist"></div>
</div>
</div>
<div class="mini-controls">
<button class="mini-control-btn" onclick="togglePlayPause()" id="mini-btn-play-pause" title="Play/Pause">
<svg viewBox="0 0 24 24" id="mini-play-pause-icon">
<path d="M8 5v14l11-7z"/>
</svg>
</button>
</div>
<div class="mini-progress-container">
<div class="mini-time-display">
<span id="mini-current-time">0:00</span>
<span id="mini-total-time">0:00</span>
</div>
<div class="mini-progress-bar" id="mini-progress-bar">
<div class="mini-progress-fill" id="mini-progress-fill"></div>
</div>
</div>
<div class="mini-volume-container">
<button class="mini-control-btn" onclick="toggleMute()" id="mini-btn-mute" title="Mute">
<svg viewBox="0 0 24 24" id="mini-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="mini-volume-slider" class="mini-volume-slider" min="0" max="100" value="50">
<div class="mini-volume-display" id="mini-volume-display">50%</div>
</div>
</div>
<!-- Auth Modal -->
<div id="auth-overlay" class="hidden">
<div class="auth-modal">
<h2 data-i18n="app.title">Media Server</h2>
<p data-i18n="auth.message">Enter your API token to connect to the media server.</p>
<input type="text" id="token-input" data-i18n-placeholder="auth.placeholder" placeholder="Enter API Token" autocomplete="off">
<button class="btn-connect" onclick="authenticate()" data-i18n="auth.connect">Connect</button>
<div class="help-text">
<p data-i18n="auth.help">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>
<div style="display: flex; align-items: center; gap: 0.5rem;">
<span class="status-dot" id="status-dot"></span>
<span class="version-label" id="version-label"></span>
</div>
<div style="display: flex; align-items: center; gap: 0.5rem;">
<div class="accent-picker">
<button class="accent-picker-btn" onclick="toggleAccentPicker()" title="Accent color">
<span class="accent-dot" id="accentDot"></span>
</button>
<div class="accent-picker-dropdown" id="accentDropdown"></div>
</div>
<button class="theme-toggle" onclick="toggleTheme()" data-i18n-title="player.theme" 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>
<select id="locale-select" onchange="changeLocale()" title="Change language">
<option value="en">English</option>
<option value="ru">Русский</option>
</select>
<button class="clear-token-btn" onclick="clearToken()" data-i18n-title="auth.logout.title" data-i18n="auth.logout" title="Clear saved token">Logout</button>
</div>
</header>
<!-- Tab Bar -->
<div class="tab-bar" id="tabBar">
<div class="tab-indicator" id="tabIndicator"></div>
<button class="tab-btn active" data-tab="player" onclick="switchTab('player')">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
<span data-i18n="tab.player">Player</span>
</button>
<button class="tab-btn" data-tab="browser" onclick="switchTab('browser')">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg>
<span data-i18n="tab.browser">Browser</span>
</button>
<button class="tab-btn" data-tab="quick-actions" onclick="switchTab('quick-actions')">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M7 2v11h3v9l7-12h-4l4-8z"/></svg>
<span data-i18n="tab.quick_actions">Actions</span>
</button>
<button class="tab-btn" data-tab="scripts" onclick="switchTab('scripts')">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"/></svg>
<span data-i18n="tab.scripts">Scripts</span>
</button>
<button class="tab-btn" data-tab="callbacks" onclick="switchTab('callbacks')">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
<span data-i18n="tab.callbacks">Callbacks</span>
</button>
</div>
<div class="player-container" data-tab-content="player">
<div class="player-layout">
<div class="album-art-container">
<img id="album-art-glow" class="album-art-glow" 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%3C/svg%3E" alt="" aria-hidden="true">
<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="player-details">
<div class="track-info">
<div id="track-title" data-i18n="player.no_media">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" data-i18n="state.idle">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()" data-i18n-title="player.previous" 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()" data-i18n-title="player.play" 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()" data-i18n-title="player.next" 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()" data-i18n-title="player.mute" 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">
<span data-i18n="player.source">Source:</span> <span id="source" data-i18n="player.unknown_source">Unknown</span>
<button class="vinyl-toggle-btn" onclick="toggleVinylMode()" id="vinylToggle" data-i18n-title="player.vinyl" title="Vinyl mode">
<svg viewBox="0 0 24 24" width="16" height="16"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="1.5"/><circle cx="12" cy="12" r="3" fill="currentColor"/><circle cx="12" cy="12" r="6.5" fill="none" stroke="currentColor" stroke-width="0.5" opacity="0.5"/></svg>
</button>
</div>
</div>
</div>
</div>
<!-- Media Browser Section -->
<div class="browser-container" data-tab-content="browser" >
<!-- Breadcrumb Navigation -->
<div class="breadcrumb" id="breadcrumb"></div>
<!-- Browser Toolbar -->
<div class="browser-toolbar" id="browserToolbar">
<div class="browser-toolbar-left">
<div class="view-toggle">
<button class="view-toggle-btn active" id="viewGridBtn" onclick="setViewMode('grid')" data-i18n-title="browser.view_grid" title="Grid view">
<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 3h8v8H3V3zm0 10h8v8H3v-8zm10-10h8v8h-8V3zm0 10h8v8h-8v-8z"/></svg>
</button>
<button class="view-toggle-btn" id="viewCompactBtn" onclick="setViewMode('compact')" data-i18n-title="browser.view_compact" title="Compact view">
<svg viewBox="0 0 24 24" width="18" height="18"><path d="M2 2h5v5H2V2zm0 8h5v5H2v-5zm0 8h5v5H2v-5zm7-16h5v5H9V2zm0 8h5v5H9v-5zm0 8h5v5H9v-5zm7-16h5v5h-5V2zm0 8h5v5h-5v-5zm0 8h5v5h-5v-5z"/></svg>
</button>
<button class="view-toggle-btn" id="viewListBtn" onclick="setViewMode('list')" data-i18n-title="browser.view_list" title="List view">
<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 4h18v2H3V4zm0 7h18v2H3v-2zm0 7h18v2H3v-2z"/></svg>
</button>
</div>
<button class="view-toggle-btn browser-refresh-btn" id="refreshBtn" onclick="refreshBrowser()" data-i18n-title="browser.refresh" title="Refresh">
<svg viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M17.65 6.35A7.958 7.958 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
</button>
<button class="browser-play-all-btn" id="playAllBtn" onclick="playAllFolder()" data-i18n-title="browser.play_all" title="Play All" style="display: none;">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M8 5v14l11-7z"/></svg>
</button>
</div>
<div class="browser-search-wrapper" id="browserSearchWrapper" style="display: none;">
<svg class="browser-search-icon" viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
<input type="text" id="browserSearchInput" class="browser-search-input" data-i18n-placeholder="browser.search" placeholder="Search..." oninput="onBrowserSearch()">
<button class="browser-search-clear" id="browserSearchClear" onclick="clearBrowserSearch()" style="display: none;">
<svg viewBox="0 0 24 24" width="14" height="14"><path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
</button>
</div>
<div class="browser-toolbar-right">
<label class="items-per-page-label">
<span data-i18n="browser.items_per_page">Items per page:</span>
<select id="itemsPerPageSelect" onchange="onItemsPerPageChanged()">
<option value="25">25</option>
<option value="50">50</option>
<option value="100" selected>100</option>
<option value="200">200</option>
<option value="500">500</option>
</select>
</label>
</div>
</div>
<!-- File/Folder Grid -->
<div class="browser-grid" id="browserGrid">
<div class="browser-empty empty-state-illustration">
<svg viewBox="0 0 64 64"><path d="M8 16h20l4-6h20a4 4 0 014 4v36a4 4 0 01-4 4H8a4 4 0 01-4-4V20a4 4 0 014-4z"/><path d="M4 24h56" stroke-dasharray="4 3" opacity="0.4"/></svg>
<p data-i18n="browser.no_folder_selected">Select a folder to browse media files</p>
</div>
</div>
<!-- Pagination -->
<div class="pagination" id="browserPagination" style="display: none;">
<button id="prevPage" onclick="previousPage()" data-i18n="browser.previous">Previous</button>
<div class="pagination-center">
<span data-i18n="browser.page">Page</span>
<input type="number" id="pageInput" class="page-input" min="1" value="1" onchange="goToPage()">
<span id="pageTotal">/ 1</span>
</div>
<button id="nextPage" onclick="nextPage()" data-i18n="browser.next">Next</button>
</div>
</div>
<!-- Scripts Section (Quick Actions) -->
<div class="scripts-container" id="scripts-container" data-tab-content="quick-actions" >
<div class="scripts-grid" id="scripts-grid">
<div class="scripts-empty empty-state-illustration">
<svg viewBox="0 0 64 64"><path d="M20 8l-8 48"/><path d="M44 8l8 48"/><path d="M10 24h44"/><path d="M8 40h44"/></svg>
<p data-i18n="scripts.no_scripts">No scripts configured</p>
</div>
<div class="script-btn add-card-grid" onclick="showAddScriptDialog()">
<span class="add-card-icon">+</span>
</div>
</div>
</div>
<!-- Script Management Section -->
<div class="script-management" data-tab-content="scripts" >
<table class="scripts-table">
<thead>
<tr>
<th data-i18n="scripts.table.name">Name</th>
<th data-i18n="scripts.table.label">Label</th>
<th data-i18n="scripts.table.command">Command</th>
<th data-i18n="scripts.table.timeout">Timeout</th>
<th data-i18n="scripts.table.actions">Actions</th>
</tr>
</thead>
<tbody id="scriptsTableBody">
<tr>
<td colspan="5" class="empty-state">
<div class="empty-state-illustration">
<svg viewBox="0 0 64 64"><rect x="8" y="4" width="48" height="56" rx="4"/><path d="M20 20h24M20 32h16M20 44h20"/></svg>
<p data-i18n="scripts.empty">No scripts configured. Click "Add" to create one.</p>
</div>
</td>
</tr>
</tbody>
</table>
<div class="add-card" onclick="showAddScriptDialog()">
<span class="add-card-icon">+</span>
</div>
</div>
<!-- Callback Management Section -->
<div class="script-management" id="callbacksSection" data-tab-content="callbacks" >
<p style="color: var(--text-secondary); font-size: 0.875rem; margin-bottom: 1rem;" data-i18n="callbacks.description">
Callbacks are scripts triggered automatically by media control events (play, pause, stop, etc.)
</p>
<table class="scripts-table">
<thead>
<tr>
<th data-i18n="callbacks.table.event">Event</th>
<th data-i18n="callbacks.table.command">Command</th>
<th data-i18n="callbacks.table.timeout">Timeout</th>
<th data-i18n="callbacks.table.actions">Actions</th>
</tr>
</thead>
<tbody id="callbacksTableBody">
<tr>
<td colspan="4" class="empty-state">
<div class="empty-state-illustration">
<svg viewBox="0 0 64 64"><circle cx="32" cy="32" r="24"/><path d="M32 20v12l8 8"/></svg>
<p>No callbacks configured. Click "Add" to create one.</p>
</div>
</td>
</tr>
</tbody>
</table>
<div class="add-card" onclick="showAddCallbackDialog()">
<span class="add-card-icon">+</span>
</div>
</div>
</div>
<!-- Add/Edit Script Dialog -->
<dialog id="scriptDialog">
<div class="dialog-header">
<h3 id="dialogTitle" data-i18n="scripts.dialog.add">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>
<span data-i18n="scripts.field.name">Script Name *</span>
<input type="text" id="scriptName" required pattern="[a-zA-Z0-9_]+"
data-i18n-title="scripts.placeholder.name" title="Only letters, numbers, and underscores allowed" maxlength="64">
</label>
<label>
<span data-i18n="scripts.field.label">Label</span>
<input type="text" id="scriptLabel" data-i18n-placeholder="scripts.placeholder.label" placeholder="Human-readable name">
</label>
<label>
<span data-i18n="scripts.field.command">Command *</span>
<textarea id="scriptCommand" required rows="3" data-i18n-placeholder="scripts.placeholder.command" placeholder="e.g., shutdown /s /t 0"></textarea>
</label>
<label>
<span data-i18n="scripts.field.description">Description</span>
<textarea id="scriptDescription" data-i18n-placeholder="scripts.placeholder.description" placeholder="What does this script do?"></textarea>
</label>
<label>
<span data-i18n="scripts.field.icon">Icon (MDI)</span>
<input type="text" id="scriptIcon" data-i18n-placeholder="scripts.placeholder.icon" placeholder="e.g., mdi:power">
</label>
<label>
<span data-i18n="scripts.field.timeout">Timeout (seconds)</span>
<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()" data-i18n="scripts.button.cancel">Cancel</button>
<button type="submit" class="btn-primary" data-i18n="scripts.button.save">Save</button>
</div>
</form>
</dialog>
<!-- Add/Edit Callback Dialog -->
<dialog id="callbackDialog">
<div class="dialog-header">
<h3 id="callbackDialogTitle" data-i18n="callbacks.dialog.add">Add Callback</h3>
</div>
<form id="callbackForm" onsubmit="saveCallback(event)">
<div class="dialog-body">
<input type="hidden" id="callbackIsEdit">
<label>
<span data-i18n="callbacks.field.event">Event *</span>
<select id="callbackName" required>
<option value="" data-i18n="callbacks.placeholder.event">Select event...</option>
<option value="on_play" data-i18n="callbacks.event.on_play">on_play - After play succeeds</option>
<option value="on_pause" data-i18n="callbacks.event.on_pause">on_pause - After pause succeeds</option>
<option value="on_stop" data-i18n="callbacks.event.on_stop">on_stop - After stop succeeds</option>
<option value="on_next" data-i18n="callbacks.event.on_next">on_next - After next track succeeds</option>
<option value="on_previous" data-i18n="callbacks.event.on_previous">on_previous - After previous track succeeds</option>
<option value="on_volume" data-i18n="callbacks.event.on_volume">on_volume - After volume change</option>
<option value="on_mute" data-i18n="callbacks.event.on_mute">on_mute - After mute toggle</option>
<option value="on_seek" data-i18n="callbacks.event.on_seek">on_seek - After seek succeeds</option>
<option value="on_turn_on" data-i18n="callbacks.event.on_turn_on">on_turn_on - Callback-only action</option>
<option value="on_turn_off" data-i18n="callbacks.event.on_turn_off">on_turn_off - Callback-only action</option>
<option value="on_toggle" data-i18n="callbacks.event.on_toggle">on_toggle - Callback-only action</option>
</select>
</label>
<label>
<span data-i18n="callbacks.field.command">Command *</span>
<textarea id="callbackCommand" required rows="3" data-i18n-placeholder="callbacks.placeholder.command" placeholder="e.g., shutdown /s /t 0"></textarea>
</label>
<label>
<span data-i18n="callbacks.field.timeout">Timeout (seconds)</span>
<input type="number" id="callbackTimeout" value="30" min="1" max="300">
</label>
<label>
<span data-i18n="callbacks.field.workdir">Working Directory</span>
<input type="text" id="callbackWorkingDir" data-i18n-placeholder="callbacks.placeholder.workdir" placeholder="Optional">
</label>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" onclick="closeCallbackDialog()" data-i18n="callbacks.button.cancel">Cancel</button>
<button type="submit" class="btn-primary" data-i18n="callbacks.button.save">Save</button>
</div>
</form>
</dialog>
<!-- Execution Result Dialog -->
<dialog id="executionDialog">
<div class="dialog-header">
<h3 id="executionDialogTitle" data-i18n="scripts.execution.title">Execution Result</h3>
</div>
<div class="dialog-body">
<div class="execution-status" id="executionStatus"></div>
<div class="result-section" id="outputSection" style="display: none;">
<h4 data-i18n="scripts.execution.output">Output</h4>
<div class="execution-result">
<pre id="executionOutput"></pre>
</div>
</div>
<div class="result-section" id="errorSection" style="display: none;">
<h4 data-i18n="scripts.execution.error_output">Error Output</h4>
<div class="execution-result">
<pre id="executionError"></pre>
</div>
</div>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" onclick="closeExecutionDialog()" data-i18n="scripts.execution.close">Close</button>
</div>
</dialog>
<!-- Folder Management Dialog -->
<dialog id="folderDialog">
<div class="dialog-header">
<h3 id="folderDialogTitle" data-i18n="browser.folder_dialog.title_add">Add Media Folder</h3>
</div>
<form id="folderForm" onsubmit="saveFolder(event)">
<div class="dialog-body">
<input type="hidden" id="folderIsEdit">
<input type="hidden" id="folderOriginalId">
<label>
<span data-i18n="browser.folder_dialog.folder_id">Folder ID *</span>
<input type="text" id="folderId" required pattern="[a-zA-Z0-9_]+"
data-i18n-title="browser.folder_dialog.folder_id_help" title="Alphanumeric and underscore only" maxlength="32">
</label>
<label>
<span data-i18n="browser.folder_dialog.label">Label *</span>
<input type="text" id="folderLabel" required data-i18n-placeholder="browser.folder_dialog.label_help" placeholder="Display name">
</label>
<label>
<span data-i18n="browser.folder_dialog.path">Path *</span>
<input type="text" id="folderPath" required data-i18n-placeholder="browser.folder_dialog.path_help" placeholder="C:\Users\YourName\Music">
</label>
<label style="display: flex; align-items: center; gap: 0.5rem;">
<input type="checkbox" id="folderEnabled" checked style="width: auto; margin: 0;">
<span data-i18n="browser.folder_dialog.enabled">Enabled</span>
</label>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" onclick="closeFolderDialog()" data-i18n="browser.folder_dialog.cancel">Cancel</button>
<button type="submit" class="btn-primary" data-i18n="browser.folder_dialog.save">Save</button>
</div>
</form>
</dialog>
<!-- Toast Notification -->
<div class="toast" id="toast"></div>
<!-- Footer -->
<footer>
<div>
<span data-i18n="footer.created_by">Created by</span> <strong>Alexei Dolgolyov</strong>
<span class="separator"></span>
<a href="mailto:dolgolyov.alexei@gmail.com">dolgolyov.alexei@gmail.com</a>
<span class="separator"></span>
<a href="https://git.dolgolyov-family.by/alexei.dolgolyov/media-player-server" target="_blank" rel="noopener noreferrer" data-i18n="footer.source_code">Source Code</a>
</div>
</footer>
<script src="/static/js/app.js"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
{
"app.title": "Media Server",
"auth.message": "Enter your API token to connect to the media server.",
"auth.placeholder": "Enter API Token",
"auth.connect": "Connect",
"auth.help": "To get your token, run:",
"auth.logout": "Logout",
"auth.logout.title": "Clear saved token",
"auth.invalid": "Invalid token. Please try again.",
"auth.cleared": "Token cleared. Please enter a new token.",
"auth.required": "Please enter a token",
"player.theme": "Toggle theme",
"player.locale": "Change language",
"player.previous": "Previous",
"player.play": "Play/Pause",
"player.next": "Next",
"player.mute": "Mute",
"player.status.connected": "Connected",
"player.status.disconnected": "Disconnected",
"player.no_media": "No media playing",
"player.title_unavailable": "Title unavailable",
"player.source": "Source:",
"player.unknown_source": "Unknown",
"player.vinyl": "Vinyl mode",
"state.playing": "Playing",
"state.paused": "Paused",
"state.stopped": "Stopped",
"state.idle": "Idle",
"scripts.quick_actions": "Quick Actions",
"scripts.no_scripts": "No scripts configured",
"scripts.management": "Script Management",
"scripts.add": "Add",
"scripts.table.name": "Name",
"scripts.table.label": "Label",
"scripts.table.command": "Command",
"scripts.table.timeout": "Timeout",
"scripts.table.actions": "Actions",
"scripts.empty": "No scripts configured. Click 'Add' to create one.",
"scripts.dialog.add": "Add Script",
"scripts.dialog.edit": "Edit Script",
"scripts.field.name": "Script Name *",
"scripts.field.label": "Label",
"scripts.field.command": "Command *",
"scripts.field.description": "Description",
"scripts.field.icon": "Icon (MDI)",
"scripts.field.timeout": "Timeout (seconds)",
"scripts.placeholder.name": "Only letters, numbers, and underscores allowed",
"scripts.placeholder.label": "Human-readable name",
"scripts.placeholder.command": "e.g., shutdown /s /t 0",
"scripts.placeholder.description": "What does this script do?",
"scripts.placeholder.icon": "e.g., mdi:power",
"scripts.button.cancel": "Cancel",
"scripts.button.save": "Save",
"scripts.button.edit": "Edit",
"scripts.button.delete": "Delete",
"scripts.msg.executed": "{name} executed successfully",
"scripts.msg.execute_failed": "Failed to execute {name}",
"scripts.msg.execute_error": "Error executing {name}",
"scripts.msg.created": "Script created successfully",
"scripts.msg.updated": "Script updated successfully",
"scripts.msg.create_failed": "Failed to create script",
"scripts.msg.update_failed": "Failed to update script",
"scripts.msg.deleted": "Script deleted successfully",
"scripts.msg.delete_failed": "Failed to delete script",
"scripts.msg.not_found": "Script not found",
"scripts.msg.load_failed": "Failed to load script details",
"scripts.msg.list_failed": "Failed to load scripts",
"scripts.confirm.delete": "Are you sure you want to delete the script \"{name}\"?",
"scripts.execution.title": "Execution Result",
"scripts.execution.output": "Output",
"scripts.execution.error_output": "Error Output",
"scripts.execution.close": "Close",
"scripts.confirm.unsaved": "You have unsaved changes. Are you sure you want to discard them?",
"callbacks.management": "Callback Management",
"callbacks.description": "Callbacks are scripts triggered automatically by media control events (play, pause, stop, etc.)",
"callbacks.add": "Add",
"callbacks.table.event": "Event",
"callbacks.table.command": "Command",
"callbacks.table.timeout": "Timeout",
"callbacks.table.actions": "Actions",
"callbacks.empty": "No callbacks configured. Click 'Add' to create one.",
"callbacks.dialog.add": "Add Callback",
"callbacks.dialog.edit": "Edit Callback",
"callbacks.field.event": "Event *",
"callbacks.field.command": "Command *",
"callbacks.field.timeout": "Timeout (seconds)",
"callbacks.field.workdir": "Working Directory",
"callbacks.placeholder.event": "Select event...",
"callbacks.placeholder.command": "e.g., shutdown /s /t 0",
"callbacks.placeholder.workdir": "Optional",
"callbacks.button.cancel": "Cancel",
"callbacks.button.save": "Save",
"callbacks.button.edit": "Edit",
"callbacks.button.delete": "Delete",
"callbacks.event.on_play": "on_play - After play succeeds",
"callbacks.event.on_pause": "on_pause - After pause succeeds",
"callbacks.event.on_stop": "on_stop - After stop succeeds",
"callbacks.event.on_next": "on_next - After next track succeeds",
"callbacks.event.on_previous": "on_previous - After previous track succeeds",
"callbacks.event.on_volume": "on_volume - After volume change",
"callbacks.event.on_mute": "on_mute - After mute toggle",
"callbacks.event.on_seek": "on_seek - After seek succeeds",
"callbacks.event.on_turn_on": "on_turn_on - Callback-only action",
"callbacks.event.on_turn_off": "on_turn_off - Callback-only action",
"callbacks.event.on_toggle": "on_toggle - Callback-only action",
"callbacks.msg.created": "Callback created successfully",
"callbacks.msg.updated": "Callback updated successfully",
"callbacks.msg.create_failed": "Failed to create callback",
"callbacks.msg.update_failed": "Failed to update callback",
"callbacks.msg.deleted": "Callback deleted successfully",
"callbacks.msg.delete_failed": "Failed to delete callback",
"callbacks.msg.not_found": "Callback not found",
"callbacks.msg.load_failed": "Failed to load callback details",
"callbacks.msg.list_failed": "Failed to load callbacks",
"callbacks.confirm.delete": "Are you sure you want to delete the callback \"{name}\"?",
"callbacks.confirm.unsaved": "You have unsaved changes. Are you sure you want to discard them?",
"tab.player": "Player",
"tab.browser": "Browser",
"tab.quick_actions": "Actions",
"tab.scripts": "Scripts",
"tab.callbacks": "Callbacks",
"browser.title": "Media Browser",
"browser.home": "Home",
"browser.manage_folders": "Manage Folders",
"browser.select_folder": "Select a folder...",
"browser.select_folder_option": "Select a folder...",
"browser.no_folder_selected": "Select a folder to browse media files",
"browser.no_items": "No media files found in this folder",
"browser.view_grid": "Grid view",
"browser.view_compact": "Compact view",
"browser.view_list": "List view",
"browser.search": "Search...",
"browser.items_per_page": "Items per page:",
"browser.page": "Page",
"browser.previous": "Previous",
"browser.next": "Next",
"browser.download": "Download",
"browser.play_success": "Playing {filename}",
"browser.play_error": "Failed to play file",
"browser.play_all": "Play All",
"browser.play_all_success": "Playing {count} files",
"browser.play_all_error": "Failed to play folder",
"browser.error_loading": "Error loading directory",
"browser.error_loading_folders": "Failed to load media folders",
"browser.manage_folders_hint": "Folder management coming soon! For now, edit config.yaml to add media folders.",
"browser.folder_dialog.title_add": "Add Media Folder",
"browser.folder_dialog.title_edit": "Edit Media Folder",
"browser.folder_dialog.folder_id": "Folder ID *",
"browser.folder_dialog.folder_id_help": "Alphanumeric and underscore only",
"browser.folder_dialog.label": "Label *",
"browser.folder_dialog.label_help": "Display name for this folder",
"browser.folder_dialog.path": "Path *",
"browser.folder_dialog.path_help": "Absolute path to media directory",
"browser.folder_dialog.enabled": "Enabled",
"browser.folder_dialog.cancel": "Cancel",
"browser.folder_dialog.save": "Save",
"footer.created_by": "Created by",
"footer.source_code": "Source Code"
}

View File

@@ -0,0 +1,159 @@
{
"app.title": "Медиа Сервер",
"auth.message": "Введите API токен для подключения к медиа серверу.",
"auth.placeholder": "Введите API токен",
"auth.connect": "Подключиться",
"auth.help": "Чтобы получить токен, выполните:",
"auth.logout": "Выйти",
"auth.logout.title": "Очистить сохраненный токен",
"auth.invalid": "Неверный токен. Пожалуйста, попробуйте снова.",
"auth.cleared": "Токен очищен. Пожалуйста, введите новый токен.",
"auth.required": "Пожалуйста, введите токен",
"player.theme": "Переключить тему",
"player.locale": "Изменить язык",
"player.previous": "Предыдущий",
"player.play": "Воспроизвести/Пауза",
"player.next": "Следующий",
"player.mute": "Без звука",
"player.status.connected": "Подключено",
"player.status.disconnected": "Отключено",
"player.no_media": "Медиа не воспроизводится",
"player.title_unavailable": "Название недоступно",
"player.source": "Источник:",
"player.unknown_source": "Неизвестно",
"player.vinyl": "Режим винила",
"state.playing": "Воспроизведение",
"state.paused": "Пауза",
"state.stopped": "Остановлено",
"state.idle": "Ожидание",
"scripts.quick_actions": "Быстрые Действия",
"scripts.no_scripts": "Скрипты не настроены",
"scripts.management": "Управление Скриптами",
"scripts.add": "Добавить",
"scripts.table.name": "Имя",
"scripts.table.label": "Метка",
"scripts.table.command": "Команда",
"scripts.table.timeout": "Таймаут",
"scripts.table.actions": "Действия",
"scripts.empty": "Скрипты не настроены. Нажмите 'Добавить' для создания.",
"scripts.dialog.add": "Добавить Скрипт",
"scripts.dialog.edit": "Редактировать Скрипт",
"scripts.field.name": "Имя Скрипта *",
"scripts.field.label": "Метка",
"scripts.field.command": "Команда *",
"scripts.field.description": "Описание",
"scripts.field.icon": "Иконка (MDI)",
"scripts.field.timeout": "Таймаут (секунды)",
"scripts.placeholder.name": "Только буквы, цифры и подчеркивания",
"scripts.placeholder.label": "Человеко-читаемое имя",
"scripts.placeholder.command": "например, shutdown /s /t 0",
"scripts.placeholder.description": "Что делает этот скрипт?",
"scripts.placeholder.icon": "например, mdi:power",
"scripts.button.cancel": "Отмена",
"scripts.button.save": "Сохранить",
"scripts.button.edit": "Редактировать",
"scripts.button.delete": "Удалить",
"scripts.msg.executed": "{name} выполнен успешно",
"scripts.msg.execute_failed": "Не удалось выполнить {name}",
"scripts.msg.execute_error": "Ошибка выполнения {name}",
"scripts.msg.created": "Скрипт создан успешно",
"scripts.msg.updated": "Скрипт обновлен успешно",
"scripts.msg.create_failed": "Не удалось создать скрипт",
"scripts.msg.update_failed": "Не удалось обновить скрипт",
"scripts.msg.deleted": "Скрипт удален успешно",
"scripts.msg.delete_failed": "Не удалось удалить скрипт",
"scripts.msg.not_found": "Скрипт не найден",
"scripts.msg.load_failed": "Не удалось загрузить данные скрипта",
"scripts.msg.list_failed": "Не удалось загрузить скрипты",
"scripts.confirm.delete": "Вы уверены, что хотите удалить скрипт \"{name}\"?",
"scripts.execution.title": "Результат выполнения",
"scripts.execution.output": "Вывод",
"scripts.execution.error_output": "Вывод ошибок",
"scripts.execution.close": "Закрыть",
"scripts.confirm.unsaved": "У вас есть несохраненные изменения. Вы уверены, что хотите отменить их?",
"callbacks.management": "Управление Обратными Вызовами",
"callbacks.description": "Обратные вызовы - это скрипты, автоматически запускаемые при событиях управления медиа (воспроизведение, пауза, остановка и т.д.)",
"callbacks.add": "Добавить",
"callbacks.table.event": "Событие",
"callbacks.table.command": "Команда",
"callbacks.table.timeout": "Таймаут",
"callbacks.table.actions": "Действия",
"callbacks.empty": "Обратные вызовы не настроены. Нажмите 'Добавить' для создания.",
"callbacks.dialog.add": "Добавить Обратный Вызов",
"callbacks.dialog.edit": "Редактировать Обратный Вызов",
"callbacks.field.event": "Событие *",
"callbacks.field.command": "Команда *",
"callbacks.field.timeout": "Таймаут (секунды)",
"callbacks.field.workdir": "Рабочая Директория",
"callbacks.placeholder.event": "Выберите событие...",
"callbacks.placeholder.command": "например, shutdown /s /t 0",
"callbacks.placeholder.workdir": "Опционально",
"callbacks.button.cancel": "Отмена",
"callbacks.button.save": "Сохранить",
"callbacks.button.edit": "Редактировать",
"callbacks.button.delete": "Удалить",
"callbacks.event.on_play": "on_play - После успешного воспроизведения",
"callbacks.event.on_pause": "on_pause - После успешной паузы",
"callbacks.event.on_stop": "on_stop - После успешной остановки",
"callbacks.event.on_next": "on_next - После успешного перехода к следующему",
"callbacks.event.on_previous": "on_previous - После успешного перехода к предыдущему",
"callbacks.event.on_volume": "on_volume - После изменения громкости",
"callbacks.event.on_mute": "on_mute - После переключения звука",
"callbacks.event.on_seek": "on_seek - После успешной перемотки",
"callbacks.event.on_turn_on": "on_turn_on - Действие только для обратных вызовов",
"callbacks.event.on_turn_off": "on_turn_off - Действие только для обратных вызовов",
"callbacks.event.on_toggle": "on_toggle - Действие только для обратных вызовов",
"callbacks.msg.created": "Обратный вызов создан успешно",
"callbacks.msg.updated": "Обратный вызов обновлен успешно",
"callbacks.msg.create_failed": "Не удалось создать обратный вызов",
"callbacks.msg.update_failed": "Не удалось обновить обратный вызов",
"callbacks.msg.deleted": "Обратный вызов удален успешно",
"callbacks.msg.delete_failed": "Не удалось удалить обратный вызов",
"callbacks.msg.not_found": "Обратный вызов не найден",
"callbacks.msg.load_failed": "Не удалось загрузить данные обратного вызова",
"callbacks.msg.list_failed": "Не удалось загрузить обратные вызовы",
"callbacks.confirm.delete": "Вы уверены, что хотите удалить обратный вызов \"{name}\"?",
"callbacks.confirm.unsaved": "У вас есть несохраненные изменения. Вы уверены, что хотите отменить их?",
"tab.player": "Плеер",
"tab.browser": "Браузер",
"tab.quick_actions": "Действия",
"tab.scripts": "Скрипты",
"tab.callbacks": "Колбэки",
"browser.title": "Медиа Браузер",
"browser.home": "Главная",
"browser.manage_folders": "Управление папками",
"browser.select_folder": "Выберите папку...",
"browser.select_folder_option": "Выберите папку...",
"browser.no_folder_selected": "Выберите папку для просмотра медиафайлов",
"browser.no_items": "В этой папке не найдено медиафайлов",
"browser.view_grid": "Сетка",
"browser.view_compact": "Компактный вид",
"browser.view_list": "Список",
"browser.search": "Поиск...",
"browser.items_per_page": "Элементов на странице:",
"browser.page": "Страница",
"browser.previous": "Предыдущая",
"browser.next": "Следующая",
"browser.download": "Скачать",
"browser.play_success": "Воспроизведение {filename}",
"browser.play_error": "Не удалось воспроизвести файл",
"browser.play_all": "Воспроизвести все",
"browser.play_all_success": "Воспроизведение {count} файлов",
"browser.play_all_error": "Не удалось воспроизвести папку",
"browser.error_loading": "Ошибка загрузки каталога",
"browser.error_loading_folders": "Не удалось загрузить медиа папки",
"browser.manage_folders_hint": "Управление папками скоро появится! Пока редактируйте config.yaml для добавления медиа папок.",
"browser.folder_dialog.title_add": "Добавить медиа папку",
"browser.folder_dialog.title_edit": "Редактировать медиа папку",
"browser.folder_dialog.folder_id": "ID папки *",
"browser.folder_dialog.folder_id_help": "Только буквы, цифры и подчеркивание",
"browser.folder_dialog.label": "Метка *",
"browser.folder_dialog.label_help": "Отображаемое имя папки",
"browser.folder_dialog.path": "Путь *",
"browser.folder_dialog.path_help": "Абсолютный путь к медиа каталогу",
"browser.folder_dialog.enabled": "Включено",
"browser.folder_dialog.cancel": "Отмена",
"browser.folder_dialog.save": "Сохранить",
"footer.created_by": "Создано",
"footer.source_code": "Исходный код"
}

View File

@@ -30,6 +30,8 @@ dependencies = [
"pydantic>=2.0",
"pydantic-settings>=2.0",
"pyyaml>=6.0",
"mutagen>=1.47.0",
"pillow>=10.0.0",
]
[project.optional-dependencies]

View File

@@ -0,0 +1,19 @@
Unregister-ScheduledTask -TaskName "MediaServer" -Confirm:$false -ErrorAction SilentlyContinue
# Get the media-server directory (parent of scripts folder)
$serverRoot = (Get-Item $PSScriptRoot).Parent.FullName
$vbsPath = Join-Path $PSScriptRoot "start-hidden.vbs"
if (-not (Test-Path $vbsPath)) {
Write-Error "start-hidden.vbs not found in scripts folder."
exit 1
}
# Launch via wscript + VBS to run python completely hidden (no console window)
$action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$vbsPath`"" -WorkingDirectory $serverRoot
$trigger = New-ScheduledTaskTrigger -AtLogon -User "$env:USERNAME"
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -LogonType Interactive -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
Register-ScheduledTask -TaskName "MediaServer" -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Media Server for Home Assistant"
Write-Host "Scheduled task 'MediaServer' created with working directory: $serverRoot"

View File

@@ -0,0 +1,24 @@
@echo off
REM Media Server Restart Script
REM This script restarts the media server
echo Restarting Media Server...
echo.
REM Stop the server first
echo [1/2] Stopping server...
call "%~dp0\stop-server.bat"
REM Wait a moment
timeout /t 2 /nobreak >nul
REM Change to parent directory (media-server root)
cd /d "%~dp0\.."
REM Start the server
echo.
echo [2/2] Starting server...
python -m media_server.main
REM If the server exits, pause to show any error messages
pause

7
scripts/start-hidden.vbs Normal file
View File

@@ -0,0 +1,7 @@
Set WshShell = CreateObject("WScript.Shell")
' Get the directory of this script (scripts\), then go up to media-server root
scriptDir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
serverRoot = CreateObject("Scripting.FileSystemObject").GetParentFolderName(scriptDir)
WshShell.CurrentDirectory = serverRoot
' Run python completely hidden (0 = hidden, False = don't wait)
WshShell.Run "python -m media_server.main", 0, False

View File

@@ -0,0 +1,7 @@
Set WshShell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
' Get parent folder of scripts folder (media-server root)
WshShell.CurrentDirectory = FSO.GetParentFolderName(FSO.GetParentFolderName(WScript.ScriptFullName))
WshShell.Run "python -m media_server.main", 0, False
Set FSO = Nothing
Set WshShell = Nothing

15
scripts/start-server.bat Normal file
View File

@@ -0,0 +1,15 @@
@echo off
REM Media Server Startup Script
REM This script starts the media server
echo Starting Media Server...
echo.
REM Change to the media-server directory (parent of scripts folder)
cd /d "%~dp0\.."
REM Start the media server
python -m media_server.main
REM If the server exits, pause to show any error messages
pause

19
scripts/stop-server.bat Normal file
View File

@@ -0,0 +1,19 @@
@echo off
REM Media Server Stop Script
REM This script stops the running media server
echo Stopping Media Server...
echo.
REM Find and kill Python processes running media_server.main
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq python.exe" /FO LIST ^| findstr /B "PID:"') do (
wmic process where "ProcessId=%%i" get CommandLine 2>nul | findstr /C:"media_server.main" >nul
if not errorlevel 1 (
taskkill /PID %%i /F
echo Media server process (PID %%i) terminated.
)
)
echo.
echo Done! Media server stopped.
pause