inbox/services/core.py

60 lines
1.6 KiB
Python
Raw Normal View History

2023-12-17 17:13:17 +00:00
from typing import Any, List
2023-11-30 06:49:23 +00:00
import aiohttp
2023-12-17 21:10:29 +00:00
from aiohttp import ClientResponse, ClientSession
2023-11-22 12:09:24 +00:00
from models.member import ChatMember
2023-12-17 17:13:17 +00:00
from settings import API_BASE
2023-10-04 20:42:39 +00:00
2023-10-11 19:12:55 +00:00
headers = {"Content-Type": "application/json"}
2023-11-14 18:25:55 +00:00
2023-10-04 20:42:39 +00:00
2023-11-28 09:05:39 +00:00
async def _request_endpoint(query_name, body) -> Any:
2023-11-30 06:49:23 +00:00
async with aiohttp.ClientSession() as session:
2023-12-17 23:34:10 +00:00
async with session.post(API_BASE, headers=headers, json=body) as response:
print(f"[services.core] {query_name} response: <{response.status}> {await response.text()}")
if response.status == 200:
2023-11-30 06:49:23 +00:00
r = await response.json()
if r:
return r.get("data", {}).get(query_name, {})
2023-12-17 23:34:10 +00:00
return []
2023-11-28 09:05:39 +00:00
2023-11-22 12:09:24 +00:00
async def get_all_authors() -> List[ChatMember]:
2023-11-14 18:20:45 +00:00
query_name = "authorsAll"
2023-11-06 16:25:28 +00:00
2023-10-04 20:42:39 +00:00
gql = {
2023-12-18 07:24:42 +00:00
"query": "query { " + query_name + " { id slug pic name } }",
2023-11-14 18:20:45 +00:00
"variables": None,
2023-10-04 20:42:39 +00:00
}
2023-11-22 12:09:24 +00:00
2023-12-17 21:54:44 +00:00
return await _request_endpoint(query_name, gql)
2023-10-04 20:42:39 +00:00
2023-10-11 19:12:55 +00:00
2023-11-28 08:33:50 +00:00
async def get_my_followed() -> List[ChatMember]:
query_name = "get_my_followed"
2023-10-11 19:12:55 +00:00
gql = {
2023-12-18 07:24:42 +00:00
"query": "query { " + query_name + " { authors { id slug pic name } } }",
2023-11-14 18:20:45 +00:00
"variables": None,
2023-10-11 19:12:55 +00:00
}
2023-11-22 12:09:24 +00:00
2023-12-18 07:24:42 +00:00
result = await _request_endpoint(query_name, gql)
return result.get("authors", [])
2023-11-28 09:05:39 +00:00
2023-12-17 23:53:25 +00:00
async def get_author(user: str = ""):
2023-12-18 00:04:25 +00:00
query_name = "get_author_id"
operation = "GetAuthorId"
2023-11-28 09:05:39 +00:00
gql = {
2023-12-18 00:09:07 +00:00
"query": f"query {operation}($user: String!) {{ {query_name}(user: $user) {{ id slug pic name }} }}",
2023-11-28 09:05:39 +00:00
"operationName": operation,
2023-12-17 23:53:25 +00:00
"variables": {"user": user},
2023-11-28 09:05:39 +00:00
}
2023-12-17 23:34:10 +00:00
r = await _request_endpoint(query_name, gql)
2023-12-17 23:55:49 +00:00
if r and isinstance(r, list):
2023-12-17 23:45:31 +00:00
r = r.pop()
2023-12-17 23:57:14 +00:00
return r or None