from django.conf import settings
from django.http import HttpResponse
import os

class StaticXFrameOptionsMiddleware:
    """
    为静态 HTML 文件添加 X-Frame-Options 响应头的中间件
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # 检查是否是媒体文件中的 HTML 文件
        if (request.path.startswith(settings.MEDIA_URL) and 
            request.path.endswith('.html')):
            # 设置 X-Frame-Options 为 SAMEORIGIN
            response['X-Frame-Options'] = 'SAMEORIGIN'
            # 添加 CSP 头部以允许 Firefox 加载 iframe 内容
            response['Content-Security-Policy'] = "frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://*.21729901.xyz"
            
        return response