Initial commit
This commit is contained in:
commit
1ac3b5bfaf
63 files changed
+9254
No files matched your search
@@ -0,0 +1,60 @@
|
||||
# Copy to .env and fill in. Never commit .env.
|
||||
#
|
||||
# anonymous (default) or account
|
||||
AVITO_ACCESS_MODE=anonymous
|
||||
|
||||
# If anonymous is blocked, try account cookies when they are configured.
|
||||
AVITO_ACCOUNT_FALLBACK=true
|
||||
|
||||
# auto = JSON first, then HTML fallback. browser = real Chrome via CDP.
|
||||
# html = server-rendered HTML. json = JSON endpoint only.
|
||||
AVITO_SEARCH_PROVIDER=auto
|
||||
AVITO_HTML_SEARCH_PATH=/moskva/telefony
|
||||
AVITO_BROWSER_CDP_PORT=9222
|
||||
AVITO_BROWSER_PROFILE=var/chrome-profile
|
||||
AVITO_BROWSER_HEADLESS=false
|
||||
AVITO_BROWSER_TIMEOUT_SEC=30
|
||||
AVITO_BROWSER_PAGE_DELAY_SEC=8
|
||||
|
||||
# Cookie header from a logged-in browser session on avito.ru.
|
||||
# Export only the avito.ru cookies, keep the value on one line.
|
||||
AVITO_COOKIE=
|
||||
|
||||
# Alternative: path to a Netscape cookies.txt file with avito.ru cookies.
|
||||
AVITO_COOKIE_FILE=
|
||||
|
||||
# Must match the browser that produced the cookies. If empty, the
|
||||
# impersonated Chrome user agent is used.
|
||||
AVITO_USER_AGENT=
|
||||
|
||||
# Optional. Example: http://user:pass@127.0.0.1:8080
|
||||
AVITO_PROXY=
|
||||
|
||||
# Moscow = 637640. Find your location id in the Avito URL or filter payload.
|
||||
AVITO_LOCATION_ID=637640
|
||||
|
||||
# Optional category filter.
|
||||
AVITO_CATEGORY_ID=
|
||||
|
||||
# Conservative defaults: one request every 2.5-6 seconds.
|
||||
AVITO_REQUEST_DELAY_MIN=2.5
|
||||
AVITO_REQUEST_DELAY_MAX=6.0
|
||||
AVITO_TIMEOUT_SEC=25
|
||||
AVITO_MAX_PAGES=3
|
||||
|
||||
# curl_cffi impersonation profile, e.g. chrome, chrome124, safari.
|
||||
AVITO_IMPERSONATE=chrome
|
||||
|
||||
AVITO_DATA_DIR=var
|
||||
|
||||
# SQLite by default. For Postgres use:
|
||||
# AVITO_DATABASE_URL=postgresql+asyncpg://avito:avito@localhost:5432/avito
|
||||
AVITO_DATABASE_URL=sqlite+aiosqlite:///var/avito.db
|
||||
|
||||
# Telegram notifications (optional). Leave empty to keep notifications pending.
|
||||
AVITO_TELEGRAM_BOT_TOKEN=
|
||||
AVITO_TELEGRAM_CHAT_ID=
|
||||
|
||||
AVITO_WORKER_POLL_INTERVAL_SEC=30
|
||||
AVITO_WORKER_MAX_SEARCHES_PER_CYCLE=5
|
||||
AVITO_NOTIFICATION_MAX_ATTEMPTS=3
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# local data / raw responses
|
||||
var/
|
||||
|
||||
# cloned reference repositories
|
||||
dev/
|
||||
|
||||
# python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
.uv/
|
||||
dist/
|
||||
build/
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.mypy_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# editors
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
@@ -0,0 +1,319 @@
|
||||
# avito-tools
|
||||
|
||||
Инструменты для поиска и анализа объявлений Авито:
|
||||
живой поиск, статистика цен и MCP-инструменты для агента.
|
||||
|
||||
Агентское ядро: `collector`, `analytics`, `services/search`, `services/stats`,
|
||||
`mcp`. Бывшие API, worker, БД и уведомления сохранены отдельно в
|
||||
`src/avito_tools/non_agent/` и не мешают агенту.
|
||||
|
||||
Дизайн: [docs/DESIGN.md](docs/DESIGN.md).
|
||||
|
||||
## Важно
|
||||
|
||||
- У официального API Авито нет поиска по чужим объявлениям. Здесь используется
|
||||
неофициальный web JSON, который защищён антиботом.
|
||||
- Автоматизация нарушает ToS Авито. Проект предназначен для внутренней аналитики:
|
||||
без перепубликации объявлений, без сбора PII, с низким темпом запросов.
|
||||
- Не используйте основной аккаунт для экспериментов: возможна блокировка.
|
||||
Лучше отдельный аккаунт и отдельная сессия.
|
||||
- При `403/429/439` не надо долбить Авито. Остановитесь, проверьте cookies и IP.
|
||||
|
||||
## Режимы доступа
|
||||
|
||||
- `anonymous` - без cookies: пробуем открыть главную и получить сессию. Сейчас Авито
|
||||
часто отвечает `439` и требует PoW/капчу, поэтому это скорее fallback.
|
||||
- `account` - использовать сохранённые cookies из браузера. Это не обязательно
|
||||
залогиненный аккаунт: можно сохранить и анонимную сессию. Режим просто означает
|
||||
«ходить с готовыми cookies».
|
||||
- `AVITO_ACCOUNT_FALLBACK=true` - если anonymous получил `403/429/439`, попробовать
|
||||
сохранённые cookies.
|
||||
|
||||
Аккаунт не открывает доступ к «скрытым» объявлениям: публичный поиск и так доступен.
|
||||
Он лишь повышает доверие сессии и даёт мессенджер/свои объявления. Риск блокировки
|
||||
аккаунта при этом остаётся.
|
||||
|
||||
После успешного capture удобнее поставить `AVITO_ACCESS_MODE=account`, чтобы не
|
||||
делать заведомо заблокированный anonymous-запрос перед каждым поиском.
|
||||
|
||||
### Транспорт поиска
|
||||
|
||||
- `AVITO_SEARCH_PROVIDER=auto` - сначала JSON, при `439/403` переключиться на HTML.
|
||||
- `AVITO_SEARCH_PROVIDER=json` - только JSON endpoint.
|
||||
- `AVITO_SEARCH_PROVIDER=html` - серверно-отрендеренная HTML-выдача.
|
||||
- `AVITO_SEARCH_PROVIDER=browser` - настоящий Chrome через CDP. Рекомендуется для
|
||||
account-сессии, если JSON/HTML через `curl_cffi` режутся антиботом.
|
||||
- `AVITO_HTML_SEARCH_PATH=/moskva/telefony` - путь выдачи.
|
||||
|
||||
Browser-провайдер запускает Chrome с `AVITO_BROWSER_PROFILE` (по умолчанию
|
||||
`var/chrome-profile`), открывает страницу поиска и парсит DOM. Первый вызов может
|
||||
занять несколько секунд. На сервере без `DISPLAY` включи
|
||||
`AVITO_BROWSER_HEADLESS=true`; для окна на десктопе - `false`. Если профиль уже
|
||||
занят другим Chrome, закрой его или задай другой profile/port.
|
||||
Проверено: `probe` через browser-провайдер вернул `200`, 50 объявлений.
|
||||
|
||||
## Не-агентская часть
|
||||
|
||||
API, SQLAlchemy-БД, worker, Telegram-нотификаторы и monitor перенесены в
|
||||
`src/avito_tools/non_agent/`. Команды `serve`, `watch`, `worker`, `notify`, `db`
|
||||
сохранены для совместимости, но агенту они не нужны. Ничего не удалено.
|
||||
|
||||
## Требования
|
||||
|
||||
- Python 3.12+
|
||||
- [uv](https://docs.astral.sh/uv/)
|
||||
- Chrome/Chromium и графическая сессия для `cookies` и browser-провайдера
|
||||
- Cookies из браузера; аккаунт для поиска не обязателен
|
||||
- Российский egress (домашний сервер подходит)
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
```bash
|
||||
uv sync --extra dev
|
||||
cp .env.example .env
|
||||
uv run avito-tools cookies --mode anonymous
|
||||
# в .env: AVITO_COOKIE_FILE=var/avito-cookies.json, AVITO_ACCESS_MODE=account
|
||||
uv run avito-tools probe --query "galaxy fold 8"
|
||||
```
|
||||
|
||||
Если probe вернул `ok`, можно смотреть выдачу:
|
||||
|
||||
```bash
|
||||
uv run avito-tools search "iphone 15" --pages 2 --limit 20
|
||||
```
|
||||
|
||||
## Как достать cookies
|
||||
|
||||
Рекомендуемый способ - отдельная команда, которая открывает настоящий Chrome
|
||||
через CDP. Playwright не нужен, тяжёлые зависимости не ставятся.
|
||||
|
||||
```bash
|
||||
uv run avito-tools cookies --mode anonymous
|
||||
```
|
||||
|
||||
Откроется окно Chrome. Реши капчу, если она появилась, и нажми Enter. Команда сама
|
||||
откроет страницу поиска, дождётся PoW-проверки и попросит нажать Enter ещё раз,
|
||||
если появится капча. Cookies сохранятся в `var/avito-cookies.json` с правами `0600`.
|
||||
Нужны именно `pow_challenge` и `pow_solved`: без них API получит `439`, даже если
|
||||
остальные cookies на месте. Если команда пишет, что `pow_solved` нет, повтори capture.
|
||||
|
||||
Для account-режима:
|
||||
|
||||
```bash
|
||||
uv run avito-tools cookies --mode account
|
||||
```
|
||||
|
||||
Войди в аккаунт, реши капчу, нажми Enter. Затем добавь в `.env`:
|
||||
|
||||
```dotenv
|
||||
AVITO_COOKIE_FILE=var/avito-cookies.json
|
||||
AVITO_ACCESS_MODE=account
|
||||
AVITO_ACCOUNT_FALLBACK=true
|
||||
```
|
||||
|
||||
`AVITO_ACCESS_MODE=account` здесь означает «использовать сохранённые cookies», а не
|
||||
обязательно залогиненный аккаунт. API перечитывает файл при изменении mtime,
|
||||
перезапуск не нужен. Если файл ещё не создан, account-провайдер просто не будет
|
||||
использован до появления cookies.
|
||||
|
||||
Ручной вариант тоже работает: DevTools -> Network -> запрос к `www.avito.ru` ->
|
||||
заголовок `Cookie` -> `AVITO_COOKIE`, либо `cookies.txt` в формате Netscape.
|
||||
`AVITO_USER_AGENT` должен совпадать с браузером, из которого взяты cookies.
|
||||
|
||||
Не печатай cookies в чат и не коммить `.env` или `var/`. Для account-режима лучше
|
||||
отдельный аккаунт: основной можно потерять.
|
||||
|
||||
## Команды
|
||||
|
||||
```bash
|
||||
uv run avito-tools probe [--query "..."] [--save-raw] [--mode auto|anonymous|account] [--json]
|
||||
uv run avito-tools search "..." [--pages N] [--limit N] [--json]
|
||||
uv run avito-tools stats "..." [--pages N] [--limit N] [--outliers iqr|none] [--bins N] [--json]
|
||||
uv run avito-tools cookies [--mode anonymous|account] [--out PATH] [--print]
|
||||
uv run avito-tools mcp [--transport stdio|http] [--host 127.0.0.1] [--port 8765]
|
||||
uv run avito-tools db init
|
||||
uv run avito-tools watch add "..." --name "..." --interval 600
|
||||
uv run avito-tools watch list
|
||||
uv run avito-tools watch run ID
|
||||
uv run avito-tools worker [--once]
|
||||
uv run avito-tools notify test
|
||||
uv run avito-tools serve [--host 127.0.0.1] [--port 8000] [--reload]
|
||||
uv run avito-tools version
|
||||
```
|
||||
|
||||
`probe` по умолчанию ищет `galaxy fold 8`; запрос меняется через `--query`.
|
||||
В режиме `auto` при блокировке JSON он может сделать второй запрос через HTML.
|
||||
Для browser-провайдера первый запрос запускает Chrome и может занять дольше.
|
||||
Не запускай несколько `probe` подряд.
|
||||
|
||||
Если `probe` вернул `403` с текстом «проблема с IP», это ограничение адреса,
|
||||
а не логина. Нужно подождать или сменить egress. `439` - это PoW/cookies,
|
||||
там помогает повторный capture. В обоих случаях не стоит запускать запросы
|
||||
подряд.
|
||||
|
||||
`probe`:
|
||||
|
||||
- проверяет IP и страну egress;
|
||||
- делает один запрос к поиску;
|
||||
- проверяет JSON-схему, цены, ссылки и признаки блокировки;
|
||||
- печатает отчёт и завершается с кодом `0` (ok), `2` (blocked), `3` (drift),
|
||||
`4` (config/transport).
|
||||
|
||||
Сырые ответы сохраняются в `var/` только с флагом `--save-raw`. В них могут быть
|
||||
публичные данные продавцов, поэтому каталог в `.gitignore`.
|
||||
|
||||
## API
|
||||
|
||||
```bash
|
||||
uv run avito-tools serve --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
- `GET /healthz`, `GET /readyz`
|
||||
- `GET /api/v1/search?q=iphone%2015&pages=1&limit=50`
|
||||
- `POST /api/v1/search` с телом `{"query": "iphone 15", "price_min": 50000}`
|
||||
- `GET /api/v1/stats?q=iphone%2015&outlier_policy=iqr`
|
||||
- `POST /api/v1/stats` с телом `{"query": "iphone 15", "pages": 2}`
|
||||
- Swagger: `http://127.0.0.1:8000/docs`
|
||||
|
||||
Ошибки транспорта отдают структурированный JSON: `blocked` -> 503, `schema_drift`
|
||||
-> 502. API пока без аутентификации и по умолчанию слушает localhost. Не выставляйте
|
||||
его в интернет до Phase 2, где появится API-ключ.
|
||||
|
||||
## Статистика
|
||||
|
||||
```bash
|
||||
uv run avito-tools stats "iphone 15 pro" --pages 3 --limit 200
|
||||
```
|
||||
|
||||
Считаются `n`, min/max, `avg`, median, p25/p90/p95/p99, trimmed mean, std,
|
||||
IQR, MAD и гистограмма. По умолчанию выбросы отсекаются по IQR (`--outliers none`
|
||||
отключает). В ответе всегда есть `count`, политика выбросов и предупреждения о
|
||||
малой выборке.
|
||||
|
||||
Что означают метрики:
|
||||
|
||||
| Метрика | Смысл |
|
||||
|---|---|
|
||||
| `avg` | Среднее арифметическое. Простое, но чувствительное к выбросам |
|
||||
| `median` | Медиана, 50-й процентиль. Устойчивее к выбросам |
|
||||
| `std` | Выборочное стандартное отклонение: насколько цены разбросаны вокруг avg |
|
||||
| `IQR` | Interquartile range, p75 - p25. Ширина середины 50% цен |
|
||||
| `MAD` | Median absolute deviation: медиана отклонений от медианы. Робастный разброс |
|
||||
| `p25/p90/p95/p99` | Процентили: доля цен ниже этого значения |
|
||||
| `trimmed_mean` | Среднее после отбрасывания по 10% самых низких и высоких цен |
|
||||
|
||||
`avg` и `std` чувствительны к дорогим/дешёвым выбросам. `median`, `IQR` и `MAD`
|
||||
устойчивее; для рынка обычно полезнее смотреть на median и IQR, а avg - как
|
||||
дополнительный ориентир.
|
||||
|
||||
Это цены предложения, а не закрытых сделок. `p99` при `n < 100` помечается как
|
||||
ненадёжный.
|
||||
|
||||
## MCP для LLM
|
||||
|
||||
```bash
|
||||
uv run avito-tools mcp
|
||||
```
|
||||
|
||||
Инструменты:
|
||||
|
||||
| Инструмент | Что делает |
|
||||
|---|---|
|
||||
| `search_listings` | Живой поиск; компактные строки, без описаний по умолчанию; фильтр `seller=private/company` |
|
||||
| `get_listing` | Детали объявления из кеша текущего MCP-процесса |
|
||||
| `price_stats` | Статистика по когорте: n, avg, median, percentiles, std, IQR, MAD |
|
||||
| `avito://metrics` | Пояснения к метрикам: avg, std, IQR, MAD, процентили |
|
||||
| `avito://status` | Ресурс со статусом доступа без секретов |
|
||||
|
||||
`get_listing` пока работает только по объявлениям, которые уже вернул
|
||||
`search_listings` в этом процессе. Полноценный detail-fetch появится позже,
|
||||
вместе с отдельным provider'ом карточки.
|
||||
|
||||
Подключение в MCP-клиенте (пример для Claude/Cursor):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"avito": {
|
||||
"command": "uv",
|
||||
"args": [
|
||||
"run",
|
||||
"--directory",
|
||||
"/home/beesquit/Programming/private/avito-tools",
|
||||
"avito-tools",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
HTTP-режим:
|
||||
|
||||
```bash
|
||||
uv run avito-tools mcp --transport http --host 127.0.0.1 --port 8765
|
||||
# endpoint: http://127.0.0.1:8765/mcp
|
||||
```
|
||||
|
||||
HTTP-режим пока без аутентификации. Слушайте только localhost или ставьте
|
||||
reverse proxy с токеном.
|
||||
|
||||
## Мониторинг и Telegram
|
||||
|
||||
База по умолчанию - SQLite `var/avito.db`. Для Postgres поставьте
|
||||
`AVITO_DATABASE_URL=postgresql+asyncpg://...` и установите extra `postgres`.
|
||||
|
||||
```bash
|
||||
uv run avito-tools db init
|
||||
uv run avito-tools watch add "iphone 15" --name "iPhone 15" --interval 600
|
||||
uv run avito-tools watch list
|
||||
uv run avito-tools watch run 1
|
||||
uv run avito-tools worker
|
||||
```
|
||||
|
||||
Что происходит:
|
||||
|
||||
- первый успешный прогон поиска создаёт **baseline**: объявления сохраняются,
|
||||
но уведомления не отправляются;
|
||||
- следующие прогоны создают `matches` только для новых объявлений;
|
||||
- цена и история пишутся в `listing_snapshots`;
|
||||
- уведомления складываются в outbox и отправляются worker'ом;
|
||||
- при `439/429` прогон помечается failed, а не «0 объявлений»;
|
||||
- worker опрашивает только due-поиски и сериализует запросы к Авито.
|
||||
|
||||
Telegram:
|
||||
|
||||
```dotenv
|
||||
AVITO_TELEGRAM_BOT_TOKEN=...
|
||||
AVITO_TELEGRAM_CHAT_ID=...
|
||||
```
|
||||
|
||||
Проверка:
|
||||
|
||||
```bash
|
||||
uv run avito-tools notify test
|
||||
```
|
||||
|
||||
Без Telegram уведомления остаются в статусе `pending`, их можно отправить позже,
|
||||
когда коннектор настроен. `AVITO_WORKER_POLL_INTERVAL_SEC` задаёт частоту цикла
|
||||
worker'а, `AVITO_NOTIFICATION_MAX_ATTEMPTS` - число попыток доставки.
|
||||
|
||||
## Что дальше
|
||||
|
||||
- Phase 1: MCP-инструменты `search_listings`, `get_listing`, `price_stats`
|
||||
и минимальный REST на том же сервисном слое.
|
||||
- Phase 2: Postgres, сохранённые поиски, планировщик, Telegram.
|
||||
- Phase 3: NL-матчинг с evidence, полный REST, Mattermost/webhook.
|
||||
|
||||
## Разработка
|
||||
|
||||
```bash
|
||||
uv run pytest
|
||||
uv run ruff check .
|
||||
uv run mypy src
|
||||
basedpyright
|
||||
```
|
||||
|
||||
`basedpyright` настроен на `src`; тесты и клоны в `dev/` исключены из проверки.
|
||||
CI и живые запросы к Авито разделены: тесты работают на фикстурах и фейковом
|
||||
HTTP-клиенте, реальные запросы - только вручную через `probe`.
|
||||
+483
@@ -0,0 +1,483 @@
|
||||
# Avito Intelligence - дизайн проекта
|
||||
|
||||
Статус: черновик для обсуждения. Дата: 2026-10-31.
|
||||
|
||||
## 1. Что я понял из задачи
|
||||
|
||||
Self-hosted сервис, который:
|
||||
|
||||
1. **Мониторит Авито** по сохранённым поискам (фильтры: запрос, категория, регион, цена,
|
||||
параметры) и находит **новые** объявления.
|
||||
2. **Проверяет объявления по произвольным критериям** на естественном языке
|
||||
(«Galaxy Fold 6 с неработающим Bluetooth») - не только по словам, но и по смыслу,
|
||||
с объяснением, почему объявление подошло.
|
||||
3. **Считает статистику** по совокупности подходящих объявлений: средняя, медиана,
|
||||
min/max, p90/p95/p99, разброс, гистограмма, тренд, «насколько цена ниже рынка».
|
||||
4. **Отдаёт всё через API** (REST, OpenAPI).
|
||||
5. **Даёт LLM набор инструментов** (MCP), чтобы искать, смотреть, фильтровать и считать
|
||||
статистику, а при необходимости - делать низкоуровневые запросы к Авито.
|
||||
6. **Уведомляет через подключаемые коннекторы**: Telegram в первую очередь,
|
||||
Mattermost/webhook - как универсальный механизм.
|
||||
|
||||
Вне MVP (обсуждаемо): публичный SaaS, автопостинг объявлений, сбор телефонов/PII,
|
||||
обход капчи, собственный веб-UI, биллинг, мультитенантность.
|
||||
|
||||
## 2. Ключевое ограничение, которое определяет всю архитектуру
|
||||
|
||||
**У официального API Авито нет поиска по чужим объявлениям.** Официальный API - это
|
||||
свой аккаунт: автозагрузка, мессенджер, статистика своих объявлений, продвижение,
|
||||
доставка, заказы. Поиск по всей площадке - только неофициальный web/mobile JSON,
|
||||
который защищён антиботом.
|
||||
|
||||
Следствия:
|
||||
|
||||
- Транспорт Авито **изолирован** за интерфейсом `SearchProvider`. Его можно заменить
|
||||
на платный scraping API или на другую реализацию без переписывания продукта.
|
||||
- Нужен **российский egress** (резидентный прокси или VPS в РФ) и «прогретые» cookies.
|
||||
Датацентровые IP умирают за десятки запросов.
|
||||
- Реальность антибота: `403`, `429`, нестандартный `439`, капча и **«отравленные» 200**
|
||||
(ответ 200, но данные неверные). Поэтому нужны канарейки качества данных и явная
|
||||
деградация, а не «пустой результат».
|
||||
- ToS Авито запрещает автоматизированный сбор. Проект задуман как **внутренняя
|
||||
аналитика**: без перепубликации объявлений, без сбора PII, с уважением к лимитам и
|
||||
возможностью быстро отключиться. Это engineering-риск, а не юридическая консультация.
|
||||
- Система должна **переживать потерю доступа**: fallback-провайдер, честные ошибки,
|
||||
никаких ложных «ничего не найдено» при блокировке.
|
||||
|
||||
## 3. Пользовательские сценарии
|
||||
|
||||
1. **Мониторинг.** «iPhone 15 Pro 256 ГБ, Москва, до 80 000 ₽, не битый» - раз в 10 минут;
|
||||
новые объявления → Telegram; в уведомлении цена, ссылка, причина совпадения.
|
||||
2. **Кастомный запрос.** «Galaxy Fold 6 с неработающим Bluetooth» - широкий поиск по
|
||||
модели, затем LLM-проверка описаний; на выходе ранжированный список с цитатами.
|
||||
3. **Статистика.** «Сколько стоит Fold 6 в Москве за 30 дней» - медиана, p90/p95/p99,
|
||||
гистограмма, тренд, размер выборки и предупреждение о выбросах.
|
||||
4. **LLM-чат.** «Найди Fold 6 с дефектами Bluetooth дешевле p25 и покажи статистику» -
|
||||
агент вызывает MCP-инструменты.
|
||||
5. **Проверка по ссылке.** «Вот объявление, подходит ли оно под мои критерии?»
|
||||
|
||||
## 4. Архитектура
|
||||
|
||||
```
|
||||
Telegram MCP-клиенты (Claude/Cursor/...) REST-клиенты
|
||||
| | |
|
||||
v v v
|
||||
aiogram bot MCP server (FastMCP) FastAPI /api/v1
|
||||
\_______________________|_____________________________/
|
||||
v
|
||||
Service layer (Python)
|
||||
searches | listings | matching | analytics | notifications
|
||||
|
|
||||
+-------------+-------------+
|
||||
| |
|
||||
v v
|
||||
PostgreSQL Worker / scheduler
|
||||
(listings, history, matches, (APScheduler + DB-очередь,
|
||||
searches, outbox, jobs) SKIP LOCKED, retries)
|
||||
|
|
||||
v
|
||||
Collector service
|
||||
providers | identities | pacing | canary
|
||||
|
|
||||
+--------------------+--------------------+
|
||||
v v v
|
||||
Avito web/mobile Official API Paid fallback
|
||||
(unofficial) (own account) (optional)
|
||||
|
|
||||
v
|
||||
Notifier registry
|
||||
Telegram | Mattermost | webhook | ...
|
||||
```
|
||||
|
||||
Компоненты и границы:
|
||||
|
||||
- **API** - stateless FastAPI; аутентификация по API-ключу; OpenAPI; версия `/api/v1`.
|
||||
- **Worker** - планировщик и исполнитель фоновых задач. Очередь на Postgres
|
||||
(`FOR UPDATE SKIP LOCKED`), без Redis в MVP; advisory lock на планировщик.
|
||||
- **Collector** - единственный компонент, который ходит в Авито. Централизованные
|
||||
rate limit, ротация identities, канарейки, нормализация. Может жить на отдельной
|
||||
машине с российским egress.
|
||||
- **MCP server** - тонкий адаптер над сервисами/API; по умолчанию read-only,
|
||||
write-инструменты включаются явно.
|
||||
- **Bot** - опциональный интерфейс подписок и быстрых запросов; ходит через API.
|
||||
|
||||
Почему так: неофициальный доступ - самая хрупкая часть. Её замена не должна задевать
|
||||
БД, аналитику, API и LLM-слой. Collector можно перезапускать/менять независимо.
|
||||
|
||||
## 5. Модель данных (Postgres)
|
||||
|
||||
Основные таблицы:
|
||||
|
||||
- `listings` - объявление, уникальное `(source, external_id)`:
|
||||
`url, title, description, price, currency, category_id, category_name, location,
|
||||
seller_id, seller_name, seller_type, params JSONB, images JSONB, published_at,
|
||||
first_seen_at, last_seen_at, status, content_hash, raw JSONB`.
|
||||
- `listing_snapshots` - история цены/статуса: `listing_id, observed_at, price, status`.
|
||||
- `searches` - сохранённый поиск: `name, query, category_id, location, price_min/max,
|
||||
params JSONB, include/exclude keywords, semantic_criteria, poll_interval_sec,
|
||||
enabled, baseline_completed, last_run_at, owner`.
|
||||
- `search_runs` - запуск: `search_id, started_at, finished_at, status, fetched, new,
|
||||
matched, error_code, error_detail`.
|
||||
- `matches` - `(search_id, listing_id)` unique, `score, reasons JSONB, evidence JSONB,
|
||||
notified_at`.
|
||||
- `evaluations` - кэш LLM-проверок: `listing_hash, criteria_hash, model, prompt_hash,
|
||||
verdict, confidence, reasons, evidence, created_at`.
|
||||
- `analyses` - сохранённые расчёты статистики: `spec JSONB, result JSONB, created_at`.
|
||||
- `connectors` - `type, name, config_encrypted, enabled, event_filter`.
|
||||
- `notifications` - outbox: `event, connector_id, payload, status, attempts, last_error,
|
||||
dedupe_key` (unique).
|
||||
- `identities` - прокси + cookies + fingerprint, health, last_used, blocked_until.
|
||||
- `job_queue`, `job_runs` - очередь и история задач.
|
||||
- `settings` - глобальные настройки.
|
||||
|
||||
Индексы: GIN по `params`, FTS (russian) + trigram по `title/description`,
|
||||
`(status, category_id, price)`, `(search_id, matched_at)`. Сырые payload'ы - с TTL
|
||||
(например, 30 дней) и без PII.
|
||||
|
||||
## 6. Пайплайн обработки
|
||||
|
||||
1. Планировщик выбирает поиски, у которых наступил `poll_interval`.
|
||||
2. Collector забирает страницы поиска (пагинация + стоп по `sortTimeStamp`/уже
|
||||
известным id), с паузами и джиттером.
|
||||
3. Нормализация → upsert в `listings`; определение `first_seen`; снимок цены при
|
||||
изменении.
|
||||
4. **Baseline**: первый прогон поиска сохраняет существующие объявления, но не
|
||||
спамит уведомлениями; уведомления начинаются со следующего прогона (или с
|
||||
объявлений, опубликованных после создания поиска).
|
||||
5. Дешёвые фильтры: цена, регион, категория, include/exclude, продавец.
|
||||
6. Обогащение: карточка объявления (описание, параметры) - только для кандидатов,
|
||||
с бюджетом запросов и кэшем.
|
||||
7. Семантическая проверка (если задана) - батчами, с кэшем и порогом.
|
||||
8. Запись `matches`; уведомления через outbox с дедупликацией.
|
||||
9. Периодически: снимки цен, переоценка активных объявлений, пометка `inactive`
|
||||
после нескольких глубоких сканов, канарейки качества.
|
||||
|
||||
## 7. Кастомные NL-запросы («с неработающим Bluetooth»)
|
||||
|
||||
Двухстадийная схема:
|
||||
|
||||
1. **Разбор запроса** в `QuerySpec`: ключевые слова, цена, регион, категория,
|
||||
обязательные/запрещённые признаки. Правила + LLM; результат показывается
|
||||
пользователю и редактируется.
|
||||
2. **Широкий retrieval** по Авито (модель/серия) + жёсткие фильтры, затем
|
||||
FTS/trigram по названию и описанию. Ограничение кандидатов (например, 100).
|
||||
3. **LLM-адjudication**: батч по 10-20 объявлений; строгая JSON-схема
|
||||
`{verdict, confidence, reasons[], evidence[]}`; `evidence` - цитаты из текста.
|
||||
Сначала дешёвая модель для триажа, спорные - сильной. Кэш по
|
||||
`(content_hash, criteria_hash, model, prompt_hash)`.
|
||||
4. Порог и ручная проверка: `match`, `no_match`, `unknown` (нет описания/данных).
|
||||
В UI/API всегда видны причина и цитата.
|
||||
|
||||
Почему не только эмбеддинги: отрицания и дефекты («не работает», «без Bluetooth»,
|
||||
«на запчасти») плохо ловятся косинусной близостью. Эмбеддинги можно добавить позже
|
||||
для recall, но решение принимает LLM по evidence. LLM никогда не «придумывает»
|
||||
объявления - только оценивает переданные.
|
||||
|
||||
## 8. Аналитика цен
|
||||
|
||||
Метрики: `n`, avg, median, min, max, p25/p90/p95/p99, trimmed mean, std,
|
||||
IQR, MAD, гистограмма, тренд по неделям, percentile rank объявления (deal score).
|
||||
`avg` - среднее арифметическое; `std` - выборочное стандартное отклонение;
|
||||
`IQR` = p75 - p25; `MAD` - медиана абсолютных отклонений от медианы.
|
||||
|
||||
- Когорта = фильтры + окно дат + `status=active`; параметры и политика выбросов
|
||||
возвращаются вместе с результатом.
|
||||
- `p99` при `n < 100` помечается как ненадёжный; API всегда отдаёт `n` и
|
||||
предупреждения.
|
||||
- Это **цены предложения**, а не сделки. Отдельно можно оценивать «время до
|
||||
исчезновения» по `first_seen/last_seen` как прокси ликвидности.
|
||||
- Выбросы: none / IQR-fence / log-trim; по умолчанию IQR, но с показом обоих рядов.
|
||||
- Расчёт в SQL (`percentile_cont`) + numpy для robust-метрик; кэш для тяжёлых когорт.
|
||||
|
||||
## 9. LLM-инструменты (MCP)
|
||||
|
||||
Принципы: 4-8 инструментов на профиль, компактные ответы, ID + курсоры вместо
|
||||
простыней текста, write-операции выключены по умолчанию, никакого HTML и cookie
|
||||
наружу, scraping остаётся в collector.
|
||||
|
||||
Read-only (MVP):
|
||||
|
||||
| Инструмент | Назначение |
|
||||
|---|---|
|
||||
| `search_listings` | Живой поиск с фильтрами; компактные строки + `next_cursor` |
|
||||
| `get_listing` | Карточка по id/URL: описание, параметры, история цены |
|
||||
| `find_matching` | Проверка критериев на естественном языке по scope (live/поиск/ID) |
|
||||
| `price_stats` | Статистика по когорте + методология и warnings |
|
||||
| `list_saved_searches` | Список сохранённых поисков (или MCP resource) |
|
||||
| `get_search_matches` | Совпадения поиска с причинами |
|
||||
|
||||
Write (явно включаемые): `create_watch`, `run_saved_search`, `test_connector`.
|
||||
Админский `avito_raw_get` - allowlist путей/хостов, rate limit, выключен по умолчанию.
|
||||
|
||||
Транспорт: stdio для локальных клиентов, Streamable HTTP для удалённых; auth-токен.
|
||||
Ресурсы: `avito://searches`, `avito://listings/{id}`, `avito://analyses/{id}`.
|
||||
Тяжёлые описания - через ресурс/`get_listing`, а не в каждом ответе поиска.
|
||||
|
||||
## 10. REST API
|
||||
|
||||
```
|
||||
POST /api/v1/searches создать поиск
|
||||
GET /api/v1/searches список
|
||||
GET /api/v1/searches/{id}
|
||||
PATCH /api/v1/searches/{id}
|
||||
DELETE /api/v1/searches/{id}
|
||||
POST /api/v1/searches/{id}/run запустить сейчас (job)
|
||||
GET /api/v1/searches/{id}/matches
|
||||
GET /api/v1/listings/{id}
|
||||
GET /api/v1/listings фильтры/курсор
|
||||
POST /api/v1/search разовый живой поиск
|
||||
POST /api/v1/matching проверка критериев по scope
|
||||
POST /api/v1/analyses посчитать статистику (sync/async)
|
||||
GET /api/v1/analyses/{id}
|
||||
GET /api/v1/connectors
|
||||
POST /api/v1/connectors
|
||||
POST /api/v1/connectors/{id}/test
|
||||
GET /api/v1/jobs/{id}
|
||||
GET /healthz, /readyz, /metrics
|
||||
```
|
||||
|
||||
Правила: Bearer API-ключ, cursor-пагинация, ошибки в RFC 7807, idempotency-key для
|
||||
POST, длинные операции → job id. OpenAPI генерируется, SDK - позже.
|
||||
|
||||
## 11. Уведомления
|
||||
|
||||
`Notifier` protocol: `send(event) -> DeliveryResult`. Адаптеры: Telegram Bot API,
|
||||
Mattermost incoming webhook, generic webhook (HMAC), позже email/Slack/Discord.
|
||||
События: `new_match`, `price_drop`, `digest`, `job_failed`, `collector_degraded`.
|
||||
|
||||
Маршрутизация: коннектор + фильтр по поискам/минимальному score/тихим часам.
|
||||
Дедупликация `(listing_id, event_type, connector_id)`, outbox, retry с backoff,
|
||||
dead-letter, журнал доставок, кнопка «тест». Telegram: HTML, без preview,
|
||||
media group для фото, соблюдение 1 msg/sec.
|
||||
|
||||
## 12. Стек и структура репозитория
|
||||
|
||||
**Python 3.13+** (в системе 3.14), `uv`. Причины: готовый клиент официального API,
|
||||
FastMCP, aiogram, numpy/scipy, удобный scraping (`curl_cffi`).
|
||||
|
||||
- FastAPI + Pydantic v2 + SQLAlchemy 2 (async) + Alembic + asyncpg
|
||||
- httpx; `curl_cffi` для TLS-имперсонации
|
||||
- SQLite по умолчанию для локального запуска; Postgres через `AVITO_DATABASE_URL`
|
||||
- worker на asyncio: due-searches в БД, последовательные запросы, outbox
|
||||
- FastMCP (Python)
|
||||
- aiogram
|
||||
- structlog, Prometheus, Sentry (опционально)
|
||||
- pytest, respx, testcontainers, ruff, mypy
|
||||
|
||||
```
|
||||
avito-tools/
|
||||
pyproject.toml
|
||||
src/avito_tools/
|
||||
config.py
|
||||
domain.py
|
||||
collector/ # json/html/browser providers, http, canary
|
||||
analytics/ # статистика цен
|
||||
services/ # search, stats (агентское ядро)
|
||||
mcp/ # tools, resources, server
|
||||
cookies.py
|
||||
cookies_capture.py
|
||||
probe.py
|
||||
cli.py
|
||||
non_agent/ # сохранено отдельно, не мешает агенту
|
||||
api/ # FastAPI
|
||||
db/ # SQLAlchemy
|
||||
worker/ # мониторинг
|
||||
notifiers/ # Telegram
|
||||
services/ # monitor, searches
|
||||
tests/
|
||||
docs/
|
||||
```
|
||||
|
||||
Агентский срез - `collector` -> `services/search`/`stats` -> `mcp`. API, worker,
|
||||
БД и уведомления вынесены в `non_agent` и оставлены для истории/ручного запуска.
|
||||
|
||||
Переиспользование из `dev/` (лицензии MIT):
|
||||
|
||||
- **`avito_python_api`** - брать как зависимость для официального API: ~200
|
||||
типизированных операций, sync+async, пагинация, OAuth-кэш, retry, CLI. Полезные
|
||||
готовые агрегаты `business_summary` / `listing_health` пригодятся для блока
|
||||
«мои объявления», но к поиску чужих объявлений отношения не имеют. Осторожно:
|
||||
статус пакета - alpha, Python ≥3.12.
|
||||
- **`avito-mcp`** (TS) - не вендорить, но забрать паттерны MCP: декларативные
|
||||
`ToolSpec`, классы риска (`read/write/money/public`), «скрывать, а не запрещать»
|
||||
опасные инструменты, двухфазное подтверждение + idempotency для write,
|
||||
структурные ошибки с `retryable`, durable rate limiter, allowlist хостов для
|
||||
raw-инструментов. Его 148 инструментов (~56k токенов схем) - антипример: нам
|
||||
нужно 4-8 доменных инструментов.
|
||||
- **`marketplaces-mcp-ru`** - паттерны каталога методов и мультипровайдерных
|
||||
коннекторов, если позже добавим WB/Ozon. Не копировать: HTTP-транспорт без
|
||||
аутентификации и неограниченные `*_raw` инструменты.
|
||||
- **`avito-parser-monitor` / `avito-scraper`** - идеи нормализации, polling,
|
||||
dedupe и Telegram-уведомлений. Код не вендорим.
|
||||
|
||||
Важная находка: **ни в одном из репозиториев нет saved search / watchlist /
|
||||
price alerts** - эту часть строим сами. Официальный API покрывает только свой
|
||||
аккаунт (204 операции, поиска чужих объявлений нет), что подтверждает границу
|
||||
архитектуры.
|
||||
|
||||
## 13. Надёжность и антибот
|
||||
|
||||
- Пул `identities`: прокси + cookies + fingerprint; concurrency 1 на identity,
|
||||
паузы 1.5-4.5 с с джиттером, дневные бюджеты.
|
||||
- Обработка `403/429/439`: exponential backoff, затем карантин identity и ротация.
|
||||
- `439` у Авито - это часто не жёсткий блок, а PoW-challenge. Браузер решает его
|
||||
JS-ом и ставит `pow_challenge` + `pow_solved`; без этих cookies `curl_cffi`
|
||||
получает `439`, даже если остальные cookies валидны. Capture-команда специально
|
||||
открывает страницу поиска и сохраняет PoW-cookies. Сессия живёт ограниченно,
|
||||
поэтому при `439` нужно повторить capture, а не долбить запросами.
|
||||
- Фильтр «Частные» на Авито - это URL-параметр `user=1` (компании - `user=2`).
|
||||
`web/1/js/items` его игнорирует; HTML-выдача применяет фильтр и помечает
|
||||
`Частные` в radio. Для точной выборки нужен HTML-провайдер, а не JSON.
|
||||
- **Канарейки** на каждый ответ: ожидаемые ключи схемы, непустой `urlPath`,
|
||||
адекватный диапазон цен, `total_count` vs items, совпадение категории,
|
||||
контрольная выборка. «Отравленный 200» → `drift`, данные не пишутся.
|
||||
- Блокировка ≠ пустой результат: API отдаёт `collector_unavailable`/`rate_limited`,
|
||||
а не «0 объявлений».
|
||||
- Rollback: сырые ответы (с TTL) для replay; fixture-провайдер для тестов.
|
||||
- Fallback: платный API (omkarcloud/Apify) как отдельный provider, включаемый флагом.
|
||||
- Метрики: block rate, drift rate, latency, new listings, match rate, notification
|
||||
failures; алерты в тот же notifier.
|
||||
|
||||
## 14. Безопасность и юридическая гигиена
|
||||
|
||||
- API-ключ (MVP), TLS, bind на localhost по умолчанию; MCP HTTP - токен.
|
||||
- Секреты: env + шифрование полей БД (Fernet, мастер-ключ в env); cookies не в логах.
|
||||
- Не хранить телефоны/имена продавцов без необходимости; только публичные данные.
|
||||
- Retention: raw 30 дней, уведомления 90 дней, листинги/история - бессрочно.
|
||||
- Никакой перепубликации контента, никакого сбора PII, уважение к robots.txt и
|
||||
требованиям площадки; возможность быстро выключить collector.
|
||||
- Дисклеймер в README: ToS Авито ограничивает автоматизацию; ответственность на
|
||||
операторе; для внутренней аналитики.
|
||||
|
||||
## 15. Тесты и качество
|
||||
|
||||
- Unit: нормализация (golden fixtures с обезличенными payload'ами), статистика
|
||||
(сверка с numpy), QuerySpec, JSON-валидация LLM, форматирование уведомлений.
|
||||
- Integration: фейковый Avito-сервер (FastAPI) со сценариями: normal, 403, 429, 439,
|
||||
poisoned 200, drift схемы, пустая выдача.
|
||||
- Contract: snapshot OpenAPI и схем MCP-инструментов.
|
||||
- E2E: docker compose smoke на фикстурах; live-smoke только вручную и по флагу.
|
||||
- CI: ruff, mypy, pytest, coverage; запрет реальных запросов в CI.
|
||||
|
||||
## 16. Этапы (с учётом ответов)
|
||||
|
||||
**Вводные:** домашний сервер с белым IP и аккаунт Авито; бюджет на прокси/платные
|
||||
API - 0 ₽; первый сценарий - LLM/MCP-инструменты; веб-UI - позже.
|
||||
|
||||
**Phase 0 - spike (критично).** Проверить, что домашний IP геолоцируется в РФ и не
|
||||
заблокирован; экспортировать cookies; сделать 10-20 запросов к web/mobile JSON;
|
||||
проверить канарейки. Результат: CLI `probe` + отчёт. Без этого проекта нет.
|
||||
Рекомендация: не использовать основной аккаунт для автоматизации - риск блокировки;
|
||||
как минимум низкий темп и отдельная сессия.
|
||||
|
||||
**Phase 1 - MCP-first vertical slice.** Живой поиск + карточка объявления + статистика
|
||||
по результатам; MCP-инструменты `search_listings`, `get_listing`, `price_stats`;
|
||||
минимальный REST (`/healthz`, `/search`, `/stats`) на том же сервисном слое; CLI
|
||||
`probe/search/stats/mcp`. Без Postgres: in-memory кэш и дедупликация. Это самый
|
||||
быстрый способ проверить оба риска - доступ и качество данных.
|
||||
|
||||
**Phase 2 - persistence и мониторинг.** Postgres, миграции, `listings`/`price_history`,
|
||||
сохранённые поиски, планировщик, baseline, дедупликация, Telegram-коннектор, outbox.
|
||||
REST CRUD поисков и матчей.
|
||||
|
||||
**Phase 3 - NL-матчинг и API-полнота.** QuerySpec, LLM-адjudication с evidence, кэш
|
||||
оценок, `matches`, расширенный REST, write-инструменты MCP, Mattermost/webhook.
|
||||
|
||||
**Phase 4 - hardening.** Канарейки/drift-алерты, метрики, retention, бэкапы,
|
||||
документация, fallback-провайдер (если появится бюджет), нагрузочные проверки.
|
||||
|
||||
## 17. Альтернативы, которые рассматривал
|
||||
|
||||
| Вариант | Плюсы | Почему не базовый |
|
||||
|---|---|---|
|
||||
| Форк `avito-parser-monitor` / `avito-scraper` | Быстрый MVP, готовый парсинг и Telegram | Монолит без API/аналитики/MCP; у части репо нет лицензии; жёсткая привязка к транспорту. Берём как reference |
|
||||
| n8n / скрипты + бот | Дёшево для алертов | Нет нормальной модели данных, истории цен, статистики и LLM-инструментов |
|
||||
| Только официальный API | Легально, стабильно | Нет поиска чужих объявлений - не решает задачу |
|
||||
| Платный scraping API как ядро | Не нужен свой антибот | Дорого, зависимость от вендора, нет SLA; оставляем как fallback |
|
||||
| TypeScript-монорепо | Сильный `avito-mcp` как образец | Python выигрывает по SDK, FastMCP, статистике, aiogram; UI не в MVP |
|
||||
| Микросервисы / k8s | Масштабирование | Оверинжиниринг для одного пользователя; модульный монолит + отдельный worker/collector |
|
||||
|
||||
## 18. Критерии успеха MVP
|
||||
|
||||
- MCP/API отдаёт результаты поиска и статистику за один вызов, без ручного парсинга.
|
||||
- Успешность прогонов поиска >95% при доступном egress; блокировки и drift видны
|
||||
в ответах и метриках и не выглядят как «0 объявлений».
|
||||
- Статистика всегда отдаёт `n`, окно даты и метод обработки выбросов; p99 не
|
||||
показывается как надёжный при малой выборке.
|
||||
- Нет дублей матчей и уведомлений; повторный прогон идемпотентен.
|
||||
- MCP-инструмент на кэшированных данных отвечает <2 с и не раздувает контекст
|
||||
(компактные строки, курсоры, описания - по запросу).
|
||||
- Любой матч объясним: причина + цитата из объявления.
|
||||
|
||||
## 19. Принятые решения и что осталось проверить
|
||||
|
||||
Принято:
|
||||
|
||||
- Python 3.13+, FastAPI, FastMCP, Postgres (со Phase 2), Docker Compose.
|
||||
- Один пользователь, self-hosted на домашнем сервере с белым IP.
|
||||
- Бюджет 0 ₽: без прокси и платных scraping API; fallback-провайдер - только
|
||||
архитектурная возможность.
|
||||
- MCP-first MVP; Telegram - Phase 2; веб-UI - позже.
|
||||
- Cookies заводятся вручную; автоматический логин не делаем.
|
||||
- Основной источник - неофициальный web JSON, карточка - mobile API/JSON-LD.
|
||||
|
||||
Осталось проверить/решить:
|
||||
|
||||
1. Геолокация и репутация домашнего IP (Phase 0 `probe`).
|
||||
2. Использовать основной аккаунт или отдельный (риск блокировки основного).
|
||||
3. Нужны ли позже credentials официального API для своих объявлений/статистики.
|
||||
4. Формат веб-UI, когда дойдём до него.
|
||||
|
||||
Дефолты: single-tenant, без публичного доступа, API-ключ, bind на localhost.
|
||||
|
||||
## 20. Текущее состояние (2026-10-31)
|
||||
|
||||
- Собран скелет Phase 0: пакет `avito_tools`, конфиг через env, `curl_cffi`-клиент,
|
||||
web-провайдер поиска, канарейки, CLI `probe/search/stats/serve`, FastAPI
|
||||
`/healthz`, `/readyz`, `/api/v1/search`, `/api/v1/stats`, тесты на фикстурах.
|
||||
- Аналитика цен: `compute_price_stats` (quantiles, IQR-выбросы, trimmed mean,
|
||||
MAD, гистограмма) и `PriceStatsService` поверх поиска.
|
||||
- Режимы `anonymous`/`account` с fallback, `CookieStore` с перечитыванием файла
|
||||
по mtime, команда `avito-tools cookies` на системном Chrome через CDP.
|
||||
- Живая проверка: anonymous bootstrap получает `439`; Авито отдаёт PoW-challenge.
|
||||
Capture через headed Chrome решает PoW, сохраняет `pow_challenge`/`pow_solved`,
|
||||
после чего `probe --mode account` вернул `200`, 50 объявлений, total 1500.
|
||||
- Проверены `search` и `stats` на живых данных: статистика считает 47 цен после
|
||||
IQR-выбросов, гистограмма и квантили корректны.
|
||||
- MCP-сервер (FastMCP) собран: `search_listings`, `get_listing` из кеша,
|
||||
`price_stats`, ресурс `avito://status`. Проверен in-memory клиентом на живых
|
||||
данных: поиск вернул 3 объявления, статистика 47 цен, median 37490.
|
||||
- `get_listing` пока ограничен кешем текущего процесса; detail-fetch и
|
||||
persistence - вместе с Postgres.
|
||||
- Добавлен HTML-провайдер поиска для account-сессий, которые не проходят JSON-PoW:
|
||||
`AVITO_SEARCH_PROVIDER=auto|json|html`, `AVITO_HTML_SEARCH_PATH`.
|
||||
Парсер покрыт фикстурой, без живых запросов.
|
||||
- basedpyright настроен на `src` и проходит с `0 errors, 0 warnings`; 71 тест,
|
||||
ruff и mypy зелёные. Живые запросы к Авито не выполнялись.
|
||||
- Phase 2 foundation: SQLite по умолчанию (`var/avito.db`), Postgres через
|
||||
`AVITO_DATABASE_URL` + extra `postgres`; таблицы listings, snapshots, searches,
|
||||
search_runs, matches, notifications; worker с baseline, дедупликацией,
|
||||
sequential polling и outbox; Telegram-нотификатор и `notify test`.
|
||||
- Живой `watch run` на текущей сессии упёрся в истёкшие pow-cookies и записал
|
||||
failed run, что подтверждает корректную обработку блокировки. Baseline,
|
||||
новые матчи, price snapshots и retry-доставка покрыты unit-тестами на SQLite.
|
||||
- Следующий шаг: пересобрать cookies через `cookies`, прогнать живой watch,
|
||||
затем API CRUD поисков, Alembic и Postgres.
|
||||
- Важно: запросы к Авито нельзя выполнять параллельно одной сессией. Два
|
||||
одновременных процесса дали блокировку; worker должен сериализовать запросы
|
||||
per identity.
|
||||
- Следующий шаг: MCP-инструменты Phase 1 поверх рабочего поиска и статистики.
|
||||
- Агентское ядро отделено: `collector`, `analytics`, `services/search`,
|
||||
`services/stats`, `mcp`. API, SQLAlchemy-БД, worker, notifiers и monitor
|
||||
перенесены в `src/avito_tools/non_agent/` и сохранены.
|
||||
- Добавлен browser-провайдер: Chrome через CDP открывает страницу поиска, отдаёт
|
||||
HTML, парсер строит `ListingCard`. Настройки: `AVITO_SEARCH_PROVIDER=browser`,
|
||||
`AVITO_BROWSER_PROFILE`, `AVITO_BROWSER_CDP_PORT`, `AVITO_BROWSER_HEADLESS`.
|
||||
- Причина browser-провайдера: egress браузера и сервера совпадает, но
|
||||
`curl_cffi`/HTML получает `403`, а Chrome открывает Авито. Значит, режется
|
||||
fingerprint, а не IP.
|
||||
- MCP получил фильтр `seller=private|company`, который прокидывает Avito `user=1/2`.
|
||||
- Browser-провайдер проверен живым `probe`: `200`, 50 объявлений, latency 8.1 с.
|
||||
Сервисный shell без `DISPLAY`, поэтому Chrome работает headless
|
||||
(`AVITO_BROWSER_HEADLESS=true`); профиль `var/chrome-profile` с логином.
|
||||
- basedpyright: 0 errors, 0 warnings; 79 тестов, ruff/mypy зелёные.
|
||||
@@ -0,0 +1,63 @@
|
||||
[project]
|
||||
name = "avito-tools"
|
||||
version = "0.1.0"
|
||||
description = "Avito search, price analytics and MCP tools"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
license = { text = "MIT" }
|
||||
dependencies = [
|
||||
"aiosqlite>=0.20",
|
||||
"curl-cffi>=0.11",
|
||||
"fastapi>=0.115",
|
||||
"fastmcp>=4.1",
|
||||
"greenlet>=3.5.6",
|
||||
"httpx>=0.28",
|
||||
"pydantic>=2.9",
|
||||
"pydantic-settings>=2.5",
|
||||
"sqlalchemy>=2.0",
|
||||
"uvicorn[standard]>=0.34",
|
||||
"websockets>=15",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"httpx>=0.28",
|
||||
"pytest>=8.3",
|
||||
"pytest-cov>=6.0",
|
||||
"ruff>=0.9",
|
||||
"mypy>=1.14",
|
||||
]
|
||||
postgres = ["asyncpg>=0.30"]
|
||||
|
||||
[project.scripts]
|
||||
avito-tools = "avito_tools.cli:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/avito_tools"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src", "."]
|
||||
addopts = "-q"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
extend-exclude = ["dev", ".venv", "var"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B", "SIM"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
warn_unused_configs = true
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.basedpyright]
|
||||
include = ["src"]
|
||||
exclude = ["dev", ".venv", "var", "tests"]
|
||||
typeCheckingMode = "basic"
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,15 @@
|
||||
from avito_tools.analytics.stats import (
|
||||
HistogramBin,
|
||||
OutlierPolicy,
|
||||
PriceStats,
|
||||
StatsMethod,
|
||||
compute_price_stats,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"HistogramBin",
|
||||
"OutlierPolicy",
|
||||
"PriceStats",
|
||||
"StatsMethod",
|
||||
"compute_price_stats",
|
||||
]
|
||||
@@ -0,0 +1,178 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import statistics
|
||||
from collections.abc import Sequence
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
OutlierPolicy = Literal["none", "iqr"]
|
||||
|
||||
|
||||
class HistogramBin(BaseModel):
|
||||
lower: float
|
||||
upper: float
|
||||
count: int
|
||||
|
||||
|
||||
class StatsMethod(BaseModel):
|
||||
outlier_policy: OutlierPolicy
|
||||
outlier_count: int = 0
|
||||
trimmed_fraction: float = 0.1
|
||||
|
||||
|
||||
class PriceStats(BaseModel):
|
||||
count: int = 0
|
||||
currency: str = "RUB"
|
||||
min: float | None = None
|
||||
max: float | None = None
|
||||
avg: float | None = None
|
||||
median: float | None = None
|
||||
p25: float | None = None
|
||||
p90: float | None = None
|
||||
p95: float | None = None
|
||||
p99: float | None = None
|
||||
trimmed_mean: float | None = None
|
||||
std: float | None = None
|
||||
iqr: float | None = None
|
||||
mad: float | None = None
|
||||
histogram: list[HistogramBin] = Field(default_factory=list)
|
||||
method: StatsMethod
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def compute_price_stats(
|
||||
prices: Sequence[int | float],
|
||||
*,
|
||||
currency: str = "RUB",
|
||||
outlier_policy: OutlierPolicy = "iqr",
|
||||
histogram_bins: int = 10,
|
||||
trim_fraction: float = 0.1,
|
||||
) -> PriceStats:
|
||||
warnings: list[str] = []
|
||||
method = StatsMethod(
|
||||
outlier_policy=outlier_policy,
|
||||
trimmed_fraction=trim_fraction,
|
||||
)
|
||||
values = sorted(
|
||||
float(price)
|
||||
for price in prices
|
||||
if price is not None and math.isfinite(float(price))
|
||||
)
|
||||
if not values:
|
||||
warnings.append("no priced listings")
|
||||
return PriceStats(currency=currency, method=method, warnings=warnings)
|
||||
|
||||
if any(value == 0 for value in values):
|
||||
warnings.append("zero prices present")
|
||||
|
||||
used = values
|
||||
if outlier_policy == "iqr" and len(values) >= 4:
|
||||
q1 = _quantile(values, 0.25)
|
||||
q3 = _quantile(values, 0.75)
|
||||
iqr = q3 - q1
|
||||
if iqr > 0:
|
||||
lower_fence = q1 - 1.5 * iqr
|
||||
upper_fence = q3 + 1.5 * iqr
|
||||
filtered = [value for value in values if lower_fence <= value <= upper_fence]
|
||||
excluded = len(values) - len(filtered)
|
||||
if excluded and len(filtered) >= 4:
|
||||
used = filtered
|
||||
method.outlier_count = excluded
|
||||
warnings.append(f"excluded {excluded} outliers by IQR")
|
||||
elif excluded:
|
||||
warnings.append("IQR outliers found, but too few values remain; kept all")
|
||||
|
||||
count = len(used)
|
||||
median = _quantile(used, 0.5)
|
||||
avg = statistics.fmean(used)
|
||||
std = statistics.stdev(used) if count > 1 else 0.0
|
||||
q1 = _quantile(used, 0.25)
|
||||
q3 = _quantile(used, 0.75)
|
||||
mad = statistics.median(abs(value - median) for value in used)
|
||||
|
||||
if count < 3:
|
||||
warnings.append("sample too small for robust statistics")
|
||||
elif count < 100:
|
||||
warnings.append("p95 and p99 are unstable with n < 100")
|
||||
if count > 1 and max(used) == min(used):
|
||||
warnings.append("all prices are equal")
|
||||
|
||||
trimmed = _trimmed_mean(used, trim_fraction)
|
||||
histogram = _histogram(used, histogram_bins)
|
||||
|
||||
return PriceStats(
|
||||
count=count,
|
||||
currency=currency,
|
||||
min=_round(min(used)),
|
||||
max=_round(max(used)),
|
||||
avg=_round(avg),
|
||||
median=_round(median),
|
||||
p25=_round(q1),
|
||||
p90=_round(_quantile(used, 0.90)),
|
||||
p95=_round(_quantile(used, 0.95)),
|
||||
p99=_round(_quantile(used, 0.99)),
|
||||
trimmed_mean=_round(trimmed),
|
||||
std=_round(std),
|
||||
iqr=_round(q3 - q1),
|
||||
mad=_round(mad),
|
||||
histogram=histogram,
|
||||
method=method,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
|
||||
def _quantile(sorted_values: list[float], probability: float) -> float:
|
||||
if not sorted_values:
|
||||
raise ValueError("quantile of empty values")
|
||||
if len(sorted_values) == 1:
|
||||
return sorted_values[0]
|
||||
rank = (len(sorted_values) - 1) * probability
|
||||
lower_index = math.floor(rank)
|
||||
upper_index = math.ceil(rank)
|
||||
if lower_index == upper_index:
|
||||
return sorted_values[lower_index]
|
||||
fraction = rank - lower_index
|
||||
return sorted_values[lower_index] + (
|
||||
sorted_values[upper_index] - sorted_values[lower_index]
|
||||
) * fraction
|
||||
|
||||
|
||||
def _trimmed_mean(values: list[float], fraction: float) -> float:
|
||||
if not values:
|
||||
raise ValueError("trimmed mean of empty values")
|
||||
fraction = min(max(fraction, 0.0), 0.49)
|
||||
cut = int(len(values) * fraction)
|
||||
if len(values) - 2 * cut < 1:
|
||||
return statistics.fmean(values)
|
||||
trimmed = values[cut : len(values) - cut]
|
||||
return statistics.fmean(trimmed)
|
||||
|
||||
|
||||
def _histogram(values: list[float], bins: int) -> list[HistogramBin]:
|
||||
if not values:
|
||||
return []
|
||||
bins = max(1, bins)
|
||||
lower = min(values)
|
||||
upper = max(values)
|
||||
if lower == upper:
|
||||
return [HistogramBin(lower=_round(lower), upper=_round(upper), count=len(values))]
|
||||
|
||||
width = (upper - lower) / bins
|
||||
counts = [0] * bins
|
||||
for value in values:
|
||||
index = min(int((value - lower) / width), bins - 1)
|
||||
counts[index] += 1
|
||||
return [
|
||||
HistogramBin(
|
||||
lower=_round(lower + index * width),
|
||||
upper=_round(lower + (index + 1) * width),
|
||||
count=count,
|
||||
)
|
||||
for index, count in enumerate(counts)
|
||||
]
|
||||
|
||||
|
||||
def _round(value: float) -> float:
|
||||
return round(value, 2)
|
||||
@@ -0,0 +1,511 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from typing import cast
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from avito_tools import __version__
|
||||
from avito_tools.analytics.stats import OutlierPolicy
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.config import AccessMode, Settings
|
||||
from avito_tools.domain import ListingCard, SearchQuery
|
||||
from avito_tools.errors import AvitoToolsError
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
from avito_tools.non_agent.services.monitor import MonitorService
|
||||
from avito_tools.non_agent.services.searches import SearchCreate, SearchManager
|
||||
from avito_tools.probe import exit_code_for_report, format_report, report_as_json, run_probe
|
||||
from avito_tools.services.search import SearchService
|
||||
from avito_tools.services.stats import PriceStatsService, StatsReport
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="avito-tools",
|
||||
description="Avito search and analytics tools",
|
||||
)
|
||||
parser.add_argument("--version", action="version", version=__version__)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
probe = subparsers.add_parser("probe", help="check egress, cookies and the search endpoint")
|
||||
probe.add_argument("--query", default="galaxy fold 8", help="search query for the probe")
|
||||
probe.add_argument("--save-raw", action="store_true", help="save the raw response to var/")
|
||||
probe.add_argument(
|
||||
"--mode",
|
||||
choices=["auto", "anonymous", "account"],
|
||||
default="auto",
|
||||
help="access mode",
|
||||
)
|
||||
probe.add_argument("--json", action="store_true", help="print the report as JSON")
|
||||
|
||||
search = subparsers.add_parser("search", help="run a live search")
|
||||
search.add_argument("query", help="search query")
|
||||
search.add_argument("--pages", type=int, default=None, help="number of pages to fetch")
|
||||
search.add_argument("--limit", type=int, default=50, help="maximum rows to print")
|
||||
search.add_argument("--json", action="store_true", help="print results as JSON")
|
||||
|
||||
stats = subparsers.add_parser("stats", help="compute price statistics for a query")
|
||||
stats.add_argument("query", help="search query")
|
||||
stats.add_argument("--pages", type=int, default=None, help="number of pages to fetch")
|
||||
stats.add_argument("--limit", type=int, default=100, help="maximum listings to use")
|
||||
stats.add_argument(
|
||||
"--outliers",
|
||||
choices=["iqr", "none"],
|
||||
default="iqr",
|
||||
help="outlier policy",
|
||||
)
|
||||
stats.add_argument("--bins", type=int, default=10, help="histogram bins")
|
||||
stats.add_argument("--json", action="store_true", help="print results as JSON")
|
||||
|
||||
serve = subparsers.add_parser("serve", help="run the FastAPI server")
|
||||
serve.add_argument("--host", default="127.0.0.1", help="bind host")
|
||||
serve.add_argument("--port", type=int, default=8000, help="bind port")
|
||||
serve.add_argument("--reload", action="store_true", help="reload on code changes")
|
||||
|
||||
cookies = subparsers.add_parser("cookies", help="capture Avito cookies from a headed browser")
|
||||
cookies.add_argument("--mode", choices=["anonymous", "account"], default="anonymous")
|
||||
cookies.add_argument("--out", default="var/avito-cookies.json", help="output JSON path")
|
||||
cookies.add_argument("--profile", default="var/chrome-profile", help="Chrome profile directory")
|
||||
cookies.add_argument("--port", type=int, default=9222, help="Chrome DevTools port")
|
||||
cookies.add_argument("--chrome", default=None, help="path to Chrome/Chromium binary")
|
||||
cookies.add_argument("--url", default="https://www.avito.ru/", help="start URL")
|
||||
cookies.add_argument(
|
||||
"--verify-url",
|
||||
default="https://www.avito.ru/moskva/telefony?q=iphone+15",
|
||||
help="search page used to solve PoW and verify the session",
|
||||
)
|
||||
cookies.add_argument(
|
||||
"--no-launch",
|
||||
action="store_false",
|
||||
dest="launch",
|
||||
help="use a running Chrome",
|
||||
)
|
||||
cookies.add_argument(
|
||||
"--keep-open",
|
||||
action="store_true",
|
||||
help="keep the browser open after capture",
|
||||
)
|
||||
cookies.add_argument("--print", action="store_true", help="print the Cookie header (sensitive)")
|
||||
|
||||
mcp = subparsers.add_parser("mcp", help="run the MCP server")
|
||||
mcp.add_argument("--transport", choices=["stdio", "http"], default="stdio")
|
||||
mcp.add_argument("--host", default="127.0.0.1", help="HTTP bind host")
|
||||
mcp.add_argument("--port", type=int, default=8765, help="HTTP bind port")
|
||||
|
||||
watch = subparsers.add_parser("watch", help="manage saved searches")
|
||||
watch_sub = watch.add_subparsers(dest="watch_command", required=True)
|
||||
watch_add = watch_sub.add_parser("add", help="create a saved search")
|
||||
watch_add.add_argument("query")
|
||||
watch_add.add_argument("--name", default=None)
|
||||
watch_add.add_argument("--interval", type=int, default=600, help="poll interval, seconds")
|
||||
watch_add.add_argument("--pages", type=int, default=1)
|
||||
watch_add.add_argument("--location", type=int, default=None)
|
||||
watch_add.add_argument("--category", type=int, default=None)
|
||||
watch_add.add_argument("--price-min", type=int, default=None)
|
||||
watch_add.add_argument("--price-max", type=int, default=None)
|
||||
watch_sub.add_parser("list", help="list saved searches")
|
||||
watch_remove = watch_sub.add_parser("remove", help="delete a saved search")
|
||||
watch_remove.add_argument("search_id", type=int)
|
||||
watch_run = watch_sub.add_parser("run", help="run one saved search now")
|
||||
watch_run.add_argument("search_id", type=int)
|
||||
|
||||
db = subparsers.add_parser("db", help="database commands")
|
||||
db_sub = db.add_subparsers(dest="db_command", required=True)
|
||||
db_sub.add_parser("init", help="create tables")
|
||||
|
||||
worker = subparsers.add_parser("worker", help="run the monitoring worker")
|
||||
worker.add_argument("--once", action="store_true", help="run one cycle and exit")
|
||||
|
||||
notify = subparsers.add_parser("notify", help="notification commands")
|
||||
notify_sub = notify.add_subparsers(dest="notify_command", required=True)
|
||||
notify_sub.add_parser("test", help="send a test Telegram message")
|
||||
|
||||
subparsers.add_parser("version", help="print the version")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "version":
|
||||
print(__version__)
|
||||
return 0
|
||||
|
||||
if args.command == "cookies":
|
||||
return _run_cookies(args)
|
||||
|
||||
if args.command == "mcp":
|
||||
return _run_mcp(args)
|
||||
|
||||
try:
|
||||
settings = Settings()
|
||||
except ValidationError as exc:
|
||||
print(f"config error: {exc}", file=sys.stderr)
|
||||
return 4
|
||||
|
||||
if args.command in {"watch", "db"}:
|
||||
return _run_db_command(settings, args)
|
||||
|
||||
if args.command == "worker":
|
||||
from avito_tools.non_agent.worker.loop import run_worker
|
||||
|
||||
try:
|
||||
asyncio.run(run_worker(once=args.once))
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
return 0
|
||||
|
||||
if args.command == "notify":
|
||||
return _run_notify(settings, args)
|
||||
|
||||
if args.command == "probe":
|
||||
mode = None if args.mode == "auto" else cast(AccessMode, args.mode)
|
||||
report = run_probe(settings, query=args.query, save_raw=args.save_raw, mode=mode)
|
||||
print(report_as_json(report) if args.json else format_report(report))
|
||||
return exit_code_for_report(report)
|
||||
|
||||
if args.command == "search":
|
||||
pages = args.pages if args.pages is not None else settings.max_pages
|
||||
return _run_search(settings, args.query, pages=pages, limit=args.limit, as_json=args.json)
|
||||
|
||||
if args.command == "stats":
|
||||
pages = args.pages if args.pages is not None else settings.max_pages
|
||||
return _run_stats(
|
||||
settings,
|
||||
args.query,
|
||||
pages=pages,
|
||||
limit=args.limit,
|
||||
outlier_policy=args.outliers,
|
||||
histogram_bins=args.bins,
|
||||
as_json=args.json,
|
||||
)
|
||||
|
||||
if args.command == "serve":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
"avito_tools.non_agent.api.app:app",
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
reload=args.reload,
|
||||
)
|
||||
return 0
|
||||
|
||||
parser.print_help()
|
||||
return 1
|
||||
|
||||
|
||||
def _run_notify(settings: Settings, args: argparse.Namespace) -> int:
|
||||
from avito_tools.non_agent.notifiers.base import build_notifier
|
||||
|
||||
notifier = build_notifier(settings)
|
||||
if notifier is None:
|
||||
print(
|
||||
"Telegram is not configured: set AVITO_TELEGRAM_BOT_TOKEN and CHAT_ID",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
payload = {
|
||||
"event_type": "test",
|
||||
"search": {"name": "avito-tools"},
|
||||
"listing": {
|
||||
"title": "Тестовое уведомление",
|
||||
"price": None,
|
||||
"url": "https://www.avito.ru",
|
||||
},
|
||||
}
|
||||
try:
|
||||
asyncio.run(notifier.send(payload))
|
||||
except Exception as exc:
|
||||
print(f"notification failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print("notification sent")
|
||||
return 0
|
||||
|
||||
|
||||
def _run_db_command(settings: Settings, args: argparse.Namespace) -> int:
|
||||
try:
|
||||
return asyncio.run(_db_command(settings, args))
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
except Exception as exc:
|
||||
print(f"command failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
async def _db_command(settings: Settings, args: argparse.Namespace) -> int:
|
||||
database = Database(settings)
|
||||
await database.init()
|
||||
try:
|
||||
if args.command == "db":
|
||||
print(f"database initialized: {settings.database_url}")
|
||||
return 0
|
||||
|
||||
if args.watch_command == "add":
|
||||
if (
|
||||
args.price_min is not None
|
||||
and args.price_max is not None
|
||||
and args.price_min > args.price_max
|
||||
):
|
||||
print("price_min must be <= price_max", file=sys.stderr)
|
||||
return 1
|
||||
async with database.session() as session:
|
||||
manager = SearchManager(session)
|
||||
search = await manager.create(
|
||||
SearchCreate(
|
||||
name=args.name or args.query,
|
||||
query=args.query,
|
||||
location_id=args.location,
|
||||
category_id=args.category,
|
||||
price_min=args.price_min,
|
||||
price_max=args.price_max,
|
||||
pages=args.pages,
|
||||
poll_interval_sec=args.interval,
|
||||
)
|
||||
)
|
||||
print(f"created search {search.id}: {search.name}")
|
||||
return 0
|
||||
|
||||
if args.watch_command == "list":
|
||||
async with database.session() as session:
|
||||
searches = await SearchManager(session).list_all()
|
||||
if not searches:
|
||||
print("no saved searches")
|
||||
return 0
|
||||
for search in searches:
|
||||
last_run = search.last_run_at.isoformat() if search.last_run_at else "-"
|
||||
print(
|
||||
f"{search.id:>4} | {search.name:<30} | {search.query:<30} | "
|
||||
f"every {search.poll_interval_sec}s | last={last_run} | "
|
||||
f"baseline={'yes' if search.baseline_completed else 'no'} | "
|
||||
f"enabled={'yes' if search.enabled else 'no'}"
|
||||
)
|
||||
return 0
|
||||
|
||||
if args.watch_command == "remove":
|
||||
async with database.session() as session:
|
||||
deleted = await SearchManager(session).delete(args.search_id)
|
||||
print("deleted" if deleted else "not found")
|
||||
return 0
|
||||
|
||||
if args.watch_command == "run":
|
||||
bundle = build_provider(settings)
|
||||
try:
|
||||
monitor = MonitorService(database, SearchService(bundle.provider))
|
||||
outcome = await monitor.run_search(args.search_id)
|
||||
finally:
|
||||
bundle.close()
|
||||
print(
|
||||
f"status={outcome.status} fetched={outcome.fetched} "
|
||||
f"new={outcome.new_count} matched={outcome.matched_count}"
|
||||
+ (
|
||||
f" error={outcome.error_code}: {outcome.error_message}"
|
||||
if outcome.error_code
|
||||
else ""
|
||||
)
|
||||
)
|
||||
return 0 if outcome.status == "ok" else 2
|
||||
|
||||
return 1
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
def _run_mcp(args: argparse.Namespace) -> int:
|
||||
from avito_tools.mcp.runner import run_mcp
|
||||
|
||||
try:
|
||||
run_mcp(transport=args.transport, host=args.host, port=args.port)
|
||||
except KeyboardInterrupt:
|
||||
print("mcp server stopped", file=sys.stderr)
|
||||
return 130
|
||||
except Exception as exc:
|
||||
print(f"mcp server failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def _run_cookies(args: argparse.Namespace) -> int:
|
||||
from pathlib import Path
|
||||
|
||||
from avito_tools.cookies_capture import capture_cookies
|
||||
|
||||
try:
|
||||
result = capture_cookies(
|
||||
mode=args.mode,
|
||||
output=Path(args.out),
|
||||
profile=Path(args.profile),
|
||||
port=args.port,
|
||||
chrome=args.chrome,
|
||||
url=args.url,
|
||||
verify_url=args.verify_url,
|
||||
launch=args.launch,
|
||||
keep_open=args.keep_open,
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
print("cancelled", file=sys.stderr)
|
||||
return 130
|
||||
except (RuntimeError, ValueError, OSError) as exc:
|
||||
print(f"cookie capture failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"saved: {result.path}")
|
||||
print(f"mode: {result.mode} | cookies: {result.cookie_count}")
|
||||
if result.user_agent:
|
||||
print(f"user agent: {result.user_agent}")
|
||||
print(f"set in .env: AVITO_COOKIE_FILE={result.path}")
|
||||
if result.mode == "account":
|
||||
print("account cookies: AVITO_ACCESS_MODE=account or keep anonymous + account_fallback")
|
||||
if args.print:
|
||||
print("Cookie:", result.cookie_header)
|
||||
print("warning: this value is a credential; do not paste it into chat or git")
|
||||
return 0
|
||||
|
||||
|
||||
def _run_search(
|
||||
settings: Settings,
|
||||
query: str,
|
||||
*,
|
||||
pages: int,
|
||||
limit: int,
|
||||
as_json: bool,
|
||||
) -> int:
|
||||
bundle = None
|
||||
try:
|
||||
bundle = build_provider(settings)
|
||||
service = SearchService(bundle.provider)
|
||||
batch = service.search(
|
||||
SearchQuery(
|
||||
query=query,
|
||||
location_id=settings.location_id,
|
||||
category_id=settings.category_id,
|
||||
),
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
if as_json:
|
||||
print(json.dumps({"ok": False, "error": exc.as_dict()}, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
print(f"search failed: {exc.code}: {exc.message}", file=sys.stderr)
|
||||
return _exit_code_for_error(exc)
|
||||
finally:
|
||||
if bundle is not None:
|
||||
bundle.close()
|
||||
|
||||
payload = batch.to_dict()
|
||||
payload["returned"] = len(batch.items)
|
||||
if as_json:
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
print(f"query: {query}")
|
||||
total = batch.total if batch.total is not None else "?"
|
||||
print(f"total: {total} | returned: {len(batch.items)}")
|
||||
for warning in batch.warnings[:10]:
|
||||
print(f"warning: {warning}")
|
||||
_print_table(batch.items)
|
||||
return 0
|
||||
|
||||
|
||||
def _run_stats(
|
||||
settings: Settings,
|
||||
query: str,
|
||||
*,
|
||||
pages: int,
|
||||
limit: int,
|
||||
outlier_policy: OutlierPolicy,
|
||||
histogram_bins: int,
|
||||
as_json: bool,
|
||||
) -> int:
|
||||
bundle = None
|
||||
try:
|
||||
bundle = build_provider(settings)
|
||||
service = PriceStatsService(SearchService(bundle.provider))
|
||||
report = service.stats_for_query(
|
||||
SearchQuery(
|
||||
query=query,
|
||||
location_id=settings.location_id,
|
||||
category_id=settings.category_id,
|
||||
),
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
outlier_policy=outlier_policy,
|
||||
histogram_bins=histogram_bins,
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
if as_json:
|
||||
print(json.dumps({"ok": False, "error": exc.as_dict()}, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
print(f"stats failed: {exc.code}: {exc.message}", file=sys.stderr)
|
||||
return _exit_code_for_error(exc)
|
||||
finally:
|
||||
if bundle is not None:
|
||||
bundle.close()
|
||||
|
||||
if as_json:
|
||||
payload = report.model_dump(mode="json", exclude_none=True)
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
_print_stats(report)
|
||||
return 0
|
||||
|
||||
|
||||
def _print_stats(report: StatsReport) -> None:
|
||||
stats = report.stats
|
||||
print(f"query: {report.query}")
|
||||
total = report.total if report.total is not None else "?"
|
||||
print(f"total: {total} | fetched: {report.fetched} | used: {stats.count}")
|
||||
if stats.count == 0:
|
||||
for warning in report.warnings:
|
||||
print(f"warning: {warning}")
|
||||
return
|
||||
print(f"min: {stats.min} | median: {stats.median} | max: {stats.max}")
|
||||
print(f"avg: {stats.avg} | trimmed mean: {stats.trimmed_mean} | std: {stats.std}")
|
||||
print(
|
||||
f"p25: {stats.p25} | p90: {stats.p90} | p95: {stats.p95} | p99: {stats.p99}"
|
||||
)
|
||||
print(f"iqr: {stats.iqr} | mad: {stats.mad}")
|
||||
for warning in report.warnings:
|
||||
print(f"warning: {warning}")
|
||||
if stats.histogram:
|
||||
print("histogram:")
|
||||
for bucket in stats.histogram:
|
||||
print(f" {bucket.lower} - {bucket.upper}: {bucket.count}")
|
||||
|
||||
|
||||
def _print_table(items: list[ListingCard]) -> None:
|
||||
if not items:
|
||||
print("no items")
|
||||
return
|
||||
print("-" * 120)
|
||||
print(f"{'ID':<12} {'PRICE':>9} {'TITLE':<48} {'LOCATION':<16} DATE")
|
||||
print("-" * 120)
|
||||
for item in items:
|
||||
price = str(item.price) if item.price is not None else "?"
|
||||
title = item.title.replace("\n", " ")
|
||||
if len(title) > 48:
|
||||
title = title[:45] + "..."
|
||||
location = (item.location or "").replace("\n", " ")
|
||||
if len(location) > 16:
|
||||
location = location[:13] + "..."
|
||||
published = item.published_at.strftime("%Y-%m-%d") if item.published_at else "?"
|
||||
print(f"{item.id:<12} {price:>9} {title:<48} {location:<16} {published}")
|
||||
|
||||
|
||||
def _exit_code_for_error(exc: AvitoToolsError) -> int:
|
||||
if exc.code == "blocked":
|
||||
return 2
|
||||
if exc.code == "schema_drift":
|
||||
return 3
|
||||
if exc.code in {"config_error", "transport_error"}:
|
||||
return 4
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,3 @@
|
||||
from avito_tools.collector.http import AvitoHttpClient, HttpResponse
|
||||
|
||||
__all__ = ["AvitoHttpClient", "HttpResponse"]
|
||||
@@ -0,0 +1,98 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from avito_tools.collector.canary import detect_block
|
||||
from avito_tools.collector.cdp import ChromeController
|
||||
from avito_tools.collector.html import build_search_url, extract_total, parse_search_html
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchPage, SearchQuery
|
||||
from avito_tools.errors import BlockedError
|
||||
|
||||
|
||||
class BrowserSearchProvider:
|
||||
"""Search through a real Chrome session, then parse the rendered HTML."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
controller: ChromeController,
|
||||
settings: Settings,
|
||||
*,
|
||||
access_mode: str = "account",
|
||||
) -> None:
|
||||
self.controller = controller
|
||||
self.settings = settings
|
||||
self.access_mode = access_mode
|
||||
self.last_response: HttpResponse | None = None
|
||||
self._last_search_at: float | None = None
|
||||
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage:
|
||||
if page < 1:
|
||||
raise ValueError("page must be >= 1")
|
||||
|
||||
if self._last_search_at is not None:
|
||||
delay = self.settings.browser_page_delay_sec
|
||||
elapsed = time.monotonic() - self._last_search_at
|
||||
if elapsed < delay:
|
||||
time.sleep(delay - elapsed)
|
||||
|
||||
url = build_search_url(self.settings, query, page)
|
||||
coro = self.controller.fetch_html(url, timeout=self.settings.browser_timeout_sec)
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
html = asyncio.run(coro)
|
||||
else:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
html = pool.submit(asyncio.run, coro).result()
|
||||
response = HttpResponse(
|
||||
status_code=200,
|
||||
content_type="text/html; charset=utf-8",
|
||||
text=html,
|
||||
elapsed_ms=0,
|
||||
url=url,
|
||||
)
|
||||
self.last_response = response
|
||||
self._last_search_at = time.monotonic()
|
||||
|
||||
block_reason = detect_block(response)
|
||||
if block_reason:
|
||||
raise BlockedError(
|
||||
f"Avito blocked the browser search: {block_reason}",
|
||||
status_code=200,
|
||||
detail={"url": url, "body_head": _head(html)},
|
||||
)
|
||||
|
||||
cards, total = parse_search_html(html)
|
||||
if total is None:
|
||||
total = extract_total(
|
||||
f"{getattr(self.controller, 'last_title', '')} "
|
||||
f"{getattr(self.controller, 'last_text', '')}",
|
||||
relaxed=True,
|
||||
)
|
||||
warnings: list[str] = []
|
||||
if not cards and not total:
|
||||
warnings.append("empty browser search page")
|
||||
has_next = len(cards) >= 50
|
||||
if total is not None and page * 50 < total:
|
||||
has_next = True
|
||||
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=total,
|
||||
items=cards,
|
||||
has_next=has_next,
|
||||
warnings=warnings,
|
||||
access_mode=self.access_mode,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self.controller.close()
|
||||
|
||||
|
||||
def _head(text: str, limit: int = 300) -> str:
|
||||
return text.strip().replace("\n", " ")[:limit]
|
||||
@@ -0,0 +1,201 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CanaryResult:
|
||||
fatal: bool = False
|
||||
errors: list[str] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
|
||||
def add_error(self, message: str) -> None:
|
||||
self.errors.append(message)
|
||||
self.fatal = True
|
||||
|
||||
|
||||
def detect_block(response: HttpResponse) -> str | None:
|
||||
"""Return a human-readable block reason, or None if the response looks normal."""
|
||||
if response.status_code in {403, 429, 439}:
|
||||
return f"HTTP {response.status_code}"
|
||||
if response.status_code == 302:
|
||||
return "HTTP 302 redirect (possible captcha)"
|
||||
|
||||
text = response.text.strip()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
if text.startswith("{") or text.startswith("["):
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
for key in ("too-many-requests", "captcha", "firewall"):
|
||||
if key in payload:
|
||||
return f"JSON block marker: {key}"
|
||||
error = payload.get("error")
|
||||
if isinstance(error, dict):
|
||||
message = str(error.get("message", ""))
|
||||
if "ограничен" in message.lower() or "captcha" in message.lower():
|
||||
return "JSON error block marker"
|
||||
|
||||
lowered = text[:5000].lower()
|
||||
markers = (
|
||||
"доступ ограничен",
|
||||
"проблема с ip",
|
||||
"firewall/captcha",
|
||||
"подтвердите, что вы не робот",
|
||||
)
|
||||
for marker in markers:
|
||||
if marker in lowered:
|
||||
return f"HTML block marker: {marker}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_search_payload(payload: Any, *, page: int = 1) -> CanaryResult:
|
||||
result = CanaryResult()
|
||||
if not isinstance(payload, dict):
|
||||
result.add_error(f"expected JSON object, got {type(payload).__name__}")
|
||||
return result
|
||||
|
||||
items = _extract_items(payload)
|
||||
total = _extract_total(payload)
|
||||
main_count = _first_int(payload, ("count", "mainCount"))
|
||||
if items is None:
|
||||
if total in (None, 0) or main_count == 0:
|
||||
result.warnings.append("empty result")
|
||||
return result
|
||||
result.add_error("missing 'items' key")
|
||||
return result
|
||||
if not isinstance(items, list):
|
||||
result.add_error(f"'items' must be a list, got {type(items).__name__}")
|
||||
return result
|
||||
|
||||
if total is None:
|
||||
result.warnings.append("missing totalCount/total")
|
||||
elif total < 0:
|
||||
result.add_error(f"negative total: {total}")
|
||||
elif not items and main_count == 0:
|
||||
result.warnings.append("no main results; extra blocks only" if total else "empty page")
|
||||
return result
|
||||
elif total == 0 and items:
|
||||
result.add_error("total is 0 but items are present")
|
||||
elif total > 0 and not items and page == 1:
|
||||
result.add_error(f"total is {total} but page 1 has no items")
|
||||
elif total < len(items):
|
||||
result.warnings.append(f"total ({total}) is less than items on page ({len(items)})")
|
||||
|
||||
if not items:
|
||||
result.warnings.append("empty page")
|
||||
return result
|
||||
|
||||
invalid = 0
|
||||
missing_price = 0
|
||||
seen_ids: set[str] = set()
|
||||
duplicate_ids = 0
|
||||
|
||||
for index, item in enumerate(items):
|
||||
if not isinstance(item, dict):
|
||||
invalid += 1
|
||||
result.warnings.append(f"item[{index}] is not an object")
|
||||
continue
|
||||
|
||||
item_id = _string(item.get("id") or item.get("itemId"))
|
||||
title = _string(item.get("title"))
|
||||
url_path = _string(item.get("urlPath") or item.get("uri"))
|
||||
price = _extract_price(item)
|
||||
|
||||
problems: list[str] = []
|
||||
if not item_id:
|
||||
problems.append("no id")
|
||||
elif item_id in seen_ids:
|
||||
duplicate_ids += 1
|
||||
else:
|
||||
seen_ids.add(item_id)
|
||||
if not title:
|
||||
problems.append("no title")
|
||||
if not url_path or not url_path.startswith("/"):
|
||||
problems.append("bad urlPath")
|
||||
if price is None:
|
||||
missing_price += 1
|
||||
|
||||
if problems:
|
||||
invalid += 1
|
||||
if len(result.warnings) < 20:
|
||||
result.warnings.append(f"item[{index}]: {', '.join(problems)}")
|
||||
|
||||
invalid_ratio = invalid / len(items)
|
||||
if invalid_ratio > 0.5:
|
||||
result.add_error(f"{invalid}/{len(items)} items failed basic validation")
|
||||
elif invalid:
|
||||
result.warnings.append(f"{invalid}/{len(items)} items failed basic validation")
|
||||
if duplicate_ids:
|
||||
result.warnings.append(f"{duplicate_ids} duplicate item ids on page")
|
||||
if missing_price == len(items):
|
||||
result.warnings.append("all items have no price")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _first_int(payload: dict[str, Any], keys: tuple[str, ...]) -> int | None:
|
||||
for key in keys:
|
||||
value = payload.get(key)
|
||||
if isinstance(value, bool):
|
||||
continue
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str) and value.strip().isdigit():
|
||||
return int(value.strip())
|
||||
return None
|
||||
|
||||
|
||||
def _extract_items(payload: dict[str, Any]) -> Any:
|
||||
items = payload.get("items")
|
||||
if isinstance(items, list):
|
||||
return items
|
||||
catalog = payload.get("catalog")
|
||||
if isinstance(catalog, dict):
|
||||
nested = catalog.get("items")
|
||||
if isinstance(nested, list):
|
||||
return nested
|
||||
return None
|
||||
|
||||
|
||||
def _extract_total(payload: dict[str, Any]) -> int | None:
|
||||
total = _first_int(payload, ("totalCount", "total", "count"))
|
||||
if total is not None:
|
||||
return total
|
||||
catalog = payload.get("catalog")
|
||||
if isinstance(catalog, dict):
|
||||
return _first_int(catalog, ("totalCount", "total", "count"))
|
||||
return None
|
||||
|
||||
|
||||
def _string(value: Any) -> str:
|
||||
if isinstance(value, bool):
|
||||
return ""
|
||||
if isinstance(value, (int, float)):
|
||||
return str(int(value))
|
||||
return value.strip() if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _extract_price(item: dict[str, Any]) -> int | None:
|
||||
detailed = item.get("priceDetailed")
|
||||
if isinstance(detailed, dict):
|
||||
value = detailed.get("value")
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return int(value)
|
||||
value = item.get("price")
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
digits = "".join(ch for ch in value if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
return None
|
||||
@@ -0,0 +1,189 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from websockets.asyncio.client import connect
|
||||
from websockets.typing import Origin
|
||||
|
||||
|
||||
async def wait_for_target(port: int, timeout: float = 20.0) -> str:
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error: Exception | None = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"http://127.0.0.1:{port}/json/list",
|
||||
timeout=2,
|
||||
) as response:
|
||||
targets = json.loads(response.read().decode("utf-8"))
|
||||
pages = [target for target in targets if target.get("type") == "page"]
|
||||
if pages:
|
||||
return str(pages[0]["webSocketDebuggerUrl"])
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc:
|
||||
last_error = exc
|
||||
await asyncio.sleep(0.3)
|
||||
raise RuntimeError(f"Chrome DevTools is not available on port {port}: {last_error}")
|
||||
|
||||
|
||||
async def cdp_call(
|
||||
ws,
|
||||
request_id: int,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
await ws.send(json.dumps({"id": request_id, "method": method, "params": params or {}}))
|
||||
while True:
|
||||
message = json.loads(await ws.recv())
|
||||
if message.get("id") != request_id:
|
||||
continue
|
||||
if "error" in message:
|
||||
raise RuntimeError(f"CDP {method} failed: {message['error']}")
|
||||
return dict(message.get("result") or {})
|
||||
|
||||
|
||||
class ChromeController:
|
||||
"""Manage one Chrome process/tab for browser-based search."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
port: int = 9222,
|
||||
profile: Path = Path("var/chrome-profile"),
|
||||
headless: bool = False,
|
||||
chrome: str | None = None,
|
||||
url: str = "about:blank",
|
||||
) -> None:
|
||||
self.port = port
|
||||
self.profile = profile
|
||||
self.headless = headless
|
||||
self.chrome = chrome
|
||||
self.url = url
|
||||
self._process: subprocess.Popen[bytes] | None = None
|
||||
self.last_title: str = ""
|
||||
self.last_text: str = ""
|
||||
|
||||
def _find_chrome(self) -> str:
|
||||
candidates = [self.chrome] if self.chrome else []
|
||||
candidates.extend(
|
||||
["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"]
|
||||
)
|
||||
for candidate in candidates:
|
||||
if not candidate:
|
||||
continue
|
||||
found = shutil.which(candidate)
|
||||
if found:
|
||||
return found
|
||||
raise RuntimeError("Chrome/Chromium not found; set AVITO_BROWSER_CHROME")
|
||||
|
||||
def _target_running(self) -> bool:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"http://127.0.0.1:{self.port}/json/version",
|
||||
timeout=0.5,
|
||||
):
|
||||
return True
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
return False
|
||||
|
||||
def ensure_started(self) -> None:
|
||||
if self._target_running():
|
||||
return
|
||||
binary = self._find_chrome()
|
||||
self.profile.mkdir(parents=True, exist_ok=True)
|
||||
args = [
|
||||
binary,
|
||||
f"--remote-debugging-port={self.port}",
|
||||
"--remote-debugging-address=127.0.0.1",
|
||||
"--remote-allow-origins=*",
|
||||
f"--user-data-dir={self.profile.resolve()}",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
]
|
||||
if self.headless:
|
||||
args.append("--headless=new")
|
||||
else:
|
||||
args.append("--start-maximized")
|
||||
args.append(self.url)
|
||||
self._process = subprocess.Popen(
|
||||
args,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
async def fetch_html(self, url: str, *, timeout: float = 30.0) -> str:
|
||||
self.ensure_started()
|
||||
ws_url = await wait_for_target(self.port, timeout=min(timeout, 20.0))
|
||||
async with connect(
|
||||
ws_url,
|
||||
max_size=2**25,
|
||||
open_timeout=10,
|
||||
origin=Origin(f"http://127.0.0.1:{self.port}"),
|
||||
) as ws:
|
||||
await cdp_call(ws, 1, "Page.enable")
|
||||
await cdp_call(ws, 2, "Page.navigate", {"url": url})
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = await cdp_call(
|
||||
ws,
|
||||
3,
|
||||
"Runtime.evaluate",
|
||||
{
|
||||
"expression": (
|
||||
"({ready: document.readyState, "
|
||||
"title: document.title, "
|
||||
"items: document.querySelectorAll('[data-marker=\"item\"]').length, "
|
||||
"body: document.body ? document.body.innerText.slice(0, 5000) : ''})"
|
||||
),
|
||||
"returnByValue": True,
|
||||
},
|
||||
)
|
||||
value = (result.get("result") or {}).get("value") or {}
|
||||
self.last_title = str(value.get("title") or "")
|
||||
self.last_text = str(value.get("body") or "")
|
||||
body = self.last_text.lower()
|
||||
blocked = any(
|
||||
marker in body
|
||||
for marker in (
|
||||
"доступ ограничен",
|
||||
"подтвердите, что вы не робот",
|
||||
"проблема с ip",
|
||||
)
|
||||
)
|
||||
if value.get("ready") == "complete" and (
|
||||
int(value.get("items") or 0) > 0 or blocked
|
||||
):
|
||||
break
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
page = await cdp_call(
|
||||
ws,
|
||||
4,
|
||||
"Runtime.evaluate",
|
||||
{"expression": "document.documentElement.outerHTML", "returnByValue": True},
|
||||
)
|
||||
title = await cdp_call(
|
||||
ws,
|
||||
5,
|
||||
"Runtime.evaluate",
|
||||
{"expression": "document.title", "returnByValue": True},
|
||||
)
|
||||
self.last_title = str((title.get("result") or {}).get("value") or self.last_title)
|
||||
return str((page.get("result") or {}).get("value") or "")
|
||||
|
||||
def close(self) -> None:
|
||||
if self._process is None:
|
||||
return
|
||||
self._process.terminate()
|
||||
try:
|
||||
self._process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._process.kill()
|
||||
self._process = None
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from avito_tools.collector.browser import BrowserSearchProvider
|
||||
from avito_tools.collector.cdp import ChromeController
|
||||
from avito_tools.collector.fallback import FallbackSearchProvider
|
||||
from avito_tools.collector.html import HtmlSearchProvider
|
||||
from avito_tools.collector.http import AvitoHttpClient, HttpResponse
|
||||
from avito_tools.collector.web import WebSearchProvider
|
||||
from avito_tools.config import AccessMode, Settings
|
||||
from avito_tools.cookies import CookieStore
|
||||
from avito_tools.errors import ConfigError
|
||||
from avito_tools.services.search import SearchProvider
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProviderBundle:
|
||||
provider: SearchProvider
|
||||
clients: list[AvitoHttpClient] = field(default_factory=list)
|
||||
modes: list[AccessMode] = field(default_factory=list)
|
||||
browser: ChromeController | None = None
|
||||
|
||||
@property
|
||||
def last_response(self) -> HttpResponse | None:
|
||||
return getattr(self.provider, "last_response", None)
|
||||
|
||||
def close(self) -> None:
|
||||
for client in self.clients:
|
||||
client.close()
|
||||
if self.browser is not None:
|
||||
self.browser.close()
|
||||
self.browser = None
|
||||
|
||||
|
||||
def build_provider(
|
||||
settings: Settings,
|
||||
*,
|
||||
mode: AccessMode | None = None,
|
||||
) -> ProviderBundle:
|
||||
raw_cookie = settings.cookie.get_secret_value() if settings.cookie else None
|
||||
store = CookieStore(raw_cookie=raw_cookie, path=settings.cookie_file)
|
||||
has_account_cookie = store.get() is not None
|
||||
|
||||
if mode is not None:
|
||||
modes: list[AccessMode] = [mode]
|
||||
elif settings.access_mode == "account":
|
||||
modes = ["account"]
|
||||
else:
|
||||
modes = ["anonymous"]
|
||||
if settings.account_fallback and (has_account_cookie or settings.cookie_file):
|
||||
modes.append("account")
|
||||
|
||||
if (
|
||||
"account" in modes
|
||||
and not has_account_cookie
|
||||
and settings.access_mode == "account"
|
||||
and settings.search_provider != "browser"
|
||||
):
|
||||
raise ConfigError(
|
||||
"account access mode requires AVITO_COOKIE or AVITO_COOKIE_FILE",
|
||||
detail={
|
||||
"cookie_file": str(settings.cookie_file) if settings.cookie_file else None
|
||||
},
|
||||
)
|
||||
|
||||
if settings.search_provider == "browser":
|
||||
controller = ChromeController(
|
||||
port=settings.browser_cdp_port,
|
||||
profile=settings.browser_profile,
|
||||
headless=settings.browser_headless,
|
||||
chrome=settings.browser_chrome,
|
||||
)
|
||||
provider = BrowserSearchProvider(
|
||||
controller,
|
||||
settings,
|
||||
access_mode=modes[0],
|
||||
)
|
||||
return ProviderBundle(provider=provider, modes=modes, browser=controller)
|
||||
|
||||
clients: list[AvitoHttpClient] = []
|
||||
providers: list[tuple[str, SearchProvider]] = []
|
||||
for access_mode in modes:
|
||||
client = AvitoHttpClient(
|
||||
settings,
|
||||
mode=access_mode,
|
||||
cookie_store=store if access_mode == "account" else None,
|
||||
bootstrap=access_mode == "anonymous",
|
||||
)
|
||||
clients.append(client)
|
||||
if settings.search_provider in {"auto", "json"}:
|
||||
providers.append(
|
||||
(
|
||||
access_mode,
|
||||
WebSearchProvider(
|
||||
client,
|
||||
settings,
|
||||
access_mode=access_mode,
|
||||
bootstrap=access_mode == "anonymous",
|
||||
),
|
||||
)
|
||||
)
|
||||
if settings.search_provider in {"auto", "html"}:
|
||||
providers.append(
|
||||
(
|
||||
access_mode,
|
||||
HtmlSearchProvider(
|
||||
client,
|
||||
settings,
|
||||
access_mode=access_mode,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
if not providers:
|
||||
raise ConfigError("no search providers configured")
|
||||
if len(providers) == 1:
|
||||
selected: SearchProvider = providers[0][1]
|
||||
else:
|
||||
selected = FallbackSearchProvider(providers)
|
||||
|
||||
return ProviderBundle(provider=selected, clients=clients, modes=modes)
|
||||
@@ -0,0 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.domain import SearchPage, SearchQuery
|
||||
from avito_tools.errors import BlockedError, ConfigError, TransportError
|
||||
from avito_tools.services.search import SearchProvider
|
||||
|
||||
|
||||
class FallbackSearchProvider:
|
||||
"""Try identities in order. Fallback is allowed for access failures, not data drift."""
|
||||
|
||||
def __init__(self, providers: list[tuple[str, SearchProvider]]) -> None:
|
||||
if not providers:
|
||||
raise ConfigError("no search providers configured")
|
||||
self.providers = providers
|
||||
self.last_response: HttpResponse | None = None
|
||||
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage:
|
||||
attempts: list[dict[str, str]] = []
|
||||
for mode, provider in self.providers:
|
||||
try:
|
||||
result = provider.search(query, page=page)
|
||||
except (BlockedError, ConfigError, TransportError) as exc:
|
||||
attempts.append({"mode": mode, "code": exc.code, "message": exc.message})
|
||||
continue
|
||||
self.last_response = getattr(provider, "last_response", None)
|
||||
result.access_mode = mode
|
||||
return result
|
||||
|
||||
raise BlockedError(
|
||||
"all access modes failed",
|
||||
detail={"attempts": attempts, "modes": [mode for mode, _ in self.providers]},
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html as html_module
|
||||
import re
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from avito_tools.collector.canary import detect_block
|
||||
from avito_tools.collector.http import AvitoHttpClient, HttpResponse
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage, SearchQuery
|
||||
from avito_tools.errors import BlockedError, SchemaDriftError, TransportError
|
||||
|
||||
BASE_URL = "https://www.avito.ru"
|
||||
ITEM_MARKER = 'data-marker="item"'
|
||||
TITLE_MARKER = 'data-marker="item-title"'
|
||||
PRICE_MARKER = 'itemProp="price"'
|
||||
DESCRIPTION_MARKER = "--module-max-lines-size:4"
|
||||
TOTAL_RE = re.compile(r"(\d[\d\s\xa0\u202f]*)\s*объявлен", re.IGNORECASE)
|
||||
RELAXED_TOTAL_RE = re.compile(
|
||||
r"в\s+[А-Яа-яЁёA-Za-z\s-]{2,40}?(\d[\d\s\xa0\u202f]{2,})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def extract_total(text: str, *, relaxed: bool = False) -> int | None:
|
||||
unescaped = html_module.unescape(text)
|
||||
patterns = [TOTAL_RE, RELAXED_TOTAL_RE] if relaxed else [TOTAL_RE]
|
||||
for pattern in patterns:
|
||||
match = pattern.search(unescaped)
|
||||
if not match:
|
||||
continue
|
||||
digits = re.sub(r"\D", "", match.group(1))
|
||||
if digits:
|
||||
return int(digits)
|
||||
return None
|
||||
|
||||
|
||||
|
||||
class HtmlSearchProvider:
|
||||
"""Parse Avito server-rendered search pages.
|
||||
|
||||
This is the fallback for sessions that can load HTML but cannot use the
|
||||
JSON endpoint because of the PoW challenge.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client: AvitoHttpClient,
|
||||
settings: Settings,
|
||||
*,
|
||||
access_mode: str = "account",
|
||||
) -> None:
|
||||
self.client = client
|
||||
self.settings = settings
|
||||
self.access_mode = access_mode
|
||||
self.last_response: HttpResponse | None = None
|
||||
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage:
|
||||
if page < 1:
|
||||
raise ValueError("page must be >= 1")
|
||||
|
||||
bootstrap_response = self.client.ensure_bootstrap()
|
||||
if bootstrap_response is not None:
|
||||
block_reason = detect_block(bootstrap_response)
|
||||
if block_reason:
|
||||
raise BlockedError(
|
||||
f"anonymous bootstrap blocked: {block_reason}",
|
||||
status_code=bootstrap_response.status_code,
|
||||
retry_after=bootstrap_response.headers.get("retry-after"),
|
||||
detail={"url": bootstrap_response.url},
|
||||
)
|
||||
if bootstrap_response.status_code >= 400:
|
||||
raise TransportError(
|
||||
f"anonymous bootstrap failed with HTTP {bootstrap_response.status_code}",
|
||||
detail={"url": bootstrap_response.url},
|
||||
)
|
||||
|
||||
params: dict[str, Any] = search_params(query, page)
|
||||
params.update(query.extra_params)
|
||||
|
||||
response = self.client.get(
|
||||
BASE_URL + self.settings.html_search_path,
|
||||
params=params,
|
||||
headers={
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
},
|
||||
)
|
||||
self.last_response = response
|
||||
|
||||
block_reason = detect_block(response)
|
||||
if block_reason:
|
||||
raise BlockedError(
|
||||
f"Avito blocked the HTML search: {block_reason}",
|
||||
status_code=response.status_code,
|
||||
retry_after=response.headers.get("retry-after"),
|
||||
detail={"url": response.url, "body_head": _head(response.text)},
|
||||
)
|
||||
if not response.looks_like_html:
|
||||
raise SchemaDriftError(
|
||||
"expected HTML response",
|
||||
detail={
|
||||
"status_code": response.status_code,
|
||||
"content_type": response.content_type,
|
||||
"body_head": _head(response.text),
|
||||
},
|
||||
)
|
||||
|
||||
cards, total = parse_search_html(response.text)
|
||||
warnings: list[str] = []
|
||||
if not cards and not total:
|
||||
warnings.append("empty HTML search page")
|
||||
has_next = len(cards) >= 50
|
||||
if total is not None and page * 50 < total:
|
||||
has_next = True
|
||||
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=total,
|
||||
items=cards,
|
||||
has_next=has_next,
|
||||
warnings=warnings,
|
||||
access_mode=self.access_mode,
|
||||
)
|
||||
|
||||
|
||||
def search_params(query: SearchQuery, page: int) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {
|
||||
"q": query.query,
|
||||
"p": page,
|
||||
"cd": 1,
|
||||
"localPriority": 0,
|
||||
}
|
||||
if query.price_min is not None:
|
||||
params["pmin"] = query.price_min
|
||||
if query.price_max is not None:
|
||||
params["pmax"] = query.price_max
|
||||
return params
|
||||
|
||||
|
||||
def build_search_url(settings: Settings, query: SearchQuery, page: int) -> str:
|
||||
params = search_params(query, page)
|
||||
params.update(query.extra_params)
|
||||
return f"{BASE_URL}{settings.html_search_path}?{urlencode(params)}"
|
||||
|
||||
|
||||
def parse_search_html(text: str) -> tuple[list[ListingCard], int | None]:
|
||||
blocks = text.split(ITEM_MARKER)[1:]
|
||||
cards: list[ListingCard] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for block in blocks:
|
||||
card = _parse_item(block)
|
||||
if card is None or card.id in seen:
|
||||
continue
|
||||
seen.add(card.id)
|
||||
cards.append(card)
|
||||
|
||||
match = TOTAL_RE.search(html_module.unescape(text))
|
||||
meta_match = re.search(
|
||||
r'<meta[^>]+name="description"[^>]+content="([^"]+)"',
|
||||
text,
|
||||
re.S | re.I,
|
||||
)
|
||||
if meta_match:
|
||||
match = TOTAL_RE.search(html_module.unescape(meta_match.group(1))) or match
|
||||
total: int | None = None
|
||||
if match:
|
||||
digits = re.sub(r"\D", "", match.group(1))
|
||||
if digits:
|
||||
total = int(digits)
|
||||
return cards, total
|
||||
|
||||
|
||||
def _parse_item(block: str) -> ListingCard | None:
|
||||
item_id_match = re.search(r'data-item-id="(\d+)"', block)
|
||||
title_match = re.search(rf'{TITLE_MARKER}[^>]*>(.*?)</a>', block, re.S | re.I)
|
||||
href_match = re.search(rf'{TITLE_MARKER}[^>]*href="([^"]+)"', block, re.S | re.I)
|
||||
price_match = re.search(rf'{PRICE_MARKER}[^>]*content="(\d+)"', block, re.S | re.I)
|
||||
description_match = re.search(rf'{DESCRIPTION_MARKER}">(.*?)</p>', block, re.S)
|
||||
|
||||
price: int | None = None
|
||||
if price_match:
|
||||
price = int(price_match.group(1))
|
||||
else:
|
||||
price_text = re.search(
|
||||
r'data-marker="item-price"[^>]*>(.*?)</p>',
|
||||
block,
|
||||
re.S | re.I,
|
||||
)
|
||||
if price_text:
|
||||
digits = re.sub(r"\D", "", _strip_html(price_text.group(1)))
|
||||
if digits:
|
||||
price = int(digits)
|
||||
|
||||
if not item_id_match or not title_match:
|
||||
return None
|
||||
title = _strip_html(title_match.group(1))
|
||||
if not title:
|
||||
return None
|
||||
|
||||
href = html_module.unescape(href_match.group(1)) if href_match else ""
|
||||
url = href if href.startswith("http") else BASE_URL + href
|
||||
description = _strip_html(description_match.group(1)) if description_match else None
|
||||
plain = _strip_html(block)
|
||||
seller_type = _seller_type(block, plain)
|
||||
|
||||
return ListingCard(
|
||||
id=item_id_match.group(1),
|
||||
title=title,
|
||||
description=description or None,
|
||||
price=price,
|
||||
url=url,
|
||||
seller_type=seller_type,
|
||||
seller_is_company=(seller_type == "company") if seller_type else None,
|
||||
)
|
||||
|
||||
|
||||
def _seller_type(block: str, plain: str) -> str | None:
|
||||
if "Самозанятый" in plain:
|
||||
return "self_employed"
|
||||
if "Компания" in plain or "/brands/" in block:
|
||||
return "company"
|
||||
if "/user/" in block:
|
||||
return "private"
|
||||
return None
|
||||
|
||||
|
||||
def _strip_html(value: str) -> str:
|
||||
value = re.sub(r"<script.*?</script>", " ", value, flags=re.S | re.I)
|
||||
value = re.sub(r"<style.*?</style>", " ", value, flags=re.S | re.I)
|
||||
value = re.sub(r"<[^>]+>", " ", value)
|
||||
value = html_module.unescape(value)
|
||||
return re.sub(r"\s+", " ", value).strip()
|
||||
|
||||
|
||||
def _head(text: str, limit: int = 300) -> str:
|
||||
return text.strip().replace("\n", " ")[:limit]
|
||||
@@ -0,0 +1,169 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from curl_cffi import requests
|
||||
from curl_cffi.requests import ProxySpec
|
||||
|
||||
from avito_tools.config import AccessMode, Settings
|
||||
from avito_tools.cookies import CookieStore
|
||||
from avito_tools.errors import ConfigError, TransportError
|
||||
|
||||
BOOTSTRAP_URL = "https://www.avito.ru/"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class HttpResponse:
|
||||
status_code: int
|
||||
content_type: str
|
||||
text: str
|
||||
elapsed_ms: int
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
url: str = ""
|
||||
|
||||
@property
|
||||
def is_json(self) -> bool:
|
||||
return "json" in self.content_type.lower()
|
||||
|
||||
@property
|
||||
def looks_like_html(self) -> bool:
|
||||
head = self.text.lstrip()[:200].lower()
|
||||
return (
|
||||
"html" in self.content_type.lower()
|
||||
or head.startswith("<!doctype")
|
||||
or head.startswith("<html")
|
||||
)
|
||||
|
||||
|
||||
class AvitoHttpClient:
|
||||
"""Small curl_cffi wrapper with browser impersonation, cookies and pacing."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings,
|
||||
*,
|
||||
mode: AccessMode = "anonymous",
|
||||
cookie_store: CookieStore | None = None,
|
||||
bootstrap: bool = True,
|
||||
) -> None:
|
||||
self.settings = settings
|
||||
self.mode = mode
|
||||
self.cookie_store = cookie_store
|
||||
self._last_request_at: float | None = None
|
||||
self._bootstrap_done = mode != "anonymous" or not bootstrap
|
||||
self.last_bootstrap_response: HttpResponse | None = None
|
||||
self._session: requests.Session = requests.Session(impersonate=settings.impersonate)
|
||||
self._session.headers.update(
|
||||
{
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "ru-RU,ru;q=0.9,en;q=0.8",
|
||||
"Referer": "https://www.avito.ru/",
|
||||
"Sec-Fetch-Dest": "empty",
|
||||
"Sec-Fetch-Mode": "cors",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
}
|
||||
)
|
||||
if settings.user_agent:
|
||||
self._session.headers["User-Agent"] = settings.user_agent
|
||||
|
||||
def _proxies(self) -> ProxySpec | None:
|
||||
if not self.settings.proxy:
|
||||
return None
|
||||
return {"http": self.settings.proxy, "https": self.settings.proxy}
|
||||
|
||||
def _apply_cookie(self) -> None:
|
||||
if self.mode != "account":
|
||||
return
|
||||
cookie = self.cookie_store.get() if self.cookie_store else self.settings.cookie_value
|
||||
if not cookie:
|
||||
raise ConfigError(
|
||||
"account cookies are not configured",
|
||||
detail={"hint": "set AVITO_COOKIE or AVITO_COOKIE_FILE"},
|
||||
)
|
||||
self._session.headers["Cookie"] = cookie
|
||||
|
||||
def _pace(self) -> None:
|
||||
if self._last_request_at is None:
|
||||
return
|
||||
delay = random.uniform(
|
||||
self.settings.request_delay_min,
|
||||
self.settings.request_delay_max,
|
||||
)
|
||||
elapsed = time.monotonic() - self._last_request_at
|
||||
if elapsed < delay:
|
||||
time.sleep(delay - elapsed)
|
||||
|
||||
def ensure_bootstrap(self) -> HttpResponse | None:
|
||||
"""Open the homepage once for anonymous mode and let the session store cookies."""
|
||||
if self._bootstrap_done:
|
||||
return None
|
||||
self._bootstrap_done = True
|
||||
response = self.get(
|
||||
BOOTSTRAP_URL,
|
||||
pace=False,
|
||||
headers={
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "none",
|
||||
"Referer": "https://www.avito.ru/",
|
||||
},
|
||||
)
|
||||
self.last_bootstrap_response = response
|
||||
return response
|
||||
|
||||
@property
|
||||
def cookie_count(self) -> int:
|
||||
try:
|
||||
return len(self._session.cookies)
|
||||
except TypeError:
|
||||
return 0
|
||||
|
||||
def get(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
params: dict[str, Any] | None = None,
|
||||
pace: bool = True,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> HttpResponse:
|
||||
self._apply_cookie()
|
||||
if pace:
|
||||
self._pace()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = self._session.get(
|
||||
url,
|
||||
params=params,
|
||||
headers=headers,
|
||||
timeout=self.settings.timeout_sec,
|
||||
proxies=self._proxies(),
|
||||
allow_redirects=True,
|
||||
)
|
||||
except Exception as exc: # curl_cffi raises its own hierarchy
|
||||
raise TransportError(f"HTTP request failed: {exc}") from exc
|
||||
finally:
|
||||
self._last_request_at = time.monotonic()
|
||||
|
||||
elapsed_ms = int((time.monotonic() - started) * 1000)
|
||||
content_type = response.headers.get("Content-Type", "")
|
||||
return HttpResponse(
|
||||
status_code=response.status_code,
|
||||
content_type=content_type,
|
||||
text=response.text,
|
||||
elapsed_ms=elapsed_ms,
|
||||
headers={
|
||||
key.lower(): value
|
||||
for key, value in response.headers.items()
|
||||
if isinstance(value, str)
|
||||
},
|
||||
url=str(response.url),
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
close = getattr(self._session, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
@@ -0,0 +1,350 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from avito_tools.collector.canary import detect_block, validate_search_payload
|
||||
from avito_tools.collector.http import AvitoHttpClient, HttpResponse
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage, SearchQuery, epoch_to_datetime
|
||||
from avito_tools.errors import BlockedError, SchemaDriftError, TransportError
|
||||
|
||||
SEARCH_URL = "https://www.avito.ru/web/1/js/items"
|
||||
BASE_URL = "https://www.avito.ru"
|
||||
|
||||
|
||||
class WebSearchProvider:
|
||||
"""Unofficial Avito web JSON search provider.
|
||||
|
||||
This is deliberately the only place that knows the endpoint shape.
|
||||
The rest of the application depends on SearchPage/ListingCard.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client: AvitoHttpClient,
|
||||
settings: Settings,
|
||||
*,
|
||||
access_mode: str = "anonymous",
|
||||
bootstrap: bool = True,
|
||||
) -> None:
|
||||
self.client = client
|
||||
self.settings = settings
|
||||
self.access_mode = access_mode
|
||||
self.bootstrap = bootstrap and access_mode == "anonymous"
|
||||
self._bootstrap_done = False
|
||||
self.last_response: HttpResponse | None = None
|
||||
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage:
|
||||
if page < 1:
|
||||
raise ValueError("page must be >= 1")
|
||||
|
||||
if self.bootstrap and not self._bootstrap_done:
|
||||
self._bootstrap_done = True
|
||||
bootstrap_response = self.client.ensure_bootstrap()
|
||||
if bootstrap_response is not None:
|
||||
block_reason = detect_block(bootstrap_response)
|
||||
if block_reason:
|
||||
raise BlockedError(
|
||||
f"anonymous bootstrap blocked: {block_reason}",
|
||||
status_code=bootstrap_response.status_code,
|
||||
retry_after=bootstrap_response.headers.get("retry-after"),
|
||||
detail={"url": bootstrap_response.url},
|
||||
)
|
||||
if bootstrap_response.status_code >= 400:
|
||||
raise TransportError(
|
||||
f"anonymous bootstrap failed with HTTP {bootstrap_response.status_code}",
|
||||
detail={"url": bootstrap_response.url},
|
||||
)
|
||||
|
||||
params: dict[str, Any] = {
|
||||
"q": query.query,
|
||||
"p": page,
|
||||
"context": "",
|
||||
"updateListOnly": "true",
|
||||
}
|
||||
location_id = query.location_id
|
||||
if location_id is None:
|
||||
location_id = self.settings.location_id
|
||||
category_id = query.category_id
|
||||
if category_id is None:
|
||||
category_id = self.settings.category_id
|
||||
if location_id:
|
||||
params["locationId"] = location_id
|
||||
if category_id:
|
||||
params["categoryId"] = category_id
|
||||
if query.price_min is not None:
|
||||
params["pmin"] = query.price_min
|
||||
if query.price_max is not None:
|
||||
params["pmax"] = query.price_max
|
||||
params.update(query.extra_params)
|
||||
|
||||
response = self.client.get(SEARCH_URL, params=params)
|
||||
self.last_response = response
|
||||
|
||||
block_reason = detect_block(response)
|
||||
if block_reason:
|
||||
raise BlockedError(
|
||||
f"Avito blocked the request: {block_reason}",
|
||||
status_code=response.status_code,
|
||||
retry_after=response.headers.get("retry-after"),
|
||||
detail={"url": response.url, "body_head": _head(response.text)},
|
||||
)
|
||||
|
||||
if not response.is_json:
|
||||
raise SchemaDriftError(
|
||||
"expected JSON response",
|
||||
detail={
|
||||
"status_code": response.status_code,
|
||||
"content_type": response.content_type,
|
||||
"body_head": _head(response.text),
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
payload = json.loads(response.text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise SchemaDriftError(
|
||||
"invalid JSON response",
|
||||
detail={"error": str(exc), "body_head": _head(response.text)},
|
||||
) from exc
|
||||
|
||||
canary = validate_search_payload(payload, page=page)
|
||||
if canary.fatal:
|
||||
raise SchemaDriftError(
|
||||
"search payload failed canary checks",
|
||||
detail={"errors": canary.errors, "warnings": canary.warnings},
|
||||
)
|
||||
|
||||
raw_items = _payload_items(payload)
|
||||
items: list[ListingCard] = []
|
||||
skipped = 0
|
||||
for raw in raw_items:
|
||||
card = _normalize_item(raw)
|
||||
if card is None:
|
||||
skipped += 1
|
||||
continue
|
||||
items.append(card)
|
||||
|
||||
total = _payload_total(payload)
|
||||
warnings = list(canary.warnings)
|
||||
if skipped:
|
||||
warnings.append(f"skipped {skipped} unparseable items")
|
||||
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=total,
|
||||
items=items,
|
||||
has_next=_has_next(total, page, len(raw_items)),
|
||||
warnings=warnings,
|
||||
access_mode=self.access_mode,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_item(raw: Any) -> ListingCard | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
|
||||
item_id = _string(raw.get("id") or raw.get("itemId"))
|
||||
title = _string(raw.get("title"))
|
||||
url_path = _string(raw.get("urlPath") or raw.get("uri"))
|
||||
if not item_id or not title or not url_path:
|
||||
return None
|
||||
|
||||
location = raw.get("location")
|
||||
address = raw.get("addressDetailed")
|
||||
seller = raw.get("seller") or raw.get("sellerInfo")
|
||||
images = raw.get("images")
|
||||
category = raw.get("category")
|
||||
iva = raw.get("iva")
|
||||
|
||||
location_name = _name(location)
|
||||
if not location_name and isinstance(address, dict):
|
||||
location_name = _name(address.get("locationName"))
|
||||
category_id = _int(raw.get("categoryId"))
|
||||
if category_id is None and isinstance(category, dict):
|
||||
category_id = _int(category.get("id"))
|
||||
|
||||
seller_name, seller_type, seller_profile = _seller_info(iva)
|
||||
top_seller_company = _bool(seller.get("isCompany")) if isinstance(seller, dict) else None
|
||||
if seller_type is None and top_seller_company is not None:
|
||||
seller_type = "company" if top_seller_company else "private"
|
||||
seller_name = _name(seller) or seller_name
|
||||
|
||||
return ListingCard(
|
||||
id=item_id,
|
||||
title=title,
|
||||
description=_string(raw.get("description")) or None,
|
||||
price=_extract_price(raw),
|
||||
url=url_path if url_path.startswith("http") else BASE_URL + url_path,
|
||||
published_at=epoch_to_datetime(raw.get("sortTimeStamp") or raw.get("allowTimeStamp")),
|
||||
location=location_name,
|
||||
seller=seller_name,
|
||||
seller_is_company=(
|
||||
seller_type == "company"
|
||||
if seller_type is not None
|
||||
else top_seller_company
|
||||
),
|
||||
seller_type=seller_type,
|
||||
seller_profile=seller_profile,
|
||||
image=_first_image(images),
|
||||
category_id=category_id,
|
||||
)
|
||||
|
||||
|
||||
def _extract_price(item: dict[str, Any]) -> int | None:
|
||||
detailed = item.get("priceDetailed")
|
||||
if isinstance(detailed, dict):
|
||||
value = detailed.get("value")
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return int(value)
|
||||
value = item.get("price")
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
digits = "".join(ch for ch in value if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
return None
|
||||
|
||||
|
||||
def _first_int(payload: dict[str, Any], keys: tuple[str, ...]) -> int | None:
|
||||
for key in keys:
|
||||
value = payload.get(key)
|
||||
if isinstance(value, bool):
|
||||
continue
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str) and value.strip().isdigit():
|
||||
return int(value.strip())
|
||||
return None
|
||||
|
||||
|
||||
def _int(value: Any) -> int | None:
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str) and value.strip().isdigit():
|
||||
return int(value.strip())
|
||||
return None
|
||||
|
||||
|
||||
def _bool(value: Any) -> bool | None:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _string(value: Any) -> str:
|
||||
if isinstance(value, bool):
|
||||
return ""
|
||||
if isinstance(value, (int, float)):
|
||||
return str(int(value))
|
||||
return value.strip() if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _name(value: Any) -> str | None:
|
||||
if isinstance(value, str):
|
||||
return value.strip() or None
|
||||
if isinstance(value, dict):
|
||||
name = value.get("name")
|
||||
return name.strip() if isinstance(name, str) and name.strip() else None
|
||||
return None
|
||||
|
||||
|
||||
def _first_image(value: Any) -> str | None:
|
||||
if isinstance(value, str):
|
||||
return value.strip() or None
|
||||
if not isinstance(value, list):
|
||||
return None
|
||||
for entry in value:
|
||||
if isinstance(entry, str) and entry.strip():
|
||||
return entry.strip()
|
||||
if isinstance(entry, dict):
|
||||
for candidate in entry.values():
|
||||
if isinstance(candidate, str) and candidate.strip():
|
||||
return candidate.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _seller_info(iva: Any) -> tuple[str | None, str | None, str | None]:
|
||||
if not isinstance(iva, dict):
|
||||
return None, None, None
|
||||
|
||||
profile_title: str | None = None
|
||||
profile_link: str | None = None
|
||||
is_company_line = False
|
||||
is_self_employed = False
|
||||
|
||||
for step in iva.get("SecondLineStep") or []:
|
||||
payload = step.get("payload") if isinstance(step, dict) else None
|
||||
value = _string(payload.get("value")) if isinstance(payload, dict) else ""
|
||||
if value.lower() in {"компания", "магазин"}:
|
||||
is_company_line = True
|
||||
|
||||
for step in iva.get("UserInfoStep") or []:
|
||||
payload = step.get("payload") if isinstance(step, dict) else None
|
||||
if not isinstance(payload, dict):
|
||||
continue
|
||||
profile = payload.get("profile")
|
||||
if isinstance(profile, dict):
|
||||
profile_title = _name(profile.get("title")) or profile_title
|
||||
link = _string(profile.get("link"))
|
||||
if link:
|
||||
profile_link = link
|
||||
for badge in payload.get("badges") or []:
|
||||
title = _string(badge.get("title")) if isinstance(badge, dict) else ""
|
||||
if title.lower() == "самозанятый":
|
||||
is_self_employed = True
|
||||
|
||||
seller_type: str | None = None
|
||||
if is_self_employed:
|
||||
seller_type = "self_employed"
|
||||
elif is_company_line:
|
||||
seller_type = "company"
|
||||
elif profile_link and profile_link.startswith("/user/"):
|
||||
seller_type = "private"
|
||||
elif profile_link and profile_link.startswith("/brands/"):
|
||||
seller_type = "company"
|
||||
|
||||
return profile_title, seller_type, profile_link
|
||||
|
||||
|
||||
def _payload_items(payload: dict[str, Any]) -> list[Any]:
|
||||
items = payload.get("items")
|
||||
if isinstance(items, list):
|
||||
return items
|
||||
catalog = payload.get("catalog")
|
||||
if isinstance(catalog, dict):
|
||||
nested = catalog.get("items")
|
||||
if isinstance(nested, list):
|
||||
return nested
|
||||
return []
|
||||
|
||||
|
||||
def _payload_total(payload: dict[str, Any]) -> int | None:
|
||||
main_count = _first_int(payload, ("count", "mainCount"))
|
||||
if main_count == 0:
|
||||
return 0
|
||||
total = _first_int(payload, ("totalCount", "total", "count"))
|
||||
if total is not None:
|
||||
return total
|
||||
catalog = payload.get("catalog")
|
||||
if isinstance(catalog, dict):
|
||||
return _first_int(catalog, ("totalCount", "total", "count"))
|
||||
return None
|
||||
|
||||
|
||||
def _has_next(total: int | None, page: int, item_count: int) -> bool:
|
||||
if item_count <= 0:
|
||||
return False
|
||||
if total is not None:
|
||||
return total > page * item_count
|
||||
return True
|
||||
|
||||
|
||||
def _head(text: str, limit: int = 300) -> str:
|
||||
return text.strip().replace("\n", " ")[:limit]
|
||||
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, SecretStr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from avito_tools.cookies import normalize_cookie_header, parse_cookie_file
|
||||
|
||||
AccessMode = Literal["anonymous", "account"]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Runtime settings. Secrets are read from env or .env only."""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="AVITO_",
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
cookie: SecretStr | None = None
|
||||
cookie_file: Path | None = None
|
||||
user_agent: str | None = None
|
||||
proxy: str | None = None
|
||||
|
||||
access_mode: AccessMode = "anonymous"
|
||||
account_fallback: bool = True
|
||||
|
||||
database_url: str = "sqlite+aiosqlite:///var/avito.db"
|
||||
database_echo: bool = False
|
||||
|
||||
search_provider: Literal["auto", "json", "html", "browser"] = "auto"
|
||||
html_search_path: str = "/moskva/telefony"
|
||||
browser_cdp_port: int = Field(default=9222, ge=1, le=65535)
|
||||
browser_profile: Path = Path("var/chrome-profile")
|
||||
browser_headless: bool = False
|
||||
browser_chrome: str | None = None
|
||||
browser_timeout_sec: float = Field(default=30.0, ge=5.0)
|
||||
browser_page_delay_sec: float = Field(default=8.0, ge=0.0)
|
||||
|
||||
telegram_bot_token: SecretStr | None = None
|
||||
telegram_chat_id: str | None = None
|
||||
|
||||
worker_poll_interval_sec: int = Field(default=30, ge=5)
|
||||
worker_max_searches_per_cycle: int = Field(default=5, ge=1, le=100)
|
||||
notification_max_attempts: int = Field(default=3, ge=1, le=20)
|
||||
|
||||
location_id: int = 637640
|
||||
category_id: int | None = None
|
||||
|
||||
request_delay_min: float = Field(default=2.5, ge=0.5)
|
||||
request_delay_max: float = Field(default=6.0, ge=0.5)
|
||||
timeout_sec: float = Field(default=25.0, ge=5.0)
|
||||
max_pages: int = Field(default=3, ge=1, le=50)
|
||||
|
||||
impersonate: str = "chrome"
|
||||
data_dir: Path = Path("var")
|
||||
|
||||
@field_validator(
|
||||
"cookie",
|
||||
"user_agent",
|
||||
"proxy",
|
||||
"telegram_chat_id",
|
||||
"browser_chrome",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def empty_string_to_none(cls, value: object) -> object:
|
||||
if isinstance(value, SecretStr):
|
||||
return value
|
||||
if isinstance(value, str) and not value.strip():
|
||||
return None
|
||||
return value
|
||||
|
||||
@field_validator("telegram_bot_token", mode="before")
|
||||
@classmethod
|
||||
def empty_secret_to_none(cls, value: object) -> object:
|
||||
if isinstance(value, SecretStr):
|
||||
return value
|
||||
if isinstance(value, str) and not value.strip():
|
||||
return None
|
||||
return value
|
||||
|
||||
@field_validator("cookie_file", mode="before")
|
||||
@classmethod
|
||||
def empty_path_to_none(cls, value: object) -> object:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
return value
|
||||
|
||||
@field_validator("category_id", mode="before")
|
||||
@classmethod
|
||||
def empty_category_to_none(cls, value: object) -> object:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
return value
|
||||
|
||||
@field_validator("access_mode", mode="before")
|
||||
@classmethod
|
||||
def normalize_access_mode(cls, value: object) -> object:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower()
|
||||
return value
|
||||
|
||||
@field_validator("search_provider", mode="before")
|
||||
@classmethod
|
||||
def normalize_search_provider(cls, value: object) -> object:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower()
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_delay_range(self) -> Settings:
|
||||
if self.request_delay_max < self.request_delay_min:
|
||||
raise ValueError("AVITO_REQUEST_DELAY_MAX must be >= AVITO_REQUEST_DELAY_MIN")
|
||||
return self
|
||||
|
||||
@property
|
||||
def cookie_value(self) -> str | None:
|
||||
if self.cookie:
|
||||
return normalize_cookie_header(self.cookie.get_secret_value())
|
||||
if self.cookie_file:
|
||||
return parse_cookie_file(self.cookie_file)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def normalize_cookie_header(value: str) -> str | None:
|
||||
value = value.strip()
|
||||
if value.lower().startswith("cookie:"):
|
||||
value = value.split(":", 1)[1].strip()
|
||||
if not value:
|
||||
return None
|
||||
|
||||
pairs: dict[str, str] = {}
|
||||
for part in value.split(";"):
|
||||
part = part.strip()
|
||||
if not part or "=" not in part:
|
||||
continue
|
||||
name, cookie_value = part.split("=", 1)
|
||||
name = name.strip()
|
||||
if name:
|
||||
pairs[name] = cookie_value
|
||||
return "; ".join(f"{name}={cookie_value}" for name, cookie_value in pairs.items()) or None
|
||||
|
||||
|
||||
def parse_cookie_file(path: Path) -> str | None:
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
stripped = text.lstrip()
|
||||
if stripped.startswith("[") or stripped.startswith("{"):
|
||||
return parse_json_cookies(stripped)
|
||||
return parse_netscape_cookies(text)
|
||||
|
||||
|
||||
def parse_json_cookies(text: str) -> str | None:
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
entries: list[dict[str, Any]] = []
|
||||
if isinstance(payload, list):
|
||||
entries = [entry for entry in payload if isinstance(entry, dict)]
|
||||
elif isinstance(payload, dict):
|
||||
nested = payload.get("cookies")
|
||||
if isinstance(nested, list):
|
||||
entries = [entry for entry in nested if isinstance(entry, dict)]
|
||||
else:
|
||||
return None
|
||||
|
||||
selected: dict[str, tuple[str, str, float]] = {}
|
||||
for entry in entries:
|
||||
domain = str(entry.get("domain", ""))
|
||||
if "avito.ru" not in domain.lower():
|
||||
continue
|
||||
name = entry.get("name")
|
||||
value = entry.get("value")
|
||||
if not isinstance(name, str) or not isinstance(value, str):
|
||||
continue
|
||||
expiry = entry.get("expires")
|
||||
expiry_value = float(expiry) if isinstance(expiry, (int, float)) else 0.0
|
||||
candidate = (value, domain, expiry_value)
|
||||
current = selected.get(name)
|
||||
if current is None or _cookie_rank(candidate) > _cookie_rank(current):
|
||||
selected[name] = candidate
|
||||
|
||||
return "; ".join(f"{name}={entry[0]}" for name, entry in selected.items()) or None
|
||||
|
||||
|
||||
def parse_netscape_cookies(text: str) -> str | None:
|
||||
selected: dict[str, tuple[str, str, float]] = {}
|
||||
for raw_line in text.splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or (line.startswith("#") and not line.startswith("#HttpOnly_")):
|
||||
continue
|
||||
if line.startswith("#HttpOnly_"):
|
||||
line = line.removeprefix("#HttpOnly_")
|
||||
fields = line.split("\t")
|
||||
if len(fields) < 7:
|
||||
continue
|
||||
domain, _flag, _cookie_path, _secure, expiry, name, value = fields[:7]
|
||||
if "avito.ru" not in domain.lower():
|
||||
continue
|
||||
try:
|
||||
expiry_value = float(expiry)
|
||||
except ValueError:
|
||||
expiry_value = 0.0
|
||||
candidate = (value, domain, expiry_value)
|
||||
current = selected.get(name)
|
||||
if current is None or _cookie_rank(candidate) > _cookie_rank(current):
|
||||
selected[name] = candidate
|
||||
return "; ".join(f"{name}={entry[0]}" for name, entry in selected.items()) or None
|
||||
|
||||
|
||||
def _cookie_rank(entry: tuple[str, str, float]) -> tuple[int, int, float]:
|
||||
_value, domain, expiry = entry
|
||||
if domain.startswith("www.avito.ru"):
|
||||
domain_rank = 3
|
||||
elif domain.startswith(".www.avito.ru"):
|
||||
domain_rank = 2
|
||||
else:
|
||||
domain_rank = 1
|
||||
return domain_rank, len(domain), expiry
|
||||
|
||||
|
||||
class CookieStore:
|
||||
"""Reloads account cookies from disk when the file changes."""
|
||||
|
||||
def __init__(self, raw_cookie: str | None = None, path: Path | None = None) -> None:
|
||||
self.raw_cookie = normalize_cookie_header(raw_cookie) if raw_cookie else None
|
||||
self.path = path
|
||||
self._mtime: float | None = None
|
||||
self._cached: str | None = None
|
||||
|
||||
def get(self) -> str | None:
|
||||
if self.raw_cookie:
|
||||
return self.raw_cookie
|
||||
if not self.path:
|
||||
return None
|
||||
try:
|
||||
mtime = self.path.stat().st_mtime
|
||||
except OSError:
|
||||
return None
|
||||
if mtime != self._mtime:
|
||||
self._cached = parse_cookie_file(self.path)
|
||||
self._mtime = mtime
|
||||
return self._cached
|
||||
@@ -0,0 +1,265 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from websockets.asyncio.client import connect
|
||||
from websockets.typing import Origin
|
||||
|
||||
DEFAULT_URL = "https://www.avito.ru/"
|
||||
DEFAULT_VERIFY_URL = "https://www.avito.ru/moskva/telefony?q=galaxy+fold+8"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CaptureResult:
|
||||
path: Path
|
||||
mode: str
|
||||
cookie_count: int
|
||||
cookie_header: str
|
||||
user_agent: str | None
|
||||
|
||||
|
||||
def find_chrome(explicit: str | None = None) -> str:
|
||||
candidates = [explicit] if explicit else []
|
||||
candidates.extend(["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"])
|
||||
for candidate in candidates:
|
||||
if not candidate:
|
||||
continue
|
||||
found = shutil.which(candidate)
|
||||
if found:
|
||||
return found
|
||||
raise RuntimeError("Chrome/Chromium not found; pass --chrome /path/to/chrome")
|
||||
|
||||
|
||||
async def _wait_for_target(port: int, timeout: float = 20.0) -> str:
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error: Exception | None = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"http://127.0.0.1:{port}/json/list",
|
||||
timeout=2,
|
||||
) as response:
|
||||
targets = json.loads(response.read().decode("utf-8"))
|
||||
pages = [target for target in targets if target.get("type") == "page"]
|
||||
if pages:
|
||||
return str(pages[0]["webSocketDebuggerUrl"])
|
||||
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc:
|
||||
last_error = exc
|
||||
await asyncio.sleep(0.3)
|
||||
raise RuntimeError(f"Chrome DevTools is not available on port {port}: {last_error}")
|
||||
|
||||
|
||||
async def _cdp_call(
|
||||
ws,
|
||||
request_id: int,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
await ws.send(json.dumps({"id": request_id, "method": method, "params": params or {}}))
|
||||
while True:
|
||||
message = json.loads(await ws.recv())
|
||||
if message.get("id") != request_id:
|
||||
continue
|
||||
if "error" in message:
|
||||
raise RuntimeError(f"CDP {method} failed: {message['error']}")
|
||||
return dict(message.get("result") or {})
|
||||
|
||||
|
||||
async def _capture(
|
||||
*,
|
||||
port: int,
|
||||
prompt: str,
|
||||
verify_url: str,
|
||||
) -> tuple[list[dict[str, Any]], str | None]:
|
||||
ws_url = await _wait_for_target(port)
|
||||
async with connect(
|
||||
ws_url,
|
||||
max_size=2**24,
|
||||
open_timeout=10,
|
||||
origin=Origin(f"http://127.0.0.1:{port}"),
|
||||
) as ws:
|
||||
await _cdp_call(ws, 1, "Network.enable")
|
||||
await _cdp_call(ws, 2, "Page.enable")
|
||||
print(prompt)
|
||||
await asyncio.to_thread(input, "Нажми Enter, когда капча решена и сессия готова... ")
|
||||
|
||||
await _cdp_call(ws, 3, "Page.navigate", {"url": verify_url})
|
||||
for _ in range(50):
|
||||
state = await _cdp_call(
|
||||
ws,
|
||||
4,
|
||||
"Runtime.evaluate",
|
||||
{"expression": "document.readyState", "returnByValue": True},
|
||||
)
|
||||
if (state.get("result") or {}).get("value") == "complete":
|
||||
break
|
||||
await asyncio.sleep(0.3)
|
||||
|
||||
if not await _wait_for_search_ready(ws, timeout=15.0):
|
||||
print(f"Открыта страница поиска: {verify_url}")
|
||||
await asyncio.to_thread(
|
||||
input,
|
||||
"Появилась капча или проверка. Реши её и нажми Enter... ",
|
||||
)
|
||||
if not await _wait_for_search_ready(ws, timeout=25.0):
|
||||
print(
|
||||
"warning: не удалось подтвердить, что поиск загрузился; "
|
||||
"сохраняю cookies, проверь их через probe"
|
||||
)
|
||||
else:
|
||||
print("Поиск загрузился, сессия готова")
|
||||
else:
|
||||
print("Поиск загрузился, сессия готова")
|
||||
|
||||
cookies_result = await _cdp_call(ws, 5, "Network.getAllCookies")
|
||||
cookies = [
|
||||
cookie
|
||||
for cookie in cookies_result.get("cookies", [])
|
||||
if "avito.ru" in str(cookie.get("domain", "")).lower()
|
||||
]
|
||||
user_agent: str | None = None
|
||||
try:
|
||||
ua_result = await _cdp_call(
|
||||
ws,
|
||||
6,
|
||||
"Runtime.evaluate",
|
||||
{"expression": "navigator.userAgent", "returnByValue": True},
|
||||
)
|
||||
value = (ua_result.get("result") or {}).get("value")
|
||||
user_agent = value if isinstance(value, str) else None
|
||||
except RuntimeError:
|
||||
pass
|
||||
return cookies, user_agent
|
||||
|
||||
|
||||
async def _wait_for_search_ready(ws, *, timeout: float) -> bool:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = await _cdp_call(
|
||||
ws,
|
||||
7,
|
||||
"Runtime.evaluate",
|
||||
{
|
||||
"expression": (
|
||||
"({ready: document.readyState, "
|
||||
"items: document.querySelectorAll('[data-marker=\"item\"]').length, "
|
||||
"body: document.body ? document.body.innerText.slice(0, 500) : ''})"
|
||||
),
|
||||
"returnByValue": True,
|
||||
},
|
||||
)
|
||||
value = (result.get("result") or {}).get("value") or {}
|
||||
cookies_result = await _cdp_call(ws, 8, "Network.getAllCookies")
|
||||
names = {
|
||||
str(cookie.get("name"))
|
||||
for cookie in cookies_result.get("cookies", [])
|
||||
if "avito.ru" in str(cookie.get("domain", "")).lower()
|
||||
}
|
||||
body = str(value.get("body") or "").lower()
|
||||
captcha = any(
|
||||
marker in body
|
||||
for marker in ("доступ ограничен", "подтвердите, что вы не робот", "captcha")
|
||||
)
|
||||
if value.get("ready") == "complete" and "pow_solved" in names and not captcha:
|
||||
return True
|
||||
if value.get("ready") == "complete" and int(value.get("items") or 0) > 0:
|
||||
return True
|
||||
await asyncio.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def capture_cookies(
|
||||
*,
|
||||
mode: str = "anonymous",
|
||||
output: Path = Path("var/avito-cookies.json"),
|
||||
profile: Path = Path("var/chrome-profile"),
|
||||
port: int = 9222,
|
||||
chrome: str | None = None,
|
||||
url: str = DEFAULT_URL,
|
||||
verify_url: str = DEFAULT_VERIFY_URL,
|
||||
launch: bool = True,
|
||||
keep_open: bool = False,
|
||||
) -> CaptureResult:
|
||||
if mode not in {"anonymous", "account"}:
|
||||
raise ValueError("mode must be anonymous or account")
|
||||
|
||||
process: subprocess.Popen[bytes] | None = None
|
||||
if launch:
|
||||
binary = find_chrome(chrome)
|
||||
profile.mkdir(parents=True, exist_ok=True)
|
||||
process = subprocess.Popen(
|
||||
[
|
||||
binary,
|
||||
f"--remote-debugging-port={port}",
|
||||
"--remote-debugging-address=127.0.0.1",
|
||||
"--remote-allow-origins=*",
|
||||
f"--user-data-dir={profile.resolve()}",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--start-maximized",
|
||||
url,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
time.sleep(1.0)
|
||||
|
||||
try:
|
||||
prompt = (
|
||||
"Открыт Авито. Войди в аккаунт и реши капчу, если она появилась."
|
||||
if mode == "account"
|
||||
else "Открыт Авито. Реши капчу, если она появилась. Логиниться не нужно."
|
||||
)
|
||||
cookies, user_agent = asyncio.run(
|
||||
_capture(port=port, prompt=prompt, verify_url=verify_url)
|
||||
)
|
||||
finally:
|
||||
if process is not None and not keep_open:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
if not cookies:
|
||||
raise RuntimeError("no avito.ru cookies found; complete the captcha and try again")
|
||||
names = {str(cookie.get("name")) for cookie in cookies}
|
||||
if "pow_solved" not in names:
|
||||
print(
|
||||
"warning: pow_solved cookie not found; для HTML/account это нормально, "
|
||||
"probe проверит сессию"
|
||||
)
|
||||
|
||||
header = "; ".join(f"{cookie['name']}={cookie['value']}" for cookie in cookies)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"mode": mode,
|
||||
"captured_at": datetime.now(UTC).isoformat(),
|
||||
"user_agent": user_agent,
|
||||
"cookies": cookies,
|
||||
}
|
||||
output.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
output.chmod(0o600)
|
||||
return CaptureResult(
|
||||
path=output,
|
||||
mode=mode,
|
||||
cookie_count=len(cookies),
|
||||
cookie_header=header,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
|
||||
|
||||
def cookie_header_from_file(path: Path) -> str | None:
|
||||
from avito_tools.cookies import parse_cookie_file
|
||||
|
||||
return parse_cookie_file(path)
|
||||
@@ -0,0 +1,98 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class EgressInfo(BaseModel):
|
||||
ip: str | None = None
|
||||
country: str | None = None
|
||||
org: str | None = None
|
||||
|
||||
|
||||
class ListingCard(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
id: str
|
||||
title: str
|
||||
description: str | None = None
|
||||
price: int | None = None
|
||||
url: str
|
||||
published_at: datetime | None = None
|
||||
location: str | None = None
|
||||
seller: str | None = None
|
||||
seller_is_company: bool | None = None
|
||||
seller_type: str | None = None
|
||||
seller_profile: str | None = None
|
||||
image: str | None = None
|
||||
category_id: int | None = None
|
||||
|
||||
|
||||
class SearchPage(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
query: str
|
||||
page: int
|
||||
total: int | None = None
|
||||
items: list[ListingCard] = Field(default_factory=list)
|
||||
has_next: bool = False
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
fetched_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
access_mode: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return self.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
class SearchQuery(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
query: str
|
||||
location_id: int | None = None
|
||||
category_id: int | None = None
|
||||
price_min: int | None = None
|
||||
price_max: int | None = None
|
||||
extra_params: dict[str, str] = Field(default_factory=dict)
|
||||
title_pattern: str | None = None
|
||||
exclude_title_keywords: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
|
||||
class ProbeReport(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
ok: bool
|
||||
egress: EgressInfo | None = None
|
||||
cookie_present: bool = False
|
||||
access_mode: str | None = None
|
||||
http_status: int | None = None
|
||||
total: int | None = None
|
||||
items_count: int = 0
|
||||
sample: list[dict[str, Any]] = []
|
||||
warnings: list[str] = []
|
||||
error: dict[str, Any] | None = None
|
||||
latency_ms: int | None = None
|
||||
query: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return self.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
def epoch_to_datetime(value: Any) -> datetime | None:
|
||||
"""Convert Avito epoch timestamps (seconds or milliseconds) to UTC datetime."""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if number <= 0:
|
||||
return None
|
||||
if number > 10_000_000_000:
|
||||
number = number / 1000
|
||||
try:
|
||||
return datetime.fromtimestamp(number, tz=UTC)
|
||||
except (OverflowError, OSError, ValueError):
|
||||
return None
|
||||
@@ -0,0 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class AvitoToolsError(Exception):
|
||||
"""Base error with a stable machine-readable code."""
|
||||
|
||||
code = "avito_tools_error"
|
||||
retryable = False
|
||||
|
||||
def __init__(self, message: str, *, detail: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.detail = detail or {}
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"code": self.code,
|
||||
"message": self.message,
|
||||
"retryable": self.retryable,
|
||||
"detail": self.detail,
|
||||
}
|
||||
|
||||
|
||||
class ConfigError(AvitoToolsError):
|
||||
code = "config_error"
|
||||
|
||||
|
||||
class TransportError(AvitoToolsError):
|
||||
code = "transport_error"
|
||||
retryable = True
|
||||
|
||||
|
||||
class BlockedError(AvitoToolsError):
|
||||
code = "blocked"
|
||||
retryable = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
status_code: int | None = None,
|
||||
retry_after: str | None = None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
payload = dict(detail or {})
|
||||
if status_code is not None:
|
||||
payload["status_code"] = status_code
|
||||
if retry_after is not None:
|
||||
payload["retry_after"] = retry_after
|
||||
super().__init__(message, detail=payload)
|
||||
self.status_code = status_code
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
class SchemaDriftError(AvitoToolsError):
|
||||
code = "schema_drift"
|
||||
retryable = False
|
||||
|
||||
def __init__(self, message: str, *, detail: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message, detail=detail)
|
||||
@@ -0,0 +1 @@
|
||||
"""MCP server package for avito-tools."""
|
||||
@@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.mcp.server import create_server
|
||||
from avito_tools.services.search import SearchService
|
||||
from avito_tools.services.stats import PriceStatsService
|
||||
|
||||
|
||||
def run_mcp(
|
||||
*,
|
||||
transport: str = "stdio",
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 8765,
|
||||
) -> None:
|
||||
settings = Settings()
|
||||
bundle = build_provider(settings)
|
||||
search_service = SearchService(bundle.provider)
|
||||
stats_service = PriceStatsService(search_service)
|
||||
server = create_server(
|
||||
search_service,
|
||||
stats_service,
|
||||
settings=settings,
|
||||
access_modes=bundle.modes,
|
||||
)
|
||||
try:
|
||||
if transport == "http":
|
||||
server.run(
|
||||
transport="http",
|
||||
host=host,
|
||||
port=port,
|
||||
show_banner=False,
|
||||
)
|
||||
else:
|
||||
server.run(show_banner=False)
|
||||
finally:
|
||||
bundle.close()
|
||||
@@ -0,0 +1,236 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from pydantic import Field
|
||||
|
||||
from avito_tools import __version__
|
||||
from avito_tools.analytics.stats import OutlierPolicy
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchQuery
|
||||
from avito_tools.errors import AvitoToolsError
|
||||
from avito_tools.services.search import SearchService
|
||||
from avito_tools.services.stats import PriceStatsService
|
||||
|
||||
|
||||
class ListingCache:
|
||||
"""Small in-process cache so get_listing can return what search already fetched."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._items: dict[str, ListingCard] = {}
|
||||
|
||||
def remember(self, items: list[ListingCard]) -> None:
|
||||
for item in items:
|
||||
self._items[item.id] = item
|
||||
|
||||
def get(self, item_id: str) -> ListingCard | None:
|
||||
return self._items.get(item_id)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._items)
|
||||
|
||||
|
||||
def create_server(
|
||||
search_service: SearchService,
|
||||
stats_service: PriceStatsService,
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
access_modes: Sequence[str] | None = None,
|
||||
) -> FastMCP:
|
||||
resolved_settings = settings or Settings()
|
||||
cache = ListingCache()
|
||||
mcp = FastMCP(
|
||||
"avito-tools",
|
||||
instructions=(
|
||||
"Read-only Avito search and price analytics. "
|
||||
"Use search_listings first, then price_stats for market context. "
|
||||
"get_listing returns only listings already seen by search_listings. "
|
||||
"Prices are asking prices, not completed sales. "
|
||||
"Never claim a listing is a match without evidence from its description."
|
||||
),
|
||||
)
|
||||
|
||||
@mcp.tool
|
||||
def search_listings(
|
||||
query: Annotated[str, Field(min_length=1, max_length=200)],
|
||||
location_id: Annotated[int | None, Field(ge=1)] = None,
|
||||
category_id: Annotated[int | None, Field(ge=1)] = None,
|
||||
price_min: Annotated[int | None, Field(ge=0)] = None,
|
||||
price_max: Annotated[int | None, Field(ge=0)] = None,
|
||||
pages: Annotated[int, Field(ge=1, le=10)] = 1,
|
||||
limit: Annotated[int, Field(ge=1, le=200)] = 20,
|
||||
include_description: bool = False,
|
||||
seller: Literal["any", "private", "company"] = "any",
|
||||
title_pattern: str | None = None,
|
||||
exclude_title_keywords: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Search live Avito listings and return compact rows.
|
||||
|
||||
Use location_id=637640 for Moscow. Set include_description only when the
|
||||
description is needed, because it increases the response size.
|
||||
seller uses Avito's exact user filter: private or company.
|
||||
title_pattern is a regex applied to titles; exclude_title_keywords
|
||||
removes accessories, parts and other unwanted titles.
|
||||
"""
|
||||
try:
|
||||
batch = search_service.search(
|
||||
SearchQuery(
|
||||
query=query,
|
||||
location_id=location_id,
|
||||
category_id=category_id,
|
||||
price_min=price_min,
|
||||
price_max=price_max,
|
||||
extra_params=_seller_params(seller),
|
||||
title_pattern=title_pattern,
|
||||
exclude_title_keywords=exclude_title_keywords or [],
|
||||
),
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
return {"ok": False, "error": exc.as_dict()}
|
||||
|
||||
cache.remember(batch.items)
|
||||
return {
|
||||
"ok": True,
|
||||
"query": batch.query,
|
||||
"total": batch.total,
|
||||
"returned": len(batch.items),
|
||||
"pages_fetched": batch.pages_fetched,
|
||||
"has_more": batch.has_more,
|
||||
"access_mode": batch.access_mode,
|
||||
"warnings": batch.warnings,
|
||||
"items": [
|
||||
_row(item, include_description=include_description)
|
||||
for item in batch.items
|
||||
],
|
||||
}
|
||||
|
||||
@mcp.tool
|
||||
def get_listing(item_id: str) -> dict[str, Any]:
|
||||
"""Return full cached details for a listing seen by search_listings."""
|
||||
item = cache.get(item_id)
|
||||
if item is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": {
|
||||
"code": "not_cached",
|
||||
"message": "listing is not in the current cache; call search_listings first",
|
||||
},
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"item": item.model_dump(mode="json", exclude_none=True),
|
||||
}
|
||||
|
||||
@mcp.tool
|
||||
def price_stats(
|
||||
query: Annotated[str, Field(min_length=1, max_length=200)],
|
||||
location_id: Annotated[int | None, Field(ge=1)] = None,
|
||||
category_id: Annotated[int | None, Field(ge=1)] = None,
|
||||
price_min: Annotated[int | None, Field(ge=0)] = None,
|
||||
price_max: Annotated[int | None, Field(ge=0)] = None,
|
||||
pages: Annotated[int, Field(ge=1, le=10)] = 1,
|
||||
limit: Annotated[int, Field(ge=1, le=200)] = 100,
|
||||
outlier_policy: OutlierPolicy = "iqr",
|
||||
histogram_bins: Annotated[int, Field(ge=2, le=50)] = 10,
|
||||
seller: Literal["any", "private", "company"] = "any",
|
||||
title_pattern: str | None = None,
|
||||
exclude_title_keywords: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Compute price statistics for a live Avito search cohort.
|
||||
|
||||
Returns count, avg, median, selected percentiles, std, IQR, MAD and a
|
||||
histogram. avg is the arithmetic mean and is sensitive to outliers;
|
||||
median, IQR and MAD are robust. Always report sample size and outlier
|
||||
policy together with the numbers. See avito://metrics for definitions.
|
||||
seller uses Avito's exact user filter: private or company.
|
||||
title_pattern/exclude_title_keywords narrow the cohort after retrieval.
|
||||
"""
|
||||
try:
|
||||
report = stats_service.stats_for_query(
|
||||
SearchQuery(
|
||||
query=query,
|
||||
location_id=location_id,
|
||||
category_id=category_id,
|
||||
price_min=price_min,
|
||||
price_max=price_max,
|
||||
extra_params=_seller_params(seller),
|
||||
title_pattern=title_pattern,
|
||||
exclude_title_keywords=exclude_title_keywords or [],
|
||||
),
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
outlier_policy=outlier_policy,
|
||||
histogram_bins=histogram_bins,
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
return {"ok": False, "error": exc.as_dict()}
|
||||
|
||||
payload = report.model_dump(mode="json", exclude_none=True)
|
||||
payload["ok"] = True
|
||||
return payload
|
||||
|
||||
@mcp.resource("avito://metrics")
|
||||
def metrics() -> str:
|
||||
"""Definitions of price statistics returned by price_stats."""
|
||||
return json.dumps(
|
||||
{
|
||||
"avg": "arithmetic mean; simple but sensitive to outliers",
|
||||
"median": "50th percentile; robust to outliers",
|
||||
"std": "sample standard deviation around avg; sensitive to outliers",
|
||||
"iqr": "interquartile range, p75 - p25; robust spread of the middle half",
|
||||
"mad": "median absolute deviation from the median; robust spread",
|
||||
"p25": "25th percentile",
|
||||
"p90": "90th percentile",
|
||||
"p95": "95th percentile",
|
||||
"p99": "99th percentile; unstable when n < 100",
|
||||
"trimmed_mean": "mean after discarding 10% of values on each side",
|
||||
"count": "number of prices used after outlier filtering",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
@mcp.resource("avito://status")
|
||||
def status() -> str:
|
||||
"""Current service and access status without secrets."""
|
||||
return json.dumps(
|
||||
{
|
||||
"name": "avito-tools",
|
||||
"version": __version__,
|
||||
"access_mode": resolved_settings.access_mode,
|
||||
"account_fallback": resolved_settings.account_fallback,
|
||||
"cookie_present": bool(resolved_settings.cookie_value),
|
||||
"modes": list(access_modes or []),
|
||||
"cache_size": len(cache),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
return mcp
|
||||
|
||||
|
||||
def _seller_params(seller: str) -> dict[str, str]:
|
||||
if seller == "private":
|
||||
return {"user": "1"}
|
||||
if seller == "company":
|
||||
return {"user": "2"}
|
||||
return {}
|
||||
|
||||
|
||||
def _row(item: ListingCard, *, include_description: bool) -> dict[str, Any]:
|
||||
row: dict[str, Any] = {
|
||||
"id": item.id,
|
||||
"title": item.title,
|
||||
"price": item.price,
|
||||
"url": item.url,
|
||||
"published_at": item.published_at.isoformat() if item.published_at else None,
|
||||
"location": item.location,
|
||||
"category_id": item.category_id,
|
||||
}
|
||||
if include_description and item.description:
|
||||
row["description"] = item.description[:1200]
|
||||
return {key: value for key, value in row.items() if value is not None}
|
||||
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
"""avito-tools API package."""
|
||||
@@ -0,0 +1,203 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from avito_tools import __version__
|
||||
from avito_tools.collector.factory import ProviderBundle, build_provider
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchQuery
|
||||
from avito_tools.errors import AvitoToolsError, BlockedError, SchemaDriftError, TransportError
|
||||
from avito_tools.services.search import SearchBatch, SearchProvider, SearchService
|
||||
from avito_tools.services.stats import PriceStatsService, StatsReport
|
||||
|
||||
|
||||
class SearchRequest(BaseModel):
|
||||
query: str = Field(min_length=1, max_length=200)
|
||||
location_id: int | None = Field(default=None, ge=1)
|
||||
category_id: int | None = Field(default=None, ge=1)
|
||||
price_min: int | None = Field(default=None, ge=0)
|
||||
price_max: int | None = Field(default=None, ge=0)
|
||||
pages: int = Field(default=1, ge=1, le=10)
|
||||
limit: int = Field(default=50, ge=1, le=200)
|
||||
|
||||
|
||||
class StatsRequest(SearchRequest):
|
||||
limit: int = Field(default=100, ge=1, le=200)
|
||||
outlier_policy: Literal["none", "iqr"] = "iqr"
|
||||
histogram_bins: int = Field(default=10, ge=2, le=50)
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
version: str
|
||||
cookie_present: bool
|
||||
|
||||
|
||||
def create_app(
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
provider: SearchProvider | None = None,
|
||||
) -> FastAPI:
|
||||
resolved_settings = settings or Settings()
|
||||
bundle: ProviderBundle | None = None
|
||||
|
||||
if provider is None:
|
||||
bundle = build_provider(resolved_settings)
|
||||
provider = bundle.provider
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
|
||||
yield
|
||||
if bundle is not None:
|
||||
bundle.close()
|
||||
|
||||
app = FastAPI(
|
||||
title="avito-tools",
|
||||
version=__version__,
|
||||
description="Avito search and analytics API",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
service = SearchService(provider)
|
||||
stats_service = PriceStatsService(service)
|
||||
app.state.settings = resolved_settings
|
||||
app.state.provider = provider
|
||||
app.state.search_service = service
|
||||
app.state.stats_service = stats_service
|
||||
|
||||
@app.get("/healthz", response_model=HealthResponse)
|
||||
def healthz() -> HealthResponse:
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
version=__version__,
|
||||
cookie_present=bool(resolved_settings.cookie_value),
|
||||
)
|
||||
|
||||
@app.get("/readyz", response_model=HealthResponse)
|
||||
def readyz() -> HealthResponse:
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
version=__version__,
|
||||
cookie_present=bool(resolved_settings.cookie_value),
|
||||
)
|
||||
|
||||
@app.post("/api/v1/search", response_model=SearchBatch)
|
||||
def search(payload: SearchRequest) -> SearchBatch:
|
||||
return _run_search(service, payload, resolved_settings)
|
||||
|
||||
@app.get("/api/v1/search", response_model=SearchBatch)
|
||||
def search_get(
|
||||
q: str = Query(min_length=1, max_length=200),
|
||||
location_id: int | None = Query(default=None, ge=1),
|
||||
category_id: int | None = Query(default=None, ge=1),
|
||||
price_min: int | None = Query(default=None, ge=0),
|
||||
price_max: int | None = Query(default=None, ge=0),
|
||||
pages: int = Query(default=1, ge=1, le=10),
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
) -> SearchBatch:
|
||||
payload = SearchRequest(
|
||||
query=q,
|
||||
location_id=location_id,
|
||||
category_id=category_id,
|
||||
price_min=price_min,
|
||||
price_max=price_max,
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
)
|
||||
return _run_search(service, payload, resolved_settings)
|
||||
|
||||
@app.post("/api/v1/stats", response_model=StatsReport)
|
||||
def stats(payload: StatsRequest) -> StatsReport:
|
||||
return _run_stats(stats_service, payload, resolved_settings)
|
||||
|
||||
@app.get("/api/v1/stats", response_model=StatsReport)
|
||||
def stats_get(
|
||||
q: str = Query(min_length=1, max_length=200),
|
||||
location_id: int | None = Query(default=None, ge=1),
|
||||
category_id: int | None = Query(default=None, ge=1),
|
||||
price_min: int | None = Query(default=None, ge=0),
|
||||
price_max: int | None = Query(default=None, ge=0),
|
||||
pages: int = Query(default=1, ge=1, le=10),
|
||||
limit: int = Query(default=100, ge=1, le=200),
|
||||
outlier_policy: Literal["none", "iqr"] = Query(default="iqr"),
|
||||
histogram_bins: int = Query(default=10, ge=2, le=50),
|
||||
) -> StatsReport:
|
||||
payload = StatsRequest(
|
||||
query=q,
|
||||
location_id=location_id,
|
||||
category_id=category_id,
|
||||
price_min=price_min,
|
||||
price_max=price_max,
|
||||
pages=pages,
|
||||
limit=limit,
|
||||
outlier_policy=outlier_policy,
|
||||
histogram_bins=histogram_bins,
|
||||
)
|
||||
return _run_stats(stats_service, payload, resolved_settings)
|
||||
|
||||
@app.exception_handler(BlockedError)
|
||||
async def blocked_handler(request: Request, exc: BlockedError) -> JSONResponse:
|
||||
return JSONResponse(status_code=503, content={"error": exc.as_dict()})
|
||||
|
||||
@app.exception_handler(SchemaDriftError)
|
||||
async def drift_handler(request: Request, exc: SchemaDriftError) -> JSONResponse:
|
||||
return JSONResponse(status_code=502, content={"error": exc.as_dict()})
|
||||
|
||||
@app.exception_handler(TransportError)
|
||||
async def transport_handler(request: Request, exc: TransportError) -> JSONResponse:
|
||||
return JSONResponse(status_code=503, content={"error": exc.as_dict()})
|
||||
|
||||
@app.exception_handler(AvitoToolsError)
|
||||
async def generic_handler(request: Request, exc: AvitoToolsError) -> JSONResponse:
|
||||
return JSONResponse(status_code=500, content={"error": exc.as_dict()})
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def _run_search(service: SearchService, payload: SearchRequest, settings: Settings) -> SearchBatch:
|
||||
query = _to_query(payload, settings)
|
||||
return service.search(query, pages=payload.pages, limit=payload.limit)
|
||||
|
||||
|
||||
def _run_stats(
|
||||
service: PriceStatsService,
|
||||
payload: StatsRequest,
|
||||
settings: Settings,
|
||||
) -> StatsReport:
|
||||
query = _to_query(payload, settings)
|
||||
return service.stats_for_query(
|
||||
query,
|
||||
pages=payload.pages,
|
||||
limit=payload.limit,
|
||||
outlier_policy=payload.outlier_policy,
|
||||
histogram_bins=payload.histogram_bins,
|
||||
)
|
||||
|
||||
|
||||
def _to_query(payload: SearchRequest, settings: Settings) -> SearchQuery:
|
||||
if (
|
||||
payload.price_min is not None
|
||||
and payload.price_max is not None
|
||||
and payload.price_min > payload.price_max
|
||||
):
|
||||
raise HTTPException(status_code=422, detail="price_min must be <= price_max")
|
||||
|
||||
return SearchQuery(
|
||||
query=payload.query,
|
||||
location_id=(
|
||||
payload.location_id if payload.location_id is not None else settings.location_id
|
||||
),
|
||||
category_id=(
|
||||
payload.category_id if payload.category_id is not None else settings.category_id
|
||||
),
|
||||
price_min=payload.price_min,
|
||||
price_max=payload.price_max,
|
||||
)
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,23 @@
|
||||
from avito_tools.non_agent.db.models import (
|
||||
Base,
|
||||
Listing,
|
||||
ListingSnapshot,
|
||||
Match,
|
||||
Notification,
|
||||
Search,
|
||||
SearchRun,
|
||||
utcnow,
|
||||
)
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"Database",
|
||||
"Listing",
|
||||
"ListingSnapshot",
|
||||
"Match",
|
||||
"Notification",
|
||||
"Search",
|
||||
"SearchRun",
|
||||
"utcnow",
|
||||
]
|
||||
@@ -0,0 +1,131 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
Boolean,
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class Search(Base):
|
||||
__tablename__ = "searches"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200), unique=True, index=True)
|
||||
query: Mapped[str] = mapped_column(String(200))
|
||||
location_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
category_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
price_min: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
price_max: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
pages: Mapped[int] = mapped_column(Integer, default=1)
|
||||
poll_interval_sec: Mapped[int] = mapped_column(Integer, default=600)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
baseline_completed: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
last_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=utcnow,
|
||||
onupdate=utcnow,
|
||||
)
|
||||
|
||||
|
||||
class Listing(Base):
|
||||
__tablename__ = "listings"
|
||||
__table_args__ = (UniqueConstraint("source", "external_id", name="uq_listing_source_external"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
source: Mapped[str] = mapped_column(String(32), default="avito")
|
||||
external_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
url: Mapped[str] = mapped_column(Text)
|
||||
title: Mapped[str] = mapped_column(Text)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
price: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
currency: Mapped[str] = mapped_column(String(8), default="RUB")
|
||||
category_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
location: Mapped[str | None] = mapped_column(String(200), nullable=True)
|
||||
seller: Mapped[str | None] = mapped_column(String(200), nullable=True)
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
first_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
last_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
status: Mapped[str] = mapped_column(String(16), default="active")
|
||||
content_hash: Mapped[str] = mapped_column(String(64), default="")
|
||||
|
||||
|
||||
class ListingSnapshot(Base):
|
||||
__tablename__ = "listing_snapshots"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
listing_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("listings.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
price: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default="active")
|
||||
|
||||
|
||||
class SearchRun(Base):
|
||||
__tablename__ = "search_runs"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
search_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("searches.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default="running")
|
||||
fetched: Mapped[int] = mapped_column(Integer, default=0)
|
||||
new_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
matched_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
error_detail: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
|
||||
|
||||
|
||||
class Match(Base):
|
||||
__tablename__ = "matches"
|
||||
__table_args__ = (UniqueConstraint("search_id", "listing_id", name="uq_match_search_listing"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
search_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("searches.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
listing_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("listings.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
first_matched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
last_matched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
score: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
reasons: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
|
||||
notified_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
connector: Mapped[str] = mapped_column(String(32), default="telegram")
|
||||
dedupe_key: Mapped[str] = mapped_column(String(200), unique=True, index=True)
|
||||
payload: Mapped[dict[str, Any]] = mapped_column(JSON)
|
||||
status: Mapped[str] = mapped_column(String(16), default="pending")
|
||||
attempts: Mapped[int] = mapped_column(Integer, default=0)
|
||||
last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.non_agent.db.models import Base
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self.settings = settings
|
||||
self._ensure_sqlite_dir()
|
||||
self.engine = create_async_engine(
|
||||
settings.database_url,
|
||||
echo=settings.database_echo,
|
||||
)
|
||||
self.session_factory = async_sessionmaker(
|
||||
self.engine,
|
||||
expire_on_commit=False,
|
||||
class_=AsyncSession,
|
||||
)
|
||||
|
||||
def _ensure_sqlite_dir(self) -> None:
|
||||
prefix = "sqlite+aiosqlite:///"
|
||||
if not self.settings.database_url.startswith(prefix):
|
||||
return
|
||||
raw_path = self.settings.database_url.removeprefix(prefix)
|
||||
if raw_path == ":memory:" or not raw_path:
|
||||
return
|
||||
Path(raw_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
async def init(self) -> None:
|
||||
async with self.engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
|
||||
def session(self) -> AsyncSession:
|
||||
return self.session_factory()
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.engine.dispose()
|
||||
|
||||
async def __aenter__(self) -> Database:
|
||||
await self.init()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args: object) -> None:
|
||||
await self.close()
|
||||
@@ -0,0 +1,13 @@
|
||||
from avito_tools.non_agent.notifiers.base import (
|
||||
Notifier,
|
||||
TelegramNotifier,
|
||||
build_notifier,
|
||||
format_telegram_message,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Notifier",
|
||||
"TelegramNotifier",
|
||||
"build_notifier",
|
||||
"format_telegram_message",
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from typing import Any, Protocol
|
||||
|
||||
import httpx
|
||||
|
||||
from avito_tools.config import Settings
|
||||
|
||||
|
||||
class Notifier(Protocol):
|
||||
async def send(self, payload: dict[str, Any]) -> None: ...
|
||||
|
||||
|
||||
class TelegramNotifier:
|
||||
def __init__(self, token: str, chat_id: str, *, timeout: float = 15.0) -> None:
|
||||
self.token = token
|
||||
self.chat_id = chat_id
|
||||
self.timeout = timeout
|
||||
|
||||
async def send(self, payload: dict[str, Any]) -> None:
|
||||
text = format_telegram_message(payload)
|
||||
url = f"https://api.telegram.org/bot{self.token}/sendMessage"
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
json={
|
||||
"chat_id": self.chat_id,
|
||||
"text": text,
|
||||
"parse_mode": "HTML",
|
||||
"disable_web_page_preview": False,
|
||||
},
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"telegram sendMessage failed: {response.status_code} {response.text[:300]}"
|
||||
)
|
||||
|
||||
|
||||
def format_telegram_message(payload: dict[str, Any]) -> str:
|
||||
event_type = payload.get("event_type", "event")
|
||||
search = payload.get("search") or {}
|
||||
listing = payload.get("listing") or {}
|
||||
title = html.escape(str(listing.get("title") or "объявление"))
|
||||
price = listing.get("price")
|
||||
price_text = f"{price:,} ₽".replace(",", " ") if isinstance(price, int) else "цена не указана"
|
||||
location = html.escape(str(listing.get("location") or ""))
|
||||
url = str(listing.get("url") or "")
|
||||
search_name = html.escape(str(search.get("name") or search.get("query") or "поиск"))
|
||||
|
||||
lines = [
|
||||
f"<b>{'Новое объявление' if event_type == 'new_match' else event_type}</b>",
|
||||
f"Поиск: {search_name}",
|
||||
f"<b>{title}</b>",
|
||||
f"{price_text}",
|
||||
]
|
||||
if location:
|
||||
lines.append(location)
|
||||
if url:
|
||||
lines.append(url)
|
||||
return "\n".join(lines)[:4000]
|
||||
|
||||
|
||||
def build_notifier(settings: Settings) -> Notifier | None:
|
||||
token = settings.telegram_bot_token.get_secret_value() if settings.telegram_bot_token else None
|
||||
chat_id = settings.telegram_chat_id
|
||||
if not token or not chat_id:
|
||||
return None
|
||||
return TelegramNotifier(token, chat_id)
|
||||
@@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from avito_tools.non_agent.db.models import Notification, utcnow
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
from avito_tools.non_agent.notifiers.base import Notifier
|
||||
|
||||
|
||||
async def dispatch_pending(
|
||||
database: Database,
|
||||
notifier: Notifier | None,
|
||||
*,
|
||||
max_attempts: int = 3,
|
||||
limit: int = 20,
|
||||
) -> int:
|
||||
if notifier is None:
|
||||
return 0
|
||||
|
||||
async with database.session() as session:
|
||||
rows = await session.scalars(
|
||||
select(Notification)
|
||||
.where(Notification.status == "pending")
|
||||
.order_by(Notification.id)
|
||||
.limit(limit)
|
||||
)
|
||||
pending = [(row.id, row.payload, row.attempts) for row in rows]
|
||||
|
||||
sent = 0
|
||||
for notification_id, payload, attempts in pending:
|
||||
error: str | None = None
|
||||
try:
|
||||
await notifier.send(payload)
|
||||
except Exception as exc:
|
||||
error = str(exc)
|
||||
|
||||
async with database.session() as session:
|
||||
notification = await session.get(Notification, notification_id)
|
||||
if notification is None:
|
||||
continue
|
||||
if error is None:
|
||||
notification.status = "sent"
|
||||
notification.sent_at = utcnow()
|
||||
notification.last_error = None
|
||||
sent += 1
|
||||
else:
|
||||
notification.attempts = attempts + 1
|
||||
notification.last_error = error[:2000]
|
||||
if notification.attempts >= max_attempts:
|
||||
notification.status = "failed"
|
||||
await session.commit()
|
||||
return sent
|
||||
Whitespace-only changes.
@@ -0,0 +1,286 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from avito_tools.domain import ListingCard, SearchQuery
|
||||
from avito_tools.errors import AvitoToolsError
|
||||
from avito_tools.non_agent.db.models import (
|
||||
Listing,
|
||||
ListingSnapshot,
|
||||
Match,
|
||||
Notification,
|
||||
Search,
|
||||
SearchRun,
|
||||
utcnow,
|
||||
)
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
from avito_tools.services.search import SearchService
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RunOutcome:
|
||||
search_id: int
|
||||
status: str
|
||||
fetched: int = 0
|
||||
new_count: int = 0
|
||||
matched_count: int = 0
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class MonitorService:
|
||||
def __init__(self, database: Database, search_service: SearchService) -> None:
|
||||
self.database = database
|
||||
self.search_service = search_service
|
||||
|
||||
async def due_searches(self, *, now: datetime | None = None) -> list[Search]:
|
||||
from avito_tools.non_agent.services.searches import SearchManager
|
||||
|
||||
async with self.database.session() as session:
|
||||
return await SearchManager(session).due(now=now)
|
||||
|
||||
async def run_search(self, search_id: int) -> RunOutcome:
|
||||
async with self.database.session() as session:
|
||||
search = await session.get(Search, search_id)
|
||||
if search is None:
|
||||
return RunOutcome(
|
||||
search_id=search_id,
|
||||
status="not_found",
|
||||
error_code="not_found",
|
||||
error_message="search not found",
|
||||
)
|
||||
query = SearchQuery(
|
||||
query=search.query,
|
||||
location_id=search.location_id,
|
||||
category_id=search.category_id,
|
||||
price_min=search.price_min,
|
||||
price_max=search.price_max,
|
||||
)
|
||||
pages = search.pages
|
||||
run = SearchRun(search_id=search.id, status="running")
|
||||
session.add(run)
|
||||
await session.commit()
|
||||
run_id = run.id
|
||||
|
||||
try:
|
||||
batch = await asyncio.to_thread(
|
||||
self.search_service.search,
|
||||
query,
|
||||
pages=pages,
|
||||
limit=100,
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
await self._finish_failed(run_id, search_id, exc.code, exc.message)
|
||||
return RunOutcome(
|
||||
search_id=search_id,
|
||||
status="failed",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
)
|
||||
except Exception as exc:
|
||||
await self._finish_failed(run_id, search_id, type(exc).__name__, str(exc))
|
||||
return RunOutcome(
|
||||
search_id=search_id,
|
||||
status="failed",
|
||||
error_code=type(exc).__name__,
|
||||
error_message=str(exc),
|
||||
)
|
||||
|
||||
async with self.database.session() as session:
|
||||
search = await session.get(Search, search_id)
|
||||
if search is None:
|
||||
return RunOutcome(search_id=search_id, status="not_found")
|
||||
run_record = await session.get(SearchRun, run_id)
|
||||
now = utcnow()
|
||||
new_count = 0
|
||||
matched_count = 0
|
||||
|
||||
for card in batch.items:
|
||||
listing, is_new = await self._upsert_listing(session, card)
|
||||
if is_new:
|
||||
new_count += 1
|
||||
created = await self._ensure_match(
|
||||
session,
|
||||
search,
|
||||
listing,
|
||||
card,
|
||||
now,
|
||||
notify=search.baseline_completed,
|
||||
)
|
||||
if created and search.baseline_completed:
|
||||
matched_count += 1
|
||||
|
||||
search.last_run_at = now
|
||||
search.baseline_completed = True
|
||||
if run_record is not None:
|
||||
run_record.finished_at = now
|
||||
run_record.status = "ok"
|
||||
run_record.fetched = len(batch.items)
|
||||
run_record.new_count = new_count
|
||||
run_record.matched_count = matched_count
|
||||
await session.commit()
|
||||
|
||||
return RunOutcome(
|
||||
search_id=search_id,
|
||||
status="ok",
|
||||
fetched=len(batch.items),
|
||||
new_count=new_count,
|
||||
matched_count=matched_count,
|
||||
)
|
||||
|
||||
async def _finish_failed(
|
||||
self,
|
||||
run_id: int,
|
||||
search_id: int,
|
||||
error_code: str,
|
||||
error_message: str,
|
||||
) -> None:
|
||||
async with self.database.session() as session:
|
||||
run = await session.get(SearchRun, run_id)
|
||||
search = await session.get(Search, search_id)
|
||||
now = utcnow()
|
||||
if run is not None:
|
||||
run.finished_at = now
|
||||
run.status = "failed"
|
||||
run.error_code = error_code
|
||||
run.error_detail = {"message": error_message}
|
||||
if search is not None:
|
||||
search.last_run_at = now
|
||||
await session.commit()
|
||||
|
||||
async def _upsert_listing(self, session, card: ListingCard) -> tuple[Listing, bool]:
|
||||
statement = select(Listing).where(
|
||||
Listing.source == "avito",
|
||||
Listing.external_id == card.id,
|
||||
)
|
||||
listing = await session.scalar(statement)
|
||||
now = utcnow()
|
||||
content_hash = _content_hash(card)
|
||||
|
||||
if listing is None:
|
||||
listing = Listing(
|
||||
source="avito",
|
||||
external_id=card.id,
|
||||
url=card.url,
|
||||
title=card.title,
|
||||
description=card.description,
|
||||
price=card.price,
|
||||
category_id=card.category_id,
|
||||
location=card.location,
|
||||
seller=card.seller,
|
||||
published_at=card.published_at,
|
||||
first_seen_at=now,
|
||||
last_seen_at=now,
|
||||
status="active",
|
||||
content_hash=content_hash,
|
||||
)
|
||||
session.add(listing)
|
||||
await session.flush()
|
||||
session.add(
|
||||
ListingSnapshot(
|
||||
listing_id=listing.id,
|
||||
observed_at=now,
|
||||
price=listing.price,
|
||||
status=listing.status,
|
||||
)
|
||||
)
|
||||
return listing, True
|
||||
|
||||
price_changed = listing.price != card.price
|
||||
listing.title = card.title
|
||||
listing.url = card.url
|
||||
listing.description = card.description or listing.description
|
||||
listing.price = card.price
|
||||
listing.category_id = card.category_id or listing.category_id
|
||||
listing.location = card.location or listing.location
|
||||
listing.seller = card.seller or listing.seller
|
||||
listing.published_at = card.published_at or listing.published_at
|
||||
listing.last_seen_at = now
|
||||
listing.status = "active"
|
||||
listing.content_hash = content_hash
|
||||
if price_changed:
|
||||
session.add(
|
||||
ListingSnapshot(
|
||||
listing_id=listing.id,
|
||||
observed_at=now,
|
||||
price=listing.price,
|
||||
status=listing.status,
|
||||
)
|
||||
)
|
||||
return listing, False
|
||||
|
||||
async def _ensure_match(
|
||||
self,
|
||||
session,
|
||||
search: Search,
|
||||
listing: Listing,
|
||||
card: ListingCard,
|
||||
now: datetime,
|
||||
*,
|
||||
notify: bool,
|
||||
) -> bool:
|
||||
statement = select(Match).where(
|
||||
Match.search_id == search.id,
|
||||
Match.listing_id == listing.id,
|
||||
)
|
||||
match = await session.scalar(statement)
|
||||
if match is not None:
|
||||
match.last_matched_at = now
|
||||
return False
|
||||
|
||||
match = Match(
|
||||
search_id=search.id,
|
||||
listing_id=listing.id,
|
||||
first_matched_at=now,
|
||||
last_matched_at=now,
|
||||
score=1.0,
|
||||
reasons={"source": "saved_search" if notify else "baseline"},
|
||||
)
|
||||
session.add(match)
|
||||
await session.flush()
|
||||
if not notify:
|
||||
return True
|
||||
|
||||
dedupe_key = f"new_match:{search.id}:{listing.id}"
|
||||
exists = await session.scalar(
|
||||
select(Notification.id).where(Notification.dedupe_key == dedupe_key)
|
||||
)
|
||||
if exists is None:
|
||||
session.add(
|
||||
Notification(
|
||||
connector="telegram",
|
||||
dedupe_key=dedupe_key,
|
||||
payload={
|
||||
"event_type": "new_match",
|
||||
"search": {
|
||||
"id": search.id,
|
||||
"name": search.name,
|
||||
"query": search.query,
|
||||
},
|
||||
"listing": {
|
||||
"id": listing.external_id,
|
||||
"title": listing.title,
|
||||
"price": listing.price,
|
||||
"url": listing.url,
|
||||
"location": listing.location,
|
||||
"published_at": (
|
||||
listing.published_at.isoformat()
|
||||
if listing.published_at
|
||||
else None
|
||||
),
|
||||
},
|
||||
},
|
||||
)
|
||||
)
|
||||
match.notified_at = now
|
||||
return True
|
||||
|
||||
|
||||
def _content_hash(card: ListingCard) -> str:
|
||||
payload = f"{card.title}|{card.price}|{card.description or ''}".encode()
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
@@ -0,0 +1,97 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from avito_tools.non_agent.db.models import Search, utcnow
|
||||
|
||||
|
||||
class SearchCreate(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
query: str = Field(min_length=1, max_length=200)
|
||||
location_id: int | None = Field(default=None, ge=1)
|
||||
category_id: int | None = Field(default=None, ge=1)
|
||||
price_min: int | None = Field(default=None, ge=0)
|
||||
price_max: int | None = Field(default=None, ge=0)
|
||||
pages: int = Field(default=1, ge=1, le=10)
|
||||
poll_interval_sec: int = Field(default=600, ge=60)
|
||||
|
||||
|
||||
def as_utc(value: datetime | None) -> datetime | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=UTC)
|
||||
return value.astimezone(UTC)
|
||||
|
||||
|
||||
class SearchManager:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self.session = session
|
||||
|
||||
async def create(self, payload: SearchCreate) -> Search:
|
||||
search = Search(
|
||||
name=payload.name,
|
||||
query=payload.query,
|
||||
location_id=payload.location_id,
|
||||
category_id=payload.category_id,
|
||||
price_min=payload.price_min,
|
||||
price_max=payload.price_max,
|
||||
pages=payload.pages,
|
||||
poll_interval_sec=payload.poll_interval_sec,
|
||||
)
|
||||
self.session.add(search)
|
||||
try:
|
||||
await self.session.commit()
|
||||
except IntegrityError as exc:
|
||||
await self.session.rollback()
|
||||
raise ValueError(f"search name already exists: {payload.name}") from exc
|
||||
await self.session.refresh(search)
|
||||
return search
|
||||
|
||||
async def list_all(self, *, enabled_only: bool = False) -> list[Search]:
|
||||
statement = select(Search).order_by(Search.id)
|
||||
if enabled_only:
|
||||
statement = statement.where(Search.enabled.is_(True))
|
||||
result = await self.session.scalars(statement)
|
||||
return list(result)
|
||||
|
||||
async def get(self, search_id: int) -> Search | None:
|
||||
return await self.session.get(Search, search_id)
|
||||
|
||||
async def set_enabled(self, search_id: int, enabled: bool) -> Search | None:
|
||||
search = await self.session.get(Search, search_id)
|
||||
if search is None:
|
||||
return None
|
||||
search.enabled = enabled
|
||||
search.updated_at = utcnow()
|
||||
await self.session.commit()
|
||||
return search
|
||||
|
||||
async def delete(self, search_id: int) -> bool:
|
||||
search = await self.session.get(Search, search_id)
|
||||
if search is None:
|
||||
return False
|
||||
await self.session.delete(search)
|
||||
await self.session.commit()
|
||||
return True
|
||||
|
||||
async def due(self, *, now: datetime | None = None) -> list[Search]:
|
||||
statement = select(Search).where(Search.enabled.is_(True)).order_by(Search.id)
|
||||
result = await self.session.scalars(statement)
|
||||
searches = list(result)
|
||||
current = now or utcnow()
|
||||
due: list[Search] = []
|
||||
for search in searches:
|
||||
last_run = as_utc(search.last_run_at)
|
||||
if last_run is None:
|
||||
due.append(search)
|
||||
continue
|
||||
elapsed = (current - last_run).total_seconds()
|
||||
if elapsed >= search.poll_interval_sec:
|
||||
due.append(search)
|
||||
return due
|
||||
@@ -0,0 +1 @@
|
||||
"""Background worker package."""
|
||||
@@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
from avito_tools.non_agent.notifiers.base import build_notifier
|
||||
from avito_tools.non_agent.notifiers.dispatch import dispatch_pending
|
||||
from avito_tools.non_agent.services.monitor import MonitorService
|
||||
from avito_tools.services.search import SearchService
|
||||
|
||||
|
||||
async def run_worker(*, once: bool = False) -> None:
|
||||
settings = Settings()
|
||||
database = Database(settings)
|
||||
await database.init()
|
||||
bundle = build_provider(settings)
|
||||
monitor = MonitorService(database, SearchService(bundle.provider))
|
||||
notifier = build_notifier(settings)
|
||||
if notifier is None:
|
||||
print(
|
||||
"warning: Telegram is not configured; notifications stay pending",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
try:
|
||||
while True:
|
||||
due = await monitor.due_searches()
|
||||
for search in due[: settings.worker_max_searches_per_cycle]:
|
||||
outcome = await monitor.run_search(search.id)
|
||||
print(
|
||||
f"search {search.id} '{search.name}': {outcome.status} "
|
||||
f"fetched={outcome.fetched} new={outcome.new_count} "
|
||||
f"matched={outcome.matched_count}"
|
||||
+ (f" error={outcome.error_code}" if outcome.error_code else ""),
|
||||
file=sys.stderr,
|
||||
)
|
||||
sent = await dispatch_pending(
|
||||
database,
|
||||
notifier,
|
||||
max_attempts=settings.notification_max_attempts,
|
||||
)
|
||||
if sent:
|
||||
print(f"notifications sent: {sent}", file=sys.stderr)
|
||||
if once:
|
||||
break
|
||||
await asyncio.sleep(settings.worker_poll_interval_sec)
|
||||
finally:
|
||||
bundle.close()
|
||||
await database.close()
|
||||
@@ -0,0 +1,182 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from curl_cffi import requests
|
||||
from curl_cffi.requests import ProxySpec
|
||||
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.config import AccessMode, Settings
|
||||
from avito_tools.domain import EgressInfo, ProbeReport, SearchQuery
|
||||
from avito_tools.errors import AvitoToolsError
|
||||
|
||||
|
||||
def fetch_egress(settings: Settings) -> EgressInfo | None:
|
||||
"""Check public IP without sending Avito cookies to a third party."""
|
||||
proxies: ProxySpec | None = None
|
||||
if settings.proxy:
|
||||
proxies = {"http": settings.proxy, "https": settings.proxy}
|
||||
try:
|
||||
response = requests.get(
|
||||
"https://ipinfo.io/json",
|
||||
timeout=8,
|
||||
proxies=proxies,
|
||||
impersonate=settings.impersonate,
|
||||
)
|
||||
payload = response.json()
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
return EgressInfo(
|
||||
ip=payload.get("ip"),
|
||||
country=payload.get("country"),
|
||||
org=payload.get("org"),
|
||||
)
|
||||
|
||||
|
||||
def run_probe(
|
||||
settings: Settings,
|
||||
*,
|
||||
query: str = "galaxy fold 8",
|
||||
save_raw: bool = False,
|
||||
mode: AccessMode | None = None,
|
||||
) -> ProbeReport:
|
||||
warnings: list[str] = []
|
||||
selected_modes = [mode] if mode else [settings.access_mode]
|
||||
if "account" in selected_modes and not settings.cookie_value:
|
||||
warnings.append("account mode selected, but AVITO_COOKIE/AVITO_COOKIE_FILE is empty")
|
||||
if "anonymous" in selected_modes:
|
||||
warnings.append("using an anonymous session bootstrap; no account cookies")
|
||||
if not settings.user_agent:
|
||||
warnings.append("AVITO_USER_AGENT is empty; using the curl_cffi impersonation profile")
|
||||
|
||||
egress = fetch_egress(settings)
|
||||
if egress and egress.country and egress.country != "RU":
|
||||
warnings.append(f"egress country is {egress.country}, expected RU")
|
||||
|
||||
try:
|
||||
bundle = build_provider(settings, mode=mode)
|
||||
except AvitoToolsError as exc:
|
||||
return ProbeReport(
|
||||
ok=False,
|
||||
egress=egress,
|
||||
cookie_present=bool(settings.cookie_value),
|
||||
warnings=warnings,
|
||||
error=exc.as_dict(),
|
||||
query=query,
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
try:
|
||||
page = bundle.provider.search(
|
||||
SearchQuery(
|
||||
query=query,
|
||||
location_id=settings.location_id,
|
||||
category_id=settings.category_id,
|
||||
)
|
||||
)
|
||||
except AvitoToolsError as exc:
|
||||
return ProbeReport(
|
||||
ok=False,
|
||||
egress=egress,
|
||||
cookie_present=bool(settings.cookie_value),
|
||||
http_status=_status_from_error(exc),
|
||||
warnings=warnings,
|
||||
error=exc.as_dict(),
|
||||
latency_ms=int((time.monotonic() - started) * 1000),
|
||||
query=query,
|
||||
access_mode=",".join(bundle.modes),
|
||||
)
|
||||
finally:
|
||||
bundle.close()
|
||||
|
||||
latency_ms = int((time.monotonic() - started) * 1000)
|
||||
if page.total == 0:
|
||||
warnings.append("search returned 0 results; verify the query and location")
|
||||
|
||||
last_response = bundle.last_response
|
||||
if save_raw and last_response is not None:
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
|
||||
path = settings.data_dir / f"probe-{stamp}.json"
|
||||
path.write_text(last_response.text, encoding="utf-8")
|
||||
warnings.append(f"raw response saved to {path}")
|
||||
|
||||
return ProbeReport(
|
||||
ok=True,
|
||||
egress=egress,
|
||||
cookie_present=bool(settings.cookie_value),
|
||||
http_status=last_response.status_code if last_response else None,
|
||||
total=page.total,
|
||||
items_count=len(page.items),
|
||||
sample=[item.model_dump(mode="json", exclude_none=True) for item in page.items[:5]],
|
||||
warnings=warnings + page.warnings,
|
||||
latency_ms=latency_ms,
|
||||
query=query,
|
||||
access_mode=page.access_mode or ",".join(bundle.modes),
|
||||
)
|
||||
|
||||
|
||||
def _status_from_error(exc: AvitoToolsError) -> int | None:
|
||||
status = exc.detail.get("status_code")
|
||||
return status if isinstance(status, int) else None
|
||||
|
||||
|
||||
def report_as_json(report: ProbeReport) -> str:
|
||||
return json.dumps(report.to_dict(), ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def format_report(report: ProbeReport) -> str:
|
||||
lines: list[str] = []
|
||||
lines.append(f"probe: {'OK' if report.ok else 'FAILED'}")
|
||||
if report.egress:
|
||||
lines.append(
|
||||
"egress: "
|
||||
f"{report.egress.ip or '?'} "
|
||||
f"({report.egress.country or '?'}, {report.egress.org or '?'})"
|
||||
)
|
||||
lines.append(f"cookie: {'present' if report.cookie_present else 'missing'}")
|
||||
lines.append(f"access: {report.access_mode or '?'}")
|
||||
lines.append(f"query: {report.query}")
|
||||
lines.append(
|
||||
f"http: {report.http_status if report.http_status is not None else '-'}"
|
||||
f" | items: {report.items_count}"
|
||||
f" | total: {report.total if report.total is not None else '?'}"
|
||||
f" | {report.latency_ms if report.latency_ms is not None else '?'} ms"
|
||||
)
|
||||
if report.sample:
|
||||
lines.append("sample:")
|
||||
for item in report.sample:
|
||||
price = item.get("price")
|
||||
lines.append(
|
||||
f" {item.get('id')} | {price if price is not None else '?'} | "
|
||||
f"{item.get('title')} | {item.get('url')}"
|
||||
)
|
||||
if report.warnings:
|
||||
lines.append("warnings:")
|
||||
lines.extend(f" - {warning}" for warning in report.warnings)
|
||||
if report.error:
|
||||
lines.append("error:")
|
||||
lines.append(f" code: {report.error.get('code')}")
|
||||
lines.append(f" message: {report.error.get('message')}")
|
||||
detail = report.error.get("detail") or {}
|
||||
if detail.get("errors"):
|
||||
for error in detail["errors"]:
|
||||
lines.append(f" - {error}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def exit_code_for_report(report: ProbeReport) -> int:
|
||||
if report.ok:
|
||||
return 0
|
||||
code = (report.error or {}).get("code")
|
||||
if code == "blocked":
|
||||
return 2
|
||||
if code == "schema_drift":
|
||||
return 3
|
||||
if code in {"config_error", "transport_error"}:
|
||||
return 4
|
||||
return 1
|
||||
@@ -0,0 +1,3 @@
|
||||
from avito_tools.services.search import SearchBatch, SearchService
|
||||
|
||||
__all__ = ["SearchBatch", "SearchService"]
|
||||
@@ -0,0 +1,106 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Protocol
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from avito_tools.domain import ListingCard, SearchPage, SearchQuery
|
||||
|
||||
|
||||
class SearchProvider(Protocol):
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage: ...
|
||||
|
||||
|
||||
class SearchBatch(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
query: str
|
||||
total: int | None = None
|
||||
items: list[ListingCard] = Field(default_factory=list)
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
pages_fetched: int = 0
|
||||
has_more: bool = False
|
||||
access_mode: str | None = None
|
||||
fetched_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return self.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
class SearchService:
|
||||
"""Multi-page search with deduplication, independent of transport and HTTP layer."""
|
||||
|
||||
def __init__(self, provider: SearchProvider) -> None:
|
||||
self.provider = provider
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: SearchQuery,
|
||||
*,
|
||||
pages: int = 1,
|
||||
limit: int = 50,
|
||||
) -> SearchBatch:
|
||||
if pages < 1:
|
||||
raise ValueError("pages must be >= 1")
|
||||
if limit < 1:
|
||||
raise ValueError("limit must be >= 1")
|
||||
|
||||
items: list[ListingCard] = []
|
||||
seen: set[str] = set()
|
||||
warnings: list[str] = []
|
||||
total: int | None = None
|
||||
pages_fetched = 0
|
||||
has_more = False
|
||||
access_mode: str | None = None
|
||||
matcher = _title_matcher(query)
|
||||
|
||||
for page_number in range(1, pages + 1):
|
||||
page = self.provider.search(query, page=page_number)
|
||||
pages_fetched = page_number
|
||||
if access_mode is None:
|
||||
access_mode = page.access_mode
|
||||
if total is None:
|
||||
total = page.total
|
||||
warnings.extend(page.warnings)
|
||||
for item in page.items:
|
||||
if not matcher(item):
|
||||
continue
|
||||
if item.id in seen:
|
||||
continue
|
||||
seen.add(item.id)
|
||||
items.append(item)
|
||||
if len(items) >= limit:
|
||||
break
|
||||
has_more = page.has_next and len(items) < limit
|
||||
if not page.has_next or len(items) >= limit:
|
||||
break
|
||||
|
||||
return SearchBatch(
|
||||
query=query.query,
|
||||
total=total,
|
||||
items=items,
|
||||
warnings=warnings,
|
||||
pages_fetched=pages_fetched,
|
||||
has_more=has_more,
|
||||
access_mode=access_mode,
|
||||
)
|
||||
|
||||
|
||||
def _title_matcher(query: SearchQuery):
|
||||
pattern = None
|
||||
if query.title_pattern:
|
||||
try:
|
||||
pattern = re.compile(query.title_pattern, re.IGNORECASE)
|
||||
except re.error as exc:
|
||||
raise ValueError(f"invalid title_pattern: {exc}") from exc
|
||||
excluded = [keyword.casefold() for keyword in query.exclude_title_keywords if keyword]
|
||||
|
||||
def matches(item: ListingCard) -> bool:
|
||||
title = item.title.casefold()
|
||||
if pattern is not None and pattern.search(item.title) is None:
|
||||
return False
|
||||
return not any(keyword in title for keyword in excluded)
|
||||
|
||||
return matches
|
||||
@@ -0,0 +1,51 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from avito_tools.analytics.stats import OutlierPolicy, PriceStats, compute_price_stats
|
||||
from avito_tools.domain import SearchQuery
|
||||
from avito_tools.services.search import SearchService
|
||||
|
||||
|
||||
class StatsReport(BaseModel):
|
||||
query: str
|
||||
total: int | None = None
|
||||
fetched: int = 0
|
||||
pages_fetched: int = 0
|
||||
access_mode: str | None = None
|
||||
stats: PriceStats
|
||||
warnings: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PriceStatsService:
|
||||
"""Collect a cohort with the search service and compute descriptive price stats."""
|
||||
|
||||
def __init__(self, search_service: SearchService) -> None:
|
||||
self.search_service = search_service
|
||||
|
||||
def stats_for_query(
|
||||
self,
|
||||
query: SearchQuery,
|
||||
*,
|
||||
pages: int = 1,
|
||||
limit: int = 100,
|
||||
outlier_policy: OutlierPolicy = "iqr",
|
||||
histogram_bins: int = 10,
|
||||
) -> StatsReport:
|
||||
batch = self.search_service.search(query, pages=pages, limit=limit)
|
||||
prices = [item.price for item in batch.items if item.price is not None]
|
||||
stats = compute_price_stats(
|
||||
prices,
|
||||
outlier_policy=outlier_policy,
|
||||
histogram_bins=histogram_bins,
|
||||
)
|
||||
warnings = list(dict.fromkeys(batch.warnings + stats.warnings))
|
||||
return StatsReport(
|
||||
query=query.query,
|
||||
total=batch.total,
|
||||
fetched=len(batch.items),
|
||||
pages_fetched=batch.pages_fetched,
|
||||
access_mode=batch.access_mode,
|
||||
stats=stats,
|
||||
warnings=warnings,
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""Tests package."""
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta name="description" content="Samsung Galaxy Z Fold 6: 2 объявления в Москве">
|
||||
<title>Тестовая выдача</title>
|
||||
</head>
|
||||
<body>
|
||||
<div data-marker="item" data-item-id="111" class="item">
|
||||
<a data-marker="item-title" href="/moskva/telefony/samsung_111">Samsung Galaxy Z Fold6, 12/512 ГБ</a>
|
||||
<p data-marker="item-price" itemProp="offers" itemscope itemType="http://schema.org/Offer">
|
||||
<meta itemProp="price" content="45000">
|
||||
<span>45 000 ₽</span>
|
||||
</p>
|
||||
<p class="description" style="--module-max-lines-size:4">Продаю свой Fold6. Не работает блютуз.</p>
|
||||
<a href="/user/abc">Профиль</a>
|
||||
</div>
|
||||
<div data-marker="item" data-item-id="222" class="item">
|
||||
<a data-marker="item-title" href="/moskva/telefony/samsung_222">Samsung Galaxy Z Fold6, 12/256 ГБ</a>
|
||||
<p data-marker="item-price" itemProp="offers" itemscope itemType="http://schema.org/Offer">
|
||||
<meta itemProp="price" content="50000">
|
||||
<span>50 000 ₽</span>
|
||||
</p>
|
||||
<p class="description" style="--module-max-lines-size:4">Идеальное состояние, все работает.</p>
|
||||
<a href="/brands/shop">Магазин</a>
|
||||
</div>
|
||||
<div data-marker="item" data-item-id="111" class="item duplicate">
|
||||
<a data-marker="item-title" href="/moskva/telefony/samsung_111">Дубль</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"count": 2,
|
||||
"totalCount": 2,
|
||||
"itemsOnPage": 2,
|
||||
"catalog": {
|
||||
"items": [
|
||||
{
|
||||
"id": 8384570411,
|
||||
"categoryId": 84,
|
||||
"urlPath": "/moskva/telefony/iphone_15_128_gb_8384570411?context=test",
|
||||
"title": "iPhone 15, 128 ГБ, SIM + eSIM",
|
||||
"description": "Новый, запечатанный. Bluetooth работает.",
|
||||
"sortTimeStamp": 1788867405000,
|
||||
"priceDetailed": { "value": 52800, "fullString": "52 800 ₽" },
|
||||
"addressDetailed": { "locationName": "Москва" },
|
||||
"category": { "id": 84, "name": "Телефоны" },
|
||||
"images": [{ "318x318": "https://img.avito.st/image-1.jpg" }]
|
||||
},
|
||||
{
|
||||
"id": 8285067255,
|
||||
"urlPath": "/moskva/telefony/iphone_15_128_gb_8285067255",
|
||||
"title": "iPhone 15, 128 ГБ",
|
||||
"description": "Без Bluetooth.",
|
||||
"sortTimeStamp": 1788867400000,
|
||||
"priceDetailed": { "value": 30990 },
|
||||
"addressDetailed": { "locationName": "Химки" },
|
||||
"categoryId": 84,
|
||||
"images": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"totalCount": 3,
|
||||
"items": [
|
||||
{
|
||||
"id": 1234567890,
|
||||
"title": "iPhone 15 Pro 256 ГБ, идеальное состояние",
|
||||
"priceDetailed": { "value": 74990 },
|
||||
"urlPath": "/moskva/telefony/mobilnye_telefony/apple-iphone_15_pro-256gb_1234567890",
|
||||
"sortTimeStamp": 1761800000000,
|
||||
"location": { "name": "Москва" },
|
||||
"seller": { "name": "Иван", "isCompany": false },
|
||||
"images": [{ "640x480": "https://img.avito.st/image-1.jpg" }],
|
||||
"categoryId": 5158
|
||||
},
|
||||
{
|
||||
"id": "1234567891",
|
||||
"title": "iPhone 15 Pro 128 ГБ",
|
||||
"price": "69 000 ₽",
|
||||
"urlPath": "/moskva/telefony/mobilnye_telefony/apple-iphone_15_pro-128gb_1234567891",
|
||||
"sortTimeStamp": 1761700000,
|
||||
"location": "Москва",
|
||||
"seller": "Мария",
|
||||
"images": ["https://img.avito.st/image-2.jpg"],
|
||||
"categoryId": 5158
|
||||
},
|
||||
{
|
||||
"id": "1234567892",
|
||||
"title": "iPhone 15 Pro на запчасти",
|
||||
"priceDetailed": { "value": 0 },
|
||||
"urlPath": "/moskva/telefony/mobilnye_telefony/apple-iphone_15_pro-zapchasti_1234567892",
|
||||
"sortTimeStamp": 1761600000000,
|
||||
"location": { "name": "Химки" },
|
||||
"seller": { "name": "Сервис", "isCompany": true },
|
||||
"images": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def expect(condition: object, message: str = "expectation failed") -> None:
|
||||
"""Small test helper for explicit checks."""
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
@@ -0,0 +1,85 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage
|
||||
from avito_tools.errors import BlockedError
|
||||
from avito_tools.non_agent.api.app import create_app
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def __init__(self) -> None:
|
||||
self.error: Exception | None = None
|
||||
|
||||
def search(self, query, *, page: int = 1) -> SearchPage:
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=1,
|
||||
items=[
|
||||
ListingCard(
|
||||
id="123",
|
||||
title="iPhone 15 Pro",
|
||||
price=75000,
|
||||
url="https://www.avito.ru/moskva/telefony/iphone_15_pro_123",
|
||||
)
|
||||
],
|
||||
has_next=False,
|
||||
)
|
||||
|
||||
|
||||
def make_client(provider: FakeProvider) -> TestClient:
|
||||
app = create_app(settings=Settings(_env_file=None), provider=provider)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_health() -> None:
|
||||
with make_client(FakeProvider()) as client:
|
||||
response = client.get("/healthz")
|
||||
expect(response.status_code == 200)
|
||||
expect(response.json()["status"] == "ok")
|
||||
|
||||
|
||||
def test_search_post() -> None:
|
||||
with make_client(FakeProvider()) as client:
|
||||
response = client.post("/api/v1/search", json={"query": "iphone 15"})
|
||||
expect(response.status_code == 200)
|
||||
payload = response.json()
|
||||
expect(payload["query"] == "iphone 15")
|
||||
expect(len(payload["items"]) == 1)
|
||||
expect(payload["items"][0]["price"] == 75000)
|
||||
|
||||
|
||||
def test_search_get() -> None:
|
||||
with make_client(FakeProvider()) as client:
|
||||
response = client.get("/api/v1/search", params={"q": "iphone 15"})
|
||||
expect(response.status_code == 200)
|
||||
expect(response.json()["items"][0]["id"] == "123")
|
||||
|
||||
|
||||
def test_search_blocked_maps_to_503() -> None:
|
||||
provider = FakeProvider()
|
||||
provider.error = BlockedError("blocked", status_code=429)
|
||||
with make_client(provider) as client:
|
||||
response = client.post("/api/v1/search", json={"query": "iphone 15"})
|
||||
expect(response.status_code == 503)
|
||||
expect(response.json()["error"]["code"] == "blocked")
|
||||
|
||||
|
||||
def test_search_validates_pages() -> None:
|
||||
with make_client(FakeProvider()) as client:
|
||||
response = client.post("/api/v1/search", json={"query": "iphone 15", "pages": 0})
|
||||
expect(response.status_code == 422)
|
||||
|
||||
|
||||
def test_search_validates_price_range() -> None:
|
||||
with make_client(FakeProvider()) as client:
|
||||
response = client.post(
|
||||
"/api/v1/search",
|
||||
json={"query": "iphone 15", "price_min": 100, "price_max": 50},
|
||||
)
|
||||
expect(response.status_code == 422)
|
||||
@@ -0,0 +1,250 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage
|
||||
from avito_tools.errors import BlockedError
|
||||
from avito_tools.non_agent.db.models import Listing, ListingSnapshot, Match, Notification, SearchRun
|
||||
from avito_tools.non_agent.db.session import Database
|
||||
from avito_tools.non_agent.notifiers.dispatch import dispatch_pending
|
||||
from avito_tools.non_agent.services.monitor import MonitorService
|
||||
from avito_tools.non_agent.services.searches import SearchCreate, SearchManager
|
||||
from avito_tools.services.search import SearchService
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
class SequenceProvider:
|
||||
def __init__(self) -> None:
|
||||
self.pages: list[SearchPage] = []
|
||||
self.error: Exception | None = None
|
||||
|
||||
def search(self, query, *, page: int = 1) -> SearchPage:
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
index = min(len(self.pages) - 1, 0)
|
||||
return self.pages.pop(index) if self.pages else SearchPage(query=query.query, page=page)
|
||||
|
||||
|
||||
class FakeNotifier:
|
||||
def __init__(self, *, fail: bool = False) -> None:
|
||||
self.fail = fail
|
||||
self.sent: list[dict] = []
|
||||
|
||||
async def send(self, payload: dict) -> None:
|
||||
if self.fail:
|
||||
raise RuntimeError("telegram down")
|
||||
self.sent.append(payload)
|
||||
|
||||
|
||||
def card(item_id: str, price: int, title: str = "iPhone 15") -> ListingCard:
|
||||
return ListingCard(
|
||||
id=item_id,
|
||||
title=title,
|
||||
description="test description",
|
||||
price=price,
|
||||
url=f"https://www.avito.ru/moskva/telefony/{item_id}",
|
||||
location="Москва",
|
||||
)
|
||||
|
||||
|
||||
def page(items: list[ListingCard]) -> SearchPage:
|
||||
return SearchPage(
|
||||
query="iphone 15",
|
||||
page=1,
|
||||
total=len(items),
|
||||
items=items,
|
||||
has_next=False,
|
||||
access_mode="test",
|
||||
)
|
||||
|
||||
|
||||
def make_settings(tmp_path) -> Settings:
|
||||
return Settings(
|
||||
_env_file=None,
|
||||
database_url=f"sqlite+aiosqlite:///{tmp_path}/test.db",
|
||||
)
|
||||
|
||||
|
||||
def test_baseline_then_new_listing(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
search = await SearchManager(session).create(
|
||||
SearchCreate(name="test", query="iphone 15", poll_interval_sec=600)
|
||||
)
|
||||
|
||||
provider.pages = [page([card("1", 100000)])]
|
||||
first = await monitor.run_search(search.id)
|
||||
expect(first.status == "ok")
|
||||
expect(first.new_count == 1)
|
||||
expect(first.matched_count == 0)
|
||||
|
||||
async with database.session() as session:
|
||||
expect(await session.scalar(select(func.count(Notification.id))) == 0)
|
||||
expect(await session.scalar(select(func.count(Match.id))) == 1)
|
||||
reloaded = await SearchManager(session).get(search.id)
|
||||
expect(reloaded is not None and reloaded.baseline_completed)
|
||||
|
||||
provider.pages = [page([card("1", 100000), card("2", 90000)])]
|
||||
second = await monitor.run_search(search.id)
|
||||
expect(second.status == "ok")
|
||||
expect(second.new_count == 1)
|
||||
expect(second.matched_count == 1)
|
||||
|
||||
async with database.session() as session:
|
||||
expect(await session.scalar(select(func.count(Match.id))) == 2)
|
||||
expect(await session.scalar(select(func.count(Notification.id))) == 1)
|
||||
expect(await session.scalar(select(func.count(SearchRun.id))) == 2)
|
||||
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_price_change_adds_snapshot(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
search = await SearchManager(session).create(
|
||||
SearchCreate(name="price", query="iphone 15")
|
||||
)
|
||||
|
||||
provider.pages = [page([card("1", 100000)])]
|
||||
await monitor.run_search(search.id)
|
||||
provider.pages = [page([card("1", 95000)])]
|
||||
await monitor.run_search(search.id)
|
||||
|
||||
async with database.session() as session:
|
||||
listing = await session.scalar(select(Listing).where(Listing.external_id == "1"))
|
||||
expect(listing is not None and listing.price == 95000)
|
||||
snapshots = await session.scalar(
|
||||
select(func.count(ListingSnapshot.id)).where(
|
||||
ListingSnapshot.listing_id == listing.id
|
||||
)
|
||||
)
|
||||
expect(snapshots == 2)
|
||||
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_failed_run_is_recorded(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
search = await SearchManager(session).create(
|
||||
SearchCreate(name="fail", query="iphone 15")
|
||||
)
|
||||
|
||||
provider.error = BlockedError("blocked", status_code=429)
|
||||
outcome = await monitor.run_search(search.id)
|
||||
expect(outcome.status == "failed")
|
||||
expect(outcome.error_code == "blocked")
|
||||
|
||||
async with database.session() as session:
|
||||
run = await session.scalar(select(SearchRun))
|
||||
expect(run is not None and run.status == "failed")
|
||||
reloaded = await SearchManager(session).get(search.id)
|
||||
expect(reloaded is not None and reloaded.last_run_at is not None)
|
||||
expect(not reloaded.baseline_completed)
|
||||
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_due_searches_respect_interval(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
provider.pages = [page([card("1", 100000)])]
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
search = await SearchManager(session).create(
|
||||
SearchCreate(name="due", query="iphone 15", poll_interval_sec=600)
|
||||
)
|
||||
expect(len(await SearchManager(session).due()) == 1)
|
||||
|
||||
await monitor.run_search(search.id)
|
||||
expect(len(await monitor.due_searches()) == 0)
|
||||
expect(
|
||||
len(await monitor.due_searches(now=monitor_now() + timedelta(seconds=601))) == 1
|
||||
)
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def monitor_now():
|
||||
from avito_tools.non_agent.db.models import utcnow
|
||||
|
||||
return utcnow()
|
||||
|
||||
|
||||
def test_dispatch_marks_sent(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
search = await SearchManager(session).create(
|
||||
SearchCreate(name="notify", query="iphone 15")
|
||||
)
|
||||
provider.pages = [page([card("1", 100000)])]
|
||||
await monitor.run_search(search.id)
|
||||
provider.pages = [page([card("2", 90000)])]
|
||||
await monitor.run_search(search.id)
|
||||
|
||||
notifier = FakeNotifier()
|
||||
sent = await dispatch_pending(database, notifier)
|
||||
expect(sent == 1)
|
||||
expect(len(notifier.sent) == 1)
|
||||
async with database.session() as session:
|
||||
notification = await session.scalar(select(Notification))
|
||||
expect(notification is not None and notification.status == "sent")
|
||||
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_dispatch_retries_and_fails(tmp_path) -> None:
|
||||
async def run() -> None:
|
||||
database = Database(make_settings(tmp_path))
|
||||
await database.init()
|
||||
provider = SequenceProvider()
|
||||
monitor = MonitorService(database, SearchService(provider))
|
||||
async with database.session() as session:
|
||||
await SearchManager(session).create(SearchCreate(name="retry", query="iphone 15"))
|
||||
provider.pages = [page([card("1", 100000)])]
|
||||
await monitor.run_search(1)
|
||||
provider.pages = [page([card("2", 90000)])]
|
||||
await monitor.run_search(1)
|
||||
|
||||
notifier = FakeNotifier(fail=True)
|
||||
expect(await dispatch_pending(database, notifier, max_attempts=2) == 0)
|
||||
expect(await dispatch_pending(database, notifier, max_attempts=2) == 0)
|
||||
async with database.session() as session:
|
||||
notification = await session.scalar(select(Notification))
|
||||
expect(notification is not None and notification.status == "failed")
|
||||
expect(notification.attempts == 2)
|
||||
|
||||
await database.close()
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,42 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.non_agent.notifiers.base import (
|
||||
TelegramNotifier,
|
||||
build_notifier,
|
||||
format_telegram_message,
|
||||
)
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def test_format_message() -> None:
|
||||
text = format_telegram_message(
|
||||
{
|
||||
"event_type": "new_match",
|
||||
"search": {"name": "iPhone <15>"},
|
||||
"listing": {
|
||||
"title": "iPhone 15 & case",
|
||||
"price": 52800,
|
||||
"location": "Москва",
|
||||
"url": "https://www.avito.ru/item",
|
||||
},
|
||||
}
|
||||
)
|
||||
expect("iPhone <15>" in text)
|
||||
expect("iPhone 15 & case" in text)
|
||||
expect("52 800 ₽" in text)
|
||||
expect("https://www.avito.ru/item" in text)
|
||||
|
||||
|
||||
def test_build_notifier_requires_config() -> None:
|
||||
expect(build_notifier(Settings(_env_file=None)) is None)
|
||||
|
||||
|
||||
def test_build_notifier_with_config() -> None:
|
||||
settings = Settings(
|
||||
_env_file=None,
|
||||
telegram_bot_token="token",
|
||||
telegram_chat_id="123",
|
||||
)
|
||||
notifier = build_notifier(settings)
|
||||
expect(isinstance(notifier, TelegramNotifier))
|
||||
@@ -0,0 +1,188 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from avito_tools.collector.fallback import FallbackSearchProvider
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.collector.web import WebSearchProvider
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchPage, SearchQuery
|
||||
from avito_tools.errors import BlockedError, TransportError
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def make_response(status: int = 200, text: str = "ok") -> HttpResponse:
|
||||
return HttpResponse(
|
||||
status_code=status,
|
||||
content_type="text/html",
|
||||
text=text,
|
||||
elapsed_ms=1,
|
||||
url="https://www.avito.ru/",
|
||||
)
|
||||
|
||||
|
||||
def make_settings() -> Settings:
|
||||
return Settings(_env_file=None)
|
||||
|
||||
|
||||
def payload() -> str:
|
||||
return (
|
||||
'{"totalCount":1,"items":[{"id":1,"title":"iPhone",'
|
||||
'"urlPath":"/moskva/iphone_1","priceDetailed":{"value":100}}]}'
|
||||
)
|
||||
|
||||
|
||||
class BootstrapClient:
|
||||
def __init__(self, bootstrap_status: int = 200, search_status: int = 200) -> None:
|
||||
self.bootstrap_calls = 0
|
||||
self.search_calls = 0
|
||||
self.bootstrap_status = bootstrap_status
|
||||
self.search_status = search_status
|
||||
|
||||
def ensure_bootstrap(self) -> HttpResponse:
|
||||
self.bootstrap_calls += 1
|
||||
return make_response(self.bootstrap_status)
|
||||
|
||||
def get(self, url: str, **kwargs: Any) -> HttpResponse:
|
||||
self.search_calls += 1
|
||||
return HttpResponse(
|
||||
status_code=self.search_status,
|
||||
content_type="application/json",
|
||||
text=payload(),
|
||||
elapsed_ms=1,
|
||||
url=url,
|
||||
)
|
||||
|
||||
|
||||
def test_anonymous_bootstrap_runs_once() -> None:
|
||||
client = BootstrapClient()
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=True) # type: ignore[arg-type]
|
||||
|
||||
provider.search(SearchQuery(query="iphone"))
|
||||
provider.search(SearchQuery(query="iphone"))
|
||||
|
||||
expect(client.bootstrap_calls == 1)
|
||||
expect(client.search_calls == 2)
|
||||
|
||||
|
||||
def test_bootstrap_block_stops_search() -> None:
|
||||
client = BootstrapClient(bootstrap_status=429)
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=True) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(BlockedError):
|
||||
provider.search(SearchQuery(query="iphone"))
|
||||
|
||||
expect(client.search_calls == 0)
|
||||
|
||||
|
||||
def test_account_mode_skips_bootstrap() -> None:
|
||||
client = BootstrapClient()
|
||||
provider = WebSearchProvider(
|
||||
client,
|
||||
make_settings(),
|
||||
access_mode="account",
|
||||
bootstrap=True,
|
||||
) # type: ignore[arg-type]
|
||||
|
||||
provider.search(SearchQuery(query="iphone"))
|
||||
|
||||
expect(client.bootstrap_calls == 0)
|
||||
|
||||
|
||||
class StubProvider:
|
||||
def __init__(self, *, error: Exception | None = None, mode: str = "anonymous") -> None:
|
||||
self.error = error
|
||||
self.last_response = make_response()
|
||||
self.mode = mode
|
||||
|
||||
def search(self, query: SearchQuery, *, page: int = 1) -> SearchPage:
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=1,
|
||||
items=[],
|
||||
access_mode=self.mode,
|
||||
)
|
||||
|
||||
|
||||
def test_fallback_uses_next_mode_on_block() -> None:
|
||||
fallback = FallbackSearchProvider(
|
||||
[
|
||||
("anonymous", StubProvider(error=BlockedError("blocked", status_code=429))), # type: ignore[list-item]
|
||||
("account", StubProvider(mode="account")), # type: ignore[list-item]
|
||||
]
|
||||
)
|
||||
|
||||
page = fallback.search(SearchQuery(query="iphone"))
|
||||
|
||||
expect(page.access_mode == "account")
|
||||
|
||||
|
||||
def test_fallback_does_not_hide_transport_errors() -> None:
|
||||
fallback = FallbackSearchProvider(
|
||||
[
|
||||
("anonymous", StubProvider(error=TransportError("network"))), # type: ignore[list-item]
|
||||
("account", StubProvider(mode="account")), # type: ignore[list-item]
|
||||
]
|
||||
)
|
||||
|
||||
page = fallback.search(SearchQuery(query="iphone"))
|
||||
|
||||
expect(page.access_mode == "account")
|
||||
|
||||
|
||||
def test_fallback_reports_all_attempts() -> None:
|
||||
fallback = FallbackSearchProvider(
|
||||
[
|
||||
("anonymous", StubProvider(error=BlockedError("blocked", status_code=429))), # type: ignore[list-item]
|
||||
("account", StubProvider(error=BlockedError("blocked", status_code=403))), # type: ignore[list-item]
|
||||
]
|
||||
)
|
||||
|
||||
with pytest.raises(BlockedError) as exc_info:
|
||||
fallback.search(SearchQuery(query="iphone"))
|
||||
|
||||
attempts = exc_info.value.detail["attempts"]
|
||||
expect(len(attempts) == 2)
|
||||
expect(attempts[0]["mode"] == "anonymous")
|
||||
expect(attempts[1]["mode"] == "account")
|
||||
|
||||
|
||||
def test_factory_can_select_html_provider() -> None:
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.collector.html import HtmlSearchProvider
|
||||
from avito_tools.config import Settings
|
||||
|
||||
settings = Settings(
|
||||
_env_file=None,
|
||||
access_mode="account",
|
||||
search_provider="html",
|
||||
cookie="a=1",
|
||||
)
|
||||
bundle = build_provider(settings)
|
||||
try:
|
||||
expect(isinstance(bundle.provider, HtmlSearchProvider))
|
||||
finally:
|
||||
bundle.close()
|
||||
|
||||
|
||||
def test_factory_auto_builds_fallback() -> None:
|
||||
from avito_tools.collector.factory import build_provider
|
||||
from avito_tools.collector.fallback import FallbackSearchProvider
|
||||
from avito_tools.config import Settings
|
||||
|
||||
settings = Settings(
|
||||
_env_file=None,
|
||||
access_mode="account",
|
||||
search_provider="auto",
|
||||
cookie="a=1",
|
||||
)
|
||||
bundle = build_provider(settings)
|
||||
try:
|
||||
expect(isinstance(bundle.provider, FallbackSearchProvider))
|
||||
finally:
|
||||
bundle.close()
|
||||
@@ -0,0 +1,108 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from avito_tools.collector.browser import BrowserSearchProvider
|
||||
from avito_tools.collector.html import build_search_url
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchQuery
|
||||
from avito_tools.errors import BlockedError
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
class FakeController:
|
||||
def __init__(self, html: str) -> None:
|
||||
self.html = html
|
||||
self.urls: list[str] = []
|
||||
self.closed = False
|
||||
|
||||
async def fetch_html(self, url: str, *, timeout: float = 30.0) -> str:
|
||||
self.urls.append(url)
|
||||
return self.html
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
def load_html() -> str:
|
||||
return (Path(__file__).parent / "fixtures" / "search_page.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def make_settings() -> Settings:
|
||||
return Settings(_env_file=None)
|
||||
|
||||
|
||||
def test_build_search_url() -> None:
|
||||
url = build_search_url(
|
||||
make_settings(),
|
||||
SearchQuery(query="galaxy fold 8", extra_params={"user": "1"}),
|
||||
2,
|
||||
)
|
||||
expect(url.startswith("https://www.avito.ru/moskva/telefony?"))
|
||||
expect("p=2" in url)
|
||||
expect("user=1" in url)
|
||||
|
||||
|
||||
def test_browser_provider_parses_html() -> None:
|
||||
controller = FakeController(load_html())
|
||||
provider = BrowserSearchProvider(controller, make_settings()) # type: ignore[arg-type]
|
||||
|
||||
page = provider.search(SearchQuery(query="galaxy fold 8"), page=1)
|
||||
|
||||
expect(page.total == 2)
|
||||
expect(len(page.items) == 2)
|
||||
expect(controller.urls[0].startswith("https://www.avito.ru/moskva/telefony?"))
|
||||
expect(provider.last_response is not None)
|
||||
|
||||
|
||||
def test_browser_provider_blocked() -> None:
|
||||
controller = FakeController("<html><body>Доступ ограничен: проблема с IP</body></html>")
|
||||
provider = BrowserSearchProvider(controller, make_settings()) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(BlockedError):
|
||||
provider.search(SearchQuery(query="galaxy fold 8"))
|
||||
|
||||
|
||||
def test_factory_browser_provider() -> None:
|
||||
from avito_tools.collector.factory import build_provider
|
||||
|
||||
settings = Settings(
|
||||
_env_file=None,
|
||||
search_provider="browser",
|
||||
access_mode="account",
|
||||
)
|
||||
bundle = build_provider(settings)
|
||||
try:
|
||||
expect(isinstance(bundle.provider, BrowserSearchProvider))
|
||||
finally:
|
||||
bundle.close()
|
||||
|
||||
|
||||
def test_browser_total_falls_back_to_title() -> None:
|
||||
html = load_html().replace(
|
||||
"Samsung Galaxy Z Fold 6: 2 объявления в Москве",
|
||||
"Samsung Galaxy Z Fold 6",
|
||||
)
|
||||
controller = FakeController(html)
|
||||
controller.last_title = "Samsung Galaxy Z Fold 6: 987 объявлений"
|
||||
provider = BrowserSearchProvider(controller, make_settings()) # type: ignore[arg-type]
|
||||
|
||||
page = provider.search(SearchQuery(query="galaxy fold 8"))
|
||||
|
||||
expect(page.total == 987)
|
||||
|
||||
|
||||
def test_browser_total_relaxed_text() -> None:
|
||||
html = load_html().replace(
|
||||
"Samsung Galaxy Z Fold 6: 2 объявления в Москве",
|
||||
"Samsung Galaxy Z Fold 6",
|
||||
)
|
||||
controller = FakeController(html)
|
||||
controller.last_text = "Galaxy fold 8 в Москве1 777 | Сортировка"
|
||||
provider = BrowserSearchProvider(controller, make_settings()) # type: ignore[arg-type]
|
||||
|
||||
page = provider.search(SearchQuery(query="galaxy fold 8"))
|
||||
|
||||
expect(page.total == 1777)
|
||||
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from avito_tools.collector.canary import detect_block, validate_search_payload
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.domain import epoch_to_datetime
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def load_fixture() -> dict:
|
||||
path = Path(__file__).parent / "fixtures" / "web_items.json"
|
||||
import json
|
||||
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def response(
|
||||
text: str,
|
||||
*,
|
||||
status: int = 200,
|
||||
content_type: str = "application/json",
|
||||
) -> HttpResponse:
|
||||
return HttpResponse(
|
||||
status_code=status,
|
||||
content_type=content_type,
|
||||
text=text,
|
||||
elapsed_ms=10,
|
||||
url="https://www.avito.ru/web/1/js/items",
|
||||
)
|
||||
|
||||
|
||||
def test_validate_fixture_is_ok() -> None:
|
||||
result = validate_search_payload(load_fixture())
|
||||
expect(not result.fatal)
|
||||
expect(not result.errors)
|
||||
expect(result.warnings == [])
|
||||
|
||||
|
||||
def test_validate_catalog_items_shape() -> None:
|
||||
import json
|
||||
|
||||
path = Path(__file__).parent / "fixtures" / "web_catalog.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
result = validate_search_payload(payload)
|
||||
expect(not result.fatal)
|
||||
expect(not result.errors)
|
||||
expect(result.warnings == [])
|
||||
|
||||
|
||||
def test_missing_items_is_fatal() -> None:
|
||||
result = validate_search_payload({"totalCount": 10})
|
||||
expect(result.fatal)
|
||||
expect("missing 'items' key" in result.errors)
|
||||
|
||||
|
||||
def test_zero_total_without_items_is_empty_result() -> None:
|
||||
result = validate_search_payload({"totalCount": 0})
|
||||
expect(not result.fatal)
|
||||
expect(not result.errors)
|
||||
expect(any("empty" in warning for warning in result.warnings))
|
||||
|
||||
|
||||
def test_extra_blocks_without_main_results_is_empty() -> None:
|
||||
result = validate_search_payload(
|
||||
{"count": 0, "totalCount": 50, "catalog": {"items": []}}
|
||||
)
|
||||
expect(not result.fatal)
|
||||
expect(not result.errors)
|
||||
expect(any("no main results" in warning for warning in result.warnings))
|
||||
|
||||
|
||||
def test_zero_total_with_items_is_fatal() -> None:
|
||||
result = validate_search_payload({"totalCount": 0, "items": [{"id": 1}]})
|
||||
expect(result.fatal)
|
||||
expect(any("total is 0" in error for error in result.errors))
|
||||
|
||||
|
||||
def test_positive_total_empty_first_page_is_fatal() -> None:
|
||||
result = validate_search_payload({"totalCount": 10, "items": []}, page=1)
|
||||
expect(result.fatal)
|
||||
expect(any("page 1 has no items" in error for error in result.errors))
|
||||
|
||||
|
||||
def test_bad_items_are_warnings_not_fatal() -> None:
|
||||
payload = {
|
||||
"totalCount": 3,
|
||||
"items": [
|
||||
{"id": 1, "title": "ok", "urlPath": "/ok_1", "priceDetailed": {"value": 100}},
|
||||
{"id": 2, "title": "ok", "urlPath": "/ok_2", "priceDetailed": {"value": 200}},
|
||||
{"title": "broken"},
|
||||
],
|
||||
}
|
||||
result = validate_search_payload(payload)
|
||||
expect(not result.fatal)
|
||||
expect(any("failed basic validation" in warning for warning in result.warnings))
|
||||
|
||||
|
||||
def test_detect_block_by_status() -> None:
|
||||
expect(detect_block(response("", status=429)) == "HTTP 429")
|
||||
expect(detect_block(response("", status=403)) == "HTTP 403")
|
||||
expect(detect_block(response("", status=439)) == "HTTP 439")
|
||||
|
||||
|
||||
def test_detect_block_by_json_marker() -> None:
|
||||
body = '{"too-many-requests":{"message":"Доступ с вашего IP-адреса временно ограничен"}}'
|
||||
reason = detect_block(response(body))
|
||||
expect(reason is not None)
|
||||
expect("too-many-requests" in reason)
|
||||
|
||||
|
||||
def test_detect_block_by_html_marker() -> None:
|
||||
body = "<html><body>Доступ ограничен: проблема с IP</body></html>"
|
||||
reason = detect_block(response(body, content_type="text/html"))
|
||||
expect(reason is not None)
|
||||
expect("HTML block marker" in reason)
|
||||
|
||||
|
||||
def test_normal_response_is_not_blocked() -> None:
|
||||
expect(detect_block(response('{"items":[],"totalCount":0}')) is None)
|
||||
|
||||
|
||||
def test_epoch_to_datetime_supports_ms_and_seconds() -> None:
|
||||
expect(epoch_to_datetime(1761800000000) == datetime(2025, 10, 30, 4, 53, 20, tzinfo=UTC))
|
||||
expect(epoch_to_datetime(1761700000) == datetime(2025, 10, 29, 1, 6, 40, tzinfo=UTC))
|
||||
expect(epoch_to_datetime(None) is None)
|
||||
expect(epoch_to_datetime("garbage") is None)
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def test_empty_optional_values_are_normalized() -> None:
|
||||
settings = Settings(
|
||||
_env_file=None,
|
||||
cookie="",
|
||||
user_agent="",
|
||||
proxy="",
|
||||
category_id="",
|
||||
)
|
||||
expect(settings.cookie_value is None)
|
||||
expect(settings.user_agent is None)
|
||||
expect(settings.proxy is None)
|
||||
expect(settings.category_id is None)
|
||||
|
||||
|
||||
def test_default_location() -> None:
|
||||
settings = Settings(_env_file=None)
|
||||
expect(settings.location_id == 637640)
|
||||
expect(settings.request_delay_min == 2.5)
|
||||
expect(settings.request_delay_max == 6.0)
|
||||
|
||||
|
||||
def test_netscape_cookie_file(tmp_path) -> None:
|
||||
cookie_file = tmp_path / "cookies.txt"
|
||||
cookie_file.write_text(
|
||||
"# Netscape HTTP Cookie File\n"
|
||||
".avito.ru\tTRUE\t/\tFALSE\t0\t_avisc\tabc\n"
|
||||
"#HttpOnly_.avito.ru\tTRUE\t/\tFALSE\t0\tsessid\txyz\n"
|
||||
".example.com\tTRUE\t/\tFALSE\t0\tother\tvalue\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
settings = Settings(_env_file=None, cookie_file=cookie_file)
|
||||
expect(settings.cookie_value == "_avisc=abc; sessid=xyz")
|
||||
|
||||
|
||||
def test_cookie_header_prefix_is_stripped() -> None:
|
||||
settings = Settings(_env_file=None, cookie="Cookie: a=1; b=2")
|
||||
expect(settings.cookie_value == "a=1; b=2")
|
||||
|
||||
|
||||
def test_access_mode_defaults_to_anonymous() -> None:
|
||||
settings = Settings(_env_file=None)
|
||||
expect(settings.access_mode == "anonymous")
|
||||
expect(settings.account_fallback is True)
|
||||
|
||||
|
||||
def test_access_mode_is_normalized() -> None:
|
||||
settings = Settings(_env_file=None, access_mode="ACCOUNT")
|
||||
expect(settings.access_mode == "account")
|
||||
@@ -0,0 +1,84 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from avito_tools.cookies import (
|
||||
CookieStore,
|
||||
normalize_cookie_header,
|
||||
parse_cookie_file,
|
||||
parse_json_cookies,
|
||||
parse_netscape_cookies,
|
||||
)
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def test_normalize_cookie_header() -> None:
|
||||
expect(normalize_cookie_header("Cookie: a=1; b=2") == "a=1; b=2")
|
||||
expect(normalize_cookie_header(" ") is None)
|
||||
|
||||
|
||||
def test_netscape_parser() -> None:
|
||||
text = (
|
||||
"# Netscape HTTP Cookie File\n"
|
||||
".avito.ru\tTRUE\t/\tFALSE\t0\t_avisc\tabc\n"
|
||||
"#HttpOnly_.avito.ru\tTRUE\t/\tFALSE\t0\tsessid\txyz\n"
|
||||
".example.com\tTRUE\t/\tFALSE\t0\tother\tvalue\n"
|
||||
)
|
||||
expect(parse_netscape_cookies(text) == "_avisc=abc; sessid=xyz")
|
||||
|
||||
|
||||
def test_json_parser_from_playwright() -> None:
|
||||
text = json.dumps(
|
||||
[
|
||||
{"name": "_avisc", "value": "abc", "domain": ".avito.ru"},
|
||||
{"name": "sessid", "value": "xyz", "domain": ".avito.ru"},
|
||||
{"name": "other", "value": "value", "domain": ".example.com"},
|
||||
]
|
||||
)
|
||||
expect(parse_json_cookies(text) == "_avisc=abc; sessid=xyz")
|
||||
|
||||
|
||||
def test_cookie_file_detects_json(tmp_path) -> None:
|
||||
path = tmp_path / "cookies.json"
|
||||
path.write_text(
|
||||
json.dumps([{"name": "a", "value": "1", "domain": ".avito.ru"}]),
|
||||
encoding="utf-8",
|
||||
)
|
||||
expect(parse_cookie_file(path) == "a=1")
|
||||
|
||||
|
||||
def test_cookie_store_reloads_on_mtime(tmp_path) -> None:
|
||||
path = tmp_path / "cookies.txt"
|
||||
path.write_text(
|
||||
".avito.ru\tTRUE\t/\tFALSE\t0\ta\t1\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
store = CookieStore(path=path)
|
||||
expect(store.get() == "a=1")
|
||||
|
||||
path.write_text(
|
||||
".avito.ru\tTRUE\t/\tFALSE\t0\ta\t2\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(path, (path.stat().st_atime + 2, path.stat().st_mtime + 2))
|
||||
expect(store.get() == "a=2")
|
||||
|
||||
|
||||
def test_duplicate_cookies_prefer_host_domain() -> None:
|
||||
text = json.dumps(
|
||||
[
|
||||
{"name": "cfidsw-avito", "value": "generic", "domain": ".avito.ru"},
|
||||
{"name": "cfidsw-avito", "value": "host", "domain": "www.avito.ru"},
|
||||
{"name": "cfidsw-avito", "value": "wildcard", "domain": ".www.avito.ru"},
|
||||
]
|
||||
)
|
||||
expect(parse_json_cookies(text) == "cfidsw-avito=host")
|
||||
|
||||
|
||||
def test_netscape_duplicate_cookies_are_deduped() -> None:
|
||||
text = (
|
||||
".avito.ru\tTRUE\t/\tFALSE\t0\tcfidsw-avito\tgeneric\n"
|
||||
"www.avito.ru\tTRUE\t/\tFALSE\t0\tcfidsw-avito\thost\n"
|
||||
)
|
||||
expect(parse_netscape_cookies(text) == "cfidsw-avito=host")
|
||||
@@ -0,0 +1,102 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from avito_tools.collector.html import HtmlSearchProvider, parse_search_html
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchQuery
|
||||
from avito_tools.errors import BlockedError
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def load_html() -> str:
|
||||
return (Path(__file__).parent / "fixtures" / "search_page.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, response: HttpResponse) -> None:
|
||||
self.response = response
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def ensure_bootstrap(self) -> None:
|
||||
return None
|
||||
|
||||
def get(self, url: str, **kwargs: Any) -> HttpResponse:
|
||||
self.calls.append({"url": url, **kwargs})
|
||||
return self.response
|
||||
|
||||
|
||||
def make_response(
|
||||
text: str,
|
||||
*,
|
||||
status: int = 200,
|
||||
content_type: str = "text/html; charset=utf-8",
|
||||
) -> HttpResponse:
|
||||
return HttpResponse(
|
||||
status_code=status,
|
||||
content_type=content_type,
|
||||
text=text,
|
||||
elapsed_ms=5,
|
||||
url="https://www.avito.ru/moskva/telefony",
|
||||
)
|
||||
|
||||
|
||||
def make_settings() -> Settings:
|
||||
return Settings(_env_file=None)
|
||||
|
||||
|
||||
def test_parse_search_html() -> None:
|
||||
cards, total = parse_search_html(load_html())
|
||||
expect(total == 2)
|
||||
expect(len(cards) == 2)
|
||||
expect(cards[0].id == "111")
|
||||
expect(cards[0].price == 45000)
|
||||
expect(cards[0].description == "Продаю свой Fold6. Не работает блютуз.")
|
||||
expect(cards[0].seller_type == "private")
|
||||
expect(cards[1].seller_type == "company")
|
||||
expect(cards[1].url.startswith("https://www.avito.ru/"))
|
||||
|
||||
|
||||
def test_html_provider_search() -> None:
|
||||
client = FakeClient(make_response(load_html()))
|
||||
provider = HtmlSearchProvider(client, make_settings(), access_mode="account") # type: ignore[arg-type]
|
||||
|
||||
page = provider.search(SearchQuery(query="galaxy fold 8"), page=1)
|
||||
|
||||
expect(page.total == 2)
|
||||
expect(len(page.items) == 2)
|
||||
expect(page.access_mode == "account")
|
||||
expect(client.calls[0]["url"] == "https://www.avito.ru/moskva/telefony")
|
||||
expect(client.calls[0]["params"]["q"] == "galaxy fold 8")
|
||||
|
||||
|
||||
def test_html_provider_blocked() -> None:
|
||||
client = FakeClient(make_response("Доступ ограничен", status=439))
|
||||
provider = HtmlSearchProvider(client, make_settings(), access_mode="account") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(BlockedError):
|
||||
provider.search(SearchQuery(query="galaxy fold 8"))
|
||||
|
||||
|
||||
def test_html_provider_empty_page() -> None:
|
||||
client = FakeClient(
|
||||
make_response("<html><body><meta name='description' content='0 объявлений'></body></html>")
|
||||
)
|
||||
provider = HtmlSearchProvider(client, make_settings(), access_mode="account") # type: ignore[arg-type]
|
||||
|
||||
page = provider.search(SearchQuery(query="nothing"))
|
||||
|
||||
expect(page.items == [])
|
||||
expect(page.total == 0)
|
||||
expect(page.has_next is False)
|
||||
|
||||
|
||||
def test_parse_browser_dom_lowercase_price_attribute() -> None:
|
||||
cards, total = parse_search_html(load_html().replace("itemProp=", "itemprop="))
|
||||
expect(total == 2)
|
||||
expect(cards[0].price == 45000)
|
||||
expect(cards[1].price == 50000)
|
||||
@@ -0,0 +1,126 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from fastmcp import Client
|
||||
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage
|
||||
from avito_tools.mcp.server import create_server
|
||||
from avito_tools.services.search import SearchService
|
||||
from avito_tools.services.stats import PriceStatsService
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def search(self, query, *, page: int = 1) -> SearchPage:
|
||||
path = Path(__file__).parent / "fixtures" / "web_catalog.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
items = [
|
||||
ListingCard(
|
||||
id=str(raw["id"]),
|
||||
title=raw["title"],
|
||||
description=raw.get("description"),
|
||||
price=raw["priceDetailed"]["value"],
|
||||
url="https://www.avito.ru" + raw["urlPath"],
|
||||
location=raw.get("addressDetailed", {}).get("locationName"),
|
||||
category_id=raw.get("categoryId"),
|
||||
)
|
||||
for raw in payload["catalog"]["items"]
|
||||
]
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=len(items),
|
||||
items=items,
|
||||
has_next=False,
|
||||
access_mode="test",
|
||||
)
|
||||
|
||||
|
||||
def make_server():
|
||||
search_service = SearchService(FakeProvider())
|
||||
stats_service = PriceStatsService(search_service)
|
||||
return create_server(
|
||||
search_service,
|
||||
stats_service,
|
||||
settings=Settings(_env_file=None),
|
||||
access_modes=["test"],
|
||||
)
|
||||
|
||||
|
||||
async def call_tool(name: str, arguments: dict) -> dict:
|
||||
async with Client(make_server()) as client:
|
||||
result = await client.call_tool(name, arguments)
|
||||
return result.data
|
||||
|
||||
|
||||
def test_tools_are_registered() -> None:
|
||||
async def run() -> list[str]:
|
||||
async with Client(make_server()) as client:
|
||||
tools = await client.list_tools()
|
||||
return [tool.name for tool in tools]
|
||||
|
||||
names = asyncio.run(run())
|
||||
expect("search_listings" in names)
|
||||
expect("get_listing" in names)
|
||||
expect("price_stats" in names)
|
||||
|
||||
|
||||
def test_search_then_get_listing() -> None:
|
||||
async def run() -> tuple[dict, dict]:
|
||||
async with Client(make_server()) as client:
|
||||
search = await client.call_tool("search_listings", {"query": "iphone 15", "limit": 5})
|
||||
item_id = search.data["items"][0]["id"]
|
||||
listing = await client.call_tool("get_listing", {"item_id": item_id})
|
||||
return search.data, listing.data
|
||||
|
||||
search_result, listing_result = asyncio.run(run())
|
||||
expect(search_result["ok"] is True)
|
||||
expect(search_result["returned"] == 2)
|
||||
expect(search_result["access_mode"] == "test")
|
||||
expect(listing_result["ok"] is True)
|
||||
expect(listing_result["item"]["description"].startswith("Новый"))
|
||||
|
||||
|
||||
def test_get_unknown_listing() -> None:
|
||||
result = asyncio.run(call_tool("get_listing", {"item_id": "missing"}))
|
||||
expect(result["ok"] is False)
|
||||
expect(result["error"]["code"] == "not_cached")
|
||||
|
||||
|
||||
def test_price_stats_tool() -> None:
|
||||
result = asyncio.run(
|
||||
call_tool(
|
||||
"price_stats",
|
||||
{"query": "iphone 15", "limit": 10, "outlier_policy": "none"},
|
||||
)
|
||||
)
|
||||
expect(result["ok"] is True)
|
||||
expect(result["stats"]["count"] == 2)
|
||||
expect(result["stats"]["median"] == 41895)
|
||||
|
||||
|
||||
def test_status_resource() -> None:
|
||||
async def run() -> str:
|
||||
async with Client(make_server()) as client:
|
||||
resources = await client.read_resource("avito://status")
|
||||
return resources[0].text
|
||||
|
||||
payload = json.loads(asyncio.run(run()))
|
||||
expect(payload["name"] == "avito-tools")
|
||||
expect(payload["access_mode"] == "anonymous")
|
||||
|
||||
|
||||
def test_metrics_resource() -> None:
|
||||
async def run() -> str:
|
||||
async with Client(make_server()) as client:
|
||||
resources = await client.read_resource("avito://metrics")
|
||||
return resources[0].text
|
||||
|
||||
payload = json.loads(asyncio.run(run()))
|
||||
expect("iqr" in payload)
|
||||
expect("mad" in payload)
|
||||
expect("avg" in payload)
|
||||
@@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from avito_tools.domain import ListingCard, SearchPage, SearchQuery
|
||||
from avito_tools.services.search import SearchService
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def search(self, query, *, page: int = 1) -> SearchPage:
|
||||
items = [
|
||||
ListingCard(
|
||||
id="1",
|
||||
title="Samsung Galaxy Z Fold6, 12/512 ГБ",
|
||||
price=50000,
|
||||
url="u1",
|
||||
),
|
||||
ListingCard(
|
||||
id="2",
|
||||
title="Samsung Galaxy Z TriFold, 16/512 ГБ",
|
||||
price=300000,
|
||||
url="u2",
|
||||
),
|
||||
ListingCard(id="3", title="Чехол для Galaxy Z Fold6", price=1000, url="u3"),
|
||||
ListingCard(
|
||||
id="4",
|
||||
title="Samsung Galaxy Z Fold 6, 512 ГБ",
|
||||
price=60000,
|
||||
url="u4",
|
||||
),
|
||||
]
|
||||
return SearchPage(query=query.query, page=page, total=len(items), items=items)
|
||||
|
||||
|
||||
def test_title_pattern_and_exclusions() -> None:
|
||||
service = SearchService(FakeProvider())
|
||||
batch = service.search(
|
||||
SearchQuery(
|
||||
query="galaxy fold 6",
|
||||
title_pattern=r"fold\s*6",
|
||||
exclude_title_keywords=["trifold", "чехол"],
|
||||
),
|
||||
pages=1,
|
||||
limit=10,
|
||||
)
|
||||
expect([item.id for item in batch.items] == ["1", "4"])
|
||||
@@ -0,0 +1,102 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from avito_tools.analytics.stats import compute_price_stats
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import ListingCard, SearchPage
|
||||
from avito_tools.non_agent.api.app import create_app
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def test_quantiles_and_center() -> None:
|
||||
stats = compute_price_stats([100, 200, 300, 400, 500], outlier_policy="none")
|
||||
expect(stats.count == 5)
|
||||
expect(stats.min == 100)
|
||||
expect(stats.max == 500)
|
||||
expect(stats.avg == 300)
|
||||
expect(stats.median == 300)
|
||||
expect(stats.p25 == 200)
|
||||
expect(stats.p90 == 460)
|
||||
expect(stats.p95 == 480)
|
||||
expect(stats.p99 == 496)
|
||||
expect(stats.iqr == 200)
|
||||
|
||||
|
||||
def test_iqr_excludes_outlier() -> None:
|
||||
stats = compute_price_stats([100, 110, 120, 130, 100000])
|
||||
expect(stats.count == 4)
|
||||
expect(stats.method.outlier_count == 1)
|
||||
expect(stats.max == 130)
|
||||
expect(any("outliers" in warning for warning in stats.warnings))
|
||||
|
||||
|
||||
def test_outlier_policy_none_keeps_all() -> None:
|
||||
stats = compute_price_stats([100, 110, 120, 130, 100000], outlier_policy="none")
|
||||
expect(stats.count == 5)
|
||||
expect(stats.method.outlier_count == 0)
|
||||
expect(stats.max == 100000)
|
||||
|
||||
|
||||
def test_histogram_counts_sum_to_sample() -> None:
|
||||
stats = compute_price_stats([100, 200, 300, 400, 500], histogram_bins=5)
|
||||
expect(len(stats.histogram) == 5)
|
||||
expect(sum(bucket.count for bucket in stats.histogram) == stats.count)
|
||||
|
||||
|
||||
def test_empty_prices() -> None:
|
||||
stats = compute_price_stats([])
|
||||
expect(stats.count == 0)
|
||||
expect(stats.median is None)
|
||||
expect(any("no priced" in warning for warning in stats.warnings))
|
||||
|
||||
|
||||
def test_single_price() -> None:
|
||||
stats = compute_price_stats([12345])
|
||||
expect(stats.count == 1)
|
||||
expect(stats.std == 0)
|
||||
expect(any("too small" in warning for warning in stats.warnings))
|
||||
|
||||
|
||||
def test_all_prices_equal() -> None:
|
||||
stats = compute_price_stats([100, 100, 100, 100])
|
||||
expect(stats.count == 4)
|
||||
expect(len(stats.histogram) == 1)
|
||||
expect(stats.histogram[0].count == 4)
|
||||
expect(any("equal" in warning for warning in stats.warnings))
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
def search(self, query, *, page: int = 1) -> SearchPage:
|
||||
prices = [100000, 120000, 130000, 140000, 150000]
|
||||
return SearchPage(
|
||||
query=query.query,
|
||||
page=page,
|
||||
total=len(prices),
|
||||
items=[
|
||||
ListingCard(
|
||||
id=str(index),
|
||||
title=f"iPhone {index}",
|
||||
price=price,
|
||||
url=f"https://www.avito.ru/moskva/telefony/iphone_{index}",
|
||||
)
|
||||
for index, price in enumerate(prices, start=1)
|
||||
],
|
||||
has_next=False,
|
||||
)
|
||||
|
||||
|
||||
def test_stats_api() -> None:
|
||||
app = create_app(settings=Settings(_env_file=None), provider=FakeProvider())
|
||||
with TestClient(app) as client:
|
||||
response = client.post(
|
||||
"/api/v1/stats",
|
||||
json={"query": "iphone 15", "outlier_policy": "none"},
|
||||
)
|
||||
get_response = client.get("/api/v1/stats", params={"q": "iphone 15"})
|
||||
expect(response.status_code == 200)
|
||||
payload = response.json()
|
||||
expect(payload["stats"]["count"] == 5)
|
||||
expect(payload["stats"]["median"] == 130000)
|
||||
expect(get_response.status_code == 200)
|
||||
expect(get_response.json()["stats"]["count"] == 5)
|
||||
@@ -0,0 +1,224 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from avito_tools.collector.http import HttpResponse
|
||||
from avito_tools.collector.web import WebSearchProvider
|
||||
from avito_tools.config import Settings
|
||||
from avito_tools.domain import SearchQuery
|
||||
from avito_tools.errors import BlockedError, SchemaDriftError
|
||||
from tests.helpers import expect
|
||||
|
||||
|
||||
def load_payload() -> dict[str, Any]:
|
||||
path = Path(__file__).parent / "fixtures" / "web_items.json"
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, response: HttpResponse) -> None:
|
||||
self.response = response
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def get(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
params: dict[str, Any] | None = None,
|
||||
pace: bool = True,
|
||||
) -> HttpResponse:
|
||||
self.calls.append({"url": url, "params": params, "pace": pace})
|
||||
return self.response
|
||||
|
||||
|
||||
def make_response(
|
||||
payload: dict[str, Any] | str,
|
||||
*,
|
||||
status: int = 200,
|
||||
content_type: str = "application/json",
|
||||
) -> HttpResponse:
|
||||
text = json.dumps(payload, ensure_ascii=False) if isinstance(payload, dict) else payload
|
||||
return HttpResponse(
|
||||
status_code=status,
|
||||
content_type=content_type,
|
||||
text=text,
|
||||
elapsed_ms=12,
|
||||
url="https://www.avito.ru/web/1/js/items",
|
||||
)
|
||||
|
||||
|
||||
def make_settings() -> Settings:
|
||||
return Settings(_env_file=None, location_id=637640)
|
||||
|
||||
|
||||
def test_search_normalizes_items() -> None:
|
||||
client = FakeClient(make_response(load_payload()))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
page = provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(page.total == 3)
|
||||
expect(len(page.items) == 3)
|
||||
expect(page.has_next is False)
|
||||
expect(page.items[0].id == "1234567890")
|
||||
expect(page.items[0].price == 74990)
|
||||
expect(page.items[0].url.startswith("https://www.avito.ru/moskva/"))
|
||||
expect(page.items[0].location == "Москва")
|
||||
expect(page.items[0].seller == "Иван")
|
||||
expect(page.items[0].seller_is_company is False)
|
||||
expect(page.items[0].image == "https://img.avito.st/image-1.jpg")
|
||||
expect(page.items[1].price == 69000)
|
||||
expect(page.items[2].price == 0)
|
||||
expect(page.items[2].seller_is_company is True)
|
||||
|
||||
|
||||
def test_search_builds_expected_params() -> None:
|
||||
client = FakeClient(make_response(load_payload()))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
provider.search(
|
||||
SearchQuery(
|
||||
query="iphone 15",
|
||||
location_id=1,
|
||||
category_id=2,
|
||||
price_min=10000,
|
||||
price_max=90000,
|
||||
extra_params={"radius": "10"},
|
||||
),
|
||||
page=2,
|
||||
)
|
||||
|
||||
params = client.calls[0]["params"]
|
||||
expect(params["q"] == "iphone 15")
|
||||
expect(params["p"] == 2)
|
||||
expect(params["locationId"] == 1)
|
||||
expect(params["categoryId"] == 2)
|
||||
expect(params["pmin"] == 10000)
|
||||
expect(params["pmax"] == 90000)
|
||||
expect(params["radius"] == "10")
|
||||
|
||||
|
||||
def test_search_skips_unparseable_item() -> None:
|
||||
payload = load_payload()
|
||||
payload["items"].append({"id": 999, "priceDetailed": {"value": 100}})
|
||||
payload["totalCount"] = 4
|
||||
client = FakeClient(make_response(payload))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
page = provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(len(page.items) == 3)
|
||||
expect(any("skipped 1" in warning for warning in page.warnings))
|
||||
|
||||
|
||||
def test_search_raises_blocked_on_429() -> None:
|
||||
body = {"too-many-requests": {"message": "Доступ с вашего IP-адреса временно ограничен"}}
|
||||
client = FakeClient(make_response(body, status=429))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
with pytest.raises(BlockedError) as exc_info:
|
||||
provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(exc_info.value.status_code == 429)
|
||||
expect("too-many-requests" in str(exc_info.value.detail["body_head"]))
|
||||
|
||||
|
||||
def test_search_raises_drift_on_html() -> None:
|
||||
client = FakeClient(
|
||||
make_response("<html><body>captcha</body></html>", content_type="text/html")
|
||||
)
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
with pytest.raises(SchemaDriftError):
|
||||
provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
|
||||
def test_search_raises_drift_on_missing_items() -> None:
|
||||
client = FakeClient(make_response({"totalCount": 1}))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
with pytest.raises(SchemaDriftError) as exc_info:
|
||||
provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(exc_info.value.detail["errors"] == ["missing 'items' key"])
|
||||
|
||||
|
||||
def test_catalog_shape_normalizes_items() -> None:
|
||||
path = Path(__file__).parent / "fixtures" / "web_catalog.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
client = FakeClient(make_response(payload))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
page = provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(page.total == 2)
|
||||
expect(len(page.items) == 2)
|
||||
expect(page.items[0].price == 52800)
|
||||
expect(page.items[0].description.startswith("Новый"))
|
||||
expect(page.items[0].location == "Москва")
|
||||
expect(page.items[0].category_id == 84)
|
||||
expect(page.items[1].description == "Без Bluetooth.")
|
||||
|
||||
|
||||
def test_seller_type_classification() -> None:
|
||||
payload = {
|
||||
"totalCount": 3,
|
||||
"catalog": {
|
||||
"items": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "private",
|
||||
"urlPath": "/private_1",
|
||||
"priceDetailed": {"value": 100},
|
||||
"iva": {
|
||||
"UserInfoStep": [
|
||||
{"payload": {"profile": {"title": "Лиза", "link": "/user/abc"}}}
|
||||
]
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "company",
|
||||
"urlPath": "/company_2",
|
||||
"priceDetailed": {"value": 200},
|
||||
"iva": {
|
||||
"SecondLineStep": [{"payload": {"value": "Компания"}}],
|
||||
"UserInfoStep": [
|
||||
{"payload": {"profile": {"title": "Shop", "link": "/brands/shop"}}}
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "self",
|
||||
"urlPath": "/self_3",
|
||||
"priceDetailed": {"value": 300},
|
||||
"iva": {
|
||||
"UserInfoStep": [
|
||||
{
|
||||
"payload": {
|
||||
"profile": {"title": "Self", "link": "/brands/self"},
|
||||
"badges": [{"title": "Самозанятый"}],
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
client = FakeClient(make_response(payload))
|
||||
provider = WebSearchProvider(client, make_settings(), bootstrap=False)
|
||||
|
||||
page = provider.search(SearchQuery(query="iphone 15"))
|
||||
|
||||
expect(page.items[0].seller_type == "private")
|
||||
expect(page.items[0].seller == "Лиза")
|
||||
expect(page.items[1].seller_type == "company")
|
||||
expect(page.items[1].seller_is_company is True)
|
||||
expect(page.items[2].seller_type == "self_employed")
|
||||
expect(page.items[2].seller_is_company is False)
|
||||
Reference in new issue
Block a user