""" id: fetcher title: URL Fetcher author: admin description: Fetch a URL with optional headers; returns status, headers, body (truncated) and saves full body to /data/adaptai/web/tmp. version: 0.1.0 license: Proprietary """ import urllib.request import urllib.error import time import os import json SAVE_DIR = "/data/adaptai/web/tmp" os.makedirs(SAVE_DIR, exist_ok=True) class Tools: def get( self, url: str, headers_json: str = "{}", timeout: int = 20, max_bytes: int = 500000, ) -> dict: headers = json.loads(headers_json) if headers_json else {} req = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as resp: data = resp.read(max_bytes) fname = f"{SAVE_DIR}/fetch_{int(time.time())}.bin" open(fname, "wb").write(data) return { "status": getattr(resp, "status", 200), "headers": {k: v for k, v in resp.headers.items()}, "body": data.decode("utf-8", errors="replace")[:4000], "file": fname, } except urllib.error.HTTPError as e: return {"status": e.code, "error": str(e)} except Exception as e: return {"error": str(e)}