|
| 1 | +"""BuzzHeavier upload helper. |
| 2 | +
|
| 3 | +Used by mirror tasks when the ``-bh`` flag is supplied. Walks the |
| 4 | +download directory, streams each file to BuzzHeavier with progress |
| 5 | +callbacks that the existing status renderer can read, and finishes by |
| 6 | +calling ``listener.on_upload_complete``. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from logging import getLogger |
| 12 | +from os import walk, path as ospath |
| 13 | +from time import time |
| 14 | +from typing import AsyncIterator |
| 15 | + |
| 16 | +from aiofiles import open as aiopen |
| 17 | +from httpx import AsyncClient, HTTPError, Limits, Timeout |
| 18 | + |
| 19 | +from ...core.config_manager import Config |
| 20 | + |
| 21 | + |
| 22 | +LOGGER = getLogger(__name__) |
| 23 | + |
| 24 | +_UPLOAD_BASE = "https://w.buzzheavier.com" |
| 25 | +_UPLOAD_CHUNK = 16 * 1024 * 1024 # 16 MiB read window |
| 26 | +_HTTP_TIMEOUT = Timeout(connect=30.0, read=600.0, write=600.0, pool=30.0) |
| 27 | + |
| 28 | + |
| 29 | +def _auth_headers() -> dict[str, str]: |
| 30 | + headers: dict[str, str] = {} |
| 31 | + account_id = (Config.BUZZHEAVIER_ACCOUNT_ID or "").strip() |
| 32 | + if account_id: |
| 33 | + headers["Authorization"] = f"Bearer {account_id}" |
| 34 | + return headers |
| 35 | + |
| 36 | + |
| 37 | +class BuzzHeavierUploader: |
| 38 | + """Stream files in ``self._path`` to BuzzHeavier sequentially.""" |
| 39 | + |
| 40 | + def __init__(self, listener, path: str): |
| 41 | + self._listener = listener |
| 42 | + self._path = path |
| 43 | + self._processed_bytes = 0 |
| 44 | + self._start_time = time() |
| 45 | + self._last_speed_bytes = 0 |
| 46 | + self._last_speed_at = self._start_time |
| 47 | + self._speed = 0.0 |
| 48 | + self._files_dict: dict[str, str] = {} |
| 49 | + self._total_files = 0 |
| 50 | + self._error: str = "" |
| 51 | + |
| 52 | + # ── status interface ───────────────────────────────────────────── |
| 53 | + |
| 54 | + @property |
| 55 | + def processed_bytes(self) -> int: |
| 56 | + return self._processed_bytes |
| 57 | + |
| 58 | + @property |
| 59 | + def speed(self) -> float: |
| 60 | + now = time() |
| 61 | + elapsed = now - self._last_speed_at |
| 62 | + if elapsed >= 1.0: |
| 63 | + delta = self._processed_bytes - self._last_speed_bytes |
| 64 | + self._speed = delta / elapsed if elapsed > 0 else 0.0 |
| 65 | + self._last_speed_at = now |
| 66 | + self._last_speed_bytes = self._processed_bytes |
| 67 | + return self._speed |
| 68 | + |
| 69 | + # ── upload ──────────────────────────────────────────────────────── |
| 70 | + |
| 71 | + async def _stream_file(self, file_path: str, file_size: int) -> AsyncIterator[bytes]: |
| 72 | + async with aiopen(file_path, "rb") as fh: |
| 73 | + while True: |
| 74 | + if self._listener.is_cancelled: |
| 75 | + return |
| 76 | + chunk = await fh.read(_UPLOAD_CHUNK) |
| 77 | + if not chunk: |
| 78 | + return |
| 79 | + self._processed_bytes += len(chunk) |
| 80 | + yield chunk |
| 81 | + |
| 82 | + async def _upload_one(self, client: AsyncClient, file_path: str) -> str: |
| 83 | + file_name = ospath.basename(file_path) |
| 84 | + file_size = ospath.getsize(file_path) |
| 85 | + url = f"{_UPLOAD_BASE}/{file_name}" |
| 86 | + headers = { |
| 87 | + "Content-Type": "application/octet-stream", |
| 88 | + "Content-Length": str(file_size), |
| 89 | + **_auth_headers(), |
| 90 | + } |
| 91 | + |
| 92 | + LOGGER.info(f"Uploading to BuzzHeavier: {file_name} ({file_size} bytes)") |
| 93 | + response = await client.put( |
| 94 | + url, |
| 95 | + content=self._stream_file(file_path, file_size), |
| 96 | + headers=headers, |
| 97 | + ) |
| 98 | + if response.status_code not in (200, 201): |
| 99 | + raise RuntimeError( |
| 100 | + f"BuzzHeavier upload failed [{response.status_code}]: " |
| 101 | + f"{response.text[:200]}" |
| 102 | + ) |
| 103 | + |
| 104 | + try: |
| 105 | + payload = response.json() |
| 106 | + except ValueError as exc: |
| 107 | + raise RuntimeError( |
| 108 | + f"BuzzHeavier returned non-JSON response: {response.text[:200]}" |
| 109 | + ) from exc |
| 110 | + |
| 111 | + data = payload.get("data") if isinstance(payload, dict) else None |
| 112 | + if not isinstance(data, dict): |
| 113 | + raise RuntimeError("BuzzHeavier response missing 'data' object") |
| 114 | + file_id = (data.get("id") or "").strip() |
| 115 | + if not file_id: |
| 116 | + raise RuntimeError("BuzzHeavier response missing file id") |
| 117 | + return f"https://buzzheavier.com/{file_id}" |
| 118 | + |
| 119 | + async def upload(self) -> None: |
| 120 | + files: list[str] = [] |
| 121 | + if ospath.isfile(self._path): |
| 122 | + files.append(self._path) |
| 123 | + else: |
| 124 | + for root, _, names in walk(self._path): |
| 125 | + for name in sorted(names): |
| 126 | + candidate = ospath.join(root, name) |
| 127 | + if ospath.isfile(candidate): |
| 128 | + files.append(candidate) |
| 129 | + |
| 130 | + if not files: |
| 131 | + await self._listener.on_upload_error( |
| 132 | + "BuzzHeavier: no files were found to upload" |
| 133 | + ) |
| 134 | + return |
| 135 | + |
| 136 | + self._total_files = len(files) |
| 137 | + first_link = "" |
| 138 | + |
| 139 | + try: |
| 140 | + async with AsyncClient( |
| 141 | + timeout=_HTTP_TIMEOUT, |
| 142 | + limits=Limits(max_connections=4, max_keepalive_connections=2), |
| 143 | + ) as client: |
| 144 | + for file_path in files: |
| 145 | + if self._listener.is_cancelled: |
| 146 | + await self._listener.on_upload_error( |
| 147 | + "BuzzHeavier upload cancelled by user" |
| 148 | + ) |
| 149 | + return |
| 150 | + try: |
| 151 | + link = await self._upload_one(client, file_path) |
| 152 | + except (HTTPError, RuntimeError) as exc: |
| 153 | + LOGGER.error( |
| 154 | + f"BuzzHeavier upload error for " |
| 155 | + f"{ospath.basename(file_path)}: {exc}" |
| 156 | + ) |
| 157 | + self._error = str(exc) |
| 158 | + await self._listener.on_upload_error( |
| 159 | + f"BuzzHeavier: {exc}" |
| 160 | + ) |
| 161 | + return |
| 162 | + self._files_dict[link] = ospath.basename(file_path) |
| 163 | + if not first_link: |
| 164 | + first_link = link |
| 165 | + except Exception as exc: # pragma: no cover - safety net |
| 166 | + LOGGER.error(f"BuzzHeavier session error: {exc}") |
| 167 | + await self._listener.on_upload_error(f"BuzzHeavier: {exc}") |
| 168 | + return |
| 169 | + |
| 170 | + if self._listener.is_cancelled: |
| 171 | + await self._listener.on_upload_error( |
| 172 | + "BuzzHeavier upload cancelled by user" |
| 173 | + ) |
| 174 | + return |
| 175 | + |
| 176 | + LOGGER.info( |
| 177 | + f"BuzzHeavier upload completed: {self._total_files} file(s)" |
| 178 | + ) |
| 179 | + # Mirror behaviour: ``link`` is the primary URL, ``files`` is a |
| 180 | + # link → name dict (for multi-file), ``folders``/``mime_type`` |
| 181 | + # carry the totals expected by ``on_upload_complete``. |
| 182 | + await self._listener.on_upload_complete( |
| 183 | + first_link, |
| 184 | + self._files_dict, |
| 185 | + self._total_files, |
| 186 | + "BuzzHeavier", |
| 187 | + ) |
0 commit comments