From 09e8d01d3a7822ab136cf624c0dc54cdf85dfdef Mon Sep 17 00:00:00 2001 From: XANTRONIX Development Date: Mon, 2 Dec 2024 23:19:01 -0500 Subject: [PATCH] Add config file support for listener, database --- lib/nntp/tiny/config.py | 37 +++++++++++++++++++++++++++++++++++++ lib/nntp/tiny/server.py | 20 ++++++++++++++------ 2 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 lib/nntp/tiny/config.py diff --git a/lib/nntp/tiny/config.py b/lib/nntp/tiny/config.py new file mode 100644 index 0000000..ba27afd --- /dev/null +++ b/lib/nntp/tiny/config.py @@ -0,0 +1,37 @@ +import os +import configparser + +from typing import Optional + +class ConfigException(Exception): + def __init__(self, path: str): + self.path = path + + def __str__(self): + return "Unable to locate file '" + self.path + "'" + +class Config(): + SEARCH_PATHS = [ + './server.conf', + '/etc/nntp-tiny/server.conf' + ] + + @staticmethod + def find(): + for path in Config.SEARCH_PATHS: + if os.path.exists(path): + return path + + return None + + def load(path: Optional[str]=None): + if path is None: + path = Config.find() + + if path is None: + raise ConfigException(path) + + parser = configparser.ConfigParser() + parser.read(path) + + return parser diff --git a/lib/nntp/tiny/server.py b/lib/nntp/tiny/server.py index a2a2995..1b4e0f8 100644 --- a/lib/nntp/tiny/server.py +++ b/lib/nntp/tiny/server.py @@ -2,8 +2,10 @@ import enum import socket import threading -from typing import Callable +from configparser import ConfigParser +from nntp.tiny.config import Config +from nntp.tiny.db import Database from nntp.tiny.newsgroup import Newsgroup from nntp.tiny.session import Session @@ -13,13 +15,16 @@ class ServerCapability(enum.Flag): POST = enum.auto() class Server(): - def __init__(self, connect_to_db: Callable): - self.connect_to_db = connect_to_db - self.capabilities = ServerCapability.NONE - self.newsgroups = dict() + def __init__(self, config: ConfigParser): + self.config = config + self.capabilities = ServerCapability.NONE + self.newsgroups = dict() self._init_newsgroups() + def connect_to_db(self): + return Database.connect(self.config['database']['path']) + def _init_newsgroups(self): db = self.connect_to_db() @@ -27,8 +32,11 @@ class Server(): self.newsgroups[newsgroup.name.casefold()] = newsgroup def run(self): + host = self.config['listen']['host'] + port = int(self.config['listen']['port']) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - listener.bind(('localhost', 1190)) + listener.bind((host, port)) listener.listen() while True: