Add config file support for listener, database
This commit is contained in:
parent
ee1c98c82d
commit
09e8d01d3a
2 changed files with 51 additions and 6 deletions
37
lib/nntp/tiny/config.py
Normal file
37
lib/nntp/tiny/config.py
Normal 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
|
|
@ -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:
|
||||
|
|
Loading…
Add table
Reference in a new issue