-
Notifications
You must be signed in to change notification settings - Fork 0
/
150120016_mbs.py
215 lines (163 loc) · 5.91 KB
/
150120016_mbs.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# Bugra Ekuklu, 150120016
import socket
from os import environ
import sys
debug = environ.get('DEBUG')
host = environ.get('MBS_ADDRESS') or '127.0.0.1'
port = int(environ.get('MBS_PORT') or 5000)
endpoint = (host, port)
def debug_print(*args, **kwargs):
if debug:
print(*args, **kwargs)
def err_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse_req(req):
return req.split(':')
def check_req_len(req, expected_len):
if len(req) != expected_len:
raise NetworkError('unexpected request length')
class NetworkError(RuntimeError):
def __init__(self, arg):
self.args = [arg]
class RegistrationError(RuntimeError):
def __init__(self, arg, username):
self.args = [arg, username]
class User:
def __init__(self, username, password):
self.username = username
self.password = password
class Board:
def __init__(self, name):
self.name = name
self.messages = []
class Message:
def __init__(self, body, sender):
self.body = body
self.sender = sender
class BoardAlreadyAddedError(RuntimeError):
def __init__(self, arg, board_name):
self.args = [arg, board_name]
class BoardNotFoundError(RuntimeError):
def __init__(self, arg, board_name):
self.args = [arg, board_name]
class Service:
def __init__(self):
self._users = {}
self.boards = {}
def register(self, user):
fetched_user = self._users.get(user.username)
if fetched_user is not None:
if fetched_user.password == user.password:
debug_print('user registered to the service: %s:%s' % (user.username, user.password))
print('Successful user registration: %s' % (user.username))
return
else:
debug_print('wrong password: %s:%s' % (user.username, user.password))
print('Rejected user registration: %s' % (user.username))
raise RegistrationError('user already exists', user)
self._users[user.username] = user
debug_print('user registered to the service: %s:%s' % (user.username, user.password))
print('Successful user registration: %s' % (user.username))
def add_board(self, board):
fetched_board = self.boards.get(board.name)
if fetched_board is not None:
raise BoardAlreadyAddedError('board already added', board.name)
self.boards[board.name] = board
print('%s Message Board Was Created!' % (board.name))
debug_print('board registered to the service: %s' % (board.name))
class Application:
def __init__(self):
self.service = Service()
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(endpoint)
print('MBS Started')
debug_print(f'Listening %s on port %d' % (host, port))
self.listen()
def listen(self):
while True:
data, address = self.sock.recvfrom(4096)
req = data.decode()
debug_print('request: received %s bytes from %s: %s' % (len(data), address, req))
resp = self.on_message(req)
if resp is None:
debug_print(f'call not handled: {req}')
resp = 'NAK'
if isinstance(resp, list):
for each_packet in resp:
self.sock.sendto(each_packet.encode(), address)
debug_print('response: %s' % (each_packet))
else:
self.sock.sendto(resp.encode(), address)
debug_print('response: %s' % (resp))
def on_message(self, message):
req = parse_req(message)
try:
if req[0] == 'REG':
check_req_len(req, 3)
user = User(req[1], req[2])
print(f'Registration request arrived from user {user.username}')
self.service.register(user)
return f'ACCEPT:{user.username}'
elif req[0] == 'CREATE':
check_req_len(req, 2)
board = Board(req[1])
self.service.add_board(board)
return f'ACCEPT:{board.name}'
elif req[0] == 'LIST' and req[1] == 'BOARDS':
check_req_len(req, 2)
if len(self.service.boards) == 0:
return 'LIST:BOARDS:'
else:
resp = ['LIST', 'BOARDS']
for each_board in self.service.boards:
resp.append(each_board)
return ':'.join(resp)
elif req[0] == 'ADD':
check_req_len(req, 5)
try:
user = User(req[1], req[2])
self.service.register(user)
board = self.service.boards.get(req[3])
if board is None:
return f'REJECT:{req[1]}::{req[4]}'
else:
msg = Message(req[4], user)
board.messages.append(msg)
print('%s added the message "%s" on %s Message Board!' % (user.username, msg.body, board.name))
return f'ACCEPT:{req[1]}:{req[3]}:{req[4]}'
except RegistrationError as e:
if self.service.boards.get(req[3]) is None:
return f'REJECT:::{req[4]}'
else:
return f'REJECT::{req[3]}:{req[4]}'
elif req[0] == 'LIST' and req[1] == 'MESSAGES':
packets = []
try:
user = User(req[2], req[3])
self.service.register(user)
board = self.service.boards.get(req[4])
if board is None:
return f'REJECT:{req[2]}::It is HW1 of BLG433E'
else:
i = 1
for each_message in board.messages:
packets.append(f'MESSAGE:{req[4]}:{each_message.sender.username}:{i}:{each_message.body}')
i += 1
packets.append(f'MESSAGE:{req[4]}:{req[2]}:-1')
return packets
except RegistrationError as e:
if self.service.boards.get(req[4]) is None:
return f'REJECT:::It is HW1 of BLG433E'
else:
return f'REJECT::{req[4]}:It is HW1 of BLG433E'
except RegistrationError as e:
return f'REJECT:{e.args[1].username}'
except BoardAlreadyAddedError as e:
print('%s Message Board Couldn\'t Be Created!' % (e.args[1]))
return f'REJECT:{e.args[1]}'
except NetworkError as e:
return None
if __name__ == '__main__':
app = Application()
app.run()