from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse import requests import os app = FastAPI() m3u8_url = "https://vixcloud.co/playlist/247057?token=9b93a3831d50b0a6449a2b1b10e6a5bf&expires=1740138167&h=1" m3u8_file_path = "video-path/myvideo.m3u8" def fetch_and_save_m3u8(url, file_path): """Fetch the M3U8 file from the URL and save it to the local file system.""" response = requests.get(url) response.raise_for_status() # Raise an error for bad responses # Create directory if it doesn't exist os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(file_path, 'w') as f: f.write(response.text) @app.get("/") async def startup_event(): """Fetch and save the M3U8 file on application startup.""" try: fetch_and_save_m3u8(m3u8_url, m3u8_file_path) except requests.RequestException as e: print(f"Failed to fetch M3U8 file: {e}") @app.get("/video-path/myvideo.m3u8") async def serve_m3u8(): """Serve the saved M3U8 file.""" if not os.path.exists(m3u8_file_path): # Return 404 if the file isn't found raise HTTPException(status_code=404, detail="M3U8 file not found") return FileResponse(m3u8_file_path, media_type='application/vnd.apple.mpegurl') if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)