This commit is contained in:
parent
15139249f1
commit
c53b7a4c6c
|
@ -1,3 +1,7 @@
|
||||||
|
[0.2.16]
|
||||||
|
- resolvers: snake case queries and mutations
|
||||||
|
- resolvers: fix auth context usage with string user_id
|
||||||
|
|
||||||
[0.2.15]
|
[0.2.15]
|
||||||
- chore: schema service removed
|
- chore: schema service removed
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone
|
import time
|
||||||
|
|
||||||
from services.auth import login_required
|
from services.auth import login_required
|
||||||
from services.rediscache import redis
|
from services.rediscache import redis
|
||||||
|
@ -32,7 +32,7 @@ async def update_chat(_, info, chat_new: ChatUpdate):
|
||||||
{
|
{
|
||||||
"title": chat_new.get("title", chat["title"]),
|
"title": chat_new.get("title", chat["title"]),
|
||||||
"description": chat_new.get("description", chat["description"]),
|
"description": chat_new.get("description", chat["description"]),
|
||||||
"updated_at": int(datetime.now(tz=timezone.utc).timestamp()),
|
"updated_at": int(time.time()),
|
||||||
"admins": chat_new.get("admins", chat.get("admins") or []),
|
"admins": chat_new.get("admins", chat.get("admins") or []),
|
||||||
"members": chat_new.get("members", chat["members"]),
|
"members": chat_new.get("members", chat["members"]),
|
||||||
}
|
}
|
||||||
|
@ -75,8 +75,8 @@ async def create_chat(_, info, title="", members=None):
|
||||||
"title": title,
|
"title": title,
|
||||||
"description": "",
|
"description": "",
|
||||||
"created_by": author_id,
|
"created_by": author_id,
|
||||||
"created_at": int(datetime.now(tz=timezone.utc).timestamp()),
|
"created_at": int(time.time()),
|
||||||
"updated_at": int(datetime.now(tz=timezone.utc).timestamp()),
|
"updated_at": int(time.time()),
|
||||||
"admins": members if (len(members) == 2 and title == "") else [],
|
"admins": members if (len(members) == 2 and title == "") else [],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,8 +11,8 @@ from models.member import ChatMember
|
||||||
from resolvers.chats import create_chat
|
from resolvers.chats import create_chat
|
||||||
|
|
||||||
|
|
||||||
async def get_unread_counter(chat_id: str, author_id: int) -> int:
|
async def get_unread_counter(chat_id: str, member_id: int) -> int:
|
||||||
unread = await redis.execute("LLEN", f"chats/{chat_id}/unread/{author_id}")
|
unread = await redis.execute("LLEN", f"chats/{chat_id}/unread/{member_id}")
|
||||||
return unread or 0
|
return unread or 0
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -101,7 +101,7 @@ async def update_message(_, info, message):
|
||||||
|
|
||||||
if body:
|
if body:
|
||||||
message["body"] = body
|
message["body"] = body
|
||||||
message["updated_at"] = int(datetime.now(tz=timezone.utc).timestamp())
|
message["updated_at"] = int(time.time())
|
||||||
|
|
||||||
await redis.execute("SET", f"chats/{chat_id}/messages/{message_id}", json.dumps(message))
|
await redis.execute("SET", f"chats/{chat_id}/messages/{message_id}", json.dumps(message))
|
||||||
|
|
||||||
|
@ -114,7 +114,7 @@ async def update_message(_, info, message):
|
||||||
return {"message": message, "error": "cannot update, no message_id"}
|
return {"message": message, "error": "cannot update, no message_id"}
|
||||||
|
|
||||||
|
|
||||||
@mutation.field("deleteMessage")
|
@mutation.field("delete_message")
|
||||||
@login_required
|
@login_required
|
||||||
async def delete_message(_, info, chat_id: str, message_id: int):
|
async def delete_message(_, info, chat_id: str, message_id: int):
|
||||||
author_id = info.context["author_id"]
|
author_id = info.context["author_id"]
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from httpx import AsyncClient, HTTPError
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from services.core import get_author
|
||||||
from settings import AUTH_URL
|
from settings import AUTH_URL
|
||||||
|
|
||||||
|
|
||||||
|
@ -42,23 +44,13 @@ def login_required(f):
|
||||||
raise Exception("You are not logged in")
|
raise Exception("You are not logged in")
|
||||||
else:
|
else:
|
||||||
# Добавляем author_id в контекст
|
# Добавляем author_id в контекст
|
||||||
context["author_id"] = user_id
|
author = await get_author(user_id)
|
||||||
|
if author:
|
||||||
|
context["author_id"] = author.id
|
||||||
|
elif user_id:
|
||||||
|
context["user_id"] = user_id
|
||||||
|
|
||||||
# Если пользователь аутентифицирован, выполняем резолвер
|
# Если пользователь аутентифицирован, выполняем резолвер
|
||||||
return await f(*args, **kwargs)
|
return await f(*args, **kwargs)
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
def auth_request(f):
|
|
||||||
@wraps(f)
|
|
||||||
async def decorated_function(*args, **kwargs):
|
|
||||||
req = args[0]
|
|
||||||
is_authenticated, user_id = await check_auth(req)
|
|
||||||
if not is_authenticated:
|
|
||||||
raise HTTPError("please, login first")
|
|
||||||
else:
|
|
||||||
req["author_id"] = user_id
|
|
||||||
return await f(*args, **kwargs)
|
|
||||||
|
|
||||||
return decorated_function
|
|
||||||
|
|
|
@ -1,11 +1,30 @@
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
from settings import API_BASE
|
from settings import API_BASE
|
||||||
from typing import List
|
from typing import List, Any
|
||||||
from models.member import ChatMember
|
from models.member import ChatMember
|
||||||
|
|
||||||
|
|
||||||
headers = {"Content-Type": "application/json"}
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
async def _request_endpoint(query_name, body) -> Any:
|
||||||
|
async with AsyncClient() as client:
|
||||||
|
try:
|
||||||
|
response = await client.post(API_BASE, headers=headers, json=body)
|
||||||
|
print(f"[services.core] {query_name}: [{response.status_code}] {len(response.text)} bytes")
|
||||||
|
if response.status_code != 200:
|
||||||
|
return []
|
||||||
|
r = response.json()
|
||||||
|
if r:
|
||||||
|
return r.get("data", {}).get(query_name, {})
|
||||||
|
else:
|
||||||
|
raise Exception("json response error")
|
||||||
|
except Exception:
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
|
||||||
async def get_all_authors() -> List[ChatMember]:
|
async def get_all_authors() -> List[ChatMember]:
|
||||||
query_name = "authorsAll"
|
query_name = "authorsAll"
|
||||||
query_type = "query"
|
query_type = "query"
|
||||||
|
@ -18,20 +37,7 @@ async def get_all_authors() -> List[ChatMember]:
|
||||||
"variables": None,
|
"variables": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
async with AsyncClient() as client:
|
return _request_endpoint(query_name, gql)
|
||||||
try:
|
|
||||||
response = await client.post(API_BASE, headers=headers, json=gql)
|
|
||||||
print(f"[services.core] {query_name}: [{response.status_code}] {len(response.text)} bytes")
|
|
||||||
if response.status_code != 200:
|
|
||||||
return []
|
|
||||||
r = response.json()
|
|
||||||
if r:
|
|
||||||
return r.get("data", {}).get(query_name, [])
|
|
||||||
except Exception:
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
traceback.print_exc()
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def get_my_followed() -> List[ChatMember]:
|
async def get_my_followed() -> List[ChatMember]:
|
||||||
|
@ -60,3 +66,25 @@ async def get_my_followed() -> List[ChatMember]:
|
||||||
|
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def get_author(author_id: int = None, slug: str = "", user: str = ""):
|
||||||
|
query_name = "get_author(author_id: $author_id, slug: $slug, user: $user)"
|
||||||
|
query_type = "query"
|
||||||
|
operation = "GetAuthor($author_id: Int, $slug: String, $user: String)"
|
||||||
|
query_fields = "id slug pic name"
|
||||||
|
vars = {}
|
||||||
|
if author_id:
|
||||||
|
vars["author_id"] = author_id
|
||||||
|
elif slug:
|
||||||
|
vars["slug"] = slug
|
||||||
|
elif user:
|
||||||
|
vars["user"] = user
|
||||||
|
|
||||||
|
gql = {
|
||||||
|
"query": query_type + " " + operation + " { " + query_name + " { " + query_fields + "} " + " }",
|
||||||
|
"operationName": operation,
|
||||||
|
"variables": None if vars == {} else vars,
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _request_endpoint(query_name, gql)
|
||||||
|
|
|
@ -14,7 +14,7 @@ async def notify_message(message: Message, action="create"):
|
||||||
print(f"Failed to publish to channel {channel_name}: {e}")
|
print(f"Failed to publish to channel {channel_name}: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def notify_chat(chat: ChatUpdate, member_id, action="create"):
|
async def notify_chat(chat: ChatUpdate, member_id: int, action="create"):
|
||||||
channel_name = f"chat:{member_id}"
|
channel_name = f"chat:{member_id}"
|
||||||
data = {"payload": chat, "action": action}
|
data = {"payload": chat, "action": action}
|
||||||
try:
|
try:
|
||||||
|
|
Loading…
Reference in New Issue
Block a user