from flask import Flask import sqlite3 import os import secrets def init_app(app): """Initialize the SQLite database""" db_path = app.config['DATABASE_URI'].replace('sqlite:///', '') # Ensure the database directory exists os.makedirs(os.path.dirname(db_path) if os.path.dirname(db_path) else '.', exist_ok=True) # Create tables if they don't exist conn = sqlite3.connect(db_path) cursor = conn.cursor() # Create users table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT DEFAULT 'user', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # Create settings table cursor.execute(''' CREATE TABLE IF NOT EXISTS settings ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT UNIQUE NOT NULL, value TEXT, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # Create sites table (for multiple NexusPHP sites) cursor.execute(''' CREATE TABLE IF NOT EXISTS sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, url TEXT NOT NULL, api_token TEXT, enabled BOOLEAN DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # Create clients table (for qBittorrent and Transmission settings) cursor.execute(''' CREATE TABLE IF NOT EXISTS clients ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, -- 'qbittorrent' or 'transmission' host TEXT NOT NULL, port INTEGER NOT NULL, username TEXT, password TEXT, enabled BOOLEAN DEFAULT 1 ) ''') # Check if secret key exists in settings, if not create one cursor.execute("SELECT value FROM settings WHERE key = 'secret_key'") result = cursor.fetchone() if not result: secret_key = secrets.token_hex(16) cursor.execute("INSERT INTO settings (key, value) VALUES ('secret_key', ?)", (secret_key,)) print(f"Generated new secret key: {secret_key}") else: app.config['SECRET_KEY'] = result[0] print("Using existing secret key from database") # Create admin user if not exists cursor.execute("SELECT id FROM users WHERE username = ?", (app.config['ADMIN_USERNAME'],)) if not cursor.fetchone(): # We'll set a temporary password that will be displayed on first run temp_password = secrets.token_hex(8) # In a real app, we would hash the password, but for simplicity we'll store it directly # In practice, use werkzeug.security.generate_password_hash() cursor.execute( "INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)", (app.config['ADMIN_USERNAME'], temp_password, 'admin') ) print(f"Created admin user with temporary password: {temp_password}") # Insert default site if none exists cursor.execute("SELECT id FROM sites") if not cursor.fetchone(): cursor.execute( "INSERT INTO sites (name, url) VALUES (?, ?)", ('铂金短剧', 'https://www.ptskit.org') ) conn.commit() conn.close()