api/endpoints/karma.py

192 lines
7.4 KiB
Python
Raw Normal View History

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-15 21:09:33 -05:00
from typing import LiteralString, Optional, Union
2024-11-14 14:37:32 -05:00
from fastapi import FastAPI, Request, HTTPException
2025-02-15 21:09:33 -05:00
from fastapi.responses import JSONResponse
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"""
2025-02-14 16:07:24 -05:00
def __init__(self) -> None:
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
2025-02-15 21:09:33 -05:00
async def get_karma(self, keyword: str) -> Union[int, dict]:
2025-02-11 20:01:07 -05:00
"""Get Karma Value for Keyword
Args:
keyword (str): The keyword to search
Returns:
2025-02-15 21:09:33 -05:00
Union[int, dict]
2025-02-11 20:01:07 -05:00
"""
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-14 16:07:24 -05:00
async def get_top(self, n: Optional[int] = 10) -> Optional[list[tuple]]:
2025-02-15 21:09:33 -05:00
"""
Get Top n=10 Karma Entries
2025-02-11 20:01:07 -05:00
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()
2025-02-14 16:07:24 -05:00
return None
2024-11-14 14:37:32 -05:00
2025-02-15 21:09:33 -05:00
async def update_karma(self, granter: str, keyword: str,
flag: int) -> Optional[bool]:
"""
Update Karma for Keyword
2025-02-11 20:01:07 -05:00
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]:
2025-02-14 16:07:24 -05:00
return None
2024-11-14 14:37:32 -05:00
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
2025-02-14 16:07:24 -05:00
return False
2024-11-14 14:37:32 -05:00
class Karma(FastAPI):
2025-02-15 21:09:33 -05:00
"""
Karma Endpoints
"""
2025-02-16 08:50:53 -05:00
def __init__(self, app: FastAPI, util, constants) -> None:
2025-02-15 21:09:33 -05:00
self.app: FastAPI = app
2024-11-14 14:37:32 -05:00
self.util = util
self.constants = constants
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"],
2025-02-16 07:56:33 -05:00
include_in_schema=True)
2024-11-14 14:37:32 -05:00
2025-02-15 21:09:33 -05:00
async def top_karma_handler(self, request: Request,
data: Optional[ValidTopKarmaRequest] = None) -> JSONResponse:
"""
Get top keywords for karma
2025-02-16 08:17:27 -05:00
- **n**: Number of top results to return (default: 10)
2025-02-15 21:09:33 -05:00
"""
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
2025-02-14 16:07:24 -05:00
if data and data.n:
n = int(data.n)
2024-11-14 19:20:37 -05:00
2024-11-14 14:37:32 -05:00
try:
2025-02-14 16:07:24 -05:00
top10: Optional[list[tuple]] = await self.db.get_top(n=n)
if not top10:
2025-02-15 21:09:33 -05:00
return JSONResponse(status_code=500, content={
2025-02-14 16:07:24 -05:00
'err': True,
'errorText': 'General failure',
2025-02-15 21:09:33 -05:00
})
return JSONResponse(content=top10)
2025-01-11 20:59:10 -05:00
except:
traceback.print_exc()
2025-02-15 21:09:33 -05:00
return JSONResponse(status_code=500, content={
2024-11-14 14:37:32 -05:00
'err': True,
'errorText': 'Exception occurred.',
2025-02-15 21:09:33 -05:00
})
2024-11-14 14:37:32 -05:00
2025-02-15 21:09:33 -05:00
async def get_karma_handler(self, data: ValidKarmaRetrievalRequest,
request: Request) -> JSONResponse:
2025-02-16 08:17:27 -05:00
"""
Get current karma value
- **keyword**: Keyword to retrieve karma value for
"""
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-15 21:09:33 -05:00
count: Union[int, dict] = await self.db.get_karma(keyword)
return JSONResponse(content={
2024-11-14 14:37:32 -05:00
'keyword': keyword,
'count': count,
2025-02-15 21:09:33 -05:00
})
2024-11-14 14:37:32 -05:00
except:
2025-01-11 20:59:10 -05:00
traceback.print_exc()
2025-02-15 21:09:33 -05:00
return JSONResponse(status_code=500, content={
2024-11-14 14:37:32 -05:00
'err': True,
2025-02-15 21:09:33 -05:00
'errorText': "Exception occurred.",
})
2024-11-14 14:37:32 -05:00
2025-02-15 21:09:33 -05:00
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest,
request: Request) -> JSONResponse:
2025-02-16 08:17:27 -05:00
"""
Update karma count
- **granter**: User who granted the karma
- **keyword**: The keyword to modify
- **flag**: 0 to decrement (--), 1 to increment (++)
"""
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]:
2025-02-15 21:09:33 -05:00
return JSONResponse(status_code=500, content={
2024-11-14 14:37:32 -05:00
'err': True,
2025-02-15 21:09:33 -05:00
'errorText': 'Invalid request',
})
2024-11-14 14:37:32 -05:00
2025-02-15 21:09:33 -05:00
return JSONResponse(content={
'success': await self.db.update_karma(data.granter,
data.keyword, data.flag)
})