Apply suggestions from code review
Browse filesCo-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Files changed (4)
2 unmodified lines345678910111213142 unmodified linesfrom mediaflow_proxy.configs import settingsasync def uqload_url(d: str, use_request_proxy: bool):async with httpx.AsyncClient(proxy=settings.proxy_url if use_request_proxy else None) as client:response = await client.get(d, follow_redirects=True)video_url_match = re.search(r'sources: \["(.*?)"\]', response.text)if video_url_match:final_url = video_url_match.group(1)uqload_dict = {"Referer": "https://uqload.to/"}return final_url, uqload_dict2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940412 unmodified linesfrom mediaflow_proxy.configs import settingsfrom typing import Tuple, Dict, Optionalasync def uqload_url(d: str, use_request_proxy: bool) -> Tuple[Optional[str], Dict[str, str]]:"""Extract video URL from Uqload.Args:d: The Uqload video URLuse_request_proxy: Whether to use proxy for the requestReturns:Tuple containing the extracted video URL (or None if not found) and headers dictionaryRaises:httpx.HTTPError: If the HTTP request fails"""if not d.startswith(('http://', 'https://')):raise ValueError("Invalid URL format")REFERER = "https://uqload.to/"final_url = Noneasync with httpx.AsyncClient(proxy=settings.proxy_url if use_request_proxy else None) as client:try:response = await client.get(d, follow_redirects=True)response.raise_for_status()# Look for video URL in response using a more robust patternvideo_url_match = re.search(r'sources:\s*\[(["\'])(.*?)\1\]', response.text)if video_url_match:final_url = video_url_match.group(2)return final_url, {"Referer": REFERER}except httpx.HTTPError as e:# Log the error here if logging is availableraise
9 unmodified lines1011121314151615 unmodified lines32333435363738399 unmodified lines@extractor_router.get("/extractor")async def doodstream_extractor(d: str = Query(..., description="Extract Clean Link from various Hosts"),use_request_proxy: bool = Query(False, description="Whether to use the MediaFlow proxy configuration."),host: str = Query(15 unmodified lines"""try:final_url, headers_dict = await host_map[host](d, use_request_proxy)except Exception as e:return JSONResponse(content={"error": str(e)})if redirect_stream == True:formatted_headers = format_headers(headers_dict)redirected_stream = f"/proxy/stream?api_password={settings.api_password}&d={final_url}&{formatted_headers}"9 unmodified lines1011121314151615 unmodified lines3233343536373839404142434445469 unmodified lines@extractor_router.get("/extractor")async def extract_media_url(d: str = Query(..., description="Extract Clean Link from various Hosts"),use_request_proxy: bool = Query(False, description="Whether to use the MediaFlow proxy configuration."),host: str = Query(15 unmodified lines"""try:final_url, headers_dict = await host_map[host](d, use_request_proxy)except KeyError:return JSONResponse(status_code=400,content={"error": f"Invalid host type. Available hosts: {', '.join(host_map.keys())}"})except ValueError as e:return JSONResponse(status_code=400, content={"error": str(e)})except Exception as e:return JSONResponse(status_code=500, content={"error": "Internal server error"})if redirect_stream == True:formatted_headers = format_headers(headers_dict)redirected_stream = f"/proxy/stream?api_password={settings.api_password}&d={final_url}&{formatted_headers}"
62 unmodified lines636465666768697071727374757677787980818283848586878889909192939495968 unmodified lines10510610710810911011111211311411511662 unmodified lines<script>const urlParams = new URLSearchParams(window.location.search);const taskId = urlParams.get("task_id");async function checkStatus() {try {const response = await fetch(`/speedtest/results/${taskId}`);if (!response.ok) {throw new Error('Network response was not ok');}const data = await response.json();console.log("Fetched data:", data);// Check if the test is still running based on the response dataif (data && data.message && data.message.includes("still running")) {console.log("Test still running, polling again...");// Poll again after 5 seconds if the test is still runningsetTimeout(checkStatus, 5000);} else {console.log("Test complete, redirecting after a short delay...");// Redirect to the results if the test is done after a short delaysetTimeout(() => {window.location.href = `/speedtest/results/${taskId}`;}, 2000); // 2 seconds delay}} catch (error) {console.error("Error fetching status:", error);// Retry after 5 seconds in case of errorsetTimeout(checkStatus, 5000);}}// Start the first status check after 120 seconds (120000 milliseconds)setTimeout(checkStatus, 120000);8 unmodified lines</head><body class="light-mode"><div class="toggle-switch"><label for="darkModeToggle">Dark Mode</label><input type="checkbox" id="darkModeToggle" onclick="toggleDarkMode()"></div><div class="container"><h1>Speedtest in progress... Please wait up to 3 minutes.</h1><div class="progress-bar"></div></div></body></html>62 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171188 unmodified lines12712812913013113213313413513613713813914062 unmodified lines<script>const urlParams = new URLSearchParams(window.location.search);const taskId = urlParams.get("task_id");if (!taskId || !/^[a-zA-Z0-9-_]+$/.test(taskId)) {window.location.href = "/speedtest";}let statusCheckTimeout;let retryCount = 0;const MAX_RETRIES = 5;async function checkStatus() {try {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 5000);const response = await fetch(`/speedtest/results/${taskId}`, {signal: controller.signal});clearTimeout(timeoutId);if (!response.ok) {throw new Error('Network response was not ok');}const data = await response.json();console.log("Fetched data:", data);retryCount = 0;if (data && data.message && data.message.includes("still running")) {console.log("Test still running, polling again...");statusCheckTimeout = setTimeout(checkStatus, 5000);} else {console.log("Test complete, redirecting after a short delay...");setTimeout(() => {window.location.href = `/speedtest/results/${taskId}`;}, 2000);}} catch (error) {console.error("Error fetching status:", error);retryCount++;if (retryCount < MAX_RETRIES) {statusCheckTimeout = setTimeout(checkStatus, 5000);} else {alert("Failed to check status after multiple attempts. Please refresh the page.");}}}// Cleanup on page unloadwindow.addEventListener('unload', () => {if (statusCheckTimeout) {clearTimeout(statusCheckTimeout);}});// Start the first status check after 120 seconds (120000 milliseconds)setTimeout(checkStatus, 120000);8 unmodified lines</head><body class="light-mode"><div class="toggle-switch"><label for="darkModeToggle" class="switch"><input type="checkbox" id="darkModeToggle" onclick="toggleDarkMode()" aria-label="Toggle dark mode"><span class="slider">Dark Mode</span></label></div><div class="container"><h1>Speedtest in progress... Please wait up to 3 minutes.</h1><div class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div></div></body></html>
36 unmodified lines373839404142434445464748495051525354555657585960616263646566676836 unmodified linesasync with AsyncClient() as client:streamer = Streamer(client)for location, base_url in test_urls.items():# Generate a random float with 16 decimal placesrandom_number = f"{random.uniform(0, 1):.16f}"url = f"{base_url}{random_number}"logging.info(f"Testing URL: {url}")start_time = time.time()total_bytes = 0try:# Stream the responseasync for chunk in streamer.stream_content(url, headers={}):if time.time() - start_time >= test_duration:breaktotal_bytes += len(chunk)duration = time.time() - start_timespeed_mbps = (total_bytes * 8) / (duration * 1_000_000)speed[location] = {"speed_mbps": round(speed_mbps, 2),"duration": round(duration, 2)}logging.info(f"Speed for {location}: {speed_mbps} Mbps in {duration} seconds")except Exception as e:speed[location] = {"error": str(e)}logging.error(f"Error for {location}: {e}")return speed36 unmodified lines37383940414243444546474849505152535455565758596061626364656667686936 unmodified linesasync with AsyncClient() as client:streamer = Streamer(client)async def test_single_url(location: str, url: str) -> Dict[str, Any]:try:start_time = time.time()total_bytes = 0async for chunk in streamer.stream_content(url, headers={}):if time.time() - start_time >= test_duration:breaktotal_bytes += len(chunk)duration = time.time() - start_timespeed_mbps = (total_bytes * 8) / (duration * 1_000_000)return {"speed_mbps": round(speed_mbps, 2),"duration": round(duration, 2)}except Exception as e:logging.error(f"Error testing {location}: {e}")return {"error": str(e)}for location, base_url in test_urls.items():random_number = f"{random.uniform(0, 1):.16f}"url = f"{base_url}{random_number}"logging.info(f"Testing URL: {url}")speed[location] = await test_single_url(location, url)# Add rate limiting between testsawait asyncio.sleep(1)return speed
mediaflow_proxy/extractors/uqload.py+35-8
mediaflow_proxy/extractors_routes.py+9-2
mediaflow_proxy/static/speedtest_progress.html+35-11
mediaflow_proxy/utils/rd_speedtest.py+24-23