File size: 7,337 Bytes
c0e9d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#  Copyright (c) 2025 AshokShau
#  Licensed under the GNU AGPL v3.0: https://www.gnu.org/licenses/agpl-3.0.html
#  Part of the TgMusicBot project. All rights reserved where applicable.

import asyncio
import re
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional, Union
from urllib.parse import unquote

import aiofiles
import httpx

from ._tools import LOGGER, DOWNLOADS_DIR, API_KEY, API_URL


@dataclass
class DownloadResult:
    success: bool
    file_path: Path | None = None
    error: str | None = None


class HttpxClient:
    DEFAULT_TIMEOUT = 10
    DEFAULT_DOWNLOAD_TIMEOUT = 60
    CHUNK_SIZE = 8192  # 8KB chunks for streaming downloads
    MAX_RETRIES = 2
    BACKOFF_FACTOR = 1.0

    def __init__(
        self,
        timeout: int = DEFAULT_TIMEOUT,
        download_timeout: int = DEFAULT_DOWNLOAD_TIMEOUT,
        max_redirects: int = 0,
    ) -> None:
        """
        Initialize the HTTP client with configurable settings.

        Args:
            timeout: Timeout for general HTTP requests in seconds
            download_timeout: Timeout for file downloads in seconds
            max_redirects: Maximum number of redirects to follow (0 to disable)
        """
        self._timeout = timeout
        self._download_timeout = download_timeout
        self._max_redirects = max_redirects
        self._session = httpx.AsyncClient(
            timeout=timeout,
            follow_redirects=max_redirects > 0,
            max_redirects=max_redirects,
        )

    async def close(self) -> None:
        """
        Close the HTTP session gracefully.
        """
        try:
            await self._session.aclose()
        except Exception as e:
            LOGGER.error("Error closing HTTP session: %s", str(e))

    async def download_file(
        self,
        url: str,
        file_path: str | Path | None = None,
        overwrite: bool = False,
        **kwargs: Any,
    ) -> DownloadResult:
        """
        Download a file from the given URL.

        Args:
            url: URL of the file to download
            file_path: Optional, path to save the file to. If not provided,
                the filename is extracted from the Content-Disposition header or
                defaults to the last part of the URL.
            overwrite: Optional, default False. If the file already exists,
                whether to overwrite it or not.
            **kwargs: Additional keyword arguments to pass to the underlying
                `httpx` client.

        Returns:
            DownloadResult: A named tuple containing a boolean indicating success,
                the path to the downloaded file if successful, or an error message
                if not.
        """
        if not url:
            return DownloadResult(success=False, error="Empty URL provided")

        headers = kwargs.pop("headers", {})
        if API_URL and url.startswith(API_URL):
            headers["X-API-Key"] = API_KEY

        try:
            async with self._session.stream(
                "GET", url, timeout=self._download_timeout, headers=headers
            ) as response:
                response.raise_for_status()
                if file_path is None:
                    cd = response.headers.get("Content-Disposition", "")
                    match = re.search(r'filename="?([^"]+)"?', cd)
                    filename = (
                        unquote(match[1])
                        if match
                        else (Path(url).name or uuid.uuid4().hex)
                    )
                    path = Path(DOWNLOADS_DIR) / filename
                else:
                    path = Path(file_path) if isinstance(file_path, str) else file_path

                if path.exists() and not overwrite:
                    return DownloadResult(success=True, file_path=path)

                path.parent.mkdir(parents=True, exist_ok=True)
                async with aiofiles.open(path, "wb") as f:
                    async for chunk in response.aiter_bytes(self.CHUNK_SIZE):
                        await f.write(chunk)

                LOGGER.debug("Successfully downloaded file to %s", path)
                return DownloadResult(success=True, file_path=path)

        except Exception as e:
            error_msg = self._handle_http_error(e, url)
            LOGGER.error(error_msg)
            return DownloadResult(success=False, error=error_msg)

    @staticmethod
    def _handle_http_error(e: Exception, url: str) -> str:
        if isinstance(e, httpx.TooManyRedirects):
            return f"Too many redirects for {url}: {e}"
        elif isinstance(e, httpx.HTTPStatusError):
            return f"HTTP error {e.response.status_code} for {url}"
        elif isinstance(e, httpx.RequestError):
            return f"Request failed for {url}: {e}"
        return f"Unexpected error for {url}: {e}"

    async def make_request(
        self,
        url: str,
        max_retries: int = MAX_RETRIES,
        backoff_factor: float = BACKOFF_FACTOR,
        **kwargs: Any,
    ) -> dict[str, Any] | None:
        """
        Make an HTTP GET request with retries and exponential backoff.

        Args:
            url: URL to request
            max_retries: Maximum number of retry attempts
            backoff_factor: Base delay for exponential backoff
            kwargs: Additional arguments to pass to httpx

        Returns:
            Parsed JSON response as dict if successful, None otherwise
        """
        if not url:
            LOGGER.warning("Empty URL provided")
            return None

        headers = kwargs.pop("headers", {})
        if API_URL and url.startswith(API_URL):
            headers["X-API-Key"] = API_KEY

        for attempt in range(max_retries):
            try:
                response = await self._session.get(url, headers=headers, **kwargs)
                response.raise_for_status()
                return response.json()

            except httpx.TooManyRedirects:
                error_msg = f"Redirect loop for {url}"
                if attempt == max_retries - 1:
                    LOGGER.error(error_msg)
                    return None
                LOGGER.warning(error_msg)

            except httpx.HTTPStatusError as e:
                error_msg = f"HTTP error {e.response.status_code} for {url}"
                if attempt == max_retries - 1:
                    LOGGER.error(error_msg)
                    return None
                LOGGER.warning(error_msg)

            except httpx.RequestError as e:
                error_msg = f"Request failed for {url}: {str(e)}"
                if attempt == max_retries - 1:
                    LOGGER.error(error_msg)
                    return None
                LOGGER.warning(error_msg)

            except ValueError as e:
                LOGGER.error("Invalid JSON response from %s: %s", url, str(e))
                return None

            except Exception as e:
                LOGGER.error("Unexpected error for %s: %s", url, str(e))
                return None

            # Exponential backoff
            await asyncio.sleep(backoff_factor * (2**attempt))

        return None

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()