Completed
Push — master ( af202d...0efa0e )
by Andrew
20s
created

MessagesHandler.invite_user()   A

Complexity

Conditions 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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