| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714 |
- import time
- import requests
- from typing import List
- from app.core.logger import logger
- from fastapi import APIRouter, Query, Depends, Body, UploadFile, File, HTTPException
- from fastapi.responses import RedirectResponse
- from sqlalchemy.orm import Session
- from app.core.redis import get_redis_client
- from app.core.database import get_db
- from redis.asyncio import Redis
- from app.schemas.user import UserOut
- from app.schemas.troov import TroovRate
- from app.schemas.sms import ShortMessageDetail
- from app.schemas.configuration import ConfigurationCreate, ConfigurationUpdate, ConfigurationOut
- from app.schemas.email_authorizations import EmailContent, EmailAuthorizationCreate, EmailAuthorizationUpdate, EmailAuthorizationOut
- from app.schemas.card import CardCreate, CardOut
- from app.schemas.task import TaskCreate, TaskOut, TaskUpdate
- from app.schemas.short_url import ShortUrlCreate
- from app.schemas.auto_booking import AutoBookingCreate, AutoBookingOut
- from app.schemas.http_session import HttpSessionCreate, HttpSessionUpdate,HttpSessionOut
- from app.schemas.visafly_config import VisaflyConfigCreate, VisaflyConfigOut
- from app.schemas.slot import SlotCreate, SlotOut
- from app.services.configuration_service import ConfigurationService
- from app.services.troov_service import get_rate_by_date
- from app.services.sms_service import save_short_message, query_short_message
- from app.services.email_authorizations_service import EmailAuthorizationService
- from app.services.short_url_service import ShortUrlService
- from app.services.task_service import TaskService
- from app.services.card_service import CardService
- from app.services.seaweedfs_service import SeaweedFSService
- from app.services.auto_booking_service import AutoBookingService
- from app.services.http_session_service import HttpSessionService
- from app.services.visafly_config_service import VisaflyConfigService
- from app.services.slot_service import SlotService
- # 公共路由
- public_router = APIRouter()
- # 受保护路由
- protected_router = APIRouter()
- @public_router.get("/ping", summary="心跳检测", tags=["测试接口"])
- def ping():
- return {"message": "pong"}
- @protected_router.get("/users", summary="查询用户", tags=["通用接口"], response_model=List[UserOut])
- def get_users():
- return [
- {"id": 1, "name": "Alice"},
- {"id": 2, "name": "Bob"}
- ]
- @public_router.get("/sms/upload", summary="上报短信", tags=["短信接口"], response_model=ShortMessageDetail)
- def sms_upload(
- phone: str = Query(..., description="手机号"),
- message: str = Query(..., description="短信内容"),
- max_ttl: int = Query(300, description="短信保存时间(秒)"),
- redis_client: Redis = Depends(get_redis_client)
- ):
- """
- 保存短信到 Redis
- """
- received_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
- msg = save_short_message(redis_client, phone, message, received_at, max_ttl)
- return msg
- @protected_router.get("/sms/download", summary="读取短信", tags=["短信接口"], response_model=List[ShortMessageDetail])
- def sms_download(
- phone: str = Query(..., description="手机号"),
- keyword: str = Query('', description="短信内容关键字"),
- sent_at: str = Query('', description="筛选时间(可选)"),
- redis_client: Redis = Depends(get_redis_client)
- ):
- """
- 查询短信(支持关键字和时间过滤)
- """
- results = query_short_message(redis_client, phone, keyword or None, sent_at or None)
- return results
- @protected_router.get("/troov/rate", summary="TROOV 查询rate", tags=["通用接口"], response_model=List[TroovRate])
- def troov_rate(date: str = Query(..., description="查询的日期, 格式: YYYY-MM-DD"),
- redis_client: Redis = Depends(get_redis_client)):
- # 调用 service 层获取数据
- return get_rate_by_date(redis_client, date)
- @protected_router.post("/dynamic-configurations", summary="创建动态配置", tags=["动态配置"], response_model=ConfigurationOut)
- def dynamic_config_create(config_in: ConfigurationCreate, db: Session = Depends(get_db)):
- existing = ConfigurationService.get_by_key(db, config_in.config_key)
- if existing:
- raise HTTPException(status_code=400, detail=f"配置 Key '{config_in.config_key}' 已存在")
- return ConfigurationService.create(db, config_in)
- @protected_router.get("/dynamic-configurations/all", summary="读取所有动态配置", tags=["动态配置"], response_model=List[ConfigurationOut])
- def dynamic_config_get_all(db: Session = Depends(get_db)):
- return ConfigurationService.get_all(db)
- @protected_router.get("/dynamic-configurations/key/{config_key}", summary="根据Key读取动态配置", tags=["动态配置"], response_model=ConfigurationOut)
- def dynamic_config_get_by_key(config_key: str, db: Session = Depends(get_db)):
- config = ConfigurationService.get_by_key(db, config_key)
- if not config:
- raise HTTPException(status_code=404, detail=f"配置 Key '{config_key}' 不存在")
- return config
- @protected_router.put("/dynamic-configurations/key/{config_key}", summary="根据Key更新动态配置", tags=["动态配置"], response_model=ConfigurationOut)
- def dynamic_config_update_by_key(config_key: str, config_in: ConfigurationUpdate, db: Session = Depends(get_db)):
- config = ConfigurationService.update_by_key(db, config_key, config_in)
- if not config:
- raise HTTPException(status_code=404, detail=f"配置 Key '{config_key}' 不存在")
- return config
- @protected_router.delete("/dynamic-configurations/key/{config_key}", summary="根据Key删除动态配置", tags=["动态配置"], response_model=ConfigurationOut)
- def dynamic_config_delete_by_key(config_key: str, db: Session = Depends(get_db)):
- config = ConfigurationService.delete_by_key(db, config_key)
- if not config:
- raise HTTPException(status_code=404, detail=f"配置 Key '{config_key}' 不存在")
- return config
- @protected_router.post(
- "/http-session",
- summary="创建http session",
- tags=["会话管理"],
- response_model=HttpSessionOut
- )
- def http_session_create(
- data: HttpSessionCreate,
- db: Session = Depends(get_db)
- ):
- logger.info(f"[Create HttpSession] sid={data.session_id}")
- return HttpSessionService.create(db, data)
- @protected_router.delete(
- "/http-session",
- summary="删除http session",
- tags=["会话管理"]
- )
- def http_session_delete_by_sid(
- session_id: str = Query(...),
- db: Session = Depends(get_db)
- ):
- logger.info(f"[Delete HttpSession] sid={session_id}")
- ok = HttpSessionService.delete_by_sid(db, session_id)
- if not ok:
- raise HTTPException(status_code=404, detail="session 不存在")
- return {"success": True, "session_id": session_id}
- @protected_router.put(
- "/http-session",
- summary="更新http session",
- tags=["会话管理"],
- response_model=HttpSessionOut
- )
- def http_session_update_by_sid(
- session_id: str = Query(...),
- data: HttpSessionUpdate = Body(...),
- db: Session = Depends(get_db)
- ):
- logger.info(f"[Update HttpSession] sid={session_id}")
- obj = HttpSessionService.update_by_sid(db, session_id, data)
- if not obj:
- raise HTTPException(status_code=404, detail="session 不存在")
- return obj
- @protected_router.get(
- "/http-session",
- summary="读取http session",
- tags=["会话管理"],
- response_model=HttpSessionOut
- )
- def http_session_get_by_sid(
- session_id: str = Query(...),
- db: Session = Depends(get_db)
- ):
- logger.info(f"[Get HttpSession] sid={session_id}")
- obj = HttpSessionService.get_by_sid(db, session_id)
- if not obj:
- raise HTTPException(status_code=404, detail="session 不存在")
- return obj
- @protected_router.get("/email-authorizations", summary="查询所有内部邮箱", tags=["邮箱接口"], response_model=List[EmailAuthorizationOut])
- def email_authorizations_get(db: Session = Depends(get_db)):
- return EmailAuthorizationService.get_all(db)
- @protected_router.post("/email-authorizations", summary="创建内部邮箱", tags=["邮箱接口"], response_model=EmailAuthorizationOut)
- def email_authorizations_create(data: EmailAuthorizationCreate, db: Session = Depends(get_db)):
- existing = EmailAuthorizationService.get_by_email(db, data.email)
- if existing:
- raise HTTPException(status_code=400, detail=f"邮箱 {data.email} 已存在")
- return EmailAuthorizationService.create(db, data)
- @protected_router.get("/email-authorizations/{id}", summary="通过id查询内部邮箱", tags=["邮箱接口"], response_model=EmailAuthorizationOut)
- def email_authorizations_get_by_id(id: int, db: Session = Depends(get_db)):
- email_auth = EmailAuthorizationService.get_by_id(db, id)
- if not email_auth:
- raise HTTPException(status_code=404, detail=f"ID={id} 的邮箱记录不存在")
- return email_auth
- @protected_router.put("/email-authorizations/{id}", summary="通过id更新内部邮箱", tags=["邮箱接口"], response_model=EmailAuthorizationOut)
- def email_authorizations_update_by_id(id: int, data: EmailAuthorizationUpdate, db: Session = Depends(get_db)):
- updated = EmailAuthorizationService.update(db, id, data)
- if not updated:
- raise HTTPException(status_code=404, detail=f"ID={id} 的邮箱记录不存在")
- return updated
- @protected_router.delete("/email-authorizations/{id}", summary="通过id删除内部邮箱", tags=["邮箱接口"], response_model=EmailAuthorizationOut)
- def email_authorizations_delete_by_id(id: int, db: Session = Depends(get_db)):
- deleted = EmailAuthorizationService.delete(db, id)
- if not deleted:
- raise HTTPException(status_code=404, detail=f"ID={id} 的邮箱记录不存在")
- return deleted
- @protected_router.get("/email-authorizations/email/{email}", summary="通过邮箱地址查询内部邮箱", tags=["邮箱接口"], response_model=EmailAuthorizationOut)
- def email_authorizations_get_by_email(email: str, db: Session = Depends(get_db)):
- email_auth = EmailAuthorizationService.get_by_email(db, email)
- if not email_auth:
- raise HTTPException(status_code=404, detail=f"邮箱 {email} 不存在")
- return email_auth
- @protected_router.post("/email-authorizations/fetch", summary="读取邮件, 仅限文本内容", tags=["邮箱接口"])
- def email_authorizations_fetch_email(
- email: str = Query(..., description="收件邮箱账号, 格式: xxx@xxx.xxx"),
- sender: str = Query(..., description="发件人邮箱账号或者名字"),
- recipient: str = Query(..., description="收件人账号或者名字"),
- subjectKeywords: str = Query("", description="邮件主题关键词, 支持多个关键词, 用逗号隔开"),
- bodyKeywords: str = Query("", description="邮件内容关键词, 支持多个关键词, 用逗号隔开"),
- sentDate: str = Query(..., description="发件日期, UTC时间, 格式: yyyy-mm-dd hh:mm:ss"),
- expiry: int = Query(300, description="邮件有效期, 单位秒, 从sentDate 开始算起"),
- db: Session = Depends(get_db)
- ):
- auth = EmailAuthorizationService.get_by_email(db, email)
- if not auth:
- raise HTTPException(status_code=404, detail=f"未找到邮箱授权记录: {email}")
- result = EmailAuthorizationService.fetch_email_authorizations(
- auth,
- sender=sender,
- recipient=recipient,
- subject_keywords=subjectKeywords,
- body_keywords=bodyKeywords,
- sent_date=sentDate,
- expiry=expiry,
- only_text=True
- )
- if result is None:
- raise HTTPException(status_code=404, detail="在有效期内未找到匹配邮件")
- return {"body": result}
- @protected_router.post("/email-authorizations/fetch-top", summary="从最近的几封邮件读取目标邮件,仅限文本内容, 性能会更好, 邮件多时有可能漏读", tags=["邮箱接口"])
- def email_authorizations_fetch_email_from_topn(
- email: str = Query(..., description="收件邮箱账号, 格式: xxx@xxx.xxx"),
- sender: str = Query(..., description="发件人邮箱账号或者名字"),
- recipient: str = Query(..., description="收件人账号或者名字"),
- subjectKeywords: str = Query("", description="邮件主题关键词, 支持多个关键词, 用逗号隔开"),
- bodyKeywords: str = Query("", description="邮件内容关键词, 支持多个关键词, 用逗号隔开"),
- top: int = Query(10, description="指定从最近几封邮件读取"),
- db: Session = Depends(get_db)
- ):
- auth = EmailAuthorizationService.get_by_email(db, email)
- if not auth:
- raise HTTPException(status_code=404, detail=f"未找到邮箱授权记录: {email}")
- result = EmailAuthorizationService.fetch_email_authorizations_from_top_n(
- auth,
- sender=sender,
- recipient=recipient,
- subject_keywords=subjectKeywords,
- body_keywords=bodyKeywords,
- top=top,
- only_text=True
- )
- if result is None:
- raise HTTPException(status_code=404, detail=f"未在前{top}封邮件中查找到匹配邮件")
- return {"body": result}
- @protected_router.post("/email-authorizations/forward", summary="转发邮件", tags=["邮箱接口"])
- def email_authorizations_forward_email(
- emailAccount: str = Query(..., description="收件邮箱账号, 格式: xxx@xxx.xxx"),
- forwardTo: str = Query(..., description="转发到哪个邮箱地址, 格式: xxx@xxx.xxx"),
- sender: str = Query(..., description="发件人邮箱账号或者名字"),
- recipient: str = Query(..., description="收件人账号或者名字"),
- subjectKeywords: str = Query("", description="邮件主题关键词, 支持多个关键词, 用逗号隔开"),
- bodyKeywords: str = Query("", description="邮件内容关键词, 支持多个关键词, 用逗号隔开"),
- db: Session = Depends(get_db)
- ):
- auth = EmailAuthorizationService.get_by_email(db, emailAccount)
- if not auth:
- raise HTTPException(status_code=404, detail=f"未找到邮箱授权记录: {emailAccount}")
- result = EmailAuthorizationService.forward_first_matching_email(
- auth,
- forward_to = forwardTo,
- sender = sender,
- recipient = recipient,
- subject_keywords = subjectKeywords,
- body_keywords = bodyKeywords
- )
- if result is None:
- raise HTTPException(status_code=404, detail=f"未找可转发的邮件")
- return {"body": result}
- @protected_router.post("/email-authorizations/sendmail", summary="发送邮件", tags=["邮箱接口"])
- def email_authorizations_send_email(
- emailAccount: str = Query(..., description="收件邮箱账号, 格式: xxx@xxx.xxx"),
- sendTo: str = Query(..., description="收件人邮箱账号"),
- subject: str = Query(..., description="邮件主题"),
- contentType: str = Query("text", description="内容格式,支持 text 和 html"),
- content: EmailContent = Body("", description="邮件内容"),
- db: Session = Depends(get_db)
- ):
- auth = EmailAuthorizationService.get_by_email(db, emailAccount)
- if not auth:
- raise HTTPException(status_code=404, detail=f"未找到邮箱授权记录: {emailAccount}")
- result = EmailAuthorizationService.send_email(
- auth,
- send_to = sendTo,
- subject = subject,
- content_type = contentType,
- content = content.body
- )
- if result is None:
- raise HTTPException(status_code=404, detail=f"邮件发送失败")
- return {"body": result}
- @protected_router.post("/email-authorizations/sendmail-bulk", summary="群发送邮件", tags=["邮箱接口"])
- def email_authorizations_send_email_bulk(
- emailAccount: str = Query(..., description="收件邮箱账号, 格式: xxx@xxx.xxx"),
- sendTo: str = Query(..., description="收件人邮箱账号,多个用逗号隔开"),
- subject: str = Query(..., description="邮件主题"),
- contentType: str = Query("text", description="内容格式,支持 text 和 html"),
- content: EmailContent = Body(..., description="邮件内容"),
- db: Session = Depends(get_db)
- ):
- auth = EmailAuthorizationService.get_by_email(db, emailAccount)
- if not auth:
- raise HTTPException(status_code=404, detail=f"未找到邮箱授权记录: {emailAccount}")
- result = EmailAuthorizationService.send_email_bulk(
- auth,
- send_to = sendTo,
- subject = subject,
- content_type = contentType,
- content = content.body
- )
- if result is None:
- raise HTTPException(status_code=404, detail=f"邮件发送失败")
- return {"body": result}
- @protected_router.post("/resource/pdf", summary="上传pdf文件", tags=["文件管理"])
- def resource_upload_pdf(pdf: UploadFile = File(...)):
- if not pdf.filename.lower().endswith(".pdf"):
- raise HTTPException(status_code=400, detail="仅支持上传 PDF 文件")
- result = SeaweedFSService.upload(pdf)
- if not result:
- raise HTTPException(status_code=500, detail="上传失败")
- return {"success": True, "fid": result["fid"], "url": result["url"]}
- @protected_router.get("/resource/pdf/{fid}", summary="读取pdf", tags=["文件管理"])
- def resource_get_pdf(fid: str):
- data = SeaweedFSService.get(fid)
- if not data:
- raise HTTPException(status_code=404, detail="文件不存在")
- content, mime = data
- return Response(content=content, media_type=mime)
- @protected_router.delete("/resource/pdf/{fid}", summary="删除pdf文件", tags=["文件管理"])
- def resource_delete_pdf(fid: str):
- ok = SeaweedFSService.delete(fid)
- if not ok:
- raise HTTPException(status_code=404, detail="文件不存在或删除失败")
- return {"success": True, "fid": fid}
- @protected_router.post("/resource/image", summary="上传图片", tags=["文件管理"])
- def resource_upload_image(image: UploadFile = File(...)):
- if not image.content_type.startswith("image/"):
- raise HTTPException(status_code=400, detail="仅支持上传图片文件")
- print('upload')
- result = SeaweedFSService.upload(image)
- if not result:
- raise HTTPException(status_code=500, detail="上传失败")
- return {"success": True, "fid": result["fid"], "url": result["url"]}
- @protected_router.get("/resource/image/{fid}", summary="读取图片", tags=["文件管理"])
- def resource_get_image(fid: str):
- data = SeaweedFSService.get(fid)
- if not data:
- raise HTTPException(status_code=404, detail="图片不存在")
- content, mime = data
- return Response(content=content, media_type=mime)
- @protected_router.delete("/resource/image/{fid}", summary="删除图片", tags=["文件管理"])
- def resource_delete_image(fid: str):
- ok = SeaweedFSService.delete(fid)
- if not ok:
- raise HTTPException(status_code=404, detail="图片不存在或删除失败")
- return {"success": True, "fid": fid}
- @protected_router.post("/s/generate", summary="生成短链接地址<压缩地址长度>", tags=["Short URL"])
- def short_url_generate(
- data: ShortUrlCreate,
- db: Session = Depends(get_db),
- ):
- """生成短链接"""
- record = ShortUrlService.create_short_url(db, data.longUrl)
- return {
- "short_key": record.short_key,
- "short_url": f"/s/{record.short_key}",
- "long_url": record.long_url,
- "created_at": record.created_at,
- }
- @public_router.get("/s/{shortKey}", summary="访问短链接地址<自动重定向到真实链接地址>", tags=["Short URL"])
- def short_url_request(shortKey: str, db: Session = Depends(get_db)):
- """访问短链接自动重定向"""
- long_url = ShortUrlService.get_long_url(db, shortKey)
- if not long_url:
- raise HTTPException(status_code=404, detail="短链接不存在或已失效")
- return RedirectResponse(url=long_url, status_code=302)
- @protected_router.post("/tasks", summary="创建任务", tags=["任务管理接口"], response_model=TaskOut)
- def task_create(data: TaskCreate, db: Session = Depends(get_db)):
- """创建任务"""
- return TaskService.create(db, data)
- @protected_router.get("/tasks/{taskId:int}", summary="根据taskId读取任务状态", tags=["任务管理接口"], response_model=TaskOut)
- def task_get_by_id(taskId: int, db: Session = Depends(get_db)):
- """获取任务"""
- task = TaskService.get_by_id(db, taskId)
- if not task:
- raise HTTPException(status_code=404, detail=f"任务 {taskId} 不存在")
- return task
- @protected_router.get("/tasks/pending", summary="获取等待执行的任务", tags=["任务管理接口"], response_model=List[TaskOut])
- def task_get_pending(
- page: int = Query(0, description="第几页"),
- size: int = Query(10, description="分页大小"),
- command: str = Query(..., description="任务类型"),
- db: Session = Depends(get_db),
- ):
- """分页获取等待执行的任务"""
- return TaskService.get_pending(db, command, page, size)
- @protected_router.put("/tasks/{taskId}", summary="根据taskId更新任务状态", tags=["任务管理接口"], response_model=TaskOut)
- def task_update_by_id(taskId: int, data: TaskUpdate, db: Session = Depends(get_db)):
- """更新任务状态或结果"""
- updated = TaskService.update(db, taskId, data)
- if not updated:
- raise HTTPException(status_code=404, detail=f"任务 {taskId} 不存在")
- return updated
- @protected_router.post("/tg/send_message", summary="推送电报消息", tags=["消息推送接口"])
- def tg_send_message(
- apiToken: str = Query(..., description="电报的APITOKEN"),
- chatID: str = Query(..., description="电报群ID"),
- message: str = Query(..., description="推送的文本信息")
- ):
- url = f"https://api.telegram.org/bot{apiToken}/sendMessage"
- payload = {
- "chat_id": chatID,
- "text": message,
- "parse_mode": "HTML"
- }
- try:
- response = requests.post(url, json=payload, timeout=10)
- if response.status_code != 200:
- # logger.error(f"Telegram 推送失败: {response.text}")
- raise HTTPException(status_code=500, detail=f"Telegram 推送失败: {response.text}")
- return {"success": True, "detail": "Telegram 消息推送成功"}
- except Exception as e:
- # logger.exception("Telegram 发送消息异常")
- raise HTTPException(status_code=500, detail=str(e))
- @protected_router.post("/tg/send_image", summary="推送电报图片", tags=["消息推送接口"])
- def tg_send_image(
- apiToken: str = Query(..., description="电报的APITOKEN"),
- chatID: str = Query(..., description="电报群ID"),
- message: str = Query("", description="推送的文本信息"),
- image: UploadFile = File(..., description="推送的图像文件")
- ):
- url = f"https://api.telegram.org/bot{apiToken}/sendPhoto"
- files = {"photo": (image.filename, image.file, image.content_type)}
- data = {"chat_id": chatID, "caption": message}
- try:
- response = requests.post(url, data=data, files=files, timeout=15)
- if response.status_code != 200:
- # logger.error(f"Telegram 图片推送失败: {response.text}")
- raise HTTPException(status_code=500, detail=f"Telegram 图片推送失败: {response.text}")
- return {"success": True, "detail": "Telegram 图片推送成功"}
- except Exception as e:
- # logger.exception("Telegram 发送图片异常")
- raise HTTPException(status_code=500, detail=str(e))
- @protected_router.post("/wechat/send", summary="推送微信消息", tags=["消息推送接口"])
- def wechat_send(
- apikey: str = Query(..., description="企业微信的APITOKEN"),
- message: str = Query(..., description="推送的文本信息")
- ):
- """
- 企业微信 WebHook 格式:
- https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY
- """
- url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={apikey}"
- payload = {"msgtype": "text", "text": {"content": message}}
- try:
- response = requests.post(url, json=payload, timeout=10)
- data = response.json()
- if response.status_code != 200 or data.get("errcode") != 0:
- # logger.error(f"企业微信推送失败: {response.text}")
- raise HTTPException(status_code=500, detail=f"企业微信推送失败: {response.text}")
- return {"success": True, "detail": "企业微信消息推送成功"}
- except Exception as e:
- # logger.exception("企业微信推送异常")
- raise HTTPException(status_code=500, detail=str(e))
- @protected_router.post("/cards/publish", summary="创建新的消息卡片", tags=["信息卡片接口"], response_model=CardOut)
- def cards_publish(
- data: CardCreate = Body(...),
- db: Session = Depends(get_db)
- ):
- return CardService.create(db, data)
- @public_router.get("/cards/view", summary="分页读取全部卡片, 可选择语言", tags=["信息卡片接口"], response_model=List[CardOut])
- def cards_view_paginated(
- page: int = Query(0, description="第几页"),
- size: int = Query(10, description="分页大小"),
- culture: str = Query("english", description="语言, 可设置 chinese, english"),
- db: Session = Depends(get_db)
- ):
- return CardService.get_paginated(db, page, size, culture)
- @public_router.get("/cards/view2", summary="根据关键词分页查询卡片, 可选择语言", tags=["信息卡片接口"], response_model=List[CardOut])
- def cards_view_paginated2(
- keywords: str = Query("", description="查询的关键词,多个关键词用逗号隔开"),
- page: int = Query(0, description="第几页"),
- size: int = Query(10, description="分页大小"),
- culture: str = Query("english", description="语言, 可设置 chinese, english"),
- db: Session = Depends(get_db)
- ):
- keyword_list = [k.strip() for k in keywords.split(",") if k.strip()]
- return CardService.get_by_keywords(db, keyword_list, page, size, culture)
- @protected_router.post("/autobooking", summary="创建自动预定订单", tags=["自动预定订单管理接口"], response_model=AutoBookingOut)
- def autobooking_create(data: AutoBookingCreate, db: Session = Depends(get_db)):
- return AutoBookingService.create(db, data)
- @protected_router.post("/autobooking/create-by-ai", summary="用自然语言创建自动预定订单(底层使用chatgpt)", tags=["自动预定订单管理接口"])
- def autobooking_create_by_ai():
- # TODO: 这里可以对接 GPT 解析自然语言生成结构化 AutoBooking 数据
- return {"message": "AI 自动创建暂未实现"}
- @protected_router.post("/autobooking/batch", summary="批量查询多个自动预定订单信息", tags=["自动预定订单管理接口"])
- def autobooking_get_by_ids(ids: List[int] = Body(...), db: Session = Depends(get_db)):
- return AutoBookingService.batch_get_by_ids(db, ids)
- @protected_router.get("/autobooking", summary="分页查询所有的自动预定订单信息", tags=["自动预定订单管理接口"], response_model=List[AutoBookingOut])
- def autobooking_get_paginated(
- tech_provider: str = Query("", description="签证网站技术提供商"),
- keyword: str = Query("", description="关键词查询"),
- page: int = Query(0, description="第几页"),
- size: int = Query(10, description="分页大小"),
- db: Session = Depends(get_db)
- ):
- return AutoBookingService.get_paginated(db, tech_provider, keyword, page, size)
- @protected_router.get("/autobooking/{id:int}", summary="根据id查询自动预定订单详情", tags=["自动预定订单管理接口"], response_model=AutoBookingOut)
- def autobooking_get_by_id(id: int, db: Session = Depends(get_db)):
- result = AutoBookingService.get_by_id(db, id)
- if not result:
- raise HTTPException(status_code=404, detail="未找到订单")
- return result
- @protected_router.delete("/autobooking/{id:int}", summary="根据id删除自动预定订单", tags=["自动预定订单管理接口"])
- def autobooking_delete_by_id(id: int, db: Session = Depends(get_db)):
- ok = AutoBookingService.delete_by_id(db, id)
- if not ok:
- raise HTTPException(status_code=404, detail="删除失败或记录不存在")
- return {"success": True, "id": id}
- @protected_router.put("/autobooking/{id:int}", summary="根据id更新自动预定订单信息", tags=["自动预定订单管理接口"], response_model=AutoBookingOut)
- def autobooking_update_by_id(id: int, updated_order_info: dict = Body(...), db: Session = Depends(get_db)):
- result = AutoBookingService.update_by_id(db, id, updated_order_info)
- if not result:
- raise HTTPException(status_code=404, detail="更新失败或记录不存在")
- return result
- @protected_router.get("/autobooking/statistics", summary="统计自动预定订单信息", tags=["自动预定订单管理接口"])
- def autobooking_statistics(
- tech_provider: str = Query("", description="签证网站技术提供商"),
- db: Session = Depends(get_db)
- ):
- return AutoBookingService.statistics(db, tech_provider)
- @protected_router.get("/autobooking/pending", summary="获取未处理的自动预定订单信息列表", tags=["自动预定订单管理接口"], response_model=List[AutoBookingOut])
- def autobooking_pending(
- tech_provider: str = Query("", description="签证网站技术提供商"),
- db: Session = Depends(get_db)
- ):
- return AutoBookingService.get_pending(db, tech_provider)
- @protected_router.get("/autobooking/trigger-finish", summary="触发自动预定订单完成操作", tags=["自动预定订单管理接口"])
- def autobooking_trigger_finish(id: int):
- pass
- @protected_router.post("/stripe-price/create", summary="创建stripe 商品", tags=["Stripe 操作接口"])
- def stripe_price_create(
- stripePrice: str = Body(..., description="stripe 商品价格信息")
- ):
- pass
- @protected_router.post(
- "/slot/report",
- summary="上报 slot 记录",
- tags=["SLOT接口"],
- response_model=SlotOut
- )
- def slot_report(data: SlotCreate = Body(...), db: Session = Depends(get_db)):
- logger.info(f"[Slot Report] {data}")
- return SlotService.report(db, data)
- @protected_router.get(
- "/slot/search",
- summary="查询 slot 记录",
- tags=["SLOT接口"],
- response_model=SlotOut
- )
- def slot_search(
- submit_city: str = Query(..., description="提交城市"),
- travel_country: str = Query(..., description="旅行国家"),
- visa_type: str = Query(..., description="签证类别"),
- date_type: str = Query("latest", description="查询方式, latest 最近一条上报的信息, earliest 最早的日期"),
- db: Session = Depends(get_db)
- ):
- result = SlotService.search(db, submit_city, travel_country, visa_type, date_type)
- if not result:
- raise HTTPException(status_code=404, detail="未找到相关记录")
- return result
- @protected_router.post(
- "/visafly-config",
- summary="创建一条可以被前端查询到的签证类别",
- tags=["visafly-config接口"],
- response_model=VisaflyConfigOut
- )
- def visafly_config_create(
- visafly_config: VisaflyConfigCreate = Body(...),
- db: Session = Depends(get_db)
- ):
- logger.info(f"[VisaflyConfig Create] {visa_slot_queries}")
- return VisaflyConfigService.create(db, visa_slot_queries)
- @protected_router.get(
- "/visafly-config/submission-countries",
- summary="查询支持从哪些国家递交申请",
- tags=["visafly-config接口"]
- )
- def visafly_config_get_submission_countries(db: Session = Depends(get_db)):
- return VisaflyConfigService.get_submission_countries(db)
- @protected_router.get(
- "/visafly-config/cities",
- summary="查询支持从哪个国家的哪些城市递交申请",
- tags=["visafly-config接口"]
- )
- def visafly_config_get_cities_by_country_code(
- country_code: str = Query(..., description="递交申请的国家编号,大写的两个英文字符"),
- db: Session = Depends(get_db)
- ):
- return VisaflyConfigService.get_cities_by_country(db, country_code)
- @protected_router.get(
- "/visafly-config/travel-countries-with-categories",
- summary="查询某个城市可以办理哪些国家的签证(包含签证类别)",
- tags=["visafly-config接口"]
- )
- def visafly_config_get_travel_countries_by_city_code(
- city_code: str = Query(..., description="递交申请的城市编号,大写的三个英文字符"),
- db: Session = Depends(get_db)
- ):
- return VisaflyConfigService.get_travel_countries_by_city(db, city_code)
|