{
  "version": "2026.11",
  "base_url": "https://info.eaplfm.com",
  "groups": [
    {
      "id": "playback",
      "title": {
        "ru": "Эфир и музыка",
        "en": "Airplay & music"
      },
      "description": {
        "ru": "Потоки, композиции и история эфира.",
        "en": "Streams, tracks and airplay history."
      },
      "icon": "radio"
    },
    {
      "id": "community",
      "title": {
        "ru": "Реакции и комментарии",
        "en": "Reactions & comments"
      },
      "description": {
        "ru": "Обратная связь слушателей.",
        "en": "Listener feedback."
      },
      "icon": "message"
    },
    {
      "id": "analytics",
      "title": {
        "ru": "Аналитика",
        "en": "Analytics"
      },
      "description": {
        "ru": "Эфиры услуг и отчёты аудитории.",
        "en": "Service airplays and audience reports."
      },
      "icon": "chart"
    },
    {
      "id": "auth",
      "title": {
        "ru": "Авторизация",
        "en": "Authentication"
      },
      "description": {
        "ru": "Вход, первый пароль и выход.",
        "en": "Sign-in, initial password setup and sign-out."
      },
      "icon": "key"
    },
    {
      "id": "profiles",
      "title": {
        "ru": "Профили и исполнители",
        "en": "Profiles & artists"
      },
      "description": {
        "ru": "Данные аккаунтов и исполнителей.",
        "en": "Account profiles and artist records."
      },
      "icon": "user"
    },
    {
      "id": "apps",
      "title": {
        "ru": "Приложения",
        "en": "Apps"
      },
      "description": {
        "ru": "Устройства, уведомления и технические работы.",
        "en": "Devices, notifications and maintenance."
      },
      "icon": "phone"
    }
  ],
  "endpoints": [
    {
      "id": "player-streams",
      "group": "playback",
      "method": "GET",
      "path": "/api.pleer.php",
      "title": {
        "ru": "Потоки для плеера",
        "en": "Player streams"
      },
      "summary": {
        "ru": "Активные потоки с адресами трансляций и названиями на двух языках.",
        "en": "Active streams with playback URLs and names in both languages."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {},
      "body": {},
      "params": [],
      "response_kind": "json",
      "response": {
        "status": "ok",
        "cache_generated_at": "2026-11-20 12:00:00",
        "cache_file_time": "2026-11-20 12:00:00",
        "streams": [
          {
            "id": 3,
            "sort_order": 1,
            "slug": "top",
            "name_ru": "Топ",
            "name_en": "TOP",
            "stream_url": "https://listen.eaplfm.com/top.mp3"
          }
        ]
      },
      "fields": [
        {
          "name": "streams",
          "type": "array",
          "description": {
            "ru": "Потоки в порядке sort_order.",
            "en": "Streams ordered by sort_order."
          }
        },
        {
          "name": "streams[].stream_url",
          "type": "string",
          "description": {
            "ru": "Адрес трансляции для плеера.",
            "en": "Broadcast URL for the player."
          }
        },
        {
          "name": "cache_generated_at",
          "type": "string | null",
          "description": {
            "ru": "Время создания сохранённого списка.",
            "en": "Time when the cached list was generated."
          }
        }
      ],
      "notes": [
        {
          "ru": "Оба названия name_ru и name_en возвращаются в одном ответе.",
          "en": "Both name_ru and name_en are included in the same response."
        }
      ],
      "errors": [
        {
          "status": 200,
          "code": "status=error",
          "description": {
            "ru": "Кэш потоков отсутствует или повреждён.",
            "en": "The stream cache is missing or invalid."
          }
        }
      ]
    },
    {
      "id": "now",
      "group": "playback",
      "method": "GET",
      "path": "/api.php?action=now",
      "title": {
        "ru": "Текущая композиция",
        "en": "Current track"
      },
      "summary": {
        "ru": "Текущий фактический эфир выбранного потока, состояние вещания и микрофона, действующая плашка «Эксклюзив» и ближайшие открытые композиции.",
        "en": "The selected stream’s current live track, broadcast and microphone state, effective Exclusive badge and upcoming public tracks."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "stream": "top",
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "stream",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока: 2–64 символа a–z, 0–9, _ или -.",
            "en": "Stream code: 2–64 characters using a–z, 0–9, _ or -."
          },
          "default": "top"
        },
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "ru — русский; остальные языки используют EN.",
            "en": "ru selects Russian; other languages use EN."
          },
          "default": "ru"
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "stream": "top",
          "engine_version": "0.2.17",
          "server_time": "2026-11-23T12:00:10.000+03:00",
          "timezone": "Europe/Moscow",
          "engine_status_available": true,
          "control_healthy": true,
          "broadcast_status": "in",
          "is_broadcasting": true,
          "on_air_enabled": 1,
          "microphone_enabled": 1,
          "microphone_active": false,
          "source": "earth_plus_live",
          "show_in_api": 1,
          "metadata_hidden": false,
          "is_exclusive": 1,
          "exclusive_first_aired_at": "2026-11-20T12:00:00.000+03:00",
          "exclusive_expires_at": "2026-12-04T12:00:00.000+03:00",
          "item": {
            "id": 42,
            "name": "Artist - Track",
            "artist": "Artist",
            "title": "Track",
            "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "service_id": null,
            "played_at": "2026-11-23 11:59:00",
            "allow_listen": 1,
            "is_ai": 0,
            "file_path": null,
            "show_in_api": 1,
            "metadata_hidden": false,
            "schedule_id": 626481,
            "starts_at": "2026-11-23T11:59:00.000+03:00",
            "ends_at": "2026-11-23T12:03:00.000+03:00",
            "actual_started_at": "2026-11-23T11:59:00.000+03:00",
            "duration_ms": 240000,
            "position_ms": 70000,
            "remaining_ms": 170000,
            "is_exclusive": 1,
            "exclusive_first_aired_at": "2026-11-20T12:00:00.000+03:00",
            "exclusive_expires_at": "2026-12-04T12:00:00.000+03:00"
          },
          "stats": {
            "likes": 40,
            "dislikes": 3,
            "stars": 8,
            "score": 45
          },
          "label": "20.11.2026",
          "next_scope": "loaded_timeline",
          "next": [
            {
              "schedule_id": 626482,
              "starts_at": "2026-11-23T12:03:00.000+03:00",
              "ends_at": "2026-11-23T12:06:00.000+03:00",
              "show_in_api": 1,
              "metadata_hidden": false,
              "name": "Next Artist - Next Track",
              "artist": "Next Artist",
              "title": "Next Track",
              "hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
              "allow_listen": 1,
              "is_ai": 0,
              "is_exclusive": 0,
              "exclusive_first_aired_at": null,
              "exclusive_expires_at": null
            }
          ],
          "microphone_status": "off"
        }
      },
      "fields": [
        {
          "name": "data.stream",
          "type": "string",
          "description": {
            "ru": "Slug выбранного потока; состояние относится именно к нему.",
            "en": "Selected stream slug; all state fields refer to this stream."
          }
        },
        {
          "name": "data.source",
          "type": "string",
          "description": {
            "ru": "earth_plus_live: текущий трек подтверждён свежим состоянием движка.",
            "en": "earth_plus_live: the current track is confirmed by a fresh engine snapshot."
          }
        },
        {
          "name": "data.broadcast_status",
          "type": "string",
          "description": {
            "ru": "in — поток фактически вещает и управление исправно; off — иначе.",
            "en": "in means the stream is actually broadcasting with healthy control; off otherwise."
          }
        },
        {
          "name": "data.is_broadcasting",
          "type": "boolean",
          "description": {
            "ru": "Логический эквивалент broadcast_status=in.",
            "en": "Boolean equivalent of broadcast_status=in."
          }
        },
        {
          "name": "data.on_air_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — вещание разрешено настройкой потока; 0 — выключено. Это разрешение отдельно от фактического is_broadcasting.",
            "en": "1 means the stream is enabled for broadcasting; 0 means disabled. This setting is separate from actual is_broadcasting."
          }
        },
        {
          "name": "data.microphone_enabled",
          "type": "integer | null",
          "description": {
            "ru": "1 — микрофон разрешён настройкой; 0 — выключен. null, если установленный движок ещё не передаёт это поле.",
            "en": "1 means microphone input is enabled; 0 means disabled. null when the installed engine does not yet provide this field."
          }
        },
        {
          "name": "data.microphone_active",
          "type": "boolean | null",
          "description": {
            "ru": "true — микрофон фактически активен в эфире; false — нет; null — состояние недоступно в старой версии движка.",
            "en": "true means the microphone is active on air; false means inactive; null means unavailable from an older engine version."
          }
        },
        {
          "name": "data.microphone_status",
          "type": "string | null",
          "description": {
            "ru": "in — микрофон фактически активен в эфире; off — неактивен; null — старый движок не передал состояние.",
            "en": "in means the microphone is actually active on air; off means inactive; null means the older engine did not provide the state."
          }
        },
        {
          "name": "data.engine_version",
          "type": "string | null",
          "description": {
            "ru": "Версия движка; новые поля состояния поддерживаются в Earth_Plus 0.2.16.",
            "en": "Engine version; Earth_Plus 0.2.16 supports the new state fields."
          }
        },
        {
          "name": "data.server_time",
          "type": "string",
          "description": {
            "ru": "Время свежего снимка движка, ISO 8601, Europe/Moscow.",
            "en": "Fresh engine snapshot time in ISO 8601, Europe/Moscow."
          }
        },
        {
          "name": "data.engine_status_available",
          "type": "boolean",
          "description": {
            "ru": "В успешном ответе true; при недоступном или просроченном снимке возвращается ошибка 503.",
            "en": "true in a successful response; an unavailable or stale snapshot produces a 503 error."
          }
        },
        {
          "name": "data.control_healthy",
          "type": "boolean",
          "description": {
            "ru": "Исправность управления движком. При false текущая композиция не публикуется.",
            "en": "Engine control health. When false, no current track is published."
          }
        },
        {
          "name": "data.show_in_api",
          "type": "integer",
          "description": {
            "ru": "1 — текущие исполнитель и название доступны; 0 — скрыты либо текущего публичного трека нет.",
            "en": "1 means the current artist and title are available; 0 means hidden or no current public track is available."
          }
        },
        {
          "name": "data.metadata_hidden",
          "type": "boolean",
          "description": {
            "ru": "false при show_in_api=1; true при show_in_api=0.",
            "en": "false when show_in_api=1; true when show_in_api=0."
          }
        },
        {
          "name": "data.item",
          "type": "object | null",
          "description": {
            "ru": "Текущий публичный трек. null при скрытых метаданных, выключенном эфире, отсутствии или окончании текущей записи.",
            "en": "Current public track. null for hidden metadata, an offline stream, or an absent or ended current entry."
          }
        },
        {
          "name": "data.item.id",
          "type": "integer | null",
          "description": {
            "ru": "ID фактического выхода в songs; может быть null до записи истории.",
            "en": "Actual airplay ID in songs; may be null before history persistence completes."
          }
        },
        {
          "name": "data.item.name",
          "type": "string",
          "description": {
            "ru": "Исполнитель и название с учётом lang и сохранённого приоритета языка.",
            "en": "Artist and title resolved using lang and the stored language priority."
          }
        },
        {
          "name": "data.item.hash",
          "type": "string | null",
          "description": {
            "ru": "Ключ аудиофайла для истории, реакций и комментариев.",
            "en": "Audio-file key used for history, reactions and comments."
          }
        },
        {
          "name": "data.item.starts_at / data.item.ends_at / data.item.actual_started_at",
          "type": "string | null",
          "description": {
            "ru": "Плановые границы и фактическое начало текущего выхода, ISO 8601.",
            "en": "Planned boundaries and actual start of the current airplay, in ISO 8601."
          }
        },
        {
          "name": "data.stats",
          "type": "object (optional)",
          "description": {
            "ru": "Реакции likes, dislikes, stars и score, если соответствующий фактический выход уже доступен в истории.",
            "en": "likes, dislikes, stars and score when the matching actual airplay is already available in history."
          }
        },
        {
          "name": "data.label",
          "type": "string | null (optional)",
          "description": {
            "ru": "Существующая отметка new первые 72 часа, затем дата первого эфира DD.MM.YYYY; это отдельное правило от 14-дневного эксклюзива.",
            "en": "Existing new label for the first 72 hours, then the first airplay date as DD.MM.YYYY; this is separate from the 14-day Exclusive window."
          }
        },
        {
          "name": "data.item.allow_listen",
          "type": "integer",
          "description": {
            "ru": "1 — прослушивание разрешено; 0 — запрещено.",
            "en": "1 allows playback; 0 disables it."
          }
        },
        {
          "name": "data.item.is_ai",
          "type": "integer",
          "description": {
            "ru": "1 — композиция отмечена как созданная с ИИ; 0 — нет.",
            "en": "1 marks a track as AI-created; 0 does not."
          }
        },
        {
          "name": "data.item.file_path",
          "type": "string | null",
          "description": {
            "ru": "Временная HTTPS-ссылка на MP3 или null; разрешение проверяется по текущему эфиру.",
            "en": "Temporary HTTPS MP3 link or null; permission is checked against the current live entry."
          }
        },
        {
          "name": "data.item.is_exclusive",
          "type": "integer",
          "description": {
            "ru": "Действующая плашка «Эксклюзив»: 1 только для отмеченного трека в течение 14 суток с его первого фактического эфира; иначе 0.",
            "en": "Effective Exclusive badge: 1 only for a marked track during the 14 days after its first actual airplay; otherwise 0."
          }
        },
        {
          "name": "data.item.exclusive_first_aired_at",
          "type": "string | null",
          "description": {
            "ru": "Первый фактический эфир этого аудиофайла по hash, ISO 8601 с миллисекундами и +03:00; null, пока время неизвестно или сохранённый флаг равен 0.",
            "en": "First actual airplay of this audio file identified by hash, in ISO 8601 with milliseconds and +03:00; null when unknown or when the saved flag is 0."
          }
        },
        {
          "name": "data.item.exclusive_expires_at",
          "type": "string | null",
          "description": {
            "ru": "Конец 14-дневного срока. Начиная с этого момента is_exclusive=0; null, пока первый эфир неизвестен или сохранённый флаг равен 0.",
            "en": "End of the 14-day window. is_exclusive is 0 from this instant onward; null while the first airplay is unknown or when the saved flag is 0."
          }
        },
        {
          "name": "data.is_exclusive",
          "type": "integer",
          "description": {
            "ru": "Дублирует действующий флаг текущего item; 0 при item=null.",
            "en": "Mirrors the effective flag of the current item; 0 when item=null."
          }
        },
        {
          "name": "data.exclusive_first_aired_at / data.exclusive_expires_at",
          "type": "string | null (optional)",
          "description": {
            "ru": "Даты текущего публичного item; отсутствуют при item=null.",
            "en": "Dates from the current public item; omitted when item=null."
          }
        },
        {
          "name": "data.next",
          "type": "array",
          "description": {
            "ru": "До трёх ближайших открытых композиций загруженной очереди. Скрытые записи пропускаются; массив может быть пустым.",
            "en": "Up to three upcoming public tracks from the loaded timeline. Hidden entries are skipped; the array may be empty."
          }
        },
        {
          "name": "data.next_scope",
          "type": "string",
          "description": {
            "ru": "loaded_timeline — только уже загруженная очередь, без обещания полного будущего расписания.",
            "en": "loaded_timeline means the already loaded queue, not a guarantee of a complete future timetable."
          }
        },
        {
          "name": "data.next[].show_in_api / data.next[].metadata_hidden",
          "type": "integer / boolean",
          "description": {
            "ru": "Публикуемые следующие треки имеют 1 / false; их названия разрешены к показу.",
            "en": "Published upcoming tracks have 1 / false, permitting their names to be displayed."
          }
        },
        {
          "name": "data.next[].is_exclusive",
          "type": "integer",
          "description": {
            "ru": "Действующая плашка «Эксклюзив»: 1 только для отмеченного трека в течение 14 суток с его первого фактического эфира; иначе 0.",
            "en": "Effective Exclusive badge: 1 only for a marked track during the 14 days after its first actual airplay; otherwise 0."
          }
        },
        {
          "name": "data.next[].exclusive_first_aired_at",
          "type": "string | null",
          "description": {
            "ru": "Первый фактический эфир этого аудиофайла по hash, ISO 8601 с миллисекундами и +03:00; null, пока время неизвестно или сохранённый флаг равен 0.",
            "en": "First actual airplay of this audio file identified by hash, in ISO 8601 with milliseconds and +03:00; null when unknown or when the saved flag is 0."
          }
        },
        {
          "name": "data.next[].exclusive_expires_at",
          "type": "string | null",
          "description": {
            "ru": "Конец 14-дневного срока. Начиная с этого момента is_exclusive=0; null, пока первый эфир неизвестен или сохранённый флаг равен 0.",
            "en": "End of the 14-day window. is_exclusive is 0 from this instant onward; null while the first airplay is unknown or when the saved flag is 0."
          }
        }
      ],
      "notes": [
        {
          "ru": "При show_in_api=0 и metadata_hidden=true item=null: исполнитель, название, hash и плейлист текущего трека не публикуются. Предыдущий трек из кеша не подставляется. Ближайшие открытые треки могут оставаться в next.",
          "en": "With show_in_api=0 and metadata_hidden=true, item=null: the current artist, title, hash and playlist are not published. A previous cached track is never substituted. Upcoming public tracks may still appear in next."
        },
        {
          "ru": "is_exclusive=1 действует только при установленной отметке и известном первом фактическом эфире. Срок равен 14 × 24 часам, общий для одного hash во всех потоках; одобрение заявки, повторный эфир и повторная загрузка того же файла не запускают срок заново.",
          "en": "is_exclusive=1 requires the Exclusive flag and a known first actual airplay. The window is 14 × 24 hours for the same hash across all streams; approval, repeat plays and re-uploading the same file do not restart it."
        },
        {
          "ru": "До первого фактического эфира и с exclusive_expires_at публичный is_exclusive равен 0. Cron сохраняет 0 по hash. При сохранённом 0 даты в ответе null и срок не рассчитывается; GET не меняет БД.",
          "en": "Public is_exclusive is 0 before the first actual airplay and from exclusive_expires_at onward. Cron persists 0 by hash. A saved 0 skips date calculation and returns null dates; GET never writes the database."
        },
        {
          "ru": "Язык исполнителя и названия определяется lang и priority_ru/priority_en; отсутствующие части берутся из другого языка.",
          "en": "Artist and title language follows lang and priority_ru/priority_en, with missing components taken from the other language."
        },
        {
          "ru": "Отметка label=new по-прежнему действует 72 часа с первого эфира по станции и не зависит от плашки «Эксклюзив».",
          "en": "The existing label=new still lasts 72 hours from the first station-wide airplay and is independent of the Exclusive badge."
        },
        {
          "ru": "Полное расписание плейлистов доступно отдельным методом schedule; оно не вкладывается в /api/v1/status.",
          "en": "The full playlist timetable is available through the separate schedule method; it is not embedded in /api/v1/status."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 404,
          "code": "stream_not_found",
          "description": {
            "ru": "Движок не нашёл выбранный поток.",
            "en": "The engine did not find the selected stream."
          }
        },
        {
          "status": 503,
          "code": "engine_temporarily_unavailable",
          "description": {
            "ru": "Свежий снимок движка недоступен; предыдущая композиция не возвращается вместо него.",
            "en": "A fresh engine snapshot is unavailable; a previous track is not returned instead."
          }
        },
        {
          "status": 500,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        }
      ]
    },
    {
      "id": "history",
      "group": "playback",
      "method": "GET",
      "path": "/api.php?action=history",
      "title": {
        "ru": "История эфира",
        "en": "Airplay history"
      },
      "summary": {
        "ru": "Фактические выходы композиций с поиском, фильтрами времени, страницами и действующей 14-дневной плашкой «Эксклюзив».",
        "en": "Recorded track plays with search, time filters, pagination and the effective 14-day Exclusive badge."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "stream": "top",
        "limit": 5,
        "page": 1,
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "stream",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока: 2–64 символа a–z, 0–9, _ или -.",
            "en": "Stream code: 2–64 characters using a–z, 0–9, _ or -."
          },
          "default": "top"
        },
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "ru — русский; остальные языки используют EN.",
            "en": "ru selects Russian; other languages use EN."
          },
          "default": "ru"
        },
        {
          "name": "limit",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Количество записей: от 1 до 200.",
            "en": "Number of records, from 1 to 200."
          },
          "default": 200
        },
        {
          "name": "page",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Номер страницы от 1 до 1 000 000.",
            "en": "Page number from 1 to 1,000,000."
          },
          "default": 1
        },
        {
          "name": "q",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Исполнитель, название, hash или номер услуги; до 1024 байт и 12 слов.",
            "en": "Artist, title, hash or service ID; up to 1,024 bytes and 12 words."
          }
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Дата YYYY-MM-DD по Москве.",
            "en": "Date in YYYY-MM-DD format, Moscow time."
          }
        },
        {
          "name": "from",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Начало интервала HH:MM по Москве.",
            "en": "Interval start in HH:MM format, Moscow time."
          }
        },
        {
          "name": "to",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Конец интервала HH:MM; последняя минута включается.",
            "en": "Interval end in HH:MM format; the final minute is included."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "items": [
            {
              "id": 42,
              "name": "Artist - Track",
              "played_at": "2026-11-20 12:00:00",
              "allow_listen": 1,
              "file_path": null,
              "likes": 40,
              "dislikes": 3,
              "stars": 8,
              "score": 45,
              "is_ai": 0,
              "is_exclusive": 1,
              "exclusive_first_aired_at": "2026-11-20T12:00:00.000+03:00",
              "exclusive_expires_at": "2026-12-04T12:00:00.000+03:00"
            }
          ],
          "page": 1,
          "limit": 5,
          "has_more": false,
          "next_page": null,
          "source": "airplay_history",
          "timezone": "Europe/Moscow"
        }
      },
      "fields": [
        {
          "name": "data.items",
          "type": "array",
          "description": {
            "ru": "Отдельные выходы в эфир; повторные выходы имеют разные id.",
            "en": "Individual airplays; repeat plays have different IDs."
          }
        },
        {
          "name": "data.items[].played_at",
          "type": "string",
          "description": {
            "ru": "Дата и время выхода YYYY-MM-DD HH:MM:SS, МСК.",
            "en": "Airplay time as YYYY-MM-DD HH:MM:SS, Moscow time."
          }
        },
        {
          "name": "data.items[].file_path",
          "type": "string | null",
          "description": {
            "ru": "Ссылка доступна только в первые 48 часов после этого выхода.",
            "en": "A link is available only within 48 hours of this airplay."
          }
        },
        {
          "name": "data.items[].is_exclusive",
          "type": "integer",
          "description": {
            "ru": "Действующая плашка «Эксклюзив»: 1 только для отмеченного трека в течение 14 суток с его первого фактического эфира; иначе 0.",
            "en": "Effective Exclusive badge: 1 only for a marked track during the 14 days after its first actual airplay; otherwise 0."
          }
        },
        {
          "name": "data.items[].exclusive_first_aired_at",
          "type": "string | null",
          "description": {
            "ru": "Первый фактический эфир этого аудиофайла по hash, ISO 8601 с миллисекундами и +03:00; null, пока время неизвестно или сохранённый флаг равен 0.",
            "en": "First actual airplay of this audio file identified by hash, in ISO 8601 with milliseconds and +03:00; null when unknown or when the saved flag is 0."
          }
        },
        {
          "name": "data.items[].exclusive_expires_at",
          "type": "string | null",
          "description": {
            "ru": "Конец 14-дневного срока. Начиная с этого момента is_exclusive=0; null, пока первый эфир неизвестен или сохранённый флаг равен 0.",
            "en": "End of the 14-day window. is_exclusive is 0 from this instant onward; null while the first airplay is unknown or when the saved flag is 0."
          }
        },
        {
          "name": "data.has_more",
          "type": "boolean",
          "description": {
            "ru": "Есть ли следующая страница.",
            "en": "Whether another page is available."
          }
        },
        {
          "name": "data.next_page",
          "type": "integer | null",
          "description": {
            "ru": "Номер следующей страницы или null.",
            "en": "The next page number, or null."
          }
        }
      ],
      "notes": [
        {
          "ru": "Через 48 часов file_path становится null даже при allow_listen=1.",
          "en": "After 48 hours, file_path is null even when allow_listen=1."
        },
        {
          "ru": "Без date фильтры from и to выбирают время суток во всех датах.",
          "en": "Without date, from and to filter the time of day across all dates."
        },
        {
          "ru": "is_exclusive — действующая плашка на момент запроса, а не сохранённое состояние на дату исторического выхода. После 14 суток с первого фактического эфира он равен 0 и в старых записях истории.",
          "en": "is_exclusive is the effective badge at request time, not the saved badge at the historical airplay time. After 14 days from the first actual airplay, it is 0 in older history entries too."
        },
        {
          "ru": "Срок отсчитывается по известному первому фактическому эфиру hash во всех потоках. Повторы не продлевают срок. Cron сохраняет 0 в songs и связанных таблицах. При сохранённом 0 даты null, срок не рассчитывается. Для1 проверка при чтении исключает истёкшую плашку до cron.",
          "en": "The window starts at the known first actual airplay of a hash across streams. Repeats do not extend it. Cron persists0 in songs and related tables. Saved0 returns null dates without interval calculation. Saved1 has a read-time expiry guard before cron runs."
        },
        {
          "ru": "source остаётся airplay_history; существующая отметка label=new на 72 часа и доступность прослушивания на 48 часов сохраняют отдельные правила.",
          "en": "source remains airplay_history; the existing 72-hour label=new and 48-hour playback availability retain their separate rules."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 500,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        },
        {
          "status": 400,
          "code": "invalid_date",
          "description": {
            "ru": "Некорректная дата.",
            "en": "Invalid date."
          }
        },
        {
          "status": 400,
          "code": "invalid_time",
          "description": {
            "ru": "Некорректное время.",
            "en": "Invalid time."
          }
        },
        {
          "status": 400,
          "code": "query_too_long",
          "description": {
            "ru": "Поисковый запрос слишком длинный.",
            "en": "Search query is too long."
          }
        },
        {
          "status": 400,
          "code": "invalid_query",
          "description": {
            "ru": "Некорректный поисковый запрос.",
            "en": "Invalid search query."
          }
        },
        {
          "status": 400,
          "code": "too_many_search_words",
          "description": {
            "ru": "В поиске больше 12 слов.",
            "en": "The search contains more than 12 words."
          }
        },
        {
          "status": 202,
          "code": "api_cache_warming",
          "description": {
            "ru": "Первый снимок ещё готовится; повторите запрос.",
            "en": "The first snapshot is still being prepared; retry the request."
          }
        }
      ]
    },
    {
      "id": "schedule",
      "group": "playback",
      "method": "GET",
      "path": "/api.schedule.php",
      "title": {
        "ru": "Расписание плейлистов на четыре дня",
        "en": "Four-day playlist timetable"
      },
      "summary": {
        "ru": "Отдельный публичный API сохранённых запусков плейлистов: четыре московских дня, один поток или все активные потоки, с соблюдением скрытия метаданных.",
        "en": "Separate public API for saved playlist occurrences: four Moscow calendar days, one stream or all active streams, respecting metadata visibility."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "stream": "top"
      },
      "body": {},
      "params": [
        {
          "name": "stream",
          "in": "query",
          "type": "string",
          "required": false,
          "default": "all",
          "description": {
            "ru": "all или отсутствие параметра — все активные потоки; иначе slug из 2–64 символов a–z, 0–9, _ или -.",
            "en": "all or an omitted parameter selects all active streams; otherwise use a 2–64 character slug with a–z, 0–9, _ or -."
          }
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Начальная дата YYYY-MM-DD по Москве, от сегодня до сегодня + 3 дня. По умолчанию сегодня.",
            "en": "Start date as YYYY-MM-DD in Moscow, from today through today + 3 days. Defaults to today."
          }
        },
        {
          "name": "days",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "От 1 до 4, без выхода за сегодня + 3 дня. По умолчанию все оставшиеся дни горизонта; без date это 4.",
            "en": "From 1 to 4, without extending past today + 3 days. Defaults to all remaining days in the horizon; without date this is 4."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "schema_version": 1,
        "status": "ok",
        "source": "broadcast_schedule",
        "timezone": "Europe/Moscow",
        "server_time": "2026-11-23T12:00:10.000+03:00",
        "scope": "stream",
        "playlist_scope": "all_playlists",
        "from": "2026-11-23T00:00:00.000+03:00",
        "until": "2026-11-27T00:00:00.000+03:00",
        "horizon_until": "2026-11-27T00:00:00.000+03:00",
        "days_requested": 4,
        "dates": [
          "2026-11-23",
          "2026-11-24",
          "2026-11-25",
          "2026-11-26"
        ],
        "streams": [
          {
            "id": 3,
            "slug": "top",
            "name_ru": "Топ",
            "name_en": "TOP",
            "days": [
              {
                "date": "2026-11-23",
                "starts_at": "2026-11-23T00:00:00.000+03:00",
                "ends_at": "2026-11-24T00:00:00.000+03:00",
                "coverage": {
                  "state": "partial",
                  "primary_audio_covered_seconds": 3600,
                  "unfilled_seconds": 82800,
                  "continuous_until": null,
                  "saved_until": "2026-11-23T09:00:00.000+03:00"
                },
                "pending_rebuild": false,
                "playlists": [
                  {
                    "starts_at": "2026-11-23T08:00:00.000+03:00",
                    "ends_at": "2026-11-23T09:00:00.000+03:00",
                    "scheduled_at": "2026-11-23T08:00:00.000+03:00",
                    "planned_starts_at": "2026-11-23T08:00:00.000+03:00",
                    "planned_ends_at": "2026-11-23T09:00:00.000+03:00",
                    "actual_started_at": "2026-11-23T08:00:00.000+03:00",
                    "actual_ended_at": "2026-11-23T09:00:00.000+03:00",
                    "ends_at_estimated": false,
                    "source": "actual",
                    "audio_layer": 0,
                    "show_in_api": 1,
                    "metadata_hidden": false,
                    "playlist": {
                      "id": 12,
                      "name_ru": "Энергия жизни",
                      "name_en": "Energy of Life",
                      "type": "music"
                    }
                  }
                ],
                "gaps": []
              },
              {
                "date": "2026-11-24",
                "starts_at": "2026-11-24T00:00:00.000+03:00",
                "ends_at": "2026-11-25T00:00:00.000+03:00",
                "coverage": {
                  "state": "partial",
                  "primary_audio_covered_seconds": 3600,
                  "unfilled_seconds": 82800,
                  "continuous_until": null,
                  "saved_until": "2026-11-24T09:00:00.000+03:00"
                },
                "pending_rebuild": false,
                "playlists": [
                  {
                    "starts_at": "2026-11-24T08:00:00.000+03:00",
                    "ends_at": "2026-11-24T09:00:00.000+03:00",
                    "scheduled_at": "2026-11-24T08:00:00.000+03:00",
                    "planned_starts_at": "2026-11-24T08:00:00.000+03:00",
                    "planned_ends_at": "2026-11-24T09:00:00.000+03:00",
                    "actual_started_at": null,
                    "actual_ended_at": null,
                    "ends_at_estimated": true,
                    "source": "forecast",
                    "audio_layer": 0,
                    "show_in_api": 0,
                    "metadata_hidden": true
                  }
                ],
                "gaps": []
              },
              {
                "date": "2026-11-25",
                "starts_at": "2026-11-25T00:00:00.000+03:00",
                "ends_at": "2026-11-26T00:00:00.000+03:00",
                "coverage": {
                  "state": "empty",
                  "primary_audio_covered_seconds": 0,
                  "unfilled_seconds": 86400,
                  "continuous_until": null,
                  "saved_until": null
                },
                "pending_rebuild": false,
                "playlists": [],
                "gaps": []
              },
              {
                "date": "2026-11-26",
                "starts_at": "2026-11-26T00:00:00.000+03:00",
                "ends_at": "2026-11-27T00:00:00.000+03:00",
                "coverage": {
                  "state": "empty",
                  "primary_audio_covered_seconds": 0,
                  "unfilled_seconds": 86400,
                  "continuous_until": null,
                  "saved_until": null
                },
                "pending_rebuild": false,
                "playlists": [],
                "gaps": []
              }
            ]
          }
        ]
      },
      "fields": [
        {
          "name": "schema_version",
          "type": "integer",
          "description": {
            "ru": "Версия схемы расписания: 1.",
            "en": "Schedule schema version: 1."
          }
        },
        {
          "name": "status / source",
          "type": "string / string",
          "description": {
            "ru": "ok / broadcast_schedule: прочитана сохранённая эфирная сетка.",
            "en": "ok / broadcast_schedule: the saved broadcast grid has been read."
          }
        },
        {
          "name": "timezone / server_time",
          "type": "string / string",
          "description": {
            "ru": "Europe/Moscow и время ответа в ISO 8601 с миллисекундами.",
            "en": "Europe/Moscow and response time in ISO 8601 with milliseconds."
          }
        },
        {
          "name": "scope",
          "type": "string",
          "description": {
            "ru": "all_streams для всех активных потоков; stream для одного slug.",
            "en": "all_streams for all active streams; stream for one slug."
          }
        },
        {
          "name": "playlist_scope",
          "type": "string",
          "description": {
            "ru": "all_playlists: учитываются все плейлисты сохранённой сетки, включая интервалы со скрытыми именами.",
            "en": "all_playlists: all playlists in the saved grid are considered, including intervals with hidden names."
          }
        },
        {
          "name": "from / until",
          "type": "string / string",
          "description": {
            "ru": "Запрошенный интервал по Москве; from включается, until не включается.",
            "en": "Requested Moscow-time interval; from is inclusive and until is exclusive."
          }
        },
        {
          "name": "horizon_until",
          "type": "string",
          "description": {
            "ru": "Исключительная правая граница: начало дня через четыре календарных дня от сегодняшнего. Это предел запроса, не обещание заполненной сетки.",
            "en": "Exclusive right boundary: the start of the day four calendar days after today. This limits requests and does not guarantee a filled grid."
          }
        },
        {
          "name": "days_requested / dates",
          "type": "integer / array",
          "description": {
            "ru": "Количество дней и все запрошенные московские даты, включая даты без сохранённых запусков.",
            "en": "Day count and every requested Moscow date, including dates without saved entries."
          }
        },
        {
          "name": "streams",
          "type": "array",
          "description": {
            "ru": "Активные потоки. При stream=all и отсутствии активных потоков массив пуст.",
            "en": "Active streams. With stream=all, the array is empty when there are no active streams."
          }
        },
        {
          "name": "streams[].id / streams[].slug / streams[].name_ru / streams[].name_en",
          "type": "integer / string / string / string",
          "description": {
            "ru": "Публичный идентификатор, код и названия потока.",
            "en": "Public stream identifier, slug and names."
          }
        },
        {
          "name": "streams[].days",
          "type": "array",
          "description": {
            "ru": "Блок на каждый запрошенный день, даже если playlists пуст.",
            "en": "One bucket for each requested day, even when playlists is empty."
          }
        },
        {
          "name": "streams[].days[].coverage.state",
          "type": "string",
          "description": {
            "ru": "complete — основное аудио покрывает весь день; partial — сетка неполная; empty — подходящих сохранённых интервалов нет.",
            "en": "complete means primary audio covers the entire day; partial means incomplete coverage; empty means no matching saved intervals."
          }
        },
        {
          "name": "streams[].days[].coverage.primary_audio_covered_seconds / streams[].days[].coverage.unfilled_seconds",
          "type": "number / number",
          "description": {
            "ru": "Покрытые и непокрытые секунды основного аудиослоя. Фактические прерывания учитываются; наложения не заполняют основной слой.",
            "en": "Covered and unfilled seconds of the primary audio layer. Actual interruptions are respected; overlays do not fill primary coverage."
          }
        },
        {
          "name": "streams[].days[].coverage.continuous_until / streams[].days[].coverage.saved_until",
          "type": "string | null",
          "description": {
            "ru": "Конец непрерывного покрытия от полуночи и самый поздний сохранённый конец. Один saved_until не доказывает полноту дня.",
            "en": "End of continuous coverage from midnight and the latest saved end. saved_until alone does not establish complete coverage."
          }
        },
        {
          "name": "streams[].days[].pending_rebuild",
          "type": "boolean",
          "description": {
            "ru": "true, если источник сохранённого будущего запуска стал недоступен; такой запуск не публикуется до пересборки сетки планировщиком.",
            "en": "true when the source of a saved future entry has become unavailable; that entry is omitted until the planner rebuilds the grid."
          }
        },
        {
          "name": "streams[].days[].playlists",
          "type": "array",
          "description": {
            "ru": "Хронологические интервалы плейлистов, сгруппированные по непрерывному запуску. Отдельных треков здесь нет.",
            "en": "Chronological playlist intervals grouped by contiguous occurrence. Individual tracks are not included."
          }
        },
        {
          "name": "streams[].days[].playlists[].starts_at / streams[].days[].playlists[].ends_at",
          "type": "string / string",
          "description": {
            "ru": "Границы интервала внутри данного московского дня; пересечение полуночи разделяется между днями.",
            "en": "Interval boundaries within this Moscow day; an interval crossing midnight is split between days."
          }
        },
        {
          "name": "streams[].days[].playlists[].scheduled_at",
          "type": "string | null",
          "description": {
            "ru": "Время фиксированного запуска; null для фоновой ротации без фиксированного старта.",
            "en": "Fixed occurrence start; null for background rotation without a fixed start."
          }
        },
        {
          "name": "streams[].days[].playlists[].planned_starts_at / streams[].days[].playlists[].planned_ends_at",
          "type": "string / string",
          "description": {
            "ru": "Исходные плановые границы сохранённой группы до разделения по дням.",
            "en": "Original planned boundaries of the saved group before day splitting."
          }
        },
        {
          "name": "streams[].days[].playlists[].actual_started_at / streams[].days[].playlists[].actual_ended_at",
          "type": "string | null",
          "description": {
            "ru": "Фактические границы, если они уже записаны; конец может быть неизвестен у текущего выхода.",
            "en": "Actual boundaries when recorded; the end may be unknown for an ongoing airplay."
          }
        },
        {
          "name": "streams[].days[].playlists[].source",
          "type": "string",
          "description": {
            "ru": "actual — есть фактическое начало; forecast — сохранённый будущий план.",
            "en": "actual means an actual start was recorded; forecast means a saved future plan."
          }
        },
        {
          "name": "streams[].days[].playlists[].ends_at_estimated",
          "type": "boolean",
          "description": {
            "ru": "true, если фактический конец ещё неизвестен и используется плановый конец.",
            "en": "true when the actual end is not yet known and the planned end is used."
          }
        },
        {
          "name": "streams[].days[].playlists[].audio_layer",
          "type": "integer",
          "description": {
            "ru": "0 — основной слой; 1 — наложение, например джингл.",
            "en": "0 is the primary layer; 1 is an overlay, such as a jingle."
          }
        },
        {
          "name": "streams[].days[].playlists[].show_in_api / streams[].days[].playlists[].metadata_hidden",
          "type": "integer / boolean",
          "description": {
            "ru": "1 / false — имена открыты; 0 / true — скрыты.",
            "en": "1 / false means names are public; 0 / true means hidden."
          }
        },
        {
          "name": "streams[].days[].playlists[].playlist",
          "type": "object (optional)",
          "description": {
            "ru": "Только при show_in_api=1: id, name_ru, name_en и type. Для скрытого интервала весь объект отсутствует, включая ID.",
            "en": "Only when show_in_api=1: id, name_ru, name_en and type. For a hidden interval the entire object is omitted, including its ID."
          }
        },
        {
          "name": "streams[].days[].gaps",
          "type": "array",
          "description": {
            "ru": "Сохранённые интервалы тишины основного слоя; остальные незаполненные части дня отражает coverage.",
            "en": "Saved primary-layer silence intervals; coverage also accounts for other unfilled parts of the day."
          }
        }
      ],
      "notes": [
        {
          "ru": "По умолчанию возвращаются сегодня, завтра, послезавтра и следующий день по Москве, для всех активных потоков. days и date могут только сократить этот горизонт.",
          "en": "By default, the response covers today and the next three Moscow calendar days for all active streams. days and date can only narrow this horizon."
        },
        {
          "ru": "Это чтение сохранённой broadcast_schedule: запрос не запускает планировщик и не создаёт будущие треки. Пустые и частичные дни явно обозначены в coverage.",
          "en": "This reads the saved broadcast_schedule: the request does not run the planner or create future tracks. Empty and partial days are explicitly identified by coverage."
        },
        {
          "ru": "Проверяются и сохранённый show_in_api, и текущая видимость плейлиста, а для программы — также её музыкального источника. При скрытии не выдаются названия или ID плейлиста. Имена треков, пути файлов и ID клиентов не входят в этот API.",
          "en": "Both saved show_in_api and current playlist visibility are checked, including a program’s music source. Hidden intervals expose no playlist names or IDs. Track names, file paths and client IDs are outside this API."
        },
        {
          "ru": "Объект playlist может отсутствовать у отдельных интервалов. Сами времена, show_in_api=0 и metadata_hidden=true остаются доступными для отрисовки закрытого блока.",
          "en": "Individual intervals can omit playlist. Their timing, show_in_api=0 and metadata_hidden=true remain available to render a private block."
        },
        {
          "ru": "Повторяющиеся запуски одного плейлиста могут давать несколько интервалов; фоновые записи объединяются только при непрерывном соседстве. Фактические и прогнозные части помечены отдельно.",
          "en": "Repeated occurrences of one playlist may produce multiple intervals; background entries merge only when contiguous. Actual and forecast portions are labelled separately."
        },
        {
          "ru": "Прямой /api.schedule.php отдаёт объект расписания без оболочки ok/data. Alias /api.php?action=schedule отдаёт тот же объект внутри {ok:true,data:{...}}.",
          "en": "Direct /api.schedule.php returns the timetable object without an ok/data envelope. The /api.php?action=schedule alias returns the same object inside {ok:true,data:{...}}."
        },
        {
          "ru": "Адрес https://listen.eaplfm.com/api/v1/schedule подключается отдельно командой earth-plus/enable-public-schedule.sh --apply после загрузки PHP и миграции. Он проксирует прямой ответ /api.schedule.php. Полное расписание не добавляется в /api/v1/status, в том числе в Earth_Plus 0.2.16.",
          "en": "https://listen.eaplfm.com/api/v1/schedule is enabled separately with earth-plus/enable-public-schedule.sh --apply after deploying PHP and the migration. It proxies the direct /api.schedule.php response. The full timetable is not added to /api/v1/status, including in Earth_Plus 0.2.16."
        },
        {
          "ru": "Прямой метод поддерживает GET, HEAD и OPTIONS с CORS. Ответы не кешируются, чтобы снятие публикации сразу действовало при следующем запросе.",
          "en": "The direct endpoint supports GET, HEAD and OPTIONS with CORS. Responses are not cached, so publication revocation applies on the next request."
        },
        {
          "ru": "Ошибка прямого метода имеет форму {schema_version:1,status:\"error\",error:\"code\"}.",
          "en": "A direct-endpoint error has the form {schema_version:1,status:\"error\",error:\"code\"}."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 404,
          "code": "stream_not_found",
          "description": {
            "ru": "Активный поток с этим slug не найден.",
            "en": "No active stream matches this slug."
          }
        },
        {
          "status": 422,
          "code": "invalid_schedule_date",
          "description": {
            "ru": "Дата должна быть строкой YYYY-MM-DD.",
            "en": "The date must be a YYYY-MM-DD string."
          }
        },
        {
          "status": 422,
          "code": "schedule_date_outside_horizon",
          "description": {
            "ru": "Дата неверна или находится вне интервала от сегодня до сегодня + 3 дня по Москве.",
            "en": "The date is invalid or outside today through today + 3 days in Moscow."
          }
        },
        {
          "status": 422,
          "code": "invalid_schedule_days",
          "description": {
            "ru": "days должен быть целым от 1 до 4 и укладываться в оставшийся горизонт от date.",
            "en": "days must be an integer from 1 to 4 and fit the remaining horizon from date."
          }
        },
        {
          "status": 405,
          "code": "method_not_allowed",
          "description": {
            "ru": "Поддерживаются GET, HEAD и OPTIONS.",
            "en": "GET, HEAD and OPTIONS are supported."
          }
        },
        {
          "status": 503,
          "code": "schedule_too_large",
          "description": {
            "ru": "Сохранённая выборка превышает безопасный предел; ответ не обрезается молча.",
            "en": "The saved selection exceeds the safe limit; the response is not silently truncated."
          }
        },
        {
          "status": 503,
          "code": "schedule_temporarily_unavailable",
          "description": {
            "ru": "Расписание временно недоступно; повторите запрос после Retry-After.",
            "en": "The timetable is temporarily unavailable; retry after Retry-After."
          }
        }
      ]
    },
    {
      "id": "schedule-alias",
      "group": "playback",
      "method": "GET",
      "path": "/api.php?action=schedule",
      "title": {
        "ru": "Расписание через api.php",
        "en": "Playlist timetable through api.php"
      },
      "summary": {
        "ru": "Alias расписания плейлистов с общей оболочкой API: {ok:true,data:{...}}. Параметры, видимость и четырёхдневный горизонт совпадают с /api.schedule.php.",
        "en": "Alias for the playlist timetable using the shared API envelope: {ok:true,data:{...}}. Parameters, visibility and the four-day horizon match /api.schedule.php."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "stream": "top"
      },
      "body": {},
      "params": [
        {
          "name": "stream",
          "in": "query",
          "type": "string",
          "required": false,
          "default": "all",
          "description": {
            "ru": "all или отсутствие параметра — все активные потоки; иначе slug из 2–64 символов a–z, 0–9, _ или -.",
            "en": "all or an omitted parameter selects all active streams; otherwise use a 2–64 character slug with a–z, 0–9, _ or -."
          }
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Начальная дата YYYY-MM-DD по Москве, от сегодня до сегодня + 3 дня. По умолчанию сегодня.",
            "en": "Start date as YYYY-MM-DD in Moscow, from today through today + 3 days. Defaults to today."
          }
        },
        {
          "name": "days",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "От 1 до 4, без выхода за сегодня + 3 дня. По умолчанию все оставшиеся дни горизонта; без date это 4.",
            "en": "From 1 to 4, without extending past today + 3 days. Defaults to all remaining days in the horizon; without date this is 4."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "schema_version": 1,
          "status": "ok",
          "source": "broadcast_schedule",
          "timezone": "Europe/Moscow",
          "server_time": "2026-11-23T12:00:10.000+03:00",
          "scope": "stream",
          "playlist_scope": "all_playlists",
          "from": "2026-11-23T00:00:00.000+03:00",
          "until": "2026-11-27T00:00:00.000+03:00",
          "horizon_until": "2026-11-27T00:00:00.000+03:00",
          "days_requested": 4,
          "dates": [
            "2026-11-23",
            "2026-11-24",
            "2026-11-25",
            "2026-11-26"
          ],
          "streams": [
            {
              "id": 3,
              "slug": "top",
              "name_ru": "Топ",
              "name_en": "TOP",
              "days": [
                {
                  "date": "2026-11-23",
                  "starts_at": "2026-11-23T00:00:00.000+03:00",
                  "ends_at": "2026-11-24T00:00:00.000+03:00",
                  "coverage": {
                    "state": "partial",
                    "primary_audio_covered_seconds": 3600,
                    "unfilled_seconds": 82800,
                    "continuous_until": null,
                    "saved_until": "2026-11-23T09:00:00.000+03:00"
                  },
                  "pending_rebuild": false,
                  "playlists": [
                    {
                      "starts_at": "2026-11-23T08:00:00.000+03:00",
                      "ends_at": "2026-11-23T09:00:00.000+03:00",
                      "scheduled_at": "2026-11-23T08:00:00.000+03:00",
                      "planned_starts_at": "2026-11-23T08:00:00.000+03:00",
                      "planned_ends_at": "2026-11-23T09:00:00.000+03:00",
                      "actual_started_at": "2026-11-23T08:00:00.000+03:00",
                      "actual_ended_at": "2026-11-23T09:00:00.000+03:00",
                      "ends_at_estimated": false,
                      "source": "actual",
                      "audio_layer": 0,
                      "show_in_api": 1,
                      "metadata_hidden": false,
                      "playlist": {
                        "id": 12,
                        "name_ru": "Энергия жизни",
                        "name_en": "Energy of Life",
                        "type": "music"
                      }
                    }
                  ],
                  "gaps": []
                },
                {
                  "date": "2026-11-24",
                  "starts_at": "2026-11-24T00:00:00.000+03:00",
                  "ends_at": "2026-11-25T00:00:00.000+03:00",
                  "coverage": {
                    "state": "partial",
                    "primary_audio_covered_seconds": 3600,
                    "unfilled_seconds": 82800,
                    "continuous_until": null,
                    "saved_until": "2026-11-24T09:00:00.000+03:00"
                  },
                  "pending_rebuild": false,
                  "playlists": [
                    {
                      "starts_at": "2026-11-24T08:00:00.000+03:00",
                      "ends_at": "2026-11-24T09:00:00.000+03:00",
                      "scheduled_at": "2026-11-24T08:00:00.000+03:00",
                      "planned_starts_at": "2026-11-24T08:00:00.000+03:00",
                      "planned_ends_at": "2026-11-24T09:00:00.000+03:00",
                      "actual_started_at": null,
                      "actual_ended_at": null,
                      "ends_at_estimated": true,
                      "source": "forecast",
                      "audio_layer": 0,
                      "show_in_api": 0,
                      "metadata_hidden": true
                    }
                  ],
                  "gaps": []
                },
                {
                  "date": "2026-11-25",
                  "starts_at": "2026-11-25T00:00:00.000+03:00",
                  "ends_at": "2026-11-26T00:00:00.000+03:00",
                  "coverage": {
                    "state": "empty",
                    "primary_audio_covered_seconds": 0,
                    "unfilled_seconds": 86400,
                    "continuous_until": null,
                    "saved_until": null
                  },
                  "pending_rebuild": false,
                  "playlists": [],
                  "gaps": []
                },
                {
                  "date": "2026-11-26",
                  "starts_at": "2026-11-26T00:00:00.000+03:00",
                  "ends_at": "2026-11-27T00:00:00.000+03:00",
                  "coverage": {
                    "state": "empty",
                    "primary_audio_covered_seconds": 0,
                    "unfilled_seconds": 86400,
                    "continuous_until": null,
                    "saved_until": null
                  },
                  "pending_rebuild": false,
                  "playlists": [],
                  "gaps": []
                }
              ]
            }
          ]
        }
      },
      "fields": [
        {
          "name": "data.schema_version",
          "type": "integer",
          "description": {
            "ru": "Версия схемы расписания: 1.",
            "en": "Schedule schema version: 1."
          }
        },
        {
          "name": "data.status / data.source",
          "type": "string / string",
          "description": {
            "ru": "ok / broadcast_schedule: прочитана сохранённая эфирная сетка.",
            "en": "ok / broadcast_schedule: the saved broadcast grid has been read."
          }
        },
        {
          "name": "data.timezone / data.server_time",
          "type": "string / string",
          "description": {
            "ru": "Europe/Moscow и время ответа в ISO 8601 с миллисекундами.",
            "en": "Europe/Moscow and response time in ISO 8601 with milliseconds."
          }
        },
        {
          "name": "data.scope",
          "type": "string",
          "description": {
            "ru": "all_streams для всех активных потоков; stream для одного slug.",
            "en": "all_streams for all active streams; stream for one slug."
          }
        },
        {
          "name": "data.playlist_scope",
          "type": "string",
          "description": {
            "ru": "all_playlists: учитываются все плейлисты сохранённой сетки, включая интервалы со скрытыми именами.",
            "en": "all_playlists: all playlists in the saved grid are considered, including intervals with hidden names."
          }
        },
        {
          "name": "data.from / data.until",
          "type": "string / string",
          "description": {
            "ru": "Запрошенный интервал по Москве; from включается, until не включается.",
            "en": "Requested Moscow-time interval; from is inclusive and until is exclusive."
          }
        },
        {
          "name": "data.horizon_until",
          "type": "string",
          "description": {
            "ru": "Исключительная правая граница: начало дня через четыре календарных дня от сегодняшнего. Это предел запроса, не обещание заполненной сетки.",
            "en": "Exclusive right boundary: the start of the day four calendar days after today. This limits requests and does not guarantee a filled grid."
          }
        },
        {
          "name": "data.days_requested / data.dates",
          "type": "integer / array",
          "description": {
            "ru": "Количество дней и все запрошенные московские даты, включая даты без сохранённых запусков.",
            "en": "Day count and every requested Moscow date, including dates without saved entries."
          }
        },
        {
          "name": "data.streams",
          "type": "array",
          "description": {
            "ru": "Активные потоки. При stream=all и отсутствии активных потоков массив пуст.",
            "en": "Active streams. With stream=all, the array is empty when there are no active streams."
          }
        },
        {
          "name": "data.streams[].id / data.streams[].slug / data.streams[].name_ru / data.streams[].name_en",
          "type": "integer / string / string / string",
          "description": {
            "ru": "Публичный идентификатор, код и названия потока.",
            "en": "Public stream identifier, slug and names."
          }
        },
        {
          "name": "data.streams[].days",
          "type": "array",
          "description": {
            "ru": "Блок на каждый запрошенный день, даже если playlists пуст.",
            "en": "One bucket for each requested day, even when playlists is empty."
          }
        },
        {
          "name": "data.streams[].days[].coverage.state",
          "type": "string",
          "description": {
            "ru": "complete — основное аудио покрывает весь день; partial — сетка неполная; empty — подходящих сохранённых интервалов нет.",
            "en": "complete means primary audio covers the entire day; partial means incomplete coverage; empty means no matching saved intervals."
          }
        },
        {
          "name": "data.streams[].days[].coverage.primary_audio_covered_seconds / data.streams[].days[].coverage.unfilled_seconds",
          "type": "number / number",
          "description": {
            "ru": "Покрытые и непокрытые секунды основного аудиослоя. Фактические прерывания учитываются; наложения не заполняют основной слой.",
            "en": "Covered and unfilled seconds of the primary audio layer. Actual interruptions are respected; overlays do not fill primary coverage."
          }
        },
        {
          "name": "data.streams[].days[].coverage.continuous_until / data.streams[].days[].coverage.saved_until",
          "type": "string | null",
          "description": {
            "ru": "Конец непрерывного покрытия от полуночи и самый поздний сохранённый конец. Один saved_until не доказывает полноту дня.",
            "en": "End of continuous coverage from midnight and the latest saved end. saved_until alone does not establish complete coverage."
          }
        },
        {
          "name": "data.streams[].days[].pending_rebuild",
          "type": "boolean",
          "description": {
            "ru": "true, если источник сохранённого будущего запуска стал недоступен; такой запуск не публикуется до пересборки сетки планировщиком.",
            "en": "true when the source of a saved future entry has become unavailable; that entry is omitted until the planner rebuilds the grid."
          }
        },
        {
          "name": "data.streams[].days[].playlists",
          "type": "array",
          "description": {
            "ru": "Хронологические интервалы плейлистов, сгруппированные по непрерывному запуску. Отдельных треков здесь нет.",
            "en": "Chronological playlist intervals grouped by contiguous occurrence. Individual tracks are not included."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].starts_at / data.streams[].days[].playlists[].ends_at",
          "type": "string / string",
          "description": {
            "ru": "Границы интервала внутри данного московского дня; пересечение полуночи разделяется между днями.",
            "en": "Interval boundaries within this Moscow day; an interval crossing midnight is split between days."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].scheduled_at",
          "type": "string | null",
          "description": {
            "ru": "Время фиксированного запуска; null для фоновой ротации без фиксированного старта.",
            "en": "Fixed occurrence start; null for background rotation without a fixed start."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].planned_starts_at / data.streams[].days[].playlists[].planned_ends_at",
          "type": "string / string",
          "description": {
            "ru": "Исходные плановые границы сохранённой группы до разделения по дням.",
            "en": "Original planned boundaries of the saved group before day splitting."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].actual_started_at / data.streams[].days[].playlists[].actual_ended_at",
          "type": "string | null",
          "description": {
            "ru": "Фактические границы, если они уже записаны; конец может быть неизвестен у текущего выхода.",
            "en": "Actual boundaries when recorded; the end may be unknown for an ongoing airplay."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].source",
          "type": "string",
          "description": {
            "ru": "actual — есть фактическое начало; forecast — сохранённый будущий план.",
            "en": "actual means an actual start was recorded; forecast means a saved future plan."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].ends_at_estimated",
          "type": "boolean",
          "description": {
            "ru": "true, если фактический конец ещё неизвестен и используется плановый конец.",
            "en": "true when the actual end is not yet known and the planned end is used."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].audio_layer",
          "type": "integer",
          "description": {
            "ru": "0 — основной слой; 1 — наложение, например джингл.",
            "en": "0 is the primary layer; 1 is an overlay, such as a jingle."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].show_in_api / data.streams[].days[].playlists[].metadata_hidden",
          "type": "integer / boolean",
          "description": {
            "ru": "1 / false — имена открыты; 0 / true — скрыты.",
            "en": "1 / false means names are public; 0 / true means hidden."
          }
        },
        {
          "name": "data.streams[].days[].playlists[].playlist",
          "type": "object (optional)",
          "description": {
            "ru": "Только при show_in_api=1: id, name_ru, name_en и type. Для скрытого интервала весь объект отсутствует, включая ID.",
            "en": "Only when show_in_api=1: id, name_ru, name_en and type. For a hidden interval the entire object is omitted, including its ID."
          }
        },
        {
          "name": "data.streams[].days[].gaps",
          "type": "array",
          "description": {
            "ru": "Сохранённые интервалы тишины основного слоя; остальные незаполненные части дня отражает coverage.",
            "en": "Saved primary-layer silence intervals; coverage also accounts for other unfilled parts of the day."
          }
        }
      ],
      "notes": [
        {
          "ru": "По умолчанию возвращаются сегодня, завтра, послезавтра и следующий день по Москве, для всех активных потоков. days и date могут только сократить этот горизонт.",
          "en": "By default, the response covers today and the next three Moscow calendar days for all active streams. days and date can only narrow this horizon."
        },
        {
          "ru": "Это чтение сохранённой broadcast_schedule: запрос не запускает планировщик и не создаёт будущие треки. Пустые и частичные дни явно обозначены в coverage.",
          "en": "This reads the saved broadcast_schedule: the request does not run the planner or create future tracks. Empty and partial days are explicitly identified by coverage."
        },
        {
          "ru": "Проверяются и сохранённый show_in_api, и текущая видимость плейлиста, а для программы — также её музыкального источника. При скрытии не выдаются названия или ID плейлиста. Имена треков, пути файлов и ID клиентов не входят в этот API.",
          "en": "Both saved show_in_api and current playlist visibility are checked, including a program’s music source. Hidden intervals expose no playlist names or IDs. Track names, file paths and client IDs are outside this API."
        },
        {
          "ru": "Объект playlist может отсутствовать у отдельных интервалов. Сами времена, show_in_api=0 и metadata_hidden=true остаются доступными для отрисовки закрытого блока.",
          "en": "Individual intervals can omit playlist. Their timing, show_in_api=0 and metadata_hidden=true remain available to render a private block."
        },
        {
          "ru": "Повторяющиеся запуски одного плейлиста могут давать несколько интервалов; фоновые записи объединяются только при непрерывном соседстве. Фактические и прогнозные части помечены отдельно.",
          "en": "Repeated occurrences of one playlist may produce multiple intervals; background entries merge only when contiguous. Actual and forecast portions are labelled separately."
        },
        {
          "ru": "Прямой /api.schedule.php отдаёт объект расписания без оболочки ok/data. Alias /api.php?action=schedule отдаёт тот же объект внутри {ok:true,data:{...}}.",
          "en": "Direct /api.schedule.php returns the timetable object without an ok/data envelope. The /api.php?action=schedule alias returns the same object inside {ok:true,data:{...}}."
        },
        {
          "ru": "Адрес https://listen.eaplfm.com/api/v1/schedule подключается отдельно командой earth-plus/enable-public-schedule.sh --apply после загрузки PHP и миграции. Он проксирует прямой ответ /api.schedule.php. Полное расписание не добавляется в /api/v1/status, в том числе в Earth_Plus 0.2.16.",
          "en": "https://listen.eaplfm.com/api/v1/schedule is enabled separately with earth-plus/enable-public-schedule.sh --apply after deploying PHP and the migration. It proxies the direct /api.schedule.php response. The full timetable is not added to /api/v1/status, including in Earth_Plus 0.2.16."
        },
        {
          "ru": "Alias использует стандартную оболочку ошибки api.php: {ok:false,error:\"code\"}. Для прямого API и listen-прокси оболочка отличается.",
          "en": "The alias uses the standard api.php error envelope: {ok:false,error:\"code\"}. The direct API and listen proxy use a different envelope."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 404,
          "code": "stream_not_found",
          "description": {
            "ru": "Активный поток с этим slug не найден.",
            "en": "No active stream matches this slug."
          }
        },
        {
          "status": 422,
          "code": "invalid_schedule_date",
          "description": {
            "ru": "Дата должна быть строкой YYYY-MM-DD.",
            "en": "The date must be a YYYY-MM-DD string."
          }
        },
        {
          "status": 422,
          "code": "schedule_date_outside_horizon",
          "description": {
            "ru": "Дата неверна или находится вне интервала от сегодня до сегодня + 3 дня по Москве.",
            "en": "The date is invalid or outside today through today + 3 days in Moscow."
          }
        },
        {
          "status": 422,
          "code": "invalid_schedule_days",
          "description": {
            "ru": "days должен быть целым от 1 до 4 и укладываться в оставшийся горизонт от date.",
            "en": "days must be an integer from 1 to 4 and fit the remaining horizon from date."
          }
        },
        {
          "status": 202,
          "code": "api_cache_warming",
          "description": {
            "ru": "Лимит одновременного чтения занят; повторите запрос.",
            "en": "The concurrent read limit is occupied; retry the request."
          }
        },
        {
          "status": 500,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "Расписание временно недоступно или превышает допустимый размер выборки.",
            "en": "The timetable is temporarily unavailable or exceeds the permitted selection size."
          }
        }
      ]
    },
    {
      "id": "top",
      "group": "playback",
      "method": "GET",
      "path": "/api_top.php?action=list",
      "title": {
        "ru": "ТОП-300",
        "en": "Top 300"
      },
      "summary": {
        "ru": "Рейтинг композиций за период по всей станции или выбранному потоку.",
        "en": "Track rankings for a period across the station or a selected stream."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "type": "today",
        "stream": "top",
        "lang": "ru",
        "page": 1,
        "per_page": 10
      },
      "body": {},
      "params": [
        {
          "name": "type",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Период рейтинга.",
            "en": "Ranking period."
          },
          "default": "today",
          "enum": [
            "today",
            "week",
            "month",
            "all"
          ]
        },
        {
          "name": "stream",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока; all или отсутствие — вся станция.",
            "en": "Stream code; all or no value selects the entire station."
          }
        },
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "ru — русский; остальные языки используют EN.",
            "en": "ru selects Russian; other languages use EN."
          },
          "default": "ru"
        },
        {
          "name": "page",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Номер страницы, начиная с 1.",
            "en": "Page number, starting at 1."
          },
          "default": 1
        },
        {
          "name": "per_page",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Количество композиций: от 1 до 200.",
            "en": "Number of tracks, from 1 to 200."
          },
          "default": 30
        },
        {
          "name": "q",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Поиск среди композиций рейтинга.",
            "en": "Search within the ranked tracks."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "page": 1,
        "pages": 1,
        "per_page": 30,
        "total": 1,
        "items": [
          {
            "id": 42,
            "name": "Artist - Track",
            "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "rank": 1,
            "plays": 5,
            "likes": 40,
            "dislikes": 3,
            "stars": 8,
            "score": 45,
            "is_ai": 0,
            "file_path": null
          }
        ],
        "generated_at": "2026-11-20 12:00:00",
        "next_update": "2026-11-20 12:30:00",
        "error": null,
        "type": "today",
        "stream": null,
        "lang": "ru",
        "timezone": "Europe/Moscow",
        "cache_stale": false,
        "cache_status": "fresh"
      },
      "fields": [
        {
          "name": "items",
          "type": "array",
          "description": {
            "ru": "Композиции и реакции на текущей странице.",
            "en": "Tracks and their reactions on the current page."
          }
        },
        {
          "name": "items[].rank",
          "type": "integer",
          "description": {
            "ru": "Место в полном рейтинге, сохраняется при поиске.",
            "en": "Position in the full ranking, retained when searching."
          }
        },
        {
          "name": "total",
          "type": "integer",
          "description": {
            "ru": "Количество найденных композиций, не более 300.",
            "en": "Number of matching tracks, at most 300."
          }
        },
        {
          "name": "pages",
          "type": "integer",
          "description": {
            "ru": "Количество страниц результата.",
            "en": "Number of result pages."
          }
        },
        {
          "name": "generated_at",
          "type": "string | null",
          "description": {
            "ru": "Время расчёта рейтинга.",
            "en": "Time when the ranking was calculated."
          }
        },
        {
          "name": "next_update",
          "type": "string | null",
          "description": {
            "ru": "Плановое время обновления.",
            "en": "Scheduled refresh time."
          }
        },
        {
          "name": "error",
          "type": "string | null",
          "description": {
            "ru": "Описание ошибки; null при успешном ответе.",
            "en": "Error description, or null for a successful response."
          }
        }
      ],
      "notes": [
        {
          "ru": "Сортировка: stars, затем likes, затем plays — по убыванию.",
          "en": "Sorted by stars, then likes, then plays, in descending order."
        },
        {
          "ru": "Периоды считаются по Москве; неделя начинается в понедельник.",
          "en": "Periods use Moscow time; the week starts on Monday."
        },
        {
          "ru": "Рейтинг обычно обновляется каждые 30 минут; результат находится в корне JSON.",
          "en": "The ranking normally refreshes every 30 minutes; results are at the JSON root."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 400,
          "code": "unknown_stream",
          "description": {
            "ru": "Поток не найден.",
            "en": "Stream not found."
          }
        },
        {
          "status": 400,
          "code": "unknown_action",
          "description": {
            "ru": "Действие не найдено.",
            "en": "Unknown action."
          }
        },
        {
          "status": 503,
          "code": "cache_unavailable",
          "description": {
            "ru": "Кэш рейтинга недоступен.",
            "en": "The ranking cache is unavailable."
          }
        },
        {
          "status": 503,
          "code": "cache_busy",
          "description": {
            "ru": "Рейтинг обновляется; повторите запрос позже.",
            "en": "The ranking is being refreshed; retry later."
          }
        },
        {
          "status": 503,
          "code": "cache_retry_later",
          "description": {
            "ru": "Повторите запрос рейтинга позже.",
            "en": "Retry the ranking request later."
          }
        },
        {
          "status": 503,
          "code": "top_temporarily_unavailable",
          "description": {
            "ru": "Рейтинг временно недоступен.",
            "en": "The ranking is temporarily unavailable."
          }
        }
      ]
    },
    {
      "id": "audio",
      "group": "playback",
      "method": "GET",
      "path": "/song_audio.php",
      "title": {
        "ru": "Прослушать запись",
        "en": "Play a recording"
      },
      "summary": {
        "ru": "Получить MP3 по защищённой ссылке из поля file_path.",
        "en": "Retrieve an MP3 using the signed link in file_path."
      },
      "auth": "signed",
      "run": false,
      "format": "none",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "id",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "ID записи из готовой ссылки.",
            "en": "Recording ID from the issued link."
          }
        },
        {
          "name": "expires",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Срок действия из готовой ссылки.",
            "en": "Expiration value from the issued link."
          }
        },
        {
          "name": "scope",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Область доступа из готовой ссылки.",
            "en": "Access scope from the issued link."
          },
          "enum": [
            "public",
            "history"
          ]
        },
        {
          "name": "signature",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Подпись из готовой ссылки.",
            "en": "Signature from the issued link."
          }
        },
        {
          "name": "Range",
          "in": "header",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Один диапазон байтов, например bytes=0-1023.",
            "en": "One byte range, for example bytes=0-1023."
          }
        }
      ],
      "response_kind": "audio",
      "response": {},
      "fields": [
        {
          "name": "Content-Type",
          "type": "header",
          "description": {
            "ru": "audio/mpeg; тело ответа содержит аудиофайл.",
            "en": "audio/mpeg; the response body contains the audio file."
          }
        },
        {
          "name": "Accept-Ranges",
          "type": "header",
          "description": {
            "ru": "bytes — доступно частичное чтение.",
            "en": "bytes indicates support for partial reads."
          }
        },
        {
          "name": "Content-Length",
          "type": "header",
          "description": {
            "ru": "Размер ответа в байтах.",
            "en": "Response size in bytes."
          }
        }
      ],
      "notes": [
        {
          "ru": "Используйте file_path целиком: ссылка действует до 15 минут, а запись истории доступна только первые 48 часов после эфира.",
          "en": "Use file_path unchanged: links last up to 15 minutes, and history recordings are available only within 48 hours of airplay."
        },
        {
          "ru": "При file_path=null воспроизведение недоступно.",
          "en": "Playback is unavailable when file_path is null."
        },
        {
          "ru": "Поддерживаются GET, HEAD и одиночный Range; частичный ответ имеет статус 206.",
          "en": "GET, HEAD and a single Range are supported; partial responses use status 206."
        }
      ],
      "errors": [
        {
          "status": 404,
          "code": "",
          "description": {
            "ru": "Ссылка истекла, недействительна или запись недоступна.",
            "en": "The link is expired or invalid, or the recording is unavailable."
          }
        },
        {
          "status": 405,
          "code": "",
          "description": {
            "ru": "Метод HTTP не поддерживается.",
            "en": "The HTTP method is not supported."
          }
        },
        {
          "status": 416,
          "code": "",
          "description": {
            "ru": "Запрошенный диапазон байтов недоступен.",
            "en": "The requested byte range is not available."
          }
        },
        {
          "status": 503,
          "code": "",
          "description": {
            "ru": "Временная ошибка сервера.",
            "en": "Temporary server error."
          }
        }
      ]
    },
    {
      "id": "streams",
      "group": "playback",
      "method": "GET",
      "path": "/api.php?action=streams",
      "title": {
        "ru": "Справочник потоков",
        "en": "Stream directory"
      },
      "summary": {
        "ru": "Коды и названия потоков радиостанции.",
        "en": "Radio stream codes and names."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {},
      "body": {},
      "params": [],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "items": [
            {
              "slug": "top",
              "name_ru": "Топ",
              "name_en": "TOP"
            }
          ]
        }
      },
      "fields": [
        {
          "name": "data.items",
          "type": "array",
          "description": {
            "ru": "Все записи справочника потоков.",
            "en": "All entries in the stream directory."
          }
        },
        {
          "name": "data.items[].slug",
          "type": "string",
          "description": {
            "ru": "Код для параметра stream.",
            "en": "Code to pass as the stream parameter."
          }
        }
      ],
      "notes": [
        {
          "ru": "Для воспроизведения используйте адреса из api.pleer.php.",
          "en": "Use the URLs returned by api.pleer.php for playback."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        }
      ]
    },
    {
      "id": "ping",
      "group": "playback",
      "method": "GET",
      "path": "/api.php?action=ping",
      "title": {
        "ru": "Проверка API",
        "en": "API health check"
      },
      "summary": {
        "ru": "Проверить доступность основного API.",
        "en": "Check availability of the main API."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {},
      "body": {},
      "params": [],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "pong": true
        }
      },
      "fields": [
        {
          "name": "data.pong",
          "type": "boolean",
          "description": {
            "ru": "true — API ответил на запрос.",
            "en": "true means the API responded to the request."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        }
      ]
    },
    {
      "id": "comments",
      "group": "community",
      "method": "GET",
      "path": "/api.php?action=comment.list",
      "title": {
        "ru": "Комментарии к треку",
        "en": "Track comments"
      },
      "summary": {
        "ru": "Последние комментарии к композиции по её hash.",
        "en": "Recent comments for a track identified by its hash."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      },
      "body": {},
      "params": [
        {
          "name": "hash",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Hash композиции из now или history.",
            "en": "Track hash returned by now or history."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "items": [
            {
              "id": 12,
              "name": "Слушатель",
              "text": "Отличная композиция!",
              "created_at": "2026-11-20 12:00:00"
            }
          ]
        }
      },
      "fields": [
        {
          "name": "data.items",
          "type": "array",
          "description": {
            "ru": "Последние 5 комментариев, от новых к старым.",
            "en": "The latest 5 comments, newest first."
          }
        },
        {
          "name": "data.items[].created_at",
          "type": "string",
          "description": {
            "ru": "Время публикации YYYY-MM-DD HH:MM:SS.",
            "en": "Publication time in YYYY-MM-DD HH:MM:SS format."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        },
        {
          "status": 400,
          "code": "hash_required",
          "description": {
            "ru": "Не передан hash композиции.",
            "en": "The track hash is required."
          }
        }
      ]
    },
    {
      "id": "like",
      "group": "community",
      "method": "POST",
      "path": "/api.php?action=like",
      "title": {
        "ru": "Поставить лайк",
        "en": "Like a track"
      },
      "summary": {
        "ru": "Сохранить реакцию на композицию выбранного потока.",
        "en": "Save a reaction to a track on the selected stream."
      },
      "auth": "public",
      "run": false,
      "format": "form",
      "query": {},
      "body": {
        "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "stream": "top",
        "lang": "ru"
      },
      "params": [
        {
          "name": "hash",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Hash композиции.",
            "en": "Track hash."
          }
        },
        {
          "name": "stream",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока.",
            "en": "Stream code."
          },
          "default": "top"
        },
        {
          "name": "lang",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык ответа.",
            "en": "Response language."
          },
          "default": "ru"
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "stats": {
            "likes": 40,
            "dislikes": 3,
            "stars": 8,
            "score": 45
          }
        }
      },
      "fields": [
        {
          "name": "data.stats",
          "type": "object",
          "description": {
            "ru": "Реакции: likes, dislikes, stars и итог score.",
            "en": "Reactions: likes, dislikes, stars and the resulting score."
          }
        }
      ],
      "notes": [
        {
          "ru": "Передавайте тело как application/x-www-form-urlencoded или FormData.",
          "en": "Send the body as application/x-www-form-urlencoded or FormData."
        },
        {
          "ru": "Пауза между повторными реакциями с одного IP на трек в потоке — 5 минут.",
          "en": "Repeat reactions from one IP for the same track and stream require a 5-minute interval."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        },
        {
          "status": 400,
          "code": "hash_required",
          "description": {
            "ru": "Не передан hash композиции.",
            "en": "The track hash is required."
          }
        },
        {
          "status": 400,
          "code": "vote_failed",
          "description": {
            "ru": "Реакция не сохранена.",
            "en": "The reaction could not be saved."
          }
        },
        {
          "status": 429,
          "code": "",
          "description": {
            "ru": "Повторное голосование слишком скоро; error содержит текст на выбранном языке.",
            "en": "Another vote was submitted too soon; error contains a message in the selected language."
          }
        }
      ]
    },
    {
      "id": "dislike",
      "group": "community",
      "method": "POST",
      "path": "/api.php?action=dislike",
      "title": {
        "ru": "Поставить дизлайк",
        "en": "Dislike a track"
      },
      "summary": {
        "ru": "Сохранить реакцию на композицию выбранного потока.",
        "en": "Save a reaction to a track on the selected stream."
      },
      "auth": "public",
      "run": false,
      "format": "form",
      "query": {},
      "body": {
        "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "stream": "top",
        "lang": "ru"
      },
      "params": [
        {
          "name": "hash",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Hash композиции.",
            "en": "Track hash."
          }
        },
        {
          "name": "stream",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока.",
            "en": "Stream code."
          },
          "default": "top"
        },
        {
          "name": "lang",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык ответа.",
            "en": "Response language."
          },
          "default": "ru"
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "stats": {
            "likes": 40,
            "dislikes": 3,
            "stars": 8,
            "score": 45
          }
        }
      },
      "fields": [
        {
          "name": "data.stats",
          "type": "object",
          "description": {
            "ru": "Реакции: likes, dislikes, stars и итог score.",
            "en": "Reactions: likes, dislikes, stars and the resulting score."
          }
        }
      ],
      "notes": [
        {
          "ru": "Передавайте тело как application/x-www-form-urlencoded или FormData.",
          "en": "Send the body as application/x-www-form-urlencoded or FormData."
        },
        {
          "ru": "Пауза между повторными реакциями с одного IP на трек в потоке — 5 минут.",
          "en": "Repeat reactions from one IP for the same track and stream require a 5-minute interval."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        },
        {
          "status": 400,
          "code": "hash_required",
          "description": {
            "ru": "Не передан hash композиции.",
            "en": "The track hash is required."
          }
        },
        {
          "status": 400,
          "code": "vote_failed",
          "description": {
            "ru": "Реакция не сохранена.",
            "en": "The reaction could not be saved."
          }
        },
        {
          "status": 429,
          "code": "",
          "description": {
            "ru": "Повторное голосование слишком скоро; error содержит текст на выбранном языке.",
            "en": "Another vote was submitted too soon; error contains a message in the selected language."
          }
        }
      ]
    },
    {
      "id": "comment-add",
      "group": "community",
      "method": "POST",
      "path": "/api.php?action=comment.add",
      "title": {
        "ru": "Добавить комментарий",
        "en": "Add a comment"
      },
      "summary": {
        "ru": "Опубликовать комментарий к выбранной композиции.",
        "en": "Publish a comment on the selected track."
      },
      "auth": "public",
      "run": false,
      "format": "form",
      "query": {},
      "body": {
        "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "name": "Listener",
        "text": "Great track!",
        "stream": "top",
        "lang": "ru"
      },
      "params": [
        {
          "name": "hash",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Hash композиции.",
            "en": "Track hash."
          }
        },
        {
          "name": "text",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Текст комментария.",
            "en": "Comment text."
          }
        },
        {
          "name": "name",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя автора.",
            "en": "Author name."
          },
          "default": "Anon"
        },
        {
          "name": "stream",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код потока.",
            "en": "Stream code."
          },
          "default": "top"
        },
        {
          "name": "lang",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык ответа.",
            "en": "Response language."
          },
          "default": "ru"
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "items": [
            {
              "id": 12,
              "name": "Слушатель",
              "text": "Отличная композиция!",
              "created_at": "2026-11-20 12:00:00"
            }
          ]
        }
      },
      "fields": [
        {
          "name": "data.items",
          "type": "array",
          "description": {
            "ru": "Обновлённый список последних комментариев.",
            "en": "Updated list of recent comments."
          }
        }
      ],
      "notes": [
        {
          "ru": "Передавайте тело как application/x-www-form-urlencoded или FormData.",
          "en": "Send the body as application/x-www-form-urlencoded or FormData."
        },
        {
          "ru": "Пауза между комментариями с одного IP к одному треку — 5 минут.",
          "en": "Comments from one IP on the same track require a 5-minute interval."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "invalid_stream",
          "description": {
            "ru": "Некорректный код потока.",
            "en": "Invalid stream code."
          }
        },
        {
          "status": 503,
          "code": "api_temporarily_unavailable",
          "description": {
            "ru": "API временно недоступен.",
            "en": "The API is temporarily unavailable."
          }
        },
        {
          "status": 400,
          "code": "comment_invalid",
          "description": {
            "ru": "Укажите hash и текст комментария.",
            "en": "Provide the track hash and comment text."
          }
        },
        {
          "status": 400,
          "code": "comment_failed",
          "description": {
            "ru": "Комментарий не сохранён.",
            "en": "The comment could not be saved."
          }
        },
        {
          "status": 429,
          "code": "too_often",
          "description": {
            "ru": "Повторный комментарий отправлен слишком быстро.",
            "en": "Another comment was submitted too soon."
          }
        }
      ]
    },
    {
      "id": "client-statistics",
      "group": "analytics",
      "method": "GET",
      "path": "/userstatic/api/stats_service.php",
      "title": {
        "ru": "Аналитика услуги",
        "en": "Service analytics"
      },
      "summary": {
        "ru": "Эфиры, реакции, графики и достижения по номеру услуги.",
        "en": "Airplays, reactions, charts and achievements for a service."
      },
      "auth": "service",
      "run": false,
      "format": "none",
      "query": {
        "service_id": "SERVICE_ID",
        "mode": "week",
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "service_id",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Номер вашей услуги; передавайте строкой.",
            "en": "Your service ID, sent as a string."
          }
        },
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "ru — русский; остальные языки используют EN.",
            "en": "ru selects Russian; other languages use EN."
          },
          "default": "ru"
        },
        {
          "name": "mode",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Период отчёта.",
            "en": "Report period."
          },
          "default": "today",
          "enum": [
            "today",
            "yesterday",
            "week",
            "date",
            "months",
            "year"
          ]
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Дата YYYY-MM-DD для mode=date.",
            "en": "Date as YYYY-MM-DD for mode=date."
          }
        },
        {
          "name": "m1",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Месяц YYYY-MM для mode=months.",
            "en": "Month as YYYY-MM for mode=months."
          }
        },
        {
          "name": "year",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Год для mode=year.",
            "en": "Year for mode=year."
          }
        },
        {
          "name": "details_page",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Страница отдельных выходов, начиная с 1.",
            "en": "Individual airplay page, starting at 1."
          },
          "default": 1
        },
        {
          "name": "details_limit",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Выходов на странице: от 1 до 2000.",
            "en": "Airplays per page, from 1 to 2,000."
          },
          "default": 2000
        },
        {
          "name": "airplays_page",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Страница сгруппированных композиций, начиная с 1.",
            "en": "Grouped track page, starting at 1."
          },
          "default": 1
        },
        {
          "name": "airplays_limit",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Композиций на странице: от 1 до 2000.",
            "en": "Tracks per page, from 1 to 2,000."
          },
          "default": 2000
        },
        {
          "name": "top_limit",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Композиций в analysis: от 1 до 30.",
            "en": "Tracks in analysis, from 1 to 30."
          },
          "default": 10
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "service_id": "SERVICE_ID",
        "language": "ru",
        "timezone": "Europe/Moscow",
        "data_source": "songs",
        "totals_complete": true,
        "total_plays": 0,
        "kpi": {
          "plays": 0,
          "unique_tracks": 0,
          "likes": 0,
          "dislikes": 0,
          "stars": 0,
          "reach": 0
        },
        "rows": [],
        "track_airplays": [],
        "analysis": []
      },
      "fields": [
        {
          "name": "kpi",
          "type": "object",
          "description": {
            "ru": "Итоги за весь выбранный период.",
            "en": "Totals for the entire selected period."
          }
        },
        {
          "name": "kpi_prev",
          "type": "object",
          "description": {
            "ru": "Итоги предыдущего периода для сравнения.",
            "en": "Totals for the previous comparison period."
          }
        },
        {
          "name": "rows",
          "type": "array",
          "description": {
            "ru": "Отдельные выходы в эфир.",
            "en": "Individual airplays."
          }
        },
        {
          "name": "rows_pagination",
          "type": "object",
          "description": {
            "ru": "Параметры страниц отдельных выходов.",
            "en": "Pagination information for individual airplays."
          }
        },
        {
          "name": "track_airplays",
          "type": "array",
          "description": {
            "ru": "Композиции с количеством выходов.",
            "en": "Tracks with their airplay counts."
          }
        },
        {
          "name": "track_airplays_pagination",
          "type": "object",
          "description": {
            "ru": "Параметры страниц композиций.",
            "en": "Pagination information for grouped tracks."
          }
        },
        {
          "name": "analysis",
          "type": "array",
          "description": {
            "ru": "Популярные композиции за период.",
            "en": "Leading tracks for the period."
          }
        },
        {
          "name": "links.details_csv",
          "type": "string",
          "description": {
            "ru": "Ссылка на полный CSV выбранного отчёта.",
            "en": "Link to the full CSV export of the selected report."
          }
        }
      ],
      "notes": [
        {
          "ru": "week — последние 7 календарных дней, включая сегодня, по Москве.",
          "en": "week covers the last 7 calendar days including today, in Moscow time."
        },
        {
          "ru": "Итоги за период не зависят от выбранной страницы.",
          "en": "Period totals are independent of the selected page."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "Missing service_id",
          "description": {
            "ru": "Не передан номер услуги.",
            "en": "The service ID is required."
          }
        },
        {
          "status": 404,
          "code": "Invalid service_id",
          "description": {
            "ru": "Услуга не найдена.",
            "en": "Service not found."
          }
        },
        {
          "status": 400,
          "code": "Invalid statistics parameters",
          "description": {
            "ru": "Некорректные параметры периода или страниц.",
            "en": "Invalid period or pagination parameters."
          }
        },
        {
          "status": 500,
          "code": "Server error",
          "description": {
            "ru": "Временная ошибка сервера.",
            "en": "Temporary server error."
          }
        }
      ]
    },
    {
      "id": "client-csv",
      "group": "analytics",
      "method": "GET",
      "path": "/userstatic/api/stats_service.php?export=csv",
      "title": {
        "ru": "Экспорт истории услуги",
        "en": "Export service history"
      },
      "summary": {
        "ru": "Скачать все выходы услуги за выбранный период в CSV.",
        "en": "Download all airplays for a service and period as CSV."
      },
      "auth": "service",
      "run": false,
      "format": "none",
      "query": {
        "service_id": "SERVICE_ID",
        "mode": "week",
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "service_id",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Номер вашей услуги; передавайте строкой.",
            "en": "Your service ID, sent as a string."
          }
        },
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "ru — русский; остальные языки используют EN.",
            "en": "ru selects Russian; other languages use EN."
          },
          "default": "ru"
        },
        {
          "name": "mode",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Период отчёта.",
            "en": "Report period."
          },
          "default": "today",
          "enum": [
            "today",
            "yesterday",
            "week",
            "date",
            "months",
            "year"
          ]
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Дата YYYY-MM-DD для mode=date.",
            "en": "Date as YYYY-MM-DD for mode=date."
          }
        },
        {
          "name": "m1",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Месяц YYYY-MM для mode=months.",
            "en": "Month as YYYY-MM for mode=months."
          }
        },
        {
          "name": "year",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Год для mode=year.",
            "en": "Year for mode=year."
          }
        },
        {
          "name": "as_of",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Верхняя граница времени YYYY-MM-DD HH:MM:SS из ссылки отчёта.",
            "en": "Airplay time cutoff as YYYY-MM-DD HH:MM:SS from the report link."
          }
        }
      ],
      "response_kind": "csv",
      "response": {},
      "fields": [
        {
          "name": "track_name",
          "type": "CSV column",
          "description": {
            "ru": "Название композиции.",
            "en": "Track display name."
          }
        },
        {
          "name": "stream",
          "type": "CSV column",
          "description": {
            "ru": "Код потока.",
            "en": "Stream code."
          }
        },
        {
          "name": "played_at",
          "type": "CSV column",
          "description": {
            "ru": "Время выхода в эфир.",
            "en": "Airplay time."
          }
        },
        {
          "name": "period_play_count",
          "type": "CSV column",
          "description": {
            "ru": "Выходов этой композиции за период.",
            "en": "Airplay count for this track within the period."
          }
        },
        {
          "name": "likes, dislikes, stars, reach",
          "type": "CSV columns",
          "description": {
            "ru": "Реакции и охват.",
            "en": "Reactions and reach."
          }
        }
      ],
      "notes": [
        {
          "ru": "Используйте готовую ссылку links.details_csv из аналитики услуги.",
          "en": "Use the ready-made links.details_csv URL from service analytics."
        },
        {
          "ru": "Ответ — CSV в UTF-8 с BOM и разделителем «;», без ограничения одной страницей.",
          "en": "The response is UTF-8 CSV with a BOM and semicolon separator, without a single-page limit."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "Missing service_id",
          "description": {
            "ru": "Не передан номер услуги.",
            "en": "The service ID is required."
          }
        },
        {
          "status": 404,
          "code": "Invalid service_id",
          "description": {
            "ru": "Услуга не найдена.",
            "en": "Service not found."
          }
        },
        {
          "status": 500,
          "code": "Server error",
          "description": {
            "ru": "Временная ошибка сервера.",
            "en": "Temporary server error."
          }
        }
      ]
    },
    {
      "id": "audience-day",
      "group": "analytics",
      "method": "GET",
      "path": "/api_static.php?action=day",
      "title": {
        "ru": "Аудитория за день",
        "en": "Daily audience"
      },
      "summary": {
        "ru": "Почасовой отчёт аудитории по потокам за выбранную дату.",
        "en": "Hourly audience report by stream for a selected date."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык названий в отчёте.",
            "en": "Language of report labels."
          },
          "default": "ru",
          "enum": [
            "ru",
            "en"
          ]
        },
        {
          "name": "date",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Дата YYYY-MM-DD; по умолчанию сегодня.",
            "en": "Date as YYYY-MM-DD; defaults to today."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "from_cache": true,
        "cached_at": "2026-11-20 12:00:00",
        "timezone": "Europe/Moscow",
        "lang": "ru",
        "action": "day",
        "data": [
          {
            "stat_date": "2026-11-20",
            "stat_hour": 12,
            "stream_slug": "top",
            "stream_name": "Топ",
            "listeners": 120
          }
        ]
      },
      "fields": [
        {
          "name": "data",
          "type": "array",
          "description": {
            "ru": "Сохранённые значения аудитории по потокам.",
            "en": "Cached audience values by stream."
          }
        },
        {
          "name": "cached_at",
          "type": "string | null",
          "description": {
            "ru": "Время обновления отчёта.",
            "en": "Time when the report was updated."
          }
        },
        {
          "name": "summary.total_listeners",
          "type": "integer",
          "description": {
            "ru": "Суммарное значение за выбранный период.",
            "en": "Aggregate value for the selected period."
          }
        },
        {
          "name": "summary.unique_listeners",
          "type": "integer",
          "description": {
            "ru": "Расчётная оценка уникальной аудитории.",
            "en": "Estimated unique audience."
          }
        }
      ],
      "notes": [
        {
          "ru": "Отчёт использует сохранённые данные аудитории.",
          "en": "The report uses cached audience data."
        },
        {
          "ru": "unique_listeners — оценка, а не точное число отдельных людей.",
          "en": "unique_listeners is an estimate, not an exact count of individual people."
        }
      ],
      "errors": [
        {
          "status": 200,
          "code": "ok=false",
          "description": {
            "ru": "Сохранённый отчёт отсутствует или недоступен.",
            "en": "The cached report is missing or unavailable."
          }
        }
      ]
    },
    {
      "id": "audience-month",
      "group": "analytics",
      "method": "GET",
      "path": "/api_static.php?action=month",
      "title": {
        "ru": "Аудитория за месяц",
        "en": "Monthly audience"
      },
      "summary": {
        "ru": "Ежедневные показатели аудитории по потокам за месяц.",
        "en": "Daily audience values by stream for a month."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык названий в отчёте.",
            "en": "Language of report labels."
          },
          "default": "ru",
          "enum": [
            "ru",
            "en"
          ]
        },
        {
          "name": "month",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Месяц YYYY-MM; по умолчанию текущий.",
            "en": "Month as YYYY-MM; defaults to the current month."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "from_cache": true,
        "cached_at": "2026-11-20 12:00:00",
        "timezone": "Europe/Moscow",
        "lang": "ru",
        "action": "month",
        "data": [
          {
            "date": "2026-11-20",
            "stream_slug": "top",
            "stream_name": "Топ",
            "listeners": 120
          }
        ]
      },
      "fields": [
        {
          "name": "data",
          "type": "array",
          "description": {
            "ru": "Сохранённые значения аудитории по потокам.",
            "en": "Cached audience values by stream."
          }
        },
        {
          "name": "cached_at",
          "type": "string | null",
          "description": {
            "ru": "Время обновления отчёта.",
            "en": "Time when the report was updated."
          }
        },
        {
          "name": "summary.total_listeners",
          "type": "integer",
          "description": {
            "ru": "Суммарное значение за выбранный период.",
            "en": "Aggregate value for the selected period."
          }
        },
        {
          "name": "summary.unique_listeners",
          "type": "integer",
          "description": {
            "ru": "Расчётная оценка уникальной аудитории.",
            "en": "Estimated unique audience."
          }
        }
      ],
      "notes": [
        {
          "ru": "Отчёт использует сохранённые данные аудитории.",
          "en": "The report uses cached audience data."
        },
        {
          "ru": "unique_listeners — оценка, а не точное число отдельных людей.",
          "en": "unique_listeners is an estimate, not an exact count of individual people."
        }
      ],
      "errors": [
        {
          "status": 200,
          "code": "ok=false",
          "description": {
            "ru": "Сохранённый отчёт отсутствует или недоступен.",
            "en": "The cached report is missing or unavailable."
          }
        }
      ]
    },
    {
      "id": "audience-year",
      "group": "analytics",
      "method": "GET",
      "path": "/api_static.php?action=year",
      "title": {
        "ru": "Аудитория за год",
        "en": "Yearly audience"
      },
      "summary": {
        "ru": "Показатели аудитории за один год или диапазон лет.",
        "en": "Audience values for one year or a range of years."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык названий в отчёте.",
            "en": "Language of report labels."
          },
          "default": "ru",
          "enum": [
            "ru",
            "en"
          ]
        },
        {
          "name": "year",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Год; по умолчанию текущий.",
            "en": "Year; defaults to the current year."
          }
        },
        {
          "name": "year_from",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Первый год диапазона.",
            "en": "First year in the range."
          }
        },
        {
          "name": "year_to",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Последний год диапазона.",
            "en": "Last year in the range."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "from_cache": true,
        "cached_at": "2026-11-20 12:00:00",
        "timezone": "Europe/Moscow",
        "lang": "ru",
        "action": "year",
        "data": [
          {
            "year": 2026,
            "month": "2026-11",
            "stream_slug": "top",
            "stream_name": "Топ",
            "listeners": 120
          }
        ]
      },
      "fields": [
        {
          "name": "data",
          "type": "array",
          "description": {
            "ru": "Сохранённые значения аудитории по потокам.",
            "en": "Cached audience values by stream."
          }
        },
        {
          "name": "cached_at",
          "type": "string | null",
          "description": {
            "ru": "Время обновления отчёта.",
            "en": "Time when the report was updated."
          }
        },
        {
          "name": "summary.total_listeners",
          "type": "integer",
          "description": {
            "ru": "Суммарное значение за выбранный период.",
            "en": "Aggregate value for the selected period."
          }
        },
        {
          "name": "summary.unique_listeners",
          "type": "integer",
          "description": {
            "ru": "Расчётная оценка уникальной аудитории.",
            "en": "Estimated unique audience."
          }
        }
      ],
      "notes": [
        {
          "ru": "Отчёт использует сохранённые данные аудитории.",
          "en": "The report uses cached audience data."
        },
        {
          "ru": "unique_listeners — оценка, а не точное число отдельных людей.",
          "en": "unique_listeners is an estimate, not an exact count of individual people."
        },
        {
          "ru": "Один год разбивается по месяцам, диапазон — по годам.",
          "en": "A single year is grouped by month; a range is grouped by year."
        }
      ],
      "errors": [
        {
          "status": 200,
          "code": "ok=false",
          "description": {
            "ru": "Сохранённый отчёт отсутствует или недоступен.",
            "en": "The cached report is missing or unavailable."
          }
        }
      ]
    },
    {
      "id": "audience-periods",
      "group": "analytics",
      "method": "GET",
      "path": "/api_static.php?action=periods",
      "title": {
        "ru": "Доступные периоды",
        "en": "Available periods"
      },
      "summary": {
        "ru": "Месяцы и годы, для которых доступны сохранённые отчёты аудитории.",
        "en": "Months and years with cached audience reports."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык названий в отчёте.",
            "en": "Language of report labels."
          },
          "default": "ru",
          "enum": [
            "ru",
            "en"
          ]
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "from_cache": true,
        "action": "periods",
        "data": {
          "months": [
            {
              "value": "2026-11",
              "label": "Ноябрь 2026",
              "year": 2026,
              "month": 11
            }
          ],
          "years": [
            {
              "value": "2026",
              "label": "2026"
            }
          ],
          "latest_month": "2026-11",
          "latest_year": "2026"
        }
      },
      "fields": [
        {
          "name": "data.months",
          "type": "array",
          "description": {
            "ru": "Доступные месяцы с кодами и подписями.",
            "en": "Available months with values and labels."
          }
        },
        {
          "name": "data.years",
          "type": "array",
          "description": {
            "ru": "Доступные годы.",
            "en": "Available years."
          }
        },
        {
          "name": "data.latest_month",
          "type": "string | null",
          "description": {
            "ru": "Последний доступный месяц YYYY-MM.",
            "en": "Latest available month as YYYY-MM."
          }
        },
        {
          "name": "data.latest_year",
          "type": "string | null",
          "description": {
            "ru": "Последний доступный год.",
            "en": "Latest available year."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 200,
          "code": "ok=false",
          "description": {
            "ru": "Сохранённый отчёт отсутствует или недоступен.",
            "en": "The cached report is missing or unavailable."
          }
        }
      ]
    },
    {
      "id": "audience-countries",
      "group": "analytics",
      "method": "GET",
      "path": "/api_static.php?action=countries",
      "title": {
        "ru": "География аудитории",
        "en": "Audience geography"
      },
      "summary": {
        "ru": "До 12 стран по средней доле аудитории за период.",
        "en": "Up to 12 countries by average audience share for a period."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {
        "lang": "ru"
      },
      "body": {},
      "params": [
        {
          "name": "lang",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Язык названий в отчёте.",
            "en": "Language of report labels."
          },
          "default": "ru",
          "enum": [
            "ru",
            "en"
          ]
        },
        {
          "name": "month",
          "in": "query",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Месяц YYYY-MM; имеет приоритет над годом.",
            "en": "Month as YYYY-MM; takes precedence over the year."
          }
        },
        {
          "name": "year",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Год; по умолчанию текущий.",
            "en": "Year; defaults to the current year."
          }
        },
        {
          "name": "year_from",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Первый год диапазона.",
            "en": "First year in the range."
          }
        },
        {
          "name": "year_to",
          "in": "query",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Последний год диапазона.",
            "en": "Last year in the range."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "from_cache": true,
        "action": "countries",
        "data": [
          {
            "country": "Россия",
            "percent": 60.2
          }
        ],
        "period": {
          "month_from": "2026-11",
          "month_to": "2026-11",
          "year_from": 2026,
          "year_to": 2026
        }
      },
      "fields": [
        {
          "name": "data[].country",
          "type": "string",
          "description": {
            "ru": "Название страны.",
            "en": "Country name."
          }
        },
        {
          "name": "data[].percent",
          "type": "number",
          "description": {
            "ru": "Средняя доля аудитории в процентах.",
            "en": "Average audience share as a percentage."
          }
        },
        {
          "name": "period",
          "type": "object",
          "description": {
            "ru": "Границы выбранного периода.",
            "en": "Selected period boundaries."
          }
        }
      ],
      "notes": [
        {
          "ru": "Доли рассчитаны по сохранённым отчётам и отсортированы по убыванию.",
          "en": "Shares are calculated from cached reports and sorted in descending order."
        }
      ],
      "errors": [
        {
          "status": 200,
          "code": "ok=false",
          "description": {
            "ru": "Сохранённый отчёт отсутствует или недоступен.",
            "en": "The cached report is missing or unavailable."
          }
        }
      ]
    },
    {
      "id": "client-check-service",
      "group": "auth",
      "method": "POST",
      "path": "/api.auth.client.php?action=check_service",
      "title": {
        "ru": "Проверить услугу",
        "en": "Check a service"
      },
      "summary": {
        "ru": "Узнать, назначен ли пароль для указанной услуги.",
        "en": "Check whether a password has been set for a service."
      },
      "auth": "public",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "service_id": "SERVICE_ID"
      },
      "params": [
        {
          "name": "service_id",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Номер услуги, до 64 символов.",
            "en": "Service ID, up to 64 characters."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "service_id": "SERVICE_ID",
          "password_set": true
        }
      },
      "fields": [
        {
          "name": "data.password_set",
          "type": "boolean",
          "description": {
            "ru": "true — пароль уже есть, false — требуется первый пароль.",
            "en": "true means a password exists; false means initial setup is needed."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 400,
          "code": "missing_credentials",
          "description": {
            "ru": "Укажите необходимые данные для входа.",
            "en": "Provide the required credentials."
          }
        },
        {
          "status": 404,
          "code": "service_not_found",
          "description": {
            "ru": "Услуга не найдена.",
            "en": "Service not found."
          }
        },
        {
          "status": 403,
          "code": "service_status_deleted",
          "description": {
            "ru": "Услуга удалена.",
            "en": "The service has been deleted."
          }
        }
      ]
    },
    {
      "id": "client-login",
      "group": "auth",
      "method": "POST",
      "path": "/api.auth.client.php?action=login",
      "title": {
        "ru": "Вход клиента",
        "en": "Client sign-in"
      },
      "summary": {
        "ru": "Получить клиентский токен по номеру услуги и паролю.",
        "en": "Get a client token using a service ID and password."
      },
      "auth": "public",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "service_id": "SERVICE_ID",
        "password": "PASSWORD"
      },
      "params": [
        {
          "name": "service_id",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Номер услуги, до 64 символов.",
            "en": "Service ID, up to 64 characters."
          }
        },
        {
          "name": "password",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Пароль клиента.",
            "en": "Client password."
          }
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "UUID ранее зарегистрированного push-устройства.",
            "en": "UUID of a previously registered push device."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "login",
          "token": {
            "access_token": "ACCESS_TOKEN",
            "token_type": "Bearer",
            "expires_at": "2026-12-20 12:00:00",
            "expires_in": 2592000
          },
          "profile_api": "api.profile.client.php",
          "user": {
            "id": 1001,
            "name": "Client",
            "service_id": "SERVICE_ID",
            "status": "active"
          }
        }
      },
      "fields": [
        {
          "name": "data.token.access_token",
          "type": "string",
          "description": {
            "ru": "Токен для заголовка Authorization: Bearer.",
            "en": "Token for the Authorization: Bearer header."
          }
        },
        {
          "name": "data.token.expires_at",
          "type": "string",
          "description": {
            "ru": "Срок действия, указанный при выдаче токена.",
            "en": "Expiration time returned when the token is issued."
          }
        },
        {
          "name": "data.user",
          "type": "object",
          "description": {
            "ru": "Профиль клиента и параметры услуги.",
            "en": "Client profile and service details."
          }
        }
      ],
      "notes": [
        {
          "ru": "Используйте полученный токен для клиентского профиля и исполнителей.",
          "en": "Use the returned token for client profile and artist endpoints."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "missing_credentials",
          "description": {
            "ru": "Укажите необходимые данные для входа.",
            "en": "Provide the required credentials."
          }
        },
        {
          "status": 401,
          "code": "invalid_credentials",
          "description": {
            "ru": "Номер услуги или пароль не принят.",
            "en": "The service ID or password was not accepted."
          }
        },
        {
          "status": 409,
          "code": "password_setup_required",
          "description": {
            "ru": "Сначала создайте пароль услуги.",
            "en": "Create the service password first."
          }
        },
        {
          "status": 403,
          "code": "service_status_deleted",
          "description": {
            "ru": "Услуга удалена.",
            "en": "The service has been deleted."
          }
        }
      ]
    },
    {
      "id": "client-create-password",
      "group": "auth",
      "method": "POST",
      "path": "/api.auth.client.php?action=create_password",
      "title": {
        "ru": "Первый пароль клиента",
        "en": "Set the first client password"
      },
      "summary": {
        "ru": "Назначить первый пароль услуги и получить клиентский токен.",
        "en": "Set the service’s first password and receive a client token."
      },
      "auth": "public",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "service_id": "SERVICE_ID",
        "password": "NEW_PASSWORD"
      },
      "params": [
        {
          "name": "service_id",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Номер услуги, до 64 символов.",
            "en": "Service ID, up to 64 characters."
          }
        },
        {
          "name": "password",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "От 8 до 128 символов.",
            "en": "From 8 to 128 characters."
          }
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "UUID ранее зарегистрированного push-устройства.",
            "en": "UUID of a previously registered push device."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "password_created",
          "token": {
            "access_token": "ACCESS_TOKEN",
            "token_type": "Bearer",
            "expires_at": "2026-12-20 12:00:00",
            "expires_in": 2592000
          },
          "profile_api": "api.profile.client.php",
          "user": {
            "id": 1001,
            "name": "Client",
            "service_id": "SERVICE_ID",
            "status": "active"
          }
        }
      },
      "fields": [
        {
          "name": "data.token.access_token",
          "type": "string",
          "description": {
            "ru": "Токен для заголовка Authorization: Bearer.",
            "en": "Token for the Authorization: Bearer header."
          }
        },
        {
          "name": "data.token.expires_at",
          "type": "string",
          "description": {
            "ru": "Срок действия, указанный при выдаче токена.",
            "en": "Expiration time returned when the token is issued."
          }
        },
        {
          "name": "data.user",
          "type": "object",
          "description": {
            "ru": "Профиль клиента и параметры услуги.",
            "en": "Client profile and service details."
          }
        }
      ],
      "notes": [
        {
          "ru": "Применяется только к услуге, у которой ещё нет пароля.",
          "en": "Available only for a service that does not have a password yet."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "missing_credentials",
          "description": {
            "ru": "Укажите необходимые данные для входа.",
            "en": "Provide the required credentials."
          }
        },
        {
          "status": 401,
          "code": "invalid_credentials",
          "description": {
            "ru": "Номер услуги или пароль не принят.",
            "en": "The service ID or password was not accepted."
          }
        },
        {
          "status": 403,
          "code": "service_status_deleted",
          "description": {
            "ru": "Услуга удалена.",
            "en": "The service has been deleted."
          }
        },
        {
          "status": 409,
          "code": "password_already_set",
          "description": {
            "ru": "Пароль уже назначен.",
            "en": "A password has already been set."
          }
        },
        {
          "status": 422,
          "code": "password_too_short",
          "description": {
            "ru": "Пароль короче 8 символов.",
            "en": "The password is shorter than 8 characters."
          }
        },
        {
          "status": 422,
          "code": "password_too_long",
          "description": {
            "ru": "Пароль длиннее 128 символов.",
            "en": "The password is longer than 128 characters."
          }
        }
      ]
    },
    {
      "id": "client-logout",
      "group": "auth",
      "method": "POST",
      "path": "/api.auth.client.php?action=logout",
      "title": {
        "ru": "Выход клиента",
        "en": "Client sign-out"
      },
      "summary": {
        "ru": "Отозвать переданный токен доступа.",
        "en": "Revoke the supplied access token."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Устаревший необязательный параметр, игнорируется. Устройство определяется по push_device_id отзываемой сессии.",
            "en": "Legacy optional parameter; ignored. The device is identified by the revoked session’s push_device_id."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "logged_out": true
        }
      },
      "fields": [
        {
          "name": "data.logged_out",
          "type": "boolean",
          "description": {
            "ru": "true — выход выполнен.",
            "en": "true means sign-out is complete."
          }
        }
      ],
      "notes": [
        {
          "ru": "Выход отзывает переданный Bearer и снимает только его привязку к устройству, если текущий владелец ещё совпадает. Переданный UUID не выбирает устройство; прежняя сессия не снимает привязку нового владельца.",
          "en": "Sign-out revokes the supplied Bearer and detaches only its device binding while the current owner still matches. A posted UUID does not select the device; an old session cannot detach a new owner."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        }
      ]
    },
    {
      "id": "listener-logout",
      "group": "auth",
      "method": "POST",
      "path": "/api.auth.app.php?action=logout",
      "title": {
        "ru": "Выход слушателя",
        "en": "Listener sign-out"
      },
      "summary": {
        "ru": "Отозвать переданный токен доступа.",
        "en": "Revoke the supplied access token."
      },
      "auth": "bearer-app",
      "run": false,
      "format": "json",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен слушателя.",
            "en": "Bearer ACCESS_TOKEN — a listener token."
          }
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Устаревший необязательный параметр, игнорируется. Устройство определяется по push_device_id отзываемой сессии.",
            "en": "Legacy optional parameter; ignored. The device is identified by the revoked session’s push_device_id."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "logged_out": true
        }
      },
      "fields": [
        {
          "name": "data.logged_out",
          "type": "boolean",
          "description": {
            "ru": "true — выход выполнен.",
            "en": "true means sign-out is complete."
          }
        }
      ],
      "notes": [
        {
          "ru": "Выход отзывает переданный Bearer и снимает только его привязку к устройству, если текущий владелец ещё совпадает. Переданный UUID не выбирает устройство; прежняя сессия не снимает привязку нового владельца.",
          "en": "Sign-out revokes the supplied Bearer and detaches only its device binding while the current owner still matches. A posted UUID does not select the device; an old session cannot detach a new owner."
        },
        {
          "ru": "Выход слушателя не изменяет устройство, привязанное к клиенту через user_id.",
          "en": "Listener sign-out does not modify a device bound to a client through user_id."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        }
      ]
    },
    {
      "id": "profile-app",
      "group": "profiles",
      "method": "GET",
      "path": "/api.profile.app.php?action=me",
      "title": {
        "ru": "Профиль слушателя",
        "en": "Listener profile"
      },
      "summary": {
        "ru": "Получить профиль владельца токена слушателя.",
        "en": "Get the profile of the listener token owner."
      },
      "auth": "bearer-app",
      "run": false,
      "format": "none",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен слушателя.",
            "en": "Bearer ACCESS_TOKEN — a listener token."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "id": 1001,
          "name": "Listener",
          "last_name": null,
          "email": null,
          "platform": "ios",
          "language_code": "ru",
          "country_code": "RU",
          "status": "active"
        }
      },
      "fields": [
        {
          "name": "data",
          "type": "object",
          "description": {
            "ru": "Профиль владельца токена слушателя.",
            "en": "Profile of the listener token owner."
          }
        },
        {
          "name": "data.language_code",
          "type": "string | null",
          "description": {
            "ru": "Язык профиля.",
            "en": "Profile language."
          }
        },
        {
          "name": "data.country_code",
          "type": "string | null",
          "description": {
            "ru": "Код страны.",
            "en": "Country code."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 404,
          "code": "user_not_found",
          "description": {
            "ru": "Аккаунт не найден.",
            "en": "Account not found."
          }
        }
      ]
    },
    {
      "id": "profile-app-update",
      "group": "profiles",
      "method": "POST",
      "path": "/api.profile.app.php?action=update",
      "title": {
        "ru": "Изменить профиль слушателя",
        "en": "Update listener profile"
      },
      "summary": {
        "ru": "Сохранить имя, язык и страну своего профиля.",
        "en": "Save your profile name, language and country."
      },
      "auth": "bearer-app",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "name": "Listener",
        "language_code": "ru",
        "country_code": "RU"
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен слушателя.",
            "en": "Bearer ACCESS_TOKEN — a listener token."
          }
        },
        {
          "name": "name",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя, до 128 символов.",
            "en": "First name, up to 128 characters."
          }
        },
        {
          "name": "last_name",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Фамилия, до 128 символов.",
            "en": "Last name, up to 128 characters."
          }
        },
        {
          "name": "language_code",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код языка; локаль сокращается до языка.",
            "en": "Language code; a locale is reduced to its language."
          }
        },
        {
          "name": "country_code",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Код страны из 2–3 латинских букв.",
            "en": "Country code with 2–3 Latin letters."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "id": 1001,
          "name": "Listener",
          "last_name": null,
          "email": null,
          "platform": "ios",
          "language_code": "ru",
          "country_code": "RU",
          "status": "active"
        }
      },
      "fields": [
        {
          "name": "data",
          "type": "object",
          "description": {
            "ru": "Профиль владельца токена слушателя.",
            "en": "Profile of the listener token owner."
          }
        },
        {
          "name": "data.language_code",
          "type": "string | null",
          "description": {
            "ru": "Язык профиля.",
            "en": "Profile language."
          }
        },
        {
          "name": "data.country_code",
          "type": "string | null",
          "description": {
            "ru": "Код страны.",
            "en": "Country code."
          }
        }
      ],
      "notes": [
        {
          "ru": "Неуказанные и пустые необязательные поля сохраняют прежние значения.",
          "en": "Omitted and empty optional fields retain their previous values."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 404,
          "code": "user_not_found",
          "description": {
            "ru": "Аккаунт не найден.",
            "en": "Account not found."
          }
        }
      ]
    },
    {
      "id": "profile-client",
      "group": "profiles",
      "method": "GET",
      "path": "/api.profile.client.php?action=me",
      "title": {
        "ru": "Профиль клиента",
        "en": "Client profile"
      },
      "summary": {
        "ru": "Получить свой профиль и параметры услуги.",
        "en": "Get your profile and service details."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "none",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "id": 1001,
          "name": "Client",
          "service_id": "SERVICE_ID",
          "status": "active",
          "service_name": "Rotation",
          "service_start": "2026-11-01",
          "service_end": "2026-12-01",
          "track_limit": 3
        }
      },
      "fields": [
        {
          "name": "data",
          "type": "object",
          "description": {
            "ru": "Профиль владельца клиентского токена.",
            "en": "Profile of the client token owner."
          }
        },
        {
          "name": "data.service_id",
          "type": "string",
          "description": {
            "ru": "Номер услуги.",
            "en": "Service ID."
          }
        },
        {
          "name": "data.streams",
          "type": "array",
          "description": {
            "ru": "Потоки, связанные с услугой.",
            "en": "Streams associated with the service."
          }
        },
        {
          "name": "data.service_end",
          "type": "string | null",
          "description": {
            "ru": "Дата окончания услуги.",
            "en": "Service end date."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 404,
          "code": "user_not_found",
          "description": {
            "ru": "Аккаунт не найден.",
            "en": "Account not found."
          }
        }
      ]
    },
    {
      "id": "profile-client-update",
      "group": "profiles",
      "method": "POST",
      "path": "/api.profile.client.php?action=update",
      "title": {
        "ru": "Изменить профиль клиента",
        "en": "Update client profile"
      },
      "summary": {
        "ru": "Сохранить имя владельца клиентского аккаунта.",
        "en": "Save the name of the client account owner."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "name": "Client"
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "name",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Имя, до 128 символов.",
            "en": "Name, up to 128 characters."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "id": 1001,
          "name": "Client",
          "service_id": "SERVICE_ID",
          "status": "active",
          "service_name": "Rotation",
          "service_start": "2026-11-01",
          "service_end": "2026-12-01",
          "track_limit": 3
        }
      },
      "fields": [
        {
          "name": "data",
          "type": "object",
          "description": {
            "ru": "Профиль владельца клиентского токена.",
            "en": "Profile of the client token owner."
          }
        },
        {
          "name": "data.service_id",
          "type": "string",
          "description": {
            "ru": "Номер услуги.",
            "en": "Service ID."
          }
        },
        {
          "name": "data.streams",
          "type": "array",
          "description": {
            "ru": "Потоки, связанные с услугой.",
            "en": "Streams associated with the service."
          }
        },
        {
          "name": "data.service_end",
          "type": "string | null",
          "description": {
            "ru": "Дата окончания услуги.",
            "en": "Service end date."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 400,
          "code": "missing_name",
          "description": {
            "ru": "Укажите имя.",
            "en": "A name is required."
          }
        },
        {
          "status": 404,
          "code": "user_not_found",
          "description": {
            "ru": "Аккаунт не найден.",
            "en": "Account not found."
          }
        }
      ]
    },
    {
      "id": "artists-list",
      "group": "profiles",
      "method": "GET",
      "path": "/api.client_artists.php?action=list",
      "title": {
        "ru": "Исполнители клиента",
        "en": "Client artists"
      },
      "summary": {
        "ru": "Получить исполнителей, связанных с вашим клиентским аккаунтом.",
        "en": "Get the artists associated with your client account."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "none",
      "query": {},
      "body": {},
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "items": [
            {
              "id": 2001,
              "artist_name_ru": "Имя исполнителя",
              "artist_name_en": "Artist name",
              "is_active": 1,
              "notify_enabled": 1,
              "cooldown_minutes": 10
            }
          ],
          "total": 1
        }
      },
      "fields": [
        {
          "name": "data.items",
          "type": "array",
          "description": {
            "ru": "Исполнители: активные выше, затем новые.",
            "en": "Artists with active records first, then newest first."
          }
        },
        {
          "name": "data.total",
          "type": "integer",
          "description": {
            "ru": "Общее количество записей.",
            "en": "Total record count."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        }
      ]
    },
    {
      "id": "artists-add",
      "group": "profiles",
      "method": "POST",
      "path": "/api.client_artists.php?action=add",
      "title": {
        "ru": "Добавить исполнителя",
        "en": "Add an artist"
      },
      "summary": {
        "ru": "Добавить исполнителя и настройки его уведомлений.",
        "en": "Add an artist and configure their notifications."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "artist_name_ru": "Имя исполнителя",
        "artist_name_en": "Artist name",
        "notify_enabled": 1,
        "cooldown_minutes": 10
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "artist_name_ru",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя на русском, до 255 символов.",
            "en": "Russian artist name, up to 255 characters."
          }
        },
        {
          "name": "artist_name_en",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя латиницей, до 255 символов.",
            "en": "Artist name in Latin script, up to 255 characters."
          }
        },
        {
          "name": "is_active",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Активность записи.",
            "en": "Whether the record is active."
          },
          "default": 1,
          "enum": [
            0,
            1
          ]
        },
        {
          "name": "notify_enabled",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Разрешение уведомлений.",
            "en": "Whether notifications are enabled."
          },
          "default": 1,
          "enum": [
            0,
            1
          ]
        },
        {
          "name": "cooldown_minutes",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Пауза между уведомлениями: от 1 до 1440 минут.",
            "en": "Interval between notifications, from 1 to 1,440 minutes."
          },
          "default": 10
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "add",
          "artist": {
            "id": 2001,
            "artist_name_ru": "Имя исполнителя",
            "artist_name_en": "Artist name",
            "is_active": 1,
            "notify_enabled": 1,
            "cooldown_minutes": 10
          }
        }
      },
      "fields": [
        {
          "name": "data.artist",
          "type": "object",
          "description": {
            "ru": "Сохранённая запись исполнителя.",
            "en": "Saved artist record."
          }
        },
        {
          "name": "data.artist.is_active",
          "type": "integer",
          "description": {
            "ru": "1 — запись активна; 0 — выключена.",
            "en": "1 means the record is active; 0 means disabled."
          }
        },
        {
          "name": "data.artist.notify_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — уведомления разрешены; 0 — выключены.",
            "en": "1 enables notifications; 0 disables them."
          }
        },
        {
          "name": "data.artist.cooldown_minutes",
          "type": "integer",
          "description": {
            "ru": "Минимальная пауза уведомлений в минутах.",
            "en": "Minimum notification interval in minutes."
          }
        }
      ],
      "notes": [
        {
          "ru": "Обязательно хотя бы одно имя: artist_name_ru или artist_name_en.",
          "en": "At least one name is required: artist_name_ru or artist_name_en."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 400,
          "code": "missing_artist_name",
          "description": {
            "ru": "Укажите хотя бы одно имя исполнителя.",
            "en": "Provide at least one artist name."
          }
        },
        {
          "status": 409,
          "code": "artist_already_exists",
          "description": {
            "ru": "Такой исполнитель уже добавлен.",
            "en": "The artist has already been added."
          }
        }
      ]
    },
    {
      "id": "artists-update",
      "group": "profiles",
      "method": "POST",
      "path": "/api.client_artists.php?action=update",
      "title": {
        "ru": "Изменить исполнителя",
        "en": "Update an artist"
      },
      "summary": {
        "ru": "Обновить имена и настройки своего исполнителя.",
        "en": "Update your artist’s names and settings."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "id": 2001,
        "notify_enabled": 0
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "id",
          "in": "body",
          "type": "integer",
          "required": true,
          "description": {
            "ru": "ID записи исполнителя в вашем аккаунте.",
            "en": "Artist record ID in your account."
          }
        },
        {
          "name": "artist_name_ru",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя на русском, до 255 символов.",
            "en": "Russian artist name, up to 255 characters."
          }
        },
        {
          "name": "artist_name_en",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Имя латиницей, до 255 символов.",
            "en": "Artist name in Latin script, up to 255 characters."
          }
        },
        {
          "name": "is_active",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Активность записи.",
            "en": "Whether the record is active."
          },
          "enum": [
            0,
            1
          ]
        },
        {
          "name": "notify_enabled",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Разрешение уведомлений.",
            "en": "Whether notifications are enabled."
          },
          "enum": [
            0,
            1
          ]
        },
        {
          "name": "cooldown_minutes",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Пауза между уведомлениями: от 1 до 1440 минут.",
            "en": "Interval between notifications, from 1 to 1,440 minutes."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "update",
          "artist": {
            "id": 2001,
            "artist_name_ru": "Имя исполнителя",
            "artist_name_en": "Artist name",
            "is_active": 1,
            "notify_enabled": 0,
            "cooldown_minutes": 10
          }
        }
      },
      "fields": [
        {
          "name": "data.artist",
          "type": "object",
          "description": {
            "ru": "Сохранённая запись исполнителя.",
            "en": "Saved artist record."
          }
        },
        {
          "name": "data.artist.is_active",
          "type": "integer",
          "description": {
            "ru": "1 — запись активна; 0 — выключена.",
            "en": "1 means the record is active; 0 means disabled."
          }
        },
        {
          "name": "data.artist.notify_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — уведомления разрешены; 0 — выключены.",
            "en": "1 enables notifications; 0 disables them."
          }
        },
        {
          "name": "data.artist.cooldown_minutes",
          "type": "integer",
          "description": {
            "ru": "Минимальная пауза уведомлений в минутах.",
            "en": "Minimum notification interval in minutes."
          }
        }
      ],
      "notes": [
        {
          "ru": "Неуказанные поля сохраняются; хотя бы одно имя должно остаться заполненным.",
          "en": "Omitted fields are retained; at least one name must remain filled in."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 400,
          "code": "missing_artist_id",
          "description": {
            "ru": "Не передан ID исполнителя.",
            "en": "The artist ID is required."
          }
        },
        {
          "status": 404,
          "code": "artist_not_found",
          "description": {
            "ru": "Исполнитель не найден в вашем аккаунте.",
            "en": "The artist was not found in your account."
          }
        },
        {
          "status": 400,
          "code": "missing_artist_name",
          "description": {
            "ru": "Укажите хотя бы одно имя исполнителя.",
            "en": "Provide at least one artist name."
          }
        },
        {
          "status": 409,
          "code": "artist_already_exists",
          "description": {
            "ru": "Такой исполнитель уже добавлен.",
            "en": "The artist has already been added."
          }
        }
      ]
    },
    {
      "id": "artists-toggle",
      "group": "profiles",
      "method": "POST",
      "path": "/api.client_artists.php?action=toggle",
      "title": {
        "ru": "Настройка исполнителя",
        "en": "Set an artist flag"
      },
      "summary": {
        "ru": "Изменить активность исполнителя или разрешение уведомлений.",
        "en": "Change an artist’s active state or notification setting."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "id": 2001,
        "field": "notify_enabled",
        "value": 0
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "id",
          "in": "body",
          "type": "integer",
          "required": true,
          "description": {
            "ru": "ID записи исполнителя в вашем аккаунте.",
            "en": "Artist record ID in your account."
          }
        },
        {
          "name": "field",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Настройка для изменения.",
            "en": "Setting to change."
          },
          "default": "is_active",
          "enum": [
            "is_active",
            "notify_enabled"
          ]
        },
        {
          "name": "value",
          "in": "body",
          "type": "integer",
          "required": false,
          "description": {
            "ru": "Новое значение настройки.",
            "en": "New setting value."
          },
          "default": 1,
          "enum": [
            0,
            1
          ]
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "toggle",
          "updated": true,
          "artist": {
            "id": 2001,
            "artist_name_ru": "Имя исполнителя",
            "artist_name_en": "Artist name",
            "is_active": 1,
            "notify_enabled": 0,
            "cooldown_minutes": 10
          }
        }
      },
      "fields": [
        {
          "name": "data.artist",
          "type": "object",
          "description": {
            "ru": "Сохранённая запись исполнителя.",
            "en": "Saved artist record."
          }
        },
        {
          "name": "data.artist.is_active",
          "type": "integer",
          "description": {
            "ru": "1 — запись активна; 0 — выключена.",
            "en": "1 means the record is active; 0 means disabled."
          }
        },
        {
          "name": "data.artist.notify_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — уведомления разрешены; 0 — выключены.",
            "en": "1 enables notifications; 0 disables them."
          }
        },
        {
          "name": "data.artist.cooldown_minutes",
          "type": "integer",
          "description": {
            "ru": "Минимальная пауза уведомлений в минутах.",
            "en": "Minimum notification interval in minutes."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 400,
          "code": "missing_artist_id",
          "description": {
            "ru": "Не передан ID исполнителя.",
            "en": "The artist ID is required."
          }
        },
        {
          "status": 400,
          "code": "invalid_toggle_field",
          "description": {
            "ru": "Допустимы is_active и notify_enabled.",
            "en": "Only is_active and notify_enabled are supported."
          }
        },
        {
          "status": 404,
          "code": "artist_not_found",
          "description": {
            "ru": "Исполнитель не найден в вашем аккаунте.",
            "en": "The artist was not found in your account."
          }
        }
      ]
    },
    {
      "id": "artists-delete",
      "group": "profiles",
      "method": "POST",
      "path": "/api.client_artists.php?action=delete",
      "title": {
        "ru": "Удалить исполнителя",
        "en": "Delete an artist"
      },
      "summary": {
        "ru": "Удалить запись исполнителя из своего аккаунта.",
        "en": "Delete an artist record from your account."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "id": 2001
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN — токен клиента.",
            "en": "Bearer ACCESS_TOKEN — a client token."
          }
        },
        {
          "name": "id",
          "in": "body",
          "type": "integer",
          "required": true,
          "description": {
            "ru": "ID записи исполнителя в вашем аккаунте.",
            "en": "Artist record ID in your account."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "mode": "delete",
          "deleted": true,
          "id": 2001
        }
      },
      "fields": [
        {
          "name": "data.deleted",
          "type": "boolean",
          "description": {
            "ru": "true — запись удалена.",
            "en": "true means the record was deleted."
          }
        },
        {
          "name": "data.id",
          "type": "integer",
          "description": {
            "ru": "ID удалённой записи.",
            "en": "Deleted record ID."
          }
        }
      ],
      "notes": [],
      "errors": [
        {
          "status": 401,
          "code": "missing_bearer_token",
          "description": {
            "ru": "Не передан Bearer-токен.",
            "en": "The Bearer token is missing."
          }
        },
        {
          "status": 401,
          "code": "invalid_token",
          "description": {
            "ru": "Токен не принят.",
            "en": "The token was not accepted."
          }
        },
        {
          "status": 403,
          "code": "token_scope_mismatch",
          "description": {
            "ru": "Токен относится к другому типу аккаунта.",
            "en": "The token belongs to a different account type."
          }
        },
        {
          "status": 401,
          "code": "token_revoked",
          "description": {
            "ru": "Токен отозван.",
            "en": "The token has been revoked."
          }
        },
        {
          "status": 401,
          "code": "token_expired",
          "description": {
            "ru": "Токен истёк.",
            "en": "The token has expired."
          }
        },
        {
          "status": 400,
          "code": "missing_artist_id",
          "description": {
            "ru": "Не передан ID исполнителя.",
            "en": "The artist ID is required."
          }
        },
        {
          "status": 404,
          "code": "artist_not_found",
          "description": {
            "ru": "Исполнитель не найден в вашем аккаунте.",
            "en": "The artist was not found in your account."
          }
        }
      ]
    },
    {
      "id": "maintenance",
      "group": "apps",
      "method": "GET",
      "path": "/api.app_maintenance.php",
      "title": {
        "ru": "Технические работы",
        "en": "Maintenance"
      },
      "summary": {
        "ru": "Состояние и расписание технических работ для приложения.",
        "en": "Maintenance status and schedule for the app."
      },
      "auth": "public",
      "run": true,
      "format": "none",
      "query": {},
      "body": {},
      "params": [],
      "response_kind": "json",
      "response": {
        "ok": true,
        "source": "cache",
        "schema_version": 1,
        "server_time": "2026-11-20T12:00:00+03:00",
        "timezone": "Europe/Moscow",
        "recommended_poll_seconds": 30,
        "maintenance_active": false,
        "show_notification": false,
        "active_maintenance": [],
        "upcoming_maintenance": [],
        "notifications": [],
        "count": 0,
        "items": []
      },
      "fields": [
        {
          "name": "maintenance_active",
          "type": "boolean | null",
          "description": {
            "ru": "Есть ли активные работы; null при недоступности данных.",
            "en": "Whether maintenance is active; null when data is unavailable."
          }
        },
        {
          "name": "show_notification",
          "type": "boolean | null",
          "description": {
            "ru": "Нужно ли показать уведомление.",
            "en": "Whether a notification should be shown."
          }
        },
        {
          "name": "items",
          "type": "array",
          "description": {
            "ru": "Расписание работ и состояния записей.",
            "en": "Maintenance schedule and item states."
          }
        },
        {
          "name": "server_time",
          "type": "string",
          "description": {
            "ru": "Время сервера в ISO 8601 с часовым поясом.",
            "en": "Server time in ISO 8601 with its time zone."
          }
        },
        {
          "name": "recommended_poll_seconds",
          "type": "integer",
          "description": {
            "ru": "Рекомендуемый интервал опроса в секундах.",
            "en": "Recommended polling interval in seconds."
          }
        }
      ],
      "notes": [
        {
          "ru": "Поддерживаются GET, HEAD и OPTIONS; рекомендуемый опрос — каждые 30 секунд.",
          "en": "GET, HEAD and OPTIONS are supported; recommended polling is every 30 seconds."
        },
        {
          "ru": "При ответе 503 не считайте null отсутствием работ.",
          "en": "For a 503 response, do not interpret null as no maintenance."
        }
      ],
      "errors": [
        {
          "status": 405,
          "code": "method_not_allowed",
          "description": {
            "ru": "Метод HTTP не поддерживается.",
            "en": "The HTTP method is not supported."
          }
        },
        {
          "status": 503,
          "code": "maintenance_cache_unavailable",
          "description": {
            "ru": "Расписание работ временно недоступно.",
            "en": "The maintenance schedule is temporarily unavailable."
          }
        }
      ]
    },
    {
      "id": "push-register",
      "group": "apps",
      "method": "POST",
      "path": "/api.push_devices.php",
      "title": {
        "ru": "Регистрация устройства",
        "en": "Register a device"
      },
      "summary": {
        "ru": "Регистрация установки и обновление её параметров. Для связанной установки нужен Bearer или служебная cookie существующей сессии (Device API 1.0.6).",
        "en": "Register an installation and update its metadata. A bound installation requires its Bearer or the compatibility cookie of an existing session (Device API 1.0.6)."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "action": "register",
        "device_uuid": "DEVICE_UUID",
        "platform": "ios",
        "store": "app_store",
        "locale": "ru-RU",
        "push_timezone": "Europe/Moscow"
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Действующий Bearer точного устройства и текущего владельца. Для register/permission без непустого Authorization допустима подписанная cookie существующей сессии, выданная при входе/профиле. Старая программа должна сохранять cookie на том же HTTPS-хосте. Для новой или непривязанной установки авторизация необязательна. Неверный непустой Authorization не заменяется cookie.",
            "en": "Unexpired Bearer of this exact device and current owner. For register/permission without a nonempty Authorization header, a signed compatibility cookie issued by login/profile may authorize the existing session. The old client must share cookies on the same HTTPS host. New/unbound installations need no credential. Invalid nonempty Authorization never falls back to a cookie."
          }
        },
        {
          "name": "action",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Действие в теле запроса. Если отсутствует, допускается action в URL; конфликт двух явных значений отклоняется. Если действие не задано нигде, используется register.",
            "en": "Body action. If omitted, action may be supplied in the URL; conflicting explicit values are rejected. With no action in either place, register is used."
          },
          "default": "register",
          "enum": [
            "register"
          ]
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Стабильный UUID установки, до 191 символа.",
            "en": "Stable installation UUID, up to 191 characters."
          }
        },
        {
          "name": "platform",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Обязательна для новой установки. Для существующей записи отсутствие, null или пустая строка сохраняет платформу; явно неизвестное непустое значение отклоняется.",
            "en": "Required for a new installation. For an existing record, omission, null or an empty string preserves the platform; an explicit unknown nonempty value is rejected."
          },
          "enum": [
            "ios",
            "ipados",
            "macos",
            "watchos",
            "tvos",
            "visionos",
            "android_phone",
            "android_tablet",
            "android_tv",
            "android_auto",
            "android_desktop",
            "android_laptop"
          ]
        },
        {
          "name": "store",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Магазин установки. Принимаются канонические коды и явные варианты названия (App Store, AppStore, TestFlight, Google Play). Пустое, unknown или неподдерживаемое значение сохраняет известный магазин, совместимый с платформой. Из iOS или среды APNs магазин не определяется.",
            "en": "Installation store. Canonical codes and explicit name variants (App Store, AppStore, TestFlight, Google Play) are accepted. Empty, unknown or unsupported values preserve a known platform-compatible store. The store is not inferred from iOS or APNs environment."
          },
          "enum": [
            "app_store",
            "testflight",
            "google_play",
            "rustore",
            "huawei_appgallery",
            "samsung_galaxy_store",
            "apk",
            "unknown"
          ]
        },
        {
          "name": "device_name",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Название устройства, до 255 символов.",
            "en": "Device name, up to 255 characters."
          }
        },
        {
          "name": "app_version",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Версия приложения, до 50 символов.",
            "en": "App version, up to 50 characters."
          }
        },
        {
          "name": "os_version",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Версия ОС, до 50 символов.",
            "en": "OS version, up to 50 characters."
          }
        },
        {
          "name": "locale",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Локаль до 20 символов. Явное корректное значение обновляет язык; непереданное, пустое или некорректное сохраняет известный язык. Accept-Language и en используются только если язык ещё не сохранён. Также принимается language_code.",
            "en": "Locale up to 20 characters. An explicit valid value updates the language; omitted, empty or malformed values preserve a known language. Accept-Language and en are only fallbacks when no language is saved. language_code is also accepted."
          }
        },
        {
          "name": "push_timezone",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Часовой пояс IANA, например Europe/Moscow; также поддерживается timezone. Корректный пояс обновляется, отсутствие/null/пустое/нераспознанное значение сохраняет известный пояс. Для намеренного удаления используйте clear_timezone=true.",
            "en": "IANA time zone such as Europe/Moscow; timezone is also accepted. A valid zone updates the record; omission/null/empty/unrecognized values preserve a known zone. Use clear_timezone=true to deliberately clear it."
          }
        },
        {
          "name": "clear_timezone",
          "in": "body",
          "type": "boolean",
          "required": false,
          "description": {
            "ru": "Намеренно очистить часовой пояс, смещение UTC и дату обновления пояса. Принимаются true/false, 0/1, строки 0/1. true вместе с корректным поясом — ошибка без записи изменений.",
            "en": "Deliberately clear the time zone, UTC offset and zone-update timestamp. Accepts true/false, 0/1 and strings 0/1. true together with a valid zone is rejected without changes."
          },
          "default": false
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "push_timezone": "Europe/Moscow",
          "utc_offset_minutes": 180,
          "timezone_country_codes": [
            "RU"
          ],
          "status": "registered",
          "device_status": "inactive",
          "notifications_enabled": 0,
          "push_provider": null,
          "store": "app_store",
          "locale": "ru-RU",
          "device_id": 17,
          "push_permission_status": "unknown",
          "push_token_environment": "unknown",
          "push_token_invalid": false
        }
      },
      "fields": [
        {
          "name": "data.status",
          "type": "string",
          "description": {
            "ru": "Результат регистрации или изменения устройства.",
            "en": "Result of device registration or update."
          }
        },
        {
          "name": "data.device_status",
          "type": "string",
          "description": {
            "ru": "Текущее состояние устройства.",
            "en": "Current device state."
          }
        },
        {
          "name": "data.notifications_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — уведомления разрешены; 0 — выключены.",
            "en": "1 enables notifications; 0 disables them."
          }
        },
        {
          "name": "data.push_provider",
          "type": "string | null",
          "description": {
            "ru": "Определённый сервером провайдер APNs или FCM.",
            "en": "APNs or FCM provider determined by the server."
          }
        },
        {
          "name": "data.push_timezone",
          "type": "string | null",
          "description": {
            "ru": "Сохранённый часовой пояс устройства.",
            "en": "Saved device time zone."
          }
        },
        {
          "name": "data.device_id",
          "type": "integer",
          "description": {
            "ru": "ID записи устройства в push_devices.",
            "en": "Device record ID in push_devices."
          }
        },
        {
          "name": "data.push_permission_status",
          "type": "string",
          "description": {
            "ru": "Последнее известное разрешение ОС: unknown, authorized, denied, provisional или ephemeral.",
            "en": "Last known OS permission: unknown, authorized, denied, provisional or ephemeral."
          }
        },
        {
          "name": "data.push_token_environment",
          "type": "string",
          "description": {
            "ru": "Среда APNs: unknown, production или sandbox; для FCM — unknown.",
            "en": "APNs environment: unknown, production or sandbox; FCM uses unknown."
          }
        },
        {
          "name": "data.push_token_invalid",
          "type": "boolean",
          "description": {
            "ru": "true — сохранённый токен признан недействительным; повтор той же строки токена этот флаг не сбрасывает.",
            "en": "true means the stored token is invalid; submitting the same token again does not reset this flag."
          }
        }
      ],
      "notes": [
        {
          "ru": "action передаётся в теле либо в URL при отсутствии в теле; конфликт отклоняется. register обновляет метаданные, permission — разрешение, адрес push и явно сообщённую среду APNs.",
          "en": "Supply action in the body, or in the URL when omitted from the body; conflicts are rejected. register updates metadata; permission updates consent, push destination and any explicitly reported APNs environment."
        },
        {
          "ru": "Новая и непривязанная установка может обращаться без авторизации. Связанная установка использует действующий Bearer точного устройства/владельца либо cookie этой сессии для register/permission. Для устройства клиента нужен аккаунт клиента.",
          "en": "New and unbound installations may call without authentication. A bound installation uses an unexpired Bearer for the exact device/owner, or that session’s register/permission compatibility cookie. A client device requires its client account."
        },
        {
          "ru": "Привязка user_id выполняется обычным входом клиента с тем же device_uuid. Переданный в register или permission user_id не назначает владельца. Токен слушателя не может изменять устройство клиента, даже если в строке также есть app_user_id.",
          "en": "Sign in through the client login using the same device_uuid to bind user_id. A user_id sent to register or permission does not assign ownership. A listener token cannot modify a client device even when app_user_id is also populated."
        },
        {
          "ru": "Порядок: register → вход с тем же device_uuid → permission. Новые клиенты передают Bearer; прежние клиенты с общим хранилищем cookie могут использовать выданную сессию без изменения тела.",
          "en": "Sequence: register → login with the same device_uuid → permission. New clients send Bearer; older clients with shared cookie storage can use the issued session without body changes."
        },
        {
          "ru": "Версия передаётся заголовком X-EarthPlus-Device-API: 1.0.6; успешная авторизация связанной записи — X-EarthPlus-Device-Auth: bearer или session_cookie. JSON-обёртка и прежние статусы сохранены.",
          "en": "X-EarthPlus-Device-API: 1.0.6 identifies the version. Successful bound-device authorization adds X-EarthPlus-Device-Auth: bearer or session_cookie. The JSON envelope and existing statuses are preserved."
        },
        {
          "ru": "В 1.0.4 поддерживается cookie совместимости для прежних тел запросов Apple-клиента с общей URLSession. Она ограничена операциями устройства и не является Bearer аккаунта. Без Bearer и cookie UUID не даёт права менять токен связанного аккаунта. Известная среда APNs сохраняется при том же токене; среда нового токена требует подтверждения.",
          "en": "Version 1.0.4 supports a scoped compatibility cookie for existing Apple request bodies using a shared URLSession. It is limited to device operations and is not an account Bearer. UUID alone cannot replace a bound account destination. A known APNs environment is preserved for the same token; a new token requires confirmed environment information."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "device_uuid_required",
          "description": {
            "ru": "Не передан UUID устройства.",
            "en": "The device UUID is required."
          }
        },
        {
          "status": 400,
          "code": "invalid_platform",
          "description": {
            "ru": "Неподдерживаемая платформа.",
            "en": "Unsupported platform."
          }
        },
        {
          "status": 401,
          "code": "device_authorization_required",
          "description": {
            "ru": "Нужна действующая сессия точного устройства/владельца: Bearer либо допустимая cookie для register/permission. UUID сам по себе не разрешает изменение связанной записи.",
            "en": "A valid session for the exact device/owner is required: Bearer or an eligible register/permission compatibility cookie. UUID alone cannot authorize a bound record mutation."
          }
        },
        {
          "status": 503,
          "code": "push_device_unavailable",
          "description": {
            "ru": "Операция не завершена; повторите позднее. Изменения транзакции откатываются.",
            "en": "The operation could not complete; retry later. Transaction changes are rolled back."
          }
        },
        {
          "status": 400,
          "code": "invalid_clear_timezone",
          "description": {
            "ru": "Некорректный флаг намеренной очистки пояса.",
            "en": "Invalid explicit time-zone clear flag."
          }
        },
        {
          "status": 400,
          "code": "conflicting_timezone_update",
          "description": {
            "ru": "Нельзя одновременно очистить пояс и установить корректный пояс.",
            "en": "Cannot clear the time zone and set a valid time zone in the same request."
          }
        },
        {
          "status": 400,
          "code": "invalid_action",
          "description": {
            "ru": "Действие должно быть строкой допустимой длины.",
            "en": "Action must be a string of supported length."
          }
        },
        {
          "status": 400,
          "code": "conflicting_action",
          "description": {
            "ru": "В теле и URL заданы разные действия; запись не выполнена.",
            "en": "Body and URL specify different actions; no write is performed."
          }
        }
      ]
    },
    {
      "id": "push-permission",
      "group": "apps",
      "method": "POST",
      "path": "/api.push_devices.php",
      "title": {
        "ru": "Разрешение уведомлений",
        "en": "Notification permission"
      },
      "summary": {
        "ru": "Сохранение разрешения и адреса push устройства. Для связанной установки нужен Bearer или служебная cookie существующей сессии (Device API 1.0.6).",
        "en": "Save the device push consent and destination. A bound installation requires its Bearer or the compatibility cookie of an existing session (Device API 1.0.6)."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "action": "permission",
        "device_uuid": "DEVICE_UUID",
        "notifications_enabled": 1,
        "push_token": "PUSH_TOKEN",
        "locale": "ru-RU",
        "push_timezone": "Europe/Moscow",
        "push_permission_status": "authorized",
        "push_token_environment": "production"
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Действующий Bearer точного устройства и текущего владельца. Для register/permission без непустого Authorization допустима подписанная cookie существующей сессии, выданная при входе/профиле. Старая программа должна сохранять cookie на том же HTTPS-хосте. Для новой или непривязанной установки авторизация необязательна. Неверный непустой Authorization не заменяется cookie.",
            "en": "Unexpired Bearer of this exact device and current owner. For register/permission without a nonempty Authorization header, a signed compatibility cookie issued by login/profile may authorize the existing session. The old client must share cookies on the same HTTPS host. New/unbound installations need no credential. Invalid nonempty Authorization never falls back to a cookie."
          }
        },
        {
          "name": "action",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Действие в теле запроса. Если отсутствует, допускается action в URL; конфликт двух явных значений отклоняется. Если действие не задано нигде, используется register.",
            "en": "Body action. If omitted, action may be supplied in the URL; conflicting explicit values are rejected. With no action in either place, register is used."
          },
          "enum": [
            "permission"
          ]
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Стабильный UUID установки, до 191 символа.",
            "en": "Stable installation UUID, up to 191 characters."
          }
        },
        {
          "name": "notifications_enabled",
          "in": "body",
          "type": "boolean | integer",
          "required": false,
          "description": {
            "ru": "Согласие на уведомления: true/1 или false/0. Если поле отсутствует, сохраняется прежнее значение. Явный denied от ОС принудительно выключает уведомления.",
            "en": "Notification consent: true/1 or false/0. Omitting the field preserves the saved value. An explicit OS denied state forces notifications off."
          }
        },
        {
          "name": "push_token",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Токен APNs/FCM до 512 байт без пробелов и управляющих символов. Для включения нужен новый или уже сохранённый токен; отсутствующее, пустое или null значение сохраняет текущий.",
            "en": "APNs/FCM token up to 512 bytes without spaces or control characters. Enabling requires a supplied or already stored token; omitted, empty or null values preserve the current token."
          }
        },
        {
          "name": "platform",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Платформа; по умолчанию сохранённое значение.",
            "en": "Platform; defaults to the saved value."
          },
          "enum": [
            "ios",
            "ipados",
            "macos",
            "watchos",
            "tvos",
            "visionos",
            "android_phone",
            "android_tablet",
            "android_tv",
            "android_auto",
            "android_desktop",
            "android_laptop"
          ]
        },
        {
          "name": "store",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Магазин установки. Принимаются канонические коды и явные варианты названия (App Store, AppStore, TestFlight, Google Play). Пустое, unknown или неподдерживаемое значение сохраняет известный магазин, совместимый с платформой. Из iOS или среды APNs магазин не определяется.",
            "en": "Installation store. Canonical codes and explicit name variants (App Store, AppStore, TestFlight, Google Play) are accepted. Empty, unknown or unsupported values preserve a known platform-compatible store. The store is not inferred from iOS or APNs environment."
          },
          "enum": [
            "app_store",
            "testflight",
            "google_play",
            "rustore",
            "huawei_appgallery",
            "samsung_galaxy_store",
            "apk",
            "unknown"
          ]
        },
        {
          "name": "device_name",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Название устройства, до 255 символов.",
            "en": "Device name, up to 255 characters."
          }
        },
        {
          "name": "app_version",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Версия приложения, до 50 символов.",
            "en": "App version, up to 50 characters."
          }
        },
        {
          "name": "os_version",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Версия ОС, до 50 символов.",
            "en": "OS version, up to 50 characters."
          }
        },
        {
          "name": "locale",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Локаль до 20 символов. Явное корректное значение обновляет язык; непереданное, пустое или некорректное сохраняет известный язык. Accept-Language и en используются только если язык ещё не сохранён. Также принимается language_code.",
            "en": "Locale up to 20 characters. An explicit valid value updates the language; omitted, empty or malformed values preserve a known language. Accept-Language and en are only fallbacks when no language is saved. language_code is also accepted."
          }
        },
        {
          "name": "push_timezone",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Часовой пояс IANA, например Europe/Moscow; также поддерживается timezone. Корректный пояс обновляется, отсутствие/null/пустое/нераспознанное значение сохраняет известный пояс. Для намеренного удаления используйте clear_timezone=true.",
            "en": "IANA time zone such as Europe/Moscow; timezone is also accepted. A valid zone updates the record; omission/null/empty/unrecognized values preserve a known zone. Use clear_timezone=true to deliberately clear it."
          }
        },
        {
          "name": "push_permission_status",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Фактическое разрешение ОС. denied выключает согласие; unknown не стирает ранее известное разрешение.",
            "en": "Actual OS permission. denied disables consent; unknown does not erase a previously known permission."
          },
          "enum": [
            "unknown",
            "authorized",
            "denied",
            "provisional",
            "ephemeral"
          ]
        },
        {
          "name": "push_token_environment",
          "in": "body",
          "type": "string",
          "required": false,
          "description": {
            "ru": "Явная среда APNs production или sandbox. Новый токен без среды получает unknown и не отправляется через APNs до уточнения. Для FCM сохраняется unknown.",
            "en": "Explicit APNs production or sandbox environment. A new token without an environment becomes unknown and is not sent through APNs until resolved. FCM stores unknown."
          },
          "enum": [
            "unknown",
            "production",
            "sandbox"
          ]
        },
        {
          "name": "clear_timezone",
          "in": "body",
          "type": "boolean",
          "required": false,
          "description": {
            "ru": "Намеренно очистить часовой пояс, смещение UTC и дату обновления пояса. Принимаются true/false, 0/1, строки 0/1. true вместе с корректным поясом — ошибка без записи изменений.",
            "en": "Deliberately clear the time zone, UTC offset and zone-update timestamp. Accepts true/false, 0/1 and strings 0/1. true together with a valid zone is rejected without changes."
          },
          "default": false
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "push_timezone": "Europe/Moscow",
          "utc_offset_minutes": 180,
          "timezone_country_codes": [
            "RU"
          ],
          "status": "permission_saved",
          "device_status": "active",
          "notifications_enabled": 1,
          "push_provider": "apns",
          "store": "app_store",
          "locale": "ru-RU",
          "device_id": 17,
          "push_permission_status": "authorized",
          "push_token_environment": "production",
          "push_token_invalid": false
        }
      },
      "fields": [
        {
          "name": "data.status",
          "type": "string",
          "description": {
            "ru": "Результат регистрации или изменения устройства.",
            "en": "Result of device registration or update."
          }
        },
        {
          "name": "data.device_status",
          "type": "string",
          "description": {
            "ru": "Текущее состояние устройства.",
            "en": "Current device state."
          }
        },
        {
          "name": "data.notifications_enabled",
          "type": "integer",
          "description": {
            "ru": "1 — уведомления разрешены; 0 — выключены.",
            "en": "1 enables notifications; 0 disables them."
          }
        },
        {
          "name": "data.push_provider",
          "type": "string | null",
          "description": {
            "ru": "Определённый сервером провайдер APNs или FCM.",
            "en": "APNs or FCM provider determined by the server."
          }
        },
        {
          "name": "data.push_timezone",
          "type": "string | null",
          "description": {
            "ru": "Сохранённый часовой пояс устройства.",
            "en": "Saved device time zone."
          }
        },
        {
          "name": "data.device_id",
          "type": "integer",
          "description": {
            "ru": "ID записи устройства в push_devices.",
            "en": "Device record ID in push_devices."
          }
        },
        {
          "name": "data.push_permission_status",
          "type": "string",
          "description": {
            "ru": "Последнее известное разрешение ОС: unknown, authorized, denied, provisional или ephemeral.",
            "en": "Last known OS permission: unknown, authorized, denied, provisional or ephemeral."
          }
        },
        {
          "name": "data.push_token_environment",
          "type": "string",
          "description": {
            "ru": "Среда APNs: unknown, production или sandbox; для FCM — unknown.",
            "en": "APNs environment: unknown, production or sandbox; FCM uses unknown."
          }
        },
        {
          "name": "data.push_token_invalid",
          "type": "boolean",
          "description": {
            "ru": "true — сохранённый токен признан недействительным; повтор той же строки токена этот флаг не сбрасывает.",
            "en": "true means the stored token is invalid; submitting the same token again does not reset this flag."
          }
        }
      ],
      "notes": [
        {
          "ru": "action передаётся в теле либо в URL при отсутствии в теле; конфликт отклоняется. register обновляет метаданные, permission — разрешение, адрес push и явно сообщённую среду APNs.",
          "en": "Supply action in the body, or in the URL when omitted from the body; conflicts are rejected. register updates metadata; permission updates consent, push destination and any explicitly reported APNs environment."
        },
        {
          "ru": "Новая и непривязанная установка может обращаться без авторизации. Связанная установка использует действующий Bearer точного устройства/владельца либо cookie этой сессии для register/permission. Для устройства клиента нужен аккаунт клиента.",
          "en": "New and unbound installations may call without authentication. A bound installation uses an unexpired Bearer for the exact device/owner, or that session’s register/permission compatibility cookie. A client device requires its client account."
        },
        {
          "ru": "Привязка user_id выполняется обычным входом клиента с тем же device_uuid. Переданный в register или permission user_id не назначает владельца. Токен слушателя не может изменять устройство клиента, даже если в строке также есть app_user_id.",
          "en": "Sign in through the client login using the same device_uuid to bind user_id. A user_id sent to register or permission does not assign ownership. A listener token cannot modify a client device even when app_user_id is also populated."
        },
        {
          "ru": "Выключение уведомлений сохраняет адрес токена и историю его недействительности, но запрещает отправку. Это не включает уведомления повторно.",
          "en": "Opting out retains the token address and invalidation history while disabling delivery. It does not enable notifications again."
        },
        {
          "ru": "Флаг push_token_invalid сбрасывается только при действительной смене строки токена. Повтор токена, смена платформы или среды APNs его не сбрасывают. Заблокированное устройство остаётся заблокированным.",
          "en": "Only an actual token-string change resets push_token_invalid. Resubmitting a token or changing platform/APNs environment does not reset it. A blocked device remains blocked."
        },
        {
          "ru": "Провайдер определяется по платформе; push_provider не передаётся. Среда APNs не определяется по магазину установки. unknown не заменяет известную среду для того же токена.",
          "en": "The provider is derived from the platform; do not send push_provider. APNs environment is not inferred from the installation store. unknown does not replace a known environment for the same token."
        },
        {
          "ru": "Успешное сохранение не гарантирует отправку: учитываются push_settings, режим тестирования, состояние устройства, разрешение ОС и настройки категории.",
          "en": "A successful save does not guarantee a send: push_settings, test mode, device state, OS permission and category preferences still apply."
        },
        {
          "ru": "Версия передаётся заголовком X-EarthPlus-Device-API: 1.0.6; успешная авторизация связанной записи — X-EarthPlus-Device-Auth: bearer или session_cookie. JSON-обёртка и прежние статусы сохранены.",
          "en": "X-EarthPlus-Device-API: 1.0.6 identifies the version. Successful bound-device authorization adds X-EarthPlus-Device-Auth: bearer or session_cookie. The JSON envelope and existing statuses are preserved."
        },
        {
          "ru": "В 1.0.4 поддерживается cookie совместимости для прежних тел запросов Apple-клиента с общей URLSession. Она ограничена операциями устройства и не является Bearer аккаунта. Без Bearer и cookie UUID не даёт права менять токен связанного аккаунта. Известная среда APNs сохраняется при том же токене; среда нового токена требует подтверждения.",
          "en": "Version 1.0.4 supports a scoped compatibility cookie for existing Apple request bodies using a shared URLSession. It is limited to device operations and is not an account Bearer. UUID alone cannot replace a bound account destination. A known APNs environment is preserved for the same token; a new token requires confirmed environment information."
        }
      ],
      "errors": [
        {
          "status": 400,
          "code": "device_uuid_required",
          "description": {
            "ru": "Не передан UUID устройства.",
            "en": "The device UUID is required."
          }
        },
        {
          "status": 404,
          "code": "device_not_found",
          "description": {
            "ru": "Сначала зарегистрируйте устройство.",
            "en": "Register the device first."
          }
        },
        {
          "status": 400,
          "code": "invalid_platform",
          "description": {
            "ru": "Неподдерживаемая платформа.",
            "en": "Unsupported platform."
          }
        },
        {
          "status": 400,
          "code": "invalid_push_provider",
          "description": {
            "ru": "Не удалось определить push-провайдера.",
            "en": "The push provider could not be determined."
          }
        },
        {
          "status": 400,
          "code": "push_token_required",
          "description": {
            "ru": "Для уведомлений нужен push-токен.",
            "en": "A push token is required to enable notifications."
          }
        },
        {
          "status": 401,
          "code": "device_authorization_required",
          "description": {
            "ru": "Нужна действующая сессия точного устройства/владельца: Bearer либо допустимая cookie для register/permission. UUID сам по себе не разрешает изменение связанной записи.",
            "en": "A valid session for the exact device/owner is required: Bearer or an eligible register/permission compatibility cookie. UUID alone cannot authorize a bound record mutation."
          }
        },
        {
          "status": 503,
          "code": "push_device_unavailable",
          "description": {
            "ru": "Операция не завершена; повторите позднее. Изменения транзакции откатываются.",
            "en": "The operation could not complete; retry later. Transaction changes are rolled back."
          }
        },
        {
          "status": 400,
          "code": "invalid_notifications_enabled",
          "description": {
            "ru": "Неверное значение согласия на уведомления.",
            "en": "Invalid notification consent value."
          }
        },
        {
          "status": 400,
          "code": "invalid_permission_status",
          "description": {
            "ru": "Неизвестный статус разрешения ОС.",
            "en": "Unknown OS permission status."
          }
        },
        {
          "status": 400,
          "code": "invalid_token_environment",
          "description": {
            "ru": "Допустимы unknown, production или sandbox.",
            "en": "Allowed values are unknown, production or sandbox."
          }
        },
        {
          "status": 400,
          "code": "invalid_push_token",
          "description": {
            "ru": "Некорректная строка push-токена.",
            "en": "Invalid push token string."
          }
        },
        {
          "status": 409,
          "code": "push_token_in_use",
          "description": {
            "ru": "Этот токен связан с другим владельцем или несовместимым провайдером.",
            "en": "This token belongs to another owner or incompatible provider."
          }
        },
        {
          "status": 409,
          "code": "push_token_invalid",
          "description": {
            "ru": "Токен другой записи устройства уже признан недействительным; требуется актуальный токен.",
            "en": "The token on another device record is already invalid; a current token is required."
          }
        },
        {
          "status": 400,
          "code": "invalid_clear_timezone",
          "description": {
            "ru": "Некорректный флаг намеренной очистки пояса.",
            "en": "Invalid explicit time-zone clear flag."
          }
        },
        {
          "status": 400,
          "code": "conflicting_timezone_update",
          "description": {
            "ru": "Нельзя одновременно очистить пояс и установить корректный пояс.",
            "en": "Cannot clear the time zone and set a valid time zone in the same request."
          }
        },
        {
          "status": 400,
          "code": "invalid_action",
          "description": {
            "ru": "Действие должно быть строкой допустимой длины.",
            "en": "Action must be a string of supported length."
          }
        },
        {
          "status": 400,
          "code": "conflicting_action",
          "description": {
            "ru": "В теле и URL заданы разные действия; запись не выполнена.",
            "en": "Body and URL specify different actions; no write is performed."
          }
        }
      ]
    },
    {
      "id": "push-categories",
      "group": "apps",
      "method": "GET",
      "path": "/api.push_devices.php",
      "title": {
        "ru": "Категории уведомлений",
        "en": "Notification categories"
      },
      "summary": {
        "ru": "Получить доступные коды категорий из push_categories.",
        "en": "Read available category codes from push_categories."
      },
      "auth": "public",
      "run": true,
      "format": "json",
      "query": {
        "action": "categories"
      },
      "body": {},
      "params": [
        {
          "name": "action",
          "in": "query",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Действие чтения каталога.",
            "en": "Catalog read action."
          },
          "enum": [
            "categories"
          ]
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "categories": [
            {
              "code": "service_expiring",
              "group_code": "artist",
              "name_ru": "Скорое окончание услуги",
              "description_ru": "Предупреждение о приближении даты окончания оплаченного периода услуги.",
              "default_enabled": true
            }
          ]
        }
      },
      "fields": [
        {
          "name": "data.categories",
          "type": "array",
          "description": {
            "ru": "Включённые, не удалённые категории, действующие на текущую дату.",
            "en": "Enabled, non-deleted categories within their active time window."
          }
        },
        {
          "name": "data.categories[].code",
          "type": "string",
          "description": {
            "ru": "Код категории для preferences и payload обеих платформ.",
            "en": "Category code for preferences and payloads on both platforms."
          }
        },
        {
          "name": "data.categories[].group_code",
          "type": "string",
          "description": {
            "ru": "Группа категории.",
            "en": "Category group."
          }
        },
        {
          "name": "data.categories[].name_ru",
          "type": "string",
          "description": {
            "ru": "Название категории на русском.",
            "en": "Russian category label."
          }
        },
        {
          "name": "data.categories[].description_ru",
          "type": "string",
          "description": {
            "ru": "Описание категории на русском.",
            "en": "Russian category description."
          }
        },
        {
          "name": "data.categories[].default_enabled",
          "type": "boolean",
          "description": {
            "ru": "Значение категории по умолчанию при отсутствии персонального выбора.",
            "en": "Category default when no explicit device preference exists."
          }
        }
      ],
      "notes": [
        {
          "ru": "Авторизация и device_uuid не нужны. Ответ не содержит владельца или данные устройства.",
          "en": "Authorization and device_uuid are not required. The response does not expose device ownership or metadata."
        }
      ],
      "errors": [
        {
          "status": 503,
          "code": "push_device_unavailable",
          "description": {
            "ru": "Операция не завершена; повторите позднее. Изменения транзакции откатываются.",
            "en": "The operation could not complete; retry later. Transaction changes are rolled back."
          }
        }
      ]
    },
    {
      "id": "push-preferences",
      "group": "apps",
      "method": "POST",
      "path": "/api.push_devices.php",
      "title": {
        "ru": "Настройки категорий",
        "en": "Category preferences"
      },
      "summary": {
        "ru": "Прочитать или изменить категории уведомлений конкретного устройства.",
        "en": "Read or change notification categories for a particular device."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "action": "preferences",
        "device_uuid": "DEVICE_UUID",
        "preferences": {
          "track_airtime": true,
          "service_expiring": false
        }
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN этой установки: токен должен быть действующим, связанным с тем же device_id и текущим владельцем. Для устройства, привязанного к клиенту, нужен токен клиента.",
            "en": "Bearer ACCESS_TOKEN for this installation: it must be unexpired, bound to the same device_id and current owner. A client-bound device requires a client token."
          }
        },
        {
          "name": "action",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Действие настроек категорий.",
            "en": "Category preferences action."
          },
          "enum": [
            "preferences"
          ]
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "UUID установки, связанной с переданным Bearer.",
            "en": "Installation UUID bound to the supplied Bearer."
          }
        },
        {
          "name": "preferences",
          "in": "body",
          "type": "object",
          "required": false,
          "description": {
            "ru": "Объект код → true/false (также 1/0), до 128 категорий. Переданные коды меняются, остальные сохраняются. Без этого поля запрос только читает настройки.",
            "en": "Map category code → true/false (1/0 also accepted), up to 128 categories. Supplied codes are updated; others are preserved. Omit this field to read only."
          }
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "preferences": [
            {
              "code": "track_airtime",
              "name_ru": "Сейчас в эфире",
              "default_enabled": true,
              "category_enabled": true,
              "enabled": true,
              "explicit": true
            }
          ],
          "device_id": 17,
          "push_permission_status": "authorized",
          "push_token_environment": "production",
          "push_token_invalid": false
        }
      },
      "fields": [
        {
          "name": "data.preferences",
          "type": "array",
          "description": {
            "ru": "Не удалённые категории с эффективным выбором устройства.",
            "en": "Non-deleted categories with the device’s effective selection."
          }
        },
        {
          "name": "data.preferences[].code",
          "type": "string",
          "description": {
            "ru": "Код из push_categories.",
            "en": "Code from push_categories."
          }
        },
        {
          "name": "data.preferences[].enabled",
          "type": "boolean",
          "description": {
            "ru": "Явный выбор устройства или default_enabled, если своего выбора нет.",
            "en": "Explicit device choice, or default_enabled when no override exists."
          }
        },
        {
          "name": "data.preferences[].explicit",
          "type": "boolean",
          "description": {
            "ru": "Есть ли отдельная сохранённая настройка этой категории.",
            "en": "Whether a saved override exists for this category."
          }
        },
        {
          "name": "data.preferences[].category_enabled",
          "type": "boolean",
          "description": {
            "ru": "Общий флаг включения категории; персональный выбор его не отменяет.",
            "en": "Global category enablement flag; a device choice cannot override it."
          }
        },
        {
          "name": "data.preferences[].default_enabled",
          "type": "boolean",
          "description": {
            "ru": "Настройка категории по умолчанию.",
            "en": "Default category selection."
          }
        },
        {
          "name": "data.preferences[].name_ru",
          "type": "string",
          "description": {
            "ru": "Название категории на русском.",
            "en": "Russian category label."
          }
        },
        {
          "name": "data.device_id",
          "type": "integer",
          "description": {
            "ru": "ID записи устройства в push_devices.",
            "en": "Device record ID in push_devices."
          }
        },
        {
          "name": "data.push_permission_status",
          "type": "string",
          "description": {
            "ru": "Последнее известное разрешение ОС: unknown, authorized, denied, provisional или ephemeral.",
            "en": "Last known OS permission: unknown, authorized, denied, provisional or ephemeral."
          }
        },
        {
          "name": "data.push_token_environment",
          "type": "string",
          "description": {
            "ru": "Среда APNs: unknown, production или sandbox; для FCM — unknown.",
            "en": "APNs environment: unknown, production or sandbox; FCM uses unknown."
          }
        },
        {
          "name": "data.push_token_invalid",
          "type": "boolean",
          "description": {
            "ru": "true — сохранённый токен признан недействительным; повтор той же строки токена этот флаг не сбрасывает.",
            "en": "true means the stored token is invalid; submitting the same token again does not reset this flag."
          }
        }
      ],
      "notes": [
        {
          "ru": "Нужен Bearer именно этого устройства и текущего владельца. В примере — токен клиента; для устройства только слушателя используется его Bearer. Нельзя изменить устройство клиента токеном слушателя.",
          "en": "Requires the Bearer for this exact device and current owner. The example uses a client token; a listener-only device uses its listener Bearer. A listener token cannot modify a client device."
        },
        {
          "ru": "Для чтения можно отправить POST без preferences либо GET с action=preferences и device_uuid в строке запроса. Изменения принимаются только POST.",
          "en": "Read with POST without preferences, or GET with action=preferences and device_uuid in the query string. Changes require POST."
        },
        {
          "ru": "Пакет изменений применяется одной транзакцией. Включение категории не отменяет общий запрет уведомлений, push_settings, разрешение ОС или временные ограничения категории.",
          "en": "Changes are applied in one transaction. Enabling a category does not override master opt-out, push_settings, OS permission or the category time window."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "device_authorization_required",
          "description": {
            "ru": "Нужен действующий Bearer текущего владельца именно этого устройства; токен другой установки не подходит.",
            "en": "An unexpired Bearer for this exact device and current owner is required; another installation token is not accepted."
          }
        },
        {
          "status": 400,
          "code": "invalid_preferences",
          "description": {
            "ru": "Неверный объект настроек, значение или количество категорий.",
            "en": "Invalid preference map, value or category count."
          }
        },
        {
          "status": 400,
          "code": "unknown_category",
          "description": {
            "ru": "Категория неизвестна или удалена.",
            "en": "The category is unknown or deleted."
          }
        },
        {
          "status": 405,
          "code": "method_not_allowed",
          "description": {
            "ru": "Для изменения настроек используйте POST.",
            "en": "Use POST to change preferences."
          }
        },
        {
          "status": 503,
          "code": "push_device_unavailable",
          "description": {
            "ru": "Операция не завершена; повторите позднее. Изменения транзакции откатываются.",
            "en": "The operation could not complete; retry later. Transaction changes are rolled back."
          }
        }
      ]
    },
    {
      "id": "push-receipt",
      "group": "apps",
      "method": "POST",
      "path": "/api.push_devices.php",
      "title": {
        "ru": "Получение и прочтение уведомления",
        "en": "Notification delivery and reading"
      },
      "summary": {
        "ru": "Подтвердить получение или открытие push и получить текущее состояние. Прочтение отмечается после явного действия пользователя в приложении.",
        "en": "Acknowledge receipt or opening and return its current state. Reading is recorded after an explicit user action in the app."
      },
      "auth": "bearer-client",
      "run": false,
      "format": "json",
      "query": {},
      "body": {
        "action": "receipt",
        "device_uuid": "DEVICE_UUID",
        "push_log_id": "123",
        "receipt": "opened"
      },
      "params": [
        {
          "name": "Authorization",
          "in": "header",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Bearer ACCESS_TOKEN этой установки: токен должен быть действующим, связанным с тем же device_id и текущим владельцем. Для устройства, привязанного к клиенту, нужен токен клиента.",
            "en": "Bearer ACCESS_TOKEN for this installation: it must be unexpired, bound to the same device_id and current owner. A client-bound device requires a client token."
          }
        },
        {
          "name": "action",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "Действие подтверждения.",
            "en": "Acknowledgement action."
          },
          "enum": [
            "receipt"
          ]
        },
        {
          "name": "device_uuid",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "UUID установки, получившей push и связанной с Bearer.",
            "en": "UUID of the receiving installation bound to the Bearer."
          }
        },
        {
          "name": "push_log_id",
          "in": "body",
          "type": "string | integer",
          "required": true,
          "description": {
            "ru": "Положительный ID из payload push. Передавайте строкой, чтобы избежать потери точности больших ID на клиенте.",
            "en": "Positive ID from the push payload. Send as a string to avoid losing precision for large client-side IDs."
          }
        },
        {
          "name": "receipt",
          "in": "body",
          "type": "string",
          "required": true,
          "description": {
            "ru": "delivered — приложение подтвердило получение; opened — пользователь открыл уведомление; read — синоним opened. В ответе read нормализуется в opened.",
            "en": "delivered means the app confirmed receipt; opened means the user opened the notification; read aliases opened. The response normalizes read to opened."
          },
          "enum": [
            "delivered",
            "opened",
            "read"
          ]
        }
      ],
      "response_kind": "json",
      "response": {
        "ok": true,
        "data": {
          "push_log_id": 123,
          "receipt": "opened",
          "changed": true,
          "device_id": 17,
          "push_permission_status": "authorized",
          "push_token_environment": "production",
          "push_token_invalid": false,
          "status": "delivered",
          "is_read": true,
          "delivered_at": "2026-11-28T19:00:01+03:00",
          "opened_at": "2026-11-28T19:00:05+03:00"
        }
      },
      "fields": [
        {
          "name": "data.push_log_id",
          "type": "integer",
          "description": {
            "ru": "ID подтверждённой записи журнала.",
            "en": "Acknowledged journal entry ID."
          }
        },
        {
          "name": "data.receipt",
          "type": "string",
          "description": {
            "ru": "Нормализованный тип: delivered или opened. Входящее read возвращается как opened.",
            "en": "Normalized type: delivered or opened. An incoming read value is returned as opened."
          }
        },
        {
          "name": "data.changed",
          "type": "boolean",
          "description": {
            "ru": "true — сохранено новое подтверждение или исправлено неполное прежнее состояние; повтор без изменений возвращает false и не увеличивает счётчики.",
            "en": "true means a new acknowledgement was recorded or incomplete legacy state was repaired. An unchanged repeat returns false and does not increment counters."
          }
        },
        {
          "name": "data.device_id",
          "type": "integer",
          "description": {
            "ru": "ID записи устройства в push_devices.",
            "en": "Device record ID in push_devices."
          }
        },
        {
          "name": "data.push_permission_status",
          "type": "string",
          "description": {
            "ru": "Последнее известное разрешение ОС: unknown, authorized, denied, provisional или ephemeral.",
            "en": "Last known OS permission: unknown, authorized, denied, provisional or ephemeral."
          }
        },
        {
          "name": "data.push_token_environment",
          "type": "string",
          "description": {
            "ru": "Среда APNs: unknown, production или sandbox; для FCM — unknown.",
            "en": "APNs environment: unknown, production or sandbox; FCM uses unknown."
          }
        },
        {
          "name": "data.push_token_invalid",
          "type": "boolean",
          "description": {
            "ru": "true — сохранённый токен признан недействительным; повтор той же строки токена этот флаг не сбрасывает.",
            "en": "true means the stored token is invalid; submitting the same token again does not reset this flag."
          }
        },
        {
          "name": "data.status",
          "type": "string",
          "description": {
            "ru": "Текущий статус записи после подтверждения: delivered. Статус отправки отделён от признака прочтения.",
            "en": "Current journal status after acknowledgement: delivered. Sending status is separate from reading."
          }
        },
        {
          "name": "data.is_read",
          "type": "boolean",
          "description": {
            "ru": "Сохранённая отметка прочтения. Для прежней записи может быть true при неизвестном времени открытия; проверяйте opened_at.",
            "en": "Stored read flag. A legacy entry may be true with an unknown opening time; inspect opened_at."
          }
        },
        {
          "name": "data.delivered_at",
          "type": "string | null",
          "description": {
            "ru": "Первое серверное время подтверждения получения, ISO8601 с +03:00. Открытие также подтверждает получение.",
            "en": "First server receipt confirmation time, ISO8601 with +03:00. Opening also confirms receipt."
          }
        },
        {
          "name": "data.opened_at",
          "type": "string | null",
          "description": {
            "ru": "Первое серверное время подтверждения открытия, ISO8601 с +03:00. null означает отсутствие подтверждённого времени, а не доказательство непрочтения.",
            "en": "First server opening confirmation time, ISO8601 with +03:00. null means no confirmed time, not proof that the notification was unread."
          }
        }
      ],
      "notes": [
        {
          "ru": "Нужен Bearer именно этого устройства и текущего владельца. В примере — токен клиента; для устройства только слушателя используется его Bearer. Нельзя изменить устройство клиента токеном слушателя.",
          "en": "Requires the Bearer for this exact device and current owner. The example uses a client token; a listener-only device uses its listener Bearer. A listener token cannot modify a client device."
        },
        {
          "ru": "Запись журнала должна принадлежать тому же устройству и текущему владельцу; провайдер должен уже принять отправку. Подтверждение после смены владельца не принимается.",
          "en": "The journal entry must match the same device and current owner, and the provider must already have accepted the send. An acknowledgement for a previous owner is rejected."
        },
        {
          "ru": "Принятие APNs/FCM само по себе не является доставкой. Отправляйте delivered только после подтверждения приложением, opened — по факту открытия пользователем. Время фиксирует сервер.",
          "en": "APNs/FCM acceptance alone is not delivery. Send delivered only after an app acknowledgement, and opened after the user opens it. The server records timestamps."
        },
        {
          "ru": "opened также подтверждает получение. Повторные запросы не увеличивают счётчики; состояние журнала и счётчики меняются одной транзакцией.",
          "en": "opened also confirms receipt. Repeated requests do not increase counters; the journal state and counters change in one transaction."
        },
        {
          "ru": "Прежние delivered/opened, JSON-обёртка и коды ошибок сохранены. Cookie совместимости register/permission не разрешает receipt; требуется Bearer.",
          "en": "Existing delivered/opened, the JSON envelope and error codes remain supported. The register/permission compatibility cookie does not authorize receipt; a Bearer is required."
        },
        {
          "ru": "Повторное opened/read и позднее delivered не меняют первое время и не снимают отметку прочтения. Старые is_read/opened_at согласуются без повторного увеличения счётчика; одно is_read=1 не создаёт выдуманное время открытия.",
          "en": "Repeated opened/read and late delivered preserve the first timestamp and never clear reading. Legacy is_read/opened_at values are reconciled without recounting; is_read=1 alone does not invent an opening time."
        },
        {
          "ru": "После очистки записи журнала сервер вернёт push_log_not_found (404) и не восстановит историю. Клиент должен прекратить повторять такое подтверждение. При 503 можно повторить тот же запрос; при 401 нужна действующая сессия того же устройства и владельца.",
          "en": "After journal retention removes the entry, the server returns push_log_not_found (404) without recreating history. The client should stop retrying it. On 503, retry the same request; on 401, a current session for the same device and owner is required."
        },
        {
          "ru": "Сервер не узнаёт о прочтении по ответу Apple/Google. Приложение вызывает receipt с push_log_id из payload при открытии уведомления или связанного сообщения. Не отправляйте opened при простом запуске приложения или показе баннера.",
          "en": "Apple/Google acceptance does not tell the server that a notification was read. The app calls receipt with push_log_id from the payload when the notification or linked message is opened. Do not send opened on general app launch or banner presentation."
        }
      ],
      "errors": [
        {
          "status": 401,
          "code": "device_authorization_required",
          "description": {
            "ru": "Нужен действующий Bearer текущего владельца именно этого устройства; токен другой установки не подходит.",
            "en": "An unexpired Bearer for this exact device and current owner is required; another installation token is not accepted."
          }
        },
        {
          "status": 400,
          "code": "invalid_receipt",
          "description": {
            "ru": "Нужны положительный push_log_id и receipt=delivered, opened или read.",
            "en": "Supply a positive push_log_id and receipt=delivered, opened or read."
          }
        },
        {
          "status": 404,
          "code": "push_log_not_found",
          "description": {
            "ru": "Запись не найдена для этого устройства и владельца, в том числе после очистки истории.",
            "en": "The entry was not found for this device and owner, including after history retention."
          }
        },
        {
          "status": 409,
          "code": "push_not_accepted",
          "description": {
            "ru": "В журнале ещё нет принятой провайдером отправки; подтверждение не сохранено.",
            "en": "The journal does not yet show provider acceptance; the acknowledgement was not saved."
          }
        },
        {
          "status": 405,
          "code": "method_not_allowed",
          "description": {
            "ru": "Подтверждение принимается только POST.",
            "en": "Acknowledgements require POST."
          }
        },
        {
          "status": 503,
          "code": "push_device_unavailable",
          "description": {
            "ru": "Операция не завершена; повторите позднее. Изменения транзакции откатываются.",
            "en": "The operation could not complete; retry later. Transaction changes are rolled back."
          }
        }
      ]
    }
  ]
}
