significant refactor/cleanup
This commit is contained in:
@@ -7,6 +7,7 @@ import time
|
||||
import datetime
|
||||
import traceback
|
||||
import aiosqlite as sqlite3
|
||||
from typing import LiteralString, Optional
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from .constructors import ValidTopKarmaRequest, ValidKarmaRetrievalRequest,\
|
||||
ValidKarmaUpdateRequest
|
||||
@@ -14,11 +15,16 @@ from .constructors import ValidTopKarmaRequest, ValidKarmaRetrievalRequest,\
|
||||
class KarmaDB:
|
||||
"""Karma DB Util"""
|
||||
def __init__(self):
|
||||
self.db_path = os.path.join("/", "usr", "local", "share",
|
||||
self.db_path: LiteralString = os.path.join("/", "usr", "local", "share",
|
||||
"sqlite_dbs", "karma.db")
|
||||
|
||||
async def get_karma(self, keyword: str) -> int | dict:
|
||||
"""Get Karma Value for Keyword"""
|
||||
"""Get Karma Value for Keyword
|
||||
Args:
|
||||
keyword (str): The keyword to search
|
||||
Returns:
|
||||
int|dict
|
||||
"""
|
||||
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
|
||||
async with await db_conn.execute("SELECT score FROM karma WHERE keyword LIKE ? LIMIT 1", (keyword,)) as db_cursor:
|
||||
try:
|
||||
@@ -30,8 +36,13 @@ class KarmaDB:
|
||||
'errorText': f'No records for {keyword}',
|
||||
}
|
||||
|
||||
async def get_top(self, n: int = 10):
|
||||
"""Get Top n=10 Karma Entries"""
|
||||
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]
|
||||
"""
|
||||
try:
|
||||
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
|
||||
async with await db_conn.execute("SELECT keyword, score FROM karma ORDER BY score DESC LIMIT ?", (n,)) as db_cursor:
|
||||
@@ -40,25 +51,32 @@ class KarmaDB:
|
||||
traceback.print_exc()
|
||||
return
|
||||
|
||||
async def update_karma(self, granter: str, keyword: str, flag: int):
|
||||
"""Update Karma for Keyword"""
|
||||
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]
|
||||
"""
|
||||
|
||||
if not flag in [0, 1]:
|
||||
return
|
||||
|
||||
modifier = "score + 1" if not flag else "score - 1"
|
||||
query = f"UPDATE karma SET score = {modifier}, last_change = ? WHERE keyword LIKE ?"
|
||||
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())
|
||||
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())
|
||||
|
||||
logging.debug("Audit message: %s{audit_message}\nKeyword: %s{keyword}")
|
||||
|
||||
async with sqlite3.connect(self.db_path, timeout=2) as db_conn:
|
||||
async with await db_conn.execute(audit_query, (keyword, audit_message,)) as db_cursor:
|
||||
await db_conn.commit()
|
||||
await db_cursor.close()
|
||||
await db_conn.commit()
|
||||
async with await db_conn.execute(query, (now, keyword,)) as db_cursor:
|
||||
if db_cursor.rowcount:
|
||||
await db_conn.commit()
|
||||
@@ -72,11 +90,6 @@ class KarmaDB:
|
||||
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
|
||||
@@ -86,7 +99,7 @@ class Karma(FastAPI):
|
||||
self.glob_state = glob_state
|
||||
self.db = KarmaDB()
|
||||
|
||||
self.endpoints = {
|
||||
self.endpoints: dict = {
|
||||
"karma/get": self.get_karma_handler,
|
||||
"karma/modify": self.modify_karma_handler,
|
||||
"karma/top": self.top_karma_handler,
|
||||
@@ -97,23 +110,19 @@ class Karma(FastAPI):
|
||||
include_in_schema=False)
|
||||
|
||||
|
||||
async def top_karma_handler(self, request: Request, data: ValidTopKarmaRequest | None = None):
|
||||
"""
|
||||
/karma/top
|
||||
Get top keywords for karma
|
||||
(Requires key)
|
||||
"""
|
||||
async def top_karma_handler(self, request: Request, data: ValidTopKarmaRequest | None = None) -> list[tuple]|dict:
|
||||
"""Get top keywords for karma"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
|
||||
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||
|
||||
n = 10
|
||||
n: int = 10
|
||||
if data:
|
||||
n = data.n
|
||||
n: int = int(data.n)
|
||||
|
||||
|
||||
try:
|
||||
top10 = await self.db.get_top(n=n)
|
||||
top10: list[tuple] = await self.db.get_top(n=n)
|
||||
return top10
|
||||
except:
|
||||
traceback.print_exc()
|
||||
@@ -123,18 +132,14 @@ class Karma(FastAPI):
|
||||
}
|
||||
|
||||
async def get_karma_handler(self, data: ValidKarmaRetrievalRequest, request: Request):
|
||||
"""
|
||||
/karma/get
|
||||
Get current karma value
|
||||
(Requires key)
|
||||
"""
|
||||
"""Get current karma value"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With')):
|
||||
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||
|
||||
keyword = data.keyword
|
||||
keyword: str = data.keyword
|
||||
try:
|
||||
count = await self.db.get_karma(keyword)
|
||||
count: int|dict = await self.db.get_karma(keyword)
|
||||
return {
|
||||
'keyword': keyword,
|
||||
'count': count,
|
||||
@@ -146,12 +151,8 @@ class Karma(FastAPI):
|
||||
'errorText': "Exception occurred."
|
||||
}
|
||||
|
||||
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest, request: Request):
|
||||
"""
|
||||
/karma/update
|
||||
Update karma count
|
||||
(Requires key)
|
||||
"""
|
||||
async def modify_karma_handler(self, data: ValidKarmaUpdateRequest, request: Request) -> dict:
|
||||
"""Update karma count"""
|
||||
|
||||
if not self.util.check_key(request.url.path, request.headers.get('X-Authd-With'), 2):
|
||||
raise HTTPException(status_code=403, detail="Unauthorized")
|
||||
|
||||
Reference in New Issue
Block a user