# MbetterClient

A cross-platform multimedia client application with video playback, web dashboard, and REST API integration.

## Features

- **PyQt Video Player**: Fullscreen video playback with dual overlay system (WebEngine and native Qt widgets)
- **Template Management System**: Upload, manage, and live-reload HTML overlay templates with persistent storage
- **Web Dashboard**: Authentication, user management, configuration interface, and admin system controls
- **REST API Client**: Configurable external API integration with automatic retry
- **Multi-threaded Architecture**: Four threads with Queue-based message passing and proper daemon thread management
- **Offline Capability**: Works seamlessly without internet connectivity
- **Cross-Platform**: Supports Windows, Linux, and macOS
- **Single Executable**: Built with PyInstaller for easy deployment
- **API Token Management**: Create, manage, and revoke long-lived API tokens
- **User Management**: Complete user registration and administration system
- **Configuration Management**: Web-based configuration with section-based updates
- **Remote Shutdown**: Admin-only application shutdown from web dashboard
- **Overlay System**: Command-line switchable between WebEngine and native Qt overlay rendering

## Recent Improvements

### Version 1.2.3 (August 2025)

- ✅ **Boxing Match Database**: Added comprehensive `matches` and `match_outcomes` database tables adapted from mbetterd MySQL schema
- ✅ **Cross-Platform Persistence**: Complete PyInstaller executable persistence with platform-specific user directories
- ✅ **Match Data Management**: Full SQLAlchemy models for boxing match tracking with fighter townships, venues, and outcomes
- ✅ **Fixtures Management System**: Complete fixtures dashboard with API synchronization, database integration, and administrative controls
- ✅ **API Synchronization**: Real-time fixture and match data synchronization with server using proper Unix timestamp format
- ✅ **File Upload Tracking**: ZIP file upload management with progress tracking and status monitoring
- ✅ **Database Migration System**: Migration_008_AddMatchTables with comprehensive indexing and foreign key relationships
- ✅ **User Data Directories**: Automatic creation of persistent directories on Windows (%APPDATA%), macOS (~/Library/Application Support), and Linux (~/.local/share)
- ✅ **Robust Error Handling**: Fallback directory creation with permission testing and write verification
- ✅ **Cross-Platform Testing**: Comprehensive test suite verifying directory creation and database persistence across all platforms

### Version 1.2.2 (August 2025)

- ✅ **Template Management System**: Complete HTML overlay template management with upload, delete, and real-time editing capabilities
- ✅ **Persistent Template Storage**: Cross-platform user template storage that survives PyInstaller executable updates
- ✅ **Template Priority System**: Uploaded templates automatically override built-in templates with same filename
- ✅ **JavaScript Resource Access**: Custom URL scheme handler enables uploaded templates to access overlay.js functionality
- ✅ **Live Template Switching**: Dashboard forms now switch to selected template instantly with overlay updates
- ✅ **Template Code Viewer**: View and copy template source code directly from web interface
- ✅ **File Watcher Integration**: Automatic template reloading when files change on disk
- ✅ **Enhanced Template UI**: Popup preview windows and comprehensive template management interface

### Version 1.2.1 (August 2025)

- ✅ **CRITICAL FIX: Video Display Resolved**: Completely fixed Qt video player black screen issue - video frames now render properly on all platforms
- ✅ **CRITICAL FIX: Window Behavior**: Resolved WindowStaysOnTopHint interference with video rendering by fixing always_on_top configuration
- ✅ **CRITICAL FIX: Database Persistence**: Fixed configuration loading sequence to prevent old database settings from overriding new defaults
- ✅ **Clean Minimal Interface**: Removed all toolbars, menu bars, status bars, and context menus for professional video player appearance
- ✅ **Complete Keyboard Control**: All functionality accessible via keyboard shortcuts (F11: fullscreen, S: stats, Space: play/pause, M: mute)
- ✅ **Window Management**: Main window now properly goes behind other applications, overlay window stays on top as intended
- ✅ **Configuration Reset**: Implemented database reset mechanism to clear cached configuration conflicts
- ✅ **Threading Architecture**: Qt player runs on main thread with background components properly separated

### Version 1.2.0 (August 2025)

- ✅ **Qt Player Overlay System**: Implemented dual overlay system with command-line switchable options between QWebEngineView and native Qt widgets
- ✅ **Complete Shutdown System**: Fixed critical application shutdown issues - Qt window close, Ctrl+C, and web dashboard all properly terminate entire application
- ✅ **Admin Dashboard Controls**: Added admin-only quit button to web dashboard with guaranteed force termination mechanism
- ✅ **Threading Architecture**: Fixed background thread management with proper daemon threads preventing exit blocking
- ✅ **WebEngine Stability**: Significantly reduced JavaScript timing errors with enhanced DOM readiness checks and error handling
- ✅ **Transparency Issues**: Resolved desktop transparency bleed-through by removing problematic window attributes
- ✅ **Clean Video Interface**: Removed video controls for overlay-only display mode
- ✅ **Circular Dependency Prevention**: Eliminated shutdown deadlocks using force-exit mechanism with delayed execution

### Version 1.1 (August 2025)

- ✅ **Fixed Token Management**: API tokens now properly display after creation and can be permanently deleted when revoked
- ✅ **Enhanced User Management**: Fixed user creation issues, users now save properly and display immediately in management interface
- ✅ **Improved Shutdown Handling**: Application now exits gracefully with single Ctrl+C press instead of requiring two
- ✅ **Configuration Management**: Added missing configuration update methods for web dashboard settings
- ✅ **Session Management**: Resolved SQLAlchemy session binding issues that caused data access errors
- ✅ **Frontend Integration**: Enhanced token creation workflow with professional modal dialogs and proper error handling
- ✅ **Database Stability**: All database operations now extract data before session closure to prevent binding errors
- ✅ **Signal Handling**: Optimized application shutdown process with reduced timeouts for faster exit

## Architecture

The application consists of four main threads:

1. **PyQt Thread**: Video player with overlay rendering
2. **Web Dashboard Thread**: Flask-based web interface
3. **REST API Client Thread**: External API communication
4. **Main Loop Thread**: Inter-thread message coordination

## Quick Start

### Installation

```bash
# Clone the repository
git clone https://git.nexlab.net/mbetter/mbetterc.git
cd mbetterc

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

### Running the Application

```bash
# Run in fullscreen mode (default)
python main.py

# Run in windowed mode
python main.py --no-fullscreen

# Use native Qt overlays instead of WebEngine
python main.py --overlay-type native

# Use WebEngine overlays (default)
python main.py --overlay-type webengine

# Show help
python main.py --help
```

### Building Executable

```bash
# Build for current platform
python build.py

# The executable will be in dist/ directory
```

## Configuration

Configuration is stored in SQLite database with automatic versioning. Access the web dashboard at `http://localhost:5001` (default) to configure:

- Video overlay templates
- REST API endpoints and tokens  
- User authentication
- System settings
- API token management
- User account management

### Default Login

The application creates a default admin account on first run:
- **Username**: `admin`
- **Password**: `admin123`

**Important**: Change the default password immediately after first login for security.

## Development

### Project Structure

```
mbetterc/
├── main.py                 # Application entry point
├── requirements.txt        # Python dependencies
├── build.py               # PyInstaller build script
├── mbetterclient/         # Main application package
│   ├── __init__.py
│   ├── config/            # Configuration management
│   ├── database/          # SQLite database and models
│   ├── qt_player/         # PyQt video player
│   ├── web_dashboard/     # Flask web interface
│   ├── api_client/        # REST API client
│   ├── core/              # Main loop and message handling
│   └── utils/             # Utility functions
├── assets/                # Static assets (images, templates)
├── templates/             # Video overlay templates (built-in)
├── tests/                 # Unit tests
└── docs/                  # Documentation

# Persistent User Data Directories (Created automatically for PyInstaller compatibility)
# Windows: %APPDATA%\MbetterClient\ (data, config, templates, logs)
# macOS: ~/Library/Application Support/MbetterClient/ (unified location)
# Linux: ~/.local/share/MbetterClient/ (data) & ~/.config/MbetterClient/ (config)
```

### Message System

Threads communicate via Python Queues with structured messages:

```python
{
    "type": "VIDEO_PLAY",
    "data": {
        "file_path": "/path/to/video.mp4",
        "template": "news_template",
        "overlay_data": {...}
    },
    "timestamp": 1234567890.123,
    "sender": "web_dashboard"
}
```

## API Documentation

### Web Dashboard API

#### Authentication
- `POST /auth/login` - User authentication
- `POST /auth/logout` - User logout

#### Token Management
- `GET /api/tokens` - List user API tokens
- `POST /api/tokens` - Create new API token
- `DELETE /api/tokens/{id}` - Delete API token (permanent deletion)

#### User Management (Admin only)
- `GET /api/users` - List all users
- `POST /api/users` - Create new user
- `DELETE /api/users/{id}` - Delete user

#### Configuration Management
- `GET /api/config` - Get configuration
- `PUT /api/config/{section}` - Update configuration section
- `GET /api/config/{section}` - Get specific configuration section

#### Template Management
- `GET /api/templates` - List available overlay templates
- `POST /api/templates/upload` - Upload new template file
- `DELETE /api/templates/{name}` - Delete uploaded template
- `GET /api/templates/{name}/preview` - Preview template in browser
- `GET /api/templates/{name}/source` - Get template source code

#### Video Control
- `POST /api/video/control` - Control video playback (play, pause, stop, etc.)
- `GET /api/video/status` - Get current video player status
- `POST /api/video/upload` - Upload video file for playback
- `POST /api/overlay` - Update overlay content and switch templates

### Message Types

#### Video Control
- `VIDEO_PLAY` - Start video playback
- `VIDEO_PAUSE` - Pause video
- `VIDEO_STOP` - Stop video
- `VIDEO_PROGRESS` - Progress update from player

#### API Client
- `API_REQUEST` - Make external API request
- `API_RESPONSE` - Response from external API
- `API_ERROR` - API request error

#### Configuration
- `CONFIG_UPDATE` - Configuration changed
- `TEMPLATE_CHANGE` - Video template changed
- `OVERLAY_UPDATE` - Overlay content updated

#### System Messages
- `SYSTEM_SHUTDOWN` - Application shutdown request
- `SYSTEM_STATUS` - Component status update
- `LOG_ENTRY` - Log entry for database storage

## Troubleshooting

### Common Issues

**Application requires two Ctrl+C to exit**
- Fixed in version 1.1 - application now exits gracefully with single Ctrl+C

**API tokens not displaying after creation**
- Fixed in version 1.1 - tokens now show in professional modal dialog

**User creation fails or users don't appear**
- Fixed in version 1.1 - resolved SQLAlchemy session binding issues

**Configuration updates not working**
- Fixed in version 1.1 - added missing configuration section update methods

**Database errors during operation**
- Fixed in version 1.1 - all database operations now properly handle session closure

### Building Issues

**PyInstaller build fails with missing modules**
- Ensure all dependencies are installed: `pip install -r requirements.txt`
- Run build script: `python build.py`

**SQLite3 wheel build errors**
- Fixed in requirements.txt - simplified dependencies for better compatibility

### Web Dashboard Issues

**404 errors for CSS/JS files**
- Fixed in version 1.1 - updated to use CDN versions of Bootstrap and FontAwesome

**Token revocation doesn't work**
- Fixed in version 1.1 - tokens are now permanently deleted from database

## Testing Qt Player

To test the Qt player functionality, you can run the standalone test script:

```bash
# Test Qt player in standalone mode
python test_qt_player.py standalone

# Test Qt player with message bus communication
python test_qt_player.py message_bus
```

## License

Copyright (c) 2025 MBetter Project. All rights reserved.

## Support

For support and documentation, visit the project repository.