Upload files to "/"

This commit is contained in:
2026-03-02 09:48:49 -05:00
parent 4a7b7e6dd0
commit 366e218e26
5 changed files with 5751 additions and 0 deletions

338
README.md Normal file
View File

@@ -0,0 +1,338 @@
# 🚀 Advanced Chat Server & Client
A feature-rich, production-ready chat server and client built with Python and WebSockets. Supports **both centralized server mode and peer-to-peer (P2P) LAN communication** with **file sharing capabilities**. Works on local development and hosted deployment (Ubuntu).
## ✨ Features
### Core Features
-**Unified Client**: Single client for both Server and P2P LAN modes
-**Peer-to-Peer (P2P)**: Chat without a server on your local network
-**File Sharing**: Send and receive files up to 50MB in both modes
-**Real-time Messaging**: Instant communication with low latency
-**Multiple Rooms**: Join different channels with password protection
-**User Authentication**: Secure identification for server-based chat
-**Admin System**: Comprehensive moderation tools
-**SSL/TLS Support**: Encrypted connections for server mode
### Advanced Features
1. **Account & Registration**
- User registration with password hashing
- Secure authentication
- Nickname management
2. **Room Management**
- Create public and private rooms
- Password-protected rooms
- Room topics and announcements
- User lists per room
3. **Invite System**
- Generate time-limited invite codes
- Configurable max uses
- Invite tracking and revocation
4. **Message Search**
- Full-text search across messages
- Filter by room, user, and date
- Search history
5. **Message Replies**
- Thread-based conversations
- Quote original messages
- Reply tracking
6. **User Blocks**
- Block/ignore users
- Temporary or permanent blocks
- Block list management
7. **Command Aliases**
- Create custom command shortcuts
- Alias usage tracking
- Personal alias management
8. **Room Announcements**
- Broadcast important messages
- Time-limited announcements
- Announcement history
9. **Scheduled Messages**
- Schedule messages for future delivery
- Multiple time formats (HH:MM, +1h, +30m, +7d)
- Cancel scheduled messages
10. **Room Bookmarks**
- Save favorite rooms/commands
- Quick access to bookmarks
- Usage statistics
11. **Message Export**
- Export room history
- Export user messages
- Multiple export formats
12. **Room Backups**
- Password-protected backups
- Full room state preservation
- Backup restoration
13. **Notification Rules**
- Keyword notifications
- User-specific notifications
- @mention support
- Cooldown periods
14. **Offline Messages**
- Queue messages for offline users
- Automatic delivery on reconnect
- Message expiration
15. **Admin System**
- Admin privilege management
- Clear chat history
- User management
- System monitoring
## 🛠️ Installation
### Prerequisites
- Python 3.8 or higher
- pip (Python package manager)
- **Optional (for Advanced Features)**:
- `cryptography`: Required for End-to-End Encryption (E2EE)
- `Pillow`: Required for ASCII Image Art features
### Windows (Local Development)
1. Clone or download this repository
2. Run the setup script:
```cmd
setup_windows.bat
```
3. Edit `.env` file with your configuration
4. Start the server:
```cmd
venv\Scripts\activate
python server.py
```
5. In a new terminal, start the client:
```cmd
venv\Scripts\activate
python client.py
```
### Ubuntu (Production Deployment)
1. Clone or download this repository
2. Make the deployment script executable:
```bash
chmod +x deploy_ubuntu.sh
```
3. Run the deployment script:
```bash
./deploy_ubuntu.sh
```
4. Follow the prompts to configure systemd service and firewall
5. Edit `.env` file with your production configuration
6. If using systemd, the server will start automatically
7. Otherwise, start manually:
```bash
source venv/bin/activate
python3 server.py
```
### Manual Installation
```bash
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On Linux/Mac:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Copy environment template
cp .env.example .env
# Edit .env with your configuration
# Start server
python server.py
# In another terminal, start client
python client.py
```
## ⚙️ Configuration
Edit the `.env` file to configure the server:
```env
# Server Configuration
HOST=0.0.0.0 # Bind to all interfaces
PORT=8765 # WebSocket port
MAX_HISTORY=100 # Messages to keep in history
# Admin Configuration
ADMIN_PASSWORD=admin123 # Change this!
# SSL Configuration (optional)
USE_SSL=false
SSL_CERT_PATH=/path/to/cert.pem
SSL_KEY_PATH=/path/to/key.pem
# Database
DB_PATH=chat.db
# Logging
LOG_LEVEL=INFO
LOG_FILE=chat_server.log
# Security
MAX_MESSAGE_LENGTH=4096
MAX_NICKNAME_LENGTH=32
RATE_LIMIT_MESSAGES=120
RATE_LIMIT_WINDOW=60
# Session
SESSION_TIMEOUT=3600
KEEPALIVE_INTERVAL=30
RECONNECT_TIMEOUT=300
# Backups
BACKUP_DIR=./backups
AUTO_BACKUP_ENABLED=false
AUTO_BACKUP_INTERVAL=86400
```
## 🎮 Usage
### Server
Start the server with default settings:
```bash
python server.py
```
Or with custom options:
```bash
python server.py --host 0.0.0.0 --port 8765 --admin-pass mypassword
```
### Client
Start the unified client:
```bash
python client.py
```
The client will prompt you to choose a mode:
1. **Central Server Mode**: Connect to a central server (ws://...)
2. **P2P LAN Mode**: Connect directly to peers on your local network
In **P2P Mode**, it will also ask for a port (80, 443, or custom) and automatically discover others in the same room on your LAN.
### File Sharing
To share a file:
1. Type `/send <file_path>`
2. Others in the room will see a file offer
3. They can type `/accept <file_id>` to download
Files are saved to the `./downloads` folder by default.
### Commands
Type `/help` in the client to see all available commands.
## 🔒 Security Features
- **Password Hashing**: PBKDF2-HMAC-SHA256 with salt
- **SSL/TLS Support**: Encrypted connections
- **Rate Limiting**: Prevent spam and abuse (120 msg / 60s)
- **Input Validation**: Sanitize all user inputs
- **Session Management**: Automatic timeout and cleanup
- **Admin Controls**: Privilege-based access control
## 🌐 Deployment
### Local Network
1. Start server on your machine
2. Find your local IP address
3. Clients connect to: `ws://YOUR_LOCAL_IP:8765`
### Public Internet (Ubuntu Server)
1. Use the deployment script: `./deploy_ubuntu.sh`
2. Configure firewall to allow port 8765
3. Clients connect to: `wss://yourdomain.com:8765`
## 📊 Monitoring
### Systemd Service (Ubuntu)
- `sudo systemctl status chatserver`
- `sudo journalctl -u chatserver -f`
### Log Files
- `tail -f chat_server.log`
## 🗄️ Database
The server uses SQLite for persistence (`chat.db`).
## 🐛 Troubleshooting
### Connection Issues
1. **Cannot connect to server**: Check if server is running and firewall status.
2. **SSL/TLS errors**: Verify certificate paths in `.env`.
3. **Database errors**: Check disk space and permissions.
## 📝 Development
### Project Structure
```
radio/
├── server.py # Main server application
├── client.py # Unified client (Server & P2P Mode)
├── config.py # Configuration management
├── requirements.txt # Python dependencies
├── .env.example # Environment template
├── .env # Your configuration
├── setup_windows.bat # Windows setup script
├── deploy_ubuntu.sh # Ubuntu deployment script
├── README.md # Main documentation
├── docs/ # Detailed documentation files
├── chat.db # SQLite database
├── backups/ # Room backups directory
└── logs/ # Log files directory
```
### Documentation Index
For more detailed information, please refer to the files in the `docs/` folder:
- **QUICKSTART.md**: Step-by-step guide for beginners
- **P2P_GUIDE.md**: In-depth guide for P2P and LAN communication
- **P2P_FEATURES.md**: Technical details of the P2P engine
- **IMPROVEMENTS.md**: Summary of latest optimizations and features
- **QUICK_REFERENCE.md**: Most common commands and tips
- **CHANGELOG.md**: Version history and future plans
- **FINAL_SUMMARY.md**: Overview of the unified chat system architecture
### Contributing
Contributions are welcome! Please fork the repository, create a feature branch, and submit a pull request.
## 📜 License
This project is open source and available under the MIT License.
---
**Made with ❤️ for the chat community**

117
config.py Normal file
View File

@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""
Configuration Management for Chat Server
Supports both environment variables and .env files
"""
import os
from typing import Optional, Any, cast
from pathlib import Path
try:
from dotenv import load_dotenv # type: ignore
load_dotenv(override=True)
DOTENV_AVAILABLE = True
except ImportError:
DOTENV_AVAILABLE = False
class Config:
"""Configuration class with environment variable support"""
# Server Configuration
HOST: str = os.getenv('HOST', '127.0.0.1')
PORT: int = int(os.getenv('PORT', '8765'))
MAX_HISTORY: int = int(os.getenv('MAX_HISTORY', '100'))
# Admin Configuration
ADMIN_PASSWORD: str = os.getenv('ADMIN_PASSWORD', '') # Should be set in environment
# SSL Configuration
USE_SSL: bool = os.getenv('USE_SSL', 'false').lower() == 'true'
SSL_CERT_PATH: Optional[str] = os.getenv('SSL_CERT_PATH')
SSL_KEY_PATH: Optional[str] = os.getenv('SSL_KEY_PATH')
# Database Configuration
DB_PATH: str = os.getenv('DB_PATH', 'data/chat.db')
# Logging Configuration
LOG_LEVEL: str = os.getenv('LOG_LEVEL', 'INFO')
LOG_FILE: Optional[str] = os.getenv('LOG_FILE', 'logs/chat_server.log')
# Security Configuration
MAX_MESSAGE_LENGTH: int = int(os.getenv('MAX_MESSAGE_LENGTH', '4096'))
MAX_NICKNAME_LENGTH: int = int(os.getenv('MAX_NICKNAME_LENGTH', '32'))
RATE_LIMIT_MESSAGES: int = int(os.getenv('RATE_LIMIT_MESSAGES', '120'))
RATE_LIMIT_WINDOW: int = int(os.getenv('RATE_LIMIT_WINDOW', '60'))
# Session Configuration
SESSION_TIMEOUT: int = int(os.getenv('SESSION_TIMEOUT', '3600'))
KEEPALIVE_INTERVAL: int = int(os.getenv('KEEPALIVE_INTERVAL', '30'))
RECONNECT_TIMEOUT: int = int(os.getenv('RECONNECT_TIMEOUT', '300'))
# Backup Configuration
BACKUP_DIR: str = os.getenv('BACKUP_DIR', './backups')
AUTO_BACKUP_ENABLED: bool = os.getenv('AUTO_BACKUP_ENABLED', 'false').lower() == 'true'
AUTO_BACKUP_INTERVAL: int = int(os.getenv('AUTO_BACKUP_INTERVAL', '86400')) # 24 hours
# Room Configuration
ROOM_EXPIRATION_HOURS: int = int(os.getenv('ROOM_EXPIRATION_HOURS', '24'))
AUTO_HISTORY_CLEAR: bool = os.getenv('AUTO_HISTORY_CLEAR', 'false').lower() == 'true'
@classmethod
def validate(cls) -> bool:
"""Validate configuration"""
errors = []
# Validate port range
if not (1 <= cls.PORT <= 65535):
errors.append(f"Invalid PORT: {cls.PORT}. Must be between 1-65535")
# Validate SSL configuration
if cls.USE_SSL:
if not cls.SSL_CERT_PATH or not cls.SSL_KEY_PATH:
errors.append("SSL enabled but SSL_CERT_PATH or SSL_KEY_PATH not set")
elif not Path(cast(str, cls.SSL_CERT_PATH)).exists():
errors.append(f"SSL certificate not found: {cls.SSL_CERT_PATH}")
elif not Path(cast(str, cls.SSL_KEY_PATH)).exists():
errors.append(f"SSL key not found: {cls.SSL_KEY_PATH}")
# Validate positive integers
if cls.MAX_HISTORY < 1:
errors.append(f"MAX_HISTORY must be positive, got {cls.MAX_HISTORY}")
if cls.MAX_MESSAGE_LENGTH < 1:
errors.append(f"MAX_MESSAGE_LENGTH must be positive, got {cls.MAX_MESSAGE_LENGTH}")
if cls.MAX_NICKNAME_LENGTH < 1:
errors.append(f"MAX_NICKNAME_LENGTH must be positive, got {cls.MAX_NICKNAME_LENGTH}")
# Print errors
if errors:
print("[ERROR] Configuration errors:")
for error in errors:
print(f" - {error}")
return False
return True
@classmethod
def display(cls):
"""Display current configuration"""
print("\n" + "=" * 70)
print("CHAT SERVER CONFIGURATION")
print("=" * 70)
print(f"Server: {cls.HOST}:{cls.PORT}")
print(f"SSL: {'Enabled' if cls.USE_SSL else 'Disabled'}")
print(f"Database: {cls.DB_PATH}")
print(f"Log Level: {cls.LOG_LEVEL}")
print(f"Log File: {cls.LOG_FILE or 'Console only'}")
print(f"Max History: {cls.MAX_HISTORY} messages")
print(f"Rate Limit: {cls.RATE_LIMIT_MESSAGES} msg/{cls.RATE_LIMIT_WINDOW}s")
print(f"Auto Backup: {'Enabled' if cls.AUTO_BACKUP_ENABLED else 'Disabled'}")
print("=" * 70 + "\n")
# Validate configuration on import
if __name__ != "__main__":
if not Config.validate():
raise ValueError("Invalid configuration. Please check your environment variables or .env file")

5
requirements.txt Normal file
View File

@@ -0,0 +1,5 @@
websockets>=13.0
cryptography>=44.0.0
Pillow>=11.1.0
prompt_toolkit>=3.0.40
plyer>=2.1.0

5236
server.py Normal file

File diff suppressed because it is too large Load Diff

55
setup_windows.bat Normal file
View File

@@ -0,0 +1,55 @@
@echo off
REM Deployment script for Windows (local development)
REM This script sets up and runs the chat server on Windows
echo =========================================
echo Chat Server Setup Script for Windows
echo =========================================
echo.
REM Check if Python is installed
python --version >nul 2>&1
if errorlevel 1 (
echo ERROR: Python is not installed or not in PATH
echo Please install Python 3.8 or higher from python.org
pause
exit /b 1
)
echo Python found!
echo.
REM Upgrade pip
echo Upgrading pip...
python -m pip install --upgrade pip
REM Install dependencies
echo Installing dependencies...
pip install -r requirements.txt
REM Create .env file if it doesn't exist
if not exist ".env" (
echo .env file not found. Creating from template...
copy .env.example .env
echo Please edit .env file with your configuration!
)
REM Create necessary directories
echo Creating necessary directories...
if not exist "backups" mkdir backups
if not exist "logs" mkdir logs
if not exist "data" mkdir data
echo.
echo =========================================
echo Setup complete!
echo =========================================
echo.
echo To start the server:
echo 1. Run: python server.py
echo.
echo To start the client:
echo 1. Open a new terminal
echo 2. Run: python client.py
echo.
pause