73 lines
2.4 KiB
Python
73 lines
2.4 KiB
Python
import os
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
|
|
from tinyweb_forum.db import ForumDB
|
|
from tinyweb_forum.handlers import ForumHandlers
|
|
from tinyweb_forum.sync import ForumSync
|
|
|
|
FORUM_ENABLED_KEY = "forum_enabled"
|
|
TRUST_REFRESH_INTERVAL = 120
|
|
|
|
|
|
class ForumPlugin:
|
|
def __init__(self, data_dir, identity, reticulum, site_name="me"):
|
|
self.fdb = ForumDB(data_dir)
|
|
self.handlers = ForumHandlers(
|
|
self.fdb, None, identity, reticulum, site_name=site_name
|
|
)
|
|
self.sync = ForumSync(self.fdb, identity, reticulum, lambda: self.handlers)
|
|
self.handlers.sync = self.sync
|
|
self.identity = identity
|
|
self.reticulum = reticulum
|
|
self._started = False
|
|
self._data_dir = data_dir
|
|
self._core_db_path = os.path.join(data_dir, "index.db")
|
|
self._trust_refresh_thread = None
|
|
|
|
def is_enabled(self):
|
|
return self.fdb.get_setting(FORUM_ENABLED_KEY, "0") == "1"
|
|
|
|
def _seed_trust_from_subscriptions(self):
|
|
my_hash = self.identity.hash.hex() if self.identity else "local"
|
|
if not os.path.exists(self._core_db_path):
|
|
return
|
|
try:
|
|
core = sqlite3.connect(self._core_db_path)
|
|
rows = core.execute(
|
|
"SELECT dest_hash FROM subscriptions WHERE forum_enabled = 1"
|
|
).fetchall()
|
|
core.close()
|
|
for row in rows:
|
|
self.fdb.add_trust_source(row[0], my_hash, 0)
|
|
except Exception:
|
|
pass
|
|
|
|
def _trust_refresh_loop(self):
|
|
while self._started:
|
|
try:
|
|
self._seed_trust_from_subscriptions()
|
|
except Exception:
|
|
pass
|
|
for _ in range(TRUST_REFRESH_INTERVAL):
|
|
if not self._started:
|
|
return
|
|
time.sleep(1)
|
|
|
|
def enable(self):
|
|
self.fdb.set_setting(FORUM_ENABLED_KEY, "1")
|
|
if not self._started:
|
|
self._seed_trust_from_subscriptions()
|
|
self.sync.start()
|
|
self._started = True
|
|
self._trust_refresh_thread = threading.Thread(
|
|
target=self._trust_refresh_loop, daemon=True
|
|
)
|
|
self._trust_refresh_thread.start()
|
|
|
|
def disable(self):
|
|
self.fdb.set_setting(FORUM_ENABLED_KEY, "0")
|
|
|
|
def handle(self, method, path, query, body, cookies=None):
|
|
return self.handlers.handle(method, path, query, body, cookies)
|