Completed
Push — master ( e8a010...d3ef38 )
by Andrew
25s
created

MessagesHandler.post_firebase()   B

Complexity

Conditions 6

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
c 0
b 0
f 0
dl 0
loc 22
rs 7.7857

1 Method

Rating   Name   Duplication   Size   Complexity  
B MessagesHandler.on_reply() 0 14 5
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, inactive=False)
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
				response_obj = json.loads(response.body)
239
				delete = []
240
				for index, elem in enumerate(response_obj['results']):
241
					if elem.get('error') in ['NotRegistered', 'InvalidRegistration']:
242
						delete.append(reg_ids[index])
243
				if len(delete) > 0:
244
					self.logger.info("Deactivating subscriptions: %s", delete)
245
					Subscription.objects.filter(registration_id__in=delete).update(inactive=True)
246
			except Exception as e:
247
				self.logger.error("Unable to parse response" + str(e))
248
				pass
249
250
		headers = {"Content-Type": "application/json", "Authorization": "key=%s" % FIREBASE_API_KEY}
251
		body = json.dumps({"registration_ids": reg_ids})
252
		self.logger.debug("!! post_fire_message %s", body)
253
		r = HTTPRequest(FIREBASE_URL, method="POST", headers=headers, body=body)
254
		self.http_client.fetch(r, callback=on_reply)
255
256
	def isGiphy(self, content):
257
		if GIPHY_API_KEY is not None and content is not None:
258
			giphy_match = re.search(GIPHY_REGEX, content)
259
			return giphy_match.group(1) if giphy_match is not None else None
260
261
	def process_send_message(self, message):
262
		"""
263
		:type message: dict
264
		"""
265
		content = message.get(VarNames.CONTENT)
266
		giphy_match = self.isGiphy(content)
267
268
		# @transaction.atomic mysql has gone away
269
		def send_message(message, giphy=None):
270
			raw_imgs = message.get(VarNames.IMG)
271
			channel = message[VarNames.CHANNEL]
272
			message_db = Message(
273
				sender_id=self.user_id,
274
				content=message[VarNames.CONTENT],
275
				symbol=get_max_key(raw_imgs),
276
				giphy=giphy
277
			)
278
			message_db.room_id = channel
279
			do_db(message_db.save)
280
			db_images = save_images(raw_imgs, message_db.id)
281
			prepared_message = self.create_send_message(
282
				message_db,
283
				Actions.PRINT_MESSAGE,
284
				prepare_img(db_images, message_db.id)
285
			)
286
			self.publish(prepared_message, channel)
287
			self.notify_offline(channel, message_db.id)
288
		if giphy_match is not None:
289
			self.search_giphy(message, giphy_match, send_message)
290
		else:
291
			send_message(message)
292
293
	def create_new_room(self, message):
294
		room_name = message[VarNames.ROOM_NAME]
295
		if not room_name or len(room_name) > 16:
296
			raise ValidationError('Incorrect room name "{}"'.format(room_name))
297
		room = Room(name=room_name)
298
		do_db(room.save)
299
		RoomUsers(room_id=room.id, user_id=self.user_id).save()
300
		subscribe_message = self.subscribe_room_channel_message(room.id, room_name)
301
		self.publish(subscribe_message, self.channel, True)
302
303
	def invite_user(self, message):
304
		room_id = message[VarNames.ROOM_ID]
305
		user_id = message[VarNames.USER_ID]
306
		room = get_or_create_room(self.channels, room_id, user_id)
307
		users_in_room = {
308
			user.id: RedisPrefix.set_js_user_structure(user.username, user.sex)
309
			for user in room.users.all()
310
		}
311
		self.publish(self.add_user_to_room(room_id, user_id, users_in_room[user_id]), room_id)
312
		subscribe_message = self.invite_room_channel_message(room_id, user_id, room.name, users_in_room)
313
		self.publish(subscribe_message, RedisPrefix.generate_user(user_id), True)
314
315
	def respond_ping(self, message):
316
		self.ws_write(self.responde_pong())
317
318
	def create_user_channel(self, message):
319
		user_id = message[VarNames.USER_ID]
320
		room_id = create_room(self.user_id, user_id)
321
		subscribe_message = self.subscribe_direct_channel_message(room_id, user_id)
322
		self.publish(subscribe_message, self.channel, True)
323
		other_channel = RedisPrefix.generate_user(user_id)
324
		if self.channel != other_channel:
325
			self.publish(subscribe_message, other_channel, True)
326
327
	def delete_channel(self, message):
328
		room_id = message[VarNames.ROOM_ID]
329
		if room_id not in self.channels or room_id == ALL_ROOM_ID:
330
			raise ValidationError('You are not allowed to exit this room')
331
		room = do_db(Room.objects.get, id=room_id)
332
		if room.disabled:
333
			raise ValidationError('Room is already deleted')
334
		if room.name is None:  # if private then disable
335
			room.disabled = True
336
		else:  # if public -> leave the room, delete the link
337
			RoomUsers.objects.filter(room_id=room.id, user_id=self.user_id).delete()
338
			online = self.get_online_from_redis(room_id)
339
			online.remove(self.user_id)
340
			self.publish(self.room_online(online, Actions.LOGOUT, room_id), room_id)
341
		room.save()
342
		message = self.unsubscribe_direct_message(room_id)
343
		self.publish(message, room_id, True)
344
345
346
	def edit_message(self, data):
347
		message_id = data[VarNames.MESSAGE_ID]
348
		message = do_db(Message.objects.get, id=message_id)
349
		validate_edit_message(self.user_id, message)
350
		message.content = data[VarNames.CONTENT]
351
		selector = Message.objects.filter(id=message_id)
352
		giphy_match = self.isGiphy(data[VarNames.CONTENT])
353
		if message.content is None:
354
			action = Actions.DELETE_MESSAGE
355
			prep_imgs = None
356
			selector.update(deleted=True)
357
		elif giphy_match is not None:
358
			def edit_glyphy(message, giphy):
359
				do_db(selector.update, content=message.content, symbol=message.symbol, giphy=giphy)
360
				message.giphy = giphy
361 View Code Duplication
				self.publish(self.create_send_message(message, Actions.EDIT_MESSAGE, None), message.room_id)
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
362
			self.search_giphy(message, giphy_match, edit_glyphy)
363
			return
364
		else:
365
			action = Actions.EDIT_MESSAGE
366
			message.giphy = None
367
			prep_imgs = process_images(data.get(VarNames.IMG), message)
368
			selector.update(content=message.content, symbol=message.symbol, giphy=None)
369
		self.publish(self.create_send_message(message, action, prep_imgs), message.room_id)
370
371
	def send_client_new_channel(self, message):
372
		room_id = message[VarNames.ROOM_ID]
373
		self.add_channel(room_id)
374
		self.add_online_user(room_id)
375
376
	def send_client_delete_channel(self, message):
377
		room_id = message[VarNames.ROOM_ID]
378
		self.async_redis.unsubscribe((room_id,))
379
		self.async_redis_publisher.hdel(room_id, self.id)
380
		self.channels.remove(room_id)
381
382
	def process_get_messages(self, data):
383
		"""
384
		:type data: dict
385
		"""
386
		header_id = data.get(VarNames.GET_MESSAGES_HEADER_ID, None)
387
		count = int(data.get(VarNames.GET_MESSAGES_COUNT, 10))
388
		room_id = data[VarNames.CHANNEL]
389
		self.logger.info('!! Fetching %d messages starting from %s', count, header_id)
390
		if header_id is None:
391
			messages = Message.objects.filter(Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
392
		else:
393
			messages = Message.objects.filter(Q(id__lt=header_id), Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count]
394
		images = do_db(get_message_images, messages)
395
		response = self.get_messages(messages, room_id, images, prepare_img)
396
		self.ws_write(response)
397
398
399
class WebRtcMessageHandler(MessagesHandler, WebRtcMessageCreator):
400
401
	def __init__(self, *args, **kwargs):
402
		super(WebRtcMessageHandler, self).__init__(*args, **kwargs)
403
		self.pre_process_message.update({
404
			Actions.WEBRTC: self.proxy_webrtc,
405
			Actions.CLOSE_FILE_CONNECTION: self.close_file_connection,
406
			Actions.CLOSE_CALL_CONNECTION: self.close_call_connection,
407
			Actions.CANCEL_CALL_CONNECTION: self.cancel_call_connection,
408
			Actions.ACCEPT_CALL: self.accept_call,
409
			Actions.ACCEPT_FILE: self.accept_file,
410
			Actions.OFFER_FILE_CONNECTION: self.offer_webrtc_connection,
411
			Actions.OFFER_CALL_CONNECTION: self.offer_webrtc_connection,
412
			Actions.REPLY_FILE_CONNECTION: self.reply_file_connection,
413
			Actions.RETRY_FILE_CONNECTION: self.retry_file_connection,
414
			Actions.REPLY_CALL_CONNECTION: self.reply_call_connection,
415
		})
416
		self.post_process_message.update({
417
			Actions.OFFER_FILE_CONNECTION: self.set_opponent_call_channel,
418
			Actions.OFFER_CALL_CONNECTION: self.set_opponent_call_channel
419
		})
420
421
	def set_opponent_call_channel(self, message):
422
		connection_id = message[VarNames.CONNECTION_ID]
423
		if message[VarNames.WEBRTC_OPPONENT_ID] == self.id:
424
			return True
425
		self.sync_redis.hset(connection_id, self.id, WebRtcRedisStates.OFFERED)
426
427
	def offer_webrtc_connection(self, in_message):
428
		room_id = in_message[VarNames.CHANNEL]
429
		content = in_message.get(VarNames.CONTENT)
430
		qued_id = in_message[VarNames.WEBRTC_QUED_ID]
431
		connection_id = id_generator(RedisPrefix.CONNECTION_ID_LENGTH)
432
		# use list because sets dont have 1st element which is offerer
433
		self.async_redis_publisher.hset(WEBRTC_CONNECTION, connection_id, self.id)
434
		self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
435
		opponents_message = self.offer_webrtc(content, connection_id, room_id, in_message[VarNames.EVENT])
436
		self_message = self.set_connection_id(qued_id, connection_id)
437
		self.ws_write(self_message)
438
		self.logger.info('!! Offering a webrtc, connection_id %s', connection_id)
439
		self.publish(opponents_message, room_id, True)
440
441
	def retry_file_connection(self, in_message):
442
		connection_id = in_message[VarNames.CONNECTION_ID]
443
		opponent_ws_id = in_message[VarNames.WEBRTC_OPPONENT_ID]
444
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
445
		receiver_ws_status = self.sync_redis.shget(connection_id, opponent_ws_id)
446
		if receiver_ws_status == WebRtcRedisStates.READY and self.id == sender_ws_id:
447
			self.publish(self.retry_file(connection_id), opponent_ws_id)
448
		else:
449
			raise ValidationError("Invalid channel status.")
450
451
	def reply_file_connection(self, in_message):
452
		connection_id = in_message[VarNames.CONNECTION_ID]
453
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
454
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
455
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
456
		if sender_ws_status == WebRtcRedisStates.READY and self_ws_status == WebRtcRedisStates.OFFERED:
457
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.RESPONDED)
458
			self.publish(self.reply_webrtc(
459 View Code Duplication
				Actions.REPLY_FILE_CONNECTION,
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
460
				connection_id,
461
				HandlerNames.WEBRTC_TRANSFER,
462
				in_message[VarNames.CONTENT]
463
			), sender_ws_id)
464
		else:
465
			raise ValidationError("Invalid channel status.")
466
467
	def reply_call_connection(self, in_message):
468
		self.send_call_answer(
469
			in_message,
470
			WebRtcRedisStates.RESPONDED,
471
			Actions.REPLY_CALL_CONNECTION,
472
			[WebRtcRedisStates.OFFERED],
473
			HandlerNames.WEBRTC_TRANSFER
474
		)
475
476
	def proxy_webrtc(self, in_message):
477
		"""
478
		:type in_message: dict
479
		"""
480
		connection_id = in_message[VarNames.CONNECTION_ID]
481
		channel = in_message.get(VarNames.WEBRTC_OPPONENT_ID)
482
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
483
		opponent_channel_status = self.sync_redis.shget(connection_id, channel)
484
		if not (self_channel_status == WebRtcRedisStates.READY and opponent_channel_status == WebRtcRedisStates.READY):
485
			raise ValidationError('Error in connection status, your status is {} while opponent is {}'.format(
486
				self_channel_status, opponent_channel_status
487
			))  # todo receiver should only accept proxy_webrtc from sender, sender can accept all
488
		# I mean somebody if there're 3 ppl in 1 channel and first is initing transfer to 2nd and 3rd,
489
		# 2nd guy can fraud 3rd guy webrtc traffic, which is allowed during the call, but not while transering file
490
		in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
491
		in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
492
		self.logger.debug(
493
			"!! Forwarding message to channel %s, self %s, other status %s",
494
			channel,
495
			self_channel_status,
496
			opponent_channel_status
497
		)
498
		self.publish(in_message, channel)
499
500
	def close_file_connection(self, in_message):
501
		connection_id = in_message[VarNames.CONNECTION_ID]
502
		self_channel_status = self.sync_redis.shget(connection_id, self.id)
503
		if not self_channel_status:
504
			raise Exception("Access Denied")
505
		if self_channel_status != WebRtcRedisStates.CLOSED:
506
			sender_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
507
			if sender_id == self.id:
508
				self.close_file_sender(connection_id)
509
			else:
510
				self.close_file_receiver(connection_id, in_message, sender_id)
511
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.CLOSED)
512
513
	def close_call_connection(self, in_message):
514
		self.send_call_answer(
515
			in_message,
516
			WebRtcRedisStates.CLOSED,
517
			Actions.CLOSE_CALL_CONNECTION,
518
			[WebRtcRedisStates.READY, WebRtcRedisStates.RESPONDED],
519
			HandlerNames.PEER_CONNECTION
520
		)
521
522
	def cancel_call_connection(self, in_message):
523
		self.send_call_answer(
524
			in_message,
525
			WebRtcRedisStates.CLOSED,
526
			Actions.CANCEL_CALL_CONNECTION,
527
			[WebRtcRedisStates.OFFERED],
528
			HandlerNames.WEBRTC_TRANSFER
529
		)
530
531
	def close_file_receiver(self, connection_id, in_message, sender_id):
532
		sender_status = self.sync_redis.shget(connection_id, sender_id)
533
		if not sender_status:
534
			raise Exception("Access denied")
535
		if sender_status != WebRtcRedisStates.CLOSED:
536
			in_message[VarNames.WEBRTC_OPPONENT_ID] = self.id
537
			in_message[VarNames.HANDLER_NAME] = HandlerNames.PEER_CONNECTION
538
			self.publish(in_message, sender_id)
539
540
	def close_file_sender(self, connection_id):
541
		values = self.sync_redis.shgetall(connection_id)
542
		del values[self.id]
543
		message = self.get_close_file_sender_message(connection_id)
544
		for ws_id in values:
545
			if values[ws_id] == WebRtcRedisStates.CLOSED:
546
				continue
547
			self.publish(message, ws_id)
548
549
	def accept_file(self, in_message):
550
		connection_id = in_message[VarNames.CONNECTION_ID]
551
		content = in_message[VarNames.CONTENT]
552
		sender_ws_id = self.sync_redis.shget(WEBRTC_CONNECTION, connection_id)
553
		sender_ws_status = self.sync_redis.shget(connection_id, sender_ws_id)
554
		self_ws_status = self.sync_redis.shget(connection_id, self.id)
555
		if sender_ws_status == WebRtcRedisStates.READY \
556
				and self_ws_status in [WebRtcRedisStates.RESPONDED, WebRtcRedisStates.READY]:
557
			self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
558
			self.publish(self.get_accept_file_message(connection_id, content), sender_ws_id)
559
		else:
560
			raise ValidationError("Invalid channel status")
561
562
	# todo
563
	# we can use channel_status = self.sync_redis.shgetall(connection_id)
564
	# and then self.async_redis_publisher.hset(connection_id, self.id, WebRtcRedisStates.READY)
565
	# if we shgetall and only then do async hset
566
	# we can catch an issue when 2 concurrent users accepted the call
567
	# but we didn't  send them ACCEPT_CALL as they both were in status 'offered'
568
	def accept_call(self, in_message):
569
		connection_id = in_message[VarNames.CONNECTION_ID]
570
		self_status = self.sync_redis.shget(connection_id, self.id)
571
		if self_status == WebRtcRedisStates.RESPONDED:
572
			conn_users = self.sync_redis.shgetall(connection_id)
573
			self.publish_call_answer(
574
				conn_users,
575
				connection_id,
576
				HandlerNames.WEBRTC_TRANSFER,
577
				Actions.ACCEPT_CALL,
578
				WebRtcRedisStates.READY,
579
				{}
580
			)
581
		else:
582
			raise ValidationError("Invalid channel status")
583
584
	def send_call_answer(self, in_message, status_set, reply_action, allowed_state, message_handler):
585
		connection_id = in_message[VarNames.CONNECTION_ID]
586
		content = in_message[VarNames.CONTENT]
587
		conn_users = self.sync_redis.shgetall(connection_id)
588
		if conn_users[self.id] in allowed_state:
589
			self.publish_call_answer(conn_users, connection_id, message_handler, reply_action, status_set, content)
590
		else:
591
			raise ValidationError("Invalid channel status.")
592
593
	def publish_call_answer(self, conn_users, connection_id, message_handler, reply_action, status_set, content):
594
		self.async_redis_publisher.hset(connection_id, self.id, status_set)
595
		del conn_users[self.id]
596
		message = self.reply_webrtc(reply_action, connection_id, message_handler, content)
597
		for user in conn_users:
598
			if conn_users[user] != WebRtcRedisStates.CLOSED:
599
				self.publish(message, user)