-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
146 lines (111 loc) · 4.86 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import datetime
import grpc
import time
from concurrent import futures
import service.chat_pb2 as chat_pb2
import service.chat_pb2_grpc as chat_pb2_grpc
class ChatServiceServicer(chat_pb2_grpc.ChatServiceServicer):
def __init__(self):
self.clients = set()
self.messages = []
self.allow_users = [
{"user_id": "00", "like_count": 0, "like_from": [], "is_allow": True}]
self.max_user_id = 0
def Log(self, content):
with open("logfile.log", "a") as f:
f.write(content + '\n')
print(content)
def GenerateUserId(self):
new_id = str(self.max_user_id + 1)
# Add a leading zero to the user ID if it is less than 10
if len(new_id) < 2:
new_id = '0' + new_id
self.max_user_id += 1
return new_id
def CreateNewUser(self, request, context):
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%H:%M:%S")
# generate new user id
new_id = self.GenerateUserId()
request.id = new_id
new_user = {"user_id": new_id, 'like_count': 0,
'like_from': [], 'is_allow': True}
# Add the user to the list of allowed users
self.allow_users.append(new_user)
log = "["+formatted_time+"] " + request.name + \
" join group chat" + " - ID(" + new_id + ")"
self.Log(log)
return request
def IsLikeMessage(self, msg):
msg_components = msg.split('_')
if len(msg_components) == 2 and msg_components[0] == 'LIKE' and msg_components[1].isdigit():
return True
return False
def HandleLikeMessage(self, time, msg, from_user):
msg_components = msg.split('_')
user_id = msg_components[1]
log = "[" + time + "] User[" + from_user + \
"] like for User[" + user_id + "]"
self.Log(log)
if user_id == from_user:
error_msg = "[WARNING] You can not LIKE yourself!"
from_user = "_" + from_user
raise grpc.RpcError(error_msg + from_user)
if from_user in self.allow_users[int(user_id)]["like_from"]:
error_msg = "[WARNING] You only LIKED: [" + \
user_id + "]'s message ONCE!"
from_user = "_" + from_user
raise grpc.RpcError(error_msg + from_user)
for user in self.allow_users:
if user_id == user['user_id']:
self.allow_users[int(user_id)]['like_count'] += 1
self.allow_users[int(user_id)]['like_from'].append(from_user)
if self.allow_users[int(user_id)]['like_count'] >= 2:
self.allow_users[int(user_id)]['is_allow'] = True
log = "[" + time + "] User[" + user_id + \
"] is ALLOWED to send message"
error_msg = "[INFO] You LIKED: ["+user_id + "]'s message"
from_user = "_" + from_user
raise grpc.RpcError(error_msg + from_user)
def SendMessage(self, request, context):
if self.IsLikeMessage(request.msg):
# if LIKE msg, still allow this user send msg
self.HandleLikeMessage(request.time, request.msg, request.user.id)
else:
# if user is allowed to send message
if self.allow_users[int(request.user.id)]['is_allow']:
log = "[" + request.time + "] User[" + \
request.user.id + "] send message '" + request.msg + "'"
self.Log(log)
log = "[" + request.time + "] User[" + \
request.user.id + "] is BLOCKED to send message"
self.Log(log)
# add message
self.messages.append(request)
# reset user state
self.allow_users[int(request.user.id)]['like_count'] = 0
self.allow_users[int(request.user.id)]['like_from'] = []
self.allow_users[int(request.user.id)]['is_allow'] = False
else:
log = "[" + request.time + "] User[" + request.user.id + \
"] is not allow to send message"
self.Log(log)
error_msg = "[WARNING] You are NOT allowed to send message"
from_user = "_" + request.user.id
raise grpc.RpcError(error_msg+from_user)
return request
def ReceiveMessage(self, request, context):
# while True:
for message in self.messages:
yield message
# TODO: log file theem "Block send message", "Allow to send message"
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
chat_pb2_grpc.add_ChatServiceServicer_to_server(
ChatServiceServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()
print("Server started")
server.wait_for_termination()
if __name__ == '__main__':
serve()