online_chat.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from abc import ABCMeta
  2. class UserService(object):
  3. __metaclass__ = Singleton
  4. def __init__(self):
  5. self.users_by_id = {} # key: user id, value: User
  6. def add_user(self, user_id, name, pass_hash): # ...
  7. def remove_user(self, user_id): # ...
  8. def add_friend_request(self, from_user_id, to_user_id): # ...
  9. def approve_friend_request(self, from_user_id, to_user_id): # ...
  10. def reject_friend_request(self, from_user_id, to_user_id): # ...
  11. class User(object):
  12. def __init__(self, user_id, name, pass_hash):
  13. self.user_id = user_id
  14. self.name = name
  15. self.pass_hash = pass_hash
  16. self.friends_by_id = {} # key: friend id, value: User
  17. self.friend_ids_to_private_chats = {} # key: friend id, value: private chats
  18. self.group_chats_by_id = {} # key: chat id, value: GroupChat
  19. self.received_friend_requests_by_friend_id = {} # key: friend id, value: AddRequest
  20. self.sent_friend_requests_by_friend_id = {} # key: friend id, value: AddRequest
  21. def message_user(self, friend_id, message): # ...
  22. def message_group(self, group_id, message): # ...
  23. def send_friend_request(self, friend_id): # ...
  24. def receive_friend_request(self, friend_id): # ...
  25. def approve_friend_request(self, friend_id): # ...
  26. def reject_friend_request(self, friend_id): # ...
  27. class Chat(metaclass=ABCMeta):
  28. def __init__(self, chat_id):
  29. self.users = []
  30. self.chat_id = chat_id
  31. self.messages = []
  32. class PrivateChat(Chat):
  33. def __init__(self, first_user, second_user):
  34. super(PrivateChat, self).__init__()
  35. self.users.append(first_user)
  36. self.users.append(second_user)
  37. class GroupChat(Chat):
  38. def add_user(self, user): # ...
  39. def remove_user(self, user): # ...
  40. class Message(object):
  41. def __init__(self, message_id, message, timestamp):
  42. self.message_id = message_id
  43. self.message = message
  44. self.timestamp = timestamp
  45. class AddRequest(object):
  46. def __init__(self, from_user_id, to_user_id, request_status, timestamp):
  47. self.from_user_id = from_user_id
  48. self.to_user_id = to_user_id
  49. self.request_status = request_status
  50. self.timestamp = timestamp
  51. class RequestStatus(Enum):
  52. UNREAD = 0
  53. READ = 1
  54. ACCEPTED = 2
  55. REJECTED = 3
  56. class Singleton(type):
  57. _instances = {}
  58. def __call__(cls, *args, **kwargs):
  59. if cls not in cls._instances:
  60. cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
  61. return cls._instances[cls]