Beispiel #1
0
 def post(self, request, *args, **kwargs):
     userId = self.request.user.id
     profile_pic = UserProfileInfo.objects.get(user=userId).profile_pic
     user_name = UserProfileInfo.objects.get(user=userId).user.username
     myModel = ChatLog.objects.all()
     message = request.POST['message']
     if message == '':
         return render(request, 'chat/chat.html', {'user_name': user_name, 'userid': userId, 'profile_pic': profile_pic,'myModel': myModel})
     else:
         timeis = timezone.now()
         newChat = ChatLog()
         newChat.profile_pic = UserProfileInfo.objects.get(user=userId).profile_pic
         newChat.timestamp = timeis
         newChat.message = message
         newChat.save()
         return render(request, 'chat/chat.html', {'user_name': user_name, 'userid': userId, 'profile_pic': profile_pic,'myModel': myModel})
Beispiel #2
0
    async def receive(self, text_data=None, bytes_data=None):
        # 接收参数
        text_data_json = json.loads(text_data) or {}
        message = text_data_json.get('message', '')
        if message == '': return
        msg_type = text_data_json.get('msg_type')
        action = text_data_json.get('action', '')
        song_index = text_data_json.get('song_index', None)
        now_song_id = text_data_json.get('now_song_id', None)
        send_user_nick_name = text_data_json.get('send_user_nick_name', '')

        send_time = datetime.now()

        # 房间类型
        # 机器人
        if self.room_type == 'ROBOT' and msg_type == 'chat_message':
            robot_msg, msg_type = talk_with_me(message)
            robot_user, _ = User.objects.get_or_create(username='******')
            robot_send_time = datetime.now()
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chat_message',
                    'message': robot_msg,
                    'user_id': 'robot',
                    'send_time': robot_send_time.strftime('%p %H:%M'),
                    'msg_type': msg_type,
                    'username': self.request_user.username
                })
            if message:
                # 与机器人聊天记录
                ChatLog.objects.create(chat_datetime=robot_send_time,
                                       content=message,
                                       msg_type=msg_type,
                                       who_said=self.request_user,
                                       said_to_id=self.request_user.id,
                                       said_to_room=self.chat_room_model)

                ChatLog.objects.create(chat_datetime=robot_send_time,
                                       content=robot_msg,
                                       msg_type=msg_type,
                                       who_said=robot_user,
                                       said_to_id=self.request_user.id,
                                       said_to_room=self.chat_room_model)
        # 普通的对话
        elif msg_type == 'chat_message':
            # Send message to room group 如果他人不在房间就单对单发通知
            if self.chat_room_model:
                # 房间成员
                menbers_list = self.chat_room_model.get_members_unicode_id()
                menbers_list = [str(i) for i in menbers_list]
                # 在线成员
                online_list = ChatCache(self.room_group_name).set_members()
                # 离线成员
                outline_list = set(menbers_list) - online_list
                print('成员人数:%s\n在线人数:%s\n离线人数:%s' %
                      (menbers_list, online_list, outline_list))
                # 离线发通知
                for ntf in outline_list:
                    await self.channel_layer.group_send(
                        'notification_%s' % (ntf), {
                            'type': 'push_message',
                            'msg_type': 'push_message',
                            'message': message,
                            'send_time': send_time.strftime('%p %H:%M'),
                            'channel_no': self.room_channel_no,
                            'user_id': str(self.request_user.id),
                            'send_user_nick_name': send_user_nick_name,
                        })
                if message:
                    queryset = []
                    for on in online_list:
                        queryset.append(
                            ChatLog(chat_datetime=send_time,
                                    content=message,
                                    msg_type=msg_type,
                                    who_said=self.request_user,
                                    said_to=User.objects.filter(
                                        profile__unicode_id=on).first(),
                                    said_to_room=self.chat_room_model,
                                    status='read'))
                    for out in outline_list:
                        queryset.append(
                            ChatLog(chat_datetime=send_time,
                                    content=message,
                                    msg_type=msg_type,
                                    who_said=self.request_user,
                                    said_to=User.objects.filter(
                                        profile__unicode_id=out).first(),
                                    said_to_room=self.chat_room_model,
                                    status='unread'))
                    ChatLog.objects.bulk_create(queryset)
                await self.channel_layer.group_send(
                    self.room_group_name, {
                        'type': 'chat_message',
                        'message': message,
                        'user_id': str(self.request_user.id),
                        'send_time': send_time.strftime('%p %H:%M'),
                        'msg_type': msg_type,
                    })
        elif msg_type == 'chat_info':
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chat_message',
                    'message': message,
                    'user_id': str(self.request_user.id),
                    'send_time': send_time.strftime('%p %H:%M'),
                    'msg_type': msg_type,
                })
        elif msg_type == 'chat_music':
            aplayer_data = []
            if 'init_data' in message:
                aplayer_data = MusicRobot().get_now_song_data_list()
                action = 'init_data'
                # 询问其他人进度
            elif '点歌' in message:
                message = message.replace('点歌', '', 1).strip()
                song_info = MusicRobot().pick_a_song(message)
                # 找不到歌曲,或歌曲已存在
                if not song_info:
                    action = 'tips'
                else:
                    aplayer_data = [song_info]
                    action = 'add_song'
            elif "切歌" in message:
                MusicRobot().switch_next_song(now_song_id)
                action = 'switch_next_song'
            elif action == 'reload_song_url':
                music_robot = MusicRobot()
                music_robot.del_song_data(now_song_id)
                new_song_url = music_robot.get_song_url(now_song_id)
                if not new_song_url:
                    action = 'tips'
                else:
                    message['url'] = new_song_url
                    music_robot.upload_song_data(now_song_id, message)
                    aplayer_data = [message]
            elif action == 'remove_song':
                MusicRobot().del_song_data(now_song_id)
                return
            elif action == 'ack_song_process':
                print('询问其他人播放进度')
            elif action == 'syn_song_process':
                print('回答自己歌曲播放进度', self.request_user.profile.nick_name,
                      message)
                # todo 改为自己的 return
                if float(message) < 1:
                    return
                aplayer_data = message
            elif action == 'quit_listen_song':
                print(message)
            elif action == 'update_song':
                MusicRobot().update_song_data_song_process(
                    now_song_id, 'song_process', message)
                return
            else:
                msg_type = 'chat_message'
                aplayer_data = message
            print('>>>当前歌单\n', aplayer_data)
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chat_message',
                    'message': aplayer_data,
                    'msg_type': msg_type,
                    'user_id': str(self.request_user.id),
                    'send_time': '',
                    'action': action,
                    'song_index': song_index,
                })
Beispiel #3
0
def chat_api(request):

    def get_ip():
        '''Get the requesting client's IP address'''
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def json_serializable_chat_log(latest_seen_message_id):
        messages = []
        if not latest_seen_message_id:
            message_records = list(ChatLog.messages.all())
        else:
            message_records = \
                    list(ChatLog.messages.filter(id__gt=latest_seen_message_id))
        for message in message_records:
            CEST_time = message.time_stamp + timedelta(seconds=2*60*60)
            CET_time = message.time_stamp + timedelta(seconds=1*60*60)
            #time_stamp = CEST_time.strftime('%H:%M')  # TODO: clientside fix
            #time_stamp = CET_time.strftime('%H:%M')  # TODO: clientside fix
            #time_stamp = message.time_stamp.strftime('%H:%M')  # TODO: clientside fix ... but somehow it already works??
            time_stamp = message.time_stamp.isoformat()
            messages.append({'time_stamp': time_stamp,
                             'message_string': message.message_string,
                             'author_name': message.author.name,
                             'message_id': message.id,
                             'message_class': message.message_class,
                             'concatenated_classes': \
                                     [c for c in message.concatenated_classes],
                            'previous_messages': [m.pk for m in message.
                                    n_previous_messages()]
                            })
        return messages

    def get_classifications(unclassified_messages):
        ''' Get classifications for messages in the given list (by id) '''
        if not unclassified_messages:
            return []
        message_records = \
                list(ChatLog.messages.filter(id__in=unclassified_messages).
                                      exclude(message_class='U'))
        single_classified = {}
        concatenated_classified = {}
        previous_messages = {}
        for message in message_records:
            single_classified[message.id] = message.message_class
            concatenated_classified[message.id] = message.concatenated_classes
            previous_messages[message.id] = \
                    [m.pk for m in message.n_previous_messages()]
        """
        For each message that is still unclassified, deliver
        - the classification of the single message,
        - the classifications of the concatenations with the previous messages
        - the ids of the previous messages from the same author with which the
            concatenataions were made
        given in a JSON object, organized by message_id as keys
        """
        result = {
                'single_classified': single_classified,
                'previous_messages': previous_messages,
                'concatenated_classified': concatenated_classified
                }
        return result

    # This is the server interface with which makes the site responsive
    if request.method == 'GET':
        if request.GET.get('type') == 'update_chat_log':

            latest_seen_message_id = request.GET.get('latest_seen_message_id')
            unclassified_messages = request.GET.get('unclassified_messages')
            unclassified_messages = ast.literal_eval(unclassified_messages)
            json_chat_log = json_serializable_chat_log(latest_seen_message_id)
            classified_messages = get_classifications(unclassified_messages)
            oldest = ChatLog.messages.order_by('id').first()
            oldest_message = None if oldest is None else oldest.id
            return HttpResponse(
                    json.dumps({'chat_log': json_chat_log,
                                'classified_messages': classified_messages,
                                'oldest_message': oldest_message})
                    )

        if request.GET.get('type') == 'full_update':

            client_author = Author.get_author(get_ip(), create=False)
            client_name = None if client_author is None else client_author.name
            json_chat_log = json_serializable_chat_log(None)
            oldest = ChatLog.messages.order_by('id').first()
            oldest_message = None if oldest is None else oldest.id
            return HttpResponse(json.dumps({'client_name': client_name,
                                            'chat_log': json_chat_log,
                                            'oldest_message': oldest_message}))
        else:
            logging.error(f'Invalid GET request: {request}')
    if request.method == 'POST':
        if 'message' in request.POST:
            author_name = ChatLog.log_message(
                    message_string=request.POST['message'], ip=get_ip())
            return HttpResponse(json.dumps({'client_name': author_name}))
        else:
            logging.error(f'Invalid POST request: {request}')

    return HttpResponse('Invalid request')
Beispiel #4
0
    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        msg_type = text_data_json['msg_type']
        send_user_nick_name = text_data_json.get('send_user_nick_name',
                                                 '') or ''
        chat_user = self.scope.get('user')
        send_time = datetime.now()
        # 机器人 加思知回复
        if self.room_name == 'GP_robot' and msg_type == 'chat_message':
            self.chat_room_model = ChatRoom.objects.filter(
                channel_no=self.room_name).first()
            robot_msg, chat_type = talk_with_me(message)
            robot_user, _ = User.objects.get_or_create(username='******')
            robot_send_time = datetime.now()
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chat_message',
                    'message': robot_msg,
                    'user_id': 'robot',
                    'send_time': robot_send_time.strftime('%p %H:%M'),
                    'msg_type': chat_type,
                    'username': self.scope.get('user').username
                })
            if message and chat_type == 'chat_message':
                ChatLog.objects.create(chat_datetime=robot_send_time,
                                       content=message,
                                       msg_type=msg_type,
                                       who_said=chat_user,
                                       said_to_id=chat_user.id,
                                       said_to_room=self.chat_room_model)

                ChatLog.objects.create(chat_datetime=robot_send_time,
                                       content=robot_msg,
                                       msg_type=msg_type,
                                       who_said=robot_user,
                                       said_to_id=chat_user.id,
                                       said_to_room=self.chat_room_model)
        elif msg_type == 'chat_message':
            self.chat_room_model = ChatRoom.objects.filter(
                channel_no=self.room_name).first()
            # Send message to room group 如果他人不在房间就单对单发通知
            if self.chat_room_model:
                menbers_list = self.chat_room_model.get_members_unicode_id()
                online_list = ChatCache().get_cache(self.room_group_name)
                outline_list = set(menbers_list) - online_list
                print('成员人数:%s\n在线人数:%s\n离线人数:%s' %
                      (menbers_list, online_list, outline_list))
                for ntf in outline_list:
                    await self.channel_layer.group_send(
                        'notification_%s' % (ntf), {
                            'type': 'push_message',
                            'message': message,
                            'user_id': str(chat_user.id),
                            'send_time': send_time.strftime('%p %H:%M'),
                            'msg_type': msg_type,
                            'channel_no': self.room_name,
                            'send_user_nick_name': send_user_nick_name,
                        })
                if message:
                    queryset = []
                    for on in online_list:
                        queryset.append(
                            ChatLog(chat_datetime=send_time,
                                    content=message,
                                    msg_type=msg_type,
                                    who_said=chat_user,
                                    said_to=User.objects.filter(
                                        profile__unicode_id=on).first(),
                                    said_to_room=self.chat_room_model,
                                    status='read'))
                    for out in outline_list:
                        queryset.append(
                            ChatLog(chat_datetime=send_time,
                                    content=message,
                                    msg_type=msg_type,
                                    who_said=chat_user,
                                    said_to=User.objects.filter(
                                        profile__unicode_id=out).first(),
                                    said_to_room=self.chat_room_model,
                                    status='unread'))
                    ChatLog.objects.bulk_create(queryset)
                await self.channel_layer.group_send(
                    self.room_group_name, {
                        'type': 'chat_message',
                        'message': message,
                        'user_id': str(chat_user.id),
                        'send_time': send_time.strftime('%p %H:%M'),
                        'msg_type': msg_type,
                    })
        elif msg_type == 'chat_info':
            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type': 'chat_message',
                    'message': message,
                    'user_id': str(chat_user.id),
                    'send_time': send_time.strftime('%p %H:%M'),
                    'msg_type': msg_type,
                })
Beispiel #5
0
def user_room(request):

    if (request.method == "POST"):
        #get userid variable
        user_id = request.GET.get('uuid', " ")

        #create form
        info_form = InfoForm(request.POST)
        if (info_form.is_valid()):

            #handle form data
            email = info_form.cleaned_data.get('email')
            name = info_form.cleaned_data.get('name')
            options = info_form.cleaned_data.get('request')
            options_string = ', '.join(options)

            #### UNCOMMENT THIS TO ENABLE SECURITY
            #if(not is_authorized(user_id,"member"):
            #    return HttpResponse('Unauthorized', status=401)

            volunteer_list = current_volunters()
            print(volunteer_list)

            volunteer_on_duty = False
            try:
                if (len(volunteer_list) != 0):
                    volunteer_on_duty = True
            except:
                volunteer_on_duty = False

            #see if user has already joined queue via email
            log_user = ChatLog.objects.filter(email=email).last()
            if (log_user):
                #get information from previous join.
                queue_user = log_user.queue
                if (queue_user):
                    queue_user.request = options_string
                    queue_user.save()

                    return render(
                        request, 'chat/user_room.html', {
                            'room_name': queue_user.room_id,
                            'chat': str(log_user.text),
                            'name': queue_user.username,
                            'helped': queue_user.helping,
                            'file_form': FileForm(),
                            'uuid': user_id,
                            'volunteer': volunteer_on_duty
                        })

            #Generate room id
            roomid = randint(1, 999)

            #make sure id is unique
            current_rooms = UserQueue.objects.filter(room_id=roomid)
            while (current_rooms):
                roomid = randint(1, 999)
                current_rooms = UserQueue.objects.filter(room_id=roomid)

            #add chat to log database
            log = ChatLog(username=name, request=options_string, email=email)
            log.save()

            #Add user to queue database
            queue = UserQueue(log_id=log.id,
                              username=name,
                              room_id=roomid,
                              request=options_string,
                              log=log)
            queue.save()

            log.queue = queue
            log.save()

            channel_layer = get_channel_layer()

            async_to_sync(channel_layer.group_send)(
                'select_refresh', {
                    'type': 'select_message',
                    'function': 'add',
                    'name': name,
                    'request': options_string,
                    'room_name': roomid,
                    'email': email,
                    'created': str(queue.created)
                })

            request.session['room_id'] = roomid

            return render(
                request, 'chat/user_room.html', {
                    'room_name': roomid,
                    'chat': str(log.text),
                    'name': name,
                    'file_form': FileForm(),
                    'uuid': user_id,
                    'volunteer': volunteer_on_duty
                })
        else:
            return render(request, 'chat/forms/user_info.html', {
                'info_form': info_form,
                'uuid': user_id
            })