{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# Share links\n",
    "Upload a file, share it with a public link, read the link anonymously, revoke it. Each cell prints the request line (`→`) and the backend's JSON reply, tokens masked."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfg-md",
   "metadata": {},
   "source": [
    "## Config\n",
    "Add your settings to the repo `.env` (local) or Colab **Secrets** — this cell reads them with `get(...)`:\n",
    "`INDOX_API_KEY` (your `ak_…` key) and `INDOX_BASE_URL` (`https://indox.org`; the SDK adds `/api/v1/…` itself). A missing key stops here with its name.\n",
    "This notebook also signs in: add `INDOX_EMAIL` and `INDOX_PASSWORD` the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cfg",
   "metadata": {},
   "outputs": [],
   "source": "import json, logging, re, sys, tempfile\nfrom pathlib import Path\n\nREPO = Path.cwd().parents[1]\nsys.path[:0] = [str(REPO), str(REPO / \"languages\" / \"python\")]\ntry:\n    from google.colab import userdata\n    get = userdata.get\nexcept ImportError:\n    from tools.env import require_env as get\n\nfrom indox_client import Indox\n\nlogging.basicConfig(format=\"→ %(message)s\", force=True)\nlogging.getLogger(\"urllib3.connectionpool\").setLevel(logging.DEBUG)\n\n\ndef _mask(record):\n    record.msg = re.sub(r\"/(public|sign)/[^/ ]+\", r\"/\\1/***\", record.getMessage())\n    record.args = ()\n    return True\n\n\nlogging.getLogger(\"urllib3.connectionpool\").addFilter(_mask)\n\n\ndef show(data, limit=2500):\n    print(json.dumps(data, indent=2, default=str)[:limit])\n\n\nclient = Indox(api_key=get(\"INDOX_API_KEY\"), base_url=get(\"INDOX_BASE_URL\"))\nstart_credits = client.billing.credits_balance()[\"credit_amount\"]\nSAMPLES = REPO / \"colab\"\nout = Path(tempfile.mkdtemp())\n\nfrom indox_client import NotFoundError\n\ndef masked(data):\n    return {k: \"***\" if k.endswith((\"token\", \"url\")) else v for k, v in data.items()}\n\npng = SAMPLES / \"image\" / \"samples\" / \"sample.png\""
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "upload",
   "metadata": {},
   "outputs": [],
   "source": [
    "stored = client.user.upload_file(png)\n",
    "assert stored[\"file_size_bytes\"] == png.stat().st_size\n",
    "show(stored)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "login",
   "metadata": {},
   "outputs": [],
   "source": [
    "# a separate client keeps the sign-in cookies apart from the API-key calls below\n",
    "account = Indox(api_key=get(\"INDOX_API_KEY\"), base_url=get(\"INDOX_BASE_URL\"))\n",
    "session = account.user.login(email=get(\"INDOX_EMAIL\"), password=get(\"INDOX_PASSWORD\"))\n",
    "token = session[\"external_token\"]\n",
    "assert session[\"token_type\"] == \"Bearer\" and token\n",
    "show(masked(session))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "create",
   "metadata": {},
   "outputs": [],
   "source": [
    "link = account.user.create_share(\n",
    "    {\"user_file_id\": stored[\"id\"], \"expires_in_days\": 1, \"max_downloads\": 3}, access_token=token\n",
    ")\n",
    "assert link[\"user_file_id\"] == stored[\"id\"] and not link[\"is_revoked\"]\n",
    "show(masked(link))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "list",
   "metadata": {},
   "outputs": [],
   "source": [
    "links = client.user.list_shares(page_size=5)\n",
    "assert link[\"id\"] in {s[\"id\"] for s in links[\"results\"]}\n",
    "show({**links, \"results\": [masked(s) for s in links[\"results\"]]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "public",
   "metadata": {},
   "outputs": [],
   "source": [
    "public = client.user.public_share(link[\"token\"])\n",
    "assert public[\"file_name\"] == stored[\"file_name\"]\n",
    "show(public)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "revoke",
   "metadata": {},
   "outputs": [],
   "source": [
    "show(account.user.delete_share(link[\"id\"], access_token=token))\n",
    "try:\n",
    "    client.user.public_share(link[\"token\"])\n",
    "except NotFoundError as exc:\n",
    "    show(exc.response)\n",
    "else:\n",
    "    raise AssertionError(\"revoked link still resolves\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "usage-md",
   "metadata": {},
   "source": [
    "## Usage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "usage",
   "metadata": {},
   "outputs": [],
   "source": [
    "now = client.billing.credits_balance()[\"credit_amount\"]\n",
    "print(f\"credits used by this notebook: {start_credits - now}  (balance {now})\")\n",
    "show(client.billing.usage_by_feature())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cleanup",
   "metadata": {},
   "outputs": [],
   "source": [
    "removed = client.user.delete_files({\"file_ids\": [stored[\"id\"]]})\n",
    "assert removed[\"message\"]\n",
    "show([removed, account.user.logout()])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
