Completed
Push — master ( 41cb1b...8205ad )
by Andrew
30s
created

MessagesHandler.publish_call_answer()   A

Complexity

Conditions 3

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
1
import json
2
import logging
3
4
from django.core.exceptions import ValidationError
5
from django.db import IntegrityError
6
from django.db.models import Q
7
from tornado.gen import engine, Task
8
from tornadoredis import Client
9
10
from chat.log_filters import id_generator
11
from chat.models import Message, Room, get_milliseconds, RoomUsers
12
from chat.py2_3 import str_type
13
from chat.settings import ALL_ROOM_ID, SELECT_SELF_ROOM, \
14
	TORNADO_REDIS_PORT, WEBRTC_CONNECTION
15
from chat.tornado.constants import VarNames, HandlerNames, Actions, RedisPrefix, WebRtcRedisStates
16
from chat.tornado.image_utils import process_images, prepare_img, save_images, get_message_images
17
from chat.tornado.message_creator import WebRtcMessageCreator
18
from chat.utils import get_max_key, execute_query, do_db, update_room
19
20
parent_logger = logging.getLogger(__name__)
21
base_logger = logging.LoggerAdapter(parent_logger, {
22
	'id': 0,
23
	'ip': '000.000.000.000'
24
})
25
26
# TODO https://github.com/leporo/tornado-redis#connection-pool-support
27
# CONNECTION_POOL = tornadoredis.ConnectionPool(
28
# max_connections=500,
29
# wait_for_available=True)
30
31
32
class MessagesHandler(WebRtcMessageCreator):
33
34
	def __init__(self, *args, **kwargs):
35
		self.closed_channels = None
36
		self.parsable_prefix = 'p'
37
		super(MessagesHandler, self).__init__(*args, **kwargs)
38
		self.webrtc_ids = {}
39
		self.ip = None
40
		from chat import global_redis
41
		self.async_redis_publisher = global_redis.async_redis_publisher
42
		self.sync_redis = global_redis.sync_redis
43
		self.channels = []
44
		self._logger = None
45
		self.async_redis = Client(port=TORNADO_REDIS_PORT)
46
		self.patch_tornadoredis()
47
		self.pre_process_message = {
48
			Actions.GET_MESSAGES: self.process_get_messages,
49
			Actions.SEND_MESSAGE: self.process_send_message,
50
			Actions.WEBRTC: self.proxy_webrtc,
51
			Actions.CLOSE_FILE_CONNECTION: self.close_file_connection,
52
			Actions.CLOSE_CALL_CONNECTION: self.close_call_connection,
53
			Actions.CANCEL_CALL_CONNECTION: self.cancel_call_connection,
54
			Actions.ACCEPT_CALL: self.accept_call,
55
			Actions.ACCEPT_FILE: self.accept_file,
56
			Actions.CREATE_DIRECT_CHANNEL: self.create_user_channel,
57
			Actions.DELETE_ROOM: self.delete_channel,
58
			Actions.EDIT_MESSAGE: self.edit_message,
59
			Actions.CREATE_ROOM_CHANNEL: self.create_new_room,
60
			Actions.INVITE_USER: self.invite_user,
61
			Actions.OFFER_FILE_CONNECTION: self.offer_webrtc_connection,
62
			Actions.OFFER_CALL_CONNECTION: self.offer_webrtc_connection,
63
			Actions.REPLY_FILE_CONNECTION: self.reply_file_connection,
64
			Actions.REPLY_CALL_CONNECTION: self.reply_call_connection,
65
		}
66
		self.post_process_message = {
67
			Actions.CREATE_DIRECT_CHANNEL: self.send_client_new_channel,
68
			Actions.CREATE_ROOM_CHANNEL: self.send_client_new_channel,
69
			Actions.DELETE_ROOM: self.send_client_delete_channel,
70
			Actions.INVITE_USER: self.send_client_new_channel,
71
			Actions.OFFER_FILE_CONNECTION: self.set_opponent_call_channel,
72
			Actions.OFFER_CALL_CONNECTION: self.set_opponent_call_channel
73
		}
74
75
	def patch_tornadoredis(self):  # TODO remove this
76
		fabric = type(self.async_redis.connection.readline)
77
		self.async_redis.connection.old_read = self.async_redis.connection.readline
78
79
		def new_read(new_self, callback=None):
80
			try:
81
				return new_self.old_read(callback=callback)
82
			except Exception as e:
83
				current_online = self.get_online_from_redis(RedisPrefix.DEFAULT_CHANNEL)
84
				self.logger.error(e)
85
				self.logger.error(
86
					"Exception info: "
87
					"self.id: %s ;;; "
88
					"self.connected = '%s';;; "
89
					"Redis default channel online = '%s';;; "
90
					"self.channels = '%s';;; "
91
					"self.closed_channels  = '%s';;;",
92
					self.id, self.connected, current_online, self.channels, self.closed_channels
93
				)
94
				raise e
95
96
		self.async_redis.connection.readline = fabric(new_read, self.async_redis.connection)
97
98
	@property
99
	def connected(self):
100
		raise NotImplemented
101
102
	@connected.setter
103
	def connected(self, value):
104
		raise NotImplemented
105
106
	@engine
107
	def listen(self, channels):
108
		yield Task(
109
			self.async_redis.subscribe, channels)
110
		self.async_redis.listen(self.pub_sub_message)
111
112
	@property
113
	def logger(self):
114
		return self._logger if self._logger else base_logger
115
116
	@engine
117
	def add_channel(self, channel):
118
		self.channels.append(channel)
119
		yield Task(
120
			self.async_redis.subscribe, (channel,))
121
122
	@staticmethod
123
	def evaluate(query_set):
124
		do_db(len, query_set)
125
		return query_set
126
127
	def get_online_from_redis(self, channel, check_self_online=False):
128
		"""
129
		:rtype : dict
130
		returns (dict, bool) if check_type is present
131
		"""
132
		online = self.sync_redis.smembers(channel)
133
		self.logger.debug('!! channel %s redis online: %s', channel, online)
134
		result = set()
135
		user_is_online = False
136
		# redis stores8 REDIS_USER_FORMAT, so parse them
137
		if online:
138
			for raw in online:  # py2 iteritems
139
				decoded = raw.decode('utf-8')
140
				# : char specified in cookies_middleware.py.create_id
141
				user_id = int(decoded.split(':')[0])
142
				if user_id == self.user_id and decoded != self.id:
143
					user_is_online = True
144
				result.add(user_id)
145
		result = list(result)
146
		return (result, user_is_online) if check_self_online else result
147
148
	def add_online_user(self, room_id, offline_messages=None):
149
		"""
150
		adds to redis
151
		online_users = { connection_hash1 = stored_redis_user1, connection_hash_2 = stored_redis_user2 }
152
		:return:
153
		"""
154
		self.async_redis_publisher.sadd(room_id, self.id)
155
		# since we add user to online first, latest trigger will always show correct online
156
		online, is_online = self.get_online_from_redis(room_id, True)
157
		if not is_online:  # if a new tab has been opened
158
			online.append(self.user_id)
159
			online_user_names_mes = self.room_online(
160
				online,
161
				Actions.LOGIN,
162
				room_id
163
			)
164
			self.logger.info('!! First tab, sending refresh online for all')
165
			self.publish(online_user_names_mes, room_id)
166
			if offline_messages:
167
				self.ws_write(self.load_offline_message(offline_messages, room_id))
168
		else:  # Send user names to self
169
			online_user_names_mes = self.room_online(
170
				online,
171
				Actions.REFRESH_USER,
172
				room_id
173
			)
174
			self.logger.info('!! Second tab, retrieving online for self')
175
			self.ws_write(online_user_names_mes)
176
177
	def publish(self, message, channel, parsable=False):
178
		jsoned_mess = json.dumps(message)
179
		self.logger.debug('<%s> %s', channel, jsoned_mess)
180
		if parsable:
181
			jsoned_mess = self.encode(jsoned_mess)
182
		self.async_redis_publisher.publish(channel, jsoned_mess)
183
184
	def encode(self, message):
185
		"""
186
		Marks message with prefix to specify that
187
		it should be decoded and proccesed before sending to client
188
		@param message: message to mark
189
		@return: marked message
190
		"""
191
		return self.parsable_prefix + message
192
193
	def remove_parsable_prefix(self, message):
194
		if message.startswith(self.parsable_prefix):
195
			return message[1:]
196
197
	def pub_sub_message(self, message):
198
		data = message.body
199
		if isinstance(data, str_type):  # subscribe event
200
			prefixless_str = self.remove_parsable_prefix(data)
201
			if prefixless_str:
202
				dict_message = json.loads(prefixless_str)
203
				res = self.post_process_message[dict_message[VarNames.EVENT]](dict_message)
204
				if not res:
205
					self.ws_write(prefixless_str)
206
			else:
207
				self.ws_write(data)
208
209
	def ws_write(self, message):
210
		raise NotImplementedError('WebSocketHandler implements')
211
212
	def process_send_message(self, message):
213
		"""
214
		:type message: dict
215
		"""
216
		raw_imgs = message.get(VarNames.IMG)
217
		channel = message[VarNames.CHANNEL]
218
		message_db = Message(
219
			sender_id=self.user_id,
220
			content=message[VarNames.CONTENT],
221
			symbol=get_max_key(raw_imgs)
222
		)
223
		message_db.room_id = channel
224
		do_db(message_db.save)
225
		db_images = save_images(raw_imgs, message_db.id)
226
		prepared_message = self.create_send_message(
227
			message_db,
228
			Actions.PRINT_MESSAGE,
229
			prepare_img(db_images, message_db.id)
230
		)
231
		self.publish(prepared_message, channel)
232
233
	def close_file_connection(self, in_message):
234
		connection_id = in_message[VarNames.CONNECTION_ID]
235
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
236
		if not self_channel_status:
237
			raise Exception("Access Denied")
238
		if self_channel_status != WebRtcRedisStates.CLOSED:
239
			sender_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
240
			if sender_id == self.id:
241
				self.close_file_sender(connection_id)
242
			else:
243
				self.close_file_receiver(connection_id, in_message, sender_id)
244
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.CLOSED)
245
246
	def close_call_connection(self, in_message):
247
		self.send_call_answer(
248
			in_message,
249
			WebRtcRedisStates.CLOSED,
250
			Actions.CLOSE_CALL_CONNECTION,
251
			[WebRtcRedisStates.READY, WebRtcRedisStates.RESPONDED],
252
			HandlerNames.PEER_CONNECTION
253
		)
254
255
	def cancel_call_connection(self, in_message):
256
		self.send_call_answer(
257
			in_message,
258
			WebRtcRedisStates.CLOSED,
259
			Actions.CANCEL_CALL_CONNECTION,
260
			[WebRtcRedisStates.OFFERED],
261
			HandlerNames.WEBRTC_TRANSFER
262
		)
263
264
	def close_file_receiver(self, connection_id, in_message, sender_id):
265
		sender_status = self.sync_redis.shget(connection_id, sender_id)
266
		if not sender_status:
267
			raise Exception("Access denied")
268
		if sender_status != WebRtcRedisStates.CLOSED:
269
			in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
270
			in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
271
			self.publish(in_message, sender_id)
272
273
	def close_file_sender(self, connection_id):
274
		values = self.sync_redis.shgetall(connection_id)
275
		del values[self.id]
276
		message = self.get_close_file_sender_message(connection_id)
277
		for ws_id in values:
278
			if values[ws_id] == WebRtcRedisStates.CLOSED:
279
				continue
280
			self.publish(message, ws_id)
281
282
	def accept_file(self, in_message):
283
		connection_id = in_message[VarNames.CONNECTION_ID]
284
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
285
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
286
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
287
		if sender_ws_status == WebRtcRedisStates.READY and self_ws_status == WebRtcRedisStates.RESPONDED:
288
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
289
			self.publish(self.get_accept_file_message(connection_id), sender_ws_id)
290
		else:
291
			raise ValidationError("Invalid channel status")
292
293
	# todo
294
	# we can use channel_status = self.sync_redis.shgetall(connection_id)
295
	# and then self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
296
	# if we shgetall and only then do async hset
297
	# we can catch an issue when 2 concurrent users accepted the call
298
	# but we didn't  send them ACCEPT_CALL as they both were in status 'offered'
299
	def accept_call(self, in_message):
300
		connection_id = in_message[VarNames.CONNECTION_ID]
301
		self_status = self.sync_redis.shget(connection_id, self.id)
302
		if self_status == WebRtcRedisStates.RESPONDED:
303
			conn_users = self.sync_redis.shgetall(connection_id)
304
			self.publish_call_answer(
305
				conn_users,
306
				connection_id,
307
				HandlerNames.WEBRTC_TRANSFER,
308
				Actions.ACCEPT_CALL,
309
				WebRtcRedisStates.READY
310
			)
311
		else:
312
			raise ValidationError("Invalid channel status")
313
314
	def offer_webrtc_connection(self, in_message):
315
		room_id = in_message[VarNames.CHANNEL]
316
		content = in_message.get(VarNames.CONTENT)
317
		qued_id = in_message[VarNames.WEBRTC_QUED_ID]
318
		connection_id = id_generator(RedisPrefix.CONNECTION_ID_LENGTH)
319
		# use list because sets dont have 1st element which is offerer
320
		self.async_redis_publisher.hset(WEBRTC_CONNECTION, connection_id, self.id)
321
		self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
322
		opponents_message = self.offer_webrtc(content, connection_id, room_id, in_message[VarNames.EVENT])
323
		self_message = self.set_connection_id(qued_id, connection_id)
324
		self.ws_write(self_message)
325
		self.logger.info('!! Offering a webrtc, connection_id %s', connection_id)
326
		self.publish(opponents_message, room_id, True)
327
328
	def reply_call_connection(self, in_message):
329
		self.send_call_answer(
330
			in_message,
331
			WebRtcRedisStates.RESPONDED,
332
			Actions.REPLY_CALL_CONNECTION,
333
			[WebRtcRedisStates.OFFERED],
334
			HandlerNames.WEBRTC_TRANSFER
335
		)
336
337
	def send_call_answer(self, in_message, status_set, reply_action, allowed_state, message_handler):
338
		connection_id = in_message[VarNames.CONNECTION_ID]
339
		conn_users = self.sync_redis.shgetall(connection_id)
340
		if conn_users[self.id] in allowed_state:
341
			self.publish_call_answer(conn_users, connection_id, message_handler, reply_action, status_set)
342
		else:
343
			raise ValidationError("Invalid channel status.")
344
345
	def publish_call_answer(self, conn_users, connection_id, message_handler, reply_action, status_set):
346
		self.async_redis_publisher.hset(connection_id, self.id, status_set)
347
		del conn_users[self.id]
348
		message = self.reply_webrtc(reply_action, connection_id, message_handler)
349
		for user in conn_users:
350
			if conn_users[user] != WebRtcRedisStates.CLOSED:
351
				self.publish(message, user)
352
353
	def reply_file_connection(self, in_message):
354
		connection_id = in_message[VarNames.CONNECTION_ID]
355
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
356
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
357
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
358
		if sender_ws_status == WebRtcRedisStates.READY and self_ws_status == WebRtcRedisStates.OFFERED:
359
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.RESPONDED)
360
			self.publish(self.reply_webrtc(
361
				Actions.REPLY_FILE_CONNECTION,
362
				connection_id,
363
				HandlerNames.WEBRTC_TRANSFER
364
			), sender_ws_id)
365
		else:
366
			raise ValidationError("Invalid channel status.")
367
368
	def proxy_webrtc(self, in_message):
369
		"""
370
		:type in_message: dict
371
		"""
372
		connection_id = in_message[VarNames.CONNECTION_ID]
373
		channel = in_message.get(VarNames.WEBRTC_OPPONENT_ID)
374
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
375
		opponent_channel_status = self.sync_redis.shget(connection_id, channel)
376
		if not (self_channel_status == WebRtcRedisStates.READY and opponent_channel_status == WebRtcRedisStates.READY):
377
			raise ValidationError('Error in connection status, your status is {} while opponent is {}'.format(
378
				self_channel_status, opponent_channel_status
379
			))  # todo receiver should only accept proxy_webrtc from sender, sender can accept all
380
		# I mean somebody if there're 3 ppl in 1 channel and first is initing transfer to 2nd and 3rd,
381
		# 2nd guy can fraud 3rd guy webrtc traffic, which is allowed during the call, but not while transering file
382
		in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
383
		in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
384
		self.logger.debug(
385
			"Forwarding message to channel %s, self %s, other status %s",
386
			channel,
387
			self_channel_status,
388
			opponent_channel_status
389
		)
390
		self.publish(in_message, channel)
391
392
	def create_new_room(self, message):
393
		room_name = message[VarNames.ROOM_NAME]
394
		if not room_name or len(room_name) > 16:
395
			raise ValidationError('Incorrect room name "{}"'.format(room_name))
396
		room = Room(name=room_name)
397
		do_db(room.save)
398
		RoomUsers(room_id=room.id, user_id=self.user_id).save()
399
		subscribe_message = self.subscribe_room_channel_message(room.id, room_name)
400
		self.publish(subscribe_message, self.channel, True)
401
402
	def invite_user(self, message):
403
		room_id = message[VarNames.ROOM_ID]
404
		user_id = message[VarNames.USER_ID]
405
		if room_id not in self.channels:
406
			raise ValidationError("Access denied, only allowed for channels {}".format(self.channels))
407
		room = do_db(Room.objects.get, id=room_id)
408
		if room.is_private:
409
			raise ValidationError("You can't add users to direct room, create a new room instead")
410
		try:
411
			Room.users.through.objects.create(room_id=room_id, user_id=user_id)
412
		except IntegrityError:
413
			raise ValidationError("User is already in channel")
414
		users_in_room = {}
415
		for user in room.users.all():
416
			RedisPrefix.set_js_user_structure(users_in_room, user.id, user.username, user.sex)
417
		self.publish(self.add_user_to_room(room_id, user_id, users_in_room[user_id]), room_id)
418
		subscribe_message = self.invite_room_channel_message(room_id, user_id, room.name, users_in_room)
419
		self.publish(subscribe_message, RedisPrefix.generate_user(user_id), True)
420
421
	def create_room(self, user_rooms, user_id):
422
		if self.user_id == user_id:
423
			room_ids = list([room['room_id'] for room in self.evaluate(user_rooms)])
424
			query_res = execute_query(SELECT_SELF_ROOM, [room_ids, ])
425
		else:
426
			rooms_query = RoomUsers.objects.filter(user_id=user_id, room__in=user_rooms)
427
			query_res = rooms_query.values('room__id', 'room__disabled')
428
		try:
429
			room = do_db(query_res.get)
430
			room_id = room['room__id']
431
			update_room(room_id, room['room__disabled'])
432
		except RoomUsers.DoesNotExist:
433
			room = Room()
434
			room.save()
435
			room_id = room.id
436
			if self.user_id == user_id:
437
				RoomUsers(user_id=self.user_id, room_id=room_id).save()
438
			else:
439
				RoomUsers.objects.bulk_create([
440
					RoomUsers(user_id=user_id, room_id=room_id),
441
					RoomUsers(user_id=self.user_id, room_id=room_id),
442
				])
443
		return room_id
444
445
	def create_user_channel(self, message):
446
		user_id = message[VarNames.USER_ID]
447
		# get all self private rooms ids
448
		user_rooms = Room.users.through.objects.filter(user_id=self.user_id, room__name__isnull=True).values('room_id')
449
		# get private room that contains another user from rooms above
450
		room_id = self.create_room(user_rooms, user_id)
451
		subscribe_message = self.subscribe_direct_channel_message(room_id, user_id)
452
		self.publish(subscribe_message, self.channel, True)
453
		other_channel = RedisPrefix.generate_user(user_id)
454
		if self.channel != other_channel:
455
			self.publish(subscribe_message, other_channel, True)
456
457
	def delete_channel(self, message):
458
		room_id = message[VarNames.ROOM_ID]
459
		if room_id not in self.channels or room_id == ALL_ROOM_ID:
460
			raise ValidationError('You are not allowed to exit this room')
461
		room = do_db(Room.objects.get, id=room_id)
462
		if room.disabled:
463
			raise ValidationError('Room is already deleted')
464
		if room.name is None:  # if private then disable
465
			room.disabled = True
466
		else:  # if public -> leave the room, delete the link
467
			RoomUsers.objects.filter(room_id=room.id, user_id=self.user_id).delete()
468
			online = self.get_online_from_redis(room_id)
469
			online.remove(self.user_id)
470
			self.publish(self.room_online(online, Actions.LOGOUT, room_id), room_id)
471
		room.save()
472
		message = self.unsubscribe_direct_message(room_id)
473
		self.publish(message, room_id, True)
474
475
	def edit_message(self, data):
476
		# ord(next (iter (message['images'])))
477
		message_id = data[VarNames.MESSAGE_ID]
478
		message = Message.objects.get(id=message_id)
479
		if message.sender_id != self.user_id:
480
			raise ValidationError("You can only edit your messages")
481
		if message.time + 600000 < get_milliseconds():
482
			raise ValidationError("You can only edit messages that were send not more than 10 min ago")
483
		if message.deleted:
484
			raise ValidationError("Already deleted")
485
		message.content = data[VarNames.CONTENT]
486
		selector = Message.objects.filter(id=message_id)
487
		if message.content is None:
488
			action = Actions.DELETE_MESSAGE
489
			prep_imgs = None
490
			selector.update(deleted=True)
491
		else:
492
			action = Actions.EDIT_MESSAGE
493
			prep_imgs = process_images(data.get(VarNames.IMG), message)
494
			selector.update(content=message.content, symbol=message.symbol)
495
		self.publish(self.create_send_message(message, action, prep_imgs), message.room_id)
496
497
	def send_client_new_channel(self, message):
498
		room_id = message[VarNames.ROOM_ID]
499
		self.add_channel(room_id)
500
		self.add_online_user(room_id)
501
502
	def set_opponent_call_channel(self, message):
503
		connection_id = message[VarNames.CONNECTION_ID]
504
		if message[VarNames.WEBRTC_OPPONENT_ID] == self.id:
505
			return True
506
		self.sync_redis.hset(connection_id, self.id, WebRtcRedisStates.OFFERED)
507
508
	def send_client_delete_channel(self, message):
509
		room_id = message[VarNames.ROOM_ID]
510
		self.async_redis.unsubscribe((room_id,))
511
		self.async_redis_publisher.hdel(room_id, self.id)
512
		self.channels.remove(room_id)
513
514
	def process_get_messages(self, data):
515
		"""
516
		:type data: dict
517
		"""
518
		header_id = data.get(VarNames.GET_MESSAGES_HEADER_ID, None)
519
		count = int(data.get(VarNames.GET_MESSAGES_COUNT, 10))
520
		room_id = data[VarNames.CHANNEL]
521
		self.logger.info('!! Fetching %d messages starting from %s', count, header_id)
522
		if header_id is None:
523
			messages = Message.objects.filter(Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
524
		else:
525
			messages = Message.objects.filter(Q(id__lt=header_id), Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
526
		images = do_db(get_message_images, messages)
527
		response = self.get_messages(messages, room_id, images)
528
		self.ws_write(response)
529