Example #1
0
	def __init__(self, *args, **kwargs):
		self.closed_channels = None
		self.message_creator = WebRtcMessageCreator(None, None)
		super(MessagesHandler, self).__init__()
		self.webrtc_ids = {}
		self.id = None  # child init
		self.last_client_ping = 0
		self.user_id = 0  # anonymous by default
		self.ip = None
		from chat import global_redis
		self.async_redis_publisher = global_redis.async_redis_publisher
		self.sync_redis = global_redis.sync_redis
		self.channels = []
		self._logger = None
		self.async_redis = Client(host=REDIS_HOST, port=REDIS_PORT, selected_db=REDIS_DB)
		self.patch_tornadoredis()
		# input websocket messages handlers
		# The handler is determined by @VarNames.EVENT
		self.process_ws_message = {
			Actions.GET_MESSAGES: self.process_get_messages,
			Actions.GET_MESSAGES_BY_IDS: self.process_get_messages_by_ids,
			Actions.PRINT_MESSAGE: self.process_send_message,
			Actions.DELETE_ROOM: self.delete_room,
			Actions.EDIT_MESSAGE: self.edit_message,
			Actions.CREATE_ROOM: self.create_new_room,
			Actions.CREATE_CHANNEL: self.create_new_channel,
			Actions.SAVE_CHANNEL_SETTINGS: self.save_channels_settings,
			Actions.SAVE_ROOM_SETTINGS: self.save_room_settings,
			Actions.DELETE_CHANNEL: self.delete_channel,
			Actions.SET_USER_PROFILE: self.profile_save_user,
			Actions.SET_SETTINGS: self.profile_save_settings,
			Actions.INVITE_USER: self.invite_user,
			Actions.PING: self.respond_ping,
			Actions.PONG: self.process_pong_message,
			Actions.SEARCH_MESSAGES: self.search_messages,
			Actions.SYNC_HISTORY: self.sync_history,
			Actions.SHOW_I_TYPE: self.show_i_type,
		}
		# Handlers for redis messages, if handler returns true - message won't be sent to client
		# The handler is determined by @VarNames.EVENT
		self.process_pubsub_message = {
			Actions.CREATE_ROOM: self.send_client_new_channel,
			Actions.DELETE_ROOM: self.send_client_delete_channel,
			Actions.INVITE_USER: self.send_client_new_channel,
			Actions.ADD_INVITE: self.send_client_new_channel,
			Actions.PING: self.process_ping_message,
		}
Example #2
0
    def open(self):
        session_key = self.get_argument('sessionId', None)
        user_id = self.sync_redis.hget('sessions', session_key)
        if user_id is None:
            self.logger.warning('!! Session key %s has been rejected' %
                                session_key)
            self.close(403, "Session key %s has been rejected" % session_key)
            return
        self.user_id = int(user_id)
        self.ip = self.get_client_ip()
        user_db = UserProfile.objects.get(id=self.user_id)
        self.generate_self_id()
        self.message_creator = WebRtcMessageCreator(self.user_id, self.id)
        self._logger = logging.LoggerAdapter(parent_logger, {
            'id': self.id,
            'ip': self.ip
        })
        self.logger.debug("!! Incoming connection, session %s, thread hash %s",
                          session_key, self.id)
        self.async_redis.connect()
        self.async_redis_publisher.sadd(RedisPrefix.ONLINE_VAR, self.id)
        # since we add user to online first, latest trigger will always show correct online

        online = self.get_dict_users_from_redis()
        # current user is already online
        my_online = online.setdefault(self.user_id, [])
        if self.id not in my_online:
            my_online.append(self.id)

        was_online = len(online.get(
            self.user_id)) > 1  # if other tabs are opened
        user_rooms_query = Room.objects.filter(users__id=self.user_id, disabled=False) \
         .values('id', 'name', 'creator_id', 'channel_id', 'p2p', 'roomusers__notifications', 'roomusers__volume')
        room_users = [{
            VarNames.ROOM_ID: room['id'],
            VarNames.ROOM_NAME: room['name'],
            VarNames.CHANNEL_ID: room['channel_id'],
            VarNames.ROOM_CREATOR_ID: room['creator_id'],
            VarNames.NOTIFICATIONS: room['roomusers__notifications'],
            VarNames.P2P: room['p2p'],
            VarNames.VOLUME: room['roomusers__volume'],
            VarNames.ROOM_USERS: []
        } for room in user_rooms_query]
        user_rooms_dict = {room[VarNames.ROOM_ID]: room for room in room_users}
        channels_ids = [
            channel[VarNames.CHANNEL_ID] for channel in room_users
            if channel[VarNames.CHANNEL_ID]
        ]
        channels_db = Channel.objects.filter(Q(id__in=channels_ids)
                                             | Q(creator=self.user_id),
                                             disabled=False)
        channels = [{
            VarNames.CHANNEL_ID: channel.id,
            VarNames.CHANNEL_NAME: channel.name,
            VarNames.CHANNEL_CREATOR_ID: channel.creator_id
        } for channel in channels_db]
        room_ids = [room_id[VarNames.ROOM_ID] for room_id in room_users]
        rooms_users = RoomUsers.objects.filter(room_id__in=room_ids).values(
            'user_id', 'room_id')
        for ru in rooms_users:
            user_rooms_dict[ru['room_id']][VarNames.ROOM_USERS].append(
                ru['user_id'])
        # get all missed messages
        self.channels = room_ids  # py2 doesn't support clear()
        self.channels.append(self.channel)
        self.channels.append(self.id)
        self.listen(self.channels)
        # this was replaced to syncHistory method that's called from browser and passes existing ids
        # off_messages, history = self.get_offline_messages(room_users, was_online, self.get_argument('history', False))
        # for room in room_users:
        # 	room_id = room[VarNames.ROOM_ID]
        # 	h = history.get(room_id)
        # 	o = off_messages.get(room_id)
        # 	if h:
        # 		room[VarNames.LOAD_MESSAGES_HISTORY] = h
        # 	if o:
        # 		room[VarNames.LOAD_MESSAGES_OFFLINE] = o

        if settings.SHOW_COUNTRY_CODE:
            fetched_users = User.objects.annotate(user_c=Count('id')).values(
                'id', 'username', 'sex', 'userjoinedinfo__ip__country_code',
                'userjoinedinfo__ip__country', 'userjoinedinfo__ip__region',
                'userjoinedinfo__ip__city')
            user_dict = [
                RedisPrefix.set_js_user_structure_flag(
                    user['id'], user['username'], user['sex'],
                    user['userjoinedinfo__ip__country_code'],
                    user['userjoinedinfo__ip__country'],
                    user['userjoinedinfo__ip__region'],
                    user['userjoinedinfo__ip__city']) for user in fetched_users
            ]
        else:
            fetched_users = User.objects.values('id', 'username', 'sex')
            user_dict = [
                RedisPrefix.set_js_user_structure(user['id'], user['username'],
                                                  user['sex'])
                for user in fetched_users
            ]

        self.ws_write(
            self.message_creator.set_room(room_users, user_dict, online,
                                          user_db, channels))
        online_user_names_mes = self.message_creator.room_online_login(
            online, user_db.username, user_db.sex_str)
        self.logger.info('!! First tab, sending refresh online for all')
        self.publish(online_user_names_mes, settings.ALL_ROOM_ID)
        self.logger.info("!! User %s subscribes for %s", self.user_id,
                         self.channels)
        self.connected = True