"""Response and statistics export via the RemoteControl API. LS7 RemoteControl methods called here (lay these next to the API docs): - ``export_responses`` — params ``[session_key, sid, doc_type, language, completion_status, field_map, header]``; the result is **base64-encoded** - ``export_statistics`` — params ``[session_key, sid, doc_type, language]``; also **base64-encoded** Both functions decode the base64 and return ``bytes``; with ``output_path`` the file is written and the ``Path`` is returned (if ``output_path`` is an existing directory, a default name ``survey__responses.`` is used). """ from __future__ import annotations import base64 import binascii from pathlib import Path from typing import Any from .errors import LsApiError from .rpc import RpcClient from .utils import normalize_sid, parse_responses_json, raise_for_status def _decode_base64(result: Any, method: str) -> bytes: """Decode the base64 result of an export RPC; raise LsApiError on empty/invalid data.""" if not isinstance(result, str) or not result: raise LsApiError( f"{method} did not return a base64 string: {result!r}", method=method, raw=result, ) try: return base64.b64decode(result) except (binascii.Error, ValueError) as exc: raise LsApiError( f"{method} did not return valid base64: {exc}", method=method, raw=str(result)[:200], ) from exc def _ext(doc_type: str) -> str: return doc_type if doc_type.isalnum() else "bin" def _write_output(data: bytes, output_path: str | Path, default_name: str) -> Path: path = Path(output_path) if path.is_dir(): path = path / default_name path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) return path def export_responses( client: RpcClient, session_key: str, sid: int | str, doc_type: str = "json", *, language: str | None = None, completion_status: str = "all", field_map: str = "code", header: str = "short", output_path: str | Path | None = None, ) -> bytes | Path: """Export the responses of a survey. LS7 RPC method: ``export_responses`` with params ``[session_key, sid, doc_type, language, completion_status, field_map, header]``. Args: client: an ``RpcClient``. session_key: a valid session key. sid: survey ID. doc_type: ``"json"``, ``"csv"``, ``"xls"``/``"xlsx"``, ``"spss"``, ... language: language code or None (default language). completion_status: ``"all"``, ``"complete"`` or ``"incomplete"``. field_map: ``"code"`` or ``"title"`` (question coding in the export). header: ``"short"`` or ``"full"``. output_path: optional file path (or directory) to save the export to. Returns: The decoded export as ``bytes``; with ``output_path``, the ``Path`` of the file. """ params: list[Any] = [ session_key, normalize_sid(sid), doc_type, language, completion_status, field_map, header, ] result = client.call("export_responses", params) raise_for_status(result, "export_responses") data = _decode_base64(result, "export_responses") if output_path is not None: return _write_output(data, output_path, f"survey_{sid}_responses.{_ext(doc_type)}") return data def export_responses_json( client: RpcClient, session_key: str, sid: int | str, **kwargs: Any, ) -> list[dict[str, Any]]: """Convenience wrapper: ``export_responses(doc_type="json")`` as ``list[dict]``. Accepts the same kwargs as ``export_responses`` (except ``doc_type``). """ kwargs.pop("doc_type", None) data = export_responses(client, session_key, sid, "json", **kwargs) if isinstance(data, Path): data = data.read_bytes() return parse_responses_json(data.decode("utf-8")) def export_statistics( client: RpcClient, session_key: str, sid: int | str, doc_type: str = "json", *, language: str | None = None, output_path: str | Path | None = None, ) -> bytes | Path: """Export the statistics of a survey. LS7 RPC method: ``export_statistics`` with params ``[session_key, sid, doc_type, language]``. Args: client: an ``RpcClient``. session_key: a valid session key. sid: survey ID. doc_type: ``"json"`` or ``"csv"``. language: language code or None. output_path: optional file path (or directory) to save the export to. Returns: The decoded export as ``bytes``; with ``output_path``, the ``Path`` of the file. """ params: list[Any] = [session_key, normalize_sid(sid), doc_type, language] result = client.call("export_statistics", params) raise_for_status(result, "export_statistics") data = _decode_base64(result, "export_statistics") if output_path is not None: return _write_output(data, output_path, f"survey_{sid}_statistics.{_ext(doc_type)}") return data