api/endpoints/karma.py

168 lines
6.5 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
2025-02-11 20:01:07 -05:00
from typing import LiteralString, Optional
2024-11-14 14:37:32 -05:00
from fastapi import FastAPI, Request, HTTPException
2025-02-11 11:19:52 -05:00
from .constructors import ValidTopKarmaRequest, ValidKarmaRetrievalRequest,\
ValidKarmaUpdateRequest
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):
2025-02-11 20:01:07 -05:00
self.db_path: LiteralString = os.path.join("/", "usr", "local", "share",
2025-01-24 19:26:07 -05:00
"sqlite_dbs", "karma.db")
2024-11-14 14:37:32 -05:00
2024-11-14 19:22:43 -05:00
async def get_karma(self, keyword: str) -> int | dict:
2025-02-11 20:01:07 -05:00
"""Get Karma Value for Keyword
Args:
keyword (str): The keyword to search
Returns:
int|dict
"""
2024-11-14 14:37:32 -05:00
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
2025-01-23 13:02:03 -05:00
async with await 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}',
}
2025-02-11 20:01:07 -05:00
async def get_top(self, n: Optional[int] = 10) -> list[tuple]:
"""Get Top n=10 Karma Entries
Args:
n (Optional[int]) = 10: The number of top results to return
Returns:
list[tuple]
"""
2024-11-14 14:37:32 -05:00
try:
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
2025-01-23 13:02:03 -05:00
async with await 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
2025-02-11 20:01:07 -05:00
async def update_karma(self, granter: str, keyword: str, flag: int) -> Optional[bool]:
"""Update Karma for Keyword
Args:
granter (str): The user who granted (increased/decreased) the karma
keyword (str): The keyword to update
flag (int): 0 to increase karma, 1 to decrease karma
Returns:
Optional[bool]
"""
2024-11-14 14:37:32 -05:00
if not flag in [0, 1]:
return
2025-02-11 20:01:07 -05:00
modifier: str = "score + 1" if not flag else "score - 1"
query: str = f"UPDATE karma SET score = {modifier}, last_change = ? WHERE keyword LIKE ?"
new_keyword_query: str = "INSERT INTO karma(keyword, score, last_change) VALUES(?, ?, ?)"
friendly_flag: str = "++" if not flag else "--"
audit_message: str = f"{granter} adjusted karma for {keyword} @ {datetime.datetime.now().isoformat()}: {friendly_flag}"
audit_query: str = "INSERT INTO karma_audit(impacted_keyword, comment) VALUES(?, ?)"
now: int = int(time.time())
2024-11-14 14:37:32 -05:00
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:
2025-01-23 13:02:03 -05:00
async with await db_conn.execute(audit_query, (keyword, audit_message,)) as db_cursor:
2025-02-11 20:01:07 -05:00
await db_conn.commit()
2025-01-23 13:02:03 -05:00
async with await db_conn.execute(query, (now, keyword,)) as db_cursor:
2024-11-14 14:37:32 -05:00
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
2025-01-23 13:02:03 -05:00
async with await db_conn.execute(new_keyword_query, (keyword, new_val, now,)) as db_cursor:
2024-11-14 14:37:32 -05:00
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()
2025-02-11 20:01:07 -05:00
self.endpoints: dict = {
2024-11-14 14:37:32 -05:00
"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():
2025-01-29 15:48:47 -05:00
app.add_api_route(f"/{endpoint}", handler, methods=["POST"],
include_in_schema=False)
2024-11-14 14:37:32 -05:00
2025-02-11 20:01:07 -05:00
async def top_karma_handler(self, request: Request, data: ValidTopKarmaRequest | None = None) -> list[tuple]|dict:
"""Get top keywords for karma"""
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")
2025-02-11 20:01:07 -05:00
n: int = 10
2024-11-14 19:20:37 -05:00
if data:
2025-02-11 20:01:07 -05:00
n: int = int(data.n)
2024-11-14 19:20:37 -05:00
2024-11-14 14:37:32 -05:00
try:
2025-02-11 20:01:07 -05:00
top10: list[tuple] = 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):
2025-02-11 20:01:07 -05:00
"""Get current karma value"""
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")
2025-02-11 20:01:07 -05:00
keyword: str = data.keyword
2024-11-14 14:37:32 -05:00
try:
2025-02-11 20:01:07 -05:00
count: int|dict = await self.db.get_karma(keyword)
2024-11-14 14:37:32 -05:00
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."
}
2025-02-11 20:01:07 -05:00
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest, request: Request) -> dict:
"""Update karma count"""
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
}