inbox/services/core.py
2023-10-13 14:25:20 +03:00

80 lines
2.5 KiB
Python

import json
from httpx import AsyncClient
from settings import API_BASE
headers = {"Content-Type": "application/json"}
async def get_author(author_id):
gql = {
"query": "query GetAuthorById { getAuthorById(author_id: $author_id) { id slug userpic name lastSeen } }",
"operation": "GetAuthorById",
"variables": {"author_id": author_id}
}
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, data=gql)
if response.status_code != 200:
return None
r = response.json()
print(f"[services.core] got author: {r}")
author = r.get("data", {}).get("getAuthorbyId")
return author
except Exception:
return None
async def get_network(author_id:int, limit:int = 50, offset:int = 0) -> list:
gql = {
"query": "query LoadAuthors { authorFollowings(author_id: $author_id, limit: $limit, offset: $offset) { id slug userpic name } }",
"operation": "LoadAuthors",
"variables": {
"author_id": author_id,
"limit": limit,
"offset": offset
}
}
followings = []
followers = []
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, data=json.dumps(gql))
if response.status_code != 200:
return []
r = response.json()
followings = r.get("data", {}).get("authorFollowings", [])
more_amount = limit - len(followings)
if more_amount > 0:
followers = get_followers(author_id, more_amount)
except Exception as e:
print(e)
followings.extend(followers)
return followings
async def get_followers(author_id, amount):
gql = {
"query": "query LoadAuthors { authorFollowers(author_id: $author_id, limit: $limit) { id slug userpic name } }",
"operation": "LoadAuthors",
"variables": {
"author_id": author_id,
"limit": amount
}
}
followers = []
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, data=json.dumps(gql))
if response.status_code != 200:
return []
r = response.json()
followers = r.get("data", {}).get("authorFollowers", [])
except Exception as e:
followers = []
return followers