Completed
Push — master ( 390cb8...b1052f )
by Andrew
28s
created

MessagesHandler   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 301
Duplicated Lines 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
c 8
b 0
f 0
dl 0
loc 301
rs 6
wmc 55

29 Methods

Rating   Name   Duplication   Size   Complexity  
A publish() 0 6 2
A encode() 0 8 1
A get_online_and_status_from_redis() 0 7 2
A ws_write() 0 2 1
A parse_redis_online() 0 13 4
B __init__() 0 32 1
A create_user_channel() 0 8 2
A edit_message() 0 16 2
A add_online_user() 0 20 3
A listen() 0 5 1
A create_new_room() 0 9 3
A search_gyphy() 0 12 3
A pub_sub_message() 0 11 4
A patch_tornadoredis() 0 22 3
A add_channel() 0 4 1
A send_client_delete_channel() 0 5 1
A send_message() 0 18 1
A process_send_message() 0 10 2
B delete_channel() 0 17 5
A new_read() 0 16 2
A on_gyphy_reply() 0 7 2
A send_client_new_channel() 0 4 1
A respond_ping() 0 2 1
A connected() 0 3 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() 0 15 2

How to fix   Complexity   

Complex Class

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
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
15
from chat.py2_3 import str_type, quote
16
from chat.settings import ALL_ROOM_ID, TORNADO_REDIS_PORT, WEBRTC_CONNECTION, GIPHY_URL, GYPHY_REGEX
17
from chat.tornado.constants import VarNames, HandlerNames, Actions, RedisPrefix, WebRtcRedisStates
18
from chat.tornado.image_utils import process_images, prepare_img, save_images, get_message_images
19
from chat.tornado.message_creator import WebRtcMessageCreator, MessagesCreator
20
from chat.utils import get_max_key, do_db, validate_edit_message, get_or_create_room, \
21
	create_room
22
23
parent_logger = logging.getLogger(__name__)
24
base_logger = logging.LoggerAdapter(parent_logger, {
25
	'id': 0,
26
	'ip': '000.000.000.000'
27
})
28
29
# TODO https://github.com/leporo/tornado-redis#connection-pool-support
30
# CONNECTION_POOL = tornadoredis.ConnectionPool(
31
# max_connections=500,
32
# wait_for_available=True)
33
34
GIPHY_API_KEY = getattr(settings, "GIPHY_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
	@engine
104
	def listen(self, channels):
105
		yield Task(
106
			self.async_redis.subscribe, channels)
107
		self.async_redis.listen(self.pub_sub_message)
108
109
	@property
110
	def logger(self):
111
		return self._logger if self._logger else base_logger
112
113
	@engine
114
	def add_channel(self, channel):
115
		self.channels.append(channel)
116
		yield Task(self.async_redis.subscribe, (channel,))
117
118
	def get_online_from_redis(self, channel):
119
		return self.get_online_and_status_from_redis(channel)[1]
120
121
	def get_online_and_status_from_redis(self, channel):
122
		"""
123
		:rtype : (bool, list)
124
		"""
125
		online = self.sync_redis.ssmembers(channel)
126
		self.logger.debug('!! channel %s redis online: %s', channel, online)
127
		return self.parse_redis_online(online) if online else (False, [])
128
129
	def parse_redis_online(self, online):
130
		"""
131
		:rtype : (bool, list)
132
		"""
133
		result = set()
134
		user_is_online = False
135
		for decoded in online:  # py2 iteritems
136
			# : char specified in cookies_middleware.py.create_id
137
			user_id = int(decoded.split(':')[0])
138
			if user_id == self.user_id and decoded != self.id:
139
				user_is_online = True
140
			result.add(user_id)
141
		return user_is_online, list(result)
142
143
	def add_online_user(self, room_id, offline_messages=None):
144
		"""
145
		adds to redis
146
		online_users = { connection_hash1 = stored_redis_user1, connection_hash_2 = stored_redis_user2 }
147
		:return:
148
		"""
149
		self.async_redis_publisher.sadd(room_id, self.id)
150
		# since we add user to online first, latest trigger will always show correct online
151
		is_online, online = self.get_online_and_status_from_redis(room_id)
152
		if is_online:  # Send user names to self
153
			online_user_names_mes = self.room_online(online, Actions.REFRESH_USER, room_id)
154
			self.logger.info('!! Second tab, retrieving online for self')
155
			self.ws_write(online_user_names_mes)
156
		else:  # if a new tab has been opened
157
			online.append(self.user_id)
158
			online_user_names_mes = self.room_online(online, Actions.LOGIN, room_id)
159
			self.logger.info('!! First tab, sending refresh online for all')
160
			self.publish(online_user_names_mes, room_id)
161
			if offline_messages:
162
				self.ws_write(self.load_offline_message(offline_messages, room_id))
163
164
	def publish(self, message, channel, parsable=False):
165
		jsoned_mess = json.dumps(message)
166
		self.logger.debug('<%s> %s', channel, jsoned_mess)
167
		if parsable:
168
			jsoned_mess = self.encode(jsoned_mess)
169
		self.async_redis_publisher.publish(channel, jsoned_mess)
170
171
	def encode(self, message):
172
		"""
173
		Marks message with prefix to specify that
174
		it should be decoded and proccesed before sending to client
175
		@param message: message to mark
176
		@return: marked message
177
		"""
178
		return self.parsable_prefix + message
179
180
	def remove_parsable_prefix(self, message):
181
		if message.startswith(self.parsable_prefix):
182
			return message[1:]
183
184
	def pub_sub_message(self, message):
185
		data = message.body
186
		if isinstance(data, str_type):  # subscribe event
187
			prefixless_str = self.remove_parsable_prefix(data)
188
			if prefixless_str:
189
				dict_message = json.loads(prefixless_str)
190
				res = self.post_process_message[dict_message[VarNames.EVENT]](dict_message)
191
				if not res:
192
					self.ws_write(prefixless_str)
193
			else:
194
				self.ws_write(data)
195
196
	def ws_write(self, message):
197
		raise NotImplementedError('WebSocketHandler implements')
198
199
	@asynchronous
200
	def search_gyphy(self, message ,query):
201
		def on_gyphy_reply(response):
202
			try:
203
				res =  json.loads(response.body)
204
				gyphy = res['data'][0]['embed_url']
205
			except:
206
				gyphy = None
207
			self.send_message(message, gyphy)
208
		http_client = AsyncHTTPClient()
209
		url = GIPHY_URL.format(GIPHY_API_KEY, quote(query, safe=''))
210
		http_client.fetch(url, callback=on_gyphy_reply)
211
212
	def process_send_message(self, message):
213
		"""
214
		:type message: dict
215
		"""
216
		content = message.get(VarNames.CONTENT)
217
		gyphy_match = re.search(GYPHY_REGEX, content)
218
		if gyphy_match is not None:
219
			self.search_gyphy(message, gyphy_match.group(1))
220
		else:
221
			self.send_message(message)
222
223
	def send_message(self, message, gyphy=None):
224
		raw_imgs = message.get(VarNames.IMG)
225
		channel = message[VarNames.CHANNEL]
226
		message_db = Message(
227
			sender_id=self.user_id,
228
			content=message[VarNames.CONTENT],
229
			symbol=get_max_key(raw_imgs),
230
			gyphy=gyphy
231
		)
232
		message_db.room_id = channel
233
		do_db(message_db.save)
234
		db_images = save_images(raw_imgs, message_db.id)
235
		prepared_message = self.create_send_message(
236
			message_db,
237
			Actions.PRINT_MESSAGE,
238
			prepare_img(db_images, message_db.id)
239
		)
240
		self.publish(prepared_message, channel)
241
242
	def create_new_room(self, message):
243
		room_name = message[VarNames.ROOM_NAME]
244
		if not room_name or len(room_name) > 16:
245
			raise ValidationError('Incorrect room name "{}"'.format(room_name))
246
		room = Room(name=room_name)
247
		do_db(room.save)
248
		RoomUsers(room_id=room.id, user_id=self.user_id).save()
249
		subscribe_message = self.subscribe_room_channel_message(room.id, room_name)
250
		self.publish(subscribe_message, self.channel, True)
251
252
	def invite_user(self, message):
253
		room_id = message[VarNames.ROOM_ID]
254
		user_id = message[VarNames.USER_ID]
255
		room = get_or_create_room(self.channels, room_id, user_id)
256
		users_in_room = {
257
			user.id: RedisPrefix.set_js_user_structure(user.username, user.sex)
258
			for user in room.users.all()
259
		}
260
		self.publish(self.add_user_to_room(room_id, user_id, users_in_room[user_id]), room_id)
261
		subscribe_message = self.invite_room_channel_message(room_id, user_id, room.name, users_in_room)
262
		self.publish(subscribe_message, RedisPrefix.generate_user(user_id), True)
263
264
	def respond_ping(self, message):
265
		self.ws_write(self.responde_pong())
266
267
	def create_user_channel(self, message):
268
		user_id = message[VarNames.USER_ID]
269
		room_id = create_room(self.user_id, user_id)
270
		subscribe_message = self.subscribe_direct_channel_message(room_id, user_id)
271
		self.publish(subscribe_message, self.channel, True)
272
		other_channel = RedisPrefix.generate_user(user_id)
273
		if self.channel != other_channel:
274
			self.publish(subscribe_message, other_channel, True)
275
276
	def delete_channel(self, message):
277
		room_id = message[VarNames.ROOM_ID]
278
		if room_id not in self.channels or room_id == ALL_ROOM_ID:
279
			raise ValidationError('You are not allowed to exit this room')
280
		room = do_db(Room.objects.get, id=room_id)
281
		if room.disabled:
282
			raise ValidationError('Room is already deleted')
283
		if room.name is None:  # if private then disable
284
			room.disabled = True
285
		else:  # if public -> leave the room, delete the link
286
			RoomUsers.objects.filter(room_id=room.id, user_id=self.user_id).delete()
287
			online = self.get_online_from_redis(room_id)
288
			online.remove(self.user_id)
289
			self.publish(self.room_online(online, Actions.LOGOUT, room_id), room_id)
290
		room.save()
291
		message = self.unsubscribe_direct_message(room_id)
292
		self.publish(message, room_id, True)
293
294
	def edit_message(self, data):
295
		# ord(next (iter (message['images'])))
296
		message_id = data[VarNames.MESSAGE_ID]
297
		message = do_db(Message.objects.get, id=message_id)
298
		validate_edit_message(self.user_id, message)
299
		message.content = data[VarNames.CONTENT]
300
		selector = Message.objects.filter(id=message_id)
301
		if message.content is None:
302
			action = Actions.DELETE_MESSAGE
303
			prep_imgs = None
304
			selector.update(deleted=True)
305
		else:
306
			action = Actions.EDIT_MESSAGE
307
			prep_imgs = process_images(data.get(VarNames.IMG), message)
308
			selector.update(content=message.content, symbol=message.symbol)
309
		self.publish(self.create_send_message(message, action, prep_imgs), message.room_id)
310
311
	def send_client_new_channel(self, message):
312
		room_id = message[VarNames.ROOM_ID]
313
		self.add_channel(room_id)
314
		self.add_online_user(room_id)
315
316
	def send_client_delete_channel(self, message):
317
		room_id = message[VarNames.ROOM_ID]
318
		self.async_redis.unsubscribe((room_id,))
319
		self.async_redis_publisher.hdel(room_id, self.id)
320
		self.channels.remove(room_id)
321
322
	def process_get_messages(self, data):
323
		"""
324
		:type data: dict
325
		"""
326
		header_id = data.get(VarNames.GET_MESSAGES_HEADER_ID, None)
327
		count = int(data.get(VarNames.GET_MESSAGES_COUNT, 10))
328
		room_id = data[VarNames.CHANNEL]
329
		self.logger.info('!! Fetching %d messages starting from %s', count, header_id)
330
		if header_id is None:
331
			messages = Message.objects.filter(Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
332
		else:
333
			messages = Message.objects.filter(Q(id__lt=header_id), Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
334
		images = do_db(get_message_images, messages)
335
		response = self.get_messages(messages, room_id, images)
336
		self.ws_write(response)
337
338
339
class WebRtcMessageHandler(MessagesHandler, WebRtcMessageCreator):
340
341
	def __init__(self, *args, **kwargs):
342
		super(WebRtcMessageHandler, self).__init__(*args, **kwargs)
343
		self.pre_process_message.update({
344
			Actions.WEBRTC: self.proxy_webrtc,
345
			Actions.CLOSE_FILE_CONNECTION: self.close_file_connection,
346
			Actions.CLOSE_CALL_CONNECTION: self.close_call_connection,
347
			Actions.CANCEL_CALL_CONNECTION: self.cancel_call_connection,
348
			Actions.ACCEPT_CALL: self.accept_call,
349
			Actions.ACCEPT_FILE: self.accept_file,
350
			Actions.OFFER_FILE_CONNECTION: self.offer_webrtc_connection,
351
			Actions.OFFER_CALL_CONNECTION: self.offer_webrtc_connection,
352
			Actions.REPLY_FILE_CONNECTION: self.reply_file_connection,
353
			Actions.RETRY_FILE_CONNECTION: self.retry_file_connection,
354
			Actions.REPLY_CALL_CONNECTION: self.reply_call_connection,
355
		})
356
		self.post_process_message.update({
357
			Actions.OFFER_FILE_CONNECTION: self.set_opponent_call_channel,
358
			Actions.OFFER_CALL_CONNECTION: self.set_opponent_call_channel
359
		})
360
361 View Code Duplication
	def set_opponent_call_channel(self, message):
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
362
		connection_id = message[VarNames.CONNECTION_ID]
363
		if message[VarNames.WEBRTC_OPPONENT_ID] == self.id:
364
			return True
365
		self.sync_redis.hset(connection_id, self.id, WebRtcRedisStates.OFFERED)
366
367
	def offer_webrtc_connection(self, in_message):
368
		room_id = in_message[VarNames.CHANNEL]
369
		content = in_message.get(VarNames.CONTENT)
370
		qued_id = in_message[VarNames.WEBRTC_QUED_ID]
371
		connection_id = id_generator(RedisPrefix.CONNECTION_ID_LENGTH)
372
		# use list because sets dont have 1st element which is offerer
373
		self.async_redis_publisher.hset(WEBRTC_CONNECTION, connection_id, self.id)
374
		self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
375
		opponents_message = self.offer_webrtc(content, connection_id, room_id, in_message[VarNames.EVENT])
376
		self_message = self.set_connection_id(qued_id, connection_id)
377
		self.ws_write(self_message)
378
		self.logger.info('!! Offering a webrtc, connection_id %s', connection_id)
379
		self.publish(opponents_message, room_id, True)
380
381
	def retry_file_connection(self, in_message):
382
		connection_id = in_message[VarNames.CONNECTION_ID]
383
		opponent_ws_id = in_message[VarNames.WEBRTC_OPPONENT_ID]
384
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
385
		receiver_ws_status = self.sync_redis.shget(connection_id, opponent_ws_id)
386
		if receiver_ws_status == WebRtcRedisStates.READY and self.id == sender_ws_id:
387
			self.publish(self.retry_file(connection_id), opponent_ws_id)
388
		else:
389
			raise ValidationError("Invalid channel status.")
390
391
	def reply_file_connection(self, in_message):
392
		connection_id = in_message[VarNames.CONNECTION_ID]
393
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
394
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
395
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
396
		if sender_ws_status == WebRtcRedisStates.READY and self_ws_status == WebRtcRedisStates.OFFERED:
397
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.RESPONDED)
398
			self.publish(self.reply_webrtc(
399
				Actions.REPLY_FILE_CONNECTION,
400
				connection_id,
401
				HandlerNames.WEBRTC_TRANSFER,
402
				in_message[VarNames.CONTENT]
403
			), sender_ws_id)
404
		else:
405
			raise ValidationError("Invalid channel status.")
406
407
	def reply_call_connection(self, in_message):
408
		self.send_call_answer(
409
			in_message,
410
			WebRtcRedisStates.RESPONDED,
411
			Actions.REPLY_CALL_CONNECTION,
412
			[WebRtcRedisStates.OFFERED],
413
			HandlerNames.WEBRTC_TRANSFER
414
		)
415
416
	def proxy_webrtc(self, in_message):
417
		"""
418
		:type in_message: dict
419
		"""
420
		connection_id = in_message[VarNames.CONNECTION_ID]
421
		channel = in_message.get(VarNames.WEBRTC_OPPONENT_ID)
422
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
423
		opponent_channel_status = self.sync_redis.shget(connection_id, channel)
424
		if not (self_channel_status == WebRtcRedisStates.READY and opponent_channel_status == WebRtcRedisStates.READY):
425
			raise ValidationError('Error in connection status, your status is {} while opponent is {}'.format(
426
				self_channel_status, opponent_channel_status
427
			))  # todo receiver should only accept proxy_webrtc from sender, sender can accept all
428
		# I mean somebody if there're 3 ppl in 1 channel and first is initing transfer to 2nd and 3rd,
429
		# 2nd guy can fraud 3rd guy webrtc traffic, which is allowed during the call, but not while transering file
430
		in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
431
		in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
432
		self.logger.debug(
433
			"Forwarding message to channel %s, self %s, other status %s",
434
			channel,
435
			self_channel_status,
436
			opponent_channel_status
437
		)
438
		self.publish(in_message, channel)
439
440
	def close_file_connection(self, in_message):
441
		connection_id = in_message[VarNames.CONNECTION_ID]
442
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
443
		if not self_channel_status:
444
			raise Exception("Access Denied")
445
		if self_channel_status != WebRtcRedisStates.CLOSED:
446
			sender_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
447
			if sender_id == self.id:
448
				self.close_file_sender(connection_id)
449
			else:
450
				self.close_file_receiver(connection_id, in_message, sender_id)
451
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.CLOSED)
452
453
	def close_call_connection(self, in_message):
454
		self.send_call_answer(
455
			in_message,
456
			WebRtcRedisStates.CLOSED,
457
			Actions.CLOSE_CALL_CONNECTION,
458
			[WebRtcRedisStates.READY, WebRtcRedisStates.RESPONDED],
459 View Code Duplication
			HandlerNames.PEER_CONNECTION
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
460
		)
461
462
	def cancel_call_connection(self, in_message):
463
		self.send_call_answer(
464
			in_message,
465
			WebRtcRedisStates.CLOSED,
466
			Actions.CANCEL_CALL_CONNECTION,
467
			[WebRtcRedisStates.OFFERED],
468
			HandlerNames.WEBRTC_TRANSFER
469
		)
470
471
	def close_file_receiver(self, connection_id, in_message, sender_id):
472
		sender_status = self.sync_redis.shget(connection_id, sender_id)
473
		if not sender_status:
474
			raise Exception("Access denied")
475
		if sender_status != WebRtcRedisStates.CLOSED:
476
			in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
477
			in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
478
			self.publish(in_message, sender_id)
479
480
	def close_file_sender(self, connection_id):
481
		values = self.sync_redis.shgetall(connection_id)
482
		del values[self.id]
483
		message = self.get_close_file_sender_message(connection_id)
484
		for ws_id in values:
485
			if values[ws_id] == WebRtcRedisStates.CLOSED:
486
				continue
487
			self.publish(message, ws_id)
488
489
	def accept_file(self, in_message):
490
		connection_id = in_message[VarNames.CONNECTION_ID]
491
		content = in_message[VarNames.CONTENT]
492
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
493
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
494
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
495
		if sender_ws_status == WebRtcRedisStates.READY \
496
				and self_ws_status in [WebRtcRedisStates.RESPONDED, WebRtcRedisStates.READY]:
497
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
498
			self.publish(self.get_accept_file_message(connection_id, content), sender_ws_id)
499
		else:
500
			raise ValidationError("Invalid channel status")
501
502
	# todo
503
	# we can use channel_status = self.sync_redis.shgetall(connection_id)
504
	# and then self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
505
	# if we shgetall and only then do async hset
506
	# we can catch an issue when 2 concurrent users accepted the call
507
	# but we didn't  send them ACCEPT_CALL as they both were in status 'offered'
508
	def accept_call(self, in_message):
509
		connection_id = in_message[VarNames.CONNECTION_ID]
510
		self_status = self.sync_redis.shget(connection_id, self.id)
511
		if self_status == WebRtcRedisStates.RESPONDED:
512
			conn_users = self.sync_redis.shgetall(connection_id)
513
			self.publish_call_answer(
514
				conn_users,
515
				connection_id,
516
				HandlerNames.WEBRTC_TRANSFER,
517
				Actions.ACCEPT_CALL,
518
				WebRtcRedisStates.READY,
519
				{}
520
			)
521
		else:
522
			raise ValidationError("Invalid channel status")
523
524
	def send_call_answer(self, in_message, status_set, reply_action, allowed_state, message_handler):
525
		connection_id = in_message[VarNames.CONNECTION_ID]
526
		content = in_message[VarNames.CONTENT]
527
		conn_users = self.sync_redis.shgetall(connection_id)
528
		if conn_users[self.id] in allowed_state:
529
			self.publish_call_answer(conn_users, connection_id, message_handler, reply_action, status_set, content)
530
		else:
531
			raise ValidationError("Invalid channel status.")
532
533
	def publish_call_answer(self, conn_users, connection_id, message_handler, reply_action, status_set, content):
534
		self.async_redis_publisher.hset(connection_id, self.id, status_set)
535
		del conn_users[self.id]
536
		message = self.reply_webrtc(reply_action, connection_id, message_handler, content)
537
		for user in conn_users:
538
			if conn_users[user] != WebRtcRedisStates.CLOSED:
539
				self.publish(message, user)