Total Complexity | 78 |
Total Lines | 409 |
Duplicated Lines | 4.89 % |
Changes | 17 | ||
Bugs | 2 | Features | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex 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 |
||
248 | class MessagesHandler(MessagesCreator): |
||
249 | |||
250 | def __init__(self, *args, **kwargs): |
||
251 | self.parsable_prefix = 'p' |
||
252 | super(MessagesHandler, self).__init__(*args, **kwargs) |
||
253 | self.id = id(self) |
||
254 | self.ip = None |
||
255 | from chat import global_redis |
||
256 | self.async_redis_publisher = global_redis.async_redis_publisher |
||
257 | self.sync_redis = global_redis.sync_redis |
||
258 | self.channels = [] |
||
259 | self.call_receiver_channel = None |
||
260 | self._logger = None |
||
261 | self.async_redis = tornadoredis.Client() |
||
262 | self.pre_process_message = { |
||
263 | Actions.GET_MESSAGES: self.process_get_messages, |
||
264 | Actions.SEND_MESSAGE: self.process_send_message, |
||
265 | Actions.CALL: self.process_call, |
||
266 | Actions.CREATE_DIRECT_CHANNEL: self.create_user_channel, |
||
267 | Actions.DELETE_ROOM: self.delete_channel, |
||
268 | Actions.EDIT_MESSAGE: self.edit_message, |
||
269 | Actions.CREATE_ROOM_CHANNEL: self.create_new_room, |
||
270 | Actions.INVITE_USER: self.invite_user, |
||
271 | } |
||
272 | self.post_process_message = { |
||
273 | Actions.CREATE_DIRECT_CHANNEL: self.send_client_new_channel, |
||
274 | Actions.CREATE_ROOM_CHANNEL: self.send_client_new_channel, |
||
275 | Actions.DELETE_ROOM: self.send_client_delete_channel, |
||
276 | Actions.INVITE_USER: self.send_client_new_channel, |
||
277 | Actions.CALL: self.set_opponent_call_channel |
||
278 | } |
||
279 | |||
280 | @tornado.gen.engine |
||
281 | def listen(self, channels): |
||
282 | yield tornado.gen.Task( |
||
283 | self.async_redis.subscribe, channels) |
||
284 | self.async_redis.listen(self.new_message) |
||
285 | |||
286 | @property |
||
287 | def logger(self): |
||
288 | return self._logger if self._logger else base_logger |
||
289 | |||
290 | @tornado.gen.engine |
||
291 | def add_channel(self, channel): |
||
292 | self.channels.append(channel) |
||
293 | yield tornado.gen.Task( |
||
294 | self.async_redis.subscribe, (channel,)) |
||
295 | |||
296 | def do_db(self, callback, *args, **kwargs): |
||
297 | try: |
||
298 | return callback(*args, **kwargs) |
||
299 | except (OperationalError, InterfaceError) as e: # Connection has gone away |
||
300 | self.logger.warning('%s, reconnecting' % e) # TODO |
||
301 | connection.close() |
||
302 | return callback(*args, **kwargs) |
||
303 | |||
304 | def execute_query(self, query, *args, **kwargs): |
||
305 | cursor = connection.cursor() |
||
306 | cursor.execute(query, *args, **kwargs) |
||
307 | return cursor.fetchall() |
||
308 | |||
309 | def get_online_from_redis(self, channel, check_user_id=None, check_hash=None): |
||
310 | """ |
||
311 | :rtype : dict |
||
312 | returns (dict, bool) if check_type is present |
||
313 | """ |
||
314 | online = self.sync_redis.hgetall(channel) |
||
315 | self.logger.debug('!! channel %s redis online: %s', channel, online) |
||
316 | result = set() |
||
317 | user_is_online = False |
||
318 | # redis stores REDIS_USER_FORMAT, so parse them |
||
319 | if online: |
||
320 | for key_hash, raw_user_id in online.items(): # py2 iteritems |
||
321 | user_id = int(raw_user_id.decode('utf-8')) |
||
322 | if user_id == check_user_id and check_hash != int(key_hash.decode('utf-8')): |
||
323 | user_is_online = True |
||
324 | result.add(user_id) |
||
325 | result = list(result) |
||
326 | return (result, user_is_online) if check_user_id else result |
||
327 | |||
328 | def add_online_user(self, room_id, offline_messages=None): |
||
329 | """ |
||
330 | adds to redis |
||
331 | online_users = { connection_hash1 = stored_redis_user1, connection_hash_2 = stored_redis_user2 } |
||
332 | :return: |
||
333 | """ |
||
334 | self.async_redis_publisher.hset(room_id, self.id, self.stored_redis_user) |
||
335 | # since we add user to online first, latest trigger will always show correct online |
||
336 | online, is_online = self.get_online_from_redis(room_id, self.user_id, self.id) |
||
337 | if not is_online: # if a new tab has been opened |
||
338 | online.append(self.user_id) |
||
339 | online_user_names_mes = self.room_online( |
||
340 | online, |
||
341 | Actions.LOGIN, |
||
342 | room_id |
||
343 | ) |
||
344 | self.logger.info('!! First tab, sending refresh online for all') |
||
345 | self.publish(online_user_names_mes, room_id) |
||
346 | if offline_messages: |
||
347 | self.safe_write(self.load_offline_message(offline_messages, room_id)) |
||
348 | else: # Send user names to self |
||
349 | online_user_names_mes = self.room_online( |
||
350 | online, |
||
351 | Actions.REFRESH_USER, |
||
352 | room_id |
||
353 | ) |
||
354 | self.logger.info('!! Second tab, retrieving online for self') |
||
355 | self.safe_write(online_user_names_mes) |
||
356 | |||
357 | def publish(self, message, channel, parsable=False): |
||
358 | jsoned_mess = json.dumps(message) |
||
359 | self.logger.debug('<%s> %s', channel, jsoned_mess) |
||
360 | if parsable: |
||
361 | jsoned_mess = self.encode(jsoned_mess) |
||
362 | self.async_redis_publisher.publish(channel, jsoned_mess) |
||
363 | |||
364 | def encode(self, message): |
||
365 | """ |
||
366 | Marks message with prefix to specify that |
||
367 | it should be decoded and proccesed before sending to client |
||
368 | @param message: message to mark |
||
369 | @return: marked message |
||
370 | """ |
||
371 | return self.parsable_prefix + message |
||
372 | |||
373 | def decode(self, message): |
||
374 | """ |
||
375 | Check if message should be proccessed by server before writing to client |
||
376 | @param message: message to check |
||
377 | @type message: str |
||
378 | @return: Object structure of message if it should be processed, None if not |
||
379 | """ |
||
380 | if message.startswith(self.parsable_prefix): |
||
381 | return json.loads(message[1:]) |
||
382 | |||
383 | def new_message(self, message): |
||
384 | data = message.body |
||
385 | if isinstance(data, str_type): # subscribe event |
||
386 | decoded = self.decode(data) |
||
387 | if decoded: |
||
388 | data = decoded |
||
389 | self.safe_write(data) |
||
390 | if decoded: |
||
391 | self.post_process_message[decoded[VarNames.EVENT]](decoded) |
||
392 | |||
393 | def safe_write(self, message): |
||
394 | raise NotImplementedError('WebSocketHandler implements') |
||
395 | |||
396 | def process_send_message(self, message): |
||
397 | """ |
||
398 | :type message: dict |
||
399 | """ |
||
400 | channel = message[VarNames.CHANNEL] |
||
401 | message_db = Message( |
||
402 | sender_id=self.user_id, |
||
403 | content=message[VarNames.CONTENT] |
||
404 | ) |
||
405 | message_db.room_id = channel |
||
406 | if VarNames.IMG in message: |
||
407 | message_db.img = extract_photo(message[VarNames.IMG]) |
||
408 | self.do_db(message_db.save) # exit on hacked id with exception |
||
409 | prepared_message = self.create_send_message(message_db) |
||
410 | self.publish(prepared_message, channel) |
||
411 | |||
412 | def process_call(self, in_message): |
||
413 | """ |
||
414 | :type in_message: dict |
||
415 | """ |
||
416 | call_type = in_message.get(VarNames.CALL_TYPE) |
||
417 | set_opponent_channel = False |
||
418 | out_message = self.offer_call(in_message.get(VarNames.CONTENT), call_type) |
||
419 | if call_type == CallType.OFFER: |
||
420 | room_id = in_message[VarNames.CHANNEL] |
||
421 | user = User.rooms.through.objects.get(~Q(user_id=self.user_id), Q(room_id=room_id), Q(room__name__isnull=True)) |
||
422 | self.call_receiver_channel = RedisPrefix.generate_user(user.user_id) |
||
423 | set_opponent_channel = True |
||
424 | out_message[VarNames.CHANNEL] = room_id |
||
425 | # TODO |
||
426 | self.logger.info('!! Offering a call to user with id %s', self.call_receiver_channel) |
||
427 | self.publish(out_message, self.call_receiver_channel, set_opponent_channel) |
||
428 | |||
429 | def create_new_room(self, message): |
||
430 | room_name = message[VarNames.ROOM_NAME] |
||
431 | if not room_name or len(room_name) > 16: |
||
432 | raise ValidationError('Incorrect room name "{}"'.format(room_name)) |
||
433 | room = Room(name=room_name) |
||
434 | self.do_db(room.save) |
||
435 | RoomUsers(room_id=room.id, user_id=self.user_id).save() |
||
436 | subscribe_message = self.subscribe_room_channel_message(room.id, room_name) |
||
437 | self.publish(subscribe_message, self.channel, True) |
||
438 | |||
439 | def invite_user(self, message): |
||
440 | room_id = message[VarNames.ROOM_ID] |
||
441 | user_id = message[VarNames.USER_ID] |
||
442 | if room_id not in self.channels: |
||
443 | raise ValidationError("Access denied, only allowed for channels {}".format(self.channels)) |
||
444 | room = self.do_db(Room.objects.get, id=room_id) |
||
445 | if room.is_private: |
||
446 | raise ValidationError("You can't add users to direct room, create a new room instead") |
||
447 | try: |
||
448 | Room.users.through.objects.create(room_id=room_id, user_id=user_id) |
||
449 | except IntegrityError: |
||
450 | raise ValidationError("User is already in channel") |
||
451 | users_in_room = {} |
||
452 | for user in room.users.all(): |
||
453 | self.set_js_user_structure(users_in_room, user.id, user.username, user.sex) |
||
454 | self.publish(self.add_user_to_room(room_id, user_id, users_in_room[user_id]), room_id) |
||
455 | subscribe_message = self.invite_room_channel_message(room_id, user_id, room.name, users_in_room) |
||
456 | self.publish(subscribe_message, RedisPrefix.generate_user(user_id), True) |
||
457 | View Code Duplication | ||
|
|||
458 | def create_self_room(self, user_rooms): |
||
459 | rooms_ids = list([room['room_id'] for room in user_rooms]) |
||
460 | query_res = self.execute_query(SELECT_SELF_ROOM, [rooms_ids,]) |
||
461 | if len(query_res) > 0: |
||
462 | room = query_res[0] |
||
463 | room_id = room[0] |
||
464 | self.update_room(room_id, room[1]) |
||
465 | else: |
||
466 | room = Room() |
||
467 | room.save() |
||
468 | room_id = room.id |
||
469 | RoomUsers(user_id=self.user_id, room_id=room_id).save() |
||
470 | View Code Duplication | return room_id |
|
471 | |||
472 | def create_other_room(self, user_rooms, user_id): |
||
473 | query_res = Room.users.through.objects.filter(user_id=user_id, room__in=user_rooms).values('room__id', 'room__disabled') |
||
474 | if len(query_res) > 0: |
||
475 | room = query_res[0] |
||
476 | room_id = room['room__id'] |
||
477 | self.update_room(room_id, room['room__disabled']) |
||
478 | else: |
||
479 | room = Room() |
||
480 | room.save() |
||
481 | room_id = room.id |
||
482 | RoomUsers.objects.bulk_create([ |
||
483 | RoomUsers(user_id=user_id, room_id=room_id), |
||
484 | RoomUsers(user_id=self.user_id, room_id=room_id), |
||
485 | ]) |
||
486 | return room_id |
||
487 | |||
488 | def update_room(self, room_id, disabled): |
||
489 | if not disabled: |
||
490 | raise ValidationError('This room already exist') |
||
491 | else: |
||
492 | Room.objects.filter(id=room_id).update(disabled=False) |
||
493 | |||
494 | def create_user_channel(self, message): |
||
495 | user_id = message[VarNames.USER_ID] |
||
496 | # get all self private rooms ids |
||
497 | user_rooms = Room.users.through.objects.filter(user_id=self.user_id, room__name__isnull=True).values('room_id') |
||
498 | # get private room that contains another user from rooms above |
||
499 | if self.user_id == user_id: |
||
500 | room_id = self.create_self_room(user_rooms) |
||
501 | else: |
||
502 | room_id = self.create_other_room(user_rooms, user_id) |
||
503 | subscribe_message = self.subscribe_direct_channel_message(room_id, user_id) |
||
504 | self.publish(subscribe_message, self.channel, True) |
||
505 | other_channel = RedisPrefix.generate_user(user_id) |
||
506 | if self.channel != other_channel: |
||
507 | self.publish(subscribe_message, other_channel, True) |
||
508 | |||
509 | def delete_channel(self, message): |
||
510 | room_id = message[VarNames.ROOM_ID] |
||
511 | if room_id not in self.channels or room_id == ALL_ROOM_ID: |
||
512 | raise ValidationError('You are not allowed to exit this room') |
||
513 | room = self.do_db(Room.objects.get, id=room_id) |
||
514 | if room.disabled: |
||
515 | raise ValidationError('Room is already deleted') |
||
516 | if room.name is None: # if private then disable |
||
517 | room.disabled = True |
||
518 | else: # if public -> leave the room, delete the link |
||
519 | RoomUsers.objects.filter(room_id=room.id, user_id=self.user_id).delete() |
||
520 | online = self.get_online_from_redis(room_id) |
||
521 | online.remove(self.user_id) |
||
522 | self.publish(self.room_online(online, Actions.LOGOUT, room_id), room_id) |
||
523 | room.save() |
||
524 | message = self.unsubscribe_direct_message(room_id) |
||
525 | self.publish(message, room_id, True) |
||
526 | |||
527 | def edit_message(self, data): |
||
528 | message_id = data[VarNames.MESSAGE_ID] |
||
529 | message = Message.objects.get(id=message_id) |
||
530 | if message.sender_id != self.user_id: |
||
531 | raise ValidationError("You can only edit your messages") |
||
532 | if message.time + 60000 < get_milliseconds(): |
||
533 | raise ValidationError("You can only edit messages that were send not more than 1 min ago") |
||
534 | if message.deleted: |
||
535 | raise ValidationError("Already deleted") |
||
536 | message.content = data[VarNames.CONTENT] |
||
537 | selector = Message.objects.filter(id=message_id) |
||
538 | if message.content is None: |
||
539 | selector.update(deleted=True) |
||
540 | action = Actions.DELETE_MESSAGE |
||
541 | else: |
||
542 | action = Actions.EDIT_MESSAGE |
||
543 | selector.update(content=message.content) |
||
544 | self.publish(self.create_send_message(message, action), message.room_id) |
||
545 | |||
546 | def send_client_new_channel(self, message): |
||
547 | room_id = message[VarNames.ROOM_ID] |
||
548 | self.add_channel(room_id) |
||
549 | self.add_online_user(room_id) |
||
550 | |||
551 | def set_opponent_call_channel(self, message): |
||
552 | self.call_receiver_channel = RedisPrefix.generate_user(message[VarNames.USER_ID]) |
||
553 | |||
554 | def send_client_delete_channel(self, message): |
||
555 | room_id = message[VarNames.ROOM_ID] |
||
556 | self.async_redis.unsubscribe((room_id,)) |
||
557 | self.async_redis_publisher.hdel(room_id, self.id) |
||
558 | self.channels.remove(room_id) |
||
559 | |||
560 | def process_get_messages(self, data): |
||
561 | """ |
||
562 | :type data: dict |
||
563 | """ |
||
564 | header_id = data.get(VarNames.GET_MESSAGES_HEADER_ID, None) |
||
565 | count = int(data.get(VarNames.GET_MESSAGES_COUNT, 10)) |
||
566 | room_id = data[VarNames.CHANNEL] |
||
567 | self.logger.info('!! Fetching %d messages starting from %s', count, header_id) |
||
568 | if header_id is None: |
||
569 | messages = Message.objects.filter(Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count] |
||
570 | else: |
||
571 | messages = Message.objects.filter(Q(id__lt=header_id), Q(room_id=room_id), Q(deleted=False)).order_by('-pk')[:count] |
||
572 | response = self.do_db(self.get_messages, messages, room_id) |
||
573 | self.safe_write(response) |
||
574 | |||
575 | def get_offline_messages(self): |
||
576 | res = {} |
||
577 | offline_messages = Message.objects.filter( |
||
578 | id__gt=F('room__roomusers__last_read_message_id'), |
||
579 | deleted=False, |
||
580 | room__roomusers__user_id=self.user_id |
||
581 | ) |
||
582 | for message in offline_messages: |
||
583 | res.setdefault(message.room_id, []).append(self.create_message(message)) |
||
584 | return res |
||
585 | |||
586 | def get_users_in_current_user_rooms(self): |
||
587 | """ |
||
588 | { |
||
589 | "ROOM_ID:1": { |
||
590 | "name": "All", |
||
591 | "users": { |
||
592 | "USER_ID:admin": { |
||
593 | "name": "USER_NAME:admin", |
||
594 | "sex": "SEX:Secret" |
||
595 | }, |
||
596 | "USER_ID_2": { |
||
597 | "name": "USER_NAME:Mike", |
||
598 | "sex": "Male" |
||
599 | } |
||
600 | }, |
||
601 | "isPrivate": true |
||
602 | } |
||
603 | } |
||
604 | """ |
||
605 | user_rooms = Room.objects.filter(users__id=self.user_id, disabled=False).values('id', 'name') |
||
606 | res = {room['id']: { |
||
607 | VarNames.ROOM_NAME: room['name'], |
||
608 | VarNames.ROOM_USERS: {} |
||
609 | } for room in user_rooms} |
||
610 | room_ids = (room_id for room_id in res) |
||
611 | rooms_users = User.objects.filter(rooms__in=room_ids).values('id', 'username', 'sex', 'rooms__id') |
||
612 | for user in rooms_users: |
||
613 | self.set_js_user_structure(res[user['rooms__id']][VarNames.ROOM_USERS], user['id'], user['username'], user['sex']) |
||
614 | return res |
||
615 | |||
616 | def set_js_user_structure(self, user_dict, user_id, name, sex): |
||
617 | user_dict[user_id] = { |
||
618 | VarNames.USER: name, |
||
619 | VarNames.GENDER: GENDERS[sex] |
||
620 | } |
||
621 | |||
622 | def save_ip(self): |
||
623 | if (self.do_db(UserJoinedInfo.objects.filter( |
||
624 | Q(ip__ip=self.ip) & Q(user_id=self.user_id)).exists)): |
||
625 | return |
||
626 | ip_address = self.get_or_create_ip() |
||
627 | UserJoinedInfo.objects.create( |
||
628 | ip=ip_address, |
||
629 | user_id=self.user_id |
||
630 | ) |
||
631 | |||
632 | def get_or_create_ip(self): |
||
633 | try: |
||
634 | ip_address = IpAddress.objects.get(ip=self.ip) |
||
635 | except IpAddress.DoesNotExist: |
||
636 | try: |
||
637 | if not api_url: |
||
638 | raise Exception('api url is absent') |
||
639 | self.logger.debug("Creating ip record %s", self.ip) |
||
640 | f = urlopen(api_url % self.ip) |
||
641 | raw_response = f.read().decode("utf-8") |
||
642 | response = json.loads(raw_response) |
||
643 | if response['status'] != "success": |
||
644 | raise Exception("Creating iprecord failed, server responded: %s" % raw_response) |
||
645 | ip_address = IpAddress.objects.create( |
||
646 | ip=self.ip, |
||
647 | isp=response['isp'], |
||
648 | country=response['country'], |
||
649 | region=response['regionName'], |
||
650 | city=response['city'], |
||
651 | country_code=response['countryCode'] |
||
652 | ) |
||
653 | except Exception as e: |
||
654 | self.logger.error("Error while creating ip with country info, because %s", e) |
||
655 | ip_address = IpAddress.objects.create(ip=self.ip) |
||
656 | return ip_address |
||
657 | |||
801 |