Completed
Push — master ( cd5ef7...1da252 )
by Andrew
35s
created

MessagesHandler.send_message()   B

Complexity

Conditions 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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