Add config file support for listener, database

This commit is contained in:
XANTRONIX Development 2024-12-02 23:19:01 -05:00
parent ee1c98c82d
commit 09e8d01d3a
2 changed files with 51 additions and 6 deletions

37
lib/nntp/tiny/config.py Normal file
View file

@ -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

View file

@ -2,8 +2,10 @@ import enum
import socket import socket
import threading 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.newsgroup import Newsgroup
from nntp.tiny.session import Session from nntp.tiny.session import Session
@ -13,13 +15,16 @@ class ServerCapability(enum.Flag):
POST = enum.auto() POST = enum.auto()
class Server(): class Server():
def __init__(self, connect_to_db: Callable): def __init__(self, config: ConfigParser):
self.connect_to_db = connect_to_db self.config = config
self.capabilities = ServerCapability.NONE self.capabilities = ServerCapability.NONE
self.newsgroups = dict() self.newsgroups = dict()
self._init_newsgroups() self._init_newsgroups()
def connect_to_db(self):
return Database.connect(self.config['database']['path'])
def _init_newsgroups(self): def _init_newsgroups(self):
db = self.connect_to_db() db = self.connect_to_db()
@ -27,8 +32,11 @@ class Server():
self.newsgroups[newsgroup.name.casefold()] = newsgroup self.newsgroups[newsgroup.name.casefold()] = newsgroup
def run(self): def run(self):
host = self.config['listen']['host']
port = int(self.config['listen']['port'])
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(('localhost', 1190)) listener.bind((host, port))
listener.listen() listener.listen()
while True: while True: