"""VirginProxy - minimal official client for Python 3.8+ (one file, standard library only). Docs: https://docs.virginproxy.com/sdks/ API: https://docs.virginproxy.com/openapi.json from virginproxy import VirginProxy vp = VirginProxy() # key from VP_KEY page = vp.scrape("https://example.com/") print(page["body"]) Errors are raised as VirginProxyError with the API's stable ``code``. Calls that failed because of a short-lived limit (rate_limited, concurrency_limited, busy, ...) are retried automatically after the time the API asks for. """ import hashlib import hmac import json import os import re import time import urllib.error import urllib.parse import urllib.request __version__ = "1.2.0" __all__ = ["VirginProxy", "VirginProxyError", "verify_webhook"] RETRY_CODES = {"rate_limited", "concurrency_limited", "busy", "executor_unavailable", "idempotency_in_progress", "render_unavailable"} class VirginProxyError(Exception): """An error answer of the API. Decide by ``code``, not by the message.""" def __init__(self, status, body, headers=None): err = (body or {}).get("error") or {} self.status = status self.code = err.get("code") or "http_%d" % status self.message = err.get("message") or "The API answered with an error." self.charged = err.get("charged") self.credits = err.get("credits") retry = err.get("retry_after_ms") if retry is None and headers is not None and headers.get("Retry-After"): try: retry = int(headers.get("Retry-After")) * 1000 except ValueError: retry = None self.retry_after_ms = retry self.request_id = (body or {}).get("request_id") or (headers.get("X-Request-Id") if headers is not None else None) self.details = err super().__init__("%s: %s" % (self.code, self.message)) def _query(params): out = [] for key, value in (params or {}).items(): if value is None: continue if isinstance(value, bool): value = "true" if value else "false" out.append((key, str(value))) return ("?" + urllib.parse.urlencode(out)) if out else "" class Response: """A non-JSON answer (raw, screenshot, PDF, export).""" def __init__(self, status, headers, body): self.status = status self.headers = headers self.body = body @property def credits(self): return int(self.headers.get("X-VP-Credits") or 0) @property def request_id(self): return self.headers.get("X-VP-Request-Id") @property def target_status(self): return int(self.headers.get("X-VP-Status") or self.status) @property def test(self): return self.headers.get("X-VP-Test") == "true" class VirginProxy: """Client for https://api.virginproxy.com. ``api_key`` defaults to the environment variable VP_KEY.""" def __init__(self, api_key=None, base_url="https://api.virginproxy.com", timeout=180, max_retries=2): self.api_key = api_key or os.environ.get("VP_KEY") if not self.api_key: raise ValueError("VirginProxy: no API key. Pass api_key=... or set VP_KEY.") self.base_url = base_url.rstrip("/") self.timeout = timeout self.max_retries = max_retries # ---- transport ----------------------------------------------------------------------------- def call(self, method, path, body=None, query=None, headers=None, raw=False, timeout=None): """One call. Returns the decoded JSON, or a Response with raw=True.""" data = json.dumps(body).encode("utf-8") if body is not None else None attempt = 0 while True: req = urllib.request.Request(self.base_url + path + _query(query), data=data, method=method) req.add_header("Authorization", "Bearer " + self.api_key) req.add_header("User-Agent", "virginproxy-python/" + __version__) req.add_header("Accept", "application/json") if data is not None: req.add_header("Content-Type", "application/json") for key, value in (headers or {}).items(): req.add_header(key, value) try: with urllib.request.urlopen(req, timeout=timeout or self.timeout) as res: payload = res.read() if raw: return Response(res.status, res.headers, payload) return json.loads(payload.decode("utf-8")) if payload else None except urllib.error.HTTPError as e: payload = e.read() try: parsed = json.loads(payload.decode("utf-8")) except ValueError: parsed = None err = VirginProxyError(e.code, parsed, e.headers) if err.code in RETRY_CODES and attempt < self.max_retries: attempt += 1 time.sleep(min(30.0, max(0.25, (err.retry_after_ms or 1000) / 1000.0))) continue raise err # ---- requests ------------------------------------------------------------------------------ def request(self, body, idempotency_key=None): """POST /v1/requests with any options.""" return self.call("POST", "/v1/requests", body, headers={"Idempotency-Key": idempotency_key} if idempotency_key else None) def scrape(self, url, idempotency_key=None, **options): """One page as Markdown of its main content (override with options, e.g. render=True).""" body = {"format": "markdown", "main_content": True} body.update(options) body["url"] = url return self.request(body, idempotency_key=idempotency_key) def raw(self, url, headers=None, **query): """GET /v1/raw: the target's answer itself as a Response (body is bytes).""" query["url"] = url sent = {"X-VP-Header-" + k: v for k, v in (headers or {}).items()} return self.call("GET", "/v1/raw", query=query, headers=sent, raw=True) def screenshot(self, url, **query): """GET /v1/screenshot: a Response whose body is the image.""" query["url"] = url return self.call("GET", "/v1/screenshot", query=query, raw=True) def pdf(self, url, **query): """GET /v1/pdf: a Response whose body is the PDF.""" query["url"] = url return self.call("GET", "/v1/pdf", query=query, raw=True) def batch(self, requests=None, urls=None, request=None, max_credits=None, tag=None): """POST /v1/batch: either requests=[...] or urls=[...] with request={...} for every URL.""" body = {} if requests is not None: body["requests"] = requests if urls is not None: body["urls"] = urls body["request"] = request if request is not None else {"format": "markdown", "main_content": True} if max_credits is not None: body["max_credits"] = max_credits if tag is not None: body["tag"] = tag return self.call("POST", "/v1/batch", body, timeout=max(self.timeout, 120)) def map(self, url, **options): options["url"] = url return self.call("POST", "/v1/map", options) def search(self, query, **options): """POST /v1/search: results as JSON; options as in the docs (engine, limit, language, country, time_range, scrape ...).""" return self.call("POST", "/v1/search", dict(options, query=query), timeout=max(self.timeout, 180)) def estimate(self, body): return self.call("POST", "/v1/estimate", body) def solve_captcha(self, body): return self.call("POST", "/v1/captcha", body) # ---- jobs and crawls ----------------------------------------------------------------------- def create_job(self, body, idempotency_key=None): return self.call("POST", "/v1/jobs", body, headers={"Idempotency-Key": idempotency_key} if idempotency_key else None) def crawl(self, url, idempotency_key=None, **options): options["url"] = url return self.call("POST", "/v1/crawl", options, headers={"Idempotency-Key": idempotency_key} if idempotency_key else None) def list_jobs(self, limit=None, before=None): return self.call("GET", "/v1/jobs", query={"limit": limit, "before": before}) def get_job(self, job_id, wait=None): """With wait=1…30 the answer waits until the job moves on (or the seconds pass).""" if wait: return self.call("GET", "/v1/jobs/" + urllib.parse.quote(job_id), query={"wait": wait}, timeout=max(self.timeout, wait + 15)) return self.call("GET", "/v1/jobs/" + urllib.parse.quote(job_id)) def job_results(self, job_id, offset=0, limit=100, status=None): return self.call("GET", "/v1/jobs/%s/results" % urllib.parse.quote(job_id), query={"offset": offset, "limit": limit, "status": status}) def iter_job_results(self, job_id, status=None): """Every result of a job, page by page.""" offset = 0 while True: page = self.job_results(job_id, offset=offset, status=status) for item in page["items"]: yield item if page.get("next_offset") is None: return offset = page["next_offset"] def export_job(self, job_id, format="ndjson", status=None, include_body=None): """GET /v1/jobs/{id}/export as text (ndjson, csv or json).""" res = self.call("GET", "/v1/jobs/%s/export" % urllib.parse.quote(job_id), query={"format": format, "status": status, "include_body": include_body}, raw=True) return res.body.decode("utf-8") def stream_job(self, job_id, include_body=None): """GET /v1/jobs/{id}/stream: yields every finished item as it comes ({"type": "item", ...}), then {"type": "end", "job": ...}. Reconnects by itself after the server's 15-minute limit; pings are skipped.""" after = None while True: req = urllib.request.Request(self.base_url + "/v1/jobs/%s/stream" % urllib.parse.quote(job_id) + _query({"after": after, "include_body": include_body}), method="GET") req.add_header("Authorization", "Bearer " + self.api_key) req.add_header("User-Agent", "virginproxy-python/" + __version__) again = False try: with urllib.request.urlopen(req, timeout=16 * 60) as res: for raw_line in res: line = raw_line.decode("utf-8").strip() if not line: continue msg = json.loads(line) if msg.get("type") == "item": after = msg.get("index") yield msg elif msg.get("type") == "end": yield msg return elif msg.get("type") == "reconnect": after = msg.get("after") again = True except urllib.error.HTTPError as e: payload = e.read() try: parsed = json.loads(payload.decode("utf-8")) except ValueError: parsed = None raise VirginProxyError(e.code, parsed, e.headers) if not again: return def create_job_ndjson(self, requests, job_options=None): """POST /v1/jobs as NDJSON: one request per line (strings are taken as URLs), optional job options in a first line.""" lines = ([json.dumps({"job": job_options})] if job_options else []) + [json.dumps({"url": r} if isinstance(r, str) else r) for r in requests] req = urllib.request.Request(self.base_url + "/v1/jobs", data=("\n".join(lines) + "\n").encode("utf-8"), method="POST") req.add_header("Authorization", "Bearer " + self.api_key) req.add_header("User-Agent", "virginproxy-python/" + __version__) req.add_header("Content-Type", "application/x-ndjson") try: with urllib.request.urlopen(req, timeout=self.timeout) as res: return json.loads(res.read().decode("utf-8")) except urllib.error.HTTPError as e: payload = e.read() try: parsed = json.loads(payload.decode("utf-8")) except ValueError: parsed = None raise VirginProxyError(e.code, parsed, e.headers) def cancel_job(self, job_id): return self.call("DELETE", "/v1/jobs/" + urllib.parse.quote(job_id)) def retry_job(self, job_id): return self.call("POST", "/v1/jobs/%s/retry" % urllib.parse.quote(job_id)) def wait_for_job(self, job_id, interval=2.0, timeout=1800): """Polls until the job is done or canceled.""" end = time.time() + timeout while True: job = self.get_job(job_id, wait=25) if job["status"] not in ("queued", "running"): return job if time.time() > end: raise TimeoutError("VirginProxy: job %s still %s after %d s" % (job_id, job["status"], timeout)) time.sleep(interval) # ---- account ------------------------------------------------------------------------------- def account(self): return self.call("GET", "/v1/account") def usage(self, days=None, tag=None): return self.call("GET", "/v1/usage", query={"days": days, "tag": tag}) def usage_breakdown(self, **query): return self.call("GET", "/v1/usage/breakdown", query=query) def list_requests(self, **query): return self.call("GET", "/v1/requests", query=query) def get_request(self, request_id): return self.call("GET", "/v1/requests/" + urllib.parse.quote(request_id)) def status(self): return self.call("GET", "/v1/status") def errors(self): """Every error code with its HTTP status, meaning and whether to retry.""" return self.call("GET", "/v1/errors") def get_answer(self, request_id): """The kept answer of a request (sent with an Idempotency-Key, or cached).""" return self.call("GET", "/v1/requests/" + urllib.parse.quote(request_id) + "/answer") def limits(self): """What you may still do right now: parallel requests, rate, CAPTCHAs today, daily caps.""" return self.call("GET", "/v1/limits") def update_settings(self, **changes): """daily_cap, alert_thresholds, alert_hook_url, alert_hook_slack (a key with the manage scope).""" return self.call("PATCH", "/v1/account/settings", changes) # ---- presets and schedules ----------------------------------------------------------------- def list_presets(self): return self.call("GET", "/v1/presets") def get_preset(self, name): return self.call("GET", "/v1/presets/" + urllib.parse.quote(name)) def create_preset(self, name, request, description=None): body = {"name": name, "request": request} if description: body["description"] = description return self.call("POST", "/v1/presets", body) def update_preset(self, name, **changes): return self.call("PATCH", "/v1/presets/" + urllib.parse.quote(name), changes) def delete_preset(self, name): return self.call("DELETE", "/v1/presets/" + urllib.parse.quote(name)) def list_schedules(self): return self.call("GET", "/v1/schedules") def get_schedule(self, schedule_id): return self.call("GET", "/v1/schedules/" + urllib.parse.quote(schedule_id)) def create_schedule(self, body): return self.call("POST", "/v1/schedules", body) def update_schedule(self, schedule_id, **changes): return self.call("PATCH", "/v1/schedules/" + urllib.parse.quote(schedule_id), changes) def pause_schedule(self, schedule_id): return self.update_schedule(schedule_id, status="paused") def resume_schedule(self, schedule_id): return self.update_schedule(schedule_id, status="active") def delete_schedule(self, schedule_id): return self.call("DELETE", "/v1/schedules/" + urllib.parse.quote(schedule_id)) def preview_schedule(self, every): """A rhythm checked ("weekdays at 09:30") and its next three runs; nothing is saved.""" return self.call("POST", "/v1/schedules/preview", {"every": every}) def schedule_reports(self, schedule_id, limit=None): """Monitors (track: "pages"): what each run found - new, removed and changed pages.""" return self.call("GET", "/v1/schedules/%s/reports" % urllib.parse.quote(schedule_id), query={"limit": limit}) # ---- storage destinations (delivery to your own S3-compatible bucket) ---- def list_destinations(self): return self.call("GET", "/v1/destinations") def create_destination(self, **body): return self.call("POST", "/v1/destinations", body) def delete_destination(self, destination_id): return self.call("DELETE", "/v1/destinations/" + urllib.parse.quote(destination_id)) def test_destination(self, destination_id): return self.call("POST", "/v1/destinations/%s/test" % urllib.parse.quote(destination_id)) def run_schedule(self, schedule_id): return self.call("POST", "/v1/schedules/" + urllib.parse.quote(schedule_id) + "/run") # ---- keys and webhooks (a live key without its own credit limit) --------------------------- def list_keys(self): return self.call("GET", "/v1/keys") def create_key(self, name, mode="live", credit_limit=None, ip_allowlist=None): body = {"name": name, "mode": mode} if credit_limit is not None: body["credit_limit"] = credit_limit if ip_allowlist is not None: body["ip_allowlist"] = ip_allowlist return self.call("POST", "/v1/keys", body) def update_key(self, key_id, **changes): return self.call("PATCH", "/v1/keys/" + urllib.parse.quote(str(key_id)), changes) def revoke_key(self, key_id, confirm_current=False): return self.call("DELETE", "/v1/keys/" + urllib.parse.quote(str(key_id)), query={"confirm": "revoke_current_key"} if confirm_current else None) def get_webhooks(self, limit=None): return self.call("GET", "/v1/webhooks", query={"limit": limit}) def rotate_webhook_secret(self): return self.call("POST", "/v1/webhooks/secret") def test_webhook(self, url, event="webhook.test"): return self.call("POST", "/v1/webhooks/test", {"url": url, "event": event}) def roll_key(self, key_id, **options): return self.call("POST", "/v1/keys/" + urllib.parse.quote(str(key_id)) + "/roll", options) def list_deliveries(self, **query): return self.call("GET", "/v1/webhooks/deliveries", query=query) def get_delivery(self, delivery_id): return self.call("GET", "/v1/webhooks/deliveries/" + urllib.parse.quote(delivery_id)) def redeliver(self, delivery_id): return self.call("POST", "/v1/webhooks/deliveries/" + urllib.parse.quote(delivery_id) + "/redeliver") def verify_webhook(secret, raw_body, signature_header, tolerance=300, now=None): """Checks the X-VP-Signature header ("t=...,v1=...") against the raw body bytes. Returns True or False. During a secret rotation with a grace period the header carries two signatures ("t=...,v1=,v1="); the call is genuine when any of them matches your secret.""" m = re.match(r"^t=(\d+)((?:,v1=[0-9a-f]{64}){1,2})$", (signature_header or "").strip()) if not m: return False if abs((now if now is not None else time.time()) - int(m.group(1))) > tolerance: return False if isinstance(raw_body, str): raw_body = raw_body.encode("utf-8") want = hmac.new(secret.encode("utf-8"), m.group(1).encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest() found = False for sig in m.group(2)[4:].split(",v1="): if hmac.compare_digest(want, sig): found = True return found