import aiohttp
from django.http import HttpResponse, StreamingHttpResponse
import os
from datetime import datetime
import requests
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from urllib.parse import quote
from django.http import HttpResponse
from aiohttp import ClientSession
from django.views.decorators.csrf import csrf_exempt

def acme_challenge(request, token):
    print(token)
    content = f'{token}.E4H2n2zqARGJeN2ulDerea5xYFCDXMy1y9v61hoQfms'
    return HttpResponse(content, content_type='text/plain')


@csrf_exempt
async def download_proxy(request):
    video_url = request.GET.get('url')
    if not video_url:
        return HttpResponse("URL is required", status=400)

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    async with ClientSession() as session:
        try:
            async with session.get(video_url, headers=headers) as response:
                if response.status == 200:
                    content = await response.read()  # 读取内容到内存中，注意这不适用于大文件

                    # 创建一个 HttpResponse 对象并设置 Content-Type
                    response = HttpResponse(content, content_type=response.headers['Content-Type'])

                    # 添加自定义响应头
                    response['X-Content-Length'] = str(len(content))

                    return response
                else:
                    return HttpResponse("Failed to download video", status=response.status)
        except aiohttp.ClientConnectionError:
            return HttpResponse("Connection closed", status=500)


class ProxyView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        # 获取目标URL
        target_url = request.GET.get('url')
        if not target_url:
            return HttpResponse("Missing 'url' parameter", status=400)

        try:
            # 请求目标URL
            response = requests.get(target_url, stream=True)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            return HttpResponse(f"Error fetching target URL: {e}", status=500)

        # 获取文件类型并强制设置为 video/mp4
        content_type = 'video/mp4'

        # 获取文件名并强制使用 .mp4 后缀
        filename = target_url.split("/")[-1].split('?')[0]  # 移除查询参数
        if not filename.endswith('.mp4'):
            filename = f"{filename}.mp4"

        # 设置Content-Disposition头部，确保文件在浏览器中直接播放而不是下载
        content_disposition = f'inline; filename="{filename}"'

        # 创建响应对象并将内容传递给客户端
        proxy_response = HttpResponse(content=response.content, content_type=content_type)
        proxy_response['Content-Disposition'] = content_disposition

        return proxy_response