# Databek Lens API guide

Lens (lens.databek.com) analyses camera video with AI: child safety in kindergartens and schools (incidents with
clips, alerts to parents) and lesson analytics in universities (lesson scores and teacher dashboards). Its
integration API lets another system connect cameras or send video files, start analyses and read incidents, clips
and teacher dashboards with one API key, and receive webhooks.

This guide is written so that a developer, or an AI agent given this file, can integrate with Lens without other
help. Follow the flows in order; every request and answer below has the real shape (taken from a run against a local
Lens); ids, keys, names and times are illustrative. The full reference is [openapi.json](openapi.json) (OpenAPI 3.1, same folder).

## 1. What Lens does

Lens (lens.databek.com) connects an organisation's cameras, records the hours it works and analyses those hours with
AI:

- **`safety_daily`** (kindergartens, schools): once a day per room, finds harm to children (shouting at a child,
  hitting, pushing, a child left alone …) as **incidents** with severity 1–5, quotes and short **clips**.
- **`lesson`** (universities, schools): scores a lesson (topic coverage, talk shares, questions, engagement, rubric,
  overall 0–100) and builds **teacher dashboards** from many lessons.

You can feed Lens in two ways, and mix them:

| Mode | You send | Lens does |
|---|---|---|
| Cameras | camera addresses + working hours | records 10-minute segments while open; analyses on request or by itself ("continuous") |
| Integration | video files (upload) or video URLs | analyses each file on request |

AI cost is per hour of video and billed to the organisation; Lens never analyses the same minutes twice unless you
force it (section 11).

## 2. Basics

| | |
|---|---|
| Base URL | `https://lens.databek.com/api/v1` |
| Auth | `Authorization: Bearer lens_…` — an org API key from **Sozlamalar → API kalitlar** (an org owner or admin makes it; it is shown once) |
| Scopes | `read`: every GET. `write`: everything else (a write key can read too) |
| Body | JSON (`Content-Type: application/json`), at most 1 MB; media uploads are raw bytes (section 6) |
| Times | ISO 8601 with offset in, UTC `…Z` out |
| Ids | UUIDs |
| Errors | HTTP status + `{"code", "message", "field"?}` (section 10) |
| Lists | `?limit=1..200` (default 50) and `?cursor=`; answer `{"items": [...], "next_cursor": "…" or null}`, newest first (lesson slots: a stable order by id) |
| Idempotency | `Idempotency-Key: <your id>` on any JSON POST except `POST /media`: a retry with the same key and body within 24 hours replays the first answer |
| Unknown fields | ignored, not refused: check the spelling of optional fields |
| Request id | every API answer has `X-Request-ID` (a signed clip download does not); send your own (`[A-Za-z0-9._:-]{1,128}`) to correlate logs |
| Limits | 600 requests a minute per key, 120 uploads an hour per organisation → `429` with `Retry-After` |

Set two shell variables for the examples:

```bash
export LENS=https://lens.databek.com/api/v1
export LENS_KEY=lens_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

Check the key first:

```bash
curl -s $LENS/me -H "Authorization: Bearer $LENS_KEY"
```

```json
{
  "organization": { "id": "5b0f…", "name": "Quyosh bog'chasi", "kind": "kindergarten", "timezone": "Asia/Tashkent" },
  "key": { "id": "c41e…", "name": "ERP", "prefix": "lens_Jd3kQ0p", "scopes": ["read", "write"] }
}
```

## 3. Objects

| Object | What it is | Endpoints |
|---|---|---|
| Portfolio | a named set of cameras with one timezone, analysis profiles, default AI tier and **rooms** | `/portfolios` |
| Room | a label on cameras of one space; cameras of a room are analysed together | inside a portfolio (`rooms`) |
| Schedule | weekly working hours + date exceptions of a portfolio (recording happens only while open) | `/portfolios/{id}/schedule` |
| Lesson slot | weekday + time + room (+ teacher, topic): splits long recordings into lessons | `/lesson-slots` |
| Camera | a source (`url`, `url_auth`, `preset`, `push`); secrets are write-only | `/cameras` |
| Media | a video you uploaded or gave by URL | `/media` |
| Analysis | one AI job over one scope (room / cameras / media) and one interval | `/analyses` |
| Incident | a safety finding of a `safety_daily` analysis, with clips | `/incidents` |
| Clip | an MP4 of an incident (±15 s) per camera, behind a signed link | `/clips/{id}` |
| Teacher | a teacher name (matched case- and apostrophe-insensitively) | `/teachers` |
| Dashboard | a teacher's cards (average score, trends, …) as data | `/teachers/{id}/dashboard` |
| Webhook | your URL that gets signed events | `/webhooks` |

AI tiers: `economy` (Tejamkor), `standard` (Standart, default), `deep` (Chuqur). You never see model names.

## 4. Flow: connect cameras and a schedule

**1. Create a portfolio with its rooms.**

```bash
curl -s -X POST $LENS/portfolios -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Bog'"'"'cha 7", "rooms": ["Quyosh", "Oy"], "profiles": ["safety_daily"], "default_tier": "standard"}'
```

`201`:

```json
{
  "id": "0d6c2a1e-…",
  "name": "Bog'cha 7",
  "timezone": "Asia/Tashkent",
  "profiles": ["safety_daily"],
  "default_tier": "standard",
  "continuous": false,
  "lesson_sampling": "manual",
  "lesson_sampling_n": null,
  "parents_enabled": true,
  "rooms": [ { "id": "8f1d…", "name": "Oy" }, { "id": "a2c9…", "name": "Quyosh" } ],
  "created_at": "2026-12-01T15:40:12.481Z"
}
```

Keep `id` (portfolio) and the room ids. A later `PATCH /portfolios/{id}` with `rooms` sends the **full** list: a name
left out deletes that room.

**2. Add cameras.** Four connection kinds:

| `connection` | Body fields | Use |
|---|---|---|
| `url` | `url` (rtsp://, rtmp://, http(s):// HLS or MJPEG) | public stream without a login |
| `url_auth` | `url`, `username`, `password` | private stream |
| `preset` | `preset: {brand, host, port, channel, stream, path}`, `username`, `password` | Hikvision, Dahua, Uniview or `generic` RTSP; `stream: "sub"` (default) is lighter |
| `push` | nothing | camera / NVR behind NAT publishes to Lens (RTMP or SRT) with a per-camera key |

```bash
curl -s -X POST $LENS/cameras -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" -d '{
  "name": "Quyosh — kirish", "portfolio_id": "0d6c2a1e-…", "room_id": "a2c9…",
  "connection": "preset", "username": "viewer", "password": "secret",
  "preset": {"brand": "hikvision", "host": "cam7.example.uz", "port": 554, "channel": 1, "stream": "sub"},
  "record": true, "live_for_parents": false, "record_fps": 5 }'
```

`201` (the URL, login and password never come back; `push` is null for non-push cameras):

```json
{
  "id": "e3b7…", "name": "Quyosh — kirish", "portfolio_id": "0d6c2a1e-…", "room_id": "a2c9…",
  "connection": "preset", "source_host": "cam7.example.uz",
  "preset": { "brand": "hikvision", "host": "cam7.example.uz", "port": 554, "channel": 1, "stream": "sub", "path": "" },
  "record": true, "live_for_parents": false, "record_fps": 5,
  "status": null, "status_at": null, "probe": null, "probed_at": null, "last_frame_at": null,
  "created_at": "2026-12-01T15:41:03.107Z", "push": null
}
```

A **push** camera answers with its publish addresses once; save them in the camera or NVR (a new key:
`POST /cameras/{id}/push-key`):

```json
{ "connection": "push", "push": { "rtmp": "rtmp://lens.databek.com/live/Xk3q…?key=…", "srt": "srt://lens.databek.com:8890?streamid=publish:live/Xk3q…:lens:…" } }
```

A source host that resolves to a private, loopback, link-local, CGNAT, multicast or Docker address is refused with
`422 camera_host_blocked` (unless Databek allowed private sources for your organisation, e.g. over a VPN; loopback,
link-local and Docker addresses stay refused even then).

**3. Check the camera** (ffprobe, up to ~15 s):

```bash
curl -s -X POST $LENS/cameras/e3b7…/probe -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "probe": { "ok": true, "video": { "codec": "h264", "width": 640, "height": 360, "fps": 25 }, "audio": true, "at": "…" },
  "camera": { "id": "e3b7…", "status": "ok", "…": "…" } }
```

`status` values: `ok`, `offline` (no frames for 5 minutes while recording), `auth_failed`, `unreachable`, `blocked`.

**4. Set the working hours.** Lens records only while the portfolio is open (±5 minutes). Weekdays are 1 = Monday …
7 = Sunday; several ranges a day are allowed, ranges of a day must not overlap. `exceptions` (optional) replaces all
date exceptions: `closed` days, or `open` days with their own hours.

```bash
curl -s -X PUT $LENS/portfolios/0d6c2a1e-…/schedule -H "Authorization: Bearer $LENS_KEY" \
  -H "Content-Type: application/json" -d '{
  "weekly": [
    {"weekday": 1, "ranges": [{"start": "08:00", "end": "18:00"}]},
    {"weekday": 2, "ranges": [{"start": "08:00", "end": "18:00"}]},
    {"weekday": 3, "ranges": [{"start": "08:00", "end": "18:00"}]},
    {"weekday": 4, "ranges": [{"start": "08:00", "end": "18:00"}]},
    {"weekday": 5, "ranges": [{"start": "08:00", "end": "13:00"}, {"start": "14:00", "end": "18:00"}]}
  ],
  "exceptions": [{"date": "2026-12-31", "kind": "closed", "note": "Yangi yil"}] }'
```

`200` returns the stored schedule in the same shape (`{portfolio_id, timezone, weekly, exceptions}`).

**5. (Lessons only) add lesson slots,** so long recordings are split into lessons with their teacher and topic:

```bash
curl -s -X POST $LENS/lesson-slots -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"portfolio_id": "0d6c2a1e-…", "room_id": "a2c9…", "weekday": 3, "start": "09:00", "end": "09:45",
       "teacher_name": "Karimova N.", "topic": "Kasrlar"}'
```

```json
{ "id": "71aa…", "portfolio_id": "0d6c2a1e-…", "room_id": "a2c9…", "weekday": 3, "start": "09:00", "end": "09:45",
  "teacher_id": "5c02…", "teacher_name": "Karimova N.", "topic": "Kasrlar", "valid_from": null, "valid_to": null }
```

Recording then runs by itself. To analyse a recorded interval, see section 7 (`room_id` + `starts_at` + `ends_at`).

## 5. Flow: continuous mode

Turn it on per portfolio and Lens analyses by itself:

```bash
curl -s -X PATCH $LENS/portfolios/0d6c2a1e-… -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"continuous": true, "profiles": ["safety_daily", "lesson"], "lesson_sampling": "per_week", "lesson_sampling_n": 2}'
```

- `safety_daily`: every room, once a day, 30 minutes after the portfolio closes (results by morning; it may use the
  provider's batch API at half price).
- `lesson`: by `lesson_sampling` — `all` lesson slots, `every_nth` (n), `per_week` (n random lessons per teacher each
  week, per room for slots without a teacher; repeatable), or `manual` (none by itself).

You learn about results from webhooks (section 9: `analysis.completed`, `incident.created`) or by listing:
`GET /analyses?status=done&from=2026-12-01T00:00:00Z`.

## 6. Flow: integration mode (send video files)

**1a. Upload a file** as the raw body with its Content-Type (`video/mp4`, `video/quicktime`, `video/webm`,
`video/x-matroska`, `video/mp2t`, `video/x-msvideo`, `audio/mpeg`, `audio/mp4`, `audio/wav`, or
`application/octet-stream`). Up to 2 GiB unless agreed otherwise. `name` is optional.

```bash
curl -s -X POST "$LENS/media?name=group-a-2026-12-01" -H "Authorization: Bearer $LENS_KEY" \
  -H "Content-Type: video/mp4" --data-binary @group-a.mp4
```

`202`:

```json
{ "id": "9a41…", "name": "group-a-2026-12-01", "source": "upload", "status": "pending", "content_type": "video/mp4",
  "size_bytes": 48211337, "duration_ms": null, "sha256": "3f1c…", "error_code": null,
  "expires_at": "2026-12-15T15:44:20.000Z", "created_at": "2026-12-01T15:44:20.000Z" }
```

**1b. Or give a URL** that Lens downloads (it may carry a token: it is stored encrypted and never returned; it must
resolve to a public address, redirects are checked the same way):

```bash
curl -s -X POST $LENS/media -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"source_url": "https://files.example.uz/rec/group-a.mp4?token=…", "name": "group-a"}'
```

`202` with `"source": "url", "status": "fetching"`.

**2. Wait until `ready`.** Poll every few seconds (a file is probed in seconds; a URL takes its download time):

```bash
curl -s $LENS/media/9a41… -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "id": "9a41…", "status": "ready", "duration_ms": 3600040, "…": "…" }
```

`failed` comes with `error_code`: `media_unreadable` (no audio or video stream, or a container Lens does not open;
it opens MP4/MOV, Matroska/WebM, MPEG-TS, MPEG-PS, AVI, FLV, ASF/WMV, Dahua DAV, raw H.264/H.265, MP3, WAV, AAC, Ogg
and FLAC), `media_too_large`, `media_quota_reached`, `storage_full`, `media_fetch_failed`, `media_host_blocked`,
`media_host_unresolved`, `media_url_invalid`. A download that keeps failing on the network is retried 5 times (about 8 minutes plus the
download time), then it is `failed` with `media_fetch_failed`. Poll with a timeout of your own (for example the
expected download time plus 30 minutes); on timeout, `DELETE /media/{id}` and send it again. Media is kept as long as camera recordings (14 days by default), then deleted. One organisation
holds at most 200 GiB of media and 100 cameras.

**3. Request the analysis** with `media_ids`. `starts_at` is when the video starts on the wall clock (times in the
result are counted from it); leave it out and Lens places the video so it ends at its upload time. Several media of
one analysis are one scope (e.g. two angles of the same room at the same time).

```bash
curl -s -X POST $LENS/analyses -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: erp-job-88121" \
  -d '{"kind": "safety_daily", "media_ids": ["9a41…"], "starts_at": "2026-12-01T08:00:00+05:00", "tier": "standard"}'
```

`202`:

```json
{ "id": "f0c3…", "kind": "safety_daily", "status": "queued", "tier": "standard", "portfolio_id": null, "room_id": null,
  "camera_ids": [], "media_ids": ["9a41…"], "starts_at": "2026-12-01T03:00:00.000Z", "ends_at": "2026-12-01T04:00:01.000Z",
  "topic": "", "teacher_id": null, "language": "uz", "parent_analysis_id": null, "forced": false, "superseded_by": null,
  "requested_via": "api", "cost_uzs": 0, "error_code": null, "created_at": "…", "started_at": null, "finished_at": null,
  "result": null }
```

`status` goes `queued` → `running` → `done` (or `failed` with `error_code`). `waiting_ai` means the tier's AI
provider is not switched on yet; it starts by itself later. A lesson from a file:

```bash
curl -s -X POST $LENS/analyses -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"kind": "lesson", "media_ids": ["77d0…"], "teacher_name": "Karimova N.", "topic": "Kasrlar", "language": "uz"}'
```

## 7. Flow: get results

**Analysis.** Poll `GET /analyses/{id}` (every 10–30 s) or wait for the `analysis.completed` webhook:

```bash
curl -s $LENS/analyses/f0c3… -H "Authorization: Bearer $LENS_KEY"
```

A `safety_daily` result:

```json
{ "id": "f0c3…", "kind": "safety_daily", "status": "done", "cost_uzs": 32.2, "…": "…",
  "result": { "schema": "safety_daily.v1", "summary": "Kun tinch o'tdi, bir marta baqirish eshitildi.",
              "incidents": 2, "max_severity": 3, "clips": 0, "cameras": 1,
              "baseline": { "loudness": -31.4, "motion": 0.012 }, "windows": 3, "listen_events": 1,
              "look_observations": 2, "audio_seconds": 3600, "sent_audio_seconds": 2410 } }
```

A `lesson` result (`schema: "lesson.v1"`): `topic {given, detected, coverage_pct}`, `timeline[]`, `talk {teacher_pct,
student_pct, silence_pct}`, `teacher_questions {open, closed, total}`, `student_questions`, `interactions`,
`engagement {score, evidence[]}`, `pace`, `clarity`, `board_use`, `punctuality`, `language {shouting, insults,
swear_words}` (quotes with `t_s`), `key_moments[]`, `strengths[3]`, `improvements[3]`, `rubric {structure, clarity,
engagement, interaction, pace, language}` (1–5) and `overall` (0–100). A long block split into several lessons answers
`schema: "lesson_block.v1"` with `lessons[{analysis_id, starts_at, ends_at, teacher_id, overall}]`; each lesson is its
own analysis (`GET /analyses?parent_analysis_id=f0c3…`).

**Incidents** of an analysis (or of a room, a period, a minimum severity):

```bash
curl -s "$LENS/incidents?analysis_id=f0c3…" -H "Authorization: Bearer $LENS_KEY"
curl -s "$LENS/incidents?room_id=a2c9…&from=2026-12-01T00:00:00Z&min_severity=3" -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "items": [ {
    "id": "c9e2…", "analysis_id": "f0c3…", "portfolio_id": "0d6c2a1e-…", "room_id": "a2c9…",
    "type": "shouting", "severity": 3, "confidence": 0.8,
    "starts_at": "2026-12-01T05:12:40.000Z", "ends_at": "2026-12-01T05:12:52.000Z", "camera_ids": ["e3b7…"],
    "description": "Tarbiyachi bolaga baland ovozda baqirdi.", "quotes": ["…"],
    "status": "new", "released_at": null, "dismissed_at": null, "dismiss_reason": null, "created_at": "…",
    "clips": [ { "id": "1b7d…", "incident_id": "c9e2…", "camera_id": "e3b7…", "starts_at": "…", "ends_at": "…",
                 "size_bytes": 1840221, "status": "ready", "expires_at": "2027-12-01T…" } ] } ],
  "next_cursor": null }
```

Types: `shouting`, `crying`, `insult`, `swearing`, `threat`, `hitting_sound`, `begging`, `hitting`, `pushing`,
`restraint`, `locking`, `forced_feeding`, `isolation`, `left_alone`, `child_harm_ignored`, `inappropriate_touching`,
`rough_handling`, `other`. `status`: `new` → `released` (shown to parents) or `dismissed` (by the org, with a reason).
Clips are cut from camera recordings (severity ≥ the org's threshold, 3 by default); media analyses have no clips.

**Clips.** Ask for a signed link (valid 10 minutes, no API key needed, Range requests work, so a `<video>` tag can
play it):

```bash
curl -s $LENS/clips/1b7d… -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "id": "1b7d…", "status": "ready", "…": "…",
  "url": "https://lens.databek.com/api/v1/clips/1b7d…/file?org=5b0f…&exp=1764604800&sig=Qm9…",
  "url_expires_at": "2026-12-01T16:00:00.000Z" }
```

```bash
curl -s -o clip.mp4 "<url>"                        # whole file
curl -s -H "Range: bytes=0-1048575" -o part "<url>"  # 206 Partial Content
```

An expired or altered link answers `403`. Every link you ask for is written to the organisation's audit log.

## 8. Flow: teacher dashboards

Every analysed lesson with a teacher (from `teacher_name`, `teacher_id` or a lesson slot) feeds that teacher's
dashboard. Cards are computed from stored results on each call (no AI, no cost).

```bash
curl -s $LENS/teachers -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "items": [ { "id": "5c02…", "name": "Karimova N.", "created_at": "…", "lessons": 12 } ], "next_cursor": null }
```

```bash
curl -s $LENS/teachers/5c02…/dashboard -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "teacher_id": "5c02…", "cards": [
  { "id": "overall", "title": { "uz": "Umumiy ball", "ru": "Общий балл", "en": "Overall score" },
    "chart": "number", "unit": "score", "lessons": 12, "value": 74 },
  { "id": "overallTrend", "title": { "…": "…" }, "chart": "line", "unit": "score", "lessons": 12, "value": 5,
    "series": [ { "week": "2026-W47", "value": 71 }, { "week": "2026-W48", "value": 76 } ] },
  { "id": "pace", "title": { "…": "…" }, "chart": "bar", "unit": "text", "lessons": 12, "value": null,
    "buckets": [ { "key": "fast", "count": 3 }, { "key": "good", "count": 9 } ] },
  { "id": "improvements", "title": { "…": "…" }, "chart": "list", "unit": "text", "lessons": 12, "value": null,
    "items": [ "…", "…", "…" ] } ] }
```

The organisation chooses which cards and their order in its settings. `value` is the number of a `number` card; for a
`line` card it is the change of the last week against the week before (null with fewer than 2 weeks), with the weekly
averages in `series` (ISO weeks in the organisation's time zone); `bar` and `list` cards have `value` null and carry
`buckets` (sorted by key) or `items`. Units: `score` (0–100), `pct`, `count`, `min`, `rating` (1–5), `text`.

## 9. Webhooks

**1. Create one** (your endpoint must be `https://` and resolve to a public address). The `secret` is shown only in
this answer: store it.

```bash
curl -s -X POST $LENS/webhooks -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"url": "https://erp.example.uz/hooks/lens", "events": ["analysis.completed", "analysis.failed", "incident.created", "camera.offline"]}'
```

```json
{ "id": "3e90…", "url": "https://erp.example.uz/hooks/lens",
  "events": ["analysis.completed", "analysis.failed", "incident.created", "camera.offline"], "active": true,
  "created_at": "…", "secret": "whsec_Hq2…" }
```

**2. What arrives.** A `POST` with a JSON envelope and three headers:

```
Content-Type: application/json
Lens-Event: incident.created
Lens-Delivery: 6d1f…            (the envelope id: deduplicate on it)
Lens-Signature: t=1764604210,v1=8c5e0f…
```

```json
{ "id": "6d1f…", "event": "incident.created", "created_at": "2026-12-01T15:50:10.512Z", "org_id": "5b0f…",
  "data": { "incident": { "id": "c9e2…", "type": "shouting", "severity": 3, "…": "…", "clips": [] } } }
```

| Event | `data` |
|---|---|
| `analysis.completed` | `analysis` (the analysis object without `result`: GET it) |
| `analysis.failed` | `analysis` with `error_code` |
| `incident.created` | `incident` with its `clips` (every incident, at once; parents only see released ones; a forced re-run does not send one again for an incident parents already got) |
| `camera.offline` | `camera {id, name, status, last_frame_at}` |
| `ping` | `webhook_id` (sent by `POST /webhooks/{id}/test`) |

**3. Check the signature** before trusting the body: HMAC-SHA256 of `"<t>.<raw body>"` with your secret, hex, compared
in constant time, and `t` not older than 5 minutes. Use the **raw** body bytes, before any JSON parsing.

Node.js (no packages):

```js
import { createHmac, timingSafeEqual } from "node:crypto";

export function lensSignatureOk(secret, rawBody, header, toleranceS = 300) {
  const parts = Object.fromEntries(String(header).split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceS || !parts.v1) return false;
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  const given = Buffer.from(parts.v1, "hex");
  return given.length === expected.length && timingSafeEqual(given, expected);
}
```

Python 3 (standard library):

```python
import hashlib, hmac, time

def lens_signature_ok(secret: str, raw_body: bytes, header: str, tolerance_s: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > tolerance_s or "v1" not in parts:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])
```

**4. Answer fast with any 2xx** (do the work after answering). No answer in 10 s, a non-2xx status or a redirect counts
as a failure and is retried: after 30 s, then doubling up to 1 hour, 10 attempts in all (about 3 hours), then the
delivery is `failed`. A host that does not resolve is retried the same way; one that resolves to a private address
fails at once. Deliveries may arrive more than once and out of order: deduplicate on `Lens-Delivery` and
re-read the object (`GET /analyses/{id}`) when the order matters.

**5. Test and inspect.**

```bash
curl -s -X POST $LENS/webhooks/3e90…/test -H "Authorization: Bearer $LENS_KEY"          # 202 {"delivery_id": "…"}
curl -s "$LENS/webhooks/3e90…/deliveries?limit=20" -H "Authorization: Bearer $LENS_KEY"
```

```json
{ "items": [ { "id": "6d1f…", "webhook_id": "3e90…", "event": "ping", "status": "delivered", "attempts": 1,
  "response_status": 200, "response_ms": 41, "error": null, "next_attempt_at": null,
  "delivered_at": "…", "created_at": "…", "payload": { "…": "…" } } ], "next_cursor": null }
```

`PATCH /webhooks/{id}` with `{"active": false}` pauses it; `DELETE` removes it with its log. The same list is on the
**Sozlamalar → Webhooklar** page.

## 10. Errors and retries

Every error has the same shape:

```json
{ "code": "validation_failed", "message": "Too small: expected string to have >=1 characters", "field": "name" }
```

| Status | `code` | Meaning, what to do |
|---|---|---|
| 400 | `invalid_json` | the body is not JSON; fix it |
| 401 | `unauthorized` | missing, unknown or revoked key |
| 402 | `budget_exceeded` | the organisation's monthly AI budget is used up; ask the org admin |
| 403 | `insufficient_scope` | a `read` key tried to change something |
| 403 | `force_not_allowed` | force is not enabled for the organisation (section 11) |
| 404 | `not_found` | no such object in **your** organisation (a deleted camera too) |
| 409 | `analysis_exists` | the scope was already analysed; read `existing_id` (section 11) |
| 413 | `body_too_large`, `media_too_large`, `media_quota_reached`, `request.too_large` | JSON over 1 MB, file over the cap, the organisation's media storage is full; `request.too_large` comes from the edge proxy (a body over 2 MiB, or over 2 GiB on `/media`) |
| 415 | `unsupported_media_type` | wrong Content-Type |
| 422 | `validation_failed` | `field` names the input (JSON path such as `weekly.0.ranges`) |
| 422 | `camera_host_blocked`, `camera_host_unresolved`, `camera_url_invalid`, `camera_url_required`, `camera_preset_required`, `camera_path_required`, `camera_limit_reached`, `camera_not_push`, `portfolio_not_found`, `room_not_found` | camera input (`camera_not_push`: a push key for a camera that does not push) |
| 422 | `clock_invalid`, `ranges_overlap`, `ranges_required`, `room_duplicate` | schedule and rooms |
| 422 | `media_host_blocked`, `media_host_unresolved`, `media_not_ready`, `media_empty` | media |
| 422 | `invalid_scope`, `invalid_interval`, `force_reason_required`, `force_on_parent` | analyses |
| 422 | `idempotency_mismatch` | the `Idempotency-Key` was used with another request (any POST) |
| 422 | `webhook_url_invalid`, `webhook_host_blocked`, `webhook_host_unresolved` | webhooks |
| 429 | `rate_limited` | wait `Retry-After` seconds |
| 500 | `internal_error` | retry later with backoff; quote `X-Request-ID` to Databek |
| 503 | `storage_full` | the server is short of disk space for media; retry later |

A failed analysis is not an error answer: it is `status: "failed"` with `error_code` (also in the `analysis.failed`
webhook): `budget_exceeded`, `no_media` (no recording in the interval), `media_failed`, `ai_<code>` (the AI provider
refused or failed) or `failed`.

Retry rules: retry `429` after `Retry-After`; retry `5xx` and network errors with backoff (1 s, 2 s, 4 s … up to
1 minute); never retry `4xx` unchanged. Send an `Idempotency-Key` on every POST you may retry (it is kept per
organisation for 24 hours; reuse it only for the very same request): a replay answers the stored result with
`Idempotent-Replayed: true` and starts nothing new (answers with a secret, such as a webhook's `secret` or a camera's
`push` addresses, are stored encrypted). `POST /media` (a file or a `source_url`) does not use the key; check
`GET /media?limit=…` before sending the same file again.

## 11. Duplicates (409) and force

Lens never pays twice for the same minutes. A request of the same `kind` that shares a camera (or a media file) with
a live analysis (any status but `failed` and `superseded`) and overlaps its interval is refused:

```json
{ "code": "analysis_exists", "message": "This scope and interval already has a live analysis",
  "existing_id": "f0c3…" }
```

Do this: `GET /analyses/{existing_id}` and use its result (wait for it if it is still `queued` or `running`). A failed
analysis does not block: request it again.

To re-run anyway (a new prompt, a better tier) **force** it with a reason. Force is allowed only when Databek
enabled it for your organisation (trials); otherwise `403 force_not_allowed`.

```bash
curl -s -X POST $LENS/analyses/f0c3…/force -H "Authorization: Bearer $LENS_KEY" -H "Content-Type: application/json" \
  -d '{"reason": "deep tier for the parents meeting"}'
```

`202` with the new analysis (`"forced": true`). The old one becomes `superseded` (its result stays readable, with
`superseded_by`), and the organisation's audit log keeps who forced it and why. Incidents of the old analysis that
were not decided yet become `dismissed` with `dismiss_reason: "system:superseded"`; released ones stay (parents were
told). A new incident that repeats a released one (same type and place, overlapping time) is `dismissed` with
`dismiss_reason: "system:repeat"`, so parents get no second alert. The same works as
`POST /analyses` with `"force": true, "reason": "…"`. A lesson of a split block is forced through its block
(`422 force_on_parent` names the block).

## 12. Checklist for an agent

1. `GET /me` with the key; stop on `401`.
2. Cameras mode: portfolio (with rooms) → cameras → probe → schedule → lesson slots (lessons) → optionally
   `continuous`.
3. Integration mode: `POST /media` → poll `GET /media/{id}` to `ready` → `POST /analyses` with `media_ids` and an
   `Idempotency-Key`.
4. On `409 analysis_exists` use `existing_id`; force only when asked to and allowed.
5. Results: webhook `analysis.completed` (or poll) → `GET /analyses/{id}` → `GET /incidents?analysis_id=` →
   `GET /clips/{id}` for a 10-minute link; lessons → `GET /teachers` → `GET /teachers/{id}/dashboard`.
6. Webhooks: verify `Lens-Signature` on the raw body, answer 2xx at once, deduplicate on `Lens-Delivery`.
7. Never log the API key, a webhook secret, camera passwords or media URLs with tokens.

<!-- endpoint-index:start (generated from openapi.json) -->

## Endpoint index

Every operation of `openapi.json` (42), grouped by tag: method and path, who may call it, query parameters, body fields (`*` = required) and the top-level fields of the answer. Schemas, types and examples are in `openapi.json`.

### Organization

- `GET /me` The key and its organization · answers 200: `organization`, `key`

### Portfolios

- `GET /portfolios` List portfolios (newest first) · query: `limit`, `cursor` · answers 200: `items`, `next_cursor`
- `POST /portfolios` Create a portfolio with its rooms · headers: `Idempotency-Key` · body (JSON): `name*`, `timezone`, `profiles`, `default_tier`, `continuous`, `lesson_sampling`, `lesson_sampling_n`, `parents_enabled`, `rooms` · answers 201: `id`, `name`, `timezone`, `profiles`, `default_tier`, `continuous`, `lesson_sampling`, `lesson_sampling_n`, `parents_enabled`, `rooms`, `created_at`
- `GET /portfolios/{id}` Get a portfolio · answers 200: `id`, `name`, `timezone`, `profiles`, `default_tier`, `continuous`, `lesson_sampling`, `lesson_sampling_n`, `parents_enabled`, `rooms`, `created_at`
- `DELETE /portfolios/{id}` Delete a portfolio with its rooms, cameras and schedule · answers 204, no body
- `PATCH /portfolios/{id}` Change a portfolio · body (JSON): `name`, `timezone`, `profiles`, `default_tier`, `continuous`, `lesson_sampling`, `lesson_sampling_n`, `parents_enabled`, `rooms` · answers 200: `id`, `name`, `timezone`, `profiles`, `default_tier`, `continuous`, `lesson_sampling`, `lesson_sampling_n`, `parents_enabled`, `rooms`, `created_at`

### Schedule

- `GET /portfolios/{id}/schedule` Get the working hours · answers 200: `portfolio_id`, `timezone`, `weekly`, `exceptions`
- `PUT /portfolios/{id}/schedule` Replace the working hours (and the date exceptions when sent) · body (JSON): `weekly*`, `exceptions` · answers 200: `portfolio_id`, `timezone`, `weekly`, `exceptions`
- `GET /lesson-slots` List lesson slots · query: `limit`, `cursor`, `portfolio_id`, `room_id` · answers 200: `items`, `next_cursor`
- `POST /lesson-slots` Create a lesson slot · headers: `Idempotency-Key` · body (JSON): `portfolio_id*`, `room_id*`, `weekday*`, `start*`, `end*`, `teacher_name`, `topic`, `valid_from`, `valid_to` · answers 201: `id`, `portfolio_id`, `room_id`, `weekday`, `start`, `end`, `teacher_id`, `teacher_name`, `topic`, `valid_from`, `valid_to`
- `GET /lesson-slots/{id}` Get a lesson slot · answers 200: `id`, `portfolio_id`, `room_id`, `weekday`, `start`, `end`, `teacher_id`, `teacher_name`, `topic`, `valid_from`, `valid_to`
- `DELETE /lesson-slots/{id}` Delete a lesson slot · answers 204, no body
- `PATCH /lesson-slots/{id}` Change a lesson slot · body (JSON): `portfolio_id`, `room_id`, `weekday`, `start`, `end`, `teacher_name`, `topic`, `valid_from`, `valid_to` · answers 200: `id`, `portfolio_id`, `room_id`, `weekday`, `start`, `end`, `teacher_id`, `teacher_name`, `topic`, `valid_from`, `valid_to`

### Cameras

- `GET /cameras` List cameras · query: `limit`, `cursor`, `portfolio_id`, `room_id`, `status` · answers 200: `items`, `next_cursor`
- `POST /cameras` Connect a camera (secrets are write-only) · headers: `Idempotency-Key` · body (JSON): `name*`, `portfolio_id*`, `room_id`, `connection*`, `url`, `username`, `password`, `preset`, `record`, `live_for_parents`, `record_fps` · answers 201: `id`, `name`, `portfolio_id`, `room_id`, `connection`, `source_host`, `preset`, `record`, `live_for_parents`, `record_fps`, `status`, `status_at`, `probe`, `probed_at` and 3 more
- `GET /cameras/{id}` Get a camera · answers 200: `id`, `name`, `portfolio_id`, `room_id`, `connection`, `source_host`, `preset`, `record`, `live_for_parents`, `record_fps`, `status`, `status_at`, `probe`, `probed_at` and 2 more
- `DELETE /cameras/{id}` Delete a camera · answers 204, no body
- `PATCH /cameras/{id}` Change a camera · body (JSON): `name`, `portfolio_id`, `room_id`, `connection`, `url`, `username`, `password`, `preset`, `record`, `live_for_parents`, `record_fps` · answers 200: `id`, `name`, `portfolio_id`, `room_id`, `connection`, `source_host`, `preset`, `record`, `live_for_parents`, `record_fps`, `status`, `status_at`, `probe`, `probed_at` and 3 more
- `POST /cameras/{id}/probe` Probe the source now (ffprobe, up to 15 s) · answers 200: `probe`, `camera`
- `POST /cameras/{id}/push-key` New push key for a push camera (the old one stops) · answers 200: `id`, `name`, `portfolio_id`, `room_id`, `connection`, `source_host`, `preset`, `record`, `live_for_parents`, `record_fps`, `status`, `status_at`, `probe`, `probed_at` and 3 more

### Media

- `GET /media` List media · query: `limit`, `cursor`, `status` · answers 200: `items`, `next_cursor`
- `POST /media` Upload a video, or give a source_url · query: `name` · body (video/*): string · answers 202: `id`, `name`, `source`, `status`, `content_type`, `size_bytes`, `duration_ms`, `sha256`, `error_code`, `expires_at`, `created_at`
- `GET /media/{id}` Get a media file's status · answers 200: `id`, `name`, `source`, `status`, `content_type`, `size_bytes`, `duration_ms`, `sha256`, `error_code`, `expires_at`, `created_at`
- `DELETE /media/{id}` Delete a media file · answers 204, no body

### Analyses

- `GET /analyses` List analyses (without results) · query: `limit`, `cursor`, `kind`, `status`, `room_id`, `teacher_id`, `parent_analysis_id`, `from`, `to` · answers 200: `items`, `next_cursor`
- `POST /analyses` Request an analysis · headers: `Idempotency-Key` · body (JSON): `kind*`, `room_id`, `camera_ids`, `media_ids`, `starts_at`, `ends_at`, `tier`, `topic`, `teacher_id`, `teacher_name`, `language`, `batch`, `force`, `reason` · answers 202: `id`, `kind`, `status`, `tier`, `portfolio_id`, `room_id`, `camera_ids`, `media_ids`, `starts_at`, `ends_at`, `topic`, `teacher_id`, `language`, `parent_analysis_id` and 9 more
- `GET /analyses/{id}` Get an analysis with its result · answers 200: `id`, `kind`, `status`, `tier`, `portfolio_id`, `room_id`, `camera_ids`, `media_ids`, `starts_at`, `ends_at`, `topic`, `teacher_id`, `language`, `parent_analysis_id` and 9 more
- `POST /analyses/{id}/force` Re-run an analysis (the old one becomes superseded) · headers: `Idempotency-Key` · body (JSON): `reason*` · answers 202: `id`, `kind`, `status`, `tier`, `portfolio_id`, `room_id`, `camera_ids`, `media_ids`, `starts_at`, `ends_at`, `topic`, `teacher_id`, `language`, `parent_analysis_id` and 9 more

### Results

- `GET /incidents` List incidents with their clips · query: `limit`, `cursor`, `status`, `analysis_id`, `room_id`, `portfolio_id`, `min_severity`, `from`, `to` · answers 200: `items`, `next_cursor`
- `GET /incidents/{id}` Get an incident with its clips · answers 200: `id`, `analysis_id`, `portfolio_id`, `room_id`, `type`, `severity`, `confidence`, `starts_at`, `ends_at`, `camera_ids`, `description`, `quotes`, `status`, `released_at` and 4 more
- `GET /clips/{id}` Get a clip with a signed file URL (10 minutes) · answers 200: `id`, `incident_id`, `camera_id`, `starts_at`, `ends_at`, `size_bytes`, `status`, `expires_at`, `url`, `url_expires_at`
- `GET /clips/{id}/file` The clip MP4 behind a signed link (no API key; Range supported) · query: `org`, `exp`, `sig` · headers: `Range` · answers 200: video/mp4

### Teachers

- `GET /teachers` List teachers · query: `limit`, `cursor` · answers 200: `items`, `next_cursor`
- `GET /teachers/{id}` Get a teacher · answers 200: `id`, `name`, `created_at`, `lessons`, `merged_into`
- `GET /teachers/{id}/dashboard` A teacher's dashboard cards as data · answers 200: `teacher_id`, `cards`

### Webhooks

- `GET /webhooks` List webhooks · query: `limit`, `cursor` · answers 200: `items`, `next_cursor`
- `POST /webhooks` Create a webhook (the signing secret is returned once) · headers: `Idempotency-Key` · body (JSON): `url*`, `events*`, `active` · answers 201: `id`, `url`, `events`, `active`, `created_at`, `secret`
- `GET /webhooks/{id}` Get a webhook · answers 200: `id`, `url`, `events`, `active`, `created_at`
- `DELETE /webhooks/{id}` Delete a webhook and its delivery log · answers 204, no body
- `PATCH /webhooks/{id}` Change a webhook · body (JSON): `url`, `events`, `active` · answers 200: `id`, `url`, `events`, `active`, `created_at`
- `GET /webhooks/{id}/deliveries` A webhook's delivery log · query: `limit`, `cursor`, `status` · answers 200: `items`, `next_cursor`
- `POST /webhooks/{id}/test` Send a `ping` delivery to this webhook (also when paused) · answers 202: `delivery_id`

<!-- endpoint-index:end -->
