Merge branch 'master' into backend-dependency-update
This commit is contained in:
@@ -36,7 +36,7 @@ from classquiz.routers import (
|
||||
moderation,
|
||||
)
|
||||
from classquiz.socket_server import sio
|
||||
from classquiz.helpers import meilisearch_init, telemetry_ping
|
||||
from classquiz.helpers import meilisearch_init
|
||||
|
||||
settings = settings()
|
||||
if settings.sentry_dsn:
|
||||
@@ -63,7 +63,6 @@ async def startup() -> None:
|
||||
if not database_.is_connected:
|
||||
await database_.connect()
|
||||
await meilisearch_init()
|
||||
await telemetry_ping()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
|
||||
+14
-12
@@ -8,9 +8,8 @@ from functools import lru_cache
|
||||
from redis import asyncio as redis_lib
|
||||
import redis as redis_base_lib
|
||||
from pydantic import RedisDsn, PostgresDsn, BaseModel
|
||||
from pydantic_settings import BaseSettings
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
import meilisearch as MeiliSearch
|
||||
from typing import Optional
|
||||
from arq import create_pool
|
||||
from arq.connections import RedisSettings, ArqRedis
|
||||
|
||||
@@ -29,10 +28,13 @@ class Settings(BaseSettings):
|
||||
Settings class for the shop app.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env", extra="ignore", env_nested_delimiter="__", env_file_encoding="utf-8"
|
||||
)
|
||||
root_address: str = "http://127.0.0.1:8000"
|
||||
redis: RedisDsn = "redis://localhost:6379/0?decode_responses=True"
|
||||
skip_email_verification: bool = False
|
||||
db_url: str | PostgresDsn = "postgresql://postgres:mysecretpassword@localhost:5432/classquiz"
|
||||
db_url: PostgresDsn | str = "postgresql://postgres:mysecretpassword@localhost:5432/classquiz"
|
||||
hcaptcha_key: str | None = None
|
||||
recaptcha_key: str | None = None
|
||||
mail_address: str
|
||||
@@ -43,13 +45,13 @@ class Settings(BaseSettings):
|
||||
secret_key: str
|
||||
access_token_expire_minutes: int = 30
|
||||
cache_expiry: int = 86400
|
||||
sentry_dsn: str | None
|
||||
sentry_dsn: str | None = None
|
||||
meilisearch_url: str = "http://127.0.0.1:7700"
|
||||
meilisearch_index: str = "classquiz"
|
||||
google_client_id: Optional[str]
|
||||
google_client_secret: Optional[str]
|
||||
github_client_id: Optional[str]
|
||||
github_client_secret: Optional[str]
|
||||
google_client_id: str | None = None
|
||||
google_client_secret: str | None = None
|
||||
github_client_id: str | None = None
|
||||
github_client_secret: str | None = None
|
||||
custom_openid_provider: CustomOpenIDProvider | None = None
|
||||
telemetry_enabled: bool = True
|
||||
free_storage_limit: int = 1074000000
|
||||
@@ -58,14 +60,14 @@ class Settings(BaseSettings):
|
||||
registration_disabled: bool = False
|
||||
|
||||
# storage_backend
|
||||
storage_backend: str | None = "local"
|
||||
storage_backend: str # either "local" or "s3"
|
||||
|
||||
# if storage_backend == "local":
|
||||
storage_path: str | None
|
||||
storage_path: str | None = None
|
||||
|
||||
# if storage_backend == "s3":
|
||||
s3_access_key: str | None
|
||||
s3_secret_key: str | None
|
||||
s3_access_key: str | None = None
|
||||
s3_secret_key: str | None = None
|
||||
s3_bucket_name: str = "classquiz"
|
||||
s3_base_url: str | None
|
||||
|
||||
|
||||
@@ -139,6 +139,7 @@ class QuizQuestion(BaseModel):
|
||||
type: None | QuizQuestionType = QuizQuestionType.ABCD
|
||||
answers: list[ABCDQuizAnswer] | RangeQuizAnswer | list[TextQuizAnswer] | list[VotingQuizAnswer] | str
|
||||
image: str | None = None
|
||||
hide_results: bool | None = False
|
||||
|
||||
@field_validator("answers")
|
||||
def answers_not_none_if_abcd_type(cls, v, info: ValidationInfo):
|
||||
@@ -416,7 +417,7 @@ class PublicStorageItem(BaseModel):
|
||||
id: uuid.UUID
|
||||
uploaded_at: datetime
|
||||
mime_type: str
|
||||
hash: str | None
|
||||
hash: str | None = None
|
||||
size: int
|
||||
deleted_at: datetime | None = None
|
||||
alt_text: str | None = None
|
||||
|
||||
@@ -146,7 +146,7 @@ async def handle_import_from_excel(data: BinaryIO, user: User) -> Quiz:
|
||||
for a, answer in enumerate(answers):
|
||||
if answer is None:
|
||||
continue
|
||||
if len(answer) > 150:
|
||||
if len(str(answer)) > 150:
|
||||
raise HTTPException(status_code=400, detail=f"Answer {a + 1} in Question {i + 1} is longer than 150")
|
||||
if len(answers) < 2:
|
||||
raise HTTPException(status_code=400, detail=f"Less than 2 answers in Question {i + 1}")
|
||||
@@ -155,7 +155,7 @@ async def handle_import_from_excel(data: BinaryIO, user: User) -> Quiz:
|
||||
for a, answer in enumerate(answers):
|
||||
if answer is None:
|
||||
continue
|
||||
answers_list.append(ABCDQuizAnswer(answer=answer, right=str(a + 1) in correct_answers))
|
||||
answers_list.append(ABCDQuizAnswer(answer=str(answer), right=str(a + 1) in correct_answers))
|
||||
|
||||
existing_question: dict | None = None
|
||||
if existing_quiz is not None:
|
||||
|
||||
@@ -60,7 +60,7 @@ class _Card(BaseModel):
|
||||
cover: str | None = None
|
||||
coverMetadata: _CoverMetadata | dict[None, None] | None = None
|
||||
draftExists: bool
|
||||
inventoryItemIds: List[Any]
|
||||
inventoryItemIds: List[Any] = None
|
||||
number_of_questions: int
|
||||
creator: UUID
|
||||
creator_username: str
|
||||
|
||||
@@ -20,7 +20,7 @@ class _Response(BaseModel):
|
||||
|
||||
|
||||
async def search(
|
||||
query: str | None,
|
||||
query: str | None = None,
|
||||
limit: int | None = 9,
|
||||
cursor: int | None = 1,
|
||||
search_cluster: int | None = 1,
|
||||
|
||||
@@ -54,7 +54,7 @@ class PublicQuizResponseUser(BaseModel):
|
||||
id: uuid.UUID
|
||||
|
||||
|
||||
class PublicQuizResponse(Quiz.get_pydantic()):
|
||||
class PublicQuizResponse(Quiz.get_pydantic(exclude={"questions"})):
|
||||
user_id: PublicQuizResponseUser
|
||||
questions: list[QuizQuestion]
|
||||
likes: int
|
||||
|
||||
@@ -28,6 +28,7 @@ from pydantic import BaseModel, ValidationError, field_validator, ValidationInfo
|
||||
from datetime import datetime
|
||||
|
||||
from classquiz.socket_server.export_helpers import save_quiz_to_storage
|
||||
from classquiz.socket_server.session import get_session, save_session
|
||||
|
||||
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=[])
|
||||
settings = settings()
|
||||
@@ -117,7 +118,7 @@ async def rejoin_game(sid: str, data: dict):
|
||||
"sid_custom": sid,
|
||||
"admin": False,
|
||||
}
|
||||
await sio.save_session(sid, session)
|
||||
await save_session(sid, sio, session)
|
||||
await sio.enter_room(sid, data.game_pin)
|
||||
await sio.emit(
|
||||
"rejoined_game",
|
||||
@@ -153,7 +154,10 @@ async def join_game(sid: str, data: dict):
|
||||
try:
|
||||
async with session.post(
|
||||
"https://hcaptcha.com/siteverify",
|
||||
data={"response": data.captcha, "secret": settings.hcaptcha_key},
|
||||
data={
|
||||
"response": data.captcha,
|
||||
"secret": settings.hcaptcha_key,
|
||||
},
|
||||
) as resp:
|
||||
resp_data = await resp.model_dump_json()
|
||||
if not resp_data["success"]:
|
||||
@@ -165,7 +169,10 @@ async def join_game(sid: str, data: dict):
|
||||
elif settings.recaptcha_key is not None:
|
||||
async with session.post(
|
||||
"https://www.google.com/recaptcha/api/siteverify",
|
||||
data={"secret": settings.recaptcha_key, "response": data.captcha},
|
||||
data={
|
||||
"secret": settings.recaptcha_key,
|
||||
"response": data.captcha,
|
||||
},
|
||||
) as resp:
|
||||
try:
|
||||
resp_data = await resp.model_dump_json()
|
||||
@@ -188,7 +195,7 @@ async def join_game(sid: str, data: dict):
|
||||
"sid_custom": sid,
|
||||
"admin": False,
|
||||
}
|
||||
await sio.save_session(sid, session)
|
||||
await save_session(sid, sio, session)
|
||||
await sio.emit(
|
||||
"joined_game",
|
||||
{
|
||||
@@ -206,7 +213,11 @@ async def join_game(sid: str, data: dict):
|
||||
if data.custom_field == "":
|
||||
data.custom_field = None
|
||||
if data.custom_field is not None:
|
||||
await redis.hset(f"game:{data.game_pin}:players:custom_fields", data.username, data.custom_field)
|
||||
await redis.hset(
|
||||
f"game:{data.game_pin}:players:custom_fields",
|
||||
data.username,
|
||||
data.custom_field,
|
||||
)
|
||||
|
||||
await sio.emit(
|
||||
"player_joined",
|
||||
@@ -222,7 +233,7 @@ async def join_game(sid: str, data: dict):
|
||||
|
||||
@sio.event
|
||||
async def start_game(sid: str, _data: dict):
|
||||
session = await sio.get_session(sid)
|
||||
session = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
game_data = PlayGame.model_validate_json(await redis.get(f"game:{session['game_pin']}"))
|
||||
@@ -259,10 +270,11 @@ async def register_as_admin(sid: str, data: dict):
|
||||
{"game_id": game_id, "game": await redis.get(f"game:{game_pin}")},
|
||||
room=sid,
|
||||
)
|
||||
async with sio.session(sid) as session:
|
||||
session["game_pin"] = game_pin
|
||||
session["admin"] = True
|
||||
session["remote"] = False
|
||||
session = {}
|
||||
session["game_pin"] = game_pin
|
||||
session["admin"] = True
|
||||
session["remote"] = False
|
||||
await save_session(sid, sio, session)
|
||||
await sio.enter_room(sid, game_pin)
|
||||
await sio.enter_room(sid, f"admin:{data.game_pin}")
|
||||
else:
|
||||
@@ -271,7 +283,7 @@ async def register_as_admin(sid: str, data: dict):
|
||||
|
||||
@sio.event
|
||||
async def get_question_results(sid: str, data: dict):
|
||||
session = await sio.get_session(sid)
|
||||
session = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
|
||||
@@ -317,7 +329,7 @@ class ReturnQuestion(QuizQuestion):
|
||||
@sio.event
|
||||
async def set_question_number(sid, data: str):
|
||||
# data is just a number (as a str) of the question
|
||||
session = await sio.get_session(sid)
|
||||
session = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
game_pin = session["game_pin"]
|
||||
@@ -423,14 +435,15 @@ async def submit_answer(sid: str, data: dict):
|
||||
answer_right = bool(correct_string == data.answer)
|
||||
else:
|
||||
raise NotImplementedError
|
||||
latency = int(float((await sio.get_session(sid))["ping"]))
|
||||
latency = int(float((await get_session(sid, sio))["ping"]))
|
||||
time_q_started = datetime.fromisoformat(await redis.get(f"game:{session['game_pin']}:current_time"))
|
||||
|
||||
diff = (time_q_started - now).total_seconds() * 1000 # - timedelta(milliseconds=latency)
|
||||
score = 0
|
||||
if answer_right:
|
||||
score = calculate_score(
|
||||
abs(diff) - latency, int(float(game_data.questions[int(float(data.question_index))].time))
|
||||
abs(diff) - latency,
|
||||
int(float(game_data.questions[int(float(data.question_index))].time)),
|
||||
)
|
||||
if score > 1000:
|
||||
score = 1000
|
||||
@@ -444,7 +457,10 @@ async def submit_answer(sid: str, data: dict):
|
||||
)
|
||||
answers = await redis.get(f"game_session:{session['game_pin']}:{data.question_index}")
|
||||
answers = await set_answer(
|
||||
answers, game_pin=session["game_pin"], data=answer_data, q_index=int(float(data.question_index))
|
||||
answers,
|
||||
game_pin=session["game_pin"],
|
||||
data=answer_data,
|
||||
q_index=int(float(data.question_index)),
|
||||
)
|
||||
player_count = await redis.scard(f"game_session:{session['game_pin']}:players")
|
||||
await sio.emit("player_answer", {})
|
||||
@@ -465,7 +481,7 @@ async def submit_answer(sid: str, data: dict):
|
||||
|
||||
@sio.event
|
||||
async def get_final_results(sid: str, _data: dict):
|
||||
session: dict = await sio.get_session(sid)
|
||||
session: dict = await get_session(sid, sio)
|
||||
game_data = PlayGame(**json.loads(await redis.get(f"game:{session['game_pin']}")))
|
||||
if not session["admin"]:
|
||||
return
|
||||
@@ -475,7 +491,7 @@ async def get_final_results(sid: str, _data: dict):
|
||||
|
||||
@sio.event
|
||||
async def get_export_token(sid: str):
|
||||
session = await sio.get_session(sid)
|
||||
session = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
game_data = PlayGame(**json.loads(await redis.get(f"game:{session['game_pin']}")))
|
||||
@@ -487,7 +503,7 @@ async def get_export_token(sid: str):
|
||||
|
||||
@sio.event
|
||||
async def show_solutions(sid: str, _data: dict):
|
||||
session: dict = await sio.get_session(sid)
|
||||
session: dict = await get_session(sid, sio)
|
||||
game_data = PlayGame(**json.loads(await redis.get(f"game:{session['game_pin']}")))
|
||||
if not session["admin"]:
|
||||
return
|
||||
@@ -500,8 +516,9 @@ async def echo_time_sync(sid: str, data: str):
|
||||
then = datetime.fromisoformat(then_dec)
|
||||
now = datetime.now()
|
||||
delta = now - then
|
||||
async with sio.session(sid) as session:
|
||||
session["ping"] = delta.microseconds / 1000
|
||||
session = await get_session(sid, sio)
|
||||
session["ping"] = delta.microseconds / 1000
|
||||
await save_session(sid, sio, session)
|
||||
|
||||
|
||||
class _KickPlayerInput(BaseModel):
|
||||
@@ -517,7 +534,7 @@ async def kick_player(sid: str, data: dict):
|
||||
print(e)
|
||||
return
|
||||
|
||||
session: dict = await sio.get_session(sid)
|
||||
session: dict = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
|
||||
@@ -549,10 +566,11 @@ async def register_as_remote(sid: str, data: dict):
|
||||
room=sid,
|
||||
)
|
||||
await sio.emit("control_visibility", {"visible": False}, room=f"admin:{data.game_pin}")
|
||||
async with sio.session(sid) as session:
|
||||
session["game_pin"] = data.game_pin
|
||||
session["admin"] = True
|
||||
session["remote"] = True
|
||||
session = await get_session(sid, sio)
|
||||
session["game_pin"] = data.game_pin
|
||||
session["admin"] = True
|
||||
session["remote"] = True
|
||||
await save_session(sid, sio, session)
|
||||
await sio.enter_room(sid, data.game_pin)
|
||||
await sio.enter_room(sid, f"admin:{data.game_pin}")
|
||||
|
||||
@@ -569,14 +587,31 @@ async def set_control_visibility(sid: str, data: dict):
|
||||
await sio.emit("error", room=sid)
|
||||
print(e)
|
||||
return
|
||||
session: dict = await sio.get_session(sid)
|
||||
await sio.emit("control_visibility", {"visible": data.visible}, room=f"admin:{session['game_pin']}")
|
||||
session: dict = await get_session(sid, sio)
|
||||
await sio.emit(
|
||||
"control_visibility",
|
||||
{"visible": data.visible},
|
||||
room=f"admin:{session['game_pin']}",
|
||||
)
|
||||
|
||||
|
||||
@sio.event
|
||||
async def save_quiz(sid: str):
|
||||
session: dict = await sio.get_session(sid)
|
||||
session: dict = await get_session(sid, sio)
|
||||
if not session["admin"]:
|
||||
return
|
||||
await save_quiz_to_storage(session["game_pin"])
|
||||
await sio.emit("results_saved_successfully")
|
||||
|
||||
|
||||
class ConnectSessionIdEvent(BaseModel):
|
||||
session_id: str
|
||||
|
||||
|
||||
@sio.event
|
||||
async def connect(sid: str, _environ, _auth):
|
||||
session_id = os.urandom(16).hex()
|
||||
print("Connection opened with handler")
|
||||
sio_session = {"session_id": session_id}
|
||||
await sio.save_session(sid, sio_session)
|
||||
await sio.emit("session_id", ConnectSessionIdEvent(session_id=session_id).dict())
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# SPDX-FileCopyrightText: 2023 Marlon W (Mawoka)
|
||||
#
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
from classquiz.config import redis
|
||||
import json
|
||||
from typing import Any
|
||||
from socketio import AsyncServer
|
||||
from socketio.exceptions import ConnectionRefusedError
|
||||
|
||||
|
||||
async def get_session(sid: str, sio: AsyncServer, disconnect_on_error: bool = True) -> dict:
|
||||
session_id = (await sio.get_session(sid)).get("session_id")
|
||||
if session_id is None:
|
||||
raise ConnectionRefusedError("Session not configured")
|
||||
val = await redis.get(f"socket_io_session:{session_id}")
|
||||
if disconnect_on_error and val is None:
|
||||
raise ConnectionRefusedError("session not available")
|
||||
return json.loads(val)
|
||||
|
||||
|
||||
async def save_session(sid: str, sio: AsyncServer, data: Any, disconnect_on_error: bool = True) -> None:
|
||||
session_id = (await sio.get_session(sid)).get("session_id")
|
||||
if session_id is None:
|
||||
raise ConnectionRefusedError("Session not configured")
|
||||
await redis.set(f"socket_io_session:{session_id}", json.dumps(data), ex=3600)
|
||||
@@ -27,4 +27,4 @@ class WorkerSettings:
|
||||
cron_jobs = [cron(clean_editor_images_up, hour={0, 6, 12, 18}, minute=0)]
|
||||
on_startup = startup
|
||||
on_shutdown = shutdown
|
||||
redis_settings = RedisSettings.from_dsn(settings.redis)
|
||||
redis_settings = RedisSettings.from_dsn(str(settings.redis))
|
||||
|
||||
Reference in New Issue
Block a user