bisheng.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from datetime import datetime
  2. import httpx
  3. from app.config.config import settings
  4. from app.utils.rsa_crypto import BishengCrypto
  5. class BishengService:
  6. def __init__(self, base_url: str):
  7. self.base_url = base_url
  8. async def register(self, username: str, password: str):
  9. public_key = await self.get_public_key_api()
  10. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  11. async with httpx.AsyncClient() as client:
  12. response = await client.post(
  13. f"{self.base_url}/api/v1/user/regist",
  14. json={"user_name": username, "password": password},
  15. headers={'Content-Type': 'application/json'}
  16. )
  17. if response.status_code != 200 and response.status_code != 201:
  18. raise Exception(f"Bisheng registration failed: {response.text}")
  19. async def login(self, username: str, password: str) -> str:
  20. public_key = await self.get_public_key_api()
  21. password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
  22. async with httpx.AsyncClient() as client:
  23. response = await client.post(
  24. f"{self.base_url}/api/v1/user/login",
  25. json={"user_name": username, "password": password},
  26. headers={'Content-Type': 'application/json'}
  27. )
  28. if response.status_code != 200 and response.status_code != 201:
  29. raise Exception(f"Bisheng login failed: {response.text}")
  30. return response.json().get('data', {}).get('access_token')
  31. async def get_public_key_api(self) -> dict:
  32. async with httpx.AsyncClient() as client:
  33. response = await client.get(
  34. f"{self.base_url}/api/v1/user/public_key",
  35. headers={'Content-Type': 'application/json'}
  36. )
  37. if response.status_code != 200:
  38. raise Exception(f"Failed to get public key: {response.text}")
  39. return response.json().get('data', {}).get('public_key')
  40. async def get_chat_sessions(self, token: str) -> list:
  41. url = f"{self.base_url}/api/v1/chat/list?page=1&limit=40"
  42. headers = {'cookie': f"access_token_cookie={token};"}
  43. async with httpx.AsyncClient() as client:
  44. response = await client.get(url, headers=headers)
  45. if response.status_code != 200:
  46. raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
  47. data = response.json().get("data", [])
  48. result = [
  49. {
  50. "id": item["chat_id"],
  51. "name": item["latest_message"]["message"],
  52. "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000)
  53. }
  54. for item in data
  55. ]
  56. return result