KemoFureApi/modules/Archive/database.py

49 lines
1.8 KiB
Python

import json
from .databaseController import DatabaseController
from .endpoints.query import Archive_Query
from .endpoints.get_posts import Archive_GetPosts
class Database:
db : DatabaseController = None
def __init__(self, api) -> None:
app = api.app
if "Archive" in app.databases:
del app.databases["Archive"]
self.reload_data()
app.databases["Archive"] = self
api.add_resource(Archive_Query, "/Archive/Query")
api.add_resource(Archive_GetPosts, "/Archive/GetPosts")
def get_posts(self, num_posts, actions_taken = [0, 1, 2, 3], last_id = -1, offset = 0):
num_posts = max(1, min(num_posts, 30))
where_query = "WHERE x_post_details.id NOT NULL AND x_posts.error_id = 0"
if last_id != -1:
where_query += f" AND x_posts.id < {last_id}"
if actions_taken != [0, 1, 2, 3]:
where_query += " AND (" + " OR ".join([f"x_posts.action_taken = {action}" for action in actions_taken]) + ")"
query = f'''
SELECT x_posts.id, x_post_details.text, x_post_details.files, accounts.x_handle FROM x_posts
LEFT JOIN x_post_details
ON x_posts.id = x_post_details.id
LEFT JOIN accounts
ON x_posts.account_id = accounts.id
{where_query}
ORDER BY x_posts.id DESC
LIMIT {num_posts} OFFSET {offset}'''
result = self.db.run_query(query)
posts = []
if result is not None:
for result in self.db.run_query(query):
posts.append({"id": result[0], "id_str": str(result[0]), "text": result[1], "files": result[2].split(','), "handle": result[3]})
return posts
def reload_data(self):
self.db = DatabaseController("/home/pi/python/Katbots/JapariArchive/database.db")