Add HTTPS support with Caddy and clean up legacy files

- Add Caddy reverse proxy for automatic HTTPS with Let's Encrypt
- Update docker-compose.yml with Caddy service and internal networking
- Remove all Redis dependencies (not needed for this deployment)
- Fix Dockerfile permissions for instance and uploads directories
- Move legacy scripts to old_code_documentation folder
  - add_muted_column.py, check_fix_player.py, migrate_add_edit_enabled.py
  - docker-start.sh, run_dev.sh, start.sh, clean_for_deployment.sh
- Add HTTPS_SETUP.md documentation for Caddy configuration
- Update .env.example with DOMAIN and EMAIL variables
- Remove redis package from requirements.txt
- Remove rate limiting Redis storage from config.py
This commit is contained in:
DigiServer Admin
2025-12-11 16:56:44 +02:00
parent 328edebe3c
commit 4a9616a0f7
13 changed files with 160 additions and 21 deletions

View File

@@ -0,0 +1,21 @@
# Flask Environment
FLASK_APP=app.py
FLASK_ENV=development
# Security
SECRET_KEY=change-this-to-a-random-secret-key
# Domain & SSL (for HTTPS with Caddy)
DOMAIN=your-domain.com
EMAIL=admin@your-domain.com
# Database
DATABASE_URL=sqlite:///instance/dev.db
# Admin User Credentials (used during initial Docker deployment)
# These credentials are set when the database is first created
ADMIN_USERNAME=admin
ADMIN_PASSWORD=change-this-secure-password
# Optional: Sentry for error tracking
# SENTRY_DSN=your-sentry-dsn-here

View File

@@ -0,0 +1,75 @@
# DigiServer v2 - HTTPS Setup with Caddy
This setup uses **Caddy** as a reverse proxy with automatic HTTPS via Let's Encrypt.
## Quick Setup
### 1. Configure Domain
Create a `.env` file or edit the existing one:
```bash
cp .env.example .env
```
Edit `.env` and set:
```
DOMAIN=your-domain.com
EMAIL=admin@your-domain.com
```
### 2. Point Your Domain
Make sure your domain's DNS A record points to your server's IP address.
### 3. Start Services
```bash
docker compose up -d
```
That's it! Caddy will **automatically**:
- Obtain SSL certificates from Let's Encrypt
- Renew certificates before expiration
- Redirect HTTP to HTTPS
- Enable HTTP/2 and HTTP/3
## Access Your Site
- **HTTP**: http://your-domain.com (redirects to HTTPS)
- **HTTPS**: https://your-domain.com
## Testing Locally (Without Domain)
If you don't have a domain yet, leave DOMAIN as `localhost`:
```
DOMAIN=localhost
```
Then access: http://localhost (no HTTPS, but app works)
## Certificate Storage
SSL certificates are stored in Docker volumes:
- `caddy-data` - Certificate data
- `caddy-config` - Caddy configuration
## Troubleshooting
### Check Caddy logs:
```bash
docker logs digiserver-caddy
```
### Verify certificates:
```bash
docker exec digiserver-caddy caddy list-certificates
```
### Force certificate renewal:
```bash
docker exec digiserver-caddy caddy reload --config /etc/caddy/Caddyfile
```
## Port Forwarding
Make sure your firewall/router allows:
- Port 80 (HTTP - for Let's Encrypt challenge)
- Port 443 (HTTPS)

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Add muted column to playlist_content table."""
from app.app import create_app
from app.extensions import db
def add_muted_column():
"""Add muted column to playlist_content association table."""
app = create_app()
with app.app_context():
try:
# Check if column already exists
result = db.session.execute(db.text("PRAGMA table_info(playlist_content)")).fetchall()
columns = [row[1] for row in result]
if 'muted' in columns:
print(" Column 'muted' already exists in playlist_content table")
return
# Add muted column with default value True (muted by default)
db.session.execute(db.text("""
ALTER TABLE playlist_content
ADD COLUMN muted BOOLEAN DEFAULT TRUE
"""))
db.session.commit()
print("✅ Successfully added 'muted' column to playlist_content table")
print(" Default: TRUE (videos will be muted by default)")
except Exception as e:
db.session.rollback()
print(f"❌ Error adding column: {e}")
if __name__ == '__main__':
add_muted_column()

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Check and fix player quickconnect code."""
from app import create_app
from app.models import Player
from app.extensions import db
app = create_app()
with app.app_context():
# Find player by hostname
player = Player.query.filter_by(hostname='tv-terasa').first()
if not player:
print("❌ Player 'tv-terasa' NOT FOUND in database!")
print("\nAll registered players:")
all_players = Player.query.all()
for p in all_players:
print(f" - ID={p.id}, Name='{p.name}', Hostname='{p.hostname}'")
else:
print(f"✅ Player found:")
print(f" ID: {player.id}")
print(f" Name: {player.name}")
print(f" Hostname: {player.hostname}")
print(f" Playlist ID: {player.playlist_id}")
print(f" Status: {player.status}")
print(f" QuickConnect Hash: {player.quickconnect_code[:60] if player.quickconnect_code else 'Not set'}...")
# Test the quickconnect code
test_code = "8887779"
print(f"\n🔐 Testing quickconnect code: '{test_code}'")
if player.check_quickconnect_code(test_code):
print(f"✅ Code '{test_code}' is VALID!")
else:
print(f"❌ Code '{test_code}' is INVALID - Hash doesn't match!")
# Update it
print(f"\n🔧 Updating quickconnect code to: '{test_code}'")
player.set_quickconnect_code(test_code)
db.session.commit()
print("✅ QuickConnect code updated successfully!")
print(f" New hash: {player.quickconnect_code[:60]}...")
# Verify the update
if player.check_quickconnect_code(test_code):
print(f"✅ Verification successful - code '{test_code}' now works!")
else:
print(f"❌ Verification failed - something went wrong!")

View File

@@ -0,0 +1,93 @@
#!/bin/bash
# Clean development data before Docker deployment
# This script removes all development data to ensure a fresh start
set -e
# Get the root directory of the application
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "🧹 Cleaning DigiServer v2 for deployment..."
echo "📍 App root: $APP_ROOT"
echo ""
# Confirm action
read -p "This will delete ALL data (database, uploads, logs). Continue? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "❌ Cancelled"
exit 1
fi
echo ""
echo "📦 Cleaning development data..."
# Change to app root directory
cd "$APP_ROOT"
# Remove database files
if [ -d "instance" ]; then
echo " 🗄️ Removing database files..."
rm -rf instance/*.db
rm -rf instance/*.db-*
echo " ✅ Database cleaned"
else
echo " No instance directory found"
fi
# Remove uploaded media
if [ -d "app/static/uploads" ]; then
echo " 📁 Removing uploaded media files..."
find app/static/uploads -type f -not -name '.gitkeep' -delete 2>/dev/null || true
find app/static/uploads -type d -empty -not -path "app/static/uploads" -delete 2>/dev/null || true
echo " ✅ Uploads cleaned"
else
echo " No uploads directory found"
fi
# Remove additional upload directory if exists
if [ -d "static/uploads" ]; then
echo " 📁 Removing static uploads..."
find static/uploads -type f -not -name '.gitkeep' -delete 2>/dev/null || true
find static/uploads -type d -empty -not -path "static/uploads" -delete 2>/dev/null || true
echo " ✅ Static uploads cleaned"
fi
# Remove log files
echo " 📝 Removing log files..."
find . -name "*.log" -type f -delete 2>/dev/null || true
echo " ✅ Logs cleaned"
# Remove Python cache
echo " 🐍 Removing Python cache..."
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
find . -type f -name "*.pyc" -delete 2>/dev/null || true
find . -type f -name "*.pyo" -delete 2>/dev/null || true
echo " ✅ Python cache cleaned"
# Remove Flask session files if any
if [ -d "flask_session" ]; then
echo " 🔐 Removing session files..."
rm -rf flask_session
echo " ✅ Sessions cleaned"
fi
# Summary
echo ""
echo "✨ Cleanup complete!"
echo ""
echo "📊 Summary:"
echo " - Database: Removed"
echo " - Uploaded media: Removed"
echo " - Logs: Removed"
echo " - Python cache: Removed"
echo ""
echo "🚀 Ready for deployment!"
echo ""
echo "Next steps:"
echo " 1. Build Docker image: docker compose build"
echo " 2. Start container: docker compose up -d"
echo " 3. Access at: http://localhost:80"
echo " 4. Login with: admin / admin123"
echo ""

View File

@@ -0,0 +1,69 @@
#!/bin/bash
echo "🚀 DigiServer v2 - Docker Quick Start"
echo "====================================="
echo ""
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
echo "❌ Docker is not installed. Please install Docker first."
exit 1
fi
# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
echo "❌ Docker Compose is not installed. Please install Docker Compose first."
exit 1
fi
# Create .env file if it doesn't exist
if [ ! -f .env ]; then
echo "📝 Creating .env file..."
cp .env.example .env
# Generate random secret key
SECRET_KEY=$(openssl rand -base64 32)
sed -i "s/change-this-to-a-random-secret-key/$SECRET_KEY/" .env
echo "✅ Created .env with generated SECRET_KEY"
fi
# Create required directories
echo "📁 Creating required directories..."
mkdir -p instance app/static/uploads
echo "✅ Directories created"
echo ""
echo "🔨 Building Docker image..."
docker-compose build
echo ""
echo "🚀 Starting DigiServer v2..."
docker-compose up -d
echo ""
echo "⏳ Waiting for application to start..."
sleep 5
# Check if container is running
if docker-compose ps | grep -q "Up"; then
echo ""
echo "✅ DigiServer v2 is running!"
echo ""
echo "📍 Access the application at: http://localhost:5000"
echo ""
echo "👤 Default credentials:"
echo " Username: admin"
echo " Password: admin123"
echo ""
echo "📋 Useful commands:"
echo " View logs: docker-compose logs -f"
echo " Stop: docker-compose down"
echo " Restart: docker-compose restart"
echo " Shell access: docker-compose exec digiserver bash"
echo ""
echo "⚠️ IMPORTANT: Change the admin password after first login!"
else
echo ""
echo "❌ Failed to start DigiServer v2"
echo " Check logs with: docker-compose logs"
fi

View File

@@ -0,0 +1,47 @@
"""Migration: Add edit_on_player_enabled column to playlist_content table."""
import sqlite3
import os
DB_PATH = 'instance/dashboard.db'
def migrate():
"""Add edit_on_player_enabled column to playlist_content."""
if not os.path.exists(DB_PATH):
print(f"Database not found at {DB_PATH}")
return False
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
# Check if column already exists
cursor.execute("PRAGMA table_info(playlist_content)")
columns = [col[1] for col in cursor.fetchall()]
if 'edit_on_player_enabled' in columns:
print("Column 'edit_on_player_enabled' already exists!")
return True
# Add the new column with default value False
print("Adding 'edit_on_player_enabled' column to playlist_content table...")
cursor.execute("""
ALTER TABLE playlist_content
ADD COLUMN edit_on_player_enabled BOOLEAN DEFAULT 0
""")
conn.commit()
print("✅ Migration completed successfully!")
print("Column 'edit_on_player_enabled' added with default value False (0)")
return True
except Exception as e:
conn.rollback()
print(f"❌ Migration failed: {e}")
return False
finally:
conn.close()
if __name__ == '__main__':
migrate()

View File

@@ -0,0 +1,76 @@
#!/bin/bash
# DigiServer v2 - Development Test Runner
# This script sets up and runs the application in development mode
set -e
echo "================================================"
echo " DigiServer v2 - Development Environment"
echo "================================================"
echo ""
# Check if we're in the right directory
if [ ! -f "requirements.txt" ]; then
echo "❌ Error: requirements.txt not found. Run this from the digiserver-v2 directory."
exit 1
fi
# Check if virtual environment exists
if [ ! -d "venv" ]; then
echo "📦 Creating virtual environment..."
python3 -m venv venv
echo "✅ Virtual environment created"
else
echo "✅ Virtual environment found"
fi
# Activate virtual environment
echo "🔄 Activating virtual environment..."
source venv/bin/activate
# Install/update dependencies
echo "📥 Installing dependencies..."
pip install -q --upgrade pip
pip install -q -r requirements.txt
echo "✅ Dependencies installed"
echo ""
# Check if .env exists
if [ ! -f ".env" ]; then
echo "⚠️ Warning: .env file not found, using .env.example"
cp .env.example .env
fi
# Initialize database if it doesn't exist
if [ ! -f "instance/dashboard.db" ]; then
echo "🗄️ Initializing database..."
export FLASK_APP=app.app:create_app
flask init-db
echo "✅ Database initialized"
echo "👤 Creating default admin user..."
flask create-admin
echo "✅ Admin user created (username: admin, password: admin123)"
else
echo "✅ Database found"
fi
echo ""
echo "================================================"
echo " Starting Flask Development Server"
echo "================================================"
echo ""
echo "🌐 Server will be available at: http://localhost:5000"
echo "👤 Default admin: username=admin, password=admin123"
echo ""
echo "Press Ctrl+C to stop the server"
echo ""
# Set Flask environment
export FLASK_APP=app.app:create_app
export FLASK_ENV=development
# Run Flask
flask run --host=0.0.0.0 --port=5000

23
old_code_documentation/start.sh Executable file
View File

@@ -0,0 +1,23 @@
#!/bin/bash
# DigiServer v2 - Simple Start Script
# Starts the application with proper configuration
set -e
cd /srv/digiserver-v2
# Activate virtual environment
source venv/bin/activate
# Set environment variables
export FLASK_APP=app.app:create_app
export FLASK_ENV=development
# Start Flask server
echo "Starting DigiServer v2..."
echo "Access at: http://localhost:5000"
echo "Login: admin / admin123"
echo ""
flask run --host=0.0.0.0 --port=5000