recovered snapshot from suspended aaronjaworski710 (history unavailable)

This commit is contained in:
reform
2026-10-23 20:04:00 +03:00
commit 9b3dd46ab4
31 changed files with 8900 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
dist/
build/
# Virtual Environment
.venv/
venv/
ENV/
env/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# Environment & Secrets
.env
.env.*
accounts.json
# Data & Database
data/
*.db
*.db-shm
*.db-wal
# Logs
logs/
*.log
# Git
.git/
.gitignore
# Documentation
docs/
*.md
# Testing
.pytest_cache/
.coverage
htmlcov/
# Deployment configs (already in container context)
Dockerfile
docker-compose.yml
.dockerignore
# Scripts (not needed in container)
scripts/
# Debug data
response/
AI-note/
# OS
.DS_Store
Thumbs.db
+11
View File
@@ -0,0 +1,11 @@
NOTION_ACCOUNTS=
API_KEY=
HOST=
ALLOWED_ORIGINS=
PORT=
APP_MODE=
HOST_PORT=
DB_PATH=
SILICONFLOW_API_KEY=
LOG_LEVEL=
TZ=
+76
View File
@@ -0,0 +1,76 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
dist/
build/
.venv/
venv/
# Environment variables (SECURITY RISK)
.env
.env.*
accounts.json
# Data & Database
data/
*.db
*.db-shm
*.db-wal
# Logs
logs/
*.log
# IDEs
.vscode/
.idea/
*.swp
.DS_Store
# AI Development Notes & Tools (SECURITY: Do not commit internal notes)
AI-note/
GEMINI.md
CODEX.md
CLAUDE.md
ref/
*.md.bak
docs/PR_REVIEW_23_24_16.md
# Backup and temporary files
*.bak
*backup*
*.backup
*-backup.*
debug_*.log
tmp_*.log
*.tmp
*.old
# Test files (all tests directory)
tests/
test_*.py
*_test.py
debug_*.py
# Claude Code local settings
.claude/settings.local.json
# Docker (Optional to ignore if you want to keep configs in git, usually we keep them)
# But we definitely ignore local-specific overrides
docker-compose.override.yml
# Local cleanup folder
0311_cleanup/
# Response debug data (contains sensitive tokens)
response/
data/
*.log
farm_accounts.jsonl
state_*.json
+18
View File
@@ -0,0 +1,18 @@
# Python 3.11 slim как база
FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 TZ=Europe/Moscow
RUN apt-get update && apt-get install -y --no-install-recommends tzdata && rm -rf /var/lib/apt/lists/* && groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN mkdir -p /app/data && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.server:app", "--host", "0.0.0.0", "--port", "8000"]
+124
View File
@@ -0,0 +1,124 @@
# Notion2API-RU
> Notion AI → OpenAI-совместимый API + авторег аккаунтов
Реверс веб-интерфейса Notion AI, обёрнутый в стандартный `/v1/chat/completions`. Работает с Cherry Studio, Zotero, LobeChat и любым OpenAI-совместимым клиентом.
**Главная фишка этой сборки — встроенный авторег:** не нужно руками регистрировать аккаунты и дёргать токены из F12. `tools/farm.py` сам регистрирует новые аккаунты Notion через временные почты (voidash/mail.tm), проходит онбординг, выбирает модель и складывает готовые креды в пул.
## Возможности
- **OpenAI-совместимость** — `/v1/chat/completions`, стриминг (SSE) и обычные ответы
- **23 модели** — Claude (включая Opus 5), GPT-6 Astra, GPT-5.x, Gemini, Kimi, Grok, DeepSeek, GLM, Fable
- **Панель Thinking** — показывает рассуждения модели
- **Панель Search** — поисковые запросы и источники
- **Пул аккаунтов** — Round-Robin балансировка, cooldown при сбоях
- **Авторег** — ферма аккаунтов через временные почты, без капчи
- **Web UI** — встроенная панель, тёмная тема, анимации
- **Docker** — деплой одной командой
## Быстрый старт
### Вариант 1 — Авторег (рекомендую)
```bash
# ставим зависимости
pip install -r requirements.txt
pip install playwright httpx
playwright install chromium
# регистрируем 5 аккаунтов с Opus 5.5
python tools/farm.py 5 Opus
```
Ферма сама:
1. Создаёт временный ящик (voidash.bond или mail.tm)
2. Регистрирует аккаунт Notion, ловит код подтверждения из письма
3. Проходит онбординг (без карты, триал не нужен — модели доступны сразу)
4. Заходит в AI-чат, выбирает модель (Opus 5.5 / GPT-6.1 Sol / Kimi K3 / GPT-6 Luna)
5. Отправляет тестовое сообщение и проверяет ответ
6. Сохраняет креды в `farm_accounts.jsonl` + state-файл сессии
```bash
# конвертируем пул фермы в accounts.json для сервера
python tools/farm.py --export
```
### Вариант 2 — Ручные креды
```bash
python login.py # откроет браузер, ждёт логина, сам вытащит token_v2 и всё остальное
```
Или руками через F12: Application → Cookies → `token_v2`, потом скрипт `scripts/extract_notion_info.js` в консоли — он выдаст все поля для `accounts.json`.
### Запуск сервера
```bash
pip install -r requirements.txt
uvicorn app.server:app --host 0.0.0.0 --port 8000
```
Или Docker:
```bash
docker-compose build --no-cache && docker-compose up -d
```
## Использование API
```python
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="any")
r = client.chat.completions.create(
model="claude-opus5",
messages=[{"role": "user", "content": "Привет"}],
stream=True,
)
for chunk in r:
print(chunk.choices[0].delta.content or "", end="")
```
| Эндпоинт | Метод | Описание |
|---|---|---|
| `/v1/chat/completions` | POST | Основной |
| `/v1/models` | GET | Список моделей |
| `/health` | GET | Статус пула аккаунтов |
| `/` | GET | Web UI |
## Режимы
| | Lite | Standard | Heavy |
|---|---|---|---|
| Память | нет | клиент | сервер |
| База | нет | нет | SQLite |
| Thinking/Search | нет | да | да |
| RPS | 30/мин | 25/мин | 20/мин |
`APP_MODE=standard` в `.env` — рекомендуемый.
## Модели
`claude-opus5`, `claude-sonnet4.6`, `claude-sonnet5`, `gpt-6-astra`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gemini-3.1pro`, `kimi-2.7`, `grok-4.3`, `deepseek-v4pro`, `glm-5.2`, `fable-5` и другие. Полный список: `GET /v1/models`.
## Переменные окружения
| Переменная | Описание | По умолчанию |
|---|---|---|
| `NOTION_ACCOUNTS` | JSON-массив кредов Notion | обязателен |
| `APP_MODE` | `lite` / `standard` / `heavy` | `heavy` |
| `API_KEY` | Bearer для клиентов | нет |
| `PORT` | Порт | 8000 |
| `SILICONFLOW_API_KEY` | Для сжатия контекста в Heavy | нет |
## Заметки
- Лимиты Notion: 5-часовой квоты тратятся быстро, месячной — медленно. Пул аккаунтов распределяет нагрузку.
- При 429 — добавить аккаунтов (`python tools/farm.py 5`).
- Ключи и `accounts.json` в `.gitignore` — не коммитить.
## Лицензия
MIT
+309
View File
@@ -0,0 +1,309 @@
# Notion2API
> Notion AI → OpenAI-Compatible API
🌐 English | [中文](./README.md)
Notion2API reverse-engineers the Notion AI web interface and exposes it as a standard `/v1/chat/completions` endpoint, making it directly usable with Cherry Studio, Zotero, and any other OpenAI-compatible client.
---
## Features
- **OpenAI Compatible** — Standard `/v1/chat/completions` endpoint, streaming (SSE) and non-streaming
- **Three Operation Modes** — Lite / Standard / Heavy to fit different use cases
- **23 AI Models** — Claude (incl. Opus 5), GPT-6 Astra, GPT-5.x, Gemini, Kimi, Grok, DeepSeek, GLM, Fable
- **Thinking Panel** — Reasoning process display for all models
- **Search Panel** — Web search queries and source links
- **Multi-Account Pool** — Round-Robin load balancing with cooldown failover
- **Built-in Web UI** — Minimalist design, ambient animations, dark mode
- **Docker Ready** — One-command deployment
---
## Mode Comparison
| Feature | Lite | Standard | Heavy |
|---------|------|----------|-------|
| **Memory** | ❌ None | ✅ Client-managed | ✅ Server-managed |
| **Database** | ❌ | ❌ | ✅ SQLite |
| **Thinking Panel** | ❌ | ✅ | ✅ |
| **Search Panel** | ❌ | ✅ | ✅ |
| **Rate Limit** | 30/min | 25/min | 20/min |
| **Use Case** | Simple Q&A | Short–mid conversations | Long-term conversations |
> **Recommended**: `standard` — full context, no database required.
> Switch by setting `APP_MODE` in `.env`.
---
## Quick Start
### 1. Get Notion Credentials
Choose the method that fits your situation:
#### Method A — F12 (if you already have a Notion web session)
1. Open https://www.notion.so/ai and log in
2. Press `F12` → **Application** tab → **Storage → Cookies → https://www.notion.so**
3. Find `token_v2` and copy its Value
4. Switch to the **Console** tab, paste and run `scripts/extract_notion_info.js`
5. The script outputs all required fields — paste the result into `accounts.json`
#### Method B — Browser-Assisted Login (no existing web session needed)
```bash
python login.py
```
This launches a temporary Chrome/Edge window, waits for you to sign in to Notion, then automatically extracts all credentials and writes them to `accounts.json` and `.env`.
```bash
python login.py --check # verify a saved profile
python login.py --list # list all saved profiles
python login.py --manual # paste token_v2 manually if Chrome is unavailable
python login.py --profile work # save under a named profile
```
Both methods write to `accounts.json`. Multiple accounts are supported — add more entries to the array to enable load balancing.
> ⚠️ `accounts.json` and `.env` contain credentials. Both are git-ignored — keep them private.
---
### 2. Configure `.env`
```bash
cp .env.example .env
```
At minimum, set:
```env
APP_MODE=standard # lite / standard / heavy
```
If using **Heavy mode**, also add:
```env
SILICONFLOW_API_KEY=your_key_here
```
> Heavy mode uses SiliconFlow's LLM to compress long conversations. Register free at https://siliconflow.cn.
---
### 3. Start the Service
#### Docker (Recommended)
```bash
docker-compose build --no-cache && docker-compose up -d
```
`accounts.json` is mounted as a volume — update accounts without rebuilding:
```bash
# After editing accounts.json:
docker-compose restart
```
#### Local Run
```bash
pip install -r requirements.txt
uvicorn app.server:app --host 0.0.0.0 --port 8000
```
Access the Web UI at `http://localhost:8000`.
---
## Supported Models
| Model Name | Description |
|---|---|
| `claude-sonnet4.6` | Best balance of speed and quality — **most recommended** |
| `claude-sonnet5` | Sonnet 5 |
| `claude-opus4.6` | Stronger reasoning, use sparingly |
| `claude-opus4.7` | Stronger reasoning |
| `claude-opus4.8` | Strong reasoning Claude |
| `claude-opus5` | Newest Claude Opus, strongest reasoning |
| `claude-haiku4.5` | Haiku 4.5 |
| `gpt-6-astra` | GPT-6 Astra |
| `gpt-5.6-sol` | GPT-5.6 Sol |
| `gpt-5.6-terra` | GPT-5.6 Terra |
| `gpt-5.6-luna` | GPT-5.6 Luna |
| `gpt-5.5` | GPT-5.5 |
| `gpt-5.4` | OpenAI model |
| `gemini-3.5flash` | Gemini 3.5 Flash |
| `gemini-3.1pro` | Google's strongest reasoning model |
| `gemini-3flash` | Gemini 3 Flash |
| `kimi-2.7` | Kimi K2.7 Code |
| `grok-4.3` | xAI Grok 4.3 |
| `spacexai-4.5` | SpaceXAI 4.5 |
| `grok-build0.1` | xAI Grok Build 0.1 |
| `deepseek-v4pro` | DeepSeek V4 Pro |
| `glm-5.2` | GLM 5.2 |
| `fable-5` | Fable 5 |
Full list via API: `GET http://localhost:8000/v1/models`
To add or sync a Notion AI model, see [`docs/ADD_MODEL.md`](./docs/ADD_MODEL.md) (checklist of files to update — no need to search the whole repo).
---
## API Usage
This project accepts any string as the API key (no format requirement).
### Python Example
```python
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8000/v1",
api_key="any-string"
)
response = client.chat.completions.create(
model="claude-sonnet4.6",
messages=[{"role": "user", "content": "Hello"}],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="")
```
### Endpoints
| Endpoint | Method | Description |
|---|---|---|
| `/v1/chat/completions` | POST | Chat completions (core) |
| `/v1/models` | GET | List available models |
| `/health` | GET | Health check (account pool status, uptime) |
| `/` | GET | Built-in Web UI |
---
## Web UI
Access `http://localhost:8000` for the built-in **Notion AI Studio** interface:
- **Conversation Management** — Create, rename, delete, star/bookmark
- **Model Selector** — Grouped by provider (Anthropic / OpenAI / Google / Moonshot / xAI / DeepSeek)
- **Thinking Panel** — Collapsible reasoning display with elapsed timer
- **Search Panel** — Collapsible web search queries and source links
- **Ambient Animations** — Weather effects: default / snow / rain / sunny / night
- **Theme** — Light / dark mode toggle
- **Responsive** — Mobile-friendly sidebar
> Thinking and Search panels require `standard` or `heavy` mode.
---
## Environment Variables
| Variable | Description | Default |
|---|---|---|
| `NOTION_ACCOUNTS` | Notion credentials JSON array | **Required** |
| `APP_MODE` | `lite` / `standard` / `heavy` | `heavy` |
| `API_KEY` | Bearer token for client auth | *(none)* |
| `DB_PATH` | SQLite database path | `./data/conversations.db` |
| `HOST` | Bind address | `0.0.0.0` |
| `PORT` | Service port | `8000` |
| `HOST_PORT` | Docker host port | `8000` |
| `ALLOWED_ORIGINS` | CORS allowed origins | `*` |
| `SILICONFLOW_API_KEY` | Required for Heavy mode compression | *(none)* |
| `DISABLE_RATE_LIMIT` | Disable per-IP rate limiting | `false` |
| `NOTION_CLIENT_VERSION` | Override Notion client version header | `23.13.20260228.0625` |
| `NOTION_URL` | Notion site base URL (mirror/proxy) | `https://www.notion.so` |
| `NOTION_DOMAIN` | Cookie domain for login.py | `www.notion.so` |
| `LOG_LEVEL` | Logging level | `INFO` |
| `TZ` | Timezone | `Asia/Shanghai` |
---
## Docker Reference
```bash
# Start
docker-compose up -d
# View logs
docker-compose logs -f --tail=50
# Restart (e.g. after updating accounts.json)
docker-compose restart
# Update code and redeploy
git pull && docker-compose down && docker-compose build --no-cache && docker-compose up -d
# Stop
docker-compose down
```
### Nginx Reverse Proxy (optional)
```nginx
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
}
```
---
## FAQ
**Thinking panel not showing?**
Use `APP_MODE=standard` or `heavy`. Lite mode does not support Thinking or Search panels.
**How do I switch modes?**
Edit `APP_MODE` in `.env`, then restart: `docker-compose restart`
**How do I add multiple accounts?**
Edit `accounts.json` as an array — accounts are load-balanced automatically:
```json
[
{"token_v2": "token1", "space_id": "...", "user_id": "...", "space_view_id": "...", "user_name": "...", "user_email": "..."},
{"token_v2": "token2", "space_id": "...", "user_id": "...", "space_view_id": "...", "user_name": "...", "user_email": "..."}
]
```
**Getting 429 or Notion AI suspended?**
Notion may throttle workspaces with unusual request patterns. Adding multiple accounts helps distribute load. Business Trial workspaces are especially prone to this.
**Token expired?**
Re-run `python login.py` or repeat the F12 steps to refresh credentials.
---
## Compatibility
> Due to Notion's own AI latency, expect ~3 seconds from request to first token.
| Client | Status | Notes |
|---|---|---|
| Cherry Studio | ✅ Full support | Recommended |
| Zotero Translation | ✅ Full support | Slightly slow; sonnet model most accurate |
| Immersive Translate | ⚠️ Not recommended | High latency |
| Claude Code | ❌ Not supported | Uses Anthropic native API format |
---
## License
MIT License
---
If this project helps you, please give it a Star ⭐
*Built with assistance from Claude Code.*
View File
+114
View File
@@ -0,0 +1,114 @@
import time
import threading
from typing import Dict, List
from app.logger import logger
from app.notion_client import NotionOpusAPI
class AccountPool:
def __init__(self, accounts: List[dict]):
"""
从配置列表初始化,每个 dict 对应一组凭据。
同时初始化客户端实例和它们的状态。
"""
if not accounts:
raise ValueError("账号池初始化失败:未提供任何账号配置。")
self.clients = [NotionOpusAPI(acc) for acc in accounts]
# 记录每个客户端的冷却释放时间戳(0 表示可用)
self.cooldown_until = [0.0 for _ in self.clients]
# 轮询索引
self._current_index = 0
self._lock = threading.Lock()
def get_client(self, wait_if_cooling: bool = True) -> NotionOpusAPI:
"""
轮询(Round-Robin)返回下一个可用客户端。
过滤掉正处于冷却期中的客户端。
如果 wait_if_cooling=True(默认),当所有账号都在冷却时,
会等待最近的冷却结束后返回,而不是抛异常。
"""
now = time.time()
with self._lock:
start_index = self._current_index
while True:
idx = self._current_index
# 如果过了冷却时间,视为可用
if self.cooldown_until[idx] <= now:
# 轮询步进
self._current_index = (self._current_index + 1) % len(self.clients)
return self.clients[idx]
# 不可用则顺延
self._current_index = (self._current_index + 1) % len(self.clients)
# 如果转了一圈都没找到可用的
if self._current_index == start_index:
next_available = min(self.cooldown_until)
wait_seconds = max(0.5, next_available - now)
if wait_if_cooling and wait_seconds <= 15:
# 等待冷却结束后重新尝试
logger.info(
f"All accounts cooling, waiting {wait_seconds:.1f}s",
extra={
"request_info": {
"event": "account_pool_wait_cooling",
"wait_seconds": round(wait_seconds, 1),
}
},
)
# 释放锁再 sleep,避免阻塞其他线程
self._lock.release()
try:
time.sleep(wait_seconds)
finally:
self._lock.acquire()
# 更新时间后重新扫描
now = time.time()
continue
raise RuntimeError(
f"所有账号冷却中,请在 {max(1, int(wait_seconds))} 秒后重试。"
)
def get_status_summary(self) -> Dict[str, int]:
"""返回账号池简要状态,供健康检查和日志使用。"""
now = time.time()
with self._lock:
active = sum(1 for ts in self.cooldown_until if ts <= now)
cooling = len(self.cooldown_until) - active
return {
"total": len(self.clients),
"active": active,
"cooling": cooling,
}
def mark_failed(self, client: NotionOpusAPI, cooldown_seconds: int = 3):
"""
标记某个客户端为临时不可用(默认冷却 3 秒后恢复)。
"""
with self._lock:
try:
idx = self.clients.index(client)
# 记录未来的冷却解封时间
self.cooldown_until[idx] = time.time() + cooldown_seconds
logger.warning(
"Account marked as failed",
extra={
"request_info": {
"event": "account_failed",
"account": client.account_key,
"space_id": client.space_id,
"cooldown_seconds": cooldown_seconds,
}
},
)
except ValueError:
logger.warning(
"Attempted to mark unknown account as failed",
extra={"request_info": {"event": "account_failed_unknown"}},
)
View File
+1943
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
import time
from typing import Dict, Any
from fastapi import APIRouter
from app.model_registry import get_display_name, get_model_icon, list_available_models
router = APIRouter()
@router.get("/models", tags=["models"])
async def list_models() -> Dict[str, Any]:
"""
列出可用的模型,兼容 OpenAI 格式。
"""
created_at = int(time.time())
return {
"object": "list",
"data": [
{
"id": model_id,
"object": "model",
"created": created_at,
"owned_by": "notion",
"permission": [],
"root": model_id,
"parent": None,
"display_name": get_display_name(model_id),
"icon": get_model_icon(model_id),
}
for model_id in list_available_models()
],
}
+66
View File
@@ -0,0 +1,66 @@
import os
import json
from dotenv import load_dotenv
# 加载 .env 文件中的环境变量(override=True 确保 .env 优先于系统环境变量)
load_dotenv(override=True)
REQUIRED_ACCOUNT_FIELDS = {"token_v2", "space_id", "user_id"}
def load_accounts():
"""
从 accounts.json 文件或环境变量 NOTION_ACCOUNTS 加载账号配置。
优先级:accounts.json > NOTION_ACCOUNTS 环境变量
"""
# 优先从 accounts.json 文件读取
accounts_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "accounts.json")
accounts_json = None
if os.path.exists(accounts_file):
with open(accounts_file, "r", encoding="utf-8") as f:
accounts_json = f.read().strip()
# 回退到环境变量
if not accounts_json:
accounts_json = os.getenv("NOTION_ACCOUNTS")
if not accounts_json:
raise ValueError("未找到账号配置:请创建 accounts.json 文件或设置 NOTION_ACCOUNTS 环境变量。")
try:
accounts = json.loads(accounts_json)
if not isinstance(accounts, list) or len(accounts) == 0:
raise ValueError("账号配置格式不正确,应提供非空的 JSON 数组。")
for idx, account in enumerate(accounts):
if not isinstance(account, dict):
raise ValueError(f"账号配置[{idx}] 必须是对象。")
missing = sorted(field for field in REQUIRED_ACCOUNT_FIELDS if not account.get(field))
if missing:
raise ValueError(f"账号配置[{idx}] 缺少必要字段: {', '.join(missing)}")
return accounts
except json.JSONDecodeError as e:
raise ValueError(f"解析账号配置失败: {e}")
# 全局配置对象
ACCOUNTS = load_accounts()
# FastAPI 服务配置
API_KEY = os.getenv("API_KEY", "")
SILICONFLOW_API_KEY = os.getenv("SILICONFLOW_API_KEY", "")
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "8000"))
ALLOWED_ORIGINS = [origin.strip() for origin in os.getenv("ALLOWED_ORIGINS", "*").split(",") if origin.strip()]
# APP_MODE: heavy(默认)、lite 或 standard
APP_MODE = os.getenv("APP_MODE", "heavy").lower().strip()
def is_lite_mode() -> bool:
return APP_MODE == "lite"
def is_standard_mode() -> bool:
"""Standard 模式:发送完整上下文,支持 thinking 和搜索输出"""
return APP_MODE == "standard"
def get_default_account():
"""获取默认账号(列表中的第一个账号)"""
return ACCOUNTS[0]
+2115
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
import os
from slowapi import Limiter
from slowapi.util import get_remote_address
from app.config import is_lite_mode, is_standard_mode
# DISABLE_RATE_LIMIT=True 时关闭限流(调试用)
_disable_flag = os.getenv("DISABLE_RATE_LIMIT", "").strip().lower()
_rate_limit_disabled = _disable_flag == "true"
# 根据 APP_MODE 动态设置速率限制
# Lite 模式:30/minute(单轮问答响应快,3-5秒/次)
# Standard 模式:25/minute(完整上下文,支持 thinking 和搜索)
# Heavy 模式:20/minute(需要数据库操作,相对慢一些)
if is_lite_mode():
default_limit = "30/minute"
elif is_standard_mode():
default_limit = "25/minute"
else:
default_limit = "20/minute"
limiter = Limiter(
key_func=get_remote_address,
default_limits=[] if _rate_limit_disabled else [default_limit],
enabled=not _rate_limit_disabled,
)
+41
View File
@@ -0,0 +1,41 @@
import logging
import json
import time
from datetime import datetime
class JsonFormatter(logging.Formatter):
"""自定义 JSON 格式化器"""
def format(self, record):
log_record = {
"timestamp": datetime.fromtimestamp(record.created).isoformat(),
"level": record.levelname,
"message": record.getMessage(),
}
# 提取自定义 extra 字段
if hasattr(record, "request_info"):
log_record.update(record.request_info)
# 如果有异常,记录 trace
if record.exc_info:
log_record["exception"] = self.formatException(record.exc_info)
return json.dumps(log_record, ensure_ascii=False)
def setup_logger(name="notion_opus"):
"""配置并返回单例全局 logger"""
logger = logging.getLogger(name)
# 防止重复添加 handler
if not logger.handlers:
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(JsonFormatter())
logger.addHandler(console_handler)
return logger
# 全局单例 logger 实例
logger = setup_logger()
+138
View File
@@ -0,0 +1,138 @@
MODEL_MAP: dict[str, str] = {
"gpt-5.6-sol": "orange-mousse",
"gpt-5.6-terra": "orchid-muffin",
"gpt-5.6-luna": "olive-jellyroll",
"gpt-5.4": "oval-kumquat-medium",
"gpt-5.5": "opal-quince-medium",
"gemini-3.5flash": "vertex-gemini-3.5-flash",
"claude-sonnet4.6": "almond-croissant-low",
"claude-sonnet5": "angel-cake-high",
"claude-opus4.6": "avocado-froyo-medium",
"claude-opus4.7": "apricot-sorbet-high",
"claude-opus4.8": "ambrosia-tart-high",
"claude-opus5": "agave-flan",
"kimi-2.7": "fireworks-kimi-k2.7",
"deepseek-v4pro": "baseten-deepseek-v4-pro",
"glm-5.2": "baseten-glm-5.2",
"grok-4.3": "xigua-mochi-medium",
"spacexai-4.5": "strawberry-whoopiepie",
"grok-build0.1": "xinomavro-cake",
"gemini-3.1pro": "galette-medium-thinking",
"claude-haiku4.5": "anthropic-haiku-4.5",
"fable-5": "acai-budino-high",
"gemini-3flash": "gingerbread",
"gpt-6-astra": "orlando-quinn",
}
NOTION_MODEL_REVERSE_MAP: dict[str, str] = {value: key for key, value in MODEL_MAP.items()}
DISPLAY_NAMES: dict[str, str] = {
"gpt-5.6-sol": "GPT-5.6 Sol",
"gpt-5.6-terra": "GPT-5.6 Terra",
"gpt-5.6-luna": "GPT-5.6 Luna",
"gpt-5.4": "GPT-5.4",
"gpt-5.5": "GPT-5.5",
"gemini-3.5flash": "Gemini 3.5 Flash",
"claude-sonnet4.6": "Sonnet 4.6",
"claude-sonnet5": "Sonnet 5",
"claude-opus4.6": "Opus 4.6",
"claude-opus4.7": "Opus 4.7",
"claude-opus4.8": "Opus 4.8",
"claude-opus5": "Opus 5",
"kimi-2.7": "Kimi K2.7 Code",
"deepseek-v4pro": "DeepSeek V4 Pro",
"glm-5.2": "GLM 5.2",
"grok-4.3": "Grok 4.3",
"spacexai-4.5": "SpaceXAI 4.5",
"grok-build0.1": "Grok Build 0.1",
"gemini-3.1pro": "Gemini 3.1 Pro",
"claude-haiku4.5": "Haiku 4.5",
"fable-5": "Fable 5",
"gemini-3flash": "Gemini 3 Flash",
"gpt-6-astra": "GPT-6 Astra",
}
MODEL_ICONS: dict[str, str] = {
"gpt-5.6-sol": "⚙",
"gpt-5.6-terra": "⚙",
"gpt-5.6-luna": "⚙",
"gpt-5.4": "⚙",
"gpt-5.5": "⚙",
"gemini-3.5flash": "✦",
"claude-sonnet4.6": "✳️",
"claude-sonnet5": "✳️",
"claude-opus4.6": "✳️",
"claude-opus4.7": "✳️",
"claude-opus4.8": "✳️",
"claude-opus5": "✳️",
"kimi-2.7": "🌙",
"deepseek-v4pro": "🐋",
"glm-5.2": "◆",
"grok-4.3": "⚡",
"spacexai-4.5": "⚡",
"grok-build0.1": "⚡",
"gemini-3.1pro": "✦",
"claude-haiku4.5": "✳️",
"fable-5": "◇",
"gemini-3flash": "✦",
"gpt-6-astra": "⚙",
}
# 默认使用 Sonnet 4.6(速度和质量的最佳平衡)
DEFAULT_MODEL = "claude-sonnet4.6"
def get_notion_model(model_name: str) -> str:
return MODEL_MAP.get(model_name, MODEL_MAP[DEFAULT_MODEL])
# 需要走 markdown-chat 的 Notion 内部代号(vertex- 前缀的模型)
# Gemini 3.1 Pro (galette-medium-thinking) 已改为 workflow,不再走 markdown-chat
MARKDOWN_CHAT_MODELS: set[str] = {
"vertex-gemini-3.5-flash",
}
def is_gemini_model(model_name: str) -> bool:
"""判断是否为 Gemini 系列模型(用于 config block 构建等)"""
standard_name = get_standard_model(model_name)
if standard_name.startswith("gemini-"):
return True
notion_model = get_notion_model(standard_name)
return notion_model.startswith("vertex-") or notion_model.startswith("galette-")
def get_thread_type(model_name: str) -> str:
"""
根据模型确定 Notion thread type。
只有 vertex- 前缀的模型走 markdown-chat,其余全部走 workflow。
"""
standard_name = get_standard_model(model_name)
notion_model = get_notion_model(standard_name)
if notion_model in MARKDOWN_CHAT_MODELS:
return "markdown-chat"
return "workflow"
def get_standard_model(model_name: str) -> str:
if model_name in MODEL_MAP:
return model_name
return NOTION_MODEL_REVERSE_MAP.get(model_name, DEFAULT_MODEL)
def list_available_models() -> list[str]:
return list(MODEL_MAP.keys())
def is_supported_model(model_name: str) -> bool:
return model_name in MODEL_MAP
def get_display_name(model_name: str) -> str:
standard_name = get_standard_model(model_name)
return DISPLAY_NAMES.get(standard_name, standard_name)
def get_model_icon(model_name: str) -> str:
standard_name = get_standard_model(model_name)
return MODEL_ICONS.get(standard_name, "")
+410
View File
@@ -0,0 +1,410 @@
import os
import threading
import time
import uuid
from typing import Any, Generator, Optional
import cloudscraper
import requests
import urllib3
from app.logger import logger
from app.model_registry import get_notion_model
from app.stream_parser import parse_stream
# 禁用 SSL 警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 可通过环境变量覆盖 Notion 客户端版本号(Notion 更新后可能需要同步)
NOTION_CLIENT_VERSION = os.getenv("NOTION_CLIENT_VERSION", "23.13.20260228.0625")
# Notion 站点根地址(区域镜像 / 反代时可覆盖);未设置时保持官方默认
NOTION_URL = os.getenv("NOTION_URL", "https://www.notion.so").rstrip("/")
class NotionUpstreamError(RuntimeError):
"""Notion 上游请求失败或返回异常内容。"""
def __init__(
self,
message: str,
*,
status_code: Optional[int] = None,
retriable: bool = True,
response_excerpt: str = "",
):
super().__init__(message)
self.status_code = status_code
self.retriable = retriable
self.response_excerpt = response_excerpt
class NotionOpusAPI:
def __init__(self, account_config: dict):
"""
从单组账号配置初始化 Notion 客户端。
account_config 需要包含 token_v2, space_id, user_id, space_view_id, user_name, user_email
"""
self.token_v2 = account_config.get("token_v2", "")
self.space_id = account_config.get("space_id", "")
self.user_id = account_config.get("user_id", "")
self.space_view_id = account_config.get("space_view_id", "")
self.user_name = account_config.get("user_name", "user")
self.user_email = account_config.get("user_email", "")
self.cookies = account_config.get("cookies", {})
if not isinstance(self.cookies, dict):
self.cookies = {}
self.cookies["token_v2"] = self.token_v2
self.url = f"{NOTION_URL}/api/v3/runInferenceTranscript"
self.delete_url = f"{NOTION_URL}/api/v3/saveTransactions"
self.account_key = self.user_email or self.user_id or "unknown-account"
# 复用 cloudscraper 实例:保留 Cloudflare challenge cookie,避免每次请求都重新过验证
self._scraper = cloudscraper.create_scraper()
self._scraper_lock = threading.Lock()
def _build_cookie_header(self) -> str:
cookie_jar = self.cookies.copy()
cookie_jar["notion_user_id"] = self.user_id
return "; ".join(f"{name}={value}" for name, value in cookie_jar.items() if value)
def _to_notion_transcript(self, transcript: list[dict[str, Any]]) -> list[dict[str, Any]]:
converted: list[dict[str, Any]] = []
for block in transcript:
if block.get("type") != "config":
converted.append(block)
continue
value = block.get("value")
if not isinstance(value, dict):
converted.append(block)
continue
notion_block = dict(block)
notion_value = dict(value)
notion_value["model"] = get_notion_model(str(value.get("model", "") or ""))
notion_block["value"] = notion_value
converted.append(notion_block)
return converted
def _resolve_thread_type(self, notion_transcript: list[dict[str, Any]]) -> str:
for block in notion_transcript:
if block.get("type") != "config":
continue
value = block.get("value")
if isinstance(value, dict):
thread_type = str(value.get("type", "") or "").strip()
if thread_type:
return thread_type
return "workflow"
def _resolve_request_profile(self, thread_type: str) -> dict[str, Any]:
is_markdown_chat = thread_type == "markdown-chat"
return {
"thread_type": thread_type,
"create_thread": not is_markdown_chat,
"is_partial_transcript": is_markdown_chat,
"precreate_thread": is_markdown_chat,
"include_debug_overrides": True,
}
def _build_thread_headers(self) -> dict[str, str]:
return {
"content-type": "application/json",
"cookie": self._build_cookie_header(),
"x-notion-active-user-header": self.user_id,
"x-notion-space-id": self.space_id,
}
def _create_thread(self, thread_id: str, thread_type: str) -> bool:
payload = {
"requestId": str(uuid.uuid4()),
"transactions": [
{
"id": str(uuid.uuid4()),
"spaceId": self.space_id,
"operations": [
{
"pointer": {"table": "thread", "id": thread_id, "spaceId": self.space_id},
"path": [],
"command": "set",
"args": {
"id": thread_id,
"version": 1,
"parent_id": self.space_id,
"parent_table": "space",
"space_id": self.space_id,
"created_time": int(time.time() * 1000),
"created_by_id": self.user_id,
"created_by_table": "notion_user",
"messages": [],
"data": {},
"alive": True,
"type": thread_type,
},
}
],
}
],
}
try:
resp = requests.post(
self.delete_url,
json=payload,
headers=self._build_thread_headers(),
timeout=20,
)
if resp.status_code == 200:
return True
logger.warning(
"Pre-create thread failed",
extra={
"request_info": {
"event": "thread_precreate_failed",
"thread_id": thread_id,
"thread_type": thread_type,
"status": resp.status_code,
}
},
)
except Exception:
logger.warning(
"Pre-create thread raised exception",
exc_info=True,
extra={
"request_info": {
"event": "thread_precreate_error",
"thread_id": thread_id,
"thread_type": thread_type,
}
},
)
return False
def delete_thread(self, thread_id: str) -> None:
"""
通过 saveTransactions 接口将指定 thread 的 alive 状态设为 False,
从而清理 Notion 主页面上的对话记录。
此方法设计为在后台线程中调用,不影响主流输出。
"""
headers = self._build_thread_headers()
payload = {
"requestId": str(uuid.uuid4()),
"transactions": [
{
"id": str(uuid.uuid4()),
"spaceId": self.space_id,
"operations": [
{
"pointer": {
"table": "thread",
"id": thread_id,
"spaceId": self.space_id,
},
"command": "update",
"path": [],
"args": {"alive": False},
}
],
}
],
}
try:
resp = requests.post(self.delete_url, json=payload, headers=headers, timeout=15)
if resp.status_code == 200:
logger.info(
"Thread auto-deleted from Notion home",
extra={"request_info": {"event": "thread_deleted", "thread_id": thread_id}},
)
else:
logger.warning(
f"Thread deletion failed: HTTP {resp.status_code}",
extra={"request_info": {"event": "thread_delete_failed", "thread_id": thread_id, "status": resp.status_code}},
)
except Exception as exc:
logger.warning(
f"Thread deletion raised an exception: {exc}",
extra={"request_info": {"event": "thread_delete_error", "thread_id": thread_id}},
)
def stream_response(self, transcript: list, thread_id: Optional[str] = None) -> Generator[dict[str, Any], None, None]:
"""
发起 Notion API 请求并返回结构化流生成器。
接收完整的 transcript 列表作为参数。
Args:
transcript: 对话历史记录列表
thread_id: 可选的已有 thread_id。如果提供,将重用该线程以保持上下文
"""
if not isinstance(transcript, list) or not transcript:
raise ValueError("Invalid transcript payload: transcript must be a non-empty list.")
notion_transcript = self._to_notion_transcript(transcript)
thread_type = self._resolve_thread_type(notion_transcript)
request_profile = self._resolve_request_profile(thread_type)
# 如果没有提供 thread_id,创建新的;否则重用已有的
should_create_thread = thread_id is None
thread_id = thread_id or str(uuid.uuid4())
trace_id = str(uuid.uuid4())
response = None
# 保存 thread_id 以便外部访问
self.current_thread_id = thread_id
if request_profile["precreate_thread"] and should_create_thread:
if not self._create_thread(thread_id, thread_type):
should_create_thread = True
request_profile["create_thread"] = True
request_profile["is_partial_transcript"] = False
elif not should_create_thread:
# 如果重用已有线程,不要创建新线程
request_profile["create_thread"] = False
# 关键修复:设置 is_partial_transcript=True,让 Notion 接受客户端的历史消息
request_profile["is_partial_transcript"] = True
# 把 cookie 直接放进 header,绕过 cloudscraper 的 cookie jar
# (cookie jar 可能被 Cloudflare challenge 写入含非 ASCII 字符的 cookie,导致编码错误)
cookie_header = self._build_cookie_header()
# ВАЖНО (2026-09-06): апстрим отдаёт пустой стрим без браузерного фингерпринта
# (проверено A/B: те же payload/token/IP — с sec-fetch + свежим UA идёт NDJSON, без них пусто).
headers = {
"Content-Type": "application/json",
"Accept": "application/x-ndjson",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
"x-notion-space-id": self.space_id,
"x-notion-active-user-header": self.user_id,
"notion-audit-log-platform": "web",
"notion-client-version": NOTION_CLIENT_VERSION,
"origin": NOTION_URL,
"referer": f"{NOTION_URL}/chat",
"sec-ch-ua": '"Chromium";v="152", "Not?A_Brand";v="24", "Google Chrome";v="152"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Linux"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"cookie": cookie_header,
}
payload = {
"traceId": trace_id,
"spaceId": self.space_id,
"threadId": thread_id,
"threadType": thread_type,
"createThread": request_profile["create_thread"],
"generateTitle": True,
"saveAllThreadOperations": True,
"setUnreadState": True,
"isPartialTranscript": request_profile["is_partial_transcript"],
"asPatchResponse": True,
"isUserInAnySalesAssistedSpace": False,
"isSpaceSalesAssisted": False,
"threadParentPointer": {
"table": "space",
"id": self.space_id,
"spaceId": self.space_id,
},
"transcript": notion_transcript,
}
if request_profile["include_debug_overrides"]:
payload["debugOverrides"] = {
"emitAgentSearchExtractedResults": True,
"cachedInferences": {},
"annotationInferences": {},
"emitInferences": False,
}
logger.info(
"Dispatching request to Notion upstream",
extra={
"request_info": {
"event": "notion_upstream_request",
"trace_id": trace_id,
"thread_id": thread_id,
"thread_type": thread_type,
"create_thread": bool(request_profile["create_thread"]),
"is_partial_transcript": bool(request_profile["is_partial_transcript"]),
"account": self.account_key,
"space_id": self.space_id,
}
},
)
try:
with self._scraper_lock:
scraper = self._scraper
scraper.cookies.clear()
response = scraper.post(
self.url,
headers=headers,
json=payload,
stream=True,
timeout=(15, 120),
)
if response.status_code == 403:
# Cloudflare challenge 可能过期,重建 scraper 后重试一次
response.close()
logger.warning(
"Got 403, rebuilding cloudscraper to refresh Cloudflare challenge",
extra={"request_info": {"event": "cloudflare_challenge_refresh", "account": self.account_key}},
)
new_scraper = cloudscraper.create_scraper()
with self._scraper_lock:
self._scraper = new_scraper
response = new_scraper.post(
self.url,
headers=headers,
json=payload,
stream=True,
timeout=(15, 120),
)
if response.status_code != 200:
excerpt = (response.text or "").strip().replace("\n", " ")[:300]
# 429 和 5xx 都允许重试(换账号或等待后重试)
retriable = response.status_code >= 500 or response.status_code == 429
raise NotionUpstreamError(
f"Notion upstream returned HTTP {response.status_code}.",
status_code=response.status_code,
retriable=retriable,
response_excerpt=excerpt,
)
emitted = False
for chunk in parse_stream(response):
emitted = True
yield chunk
if not emitted:
raise NotionUpstreamError(
"Notion upstream returned an empty stream.",
status_code=502,
retriable=True,
)
# 流结束后,不再自动删除 thread
# 原因:Notion API 的 workflow 模式依赖于服务器端保存的对话历史
# 删除 thread 会导致后续请求无法获取历史消息(AI 失忆)
# 保持 thread 存活可以维持对话上下文
logger.info(
"Thread completed and preserved for conversation context",
extra={
"request_info": {
"event": "thread_completed_preserved",
"thread_id": thread_id,
"was_created_new": should_create_thread,
}
},
)
except requests.exceptions.Timeout as exc:
logger.error(f"Request timeout: {exc}", exc_info=True)
raise NotionUpstreamError("Request to Notion upstream timed out.", retriable=True) from exc
except requests.exceptions.RequestException as exc:
logger.error(f"Request failed: {exc}", exc_info=True)
# 不暴露原始异常细节给用户
raise NotionUpstreamError("Request to Notion upstream failed. Please try again later.", retriable=True) from exc
finally:
if response is not None:
response.close()
+93
View File
@@ -0,0 +1,93 @@
import time
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field, field_validator
# ================================
# 请求相关 Schema (Chat Completion)
# ================================
class ChatMessage(BaseModel):
"""单条对话消息"""
role: Literal["user", "assistant", "system"]
content: str
thinking: Optional[str] = None
@field_validator("content", mode="before")
@classmethod
def _coerce_content_parts(cls, v):
# OpenAI-style content parts (отправляют omp и др. клиенты) → plain text.
# Не-текстовые части (image_url и т.п.) мост не поддерживает и молча отбрасывает.
if v is None:
return ""
if isinstance(v, str):
return v
if isinstance(v, list):
texts = []
for part in v:
if isinstance(part, dict) and part.get("type") == "text":
texts.append(part.get("text") or "")
elif isinstance(part, str):
texts.append(part)
return "".join(texts)
return str(v)
class ChatCompletionRequest(BaseModel):
"""
OpenAI-Compatible 发起完成请求的 Payload。
保留 `conversation_id` 作为特定的扩展字段,若缺失则视为独立请求。
"""
model: str = Field(default="claude-opus4.6", description="Requested model.")
messages: List[ChatMessage]
stream: bool = Field(default=False, description="Whether to stream the response as SSE.")
temperature: Optional[float] = Field(default=None, description="Sampling temperature.")
conversation_id: Optional[str] = Field(default=None, description="Extension for stateful conversation tracking.")
# ================================
# 非流式返回 Schema
# ================================
class ChatMessageResponseChoice(BaseModel):
"""非流式响应的选项"""
index: int = 0
message: ChatMessage
finish_reason: str = "stop"
class ChatCompletionResponse(BaseModel):
"""
OpenAI-Compatible 完整返回 Payload。
"""
id: str
object: str = "chat.completion"
created: int = Field(default_factory=lambda: int(time.time()))
model: str
choices: List[ChatMessageResponseChoice]
usage: Dict[str, int] = Field(
default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
)
# Standard 模式扩展字段
search_metadata: Optional[Dict[str, Any]] = Field(default=None)
# ================================
# 流式返回 Schema (供内部组织)
# ================================
class ChatCompletionChunkDelta(BaseModel):
"""SSE Delta Block"""
content: Optional[str] = None
role: Optional[str] = None
class ChatCompletionChunkChoice(BaseModel):
"""SSE Choice Block"""
index: int = 0
delta: ChatCompletionChunkDelta
finish_reason: Optional[str] = None
class ChatCompletionChunk(BaseModel):
"""
OpenAI-Compatible 流式 Chunk
"""
id: str
object: str = "chat.completion.chunk"
created: int = Field(default_factory=lambda: int(time.time()))
model: str
choices: List[ChatCompletionChunkChoice]
+172
View File
@@ -0,0 +1,172 @@
import time
import os
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from slowapi.errors import RateLimitExceeded
from contextlib import asynccontextmanager
from app.config import ACCOUNTS, API_KEY, ALLOWED_ORIGINS, is_lite_mode, is_standard_mode
from app.account_pool import AccountPool
from app.conversation import ConversationManager
from app.api.chat import router as chat_router
from app.api.models import router as models_router
from app.logger import logger
from app.limiter import limiter
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时初始化状态
app.state.account_pool = AccountPool(ACCOUNTS)
# 确定运行模式
if is_lite_mode():
mode = "lite"
logger.info("Service starting up in LITE mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "lite"}})
elif is_standard_mode():
mode = "standard"
logger.info("Service starting up in STANDARD mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "standard"}})
else:
mode = "heavy"
app.state.conversation_manager = ConversationManager()
logger.info("Service starting up in HEAVY mode", extra={"request_info": {"event": "startup", "accounts": len(ACCOUNTS), "mode": "heavy"}})
app.state.start_time = time.time()
yield
# 关闭时清理
logger.info("Service shutting down", extra={"request_info": {"event": "shutdown"}})
app = FastAPI(
title="Notion Opus API",
description="A FastAPI wrapper providing an OpenAI-compatible interface for Notion's Claude Opus backend.",
version="1.0.0",
lifespan=lifespan
)
# 允许跨域(配合本地前端)
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注入 Limiter
app.state.limiter = limiter
# 自定义 429 速率限制响应
def custom_rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
return JSONResponse(
status_code=429,
content={"error": "Too many requests, please try again later"}
)
app.add_exception_handler(RateLimitExceeded, custom_rate_limit_exceeded_handler)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
logger.error(
"Unhandled application exception",
exc_info=True,
extra={
"request_info": {
"event": "unhandled_exception",
"method": request.method,
"path": request.url.path,
}
},
)
return JSONResponse(
status_code=500,
content={
"error": {
"message": "Internal server error",
"type": "server_error",
}
},
)
# 结构化日志中间件
@app.middleware("http")
async def log_requests_middleware(request: Request, call_next):
start_time = time.time()
# 跳过高频且不重要的日志打印,避免刷屏
skip_logging = request.url.path in ["/health", "/favicon.ico"]
try:
response = await call_next(request)
status_code = response.status_code
except Exception as e:
status_code = 500
logger.error(f"Unhandled exception: {str(e)}", exc_info=True)
raise
finally:
process_time = time.time() - start_time
client_ip = request.client.host if request.client else "unknown"
if not skip_logging:
log_level = logger.error if status_code >= 400 else logger.info
log_level(
"Request processed",
extra={
"request_info": {
"method": request.method,
"path": request.url.path,
"ip": client_ip,
"status_code": status_code,
"duration_ms": round(process_time * 1000, 2)
}
}
)
return response
# 简易 API Key 鉴权中间件
@app.middleware("http")
async def api_key_auth(request: Request, call_next):
# 如果环境配置中未设置 API_KEY,则全局不验证
if API_KEY:
# 跳过 OPTIONS 请求和非受保护的静态路由(如果以后有的话)
if request.url.path.startswith("/v1") and request.method != "OPTIONS":
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer ") or auth_header.split(" ")[1] != API_KEY:
return JSONResponse(
status_code=401,
content={
"error": {
"message": "Error: API KEY doesn't match.",
"type": "invalid_request_error",
"code": "invalid_api_key"
}
}
)
return await call_next(request)
# 挂载路由,前缀统一为 /v1
app.include_router(chat_router, prefix="/v1")
app.include_router(models_router, prefix="/v1")
# 挂载健康检查
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
return Response(content=b"", media_type="image/x-icon", status_code=204)
@app.get("/health", tags=["system"])
def health_check(request: Request):
uptime = time.time() - request.app.state.start_time
pool = request.app.state.account_pool
status = pool.get_status_summary()
return {
"status": "ok",
"accounts": status["active"],
"accounts_total": status["total"],
"accounts_cooling": status["cooling"],
"uptime": int(uptime)
}
# 挂载静态前端到根目录
frontend_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "frontend")
if os.path.exists(frontend_dir):
app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend")
+1013
View File
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
import httpx
from app.config import SILICONFLOW_API_KEY
class SummarizerUnavailableError(Exception):
"""Raised when summarizer service cannot be used."""
SILICONFLOW_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions"
MODEL_FALLBACK_CHAIN = ["Qwen/Qwen3-8B", "THUDM/glm-4-9b-chat"]
SYSTEM_PROMPT = (
"你是一个对话摘要助手。请将用户提供的一轮对话(一问一答)压缩成1~3句话的简洁摘要。\n"
"要求:保留关键信息(话题、结论、重要细节),去除废话,语言简洁,使用与对话相同的语言。\n\n"
"只输出摘要本身,不要有任何前缀或解释。"
)
def is_summarizer_configured() -> bool:
return bool(SILICONFLOW_API_KEY.strip())
def _build_user_prompt(old_summaries: list[str], user_msg: str, assistant_msg: str) -> str:
prompt_parts = []
if old_summaries:
prompt_parts.append("【已有上下文摘要(仅供参考,勿重复)】")
prompt_parts.append("\n".join(old_summaries[-5:]))
prompt_parts.append("")
prompt_parts.append("【本轮对话】")
prompt_parts.append(f"用户:{user_msg}")
prompt_parts.append(f"AI:{assistant_msg}")
prompt_parts.append("")
prompt_parts.append("请输出本轮摘要:")
return "\n".join(prompt_parts)
async def _call_summarizer(model: str, old_summaries: list[str], user_msg: str, assistant_msg: str) -> str:
timeout = httpx.Timeout(connect=5.0, read=20.0, write=20.0, pool=20.0)
headers = {
"Authorization": f"Bearer {SILICONFLOW_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": _build_user_prompt(old_summaries, user_msg, assistant_msg)},
],
"temperature": 0.2,
}
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.post(SILICONFLOW_ENDPOINT, headers=headers, json=payload)
if response.status_code != 200:
raise SummarizerUnavailableError(f"Summarizer upstream returned status {response.status_code}")
data = response.json()
content = (
data.get("choices", [{}])[0]
.get("message", {})
.get("content", "")
)
summary = str(content).strip()
if not summary:
raise SummarizerUnavailableError("Summarizer returned empty summary")
return summary
async def summarize_turn(
old_summaries: list[str],
user_msg: str,
assistant_msg: str,
) -> str:
"""
调用 LLM 将一轮对话压缩为简短摘要,返回摘要字符串。失败时抛出异常。
"""
if not is_summarizer_configured():
raise SummarizerUnavailableError("SILICONFLOW_API_KEY is empty")
last_error: Exception | None = None
for model in MODEL_FALLBACK_CHAIN:
try:
return await _call_summarizer(model, old_summaries, user_msg, assistant_msg)
except Exception as exc:
last_error = exc
continue
raise SummarizerUnavailableError(
f"All summarizer models failed: {last_error}"
) from last_error
+65
View File
@@ -0,0 +1,65 @@
# ============================================================
# Notion AI Wrapper - Docker Compose Configuration
# ============================================================
# Quick Start:
# docker-compose up -d
# docker-compose logs -f
#
# Check Health:
# curl http://localhost:8000/health
#
# Update & Restart:
# docker-compose down
# docker-compose build --no-cache
# docker-compose up -d
# ============================================================
services:
notion-ai:
build:
context: .
dockerfile: Dockerfile
image: notion-ai-wrapper:latest
container_name: notion_ai_service
restart: always
# Port mapping: Use HOST_PORT env var or default to 8000
ports:
- "${HOST_PORT:-8000}:8000"
# Environment configuration
env_file:
- .env
environment:
- DB_PATH=/app/data/conversations.db
- PYTHONUNBUFFERED=1
- TZ=Asia/Shanghai
# Data persistence + account config
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./accounts.json:/app/accounts.json:ro
# Resource limits (prevents container from using all system resources)
deploy:
resources:
limits:
memory: 1G
reservations:
memory: 256M
# Health check (Docker will restart if unhealthy)
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
# Log rotation (prevents logs from filling disk)
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
+735
View File
@@ -0,0 +1,735 @@
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
# pylint: disable=broad-exception-caught,line-too-long
# pylint: disable=consider-using-with,too-many-locals
from __future__ import annotations
import argparse
import os
import json
import shutil
import socket
import subprocess
import tempfile
import time
import webbrowser
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Sequence
from urllib.request import urlopen
import requests
from websocket import create_connection
# 与 app/notion_client.py 一致:支持区域镜像 / 反代,默认官方站点
NOTION_URL = os.getenv("NOTION_URL", "https://www.notion.so").rstrip("/")
NOTION_DOMAIN = os.getenv("NOTION_DOMAIN", "www.notion.so").lstrip(".")
BASE_URL = NOTION_URL
AI_URL = f"{NOTION_URL}/ai"
# CDP 页面识别用的主机名片段(自定义域名时填 NOTION_DOMAIN 即可)
_NOTION_HOST_HINT = (
NOTION_DOMAIN.removeprefix("www.")
if NOTION_DOMAIN.startswith("www.")
else NOTION_DOMAIN
)
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
)
ACCOUNTS_FILE = Path(__file__).resolve().parent / "accounts.json"
ENV_FILE = Path(__file__).resolve().parent / ".env"
DEFAULT_PROFILE = "default"
DEFAULT_DEBUG_PORT = 9222
DEFAULT_LOGIN_TIMEOUT = 300
@dataclass(frozen=True)
class NotionAccount:
profile_name: str
token_v2: str
space_id: str
user_id: str
space_view_id: str
user_name: str
user_email: str
cookies: dict[str, str]
def with_profile(self, profile_name: str) -> "NotionAccount":
return replace(self, profile_name=profile_name or DEFAULT_PROFILE)
def to_dict(self) -> dict[str, Any]:
return {
"profile_name": self.profile_name or DEFAULT_PROFILE,
"token_v2": self.token_v2,
"space_id": self.space_id,
"user_id": self.user_id,
"space_view_id": self.space_view_id,
"user_name": self.user_name,
"user_email": self.user_email,
"cookies": self.cookies,
}
def _print_header() -> None:
print("=" * 60)
print("Notion2API Login")
print("=" * 60)
print("This helper saves named Notion profiles into accounts.json.")
print("Default flow: launch a local Chrome window, wait for sign-in, and extract token_v2.")
print("Use --manual to paste token_v2 if Chrome is unavailable.")
def _open_login_page() -> None:
try:
webbrowser.open(AI_URL, new=2)
print(f"Opened {AI_URL} in your browser.")
except Exception:
print(f"Open this page manually: {AI_URL}")
def _prompt_token() -> str:
print()
print("Step 1: Sign in to Notion in the browser window.")
print("Step 2: Copy your token_v2 value from the Notion cookie store.")
print("Step 3: Paste it below.")
token = input("\nPaste token_v2: ").strip()
if not token:
raise ValueError("token_v2 is required")
return token
def _find_free_port(start: int = DEFAULT_DEBUG_PORT, end: int = DEFAULT_DEBUG_PORT + 20) -> int:
for port in range(start, end + 1):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(("127.0.0.1", port))
except OSError:
continue
return port
raise RuntimeError("No free debugging port found")
def _get_json(url: str, timeout: int = 2) -> Any:
with urlopen(url, timeout=timeout) as response:
payload = response.read().decode("utf-8", errors="replace")
return json.loads(payload)
def _find_chrome_executable() -> str | None:
env_path = os.getenv("CHROME_PATH")
if env_path:
candidate = Path(env_path).expanduser()
if candidate.exists():
return str(candidate)
candidates = [
"chrome.exe",
"chrome",
"google-chrome",
"google-chrome-stable",
"msedge.exe",
"msedge",
]
for name in candidates:
resolved = shutil.which(name)
if resolved:
return resolved
program_files = [
os.getenv("PROGRAMFILES"),
os.getenv("PROGRAMFILES(X86)"),
os.getenv("LOCALAPPDATA"),
]
suffixes = [
r"Google\Chrome\Application\chrome.exe",
r"Google\Chrome Beta\Application\chrome.exe",
r"Google\Chrome Canary\Application\chrome.exe",
r"Microsoft\Edge\Application\msedge.exe",
]
for root in program_files:
if not root:
continue
for suffix in suffixes:
candidate = Path(root) / suffix
if candidate.exists():
return str(candidate)
return None
def _start_chrome_debug_session(port: int) -> tuple[subprocess.Popen[bytes], Path]:
chrome = _find_chrome_executable()
if not chrome:
raise FileNotFoundError("Chrome or Edge executable not found")
profile_dir = Path(tempfile.mkdtemp(prefix="notion2api-chrome-profile-"))
args = [
chrome,
f"--remote-debugging-port={port}",
"--remote-allow-origins=*",
f"--user-data-dir={profile_dir}",
"--no-first-run",
"--no-default-browser-check",
"--start-maximized",
"--new-window",
AI_URL,
]
process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return process, profile_dir
class _CDPClient:
def __init__(self, ws_url: str) -> None:
self._ws = create_connection(ws_url, timeout=5)
self._next_id = 1
def call(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
message_id = self._next_id
self._next_id += 1
self._ws.send(json.dumps({"id": message_id, "method": method, "params": params or {}}))
while True:
response = json.loads(self._ws.recv())
if response.get("id") == message_id:
if response.get("error"):
raise RuntimeError(str(response["error"]))
result = response.get("result", {})
return result if isinstance(result, dict) else {}
def call_raw(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
return self.call(method, params)
def close(self) -> None:
try:
self._ws.close()
except Exception:
pass
def _find_debug_target(port: int) -> dict[str, Any] | None:
try:
targets = _get_json(f"http://127.0.0.1:{port}/json/list")
except Exception:
return None
items = targets if isinstance(targets, list) else targets.get("result")
if not isinstance(items, list):
return None
for item in items:
if not isinstance(item, dict):
continue
url = str(item.get("url") or "")
if _NOTION_HOST_HINT in url or "accounts.google.com" in url:
return item
return items[0] if items else None
def _parse_cookie_string(cookie_string: str) -> dict[str, str]:
cookies: dict[str, str] = {}
for part in cookie_string.split(";"):
part = part.strip()
if "=" in part:
name, _, value = part.partition("=")
name = name.strip()
value = value.strip()
if name:
cookies[name] = value
return cookies
def _extract_cookies_from_cdp(port: int) -> dict[str, str]:
target = _find_debug_target(port)
if not target:
raise RuntimeError("Chrome debugging target not available yet")
ws_url = target.get("webSocketDebuggerUrl")
if not ws_url:
raise RuntimeError("Chrome debugging target missing websocket URL")
client = _CDPClient(str(ws_url))
try:
client.call("Page.enable")
client.call("Network.enable")
try:
current_url = client.call("Runtime.evaluate", {"expression": "location.href", "returnByValue": True})
current_href = str(current_url.get("result", {}).get("value") or "") if isinstance(current_url, dict) else ""
if _NOTION_HOST_HINT not in current_href:
client.call("Page.navigate", {"url": AI_URL})
time.sleep(2)
except Exception:
pass
cookies: dict[str, str] = {}
try:
cookie_eval = client.call(
"Runtime.evaluate",
{"expression": "document.cookie", "returnByValue": True},
)
cookie_string = ""
if isinstance(cookie_eval, dict):
cookie_string = str(cookie_eval.get("result", {}).get("value") or "")
cookies.update(_parse_cookie_string(cookie_string))
except Exception:
pass
cookie_result = client.call("Network.getCookies", {"urls": [BASE_URL, AI_URL]})
cookies_list = cookie_result.get("cookies", [])
if not isinstance(cookies_list, list):
return cookies
for item in cookies_list:
if not isinstance(item, dict):
continue
name = str(item.get("name") or "").strip()
value = str(item.get("value") or "").strip()
if name:
cookies[name] = value
return cookies
finally:
client.close()
def _wait_for_browser_cookies(port: int, timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> dict[str, str]:
started = time.time()
last_error = ""
while time.time() - started < timeout_seconds:
try:
cookies = _extract_cookies_from_cdp(port)
except Exception as exc:
cookies = {}
message = str(exc)
if message and message != last_error:
print(f"Chrome DevTools not ready yet: {message}")
last_error = message
token_v2 = cookies.get("token_v2", "").strip()
if token_v2:
return cookies
print("Waiting for token_v2... sign in to the opened Chrome window.")
time.sleep(5)
raise TimeoutError("Timed out waiting for token_v2 in Chrome")
def _launch_and_extract_cookies(timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> dict[str, str]:
port = _find_free_port()
process, profile_dir = _start_chrome_debug_session(port)
try:
try:
_get_json(f"http://127.0.0.1:{port}/json/version", timeout=2)
except Exception:
pass
return _wait_for_browser_cookies(port, timeout_seconds=timeout_seconds)
finally:
try:
process.terminate()
process.wait(timeout=5)
except Exception:
try:
process.kill()
except Exception:
pass
try:
shutil.rmtree(profile_dir, ignore_errors=True)
except Exception:
pass
def _launch_and_extract_token(timeout_seconds: int = DEFAULT_LOGIN_TIMEOUT) -> str:
return _launch_and_extract_cookies(timeout_seconds=timeout_seconds).get("token_v2", "")
def _session_for_token(token_v2: str, cookies: dict[str, str] | None = None) -> requests.Session:
session = requests.Session()
cookie_values = dict(cookies or {})
cookie_values["token_v2"] = token_v2
session.headers.update(
{
"Origin": BASE_URL,
"Referer": AI_URL,
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
"Cookie": "; ".join(f"{name}={value}" for name, value in cookie_values.items() if value),
}
)
for name, value in cookie_values.items():
if not value:
continue
session.cookies.set(name, value, domain=NOTION_DOMAIN, path="/")
return session
def _safe_value(value: Any) -> dict[str, Any]:
if isinstance(value, dict):
inner = value.get("value")
if isinstance(inner, dict):
return inner
if inner is not None:
return {"value": inner}
return value
return {}
def _load_json_response(session: requests.Session, path: str) -> dict[str, Any]:
response = session.post(f"{BASE_URL}{path}", json={}, timeout=30)
response.raise_for_status()
payload = response.json()
return payload if isinstance(payload, dict) else {}
def _extract_candidates(token_v2: str, cookies: dict[str, str] | None = None) -> list[NotionAccount]:
cookies = cookies or {}
active_user_id = str(cookies.get("notion_user_id") or "").strip()
session = _session_for_token(token_v2, cookies)
try:
get_spaces = _load_json_response(session, "/api/v3/getSpaces")
except Exception:
get_spaces = {}
load_user_content = _load_json_response(session, "/api/v3/loadUserContent").get("recordMap", {})
users: dict[str, dict[str, str]] = {}
spaces: dict[str, dict[str, str]] = {}
space_views: dict[str, str] = {}
def add_users(source: dict[str, Any], target: dict[str, dict[str, str]]) -> None:
for user_id, raw in source.items():
v = _safe_value(raw)
target[user_id] = {
"name": str(v.get("given_name") or v.get("name") or v.get("family_name") or "").strip(),
"email": str(v.get("email") or "").strip(),
}
def add_spaces(source: dict[str, Any], target: dict[str, dict[str, str]]) -> None:
for space_id, raw in source.items():
v = _safe_value(raw)
target[space_id] = {
"name": str(v.get("name") or "").strip(),
"plan": str(v.get("plan_type") or v.get("subscription_tier") or "").strip(),
}
def add_space_views(source: dict[str, Any], target: dict[str, str]) -> None:
for space_view_id, raw in source.items():
v = _safe_value(raw)
space_id = str(v.get("space_id") or "").strip()
if space_id:
target.setdefault(space_id, space_view_id)
def accounts_from_maps(
account_users: dict[str, dict[str, str]],
account_spaces: dict[str, dict[str, str]],
account_space_views: dict[str, str],
) -> list[NotionAccount]:
accounts: list[NotionAccount] = []
for user_id, user_data in account_users.items():
for space_id in account_spaces:
accounts.append(
NotionAccount(
profile_name=DEFAULT_PROFILE,
token_v2=token_v2,
space_id=space_id,
user_id=user_id,
space_view_id=account_space_views.get(space_id, ""),
user_name=user_data["name"] or "user",
user_email=user_data["email"],
cookies=cookies,
)
)
return accounts
candidates: list[NotionAccount] = []
for raw_user_data in get_spaces.values():
if not isinstance(raw_user_data, dict):
continue
grouped_users: dict[str, dict[str, str]] = {}
grouped_spaces: dict[str, dict[str, str]] = {}
grouped_space_views: dict[str, str] = {}
add_users(raw_user_data.get("notion_user", {}), grouped_users)
add_spaces(raw_user_data.get("space", {}), grouped_spaces)
add_space_views(raw_user_data.get("space_view", {}), grouped_space_views)
users.update(grouped_users)
spaces.update(grouped_spaces)
space_views.update(grouped_space_views)
candidates.extend(accounts_from_maps(grouped_users, grouped_spaces, grouped_space_views))
add_users(load_user_content.get("notion_user", {}), users)
add_spaces(load_user_content.get("space", {}), spaces)
add_space_views(load_user_content.get("space_view", {}), space_views)
if not users:
raise ValueError("No Notion users were returned. The token may be invalid or expired.")
if not spaces:
raise ValueError("No Notion workspaces were returned. The token may be invalid or expired.")
if not candidates:
candidates = accounts_from_maps(users, spaces, space_views)
if active_user_id:
active_candidates = [account for account in candidates if account.user_id == active_user_id]
if active_candidates:
candidates = active_candidates
candidates.sort(
key=lambda account: (
1 if account.user_id == active_user_id else 0,
1 if account.user_email else 0,
1 if account.space_view_id else 0,
1 if account.user_name else 0,
),
reverse=True,
)
return candidates
def _choose_account(candidates: list[NotionAccount]) -> NotionAccount:
if len(candidates) == 1:
chosen = candidates[0]
print(f"Auto-selected: {chosen.user_name} {f'({chosen.user_email})' if chosen.user_email else ''}")
return chosen
print()
print("Multiple account combinations were detected. Choose one:")
for index, account in enumerate(candidates, start=1):
label = account.user_name or "(unknown)"
if account.user_email:
label += f" <{account.user_email}>"
if account.space_view_id:
label += f" | space_view_id={account.space_view_id}"
print(f" [{index}] {label}")
while True:
choice = input(f"Select 1-{len(candidates)}: ").strip()
if choice.isdigit():
index = int(choice)
if 1 <= index <= len(candidates):
return candidates[index - 1]
print("Invalid selection. Try again.")
def _read_accounts_file() -> list[dict[str, Any]]:
if not ACCOUNTS_FILE.exists():
return []
try:
data = json.loads(ACCOUNTS_FILE.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return []
if not isinstance(data, list):
return []
return [item for item in data if isinstance(item, dict)]
def _account_identity(item: dict[str, Any]) -> tuple[str, ...]:
profile_name = str(item.get("profile_name") or "").strip().lower()
if profile_name:
return ("profile", profile_name)
user_id = str(item.get("user_id") or "").strip()
space_id = str(item.get("space_id") or "").strip()
if user_id and space_id:
return ("account", user_id, space_id)
return ("raw", json.dumps(item, sort_keys=True, ensure_ascii=False))
def _write_accounts(account: NotionAccount) -> list[dict[str, Any]]:
existing = _read_accounts_file()
merged: list[dict[str, Any]] = []
identity = _account_identity(account.to_dict())
for item in existing:
if _account_identity(item) == identity:
continue
merged.append(item)
merged.insert(0, account.to_dict())
ACCOUNTS_FILE.write_text(json.dumps(merged, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return merged
def _sync_env_file(accounts: list[dict[str, Any]]) -> None:
env_line = f"NOTION_ACCOUNTS={json.dumps(accounts, ensure_ascii=False)}"
if ENV_FILE.exists():
lines = ENV_FILE.read_text(encoding="utf-8").splitlines()
updated = False
new_lines: list[str] = []
for line in lines:
stripped = line.lstrip()
if stripped.startswith("NOTION_ACCOUNTS="):
new_lines.append(env_line)
updated = True
else:
new_lines.append(line)
if not updated:
if new_lines and new_lines[-1].strip():
new_lines.append("")
new_lines.append(env_line)
ENV_FILE.write_text("\n".join(new_lines).rstrip() + "\n", encoding="utf-8")
else:
ENV_FILE.write_text(env_line + "\n", encoding="utf-8")
def _validate_account(account: dict[str, Any]) -> tuple[bool, str]:
token_v2 = str(account.get("token_v2") or "").strip()
space_id = str(account.get("space_id") or "").strip()
user_id = str(account.get("user_id") or "").strip()
if not token_v2 or not space_id or not user_id:
return False, "missing required fields"
account_cookies = account.get("cookies")
if not isinstance(account_cookies, dict):
account_cookies = {}
session = _session_for_token(token_v2, account_cookies)
try:
response = session.post(f"{BASE_URL}/api/v3/loadUserContent", json={}, timeout=30)
if response.status_code != 200:
return False, f"HTTP {response.status_code}"
payload = response.json()
record_map = payload.get("recordMap") if isinstance(payload, dict) else None
if not isinstance(record_map, dict):
return False, "unexpected response"
return True, "token appears valid"
except Exception as exc:
return False, str(exc)
def _readable_account_summary(account: NotionAccount) -> str:
user = account.user_name or "user"
if account.user_email:
user = f"{user} ({account.user_email})"
return f"profile={account.profile_name}, user={user}, space_id={account.space_id}"
def _find_account(accounts: list[dict[str, Any]], profile_name: str | None) -> dict[str, Any] | None:
if not accounts:
return None
if profile_name:
target = profile_name.strip().lower()
for item in accounts:
item_profile = str(item.get("profile_name") or "").strip().lower()
if item_profile == target:
return item
return None
return accounts[0]
def _format_account_label(account: dict[str, Any]) -> str:
profile_name = str(account.get("profile_name") or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
user_name = str(account.get("user_name") or "").strip()
user_email = str(account.get("user_email") or "").strip()
label = f"profile: {profile_name}"
if user_name:
label += f", user: {user_name}"
if user_email:
label += f" ({user_email})"
return label
def _print_account_status(account: dict[str, Any]) -> int:
ok, status = _validate_account(account)
print("Saved account:")
print(f" {_format_account_label(account)}")
print(f" space_id: {account.get('space_id', '')}")
print(f" user_id: {account.get('user_id', '')}")
print(f" status: {status}")
return 0 if ok else 1
def _list_accounts(accounts: list[dict[str, Any]]) -> int:
if not accounts:
print("No saved accounts found in accounts.json")
return 1
print("Saved profiles:")
for index, account in enumerate(accounts, start=1):
ok, status = _validate_account(account)
marker = "ok" if ok else "invalid"
print(f" [{index}] {_format_account_label(account)} | {marker} | {status}")
return 0
def _check_existing_login(profile_name: str | None = None) -> int:
accounts = _read_accounts_file()
if not accounts:
print("No saved accounts found in accounts.json")
return 1
account = _find_account(accounts, profile_name)
if account is None:
available = ", ".join(str(item.get("profile_name") or DEFAULT_PROFILE) for item in accounts)
print(f"Profile not found: {profile_name}")
print(f"Available profiles: {available}")
return 1
return _print_account_status(account)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Interactive Notion2API login helper")
parser.add_argument("--check", action="store_true", help="Check a saved profile without prompting")
parser.add_argument("--list", action="store_true", help="List saved profiles and validation state")
parser.add_argument("--profile", default=DEFAULT_PROFILE, help="Profile name to check or save")
parser.add_argument("--manual", action="store_true", help="Paste token_v2 manually instead of launching Chrome")
parser.add_argument("--timeout", type=int, default=DEFAULT_LOGIN_TIMEOUT, help="Seconds to wait for browser sign-in")
parser.add_argument("--no-env", action="store_true", help="Do not update .env automatically")
args = parser.parse_args(list(argv) if argv is not None else None)
if args.check and args.list:
parser.error("--check and --list cannot be used together")
if args.list:
return _list_accounts(_read_accounts_file())
if args.check:
return _check_existing_login(args.profile)
_print_header()
try:
if args.manual:
_open_login_page()
token_v2 = _prompt_token()
cookies = {"token_v2": token_v2}
else:
print(f"Launching Chrome for {AI_URL}...")
print(f"Chrome will wait up to {args.timeout} seconds for token_v2 to appear.")
cookies = _launch_and_extract_cookies(timeout_seconds=args.timeout)
token_v2 = str(cookies.get("token_v2") or "").strip()
print("token_v2 captured from Chrome.")
candidates = _extract_candidates(token_v2, cookies)
chosen = _choose_account(candidates).with_profile(args.profile)
merged_accounts = _write_accounts(chosen)
if not args.no_env:
_sync_env_file(merged_accounts)
print()
print("Login complete.")
print(f"Saved: {ACCOUNTS_FILE}")
if not args.no_env:
print(f"Updated: {ENV_FILE}")
print(f"Profile: {chosen.profile_name}")
print(f"User: {chosen.user_name} {f'({chosen.user_email})' if chosen.user_email else ''}")
print(f"Workspace: {chosen.space_id}")
if chosen.space_view_id:
print(f"Space view: {chosen.space_view_id}")
print(f"Summary: {_readable_account_summary(chosen)}")
return 0
except KeyboardInterrupt:
print("\nCancelled.")
return 1
except TimeoutError as exc:
print(f"\nLogin timed out: {exc}")
print("Try --manual if you want to paste token_v2 instead.")
return 1
except Exception as exc:
print(f"\nLogin failed: {exc}")
return 1
if __name__ == "__main__":
raise SystemExit(main())
+10
View File
@@ -0,0 +1,10 @@
requests
cloudscraper
python-dotenv
fastapi
uvicorn[standard]
pydantic
slowapi
httpx
websocket-client
playwright
+84
View File
@@ -0,0 +1,84 @@
@echo off
REM ==========================================
REM Notion-AI Docker 部署脚本 (Windows)
REM ==========================================
echo ==========================================
echo Notion-AI Docker 部署脚本
echo ==========================================
echo.
REM 检查 Docker 是否安装
docker --version >nul 2>&1
if errorlevel 1 (
echo ❌ Docker 未安装,请先安装 Docker Desktop
pause
exit /b 1
)
REM 检查 .env 文件是否存在
if not exist .env (
echo ⚠️ .env 文件不存在,正在从 .env.example 创建...
if exist .env.example (
copy .env.example .env >nul
echo ✅ 已创建 .env 文件
echo 📝 请编辑 .env 文件,填入你的 Notion 账号信息
echo 编辑完成后,再次运行此脚本
pause
exit /b 0
) else (
echo ❌ .env.example 文件不存在
pause
exit /b 1
)
)
REM 创建必要的目录
echo 📁 创建数据目录...
if not exist data mkdir data
if not exist logs mkdir logs
REM 构建镜像
echo 🔨 构建 Docker 镜像...
docker-compose build --no-cache
REM 启动服务
echo 🚀 启动服务...
docker-compose up -d
REM 等待服务启动
echo ⏳ 等待服务启动...
timeout /t 5 /nobreak >nul
REM 检查服务状态
echo.
echo 📊 服务状态:
docker-compose ps
REM 检查健康状态
echo.
echo 🏥 健康检查:
curl -s http://localhost:8000/health >nul 2>&1
if errorlevel 1 (
echo ❌ 服务启动失败,请查看日志:
echo docker-compose logs
) else (
echo ✅ 服务运行正常!
echo.
echo 🌐 访问地址:
echo - Web 界面: http://localhost:8000
echo - API 文档: http://localhost:8000/docs
echo - 健康检查: http://localhost:8000/health
echo.
echo 📝 查看日志:
echo docker-compose logs -f
echo.
echo 🛑 停止服务:
echo docker-compose down
)
echo.
echo ==========================================
echo 部署完成!
echo ==========================================
pause
+84
View File
@@ -0,0 +1,84 @@
#!/bin/bash
# ==========================================
# Notion-AI Docker 部署脚本
# ==========================================
set -e # 遇到错误立即退出
echo "=========================================="
echo " Notion-AI Docker 部署脚本"
echo "=========================================="
# 检查 Docker 是否安装
if ! command -v docker &> /dev/null; then
echo "❌ Docker 未安装,请先安装 Docker"
exit 1
fi
# 检查 Docker Compose 是否安装
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
echo "❌ Docker Compose 未安装,请先安装 Docker Compose"
exit 1
fi
# 检查 .env 文件是否存在
if [ ! -f .env ]; then
echo "⚠️ .env 文件不存在,正在从 .env.example 创建..."
if [ -f .env.example ]; then
cp .env.example .env
echo "✅ 已创建 .env 文件"
echo "📝 请编辑 .env 文件,填入你的 Notion 账号信息"
echo " 编辑完成后,再次运行此脚本"
exit 0
else
echo "❌ .env.example 文件不存在"
exit 1
fi
fi
# 创建必要的目录
echo "📁 创建数据目录..."
mkdir -p data logs
# 构建镜像
echo "🔨 构建 Docker 镜像..."
docker-compose build --no-cache
# 启动服务
echo "🚀 启动服务..."
docker-compose up -d
# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 5
# 检查服务状态
echo ""
echo "📊 服务状态:"
docker-compose ps
# 检查健康状态
echo ""
echo "🏥 健康检查:"
if curl -s http://localhost:8000/health > /dev/null; then
echo "✅ 服务运行正常!"
echo ""
echo "🌐 访问地址:"
echo " - Web 界面: http://localhost:8000"
echo " - API 文档: http://localhost:8000/docs"
echo " - 健康检查: http://localhost:8000/health"
echo ""
echo "📝 查看日志:"
echo " docker-compose logs -f"
echo ""
echo "🛑 停止服务:"
echo " docker-compose down"
else
echo "❌ 服务启动失败,请查看日志:"
echo " docker-compose logs"
fi
echo ""
echo "=========================================="
echo " 部署完成!"
echo "=========================================="
+237
View File
@@ -0,0 +1,237 @@
/**
* Notion 账号信息提取脚本(旧版手动备用流程)
*
* 推荐优先运行 `python login.py`。该登录脚本会自动打开临时 Chrome/Edge
* 调试窗口,并从本地浏览器会话中提取 token_v2 和账号/工作区字段。
*
* 如果自动登录流程不可用,可以使用本手动脚本:
* 1. 浏览器登录 https://www.notion.so/ai
* 2. 确保左上角切换到你要提取的账号
* 3. F12 → Application → Cookies → 复制 token_v2 的值
* 4. F12 → Console → 粘贴本脚本 → 回车
* 5. 如果有多个账号/工作区,按提示选择
* 6. 把输出的 JSON 粘贴到 accounts.json,替换 YOUR_TOKEN_V2
*/
(async () => {
try {
// ─── 第 1 步:获取所有可访问的用户和空间 ───
// getSpaces 会返回当前 token 能看到的所有用户(含多账号)
let allUsers = {}; // user_id → {name, email}
let allSpaces = {}; // space_id → {name, plan, members}
let spaceViewMap = {}; // space_id → space_view_id
// 尝试 getSpaces(返回更完整的多账号数据)
try {
const r1 = await fetch('/api/v3/getSpaces', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: '{}', credentials: 'include'
});
const d1 = await r1.json();
// getSpaces 返回 { "user_id_1": { space: {...}, ... }, "user_id_2": {...} }
if (d1 && typeof d1 === 'object' && !d1.recordMap) {
for (const [userId, userData] of Object.entries(d1)) {
if (!userData || typeof userData !== 'object') continue;
// 提取用户信息
const nu = userData.notion_user;
if (nu) {
for (const [nuid, nuData] of Object.entries(nu)) {
const v = nuData?.value?.value || nuData?.value || nuData || {};
allUsers[nuid] = {
name: v.given_name || v.name || v.family_name || '',
email: v.email || ''
};
}
}
// 提取空间信息
const sp = userData.space;
if (sp) {
for (const [sid, sData] of Object.entries(sp)) {
const v = sData?.value?.value || sData?.value || sData || {};
if (!allSpaces[sid]) {
allSpaces[sid] = {
name: v.name || '',
plan: v.plan_type || v.subscription_tier || ''
};
}
}
}
// 提取 space_view
const sv = userData.space_view;
if (sv) {
for (const [svid, svData] of Object.entries(sv)) {
const v = svData?.value?.value || svData?.value || svData || {};
if (v.space_id) spaceViewMap[v.space_id] = svid;
}
}
}
}
} catch (e) { /* getSpaces 失败,fallback 到 loadUserContent */ }
// fallback:loadUserContent
const r2 = await fetch('/api/v3/loadUserContent', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: '{}', credentials: 'include'
});
const d2 = (await r2.json()).recordMap || {};
// 合并用户
for (const [nuid, nuData] of Object.entries(d2.notion_user || {})) {
if (allUsers[nuid]) continue;
const v = nuData?.value?.value || nuData?.value || nuData || {};
allUsers[nuid] = {
name: v.given_name || v.name || v.family_name || '',
email: v.email || ''
};
}
// 合并空间
for (const [sid, sData] of Object.entries(d2.space || {})) {
if (allSpaces[sid]) continue;
const v = sData?.value?.value || sData?.value || sData || {};
allSpaces[sid] = {
name: v.name || '',
plan: v.plan_type || v.subscription_tier || ''
};
}
// 合并 space_view
for (const [svid, svData] of Object.entries(d2.space_view || {})) {
const v = svData?.value?.value || svData?.value || svData || {};
if (v.space_id && !spaceViewMap[v.space_id]) spaceViewMap[v.space_id] = svid;
}
// 读取 cookie 中的 notion_user_id(当前 UI 上的活跃账号)
const cookieUserId = document.cookie.split(';')
.map(c => c.trim())
.find(c => c.startsWith('notion_user_id='))
?.split('=')[1] || '';
const userList = Object.entries(allUsers);
const spaceList = Object.entries(allSpaces).map(([id, s]) => ({
space_id: id, name: s.name, plan: s.plan, space_view_id: spaceViewMap[id] || ''
}));
if (userList.length === 0) {
console.error('❌ 未找到任何用户信息,请确认已登录 Notion');
return;
}
// ─── 展示 & 选择用户 ───
console.log('\n');
console.log('%c═══════════════════════════════════════════════', 'color:#00a699');
console.log('%c Notion 账号信息提取工具', 'font-size:15px;font-weight:bold;color:#00a699');
console.log('%c═══════════════════════════════════════════════', 'color:#00a699');
console.log('');
let chosenUserId, chosenUserName, chosenUserEmail;
if (userList.length === 1) {
chosenUserId = userList[0][0];
chosenUserName = userList[0][1].name;
chosenUserEmail = userList[0][1].email;
console.log(`%c👤 用户: ${chosenUserName || '(未知)'} ${chosenUserEmail ? '(' + chosenUserEmail + ')' : ''}`, 'font-size:13px');
} else {
console.log(`%c👥 检测到 ${userList.length} 个 Notion 账号:`, 'font-size:13px;font-weight:bold');
console.log('');
userList.forEach(([uid, u], i) => {
const active = uid === cookieUserId ? ' ← 当前活跃' : '';
console.log(`%c [${i}] ${u.name || '(未知)'} ${u.email ? '(' + u.email + ')' : ''}${active}`, 'font-size:13px');
});
console.log('');
console.log('%c👆 请查看上方账号列表,3 秒后弹窗选择...', 'color:#ff9800;font-size:12px');
await new Promise(resolve => setTimeout(resolve, 3000));
const promptText = userList.map(([uid, u], i) => {
const active = uid === cookieUserId ? ' ← 当前' : '';
return `[${i}] ${u.name || '(未知)'} ${u.email ? '(' + u.email + ')' : ''}${active}`;
}).join('\n');
const idx = prompt(`请选择要提取的账号:\n\n${promptText}\n\n输入编号 (0 ~ ${userList.length - 1}):`);
if (idx === null || idx.trim() === '') {
console.log('%c⚠️ 已取消', 'color:#ff9800');
return;
}
const chosen = userList[parseInt(idx)];
if (!chosen) {
console.error(`❌ 编号 "${idx}" 无效`);
return;
}
chosenUserId = chosen[0];
chosenUserName = chosen[1].name;
chosenUserEmail = chosen[1].email;
}
console.log(`%c✅ 选择用户: ${chosenUserName || chosenUserId.slice(0,8)} ${chosenUserEmail ? '(' + chosenUserEmail + ')' : ''}`, 'color:#00c853;font-size:13px');
// ─── 选择工作区 ───
if (spaceList.length === 0) {
console.error('❌ 未找到任何工作区');
return;
}
console.log('');
console.log(`%c📂 找到 ${spaceList.length} 个工作区:`, 'font-size:13px;font-weight:bold');
console.log('');
spaceList.forEach((s, i) => {
const label = s.name || `(ID: ${s.space_id.slice(0, 13)}...)`;
const planStr = s.plan ? ` 计划: ${s.plan}` : '';
console.log(`%c [${i}] ${label}${planStr}`, 'font-size:13px');
});
let chosenSpace;
if (spaceList.length === 1) {
chosenSpace = spaceList[0];
console.log('%c🎯 只有一个工作区,自动选择', 'color:#2196f3;font-weight:bold');
} else {
console.log('');
console.log('%c👆 3 秒后弹窗选择工作区...', 'color:#ff9800;font-size:12px');
await new Promise(resolve => setTimeout(resolve, 3000));
const promptText = spaceList.map((s, i) => {
const label = s.name || `ID: ${s.space_id.slice(0, 13)}...`;
return `[${i}] ${label}`;
}).join('\n');
const idx = prompt(`请选择有 AI 功能的工作区:\n\n${promptText}\n\n输入编号 (0 ~ ${spaceList.length - 1}):`);
if (idx === null || idx.trim() === '') {
console.log('%c⚠️ 已取消', 'color:#ff9800');
return;
}
chosenSpace = spaceList[parseInt(idx)];
if (!chosenSpace) {
console.error(`❌ 编号 "${idx}" 无效`);
return;
}
}
// ─── 输出结果 ───
const account = {
token_v2: 'YOUR_TOKEN_V2',
space_id: chosenSpace.space_id,
user_id: chosenUserId,
space_view_id: chosenSpace.space_view_id,
user_name: chosenUserName,
user_email: chosenUserEmail
};
const json = JSON.stringify(account, null, 2);
const spaceLabel = chosenSpace.name || chosenSpace.space_id.slice(0, 13) + '...';
console.log('');
console.log('%c═══════════════════════════════════════════════', 'color:#00c853');
console.log(`%c✅ 用户: ${chosenUserName || '(未知)'} 工作区: ${spaceLabel}`, 'color:#00c853;font-weight:bold;font-size:14px');
console.log('%c═══════════════════════════════════════════════', 'color:#00c853');
console.log('');
console.log(json);
console.log('');
console.log('%c⚠️ 下一步:把 YOUR_TOKEN_V2 替换为你复制的 token_v2 值', 'color:#ff9800;font-weight:bold');
console.log('%c 然后粘贴到 accounts.json 数组中', 'color:#ff9800');
console.log('%c ⚠️ 注意:token_v2 要用你选择的那个账号的!在 Cookies 里确认', 'color:#ff9800');
setTimeout(() => {
navigator.clipboard.writeText(json)
.then(() => console.log('%c📋 已自动复制到剪贴板', 'color:#00c853'))
.catch(() => console.log('%c📋 请手动选中上方 JSON 复制', 'color:#ff9800'));
}, 800);
} catch (e) { console.error('❌ 提取失败:', e.message) }
})();
+104
View File
@@ -0,0 +1,104 @@
#!/bin/bash
# ==========================================
# Notion-AI 服务管理脚本
# ==========================================
case "$1" in
start)
echo "🚀 启动服务..."
docker-compose up -d
;;
stop)
echo "🛑 停止服务..."
docker-compose down
;;
restart)
echo "🔄 重启服务..."
docker-compose restart
;;
status)
echo "📊 服务状态:"
docker-compose ps
echo ""
echo "🏥 健康检查:"
curl -s http://localhost:8000/health | jq . 2>/dev/null || curl -s http://localhost:8000/health
;;
logs)
echo "📝 查看日志(Ctrl+C 退出):"
docker-compose logs -f
;;
build)
echo "🔨 重新构建镜像..."
docker-compose build --no-cache
;;
update)
echo "🔄 更新并重启服务..."
docker-compose down
docker-compose build --no-cache
docker-compose up -d
;;
clean)
echo "🧹 清理容器和镜像..."
docker-compose down -v
docker system prune -f
;;
backup)
echo "💾 备份数据库..."
BACKUP_DIR="backups/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp data/conversations.db "$BACKUP_DIR/"
echo "✅ 备份完成: $BACKUP_DIR"
;;
restore)
if [ -z "$2" ]; then
echo "❌ 请指定备份目录,例如: ./manage.sh restore backups/20240306_120000"
exit 1
fi
echo "📥 恢复数据库..."
cp "$2/conversations.db" data/
echo "✅ 恢复完成,请重启服务: ./manage.sh restart"
;;
shell)
echo "🐚 进入容器 Shell..."
docker-compose exec notion-opus /bin/bash
;;
test)
echo "🧪 测试 API..."
echo "发送测试请求..."
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus4.6",
"messages": [{"role": "user", "content": "Hello"}],
"stream": false
}'
;;
*)
echo "=========================================="
echo " Notion-AI 服务管理脚本"
echo "=========================================="
echo "用法: ./manage.sh {command}"
echo ""
echo "命令:"
echo " start - 启动服务"
echo " stop - 停止服务"
echo " restart - 重启服务"
echo " status - 查看状态"
echo " logs - 查看日志"
echo " build - 重新构建镜像"
echo " update - 更新并重启服务"
echo " clean - 清理容器和镜像"
echo " backup - 备份数据库"
echo " restore - 恢复数据库 (需要指定备份目录)"
echo " shell - 进入容器 Shell"
echo " test - 测试 API"
echo ""
echo "示例:"
echo " ./manage.sh start"
echo " ./manage.sh logs"
echo " ./manage.sh backup"
echo " ./manage.sh restore backups/20240306_120000"
echo "=========================================="
exit 1
;;
esac
+347
View File
@@ -0,0 +1,347 @@
# Notion Opus/GPT-6.1 free farm — FULL PIPELINE
# 1. Voidash mailbox 2. Signup + code 3. Onboarding 4. Model select + test message
# Usage: python farm.py N [model]
import asyncio, json, re, sys, time, random, string, os
import httpx
from playwright.async_api import async_playwright
BASE = os.path.dirname(os.path.abspath(__file__))
OUT = BASE + "/farm_accounts.jsonl"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
VOIDASH_DOMAINS = ["voidash.bond"]
NOTION_SIGNUP = "https://www.notion.so/signup"
FIRSTS = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"]
def voidash_create():
domain = random.choice(VOIDASH_DOMAINS)
with httpx.Client(timeout=25, trust_env=False) as c:
r = c.post("https://api.voidash.com/api/v1/inboxes", json={"domain": domain})
if r.status_code not in (200, 201):
return None, f"voidash {r.status_code}: {r.text[:100]}"
d = r.json()
return d["address"], d["session_key"]
def voidash_wait_code(session_key, deadline_s=240, since_ts=None):
t0 = time.time()
if since_ts is None:
since_ts = t0
headers = {"Authorization": f"Bearer {session_key}"}
with httpx.Client(timeout=25, trust_env=False, headers=headers) as c:
while time.time() - t0 < deadline_s:
try:
r = c.get("https://api.voidash.com/api/v1/messages")
if r.status_code == 200:
msgs = r.json()
if isinstance(msgs, dict):
msgs = msgs.get("messages", msgs.get("data", []))
for m in msgs:
try:
created = m.get("created_at") or ""
if created and since_ts:
from datetime import datetime, timezone
cts = datetime.fromisoformat(created.replace("Z", "+00:00")).timestamp()
if cts < since_ts - 120:
continue
except Exception:
pass
subj = (m.get("subject") or "").lower()
frm = json.dumps(m.get("from", {})).lower()
if "notion" in subj or "notion" in frm:
full_body = m.get("body") or m.get("text") or ""
if not full_body:
try:
r2 = c.get(f"https://api.voidash.com/api/v1/messages/{m['id']}")
full_body = r2.json().get("body") or r2.json().get("text") or ""
except Exception:
pass
lines = [l.strip() for l in full_body.splitlines() if l.strip()]
for l in lines[:4]:
if re.fullmatch(r'[A-Za-z0-9]{6,8}', l):
return l
m2 = re.search(r'\b([A-Za-z0-9]{6})\b', full_body[:200])
if m2:
return m2.group(1)
except Exception as e:
print("voidash err:", str(e)[:120])
time.sleep(6)
return None
async def farm_one(model="Opus"):
res = {"status": "error", "step": "init", "model": model}
# 1) mailbox
addr, key = voidash_create()
if not addr:
res["error"] = key
return res
res["email"] = addr
res["voidash_key"] = key
print("MAILBOX:", addr)
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True, args=["--no-sandbox"])
ctx = await browser.new_context(user_agent=UA, viewport={"width": 1600, "height": 1000})
page = await ctx.new_page()
try:
# ===== 2) signup =====
await page.goto(NOTION_SIGNUP, wait_until="domcontentloaded", timeout=60000)
await page.wait_for_timeout(4000)
email_input = page.locator("input[type=email]").first
await email_input.fill(addr)
await page.wait_for_timeout(600)
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
else:
await email_input.press("Enter")
await page.wait_for_timeout(5000)
body = (await page.inner_text("body")).lower()
if "invalid email domain" in body or "problem" in body:
res["error"] = "rejected: " + body[:150]
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png")
return res
# ===== 3) code =====
if "verification" in body or "code" in body:
sent_ts = time.time()
code = await asyncio.to_thread(voidash_wait_code, key, 240, sent_ts)
if not code:
res["error"] = "otp-not-found"
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png")
return res
res["otp"] = code
print("CODE:", code)
code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first
if await code_input.count():
await code_input.fill(code)
else:
inputs = page.locator("input")
cnt = await inputs.count()
filled = False
for j in range(cnt):
inp = inputs.nth(j)
t = await inp.get_attribute("type") or ""
ph = (await inp.get_attribute("placeholder") or "").lower()
if t not in ("email", "password") and "mail" not in ph:
await inp.fill(code)
filled = True
break
if not filled:
cells = page.locator("input[maxlength=1]")
cc = await cells.count()
for j, ch in enumerate(code):
if j < cc:
await cells.nth(j).fill(ch)
await page.wait_for_timeout(600)
cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont2.count():
await cont2.click()
await page.wait_for_timeout(7000)
# password (если есть)
body = (await page.inner_text("body")).lower()
pw_input = page.locator("input[type=password]").first
if "password" in body and await pw_input.count():
pw = "Not!" + ''.join(random.choices(string.ascii_letters + string.digits, k=10))
res["password"] = pw
await pw_input.fill(pw)
await page.wait_for_timeout(400)
cont3 = page.get_by_role("button", name=re.compile("Continue|Sign up|Create", re.I)).first
if await cont3.count():
await cont3.click()
else:
await pw_input.press("Enter")
await page.wait_for_timeout(7000)
# ===== 4) onboarding =====
for attempt in range(15):
body = (await page.inner_text("body")).lower()
if "customize your profile" in body or "your name" in body:
name_inputs = page.locator("input[type=text], input:not([type])")
cnt = await name_inputs.count()
for j in range(min(cnt, 1)):
await name_inputs.nth(j).fill(random.choice(FIRSTS).capitalize() + " " + random.choice(FIRSTS).capitalize())
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
for _ in range(10):
await page.wait_for_timeout(1500)
b2 = (await page.inner_text("body")).lower()
if "customize your profile" not in b2 and "your name" not in b2:
break
continue
if "how do you want to use" in body:
opt = page.get_by_text(re.compile("for personal|for myself", re.I)).first
if await opt.count():
await opt.click()
await page.wait_for_timeout(2000)
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
await page.wait_for_timeout(3000)
continue
if "start with your real work" in body or "connect email" in body:
btn = page.get_by_role("button", name=re.compile("Start from scratch", re.I)).first
if await btn.count():
await btn.click()
# ждём смены экрана
for _ in range(10):
await page.wait_for_timeout(1500)
b2 = (await page.inner_text("body")).lower()
if "start with your real work" not in b2:
break
continue
if "create" in body and "workspace" in body:
btn = page.get_by_role("button", name=re.compile("Create new workspace", re.I)).first
if await btn.count():
await btn.click()
await page.wait_for_timeout(4000)
continue
if "desktop" in body and ("skip" in body or "faster" in body):
skip = page.get_by_role("button", name=re.compile("skip for now|skip", re.I)).first
if await skip.count():
await skip.click()
await page.wait_for_timeout(3000)
continue
if "/onboarding" not in page.url:
break
# generic continue — только кликабельные кнопки без disabled
cont = page.locator('button:enabled, [role=button]:not([aria-disabled="true"])').filter(has_text=re.compile(r"^\s*(Continue|Next|Get started)\s*$", re.I)).first
if await cont.count():
await cont.click()
await page.wait_for_timeout(3000)
else:
break
res["post_onboarding_url"] = page.url
print("POST-ONBOARDING:", page.url)
# ===== 5) model select + test =====
# Если после онбординга мы уже на /chat — НЕ делаем goto (перезагрузка убивает чат-сессию)
if "/chat" not in page.url:
await page.goto("https://app.notion.com/chat", wait_until="domcontentloaded", timeout=60000)
try:
await page.locator('[aria-label="Choose AI model"]').first.wait_for(state="visible", timeout=45000)
except Exception:
# fallback: перезагрузка + повторное ожидание
try:
await page.goto("https://app.notion.com/chat", wait_until="domcontentloaded", timeout=60000)
await page.locator('[aria-label="Choose AI model"]').first.wait_for(state="visible", timeout=45000)
except Exception:
res["error"] = "chat/model button missing"
await ctx.storage_state(path=f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json")
res["state_path"] = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json"
res["status"] = "registered-no-chat"
await browser.close()
return res
await page.wait_for_timeout(2000)
await page.locator('[aria-label="Choose AI model"]').first.click()
await page.wait_for_timeout(2500)
items = page.locator('[role=menuitem]')
cnt = await items.count()
target = None
for j in range(cnt):
t = await items.nth(j).inner_text()
if model.lower() in t.lower():
target = items.nth(j)
break
if target is None:
res["error"] = f"model {model} not in menu"
else:
await target.click()
await page.wait_for_timeout(2000)
print("MODEL SELECTED:", model)
# test message
chat_box = page.locator('[contenteditable=true]').first
await chat_box.click()
await chat_box.fill("Hello! Which model are you? Answer in one short sentence.")
await page.wait_for_timeout(500)
submit = page.locator('[aria-label="Submit AI message"]').first
if await submit.count():
await submit.click()
else:
await chat_box.press("Enter")
# wait response
for i in range(40):
await page.wait_for_timeout(2500)
body = (await page.inner_text("body")).lower()
if "working on your request" not in body and "connecting the details" not in body:
if "hello! which model" in body:
break
body_full = await page.inner_text("body")
# extract reply: текст после нашего промпта
try:
idx = body_full.lower().rfind("hello! which model")
reply = body_full[idx + 200:idx + 600].strip()
res["ai_reply"] = reply[:300]
except Exception:
pass
res["model_active"] = model
res["final_url"] = page.url
state_path = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json"
await ctx.storage_state(path=state_path)
res["state_path"] = state_path
if "signup" not in page.url and "login" not in page.url and "appeals" not in page.url:
res["status"] = "ok"
else:
res["status"] = "incomplete"
await page.screenshot(path=f"{BASE}/final_{int(time.time())}.png")
except Exception as e:
res["error"] = str(e)[:300]
try:
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png")
except Exception:
pass
finally:
await browser.close()
return res
async def main():
if len(sys.argv) > 1 and sys.argv[1] == "--export":
export_pool()
return
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
model = sys.argv[2] if len(sys.argv) > 2 else "Opus"
for i in range(n):
print(f"=== farm {i+1}/{n} model={model} ===")
res = await farm_one(model)
with open(OUT, "a", encoding="utf-8") as f:
f.write(json.dumps(res, ensure_ascii=False) + "\n")
print("RESULT:", json.dumps(res, ensure_ascii=False)[:700])
if res.get("status") != "ok" and i + 1 < n:
print("-> continuing to next account")
if __name__ == "__main__":
asyncio.run(main())
def export_pool():
"""Конвертирует farm_accounts.jsonl → accounts.json для app/ сервера."""
accounts = []
if not os.path.exists(OUT):
print("farm_accounts.jsonl не найден — сначала запусти ферму")
return
with open(OUT, encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line)
except Exception:
continue
if rec.get("status") != "ok":
continue
accounts.append({
"token_v2": rec.get("token_v2") or "",
"space_id": rec.get("space_id") or "",
"user_id": rec.get("user_id") or "",
"space_view_id": rec.get("space_view_id") or "",
"user_name": rec.get("user_name") or "",
"user_email": rec.get("email") or "",
})
out_path = os.path.join(os.path.dirname(BASE), "accounts.json")
with open(out_path, "w", encoding="utf-8") as f:
json.dump(accounts, f, ensure_ascii=False, indent=2)
print(f"export: {len(accounts)} аккаунтов -> {out_path}")
+106
View File
@@ -0,0 +1,106 @@
# Test mail.tm for Notion signup (fresh unique inboxes)
import asyncio, json, re, random, string, time
from playwright.async_api import async_playwright
import httpx
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
BASE = os.path.dirname(os.path.abspath(__file__))
def mailtm_create():
firsts = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"]
with httpx.Client(timeout=20, trust_env=False) as c:
r = c.get("https://api.mail.tm/domains")
domain = r.json()["hydra:member"][0]["domain"]
addr = random.choice(firsts) + random.choice(firsts) + str(random.randint(100, 999)) + "@" + domain
pw = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
r = c.post("https://api.mail.tm/accounts", json={"address": addr, "password": pw})
if r.status_code not in (200, 201):
return None, None, None, r.text
# token
r2 = c.post("https://api.mail.tm/token", json={"address": addr, "password": pw})
tok = r2.json().get("token")
return addr, pw, tok, "ok"
def mailtm_wait_code(tok, deadline_s=200):
t0 = time.time()
headers = {"Authorization": f"Bearer {tok}"}
with httpx.Client(timeout=20, trust_env=False, headers=headers) as c:
while time.time() - t0 < deadline_s:
try:
r = c.get("https://api.mail.tm/messages")
msgs = r.json().get("hydra:member", [])
for m in msgs:
if "notion" in (m.get("from", {}).get("address", "") + m.get("subject", "")).lower():
# тело письма
r2 = c.get(f"https://api.mail.tm/messages/{m['id']}")
d = r2.json()
text = (d.get("text") or "") + " " + (d.get("subject") or "")
mm = re.search(r'\b([A-Za-z0-9]{6})\b', (d.get("text") or "")[:300])
if not mm:
lines = [l.strip() for l in (d.get("text") or "").splitlines() if l.strip()]
for l in lines[:5]:
if re.fullmatch(r'[A-Za-z0-9]{6,8}', l):
return l
if mm:
return mm.group(1)
except Exception as e:
print("mailtm err:", str(e)[:100])
time.sleep(5)
return None
async def main():
addr, pw, tok, st = mailtm_create()
if not addr:
print("MAILTM FAIL:", st)
return
print("MAILBOX:", addr)
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True, args=["--no-sandbox"])
ctx = await browser.new_context(user_agent=UA, viewport={"width": 1366, "height": 900})
page = await ctx.new_page()
await page.goto("https://www.notion.so/signup", wait_until="domcontentloaded", timeout=60000)
await page.wait_for_timeout(4000)
email_input = page.locator("input[type=email]").first
await email_input.fill(addr)
await page.wait_for_timeout(600)
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
await page.wait_for_timeout(6000)
body = (await page.inner_text("body")).lower()
if "problem" in body:
print("REJECTED (problem signing up)")
await page.screenshot(path=f"{BASE}/mailtm_rejected.png")
elif "verification" in body or "code" in body:
print("CODE SENT — waiting IMAP-less...")
code = mailtm_wait_code(tok)
print("CODE:", code)
if code:
code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first
if await code_input.count():
await code_input.fill(code)
else:
inputs = page.locator("input")
cnt = await inputs.count()
for j in range(cnt):
inp = inputs.nth(j)
t = await inp.get_attribute("type") or ""
if t not in ("email", "password"):
await inp.fill(code)
break
await page.wait_for_timeout(600)
cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont2.count():
await cont2.click()
await page.wait_for_timeout(8000)
body2 = (await page.inner_text("body")).lower()
print("AFTER CODE URL:", page.url)
print("AFTER CODE BODY:", body2[:300])
await page.screenshot(path=f"{BASE}/mailtm_after_code.png")
await ctx.storage_state(path=f"{BASE}/state_mailtm_test.json")
else:
print("UNKNOWN STATE:", body[:300])
await page.screenshot(path=f"{BASE}/mailtm_unknown.png")
await browser.close()
asyncio.run(main())
+267
View File
@@ -0,0 +1,267 @@
# Notion autoreg FINAL: Voidash inbox -> Notion signup -> code -> onboarding -> session
# Usage: python notion_reg.py N
import asyncio, json, re, sys, time, random, string, os
import httpx
from playwright.async_api import async_playwright
BASE = os.path.dirname(os.path.abspath(__file__))
OUT = BASE + "/accounts.jsonl"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
VOIDASH_DOMAINS = ["voidash.bond"]
NOTION_SIGNUP = "https://www.notion.so/signup"
FIRSTS = ["alex", "maria", "peter", "laura", "stef", "anna", "tony", "nina", "eric", "sara", "luca", "jana", "tom", "lena", "paul", "kate"]
def voidash_create():
"""Создать ящик Voidash. Возвращает (address, session_key) или (None, err)."""
domain = random.choice(VOIDASH_DOMAINS)
with httpx.Client(timeout=25, trust_env=False) as c:
r = c.post("https://api.voidash.com/api/v1/inboxes", json={"domain": domain})
if r.status_code not in (200, 201):
return None, f"voidash {r.status_code}: {r.text[:100]}"
d = r.json()
return d["address"], d["session_key"]
def voidash_wait_code(session_key, deadline_s=240, since_ts=None):
"""Ждать код Notion в Voidash inbox. Возвращает код или None."""
t0 = time.time()
if since_ts is None:
since_ts = t0
headers = {"Authorization": f"Bearer {session_key}"}
with httpx.Client(timeout=25, trust_env=False, headers=headers) as c:
while time.time() - t0 < deadline_s:
try:
r = c.get("https://api.voidash.com/api/v1/messages")
if r.status_code == 200:
msgs = r.json()
if isinstance(msgs, dict):
msgs = msgs.get("messages", msgs.get("data", []))
for m in msgs:
try:
created = m.get("created_at") or m.get("received_at") or ""
if created and since_ts:
# iso timestamp
from datetime import datetime, timezone
cts = datetime.fromisoformat(created.replace("Z", "+00:00")).timestamp()
if cts < since_ts - 120:
continue
except Exception:
pass
subj = (m.get("subject") or "").lower()
frm = json.dumps(m.get("from", {})).lower()
body_preview = (m.get("body") or m.get("text") or m.get("body_preview") or "")[:200]
if "notion" in subj or "notion" in frm:
full_body = m.get("body") or m.get("text") or ""
if not full_body:
# fetch single message
try:
r2 = c.get(f"https://api.voidash.com/api/v1/messages/{m['id']}")
full_body = r2.json().get("body") or r2.json().get("text") or ""
except Exception:
pass
text = subj + "\n" + full_body
m2 = re.search(r'(?:code is|code:)\s*[:\s]*([A-Za-z0-9]{5,8})\b', text, re.I)
if not m2:
lines = [l.strip() for l in full_body.splitlines() if l.strip()]
for l in lines[:4]:
if re.fullmatch(r'[A-Za-z0-9]{6,8}', l):
return l
if not m2:
m2 = re.search(r'\b([A-Za-z0-9]{6})\b', full_body[:200])
if m2:
return m2.group(1)
except Exception as e:
print("voidash err:", str(e)[:120])
time.sleep(6)
return None
async def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
for i in range(n):
print(f"=== reg {i+1}/{n} ===")
res = await register_one()
with open(OUT, "a", encoding="utf-8") as f:
f.write(json.dumps(res, ensure_ascii=False) + "\n")
print("RESULT:", json.dumps(res, ensure_ascii=False)[:700])
async def register_one():
res = {"status": "error", "step": "init"}
# 1) mailbox
addr, key = voidash_create()
if not addr:
res["error"] = key
return res
res["email"] = addr
res["voidash_key"] = key
print("MAILBOX:", addr)
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True, args=["--no-sandbox"])
ctx = await browser.new_context(user_agent=UA, viewport={"width": 1366, "height": 900})
page = await ctx.new_page()
try:
await page.goto(NOTION_SIGNUP, wait_until="domcontentloaded", timeout=60000)
await page.wait_for_timeout(4000)
# 2) email
email_input = page.locator("input[type=email]").first
await email_input.fill(addr)
await page.wait_for_timeout(600)
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
else:
await email_input.press("Enter")
res["step"] = "email-submitted"
await page.wait_for_timeout(5000)
body = (await page.inner_text("body")).lower()
if "invalid email domain" in body or "problem" in body:
res["error"] = "rejected: " + body[:150]
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png")
return res
# 3) verification code
if "verification" in body or "code" in body:
res["step"] = "await-otp"
print("waiting for code...")
sent_ts = time.time()
code = await asyncio.to_thread(voidash_wait_code, key, 240, sent_ts)
if not code:
res["error"] = "otp-not-found"
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.pxng" if False else f"{BASE}/err_{int(time.time())}.png")
return res
res["otp"] = code
print("CODE:", code)
code_input = page.locator("input[autocomplete=one-time-code], input[inputmode=numeric], input[name=code]").first
if await code_input.count():
await code_input.fill(code)
else:
inputs = page.locator("input")
cnt = await inputs.count()
filled = False
for j in range(cnt):
inp = inputs.nth(j)
t = await inp.get_attribute("type") or ""
ph = (await inp.get_attribute("placeholder") or "").lower()
if t not in ("email", "password") and "mail" not in ph:
await inp.fill(code)
filled = True
break
if not filled:
cells = page.locator("input[maxlength=1]")
cc = await cells.count()
for j, ch in enumerate(code):
if j < cc:
await cells.nth(j).fill(ch)
await page.wait_for_timeout(600)
cont2 = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont2.count():
await cont2.click()
await page.wait_for_timeout(7000)
res["step"] = "code-submitted"
# 4) password (если требуется)
body = (await page.inner_text("body")).lower()
pw_input = page.locator("input[type=password]").first
if "password" in body and await pw_input.count():
pw = "Not!" + ''.join(random.choices(string.ascii_letters + string.digits, k=10))
res["password"] = pw
res["step"] = "password-step"
await pw_input.fill(pw)
await page.wait_for_timeout(400)
cont3 = page.get_by_role("button", name=re.compile("Continue|Sign up|Create", re.I)).first
if await cont3.count():
await cont3.click()
else:
await pw_input.press("Enter")
await page.wait_for_timeout(7000)
# 5) workspace + onboarding loop
for attempt in range(12):
body = (await page.inner_text("body")).lower()
if "customize your profile" in body or "your name" in body:
res["step"] = f"profile-{attempt}"
await handle_profile(page)
await page.wait_for_timeout(3000)
continue
if "create" in body and "workspace" in body:
res["step"] = f"workspace-{attempt}"
btn = page.get_by_role("button", name=re.compile("Create new workspace", re.I)).first
if await btn.count():
await btn.click()
await page.wait_for_timeout(4000)
continue
if "what should we call" in body or "what would you like" in body or "name your" in body or "getting started" in body:
res["step"] = f"onboarding-{attempt}"
await handle_onboarding(page)
await page.wait_for_timeout(3000)
continue
break
res["final_url"] = page.url
res["body_final"] = (await page.inner_text("body")).lower()[:300]
state_path = f"{BASE}/state_{addr.replace('@', '_at_').replace('.', '_')}.json"
await ctx.storage_state(path=state_path)
res["state_path"] = state_path
if "signup" not in page.url and "login" not in page.url and "appeals" not in page.url:
res["status"] = "ok"
else:
res["status"] = "incomplete"
await page.screenshot(path=f"{BASE}/final_{int(time.time())}.png")
except Exception as e:
res["error"] = str(e)[:300]
try:
await page.screenshot(path=f"{BASE}/err_{int(time.time())}.png")
except Exception:
pass
finally:
await browser.close()
return res
async def handle_profile(page):
# "Customize your profile" — "Your name" input + Continue
name_inputs = page.locator("input[type=text], input:not([type]), input[name=name], input[placeholder*='name' i]")
cnt = await name_inputs.count()
for j in range(min(cnt, 1)):
await name_inputs.nth(j).fill(random.choice(FIRSTS).capitalize() + " " + random.choice(FIRSTS).capitalize())
cont = page.get_by_role("button", name=re.compile("Continue", re.I)).first
if await cont.count():
await cont.click()
await page.wait_for_timeout(3000)
async def handle_onboarding(page):
text_inputs = page.locator("input[type=text], input:not([type])")
cnt = await text_inputs.count()
filled = 0
for j in range(min(cnt, 2)):
inp = text_inputs.nth(j)
try:
ph = (await inp.get_attribute("placeholder") or "").lower()
except Exception:
ph = ""
if "name" in ph or "call" in ph:
await inp.fill("Alex")
filled += 1
elif "workspace" in ph or "team" in ph:
await inp.fill("My Workspace")
filled += 1
elif filled == 0:
await inp.fill("Alex")
filled += 1
radios = page.locator("input[type=radio]")
rc = await radios.count()
if rc:
await radios.first.check()
cont = page.get_by_role("button", name=re.compile("Continue|Next|Get started|Create", re.I)).first
if await cont.count():
await cont.click()
await page.wait_for_timeout(2500)
if __name__ == "__main__":
asyncio.run(main())