messages.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from abc import abstractmethod
  2. import json
  3. from typing import Dict, Type
  4. class Message:
  5. MESSAGE_TYPES: Dict[str, Type['Message']] = {}
  6. @classmethod
  7. @abstractmethod
  8. def from_hash(cls: Type['Message'], d: Dict): pass
  9. @abstractmethod
  10. def to_hash(self) -> Dict: pass
  11. @classmethod
  12. def decode(cls: Type['Message'], raw: str):
  13. hash = json.loads(raw)
  14. tag = hash['tag']
  15. return cls.MESSAGE_TYPES[tag].from_hash(hash)
  16. def json(self) -> str:
  17. hash = self.to_hash()
  18. return json.dumps(self.to_hash())
  19. def message(name: str):
  20. def decorate(class_decl: Type['Message']) -> Type['Message']:
  21. Message.MESSAGE_TYPES[name] = class_decl
  22. return class_decl
  23. return decorate
  24. @message('config')
  25. class InitialConfig(Message):
  26. user: str
  27. game: str
  28. def __init__(self, user: str, game: str):
  29. self.user = user
  30. self.game = game
  31. @classmethod
  32. def from_hash(cls, d: Dict):
  33. return cls(user=d['user'], game=d['game'])
  34. def to_hash(self) -> Dict:
  35. return {'user': self.user, 'game': self.game}
  36. @message('post')
  37. class Post(Message):
  38. author: str
  39. content: str
  40. def __init__(self, author: str, content: str):
  41. self.author = author
  42. self.content = content
  43. @classmethod
  44. def from_hash(cls, d: Dict):
  45. return cls(author=d['author'], content=d['content'])
  46. def to_hash(self) -> Dict:
  47. return {
  48. 'tag': 'post',
  49. 'author': self.author,
  50. 'content': self.content,
  51. }