inbox/services/core.py

73 lines
2.2 KiB
Python
Raw Normal View History

2023-12-19 16:17:01 +00:00
from typing import List
2023-12-19 15:31:31 +00:00
import requests
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-12-19 16:16:42 +00:00
from datetime import datetime, timedelta
# Global variables to store cached authors data and last update time
cached_authors = None
last_update_time = None
update_interval = timedelta(minutes=2)
2023-10-04 20:42:39 +00:00
2023-12-19 16:16:42 +00:00
def _request_endpoint(query_name, body) -> dict:
2023-12-19 15:58:26 +00:00
print(f"[services.core] requesting {query_name}...")
response = requests.post(API_BASE, headers={"Content-Type": "application/json"}, json=body)
2023-12-19 15:31:31 +00:00
print(f"[services.core] {query_name} response: <{response.status_code}> {response.text[:65]}..")
2023-12-19 15:58:26 +00:00
2023-12-19 15:31:31 +00:00
if response.status_code == 200:
2023-12-19 15:58:26 +00:00
try:
r = response.json()
result = r.get("data", {}).get(query_name, {})
print(f"[services.core] entries amount in result: {len(result)} ")
return result
except ValueError as e:
print(f"[services.core] Error decoding JSON response: {e}")
2023-12-19 16:16:42 +00:00
return {}
2023-11-28 09:05:39 +00:00
2023-12-19 15:58:26 +00:00
def get_all_authors():
2023-12-19 16:16:42 +00:00
global cached_authors, last_update_time
# Check if cached data is available and not expired
if cached_authors is not None and (datetime.now() - last_update_time) < update_interval:
print("[services.core] Returning cached authors data")
return cached_authors
2023-12-19 15:58:26 +00:00
authors_by_user = {}
authors_by_id = {}
query_name = "get_authors_all"
2023-11-06 16:25:28 +00:00
2023-12-19 15:58:26 +00:00
gql = {
"query": "query { " + query_name + "{ id slug pic name user } }",
"variables": None,
}
2023-12-19 08:25:06 +00:00
2023-12-19 15:58:26 +00:00
# Make a request to load authors
authors = _request_endpoint(query_name, gql)
2023-11-22 12:09:24 +00:00
2023-12-19 15:58:26 +00:00
for a in list(authors):
authors_by_user[a["user"]] = a
authors_by_id[a["id"]] = a
2023-12-19 08:25:06 +00:00
2023-12-19 16:16:42 +00:00
# Cache the authors data and update the last update time
cached_authors = authors_by_user, authors_by_id
last_update_time = datetime.now()
2023-12-19 15:58:26 +00:00
return authors_by_user, authors_by_id
2023-10-04 20:42:39 +00:00
2023-10-11 19:12:55 +00:00
2023-12-19 15:31:31 +00:00
def get_my_followed() -> List[ChatMember]:
2023-11-28 08:33:50 +00:00
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-19 16:16:42 +00:00
return _request_endpoint(query_name, gql).get(
"authors", []
) # Ensure you're returning the correct part of the response