api/endpoints/karma.py

191 lines
6.3 KiB
Python
Raw Normal View History

2024-11-14 14:37:32 -05:00
#!/usr/bin/env python3.12
2025-01-11 20:59:10 -05:00
# pylint: disable=bare-except, broad-exception-caught
2024-11-14 14:37:32 -05:00
import os
2025-01-11 20:59:10 -05:00
import logging
2024-11-14 14:37:32 -05:00
import time
import datetime
2025-01-11 20:59:10 -05:00
import traceback
2024-11-14 14:37:32 -05:00
import aiosqlite as sqlite3
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
class ValidKarmaUpdateRequest(BaseModel):
"""
Requires authentication
- **granter**: who updated the karma
- **keyword**: keyword to update karma for
- **flag**: either 0 (decrement) for --, or 1 (increment) for ++
"""
granter: str
keyword: str
flag: int
class ValidKarmaRetrievalRequest(BaseModel):
"""
- **keyword**: keyword to retrieve karma value of
"""
keyword: str
2024-11-14 19:20:37 -05:00
class ValidTopKarmaRequest(BaseModel):
"""
- **n**: Number of top results to return (default: 10)
"""
n: int | None = 10
2024-11-14 14:37:32 -05:00
class KarmaDB:
2025-01-11 20:59:10 -05:00
"""Karma DB Util"""
2024-11-14 14:37:32 -05:00
def __init__(self):
self.db_path = os.path.join("/", "var", "lib", "singerdbs", "karma.db")
2024-11-14 19:22:43 -05:00
async def get_karma(self, keyword: str) -> int | dict:
2025-01-11 20:59:10 -05:00
"""Get Karma Value for Keyword"""
2024-11-14 14:37:32 -05:00
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
2024-11-17 13:41:20 -05:00
async with db_conn.execute("SELECT score FROM karma WHERE keyword LIKE ? LIMIT 1", (keyword,)) as db_cursor:
2024-11-14 14:37:32 -05:00
try:
(score,) = await db_cursor.fetchone()
return score
2025-01-11 20:59:10 -05:00
except TypeError:
2024-11-14 14:37:32 -05:00
return {
'err': True,
'errorText': f'No records for {keyword}',
}
2024-11-14 19:20:37 -05:00
async def get_top(self, n: int = 10):
2025-01-11 20:59:10 -05:00
"""Get Top n=10 Karma Entries"""
2024-11-14 14:37:32 -05:00
try:
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
2024-11-14 19:20:37 -05:00
async with db_conn.execute("SELECT keyword, score FROM karma ORDER BY score DESC LIMIT ?", (n,)) as db_cursor:
2024-11-14 14:37:32 -05:00
return await db_cursor.fetchall()
2025-01-11 20:59:10 -05:00
except:
traceback.print_exc()
2024-11-14 14:37:32 -05:00
return
async def update_karma(self, granter: str, keyword: str, flag: int):
2025-01-11 20:59:10 -05:00
"""Update Karma for Keyword"""
2024-11-14 14:37:32 -05:00
if not flag in [0, 1]:
return
modifier = "score + 1" if not flag else "score - 1"
2024-11-17 13:41:20 -05:00
query = f"UPDATE karma SET score = {modifier}, last_change = ? WHERE keyword LIKE ?"
2024-11-14 14:37:32 -05:00
new_keyword_query = "INSERT INTO karma(keyword, score, last_change) VALUES(?, ?, ?)"
friendly_flag = "++" if not flag else "--"
audit_message = f"{granter} adjusted karma for {keyword} @ {datetime.datetime.now().isoformat()}: {friendly_flag}"
audit_query = "INSERT INTO karma_audit(impacted_keyword, comment) VALUES(?, ?)"
now = int(time.time())
2025-01-11 20:59:10 -05:00
logging.debug("Audit message: %s{audit_message}\nKeyword: %s{keyword}")
2024-11-14 14:37:32 -05:00
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
async with db_conn.execute(audit_query, (keyword, audit_message,)) as db_cursor:
await db_conn.commit()
await db_cursor.close()
async with db_conn.execute(query, (now, keyword,)) as db_cursor:
if db_cursor.rowcount:
await db_conn.commit()
return True
if db_cursor.rowcount < 1: # Keyword does not already exist
await db_cursor.close()
new_val = 1 if not flag else -1
async with db_conn.execute(new_keyword_query, (keyword, new_val, now,)) as db_cursor:
if db_cursor.rowcount >= 1:
await db_conn.commit()
return True
else:
return False
class Karma(FastAPI):
"""Karma Endpoints"""
def __init__(self, app: FastAPI, util, constants, glob_state): # pylint: disable=super-init-not-called
self.app = app
self.util = util
self.constants = constants
self.glob_state = glob_state
self.db = KarmaDB()
self.endpoints = {
"karma/get": self.get_karma_handler,
"karma/modify": self.modify_karma_handler,
"karma/top": self.top_karma_handler,
}
for endpoint, handler in self.endpoints.items():
app.add_api_route(f"/{endpoint}/", handler, methods=["POST"])
2024-11-14 19:20:37 -05:00
async def top_karma_handler(self, request: Request, data: ValidTopKarmaRequest | None = None):
2024-11-14 14:37:32 -05:00
"""
/karma/top/
2024-11-14 19:20:37 -05:00
Get top keywords for karma
2024-11-17 13:41:20 -05:00
(Requires key)
2024-11-14 14:37:32 -05:00
"""
2024-11-14 19:20:37 -05:00
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
raise HTTPException(status_code=403, detail="Unauthorized")
n = 10
if data:
n = data.n
2024-11-14 14:37:32 -05:00
try:
2024-11-14 19:20:37 -05:00
top10 = await self.db.get_top(n=n)
2024-11-14 14:37:32 -05:00
return top10
2025-01-11 20:59:10 -05:00
except:
traceback.print_exc()
2024-11-14 14:37:32 -05:00
return {
'err': True,
'errorText': 'Exception occurred.',
}
2024-11-17 13:41:20 -05:00
async def get_karma_handler(self, data: ValidKarmaRetrievalRequest, request: Request):
2024-11-14 14:37:32 -05:00
"""
/karma/get/
Get current karma value
2024-11-17 13:41:20 -05:00
(Requires key)
2024-11-14 14:37:32 -05:00
"""
2024-11-17 13:41:20 -05:00
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
raise HTTPException(status_code=403, detail="Unauthorized")
2024-11-14 14:37:32 -05:00
keyword = data.keyword
try:
count = await self.db.get_karma(keyword)
return {
'keyword': keyword,
'count': count,
}
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2024-11-14 14:37:32 -05:00
return {
'err': True,
'errorText': "Exception occurred."
}
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest, request: Request):
"""
/karma/update/
2024-11-14 19:20:37 -05:00
Update karma count
2024-11-17 13:41:20 -05:00
(Requires key)
2024-11-14 14:37:32 -05:00
"""
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With'), 2):
raise HTTPException(status_code=403, detail="Unauthorized")
if not data.flag in [0, 1]:
return {
'err': True,
'errorText': 'Invalid request'
}
return {
'success': await self.db.update_karma(data.granter, data.keyword, data.flag)
2025-01-11 20:59:10 -05:00
}