2024-02-17 21:47:42 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
from typing import Union
|
|
|
|
import hashlib
|
|
|
|
import sqlite3
|
|
|
|
|
|
|
|
from fastapi import Depends, FastAPI
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
|
import uvicorn
|
|
|
|
|
|
|
|
from aci.db import get_db
|
2024-02-18 12:26:07 +00:00
|
|
|
from aci.migrate import run_migrations
|
2024-02-17 21:47:42 +00:00
|
|
|
from aci.models import CodeSubmission
|
|
|
|
from aci import utils
|
|
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origin_regex=r"moz-extension://.*",
|
|
|
|
allow_methods=["GET"],
|
|
|
|
allow_headers="*",
|
|
|
|
)
|
|
|
|
|
2024-02-18 19:28:58 +00:00
|
|
|
@app.get('/')
|
2024-02-18 18:03:48 +00:00
|
|
|
def index():
|
|
|
|
return {
|
|
|
|
'🏳️⚧️': 'trans rights!',
|
|
|
|
}
|
|
|
|
|
2024-02-17 21:47:42 +00:00
|
|
|
@app.post('/api/codes')
|
|
|
|
def submit_code(date: str, time: str, activity: str, space: str, submission: CodeSubmission, db: sqlite3.Cursor=Depends(get_db)):
|
|
|
|
# TODO: validate parameters meet expected form.
|
|
|
|
db.execute('INSERT INTO code_results (date, time, space, activity, code, result) VALUES (?,?,?,?,?,?)', (date, time, space, activity, submission.code, submission.success))
|
|
|
|
return {'ok': True}
|
|
|
|
|
|
|
|
@app.get('/api/codes')
|
|
|
|
def current_codes(db: sqlite3.Cursor=Depends(get_db)):
|
|
|
|
result = db.execute('SELECT date, time, space, activity, code, result FROM code_results WHERE date = ?', (utils.today(),))
|
|
|
|
codes = result.fetchall()
|
|
|
|
code_scores = {}
|
|
|
|
code_info = {}
|
|
|
|
for date, time, space, activity, code, result in codes:
|
|
|
|
k = str((date, time, space, activity))
|
|
|
|
code_info[k] = (date, time, space, activity)
|
|
|
|
if k not in code_scores:
|
|
|
|
code_scores[k] = {}
|
|
|
|
if code not in code_scores[k]:
|
|
|
|
code_scores[k][code] = 0
|
|
|
|
code_scores[k][code] += 1 if result else -1
|
|
|
|
ret = []
|
|
|
|
for k, v in code_scores.items():
|
|
|
|
date, time, space, activity = code_info[k]
|
|
|
|
codes = list(map(lambda c: {'code': c[0], 'score': c[1]}, v.items()))
|
|
|
|
codes.sort(key=lambda c: -c['score'])
|
|
|
|
ret.append({
|
|
|
|
'date': date,
|
|
|
|
'time': time,
|
|
|
|
'space': space,
|
|
|
|
'activity': activity,
|
|
|
|
'codes': codes,
|
|
|
|
})
|
|
|
|
return {
|
2024-02-18 12:48:21 +00:00
|
|
|
'activities': ret,
|
2024-02-17 21:47:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-02-18 12:26:07 +00:00
|
|
|
run_migrations()
|
2024-02-18 13:44:24 +00:00
|
|
|
uvicorn.run(app, host='0.0.0.0')
|