sms.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import time
  2. from typing import List
  3. from fastapi import APIRouter, Query, Depends
  4. from app.core.redis import get_redis_client
  5. from redis.asyncio import Redis
  6. from app.utils.response import success
  7. from app.schemas.common import ApiResponse
  8. from app.schemas.sms import ShortMessageDetail, SmsSendIn
  9. from app.services.sms_service import query_short_message, save_short_message, send_sms
  10. public_router = APIRouter()
  11. protected_router = APIRouter()
  12. admin_required_router = APIRouter()
  13. @admin_required_router.get("/sms/upload", summary="上报短信", tags=["短信接口"], response_model=ApiResponse[ShortMessageDetail])
  14. async def sms_upload(
  15. phone: str = Query(..., description="手机号"),
  16. message: str = Query(..., description="短信内容"),
  17. max_ttl: int = Query(300, description="短信保存时间(秒)"),
  18. redis_client: Redis = Depends(get_redis_client)
  19. ):
  20. """
  21. 保存短信到 Redis
  22. """
  23. received_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
  24. msg = await save_short_message(redis_client, phone, message, received_at, max_ttl)
  25. return success(data=msg)
  26. @admin_required_router.get("/sms/download", summary="读取短信", tags=["短信接口"], response_model=ApiResponse[List[ShortMessageDetail]])
  27. async def sms_download(
  28. phone: str = Query(..., description="手机号"),
  29. keyword: str = Query('', description="短信内容关键字"),
  30. sent_at: str = Query('', description="筛选时间(可选)"),
  31. redis_client: Redis = Depends(get_redis_client)
  32. ):
  33. """
  34. 查询短信(支持关键字和时间过滤)
  35. """
  36. obj = await query_short_message(redis_client, phone, keyword or None, sent_at or None)
  37. return success(data=obj)
  38. @admin_required_router.post("/sms/send", summary="发送短信", tags=["短信接口"], response_model=ApiResponse[str])
  39. async def sms_send(
  40. payload: SmsSendIn,
  41. ):
  42. res = await send_sms(
  43. send_to=payload.send_to,
  44. sender=payload.sender,
  45. content=payload.content,
  46. )
  47. return success(data=res)