# 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)
- **Dynamic Betting System**: Complete database-driven betting interface with actual match outcomes replacing hardcoded terminology
- **Print Functionality**: Integrated print button for bet receipts with placeholder implementation ready for enhancement
- **Screen Casting System**: Complete screen capture and Chromecast streaming with web-based controls and device discovery
- **Template Management System**: Upload, manage, and live-reload HTML overlay templates with persistent storage
- **Extraction Management**: Complete drag-and-drop interface for managing outcome associations with extraction results
- **Server Time Digital Clock**: Prominent 24-hour format clock showing server time across all dashboard interfaces
- **Web Dashboard**: Authentication, user management, configuration interface, and admin system controls
- **REST API Client**: Configurable external API integration with automatic retry
- **Multi-threaded Architecture**: Five 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
- **Automated Game Timer**: Configurable timer system that sends START_GAME messages after specified delay

## Recent Improvements

### Version 1.2.11 (August 2025)

- ✅ **Critical Loop Functionality Fix**: Resolved video loop import scope error that prevented stop playback functionality from working
- ✅ **Fixtures Template Data Display**: Fixed fixtures template showing placeholder data instead of real match data from API endpoints
- ✅ **Template Background Transparency**: Guaranteed fully transparent backgrounds in overlay templates by removing green background tint
- ✅ **Video Loop Diagnostics**: Added comprehensive diagnostic logging system for troubleshooting video loop functionality issues
- ✅ **Enhanced Fallback Data**: Improved template fallback data with realistic fighter names and match information instead of generic placeholders
- ✅ **Template Loading Architecture**: Enhanced template initialization with proper loading states and graceful API failure handling

### Version 1.2.10 (August 2025)

- ✅ **Critical Bug Fixes**: Resolved critical betting system issues preventing bet creation and bet details page access
- ✅ **Fixture ID Constraint Fix**: Fixed NULL constraint violation in bet creation API by properly extracting fixture_id from match data
- ✅ **Bet Details Page Restoration**: Fixed 500 error in bet details route by implementing complete database data fetching and template variable population
- ✅ **Template Compatibility**: Resolved moment() undefined error in bet details template by removing server-side JavaScript calls
- ✅ **API Endpoint Corrections**: Fixed JavaScript API endpoint mismatches and added missing event handlers for bet management
- ✅ **Database Integration**: Enhanced bet creation with proper foreign key relationships and data consistency validation

### Version 1.2.9 (August 2025)

- ✅ **Dynamic Betting Outcomes System**: Complete database-driven betting outcomes replacing hardcoded WIN1/WIN2/X terminology
- ✅ **Print Functionality**: Added print button to bets list in cashier dashboard for bet receipt printing
- ✅ **Match Outcome Integration**: API endpoint enhanced to query match_outcomes table for actual betting options
- ✅ **Dynamic Frontend Generation**: JavaScript function to generate betting options from database outcomes
- ✅ **Graceful Fallback**: Maintains compatibility with standard betting options when database outcomes unavailable
- ✅ **Enhanced Betting System**: More accurate betting options reflect real match data rather than standardized terminology

### Version 1.2.8 (August 2025)

- ✅ **Offline CDN Fallback System**: Local copies of Bootstrap CSS/JS and FontAwesome with automatic fallback for offline networks
- ✅ **Enhanced Cashier Interface**: Streamlined navigation bar with clock and user menu positioned on the right side
- ✅ **PyInstaller CDN Integration**: All vendor files automatically included in executable builds for offline functionality
- ✅ **FontAwesome Icon Display**: Resolved icon rendering issues by prioritizing CDN with local fallback
- ✅ **Cashier Navigation Layout**: Fixed navbar positioning to show essential elements (clock, user menu) on right side
- ✅ **CDN Resource Loading**: Implemented proper fallback mechanism for offline network environments

### Version 1.2.7 (August 2025)

- ✅ **API Client Health Monitoring**: Fixed "Unhealthy components detected: ['api_client']" warning by implementing comprehensive heartbeat system
- ✅ **Betting Mode Configuration**: Added complete betting mode management in web dashboard with database persistence
- ✅ **Database Migration System**: Added Migration_015 for betting_modes table with proper schema and constraints
- ✅ **Enhanced Error Handling**: Improved API client error handling to prevent thread hangs and maintain health status
- ✅ **Configuration UI Enhancement**: Added betting mode settings section to configuration page with real-time feedback

### Version 1.2.6 (August 2025)

- ✅ **Automated Game Timer**: New `--start-timer` command line switch that sends START_GAME message after specified delay (default 4 minutes)
- ✅ **MatchTimerComponent Integration**: Fixed timer component initialization and registration with thread manager
- ✅ **Timer State API**: Real-time timer state API endpoints for web dashboard integration
- ✅ **Message Bus Communication**: Proper inter-thread communication between timer component and web dashboard
- ✅ **Timer Configuration**: Configurable timer delay with command-line parameter support

### Version 1.2.5 (August 2025)

- ✅ **Screen Casting Integration**: Complete screen capture and Chromecast streaming functionality integrated into MBetterC application
- ✅ **ScreenCastComponent**: New threaded component with HTTP server, FFmpeg screen capture, and Chromecast device management
- ✅ **Web-Based Screen Cast Control**: Comprehensive web interface at `/screen_cast` with device discovery, streaming controls, and real-time status
- ✅ **Chromecast Device Discovery**: Automatic discovery and management of Chromecast devices on the local network
- ✅ **Cross-Platform Screen Capture**: FFmpeg-based screen recording with platform-specific audio/video input sources for Linux, Windows, macOS
- ✅ **Administrative Settings**: Screen cast configuration panel in web dashboard with quality, bitrate, and network settings
- ✅ **Network Stream URLs**: Automatically generated network-accessible streaming URLs for Chromecast compatibility
- ✅ **Real-Time Status Updates**: Live status monitoring with proper button state management and streaming feedback
- ✅ **Command-Line Control**: Screen casting enabled by default with `--no-screen-cast` flag for opt-out configuration

### Version 1.2.5 (August 2025)

- ✅ **Extraction Management Page**: Complete drag-and-drop interface for managing outcome associations with extraction results
- ✅ **Server Time Digital Clock**: Prominent 24-hour format clock showing server time across all dashboard interfaces
- ✅ **Database Models for Extraction**: New `ExtractionAssociationModel` and `GameConfigModel` for storing outcome associations and game settings
- ✅ **Database Migration System**: Migration_014 for extraction associations and game configuration tables
- ✅ **API Endpoints for Extraction**: Complete REST API for managing outcome associations and game configuration
- ✅ **Drag & Drop Functionality**: Interactive outcome management with visual feedback and association persistence
- ✅ **Multi-Association Support**: Outcomes can be associated with multiple extraction results simultaneously
- ✅ **Trash Bin Removal**: Context-aware removal of associations based on drag source location
- ✅ **Game Configuration Panel**: Time limit settings for UNDER/OVER outcomes with database persistence
- ✅ **Server Time API**: `/api/server-time` endpoint providing server timestamp for accurate time display
- ✅ **Cross-Interface Clock**: Digital clock appears on all authenticated pages including cashier dashboard
- ✅ **Silent Drag & Drop**: No alert interruptions during drag-and-drop operations for smoother workflow
- ✅ **Time Synchronization**: Automatic server time sync every 30 seconds with offset calculation

### 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 five 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. **Screen Cast Thread**: Screen capture, HTTP streaming, and Chromecast management
5. **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 with screen casting enabled (default)
python main.py

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

# Disable screen casting functionality
python main.py --no-screen-cast

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

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

# Start with automated game timer (4 minutes default)
python main.py --start-timer

# Start with custom timer delay (2 minutes)
python main.py --start-timer 2

# Enable debug mode showing only message bus messages
python main.py --dev-message

# 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
- Screen casting settings and Chromecast devices
- REST API endpoints and tokens
- User authentication
- System settings
- API token management
- User account management
- Betting mode configuration (all bets on start vs one bet at a time)

### 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, message handling, and screen casting
│   └── 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

#### Betting Mode Management
- `GET /api/betting-mode` - Get current betting mode for user
- `POST /api/betting-mode` - Update betting mode for user

#### 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

#### Extraction Management
- `GET /api/extraction/associations` - Get all outcome associations
- `POST /api/extraction/associations` - Save outcome associations
- `GET /api/extraction/outcomes` - Get available outcomes for association
- `POST /api/extraction/config` - Update game configuration settings
- `GET /api/server-time` - Get current server time for clock synchronization

#### Timer Management
- `GET /api/match-timer/state` - Get current timer state (running, remaining time, etc.)
- `POST /api/match-timer/control` - Control timer (start/stop) with action parameter
- `GET /api/match-timer/config` - Get timer configuration settings

### 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

#### Timer Messages
- `START_GAME` - Start automated game timer with default interval
- `START_GAMES` - Start games with configuration-based interval
- `MATCH_START` - Start specific match with fixture and match IDs

#### Screen Cast Messages
- `WEB_ACTION` - Web dashboard screen cast control actions
- `SCREEN_CAST_START` - Start screen capture and streaming
- `SCREEN_CAST_STOP` - Stop screen capture and streaming
- `SCREEN_CAST_STATUS` - Screen cast component status update

## 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

**API client showing as unhealthy**
- Fixed in version 1.2.7 - enhanced heartbeat system prevents "Unhealthy components detected: ['api_client']" warnings
- API client now maintains regular heartbeat updates even during long-running operations
- Improved error handling prevents thread hangs that could cause health check failures

### 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.