Files
mdclient/CLAUDE.md
Timmy 38b4bc5377 Initial commit: Python library for Markdown note services
- Add MDAuth class for authentication and session management
- Add MDClient class for note operations (CRUD + export/search)
- Add CLI tool mdclient_cli.py for quick operations
- Support for CodiMD, HedgeDoc, and HackMD services
- Multi-endpoint API compatibility

Co-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>
2026-03-17 14:38:54 +08:00

175 lines
5.5 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
**mdclient** is a Python library for interacting with Markdown note services (CodiMD, HedgeDoc, HackMD). The project is designed as a Python-first library with an optional CLI tool for quick operations.
**Key Design Principle:** Library-first architecture - all functionality is exposed through Python APIs (`MDAuth`, `MDClient` classes), with the CLI tool (`mdclient_cli.py`) being a thin wrapper that uses these APIs.
## Architecture
### Core Components
1. **`mdclient/`** - Main Python package
- `MDAuth` class (`auth.py`) - Handles authentication and session management
- `MDClient` class (`client.py`) - All note operations (CRUD + export/search)
- `__init__.py` - Package entry point, exports `MDClient` and `MDAuth`
2. **`mdclient_cli.py`** - Optional CLI tool
- Standalone script that imports and uses the mdclient package
- Supports .env file integration for credentials
- Not installed as a package command (run directly with `python3 mdclient_cli.py`)
### Session Management Pattern
The library uses a cookie-based session system:
- `MDAuth.login()` - Authenticates and saves cookies to a JSON file (`key.conf` by default)
- `MDClient._load_cookie()` - Automatically loads cookies for each request
- Cookies are stored in simple JSON format: `{"connect.sid": "...", "_csrf": "..."}`
### Multi-Endpoint Strategy
Both authentication and note operations attempt multiple API endpoints to handle different server implementations:
- Login: `/login`, `/auth/login`, `/api/login`, `/signin`
- Note retrieval: `/api/notes/{id}`, `/api/notes/{id}/content`, `/{id}/download`, `/{id}`
- Note listing: `/api/me/notes`, `/api/notes`, `/history`, `/me/notes`
This pattern is essential for compatibility across different Markdown note service implementations.
## Development Commands
```bash
# Install in development mode
pip install -e ".[dev]"
# Run tests
pytest
# Code formatting (line length: 100)
black mdclient/
# Type checking
mypy mdclient/
# Install with .env support
pip install -e ".[env]"
```
## Testing Authentication
When working on authentication-related features, test with:
```bash
# Test if current cookie is valid
python3 mdclient_cli.py test
# Login with credentials
python3 mdclient_cli.py login
# Or use Python directly
python3 -c "from mdclient import MDAuth; MDAuth().test_cookie()"
```
## Language and Localization
**Important:** All user-facing text and documentation must use Traditional Chinese (Taiwan) with natural, direct expression. Avoid translationese and mainland Chinese terminology.
Common term mappings:
- 登录 → 登入
- 服务器 → 伺服器
- 地址 → 位址
- 保存 → 儲存
- 文件 → 檔案
- 导入 → 匯入
- 导出 → 匯出
- 创建 → 建立
- 获取 → 取得
- 用户 → 使用者
- 邮箱 → 信箱
- 请求 → 請求
- 响应 → 回應
## Environment Variables
The library supports these environment variables (typically set in `.env` file):
- `MDCLIENT_URL` - Server URL
- `MDCLIENT_EMAIL` - Login email
- `MDCLIENT_PASSWORD` - Login password
- `MDCLIENT_COOKIE_FILE` - Cookie file path (default: `key.conf`)
## Key API Patterns
When adding new note operations or endpoints:
1. **Always try multiple endpoints** - Different services use different API patterns
2. **Handle both JSON and text responses** - Some endpoints return HTML/Markdown directly
3. **Return `None` on failure** - Consistent error handling pattern
4. **Print status messages** - Users expect feedback during operations
5. **Use Taiwan Traditional Chinese** - For all user-facing messages
## Common Patterns
### Adding a New Note Operation
```python
def new_operation(self, param: str) -> Optional[Dict]:
"""
新操作的簡短描述
Args:
param: 參數說明
Returns:
操作結果,失敗時返回 None
"""
print(f"正在執行操作: {param}")
# 嘗試多個可能的端點
endpoints = ['/api/endpoint1', '/api/endpoint2']
for endpoint in endpoints:
response = self._request('GET', endpoint)
if response and response.status_code == 200:
try:
data = response.json()
print("✓ 操作成功")
return data
except json.JSONDecodeError:
# 處理非 JSON 回應
pass
print("✗ 操作失敗")
return None
```
### CLI Command Pattern
CLI commands in `mdclient_cli.py` should:
1. Load .env file automatically
2. Support both command-line args and environment variables
3. Use `MDClient` and `MDAuth` classes (no direct HTTP requests)
4. Provide clear success/failure messages
## Package Structure
```
mdclient/
├── mdclient/ # Core library (Python package)
│ ├── __init__.py # Exports MDClient, MDAuth
│ ├── auth.py # Authentication logic
│ └── client.py # Note operations API
├── mdclient_cli.py # CLI tool (uses mdclient package)
├── pyproject.toml # Package configuration
├── example.py # Usage examples
└── .env.example # Environment variable template
```
## Important Notes
- The library uses `requests` for HTTP operations with `timeout=10` on all requests
- Cookie files are stored as JSON in the current working directory
- The CLI tool is meant for quick operations, not programmatic use
- All methods print status messages to stdout for user feedback
- Error handling returns `None` rather than raising exceptions