main.py
6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import json
import os
from contextlib import asynccontextmanager
import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from app.api.v1.router import api_router
from app.config.loader import ConfigLoader
from app.infrastructure.database import engine, SessionLocal
from app.infrastructure.logging import configure_logging
from app.infrastructure.response_format import format_response_datetimes
from app.infrastructure.schema_patch import ensure_runtime_schema
from app.infrastructure.database import Base
# Register all model tables with Base.metadata so create_all works
from app.model.agent import Agent, AgentPosition, AgentSkill # noqa: F401
from app.model.agent_group import QrcodeChannel, WeComEmployeeQrcode # noqa: F401
from app.model.analytics import ( # noqa: F401
AnalyticsEvent,
AnalyticsStatistic,
ConversationLog,
GroupJoinEvent,
PageView,
ScanEvent,
)
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep # noqa: F401
from app.model.official_site_agent_display import OfficialSiteAgentDisplay # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser # noqa: F401
from app.model.skill import Skill # noqa: F401
from app.model.wecom_sync import ( # noqa: F401
WeComBot,
WeComCustomerGroup,
WeComGroupCreateRequest,
WeComJobConfig,
WeComMessage,
WeComSyncCheckpoint,
)
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub
from app.service.active_session_service import ActiveSessionService
from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService
agent_hub_instance = None
configure_logging("backend", logging.INFO)
runtime_settings = ConfigLoader().load_settings()
base_path = (runtime_settings.server.base_path or "").rstrip("/")
docs_url = f"{base_path}/docs" if base_path else "/docs"
redoc_url = f"{base_path}/redoc" if base_path else "/redoc"
openapi_url = f"{base_path}/openapi.json" if base_path else "/openapi.json"
oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/docs/oauth2-redirect"
@asynccontextmanager
async def lifespan(app: FastAPI):
global agent_hub_instance
Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine)
config_loader = ConfigLoader()
settings = config_loader.load_settings()
db = SessionLocal()
session_service = ActiveSessionService(db=db)
use_console_im = os.getenv("USE_CONSOLE_IM")
if use_console_im is None:
use_console = settings.im.use_console
else:
use_console = use_console_im.lower() == "true"
if use_console:
im_service = ConsoleIMService()
else:
im_service = IMService(
base_url=os.getenv("IM_BASE_URL", settings.im.base_url),
api_key=os.getenv("IM_API_KEY", settings.im.api_key),
)
agent_hub_instance = AgentHub(
config_loader=config_loader,
session_service=session_service,
im_service=im_service,
)
yield
if agent_hub_instance:
await agent_hub_instance.close()
db.close()
app = FastAPI(
title="Agent Admin API",
version="1.0.0",
lifespan=lifespan,
docs_url=docs_url,
redoc_url=redoc_url,
openapi_url=openapi_url,
swagger_ui_oauth2_redirect_url=oauth2_redirect_url,
)
@app.exception_handler(HTTPException)
async def http_exception_handler(_: Request, exc: HTTPException):
message = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
return JSONResponse(
status_code=exc.status_code,
content=error_response_payload(exc.status_code, message),
)
@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(_: Request, exc: RequestValidationError):
first_error = exc.errors()[0] if exc.errors() else {}
loc = ".".join(str(part) for part in first_error.get("loc", []) if part != "body")
msg = first_error.get("msg", "请求参数不合法")
detail = f"参数校验失败:{loc} {msg}".strip()
return JSONResponse(
status_code=400,
content=error_response_payload(400, detail),
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(_: Request, exc: Exception):
return JSONResponse(
status_code=500,
content=error_response_payload(500, str(exc) or "服务器内部错误"),
)
@app.middleware("http")
async def wrap_json_response(request: Request, call_next):
response = await call_next(request)
if request.url.path in {openapi_url, docs_url, oauth2_redirect_url, redoc_url}:
return response
content_type = response.headers.get("content-type", "")
if "application/json" not in content_type.lower():
return response
if response.status_code >= 400:
return response
body = b""
async for chunk in response.body_iterator:
body += chunk
if not body:
return Response(
content=body,
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.media_type,
)
payload = json.loads(body)
if is_wrapped_payload(payload):
wrapped = format_response_datetimes(payload)
else:
wrapped = format_response_datetimes(success_response_payload(response.status_code, payload))
headers = {
key: value
for key, value in response.headers.items()
if key.lower() != "content-length"
}
return JSONResponse(
status_code=response.status_code,
content=wrapped,
headers=headers,
)
app.include_router(api_router, prefix=base_path)
@app.get(f"{base_path}/health" if base_path else "/health")
def health_check():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
runtime_settings = ConfigLoader().load_settings()
uvicorn.run(
"app.main:app",
host=runtime_settings.server.host,
port=runtime_settings.server.port,
reload=runtime_settings.server.reload,
)