File size: 1,363 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)}