#!/usr/bin/env python3 """Export a Confluence page tree as readable Markdown, PDF, or both. Markdown is the default: it is fetched from the Confluence REST API and is intended to be readable by a person or downstream AI agent. No .env file is loaded; inject settings through the runtime environment. Required: CONFLUENCE_BASE and CONFLUENCE_PAGE_ID, or CONFLUENCE_PAGE_TITLE plus CONFLUENCE_SPACE. Authentication uses CONFLUENCE_AUTH_MODE=auto by default and tries configured methods from CONFLUENCE_AUTH_MODES. """ from __future__ import annotations import argparse import base64 from collections import deque from html.parser import HTMLParser import json import os from pathlib import Path import re import ssl import sys import time import urllib.error import urllib.parse import urllib.request import zipfile from typing import Any, Deque, Dict, List, Optional, Set, Tuple DEFAULT_AUTH_MODES = ("bearer", "basic-token", "basic", "cookie", "header", "none") DEFAULT_TIMEOUT = 90 DEFAULT_PAGE_LIMIT = 50 DEFAULT_RETRIES = 3 PDF_SIGNATURE = b"%PDF-" class ConfluenceError(RuntimeError): def __init__(self, message: str, status: Optional[int] = None) -> None: super().__init__(message) self.status = status class NoRedirectHandler(urllib.request.HTTPRedirectHandler): def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None: return None class ConfluenceClient: def __init__(self, base_url: str, auth_mode: str, env: Dict[str, str], timeout: int, ca_bundle: Optional[str], insecure: bool, allow_http: bool) -> None: self.base_url = base_url.rstrip("/") parsed = urllib.parse.urlsplit(self.base_url) allowed = ("https", "http") if allow_http else ("https",) if parsed.scheme not in allowed or not parsed.netloc: raise ConfluenceError("CONFLUENCE_BASE must be a valid https URL (http requires CONFLUENCE_ALLOW_HTTP=true)") self.origin = (parsed.scheme.lower(), parsed.netloc.lower()) self.timeout = timeout self.authorization: Optional[str] = None self.cookie: Optional[str] = None self.header: Optional[Tuple[str, str]] = None user, password = env.get("CONFLUENCE_USER"), env.get("CONFLUENCE_PASSWORD") token, cookie = env.get("CONFLUENCE_TOKEN"), env.get("CONFLUENCE_COOKIE") if auth_mode == "basic": if not user or password is None: raise ConfluenceError("basic auth requires CONFLUENCE_USER and CONFLUENCE_PASSWORD") raw = f"{user}:{password}".encode() self.authorization = "Basic " + base64.b64encode(raw).decode("ascii") elif auth_mode == "basic-token": if not user or not token: raise ConfluenceError("basic-token requires CONFLUENCE_USER and CONFLUENCE_TOKEN") raw = f"{user}:{token}".encode() self.authorization = "Basic " + base64.b64encode(raw).decode("ascii") elif auth_mode == "bearer": if not token: raise ConfluenceError("bearer auth requires CONFLUENCE_TOKEN") self.authorization = "Bearer " + token elif auth_mode == "cookie": if not cookie: raise ConfluenceError("cookie auth requires CONFLUENCE_COOKIE") self.cookie = cookie elif auth_mode == "header": name, value = env.get("CONFLUENCE_AUTH_HEADER_NAME", "").strip(), env.get("CONFLUENCE_AUTH_HEADER_VALUE", "") if not name or not value or "\r" in name + value or "\n" in name + value: raise ConfluenceError("header auth requires CONFLUENCE_AUTH_HEADER_NAME and CONFLUENCE_AUTH_HEADER_VALUE") self.header = (name, value) elif auth_mode != "none": raise ConfluenceError(f"Unsupported auth mode: {auth_mode}") context = ssl.create_default_context(cafile=ca_bundle) if ca_bundle else ssl.create_default_context() if insecure: context.check_hostname = False context.verify_mode = ssl.CERT_NONE self.opener = urllib.request.build_opener( urllib.request.HTTPSHandler(context=context), urllib.request.HTTPHandler(), NoRedirectHandler()) def _url(self, path: str) -> str: if path.startswith(("http://", "https://")): return path return self.base_url + "/" + path.lstrip("/") def _request(self, url: str, accept: str, allow_redirect: bool = False) -> Tuple[int, bytes, Any]: parsed = urllib.parse.urlsplit(url) if (parsed.scheme.lower(), parsed.netloc.lower()) != self.origin: raise ConfluenceError("Request points outside the configured Confluence origin") headers = {"Accept": accept, "User-Agent": "confluence-pages-to-readable-text/4.0"} if self.authorization: headers["Authorization"] = self.authorization if self.cookie: headers["Cookie"] = self.cookie if self.header: headers[self.header[0]] = self.header[1] try: with self.opener.open(urllib.request.Request(url, headers=headers), timeout=self.timeout) as response: return response.status, response.read(), response.headers except urllib.error.HTTPError as exc: if allow_redirect and exc.code in (301, 302, 303, 307, 308): return exc.code, b"", exc.headers try: detail = exc.read(500).decode("utf-8", "replace").replace("\n", " ") except Exception: detail = "" raise ConfluenceError(f"HTTP {exc.code} for {url}: {detail[:500]}", exc.code) from None except (urllib.error.URLError, TimeoutError, OSError) as exc: raise ConfluenceError(f"Request failed for {url}: {getattr(exc, 'reason', exc)}") from None def get_json(self, path: str, params: Optional[Dict[str, str]] = None) -> Dict[str, Any]: url = self._url(path) if params: url += "?" + urllib.parse.urlencode(params) _, body, _ = self._request(url, "application/json") try: result = json.loads(body.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ConfluenceError(f"Invalid JSON from Confluence for {path}: {exc}") from None if not isinstance(result, dict): raise ConfluenceError(f"Unexpected Confluence response for {path}") return result def check_auth(self) -> Dict[str, Any]: return self.get_json("/rest/api/user/current") def get_page(self, page_id: str) -> Dict[str, Any]: return self.get_json(f"/rest/api/content/{urllib.parse.quote(page_id, safe='')}", {"expand": "space,version,body.storage,body.view", "status": "current"}) def find_page(self, space: str, title: str) -> Dict[str, Any]: data = self.get_json("/rest/api/content", { "spaceKey": space, "title": title, "type": "page", "status": "current", "limit": "2", "expand": "space,version,body.storage,body.view"}) results = data.get("results") or [] if not results: raise ConfluenceError(f"Page {title!r} was not found in space {space!r}") if len(results) > 1: raise ConfluenceError("Multiple pages have this title; provide CONFLUENCE_PAGE_ID") return results[0] def child_pages(self, page_id: str, limit: int) -> List[Dict[str, Any]]: items: List[Dict[str, Any]] = [] start, seen = 0, set() while start not in seen: seen.add(start) data = self.get_json(f"/rest/api/content/{urllib.parse.quote(page_id, safe='')}/child/page", {"start": str(start), "limit": str(limit), "status": "current"}) collection = data.get("page") if isinstance(data.get("page"), dict) else data results = collection.get("results") or [] if not isinstance(results, list): raise ConfluenceError(f"Invalid child page list for ID {page_id}") items.extend(x for x in results if isinstance(x, dict)) size = int(collection.get("size", len(results)) or 0) next_link = (collection.get("_links") or {}).get("next") if next_link: query = urllib.parse.parse_qs(urllib.parse.urlsplit( urllib.parse.urljoin(self.base_url + "/", next_link)).query) if query.get("start"): start = int(query["start"][0]) continue total = collection.get("totalCount", collection.get("totalSize")) if not results or size < limit or (total is not None and start + size >= int(total)): break start += size return items def export_pdf(self, page_id: str, export_path: str, retries: int, id_param: str) -> bytes: encoded = urllib.parse.quote(page_id, safe="") path = export_path.replace("{page_id}", encoded) if "{page_id}" not in export_path: path += ("&" if "?" in path else "?") + urllib.parse.urlencode({id_param: page_id}) url, last_error = self._url(path), "Response was not a PDF" for attempt in range(1, retries + 1): try: _, body, headers = self._request(url, "application/pdf,application/octet-stream;q=0.9,*/*;q=0.8", True) if body.startswith(PDF_SIGNATURE): return body location = headers.get("Location") if location: download = urllib.parse.urljoin(url, location) parsed = urllib.parse.urlsplit(download) if (parsed.scheme.lower(), parsed.netloc.lower()) != self.origin: raise ConfluenceError("PDF redirect points to another host") _, body, response_headers = self._request(download, "application/pdf,application/octet-stream") if body.startswith(PDF_SIGNATURE): return body last_error = f"PDF endpoint returned {response_headers.get('Content-Type', 'unknown content type')}" else: last_error = f"PDF endpoint returned {headers.get('Content-Type', 'unknown content type')} without a PDF or redirect" except ConfluenceError as exc: if exc.status is not None and 400 <= exc.status < 500 and exc.status != 429: raise last_error = str(exc) if attempt < retries: time.sleep(min(2 ** (attempt - 1), 8)) raise ConfluenceError(f"Could not export page {page_id} to PDF: {last_error}") def configured_auth_modes(mode: str, modes: str, env: Dict[str, str]) -> List[str]: if mode != "auto": return [mode] order = [x.strip().lower() for x in modes.split(",") if x.strip()] available = { "bearer": bool(env.get("CONFLUENCE_TOKEN")), "basic-token": bool(env.get("CONFLUENCE_USER") and env.get("CONFLUENCE_TOKEN")), "basic": bool(env.get("CONFLUENCE_USER") and env.get("CONFLUENCE_PASSWORD") is not None), "cookie": bool(env.get("CONFLUENCE_COOKIE")), "header": bool(env.get("CONFLUENCE_AUTH_HEADER_NAME") and env.get("CONFLUENCE_AUTH_HEADER_VALUE")), "none": "none" in order, } return [x for x in order if available.get(x, False)] def authenticate(args: argparse.Namespace) -> ConfluenceClient: env = dict(os.environ) candidates = configured_auth_modes(args.auth_mode, args.auth_modes, env) if not candidates: raise ConfluenceError("No credentials configured for auto auth; check CONFLUENCE_AUTH_MODES") rejected = [] for mode in candidates: client = ConfluenceClient(args.base, mode, env, args.timeout, args.ca_bundle, args.insecure, args.allow_http) try: identity = client.check_auth() who = identity.get("displayName") or identity.get("username") or "user" print(f"Authentication successful: mode={mode}, user={who}") return client except ConfluenceError as exc: if exc.status in (301, 302, 303, 401, 403): rejected.append(f"{mode}: HTTP {exc.status}") continue raise raise ConfluenceError("No configured authentication method worked (" + "; ".join(rejected) + ")") class ReadableTextParser(HTMLParser): """Convert Confluence storage XHTML into agent-friendly Markdown text.""" BLOCKS = {"p", "div", "section", "article", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "ul", "ol", "li", "table", "tr", "hr", "figure"} def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: List[str] = [] self.hidden_depth = 0 self.links: List[str] = [] def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: if tag in ("script", "style"): self.hidden_depth += 1 return if self.hidden_depth: return values = dict(attrs) if tag in self.BLOCKS: self.parts.append("\n") if tag == "br": self.parts.append("\n") elif tag == "li": self.parts.append("- ") elif tag in ("td", "th"): self.parts.append(" | ") elif tag == "a": href = values.get("href") or "" self.links.append(href) if href: self.parts.append("[") def handle_endtag(self, tag: str) -> None: if tag in ("script", "style"): self.hidden_depth = max(0, self.hidden_depth - 1) return if self.hidden_depth: return if tag == "a" and self.links: href = self.links.pop() if href: self.parts.append(f"]({href})") if tag in self.BLOCKS: self.parts.append("\n") def handle_data(self, data: str) -> None: if not self.hidden_depth: self.parts.append(data) def text(self) -> str: raw = "".join(self.parts).replace("\xa0", " ") lines = [re.sub(r"[\t \r]+", " ", x).strip() for x in raw.splitlines()] cleaned: List[str] = [] for line in lines: if line: cleaned.append(line) elif cleaned and cleaned[-1]: cleaned.append("") return "\n".join(cleaned).strip() def page_to_markdown(page: Dict[str, Any], base_url: str) -> str: title = str(page.get("title") or page.get("id") or "Untitled") page_id = str(page.get("id") or "") body = page.get("body") or {} # Prefer rendered view so macro output is readable; fall back to storage XHTML. storage = ((body.get("view") or {}).get("value") or (body.get("storage") or {}).get("value") or "") parser = ReadableTextParser() parser.feed(storage) parser.close() links = page.get("_links") or {} webui = links.get("webui") page_url = urllib.parse.urljoin(base_url.rstrip("/") + "/", webui) if webui else "" header = [f"# {title}", "", f"Confluence page ID: {page_id}"] if page_url: header.append(f"URL: {page_url}") content = parser.text() if not content: raise ConfluenceError(f"Confluence returned an empty body for page {page_id}") header.extend(["", content]) return "\n".join(header).rstrip() + "\n" def collect_pages(api: ConfluenceClient, root: Dict[str, Any], max_depth: int, max_pages: int, page_limit: int) -> List[Dict[str, Any]]: root_id = str(root.get("id") or "") if not root_id: raise ConfluenceError("Root Confluence page has no ID") title = str(root.get("title") or root_id) space = str((root.get("space") or {}).get("key") or "") found = [{"id": root_id, "title": title, "space": space, "path": [title], "depth": 0}] queue: Deque[Tuple[str, List[str], int]] = deque([(root_id, [title], 0)]) visited = {root_id} while queue: parent_id, parent_path, depth = queue.popleft() if depth >= max_depth: continue for child in api.child_pages(parent_id, page_limit): child_id = str(child.get("id") or "") if not child_id or child_id in visited: continue visited.add(child_id) child_title = str(child.get("title") or child_id) path = parent_path + [child_title] found.append({"id": child_id, "title": child_title, "space": space, "path": path, "depth": depth + 1}) if len(found) > max_pages: raise ConfluenceError(f"CONFLUENCE_MAX_PAGES={max_pages} reached") queue.append((child_id, path, depth + 1)) return found def slugify(value: str, max_length: int = 100) -> str: value = re.sub(r"[\\/:*?\"<>|\x00-\x1f]+", " ", value).strip() return re.sub(r"\s+", "_", value).strip("._ ")[:max_length] or "page" def env_int(name: str, default: int) -> int: try: value = int(os.getenv(name, str(default))) except ValueError: raise argparse.ArgumentTypeError(f"{name} must be an integer") from None if value < 1: raise argparse.ArgumentTypeError(f"{name} must be at least 1") return value def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base", default=os.getenv("CONFLUENCE_BASE")) parser.add_argument("--auth-mode", default=os.getenv("CONFLUENCE_AUTH_MODE", "auto"), choices=("auto", "bearer", "basic", "basic-token", "cookie", "header", "none")) parser.add_argument("--auth-modes", default=os.getenv("CONFLUENCE_AUTH_MODES", ",".join(DEFAULT_AUTH_MODES))) parser.add_argument("--page-id", default=os.getenv("CONFLUENCE_PAGE_ID")) parser.add_argument("--page-title", default=os.getenv("CONFLUENCE_PAGE_TITLE")) parser.add_argument("--space", default=os.getenv("CONFLUENCE_SPACE")) parser.add_argument("--out", default=os.getenv("CONFLUENCE_OUT", "confluence_export")) parser.add_argument("--output-format", default=os.getenv("CONFLUENCE_OUTPUT_FORMAT", "text"), choices=("text", "pdf", "both"), help="text (Markdown, default), pdf, or both") parser.add_argument("--pdf-export-path", default=os.getenv( "CONFLUENCE_PDF_EXPORT_PATH", "/spaces/flyingpdf/pdfpageexport.action")) parser.add_argument("--page-id-param", default=os.getenv("CONFLUENCE_PAGE_ID_PARAM", "pageId")) parser.add_argument("--max-depth", type=int, default=env_int("CONFLUENCE_MAX_DEPTH", 100)) parser.add_argument("--max-pages", type=int, default=env_int("CONFLUENCE_MAX_PAGES", 10000)) parser.add_argument("--page-limit", type=int, default=env_int("CONFLUENCE_PAGE_LIMIT", DEFAULT_PAGE_LIMIT)) parser.add_argument("--timeout", type=int, default=env_int("CONFLUENCE_TIMEOUT", DEFAULT_TIMEOUT)) parser.add_argument("--retries", type=int, default=env_int("CONFLUENCE_RETRIES", DEFAULT_RETRIES)) parser.add_argument("--delay", type=float, default=float(os.getenv("CONFLUENCE_DELAY", "0.2"))) parser.add_argument("--ca-bundle", default=os.getenv("CONFLUENCE_CA_BUNDLE")) parser.add_argument("--insecure", action="store_true", default=os.getenv("CONFLUENCE_INSECURE", "false").lower() == "true") parser.add_argument("--allow-http", action="store_true", default=os.getenv("CONFLUENCE_ALLOW_HTTP", "false").lower() == "true") parser.add_argument("--dry-run", action="store_true") parser.add_argument("--no-zip", action="store_true", default=os.getenv("CONFLUENCE_NO_ZIP", "false").lower() == "true") parser.add_argument("--check", action="store_true") args = parser.parse_args(argv) if not args.base: parser.error("--base or CONFLUENCE_BASE is required") if not args.check and not args.page_id and not (args.page_title and args.space): parser.error("Set CONFLUENCE_PAGE_ID or both CONFLUENCE_PAGE_TITLE and CONFLUENCE_SPACE") for name in ("max_depth", "max_pages", "page_limit", "timeout", "retries"): if getattr(args, name) < 1: parser.error(f"--{name.replace('_', '-')} must be at least 1") if args.delay < 0: parser.error("--delay cannot be negative") return args def main(argv: Optional[List[str]] = None) -> int: args = parse_args(argv) try: api = authenticate(args) if args.check: return 0 root = api.get_page(args.page_id) if args.page_id else api.find_page(args.space, args.page_title) pages = collect_pages(api, root, args.max_depth, args.max_pages, args.page_limit) print(f"Root page: {root.get('title')} (ID {root.get('id')}); pages found: {len(pages)}") if args.dry_run: for page in pages: print(f"{' ' * page['depth']}{page['title']} [id={page['id']}]") return 0 out_dir = Path(args.out) out_dir.mkdir(parents=True, exist_ok=True) files: List[Dict[str, str]] = [] failures: List[str] = [] exported_ids: Set[str] = set() for index, page in enumerate(pages, 1): parent = Path(*(slugify(part) for part in page["path"][:-1])) if page["depth"] else Path() (out_dir / parent).mkdir(parents=True, exist_ok=True) stem = f"{slugify(page['title'])}_{page['id']}" if args.output_format in ("text", "both"): try: full_page = api.get_page(page["id"]) relative = (parent / f"{stem}.md").as_posix() (out_dir / relative).write_text(page_to_markdown(full_page, args.base), encoding="utf-8") files.append({"path": relative, "title": page["title"], "id": page["id"], "format": "markdown"}) exported_ids.add(str(page["id"])) print(f"[{index}/{len(pages)}] text: {relative}") except (ConfluenceError, OSError) as exc: failures.append(f"{page['title']} [id={page['id']}] text: {exc}") print(f"Text export failed for {page['title']}: {exc}", file=sys.stderr) if args.output_format in ("pdf", "both"): try: pdf = api.export_pdf(page["id"], args.pdf_export_path, args.retries, args.page_id_param) relative = (parent / f"{stem}.pdf").as_posix() (out_dir / relative).write_bytes(pdf) files.append({"path": relative, "title": page["title"], "id": page["id"], "format": "pdf"}) exported_ids.add(str(page["id"])) print(f"[{index}/{len(pages)}] pdf: {relative}") except (ConfluenceError, OSError) as exc: failures.append(f"{page['title']} [id={page['id']}] PDF: {exc}") print(f"PDF export failed for {page['title']}: {exc}", file=sys.stderr) if args.delay and index < len(pages): time.sleep(args.delay) report = {"created_at": time.strftime("%Y-%m-%d %H:%M:%S"), "root_page_id": str(root.get("id")), "root_title": str(root.get("title")), "pages_found": len(pages), "pages_exported": len(exported_ids), "failed": failures, "files": files} manifest_path = out_dir / "manifest.json" manifest_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") if not args.no_zip: zip_path = Path(args.out.rstrip("/\\") + ".zip") with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive: archive.write(manifest_path, (Path(out_dir.name) / "manifest.json").as_posix()) for item in files: archive.write(out_dir / item["path"], (Path(out_dir.name) / item["path"]).as_posix()) print(f"ZIP: {zip_path}") print(f"Export complete: {len(exported_ids)} of {len(pages)} pages saved; {len(failures)} errors") return 0 if exported_ids and not failures else 1 except ConfluenceError as exc: print(f"Error: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())