# MbetterClient

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

## Features

- **PyQt Video Player**: Fullscreen video playback with customizable overlay templates
- **Web Dashboard**: Authentication, user management, and configuration interface
- **REST API Client**: Configurable external API integration with automatic retry
- **Multi-threaded Architecture**: Four threads with Queue-based message passing
- **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

## Recent Improvements

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

# 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
├── tests/                 # Unit tests
└── docs/                  # Documentation
```

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

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

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

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

## License

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

## Support

For support and documentation, visit the project repository.