projet-reseau-1/shared/server/message.py

55 lines
1.3 KiB
Python

import logging
import re
from enum import Enum
from typing import Union, Tuple, AnyStr, Any
regex_command = r"^(?:(END|\.)|(?:(NAME|TIME|MORE) (\w+))|(?:(.+)\n))\r\n$"
class UniCommand(Enum):
END = 1
POINT = 2
@staticmethod
def from_str(command: str) -> 'UniCommand':
if command == "END":
return UniCommand.END
elif command == ".":
return UniCommand.POINT
else:
# TODO
pass
class BiCommand(Enum):
NAME = 1
TIME = 2
MORE = 3
@staticmethod
def from_str(command: str) -> 'BiCommand':
if command == "NAME":
return BiCommand.NAME
elif command == "TIME":
return BiCommand.TIME
elif command == "MORE":
return BiCommand.MORE
else:
# TODO
pass
def parse_message(message: str) -> Union[UniCommand, Tuple[BiCommand, str], Tuple[str, str]]:
matches = re.match(regex_command, message)
if matches:
groups: tuple[AnyStr | Any, ...] = matches.groups()
if groups[0] is not None:
return UniCommand.from_str(groups[0])
elif groups[1] is not None and groups[2] is not None:
return BiCommand.from_str(groups[1]), groups[2]
elif groups[3] is not None:
return groups[3]
# TODO Exception
pass