| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- from datetime import datetime
- import httpx
- from app.config.config import settings
- from app.utils.rsa_crypto import BishengCrypto
- class BishengService:
- def __init__(self, base_url: str):
- self.base_url = base_url
- async def register(self, username: str, password: str):
- public_key = await self.get_public_key_api()
- password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
- async with httpx.AsyncClient() as client:
- response = await client.post(
- f"{self.base_url}/api/v1/user/regist",
- json={"user_name": username, "password": password},
- headers={'Content-Type': 'application/json'}
- )
- if response.status_code != 200 and response.status_code != 201:
- raise Exception(f"Bisheng registration failed: {response.text}")
- async def login(self, username: str, password: str) -> str:
- public_key = await self.get_public_key_api()
- password = BishengCrypto(public_key, settings.PRIVATE_KEY).encrypt(password)
- async with httpx.AsyncClient() as client:
- response = await client.post(
- f"{self.base_url}/api/v1/user/login",
- json={"user_name": username, "password": password},
- headers={'Content-Type': 'application/json'}
- )
- if response.status_code != 200 and response.status_code != 201:
- raise Exception(f"Bisheng login failed: {response.text}")
- return response.json().get('data', {}).get('access_token')
- async def get_public_key_api(self) -> dict:
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f"{self.base_url}/api/v1/user/public_key",
- headers={'Content-Type': 'application/json'}
- )
- if response.status_code != 200:
- raise Exception(f"Failed to get public key: {response.text}")
- return response.json().get('data', {}).get('public_key')
- async def get_chat_sessions(self, token: str) -> list:
- url = f"{self.base_url}/api/v1/chat/list?page=1&limit=40"
- headers = {'cookie': f"access_token_cookie={token};"}
- async with httpx.AsyncClient() as client:
- response = await client.get(url, headers=headers)
- if response.status_code != 200:
- raise Exception(f"Failed to fetch data from Bisheng API: {response.text}")
- data = response.json().get("data", [])
- result = [
- {
- "id": item["chat_id"],
- "name": item["latest_message"]["message"],
- "updated_time": int(datetime.strptime(item["update_time"], "%Y-%m-%dT%H:%M:%S").timestamp() * 1000)
- }
- for item in data
- ]
- return result
|