|
| 1 | +"""HTTP utilities using urllib instead of requests.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import socket |
| 6 | +from pathlib import Path |
| 7 | +from typing import TYPE_CHECKING |
| 8 | +from collections.abc import Callable |
| 9 | +from urllib.error import HTTPError as UrllibHTTPError |
| 10 | +from urllib.error import URLError |
| 11 | +from urllib.request import Request, urlopen |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +class RequestError(Exception): |
| 18 | + """Base exception for HTTP requests.""" |
| 19 | + |
| 20 | + |
| 21 | +class HTTPError(RequestError): |
| 22 | + """HTTP status error.""" |
| 23 | + |
| 24 | + |
| 25 | +class NetworkConnectionError(RequestError): |
| 26 | + """Network connection error.""" |
| 27 | + |
| 28 | + |
| 29 | +class RequestTimeoutError(RequestError): |
| 30 | + """Request timeout error.""" |
| 31 | + |
| 32 | + |
| 33 | +def fetch_redirect_location(url: str, timeout: int = 10) -> tuple[bool, str | None]: |
| 34 | + """Fetch redirect location from a URL. |
| 35 | +
|
| 36 | + Args: |
| 37 | + url: URL to fetch from |
| 38 | + timeout: Request timeout in seconds |
| 39 | +
|
| 40 | + Returns: |
| 41 | + Tuple of (success, location_header) |
| 42 | +
|
| 43 | + Raises: |
| 44 | + RequestError: On network or HTTP errors |
| 45 | + """ |
| 46 | + try: |
| 47 | + req = Request(url) |
| 48 | + # Set User-Agent to avoid blocking |
| 49 | + req.add_header("User-Agent", "django-tailwind-cli") |
| 50 | + |
| 51 | + with urlopen(req, timeout=timeout) as response: |
| 52 | + # Check if it's a redirect status |
| 53 | + if response.getcode() in (301, 302, 303, 307, 308): |
| 54 | + location = response.headers.get("Location") |
| 55 | + return True, location |
| 56 | + elif response.getcode() == 200: |
| 57 | + return True, None |
| 58 | + else: |
| 59 | + return False, None |
| 60 | + |
| 61 | + except UrllibHTTPError as e: |
| 62 | + # Handle redirect responses that urllib might treat as errors |
| 63 | + if e.code in (301, 302, 303, 307, 308): |
| 64 | + location = e.headers.get("Location") |
| 65 | + return True, location |
| 66 | + return False, None |
| 67 | + except URLError as e: |
| 68 | + if isinstance(e.reason, socket.timeout): |
| 69 | + raise RequestTimeoutError(f"Request timeout: {e}") from e |
| 70 | + elif isinstance(e.reason, (ConnectionRefusedError, socket.gaierror)): |
| 71 | + raise NetworkConnectionError(f"Connection error: {e}") from e |
| 72 | + else: |
| 73 | + raise RequestError(f"URL error: {e}") from e |
| 74 | + except TimeoutError as e: |
| 75 | + raise RequestTimeoutError(f"Socket timeout: {e}") from e |
| 76 | + except Exception as e: |
| 77 | + raise RequestError(f"Unexpected error: {e}") from e |
| 78 | + |
| 79 | + |
| 80 | +def download_with_progress( |
| 81 | + url: str, filepath: Path, timeout: int = 30, progress_callback: Callable[[int, int, float], None] | None = None |
| 82 | +) -> None: |
| 83 | + """Download a file with progress indication. |
| 84 | +
|
| 85 | + Args: |
| 86 | + url: Download URL |
| 87 | + filepath: Destination file path |
| 88 | + timeout: Request timeout in seconds |
| 89 | + progress_callback: Optional callback for progress updates |
| 90 | +
|
| 91 | + Raises: |
| 92 | + RequestError: On network or HTTP errors |
| 93 | + """ |
| 94 | + try: |
| 95 | + req = Request(url) |
| 96 | + req.add_header("User-Agent", "django-tailwind-cli") |
| 97 | + |
| 98 | + with urlopen(req, timeout=timeout) as response: |
| 99 | + # Check for HTTP errors |
| 100 | + if response.getcode() >= 400: |
| 101 | + raise HTTPError(f"HTTP {response.getcode()}: {response.reason}") |
| 102 | + |
| 103 | + # Get content length for progress tracking |
| 104 | + content_length_header = response.headers.get("Content-Length") |
| 105 | + total_size = int(content_length_header) if content_length_header else 0 |
| 106 | + |
| 107 | + # Ensure parent directory exists |
| 108 | + filepath.parent.mkdir(parents=True, exist_ok=True) |
| 109 | + |
| 110 | + downloaded = 0 |
| 111 | + chunk_size = 8192 |
| 112 | + |
| 113 | + with filepath.open("wb") as f: |
| 114 | + while True: |
| 115 | + chunk = response.read(chunk_size) |
| 116 | + if not chunk: |
| 117 | + break |
| 118 | + |
| 119 | + f.write(chunk) |
| 120 | + downloaded += len(chunk) |
| 121 | + |
| 122 | + # Call progress callback if provided |
| 123 | + if progress_callback and total_size > 0: |
| 124 | + progress = (downloaded / total_size) * 100 |
| 125 | + progress_callback(downloaded, total_size, progress) |
| 126 | + |
| 127 | + except UrllibHTTPError as e: |
| 128 | + raise HTTPError(f"HTTP {e.code}: {e.reason}") from e |
| 129 | + except URLError as e: |
| 130 | + if isinstance(e.reason, socket.timeout): |
| 131 | + raise RequestTimeoutError(f"Download timeout: {e}") from e |
| 132 | + elif isinstance(e.reason, (ConnectionRefusedError, socket.gaierror)): |
| 133 | + raise NetworkConnectionError(f"Connection error: {e}") from e |
| 134 | + else: |
| 135 | + raise RequestError(f"URL error: {e}") from e |
| 136 | + except TimeoutError as e: |
| 137 | + raise RequestTimeoutError(f"Download timeout: {e}") from e |
| 138 | + except OSError as e: |
| 139 | + raise RequestError(f"File error: {e}") from e |
| 140 | + except Exception as e: |
| 141 | + raise RequestError(f"Unexpected error: {e}") from e |
| 142 | + |
| 143 | + |
| 144 | +def get_content_sync(url: str, timeout: int = 30) -> bytes: |
| 145 | + """Get content from URL synchronously. |
| 146 | +
|
| 147 | + Args: |
| 148 | + url: URL to fetch from |
| 149 | + timeout: Request timeout in seconds |
| 150 | +
|
| 151 | + Returns: |
| 152 | + Response content as bytes |
| 153 | +
|
| 154 | + Raises: |
| 155 | + RequestError: On network or HTTP errors |
| 156 | + """ |
| 157 | + try: |
| 158 | + req = Request(url) |
| 159 | + req.add_header("User-Agent", "django-tailwind-cli") |
| 160 | + |
| 161 | + with urlopen(req, timeout=timeout) as response: |
| 162 | + if response.getcode() >= 400: |
| 163 | + raise HTTPError(f"HTTP {response.getcode()}: {response.reason}") |
| 164 | + return response.read() |
| 165 | + |
| 166 | + except UrllibHTTPError as e: |
| 167 | + raise HTTPError(f"HTTP {e.code}: {e.reason}") from e |
| 168 | + except URLError as e: |
| 169 | + if isinstance(e.reason, socket.timeout): |
| 170 | + raise RequestTimeoutError(f"Request timeout: {e}") from e |
| 171 | + elif isinstance(e.reason, (ConnectionRefusedError, socket.gaierror)): |
| 172 | + raise NetworkConnectionError(f"Connection error: {e}") from e |
| 173 | + else: |
| 174 | + raise RequestError(f"URL error: {e}") from e |
| 175 | + except TimeoutError as e: |
| 176 | + raise RequestTimeoutError(f"Request timeout: {e}") from e |
| 177 | + except Exception as e: |
| 178 | + raise RequestError(f"Unexpected error: {e}") from e |
0 commit comments