Move shared constants, exceptions & helpers.py into /shared/

This commit is contained in:
Xevion
2022-06-12 13:17:26 -05:00
parent 724c0f9c4d
commit 64a5dd8c20
10 changed files with 33 additions and 26 deletions

View File

@@ -4,10 +4,9 @@ from typing import Tuple
from PyQt5.QtCore import QEvent from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QDialog, QStatusBar from PyQt5.QtWidgets import QDialog, QStatusBar
import constants from shared.constants import ConnectionOptions, DEFAULT_IP, DEFAULT_PORT
from client.ui.ConnectionDialog import Ui_ConnectionDialog from client.ui.ConnectionDialog import Ui_ConnectionDialog
from client.nickname import Ui_NicknameDialog from client.nickname import Ui_NicknameDialog
from constants import ConnectionOptions
class NicknameDialog(QDialog, Ui_NicknameDialog): class NicknameDialog(QDialog, Ui_NicknameDialog):
@@ -26,7 +25,7 @@ class NicknameDialog(QDialog, Ui_NicknameDialog):
self.show() self.show()
def controlSubmit(self): def controlSubmit(self):
"""Updates whether or not the dialog box is allowed to proceed""" """Updates whether the dialog box is allowed to proceed"""
if len(self.lineEdit.text()) > 2: if len(self.lineEdit.text()) > 2:
if self.disabled: if self.disabled:
self.disabled = False self.disabled = False
@@ -43,7 +42,7 @@ class NicknameDialog(QDialog, Ui_NicknameDialog):
class ConnectionDialog(QDialog, Ui_ConnectionDialog): class ConnectionDialog(QDialog, Ui_ConnectionDialog):
def __init__(self, nickname: str = None, *args, **kwargs): def __init__(self, nickname: str = None, *args, **kwargs):
super(ConnectionDialog, self).__init__(*args, **kwargs) super(ConnectionDialog, self).__init__(*args, **kwargs)
self.setupUi(self) self.setupUi(self)
@@ -77,8 +76,8 @@ class ConnectionDialog(QDialog, Ui_ConnectionDialog):
@property @property
def settings(self) -> ConnectionOptions: def settings(self) -> ConnectionOptions:
return ConnectionOptions(ip=self.server_address_input.text() or constants.DEFAULT_IP, return ConnectionOptions(ip=self.server_address_input.text() or DEFAULT_IP,
port=int(self.port_input.text() or constants.DEFAULT_PORT), port=int(self.port_input.text() or DEFAULT_PORT),
nickname=self.nickname_input.text(), nickname=self.nickname_input.text(),
password=self.password_input.text(), password=self.password_input.text(),
remember=self.remember_checkbox.checkState()) remember=self.remember_checkbox.checkState())
@@ -105,8 +104,8 @@ class ConnectionDialog(QDialog, Ui_ConnectionDialog):
def validate_address(self) -> Tuple[bool, bool]: def validate_address(self) -> Tuple[bool, bool]:
"""Returns True if the server address and port combination is valid""" """Returns True if the server address and port combination is valid"""
address = self.server_address_input.text() or constants.DEFAULT_IP address = self.server_address_input.text() or DEFAULT_IP
port = self.port_input.text() or str(constants.DEFAULT_PORT) port = self.port_input.text() or str(DEFAULT_PORT)
valid_address = len(address) > 0 and re.match(r'^\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}|localhost$', valid_address = len(address) > 0 and re.match(r'^\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}|localhost$',
address) is not None address) is not None

View File

@@ -6,8 +6,8 @@ from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtWidgets import QMainWindow, QLabel from PyQt5.QtWidgets import QMainWindow, QLabel
from sortedcontainers import SortedList from sortedcontainers import SortedList
import constants from shared import constants
import helpers from shared import helpers
from client.ui.MainWindow import Ui_MainWindow from client.ui.MainWindow import Ui_MainWindow
from client.worker import ReceiveWorker from client.worker import ReceiveWorker
@@ -65,7 +65,7 @@ class MainWindow(QMainWindow, Ui_MainWindow):
else: else:
self.received += change self.received += change
self.data_stats.setText(f'{helpers.sizeof_fmt(self.sent)} Sent, ' self.data_stats.setText(f'{helpers.sizeof_fmt(self.sent)} Sent, '
f'{helpers.sizeof_fmt(self. received)} Received') f'{helpers.sizeof_fmt(self.received)} Received')
@staticmethod @staticmethod
def log(log_data: dict) -> None: def log(log_data: dict) -> None:
@@ -96,7 +96,7 @@ class MainWindow(QMainWindow, Ui_MainWindow):
at_maximum = last_position == scrollbar.maximum() at_maximum = last_position == scrollbar.maximum()
self.messageHistory.setText('<br>'.join( self.messageHistory.setText('<br>'.join(
msg['compiled'] for msg in self.messages msg['compiled'] for msg in self.messages
)) ))
scrollbar.setValue(scrollbar.maximum() if at_maximum else last_position) scrollbar.setValue(scrollbar.maximum() if at_maximum else last_position)
@@ -126,10 +126,10 @@ class MainWindow(QMainWindow, Ui_MainWindow):
message = message.strip() message = message.strip()
if len(message) > 0: if len(message) > 0:
self.send(helpers.prepare_json( self.send(helpers.prepare_json(
{ {
'type': constants.Types.MESSAGE, 'type': constants.Types.MESSAGE,
'content': message 'content': message
} }
)) ))
def update_connections(self, users: List[dict]): def update_connections(self, users: List[dict]):

View File

@@ -4,8 +4,8 @@ import socket
from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtCore import QThread, pyqtSignal
import constants from shared import constants
import helpers from shared import helpers
class ReceiveWorker(QThread): class ReceiveWorker(QThread):

View File

@@ -5,7 +5,7 @@ import random
from typing import List, Optional, Callable from typing import List, Optional, Callable
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import constants from shared import constants
if TYPE_CHECKING: if TYPE_CHECKING:
from server.handler import Client from server.handler import Client

View File

@@ -5,7 +5,7 @@ import sqlite3
import threading import threading
from typing import List, Optional, Union from typing import List, Optional, Union
import constants from shared import constants
logger = logging.getLogger('database') logger = logging.getLogger('database')
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)

View File

@@ -7,10 +7,10 @@ import uuid
from json import JSONDecodeError from json import JSONDecodeError
from typing import Any, List, Optional from typing import Any, List, Optional
import constants from shared import constants
import helpers from shared import helpers
# noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences
from exceptions import DataReceptionException from shared.exceptions import DataReceptionException
from server import db from server import db
from server.commands import CommandHandler from server.commands import CommandHandler

View File

@@ -1,8 +1,9 @@
import logging import logging
import socket import socket
import sys
import threading import threading
import constants from shared import constants
from server import handler from server import handler
host = constants.DEFAULT_IP host = constants.DEFAULT_IP
@@ -10,7 +11,7 @@ port = constants.DEFAULT_PORT
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port)) server.bind((host, port))
server.listen() server.listen(1)
logger = logging.getLogger('server') logger = logging.getLogger('server')
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
@@ -21,8 +22,11 @@ clients = []
# Receiving / Listening Function # Receiving / Listening Function
def receive(): def receive():
while True: while True:
conn = None
try: try:
# Accept Connection # Accept Connection
logger.debug('Waiting for connections...')
conn, address = server.accept() conn, address = server.accept()
logger.info(f"New connection from {address}") logger.info(f"New connection from {address}")
@@ -39,8 +43,12 @@ def receive():
thread.start() thread.start()
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info('Server closed by user.') logger.info('Server closed by user.')
if conn:
conn.close()
break
except Exception as e: except Exception as e:
logger.critical(e, exc_info=e) logger.critical(e, exc_info=e)
break
if __name__ == '__main__': if __name__ == '__main__':

View File

View File

View File

@@ -3,7 +3,7 @@ import json
import time import time
from typing import List, Tuple, Any from typing import List, Tuple, Any
import constants from shared import constants
HEADER_LENGTH = 10 HEADER_LENGTH = 10