Merge pull request #254 from mawoka-myblock/classquizcontroller

🙈
This commit is contained in:
Marlon
2023-06-30 01:41:23 +02:00
committed by GitHub
23 changed files with 841 additions and 121 deletions
+2
View File
@@ -1,4 +1,6 @@
#* {
:8080 {
# tls /home/mawoka/certs/cert.pem /home/mawoka/certs/key.pem
reverse_proxy /* localhost:3000
reverse_proxy /api* localhost:8000
reverse_proxy /rapidoc* localhost:8000
+17
View File
@@ -453,3 +453,20 @@ class PrivateStorageItem(PublicStorageItem):
class UpdateStorageItem(BaseModel):
filename: str | None
alt_text: str | None
class Controller(ormar.Model):
id: uuid.UUID = ormar.UUID(primary_key=True)
user: uuid.UUID | User = ormar.ForeignKey(User)
secret_key: str = ormar.String(nullable=False, max_length=24, min_length=24)
player_name: str = ormar.Text(nullable=False)
last_seen: datetime | None = ormar.DateTime(nullable=True)
first_seen: datetime | None = ormar.DateTime(nullable=True)
name: str = ormar.Text(nullable=False)
os_version: str | None = ormar.Text(nullable=True)
wanted_os_version: str = ormar.Text(nullable=True, default=None)
class Meta:
tablename = "controller"
metadata = metadata
database = database
+21
View File
@@ -0,0 +1,21 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import random
def generate_code(specified_length: int) -> str:
buttons = [
"B",
"b",
"G",
"g",
"Y",
"y",
"R",
"r",
] # Capital stands for long press, lowercase letter for short press
resulting_code = ""
for _ in range(specified_length):
resulting_code += random.choice(buttons)
return resulting_code
@@ -0,0 +1,93 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import os
import uuid
from datetime import datetime
from fastapi import APIRouter, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
from classquiz.config import redis
from classquiz.db.models import PlayGame, Controller
from classquiz.routers.box_controller.embedded.socket import router as socket_router
router = APIRouter()
router.include_router(socket_router, prefix="/socket")
class JoinGameInput(BaseModel):
id: uuid.UUID
secret_key: str
code: str
class JoinGameResponse(BaseModel):
id: str
@router.post("/join")
async def join_game(data: JoinGameInput) -> JoinGameResponse:
controller = await Controller.objects.get_or_none(id=data.id, secret_key=data.secret_key)
game_pin = await redis.get(f"game:cqc:code:{data.code}")
if game_pin is None:
raise HTTPException(status_code=404, detail="Game not found")
game = await redis.get(f"game:{game_pin}")
game = PlayGame.parse_raw(game)
# Check if game is already running
if game.started:
raise HTTPException(status_code=400, detail="Game started already")
# check if username already exists
if await redis.get(f"game_session:{game_pin}:players:{controller.player_name}") is not None:
raise HTTPException(status_code=409, detail="Username already exists")
player_id = os.urandom(5).hex()
await redis.set(f"game:cqc:player:{player_id}", controller.player_name)
return JoinGameResponse(id=f"{player_id}:{game_pin}")
class RegisterWithCodeInput(BaseModel):
code: str
class RegisterWithCodeResponse(BaseModel):
id: uuid.UUID
secret_key: str
@router.post("/register")
async def register_with_code(data: RegisterWithCodeInput) -> RegisterWithCodeResponse:
c_id = await redis.get(f"controller_setup:{data.code}")
if c_id is None:
raise HTTPException(status_code=404, detail="Code not found")
await redis.delete(f"controller_setup:{data.code}")
c_id = uuid.UUID(c_id)
controller = await Controller.objects.get(id=c_id)
controller.first_seen = datetime.now()
controller.last_seen = datetime.now()
await controller.update()
return RegisterWithCodeResponse(id=controller.id, secret_key=controller.secret_key)
@router.get("/ping")
async def ping_server(id: uuid.UUID, secret_key: str, version: str):
controller = await Controller.objects.get_or_none(id=id, secret_key=secret_key)
if controller is None:
raise HTTPException(status_code=404, detail="Key and/or id invalid")
controller.last_seen = datetime.now()
controller.os_version = version
await controller.update()
@router.get("/update")
async def get_firmware_version(id: uuid.UUID, secret_key: str) -> PlainTextResponse:
controller = await Controller.objects.get_or_none(id=id, secret_key=secret_key)
if controller is None:
return PlainTextResponse(status_code=404, content="Key and/or id invalid")
if controller.wanted_os_version is None:
return PlainTextResponse(status_code=400, content="No update needed")
return PlainTextResponse(status_code=200, content=controller.wanted_os_version)
@@ -2,7 +2,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import enum
import os
import typing
from datetime import datetime
@@ -15,34 +14,6 @@ from classquiz.socket_server import sio, calculate_score, set_answer
router = APIRouter()
class JoinGameInput(BaseModel):
code: str
name: str
class JoinGameResponse(BaseModel):
id: str
@router.post("/join")
async def join_game(data: JoinGameInput):
game_pin = await redis.get(f"game:cqc:code:{data.code}")
if game_pin is None:
raise HTTPException(status_code=404, detail="Game not found")
game = await redis.get(f"game:{game_pin}")
game = PlayGame.parse_raw(game)
# Check if game is already running
if game.started:
raise HTTPException(status_code=400, detail="Game started already")
# check if username already exists
if await redis.get(f"game_session:{game_pin}:players:{data.name}") is not None:
raise HTTPException(status_code=409, detail="Username already exists")
player_id = os.urandom(5).hex()
await redis.set(f"game:cqc:player:{player_id}", data.name)
return JoinGameResponse(id=f"{player_id}:{game_pin}")
class SubmitAnswerInput(BaseModel):
answer: int
@@ -86,11 +57,14 @@ async def submit_answer_fn(data_answer: int, game_pin: str, player_id: str, now:
answers = await redis.get(f"game_session:{game_pin}:{game.current_question}")
answers = await set_answer(answers, game_pin=game_pin, data=answer_data, q_index=game.current_question)
player_count = await redis.scard(f"game_session:{game_pin}:players")
print(player_count, answers)
await sio.emit("player_answer", {})
if answers is not None and len(answers.__root__) == player_count:
await sio.emit("everyone_answered", {})
button_to_index_map = {"y": 0, "r": 3, "g": 1, "b": 2}
class WebSocketTypes(enum.Enum):
ButtonPress = "bp"
Error = "e"
@@ -103,19 +77,16 @@ class WebSocketRequest(BaseModel):
wss_clients = {}
button_to_index_map = {"b": 0, "g": 1, "y": 2, "r": 3}
@router.websocket("/socket/{id}")
async def websocket_endpoint(ws: WebSocket, game_id: str, id: str):
@router.websocket("/{game_id}")
async def websocket_endpoint(ws: WebSocket, game_id: str):
try:
if id in wss_clients:
if game_id in wss_clients:
await ws.close(code=status.WS_1001_GOING_AWAY)
print(f"Client {id} already exists.")
print(f"Client {game_id} already exists.")
return
await ws.accept()
wss_clients[id] = ws
wss_clients[game_id] = ws
player_id, game_pin = game_id.split(":")
if player_id is None or game_pin is None:
@@ -133,7 +104,10 @@ async def websocket_endpoint(ws: WebSocket, game_id: str, id: str):
raw_data = await ws.receive_text()
try:
data = WebSocketRequest.parse_raw(raw_data)
except ValidationError:
except ValidationError as e:
print("ValError")
print(e)
print(raw_data)
await ws.send_text(WebSocketRequest(type=WebSocketTypes.Error, data="ValidationError").json())
continue
@@ -144,10 +118,9 @@ async def websocket_endpoint(ws: WebSocket, game_id: str, id: str):
except (KeyError, AttributeError):
await ws.send_text(WebSocketRequest(type=WebSocketTypes.Error, data="InvalidButton").json())
continue
await submit_answer_fn(answer_index, game_pin, player_id, now)
print(f"Data from client {id}: {data}")
print(f"Data from client {game_id}: {data}")
except WebSocketDisconnect as ex:
print(f"Client {id} is disconnected: {ex}")
wss_clients.pop(id, None)
print(f"Client {game_id} is disconnected: {ex}")
wss_clients.pop(game_id, None)
+84 -34
View File
@@ -1,52 +1,102 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import random
import os
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from classquiz.auth import get_current_user
from classquiz.db.models import User, PlayGame
from classquiz.db.models import User, Controller
from classquiz.config import redis
from classquiz.helpers.box_controller import generate_code
router = APIRouter()
def generate_code() -> str:
specified_length = 6
buttons = [
"B",
"b",
"G",
"g",
"Y",
"y",
"R",
"r",
] # Capital stands for long press, lowercase letter for short press
resulting_code = ""
for _ in range(specified_length):
resulting_code += random.choice(buttons)
return resulting_code
class SetControllerUpInput(BaseModel):
player_name: str | None
name: str
class ActivateCqbForCurrentQuizInput(BaseModel):
game_pin: int
class ActivateCqbForCurrentQuizResponse(BaseModel):
class SetControllerUpResponse(BaseModel):
code: str
id: uuid.UUID
@router.post("/activate-for-quiz", response_model=ActivateCqbForCurrentQuizResponse)
async def activate_cqc_for_current_quiz(data: ActivateCqbForCurrentQuizInput, user: User = Depends(get_current_user)):
redis_res = await redis.get(f"game:{data.game_pin}")
if redis_res is None:
raise HTTPException(status_code=404, detail="Game not found")
game_data = PlayGame.parse_raw(redis_res)
if game_data.user_id != user.id:
raise HTTPException(status_code=401, detail="The quiz wasn't started by you")
code = generate_code()
await redis.set(f"game:cqc:code:{code}", game_data.game_pin, ex=3600)
return ActivateCqbForCurrentQuizResponse(code=code)
@router.post("/setup")
async def set_controller_up(
input_data: SetControllerUpInput, user: User = Depends(get_current_user)
) -> SetControllerUpResponse:
code = generate_code(10)
if input_data.player_name is None:
input_data.player_name = user.username
data = Controller(
id=uuid.uuid4(),
user=user,
secret_key=os.urandom(12).hex(),
player_name=input_data.player_name,
last_seen=None,
first_seen=None,
name=input_data.name,
os_version=None,
)
await data.save()
await redis.set(f"controller_setup:{code}", data.id.hex, ex=900)
return SetControllerUpResponse(code=code, id=data.id)
GetControllerResponse = Controller.get_pydantic(exclude={"secret_key", "user"})
@router.get("/controller")
async def get_controller(id: uuid.UUID, user: User = Depends(get_current_user)) -> GetControllerResponse:
controller = await Controller.objects.get_or_none(id=id, user=user.id)
if controller is None:
raise HTTPException(status_code=404, detail="Controller not found")
return GetControllerResponse(**controller.dict())
class ModifyControllerInput(BaseModel):
id: uuid.UUID
player_name: str
name: str
@router.post("/modify")
async def modify_controller(
data: ModifyControllerInput, user: User = Depends(get_current_user)
) -> GetControllerResponse:
controller = await Controller.objects.get_or_none(id=data.id, user=user.id)
if controller is None:
raise HTTPException(status_code=404, detail="Controller not found")
controller.player_name = data.player_name
controller.name = data.name
await controller.update()
return GetControllerResponse(**controller.dict())
@router.get("/list")
async def get_all_controllers(user: User = Depends(get_current_user)) -> list[GetControllerResponse]:
controllers = await Controller.objects.all(user=user.id)
if len(controllers) == 0:
return []
return_list = []
for controller in controllers:
return_list.append(GetControllerResponse(**controller.dict()))
return return_list
class SetVersionToBeFlashedInput(BaseModel):
id: uuid.UUID
version: str
@router.post("/set_update")
async def set_version_to_be_flashed(data: SetVersionToBeFlashedInput, user: User = Depends(get_current_user)):
controller = await Controller.objects.get_or_none(id=data.id, user=user.id)
if controller is None:
raise HTTPException(status_code=404, detail="Controller not found")
controller.wanted_os_version = data.version
await controller.update()
+2 -20
View File
@@ -3,7 +3,6 @@
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import json
import random
import re
import uuid
from datetime import datetime
@@ -19,6 +18,7 @@ from pydantic import ValidationError, BaseModel
from classquiz.auth import get_current_user
from classquiz.config import redis, settings, storage, meilisearch
from classquiz.db.models import Quiz, User, PlayGame, GameInLobby, QuizQuestion
from classquiz.helpers.box_controller import generate_code
from classquiz.kahoot_importer.import_quiz import import_quiz
import urllib.parse
@@ -70,24 +70,6 @@ async def get_public_quiz(quiz_id: str):
return PublicQuizResponse(**quiz.dict())
def generate_code() -> str:
specified_length = 6
buttons = [
"B",
"b",
"G",
"g",
"Y",
"y",
"R",
"r",
] # Capital stands for long press, lowercase letter for short press
resulting_code = ""
for _ in range(specified_length):
resulting_code += random.choice(buttons)
return resulting_code
@router.post("/start/{quiz_id}")
async def start_quiz(
quiz_id: str,
@@ -131,7 +113,7 @@ async def start_quiz(
)
code = None
if cqcs_enabled:
code = generate_code()
code = generate_code(6)
await redis.set(f"game:cqc:code:{code}", game_pin, ex=3600)
await redis.set(f"game:{str(game.game_pin)}", game.json(), ex=18000)
await redis.set(f"game_pin:{user.id}:{quiz_id}", game_pin, ex=18000)
@@ -0,0 +1,22 @@
<script lang="ts">
let color_map = {
r: 'red',
g: 'green',
y: 'yellow',
b: 'blue'
};
export let code: string;
</script>
<div class="flex flex-row gap-2 mx-auto">
{#each code as c}
<div class="flex flex-col">
<p class="text-center">{c}</p>
<span
style="background-color: {color_map[
c.toLowerCase()
]}; width: 2rem; height: {c.toLowerCase() == c ? '2' : '4'}rem"
/>
</div>
{/each}
</div>
+1 -6
View File
@@ -148,12 +148,7 @@
/>
</div>
<div class="flex justify-center w-full my-auto">
<label
for="cqc-toggle"
class="inline-flex relative items-center cursor-pointer"
class:pointer-events-none={!captcha_enabled}
class:opacity-50={!captcha_enabled}
>
<label for="cqc-toggle" class="inline-flex relative items-center cursor-pointer">
<input
type="checkbox"
bind:checked={cqcs_enabled}
+15
View File
@@ -156,6 +156,10 @@
"results": "Results",
"note": "Note",
"player_plural": "Players",
"version": "Version",
"never": "Never",
"unknown": "Unknown",
"update": "Update",
"score": "Score",
"slide": "Slide",
"name": "Name",
@@ -333,6 +337,17 @@
"time_taken": "Time taken",
"player_score": "Player Score"
},
"controllers": {
"add_new_controller": "Add new controller",
"player_name": "Player name",
"first_seen": "First seen",
"last_seen": "Last seen",
"controller_name": "Controller Name",
"version_overview": "The newest version available is {{newest_version}} and version {{current_version}} is installed.",
"already_latest_version": "You're already on the latest version",
"cancel_update": "Cancel Update!",
"update_from_to": "Update from {{current_version}} to {{newest_version}}"
},
"navbar": {
"donate": "Donate"
},
@@ -5,6 +5,7 @@
-->
<script lang="ts">
import AudioPlayer from '$lib/play/audio_player.svelte';
import ControllerCodeDisplay from '$lib/components/controller/code.svelte';
import { getLocalization } from '$lib/i18n';
export let game_pin: string;
@@ -30,12 +31,6 @@
}
players = players;
};
const color_map = {
r: 'red',
g: 'green',
y: 'yellow',
b: 'blue'
};
</script>
<div class="w-full h-full">
@@ -61,18 +56,7 @@
<div class="m-auto">
<div class="flex-col flex justify-center">
<p class="mx-auto">{$t('play_page.join_by_entering_code')}</p>
<div class="flex flex-row gap-2 mx-auto">
{#each cqc_code as c}
<div class="flex flex-col">
<p class="text-center">{c}</p>
<span
style="background-color: {color_map[
c.toLowerCase()
]}; width: 2rem; height: {c.toLowerCase() == c ? '2' : '4'}rem"
/>
</div>
{/each}
</div>
<ControllerCodeDisplay code={cqc_code} />
</div>
</div>
{/if}
@@ -0,0 +1,78 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { PageData } from './$types';
import BrownButton from '$lib/components/buttons/brown.svelte';
import { getLocalization } from '$lib/i18n';
const { t } = getLocalization();
export let data: PageData;
console.log(data.controllers);
const controllers: [] = data.controllers;
</script>
<div class="w-full h-full">
{#if controllers.length === 0}
<div class="w-full h-full flex">
<div class="m-auto">
<BrownButton href="/account/controllers/add"
>{$t('controllers.add_new_controller')}</BrownButton
>
</div>
</div>
{:else}
<div class="p-2">
<div class="flex">
<div class="mx-auto">
<BrownButton href="/account/controllers/add"
>{$t('controllers.add_new_controller')}</BrownButton
>
</div>
</div>
<table class="w-full">
<tr class="border-b-2 dark:border-gray-500 text-left border-gray-300">
<th class="border-r dark:border-gray-500 p-1 mx-auto border-gray-300"
>{$t('words.name')}</th
>
<th class="border-r dark:border-gray-500 p-1 mx-auto border-gray-300"
>{$t('controllers.player_name')}
</th>
<th class="border-r dark:border-gray-500 p-1 mx-auto border-gray-300"
>{$t('controllers.first_seen')}
</th>
<th class="border-r dark:border-gray-500 p-1 mx-auto border-gray-300"
>{$t('controllers.last_seen')}
</th>
<th class="mx-auto p-1">{$t('words.version')}</th>
</tr>
{#each data.controllers as controller}
<tr class="text-left">
<td class="border-r dark:border-gray-500 p-1 border-gray-300"
><a
href="/account/controllers/{controller.id}"
class="underline text-lg">{controller.name}</a
></td
>
<td class="border-r dark:border-gray-500 p-1 border-gray-300"
>{controller.player_name}</td
>
<td class="border-r dark:border-gray-500 p-1 border-gray-300"
>{controller.first_seen
? new Date(controller.first_seen).toLocaleString()
: $t('words.never')}</td
>
<td class="border-r dark:border-gray-500 p-1 border-gray-300"
>{controller.last_seen
? new Date(controller.last_seen).toLocaleString()
: $t('words.never')}</td
>
<td class="mx-auto p-1">{controller.os_version ?? $t('words.unknown')}</td>
</tr>
{/each}
</table>
</div>
{/if}
</div>
@@ -0,0 +1,16 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import type { PageLoad } from './$types';
export const load = (async ({ fetch }) => {
const resp = await fetch('/api/v1/box-controller/web/list');
// const resp = await fetch("https://localhost/api/v1/box-controller/web/list")
const controllers = await resp.json();
return {
controllers
};
}) satisfies PageLoad;
@@ -0,0 +1,145 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { PageData } from './$types';
import { SaveStatus } from './commons';
import SaveIndicator from './SaveIndicator.svelte';
import Spinner from '$lib/Spinner.svelte';
import Cookies from 'js-cookie';
import { browser } from '$app/environment';
import BrownButton from '$lib/components/buttons/brown.svelte';
import { getLocalization } from '$lib/i18n';
const { t } = getLocalization();
export let data: PageData;
const controller = data.controller;
let newest_version: string | undefined = undefined;
let saved_status = SaveStatus.Unchanged;
let save_player_timer;
const save_player_name_debounce = () => {
clearTimeout(save_player_timer);
save_player_timer = setTimeout(save_names, 750);
};
const save_names = async () => {
if (!browser) {
return;
}
saved_status = SaveStatus.Saving;
const res = await fetch(`/api/v1/box-controller/web/modify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: controller.id,
player_name: controller.player_name,
name: controller.name
})
});
if (res.ok) {
saved_status = SaveStatus.Saved;
} else {
saved_status = SaveStatus.Error;
}
};
const get_latest_version = async () => {
if (!browser) {
return;
}
const cookie_data = Cookies.get('latest_cqc_version');
if (cookie_data) {
newest_version = cookie_data;
return;
}
const res = await fetch(
'https://api.github.com/repos/mawoka-myblock/ClassQuizController/releases'
);
const json = await res.json();
newest_version = json[0].tag_name.replace('v', '');
Cookies.set('latest_cqc_version', newest_version, { path: '', expires: 3600 });
};
const allow_update_to_version = async () => {
if (newest_version === controller.os_version) {
return;
}
let wanted_version;
if (newest_version === controller.wanted_os_version) {
wanted_version = controller.os_version;
} else {
wanted_version = newest_version;
}
await fetch('/api/v1/box-controller/web/set_update', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: controller.id, version: wanted_version })
});
window.location.reload();
};
</script>
<div>
<div class="w-full flex flex-col">
<h2 class="text-2xl mx-auto">{$t('controllers.controller_name')}</h2>
<div class="mx-auto flex">
<input
class="rounded p-1 transition-all outline-none text-center dark:bg-gray-700"
bind:value={controller.name}
on:keyup={save_player_name_debounce}
/>
<SaveIndicator status={saved_status} />
</div>
</div>
<div class="flex flex-col">
<h2 class="mx-auto text-2xl">{$t('controllers.player_name')}</h2>
<div class="mx-auto flex">
<input
class="rounded p-1 transition-all outline-none text-center dark:bg-gray-700"
bind:value={controller.player_name}
on:keyup={save_player_name_debounce}
/>
<SaveIndicator status={saved_status} />
</div>
</div>
<div class="flex flex-col">
<h2 class="mx-auto text-2xl">{$t('words.update')}</h2>
{#await get_latest_version()}
<Spinner my_20={false} />
{:then _}
<p class="mx-auto">
{$t('controllers.version_overview', {
newest_version,
current_version: controller.os_version
})}
</p>
{/await}
{#if newest_version && controller.os_version}
<div class="mx-auto">
<BrownButton
disabled={newest_version === controller.os_version}
on:click={allow_update_to_version}
>
{#if newest_version === controller.os_version}
{$t('controllers.already_latest_version')}
{:else if newest_version === controller.wanted_os_version}
{$t('controllers.cancel_update')}
{:else}
{$t('controllers.update_from_to', {
newest_version,
current_version: controller.os_version
})}
{/if}
</BrownButton>
</div>
{/if}
</div>
</div>
@@ -0,0 +1,26 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load = (async ({ fetch, params }) => {
const res = await fetch(`/api/v1/box-controller/web/controller?id=${params.controller_id}`);
if (res.status !== 200) {
throw error(res.status, await res.text());
}
const json: {
id: string;
player_name: string;
last_seen?: string;
first_seen?: string;
name: string;
os_version?: string;
wanted_os_version?: string;
} = await res.json();
return {
controller: json
};
}) satisfies PageLoad;
@@ -0,0 +1,37 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import { SaveStatus } from './commons';
export let status: SaveStatus;
</script>
<div class="h-6 w-6 grow-0 my-auto">
{#if status === SaveStatus.Saved}
<svg
class="h-full w-full"
aria-hidden="true"
fill="none"
stroke="currentColor"
stroke-width="2"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M5 13l4 4L19 7" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{:else if status === SaveStatus.Saving}
<svg class="max-h-full max-w-full h-full animate-spin w-full" viewBox="3 3 18 18">
<path
class="fill-black"
d="M12 5C8.13401 5 5 8.13401 5 12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12C19 8.13401 15.866 5 12 5ZM3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12Z"
/>
<path
class="fill-blue-100"
d="M16.9497 7.05015C14.2161 4.31648 9.78392 4.31648 7.05025 7.05015C6.65973 7.44067 6.02656 7.44067 5.63604 7.05015C5.24551 6.65962 5.24551 6.02646 5.63604 5.63593C9.15076 2.12121 14.8492 2.12121 18.364 5.63593C18.7545 6.02646 18.7545 6.65962 18.364 7.05015C17.9734 7.44067 17.3403 7.44067 16.9497 7.05015Z"
/>
</svg>
{/if}
</div>
@@ -0,0 +1,15 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/* eslint-disable no-unused-vars */
export enum SaveStatus {
Unchanged,
Saved,
Saving,
Error
}
/* eslint-enable */
@@ -0,0 +1,133 @@
<script lang="ts">
import { goto } from '$app/navigation';
import type { PageData } from './$types';
export let data: PageData;
let input_data = {
player_name: data.username,
name: ''
};
let isValid = false;
let isSubmitting = false;
$: isValid = input_data.name.length !== 0 && input_data.player_name.length !== 0;
const submit = async () => {
if (!isValid) {
return;
}
const res = await fetch('/api/v1/box-controller/web/setup', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(input_data)
});
if (res.ok) {
const json = await res.json();
goto(`/account/controllers/add/wait?id=${json.id}&code=${json.code}`);
}
};
</script>
<div class="flex items-center justify-center h-full px-4">
<div>
<div
class="w-full max-w-sm mx-auto overflow-hidden bg-white rounded-lg shadow-md dark:bg-gray-800"
>
<div class="px-6 py-4">
<h2 class="text-3xl font-bold text-center text-gray-700 dark:text-white">
ClassQuiz
</h2>
<h3 class="mt-1 text-xl font-medium text-center text-gray-600 dark:text-gray-200">
Add a controller
</h3>
<form on:submit|preventDefault={submit}>
<div class="w-full mt-4">
<div class="dark:bg-gray-800 bg-white p-4 rounded-lg">
<div class="relative bg-inherit w-full">
<input
id="player_name"
name="player_name"
type="text"
class="w-full peer bg-transparent h-10 rounded-lg text-gray-700 dark:text-white placeholder-transparent ring-2 px-2 ring-gray-500 focus:ring-sky-600 focus:outline-none focus:border-rose-600"
class:ring-red-700={input_data.player_name.length === 0}
class:ring-green-600={input_data.player_name.length !== 0}
bind:value={input_data.player_name}
/>
<label
for="player_name"
class="absolute cursor-text left-0 -top-3 text-sm text-gray-700 dark:text-white bg-inherit mx-1 px-1 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-500 peer-placeholder-shown:top-2 peer-focus:-top-3 peer-focus:text-sky-600 peer-focus:text-sm transition-all"
>
Player name
</label>
</div>
</div>
<div class="dark:bg-gray-800 bg-white p-4 rounded-lg">
<div class="relative bg-inherit w-full">
<input
id="name"
name="name"
type="text"
class="w-full peer bg-transparent h-10 rounded-lg text-gray-700 dark:text-white placeholder-transparent ring-2 px-2 ring-gray-500 focus:ring-sky-600 focus:outline-none focus:border-rose-600"
placeholder="Name"
class:ring-red-700={input_data.name.length === 0}
class:ring-green-600={input_data.name.length !== 0}
bind:value={input_data.name}
/>
<label
for="name"
class="absolute cursor-text left-0 -top-3 text-sm text-gray-700 dark:text-white bg-inherit mx-1 px-1 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-500 peer-placeholder-shown:top-2 peer-focus:-top-3 peer-focus:text-sky-600 peer-focus:text-sm transition-all"
>
Name
</label>
</div>
</div>
<div class="flex items-center justify-center mt-4">
<button
class="px-4 py-2 leading-5 text-white transition-colors duration-200 transform bg-gray-700 rounded hover:bg-gray-600 focus:outline-none"
disabled={!isValid || isSubmitting}
class:cursor-not-allowed={!isValid || isSubmitting}
class:opacity-50={!isValid || isSubmitting}
type="submit"
>
{#if isSubmitting}
<svg class="h-4 w-4 animate-spin" viewBox="3 3 18 18">
<path
class="fill-blue-800"
d="M12 5C8.13401 5 5 8.13401 5 12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12C19 8.13401 15.866 5 12 5ZM3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12Z"
/>
<path
class="fill-blue-100"
d="M16.9497 7.05015C14.2161 4.31648 9.78392 4.31648 7.05025 7.05015C6.65973 7.44067 6.02656 7.44067 5.63604 7.05015C5.24551 6.65962 5.24551 6.02646 5.63604 5.63593C9.15076 2.12121 14.8492 2.12121 18.364 5.63593C18.7545 6.02646 18.7545 6.65962 18.364 7.05015C17.9734 7.44067 17.3403 7.44067 16.9497 7.05015Z"
/>
</svg>
{:else}
Add
{/if}
</button>
</div>
</div>
</form>
</div>
<div
class="flex items-center justify-center py-4 text-center bg-gray-50 dark:bg-gray-700"
>
<span class="text-sm text-gray-600 dark:text-gray-200"
>Don't know what this is?
</span>
<a
href="/account/login"
class="mx-2 text-sm font-bold text-blue-500 dark:text-blue-400 hover:underline"
>Read more here.</a
>
</div>
</div>
</div>
</div>
@@ -0,0 +1,15 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import type { PageLoad } from './$types';
export const load = (async ({ fetch }) => {
const resp = await fetch('/api/v1/users/me');
const json = await resp.json();
return {
username: json.username
};
}) satisfies PageLoad;
@@ -0,0 +1,14 @@
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load = (({ url }) => {
const code = url.searchParams.get('code');
const id = url.searchParams.get('id');
if (!id || !code) {
throw error(404, JSON.stringify({ detail: 'id and/or code are/is missing' }));
}
return {
id,
code
};
}) satisfies PageServerLoad;
@@ -0,0 +1,49 @@
<script lang="ts">
import type { PageData } from './$types';
import CodeDisplay from '$lib/components/controller/code.svelte';
import Spinner from '$lib/Spinner.svelte';
import { onMount } from 'svelte';
export let data: PageData;
let controller_seen = false;
let check_tick = 0;
let interval;
const check_if_controller_was_seen = async () => {
const res = await fetch(`/api/v1/box-controller/web/controller?id=${data.id}`);
const json = await res.json();
controller_seen = Boolean(json.first_seen);
if (controller_seen) {
clearInterval(interval);
}
};
onMount(async () => {
await check_if_controller_was_seen();
interval = setInterval(async () => {
check_tick += 1;
if (check_tick === 5) {
await check_if_controller_was_seen();
check_tick = 0;
}
}, 1000);
});
</script>
<div class="w-full h-full flex">
<div class="m-auto flex flex-col">
<div class="block">
<CodeDisplay code={data.code} />
</div>
{#if controller_seen}
<div class="mt-10">
<p class="text-center">Controller set up successfully!</p>
</div>
{:else}
<div class="mt-10 flex-col flex gap-2 justify-center">
<p>Checking if controller has been connected in {5 - check_tick} seconds.</p>
<Spinner my_20={false} />
</div>
{/if}
</div>
</div>
@@ -188,6 +188,7 @@
<BrownButton href="/account/settings/security"
>{$t('settings_page.security_settings')}
</BrownButton>
<BrownButton href="/account/controllers">ClassQuizController</BrownButton>
</div>
</div>
</div>
@@ -0,0 +1,37 @@
"""Added Controllers Table
Revision ID: 32649a1ffcf2
Revises: 89c4b5d547aa
Create Date: 2023-06-30 01:24:43.124764
"""
from alembic import op
import sqlalchemy as sa
import ormar
# revision identifiers, used by Alembic.
revision = "32649a1ffcf2"
down_revision = "89c4b5d547aa"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"controller",
sa.Column("id", ormar.fields.sqlalchemy_uuid.CHAR(32), nullable=False),
sa.Column("user", ormar.fields.sqlalchemy_uuid.CHAR(32), nullable=True),
sa.Column("secret_key", sa.String(length=24), nullable=False),
sa.Column("player_name", sa.Text(), nullable=False),
sa.Column("last_seen", sa.DateTime(), nullable=True),
sa.Column("first_seen", sa.DateTime(), nullable=True),
sa.Column("name", sa.Text(), nullable=False),
sa.Column("os_version", sa.Text(), nullable=True),
sa.Column("wanted_os_version", sa.Text(), nullable=True),
sa.ForeignKeyConstraint(["user"], ["users.id"], name="fk_controller_users_id_user"),
sa.PrimaryKeyConstraint("id"),
)
def downgrade() -> None:
op.drop_table("controller")