Completed
Push — master ( 896f50...904355 )
by Andrew
35s
created

MessagesHandler   F

Complexity

Total Complexity 68

Size/Duplication

Total Lines 347
Duplicated Lines 4.32 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
dl 15
loc 347
rs 2.9411
c 5
b 0
f 1
wmc 68

35 Methods

Rating   Name   Duplication   Size   Complexity  
A patch_tornadoredis() 0 22 3
A new_read() 0 16 2
A connected() 0 3 1
B __init__() 0 32 1
A search_giphy() 0 13 3
A publish() 0 6 2
A create_user_channel() 0 8 2
B edit_message() 0 24 4
A encode() 0 8 1
A add_online_user() 0 20 3
A listen() 0 5 1
A get_online_and_status_from_redis() 0 7 2
A create_new_room() 0 9 3
A pub_sub_message() 0 11 4
A post_firebase() 0 14 3
A edit_glyphy() 0 4 1
A isGiphy() 0 4 3
A add_channel() 0 4 1
A send_client_delete_channel() 5 5 1
A http_client() 0 3 1
A send_message() 0 19 1
A on_reply() 0 6 2
B process_send_message() 0 29 3
B delete_channel() 0 17 5
A on_giphy_reply() 0 8 2
A send_client_new_channel() 0 4 1
A respond_ping() 0 2 1
A notify_offline() 0 11 4
A ws_write() 0 2 1
A logger() 0 3 2
A get_online_from_redis() 0 2 1
A remove_parsable_prefix() 0 3 2
A invite_user() 0 11 2
A process_get_messages() 8 15 2
A parse_redis_online() 0 13 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like MessagesHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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