feat: 初始化 ekb-cli 项目骨架
- uv 管理 Python 环境,typer + httpx + rich 技术栈 - config 模块:多企业认证信息存储到 ~/.config/ekb-cli/config.json - api 模块:EkbClient 封装 HTTP 请求,自动附带 cookie 和 corpId - auth 命令:add / list / use / remove / whoami - agent 命令:list 骨架(待根据 API 响应完善)
This commit is contained in:
commit
b4a0698b13
10 files changed
+481
No files matched your search
@@ -0,0 +1,17 @@
|
||||
"""ekb-cli:快报命令行工具"""
|
||||
|
||||
import typer
|
||||
from ekb_cli.commands import auth, agent
|
||||
|
||||
app = typer.Typer(
|
||||
name="ekb",
|
||||
help="快报(ekuaibao)命令行工具",
|
||||
no_args_is_help=True,
|
||||
)
|
||||
|
||||
app.add_typer(auth.app, name="auth")
|
||||
app.add_typer(agent.app, name="agent")
|
||||
|
||||
|
||||
def main():
|
||||
app()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""HTTP 客户端:封装对快报 API 的请求,自动带上认证 cookie 和 corpId"""
|
||||
|
||||
import httpx
|
||||
from typing import Any
|
||||
|
||||
BASE_URL = "https://app.ekuaibao.com"
|
||||
|
||||
|
||||
class EkbClient:
|
||||
def __init__(self, corp_id: str, cookie: str):
|
||||
self.corp_id = corp_id
|
||||
self._client = httpx.Client(
|
||||
base_url=BASE_URL,
|
||||
headers={
|
||||
"Cookie": cookie,
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def get(self, path: str, **params) -> Any:
|
||||
params["corpId"] = self.corp_id
|
||||
resp = self._client.get(f"/api{path}", params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def post(self, path: str, body: dict = None, **params) -> Any:
|
||||
params["corpId"] = self.corp_id
|
||||
resp = self._client.post(f"/api{path}", json=body or {}, params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self._client.close()
|
||||
|
||||
|
||||
def get_client() -> EkbClient:
|
||||
"""从当前配置获取已认证的客户端,未登录时抛出友好错误"""
|
||||
from ekb_cli import config
|
||||
corp = config.get_current_corp()
|
||||
if not corp:
|
||||
raise RuntimeError("未登录,请先执行 `ekb auth add` 添加企业认证")
|
||||
corp_id = config.get_current_corp_id()
|
||||
return EkbClient(corp_id=corp_id, cookie=corp["cookie"])
|
||||
Whitespace-only changes.
@@ -0,0 +1,36 @@
|
||||
"""agent 命令:智能审核 Agent 管理(骨架,待根据 API 响应完善)"""
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli.api import get_client
|
||||
|
||||
app = typer.Typer(help="智能审核 Agent 管理")
|
||||
console = Console()
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def agent_list():
|
||||
"""列出所有智能审核 Agent"""
|
||||
with get_client() as client:
|
||||
data = client.get("/engine/hab/agent/list", page=1, size=1000)
|
||||
|
||||
items = data.get("items") or data.get("data") or []
|
||||
if not items:
|
||||
rprint("[yellow]暂无 Agent[/yellow]")
|
||||
raise typer.Exit()
|
||||
|
||||
table = Table(title="智能审核 Agent 列表")
|
||||
table.add_column("ID")
|
||||
table.add_column("名称")
|
||||
table.add_column("状态")
|
||||
|
||||
for item in items:
|
||||
table.add_row(
|
||||
str(item.get("id", "")),
|
||||
item.get("name", ""),
|
||||
item.get("status", ""),
|
||||
)
|
||||
console.print(table)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""auth 命令:管理企业认证信息"""
|
||||
|
||||
import re
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import print as rprint
|
||||
|
||||
from ekb_cli import config
|
||||
|
||||
app = typer.Typer(help="管理企业认证")
|
||||
console = Console()
|
||||
|
||||
|
||||
def _parse_corp_id(cookie: str) -> str:
|
||||
"""从 cookie 中尝试提取 corpId"""
|
||||
match = re.search(r"corpId=([^;& ]+)", cookie)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
@app.command("add")
|
||||
def auth_add():
|
||||
"""添加企业认证(从浏览器 F12 复制请求的 Cookie 头)"""
|
||||
console.print("\n[bold]添加企业认证[/bold]")
|
||||
console.print("步骤:打开快报 → F12 → 任意请求 → 复制 [cyan]Cookie[/cyan] 请求头的值\n")
|
||||
|
||||
cookie = typer.prompt("粘贴 Cookie 值").strip()
|
||||
if not cookie:
|
||||
rprint("[red]Cookie 不能为空[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
detected = _parse_corp_id(cookie)
|
||||
corp_id = typer.prompt("企业 corpId", default=detected).strip()
|
||||
if not corp_id:
|
||||
rprint("[red]corpId 不能为空[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
name = typer.prompt("企业名称(方便识别)", default=corp_id).strip()
|
||||
|
||||
config.add_corp(corp_id=corp_id, name=name, cookie=cookie)
|
||||
rprint(f"[green]✓[/green] 已添加企业 [bold]{name}[/bold] ({corp_id})")
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def auth_list():
|
||||
"""列出所有已添加的企业"""
|
||||
data = config.get_all()
|
||||
corps = data.get("corps", {})
|
||||
current = data.get("current")
|
||||
|
||||
if not corps:
|
||||
rprint("[yellow]尚未添加任何企业,请先执行 `ekb auth add`[/yellow]")
|
||||
raise typer.Exit()
|
||||
|
||||
table = Table(title="已配置的企业")
|
||||
table.add_column("", width=2)
|
||||
table.add_column("名称")
|
||||
table.add_column("corpId")
|
||||
|
||||
for corp_id, info in corps.items():
|
||||
marker = "[green]*[/green]" if corp_id == current else ""
|
||||
table.add_row(marker, info["name"], corp_id)
|
||||
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command("use")
|
||||
def auth_use(corp_id: str = typer.Argument(..., help="要切换的企业 corpId")):
|
||||
"""切换当前使用的企业"""
|
||||
try:
|
||||
config.use_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已切换到企业 [bold]{corp_id}[/bold]")
|
||||
except ValueError as e:
|
||||
rprint(f"[red]{e}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
@app.command("remove")
|
||||
def auth_remove(corp_id: str = typer.Argument(..., help="要删除的企业 corpId")):
|
||||
"""删除一个企业的认证信息"""
|
||||
config.remove_corp(corp_id)
|
||||
rprint(f"[green]✓[/green] 已删除企业 {corp_id}")
|
||||
|
||||
|
||||
@app.command("whoami")
|
||||
def auth_whoami():
|
||||
"""查看当前使用的企业"""
|
||||
corp = config.get_current_corp()
|
||||
corp_id = config.get_current_corp_id()
|
||||
if not corp:
|
||||
rprint("[yellow]未登录,请先执行 `ekb auth add`[/yellow]")
|
||||
raise typer.Exit(1)
|
||||
rprint(f"当前企业:[bold]{corp['name']}[/bold] ({corp_id})")
|
||||
@@ -0,0 +1,60 @@
|
||||
"""配置管理:存储多企业认证信息到 ~/.config/ekb-cli/config.json"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
CONFIG_DIR = Path.home() / ".config" / "ekb-cli"
|
||||
CONFIG_FILE = CONFIG_DIR / "config.json"
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
if not CONFIG_FILE.exists():
|
||||
return {"current": None, "corps": {}}
|
||||
return json.loads(CONFIG_FILE.read_text())
|
||||
|
||||
|
||||
def _save(data: dict) -> None:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
CONFIG_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
def get_all() -> dict:
|
||||
return _load()
|
||||
|
||||
|
||||
def get_current_corp_id() -> Optional[str]:
|
||||
return _load().get("current")
|
||||
|
||||
|
||||
def get_current_corp() -> Optional[dict]:
|
||||
data = _load()
|
||||
corp_id = data.get("current")
|
||||
if not corp_id:
|
||||
return None
|
||||
return data["corps"].get(corp_id)
|
||||
|
||||
|
||||
def add_corp(corp_id: str, name: str, cookie: str) -> None:
|
||||
data = _load()
|
||||
data["corps"][corp_id] = {"name": name, "cookie": cookie}
|
||||
if not data.get("current"):
|
||||
data["current"] = corp_id
|
||||
_save(data)
|
||||
|
||||
|
||||
def use_corp(corp_id: str) -> None:
|
||||
data = _load()
|
||||
if corp_id not in data["corps"]:
|
||||
raise ValueError(f"企业 {corp_id} 不存在,请先用 `ekb auth add` 添加")
|
||||
data["current"] = corp_id
|
||||
_save(data)
|
||||
|
||||
|
||||
def remove_corp(corp_id: str) -> None:
|
||||
data = _load()
|
||||
data["corps"].pop(corp_id, None)
|
||||
if data.get("current") == corp_id:
|
||||
remaining = list(data["corps"].keys())
|
||||
data["current"] = remaining[0] if remaining else None
|
||||
_save(data)
|
||||
Reference in new issue
Block a user