from flask import ( Flask, render_template, request, flash, ) from flask_wtf.csrf import CSRFProtect, CSRFError from config import config, Config import os import logging import io import time from whatsapp_statistics import ( analyze_messages, parse_chat_stream, ) import json from utils import FileValidator def setup_logging(app): log_level = logging.ERROR simple_formatter = logging.Formatter( "[%(asctime)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) console_handler = logging.StreamHandler() console_handler.setFormatter(simple_formatter) console_handler.setLevel(log_level) app.logger.handlers = [] app.logger.addHandler(console_handler) app.logger.setLevel(log_level) logger = logging.getLogger("app") env = os.getenv("FLASK_ENV", "development") config_class = config.get(env, Config) app = Flask(__name__) app.config.from_object(config_class) setup_logging(app) try: config_class.validate_required_settings() except ValueError as e: logger.error(f"Configuration error: {e}") raise config_class.enforce_security(app) csrf = CSRFProtect(app) file_validator = FileValidator( allowed_extensions=app.config.get("ALLOWED_EXTENSIONS", {"txt"}), max_size_bytes=app.config.get("MAX_CONTENT_LENGTH", 10 * 1024 * 1024), ) def _merge_csp_sources(defaults, env_key): sources = list(defaults) extras = os.getenv(env_key, "").split() for source in extras: if source and source not in sources: sources.append(source) return sources def _embed_mode_enabled(): explicit = os.getenv("ALLOW_IFRAME_EMBED", "false").lower() in { "1", "true", "yes", } on_hf_spaces = bool(os.getenv("SPACE_ID") or os.getenv("HF_SPACE_ID")) return explicit or on_hf_spaces def _build_content_security_policy(): script_sources = _merge_csp_sources( [ "'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net", "https://code.jquery.com", ], "CSP_EXTRA_SCRIPT_SRC", ) style_sources = _merge_csp_sources( [ "'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net", "https://site-assets.fontawesome.com", "https://fonts.googleapis.com", ], "CSP_EXTRA_STYLE_SRC", ) font_sources = _merge_csp_sources( [ "'self'", "https://cdn.jsdelivr.net", "https://site-assets.fontawesome.com", "https://fonts.gstatic.com", "data:", ], "CSP_EXTRA_FONT_SRC", ) img_sources = _merge_csp_sources(["'self'", "data:"], "CSP_EXTRA_IMG_SRC") connect_sources = _merge_csp_sources( ["'self'", "https://cdn.jsdelivr.net"], "CSP_EXTRA_CONNECT_SRC" ) frame_ancestors = ( _merge_csp_sources(["https://huggingface.co"], "CSP_EXTRA_FRAME_ANCESTORS") if _embed_mode_enabled() else ["'none'"] ) directives = { "default-src": ["'self'"], "script-src": script_sources, "style-src": style_sources, "font-src": font_sources, "img-src": img_sources, "connect-src": connect_sources, "form-action": ["'self'"], "base-uri": ["'self'"], "frame-ancestors": frame_ancestors, "object-src": ["'none'"], } return "; ".join( f"{directive} {' '.join(sources)}" for directive, sources in directives.items() ) UPLOAD_FOLDER = os.path.join(app.instance_path, "uploads") app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER os.makedirs(UPLOAD_FOLDER, exist_ok=True) SECURITY_HEADERS = { "Content-Security-Policy": _build_content_security_policy(), "X-Content-Type-Options": "nosniff", "Referrer-Policy": os.getenv("REFERRER_POLICY", "strict-origin-when-cross-origin"), "X-XSS-Protection": "1; mode=block", "Permissions-Policy": "geolocation=(), microphone=(), camera=()", } if not _embed_mode_enabled(): SECURITY_HEADERS["X-Frame-Options"] = "DENY" @app.after_request def apply_security_headers(response): for header, value in SECURITY_HEADERS.items(): response.headers.setdefault(header, value) if app.config.get("SESSION_COOKIE_SECURE"): response.headers.setdefault( "Strict-Transport-Security", "max-age=63072000; includeSubDomains" ) return response @app.route("/", methods=["GET", "POST"]) def index(): try: analysis_data = None if request.method == "POST": if "chatFile" not in request.files: flash("File not found in the request", "error") return render_template("dashboard.html", stats_json="null") file = request.files["chatFile"] is_valid, error_message, metadata = file_validator.validate_file(file) if not is_valid: flash(error_message, "error") return render_template("dashboard.html", stats_json="null") try: start_time = time.time() raw_bytes = file.stream.read() if not raw_bytes: flash("The file is empty", "error") return render_template("dashboard.html", stats_json="null") try: text_content = raw_bytes.decode("utf-8") except UnicodeDecodeError: text_content = raw_bytes.decode("latin-1") messages = parse_chat_stream(io.StringIO(text_content)) if not messages: flash("No valid WhatsApp messages found in the file", "warning") return render_template("dashboard.html", stats_json="null") stats = analyze_messages(messages) analysis_data = stats processing_time = time.time() - start_time flash( f"Analysis completed! Processed {len(messages)} messages in {processing_time:.2f}s. " ) except ValueError as ve: flash(f"Invalid file format: {str(ve)}", "error") except UnicodeDecodeError: flash( "Unable to read file. Please ensure it's a text file with UTF-8 or Latin-1 encoding", "error", ) except Exception as e: flash(f"Error processing the file: {str(e)}", "error") stats_json = ( json.dumps(analysis_data, ensure_ascii=False) if analysis_data else "null" ) return render_template("dashboard.html", stats_json=stats_json) except Exception as e: flash("An unexpected error occurred. Please try again.", "error") return render_template("error.html", error=str(e)) @app.errorhandler(401) def status_401(error): return render_template("dashboard.html", stats_json="null") @app.errorhandler(404) def status_404(error): return "