def execute(self, message, message_data):
        print(message_data)
        to_return = {'intent:': self.name, 'success': False, 'error': None}
        if 'conversation_id' in message_data:
            conversation_id = message_data['conversation_id']
            result = Conversation.objects.filter(id=conversation_id)
            if result.count() != 0:
                conv = result.first()
                if message.user in conv.participants.all():
                    to_return['success'] = True
                    new_message = Message()
                    new_message.content = message_data['content']
                    new_message.conversation = conv
                    new_message.from_user = message.user
                    new_message.save()
                    unixtime = time.mktime(new_message.date_sent.timetuple())
                    for p in conv.participants.all():
                        Group("chat-%s" % p.username).send({
                            "text": json.dumps({"intent": "receive_message", "conversation_id": conversation_id, "content": message_data['content'], "date_sent": unixtime, "username": new_message.from_user.username})
                        })
                else:
                    to_return['error'] = "You do not have access to this conversation."

        elif 'username' in message_data:
            recipient_username = message_data['username']
            if recipient_username in get_friends(message.user) and recipient_username != message.user.username:
                to_return['success'] = True
                recipient = User.objects.get(username=recipient_username)
                conv = Conversation()
                conv.save()
                conv.participants.add(recipient)
                conv.participants.add(message.user)
                new_message = Message()
                new_message.content = message_data['content']
                new_message.conversation = conv
                new_message.from_user = message.user
                new_message.save()
                conv.save()
                print(new_message.date_sent)
                unixtime = time.mktime(new_message.date_sent.timetuple())
                for p in conv.participants.all():
                    print(("chat-%s" % p.username))
                    Group("chat-%s" % p.username).send({
                        "text": json.dumps({"intent": "receive_message", "conversation_id": conv.id, "content": message_data['content'], "date_sent": unixtime, "username": message.from_user.username})
                    })
            else:
                to_return['error'] = "You cannot speak with this user as you are not friends with the user."
        else:
            to_return['error'] = "You appear to have sent a malformed request."

        Group("chat-%s" % message.user.username).send({
            "text": json.dumps(to_return)
        })
Esempio n. 2
0
def chat_with(request, name):
    user = request.user
    try:
        friend = ChatUser.objects.get(username=name)
    except ObjectDoesNotExist:
        return HttpResponseRedirect(reverse('chat.views.contacts'))
    if not friend in user.friend_list.all():
        return HttpResponseRedirect(reverse('chat.views.contacts'))
    messages_unread = Message.objects.filter(to_user=user,
                                             from_user=friend,
                                             is_read=False)
    for mes in messages_unread:
        mes.is_read = True
        mes.save()
    if request.method == 'POST':
        post = request.POST

        m = Message(message=post['message'],
                    from_user=user,
                    to_user=friend,
                    datetime=datetime.datetime.today())
        m.save()
    messages = Message.objects.filter(to_user=friend, from_user=user) |\
               Message.objects.filter(to_user=user, from_user=friend)

    return render(request, 'chat/chat.html', {
        'user': user,
        'friend': friend,
        'messages': messages
    })
Esempio n. 3
0
    async def get(self):
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        # session = await get_session(self.request)
        # user = User(self.request.db, {'id': session.get('user')})
        # login = await user.get_login()

        # for _ws in self.request.app['websockets']:
        #     _ws.send_str('%s joined' % login)
        login = self.request.login
        self.request.app['websockets'].append(ws)

        async for msg in ws:
            if msg.type == WSMsgType.TEXT:
                if msg.data == 'close':
                    await ws.close()
                else:
                    for _ws in self.request.app['websockets']:
                        mongo = Message(self.request.app['mongo']['test_collection'])
                        r = await mongo.save(user='******', msg=msg.data)
                        await _ws.send_json(r)
            elif msg.type == WSMsgType.ERROR:
                print('ws connection closed with exception %s' %
                      ws.exception())

        self.request.app['websockets'].remove(ws)

        return ws
Esempio n. 4
0
    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        from_user = text_data_json['from']
        to_user = text_data_json['to']

        ms = Message(message=message,
                     from_user_id=from_user,
                     to_user_id=to_user)
        ms.save()

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name, {
                'type': 'chat_message',
                'message': message,
                'message_id': ms.id,
                'from_user': from_user,
                'to_user': to_user,
                'time': ms.time.strftime("%H:%m")
            })
        await self.channel_layer.group_send(self.receiver_notificator, {
            'type': 'notificator_update',
            'user': from_user,
        })
Esempio n. 5
0
    def receive(self, text_data):
        text_data_json = json.loads(text_data)

        content = text_data_json.get('content')
        room_pk = text_data_json.get('room_id')
        user_pk = text_data_json.get('user_id')

        match = re.match(r'^/stock=([A-Z]*)$', content)

        if match:
            tasks.query_quote.delay(match.group(1), room_pk)
        else:
            room = Room.objects.get(pk=room_pk)
            user = User.objects.get(pk=user_pk)

            message = Message()
            message.content = content
            message.room = room
            message.user = user
            message.save()

            datetime = message.datetime.isoformat()
            user_name = user.username

            async_to_sync(self.channel_layer.group_send)(self.group_name, {
                'type': 'send_message',
                'datetime': datetime,
                'content': content,
                'room_pk': room_pk,
                'user_pk': user_pk,
                'user_name': user_name
            })
Esempio n. 6
0
    def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
        # TODO implement Stack-like interface
        answers_stack = chat.state.get_data_attr('answers_stack')
        if answers_stack:
            answer = answers_stack.pop()
            chat.state.set_data_attr('answers_stack', answers_stack)
            chat.state.save_json_data()

        if waffle.switch_is_active('compound_faq_answer'):
            text1 = md2html(f'Here\'s my answer to your question \"{answer.get("faq_title")}\"')
            text2 = md2html(answer.get('text'))
            text = text1 + text2
        else:
            text = answer.get('text')

        _data = {
            'chat': chat,
            'text': mark_safe(text),
            'owner': chat.user,
            'input_type': 'options',
            'kind': 'button',
            'is_additional': is_additional
        }
        message = Message(**_data)
        message.save()
        return message
    def setUp(self):

        self.user = User.objects.create(name='User Test',
                                        email='*****@*****.**',
                                        sex='M',
                                        phone='1111111111',
                                        is_active=True)

        self.user2 = User.objects.create(name='User2 Test',
                                         email='*****@*****.**',
                                         sex='M',
                                         phone='1111111111',
                                         is_active=True)

        self.view = MessageDetailView()
        self.view_class = MessageDetailView
        self.factory = RequestFactory()
        self.client = Client()
        # Create Message.

        self.response = Response()
        self.response.user_from = self.user
        self.response.user_to = self.user2
        self.response.save()

        # Create Message.
        self.message = Message()
        self.message.text = "meu texto"
        self.message.subject = "Assunto"
        self.message.user_from = self.user
        self.message.user_to = self.user
        self.message.pk = 1
        self.message.messages.add(self.response)
        self.message.save()
Esempio n. 8
0
    def insert_message(room_name, message, user):
        room = Room.objects.get(name=room_name)

        m = Message(room=room, message=message, user=user)
        m.save()

        return m
    def setUp(self):

        self.health_professional = HealthProfessional.objects.create(name='User Test',
                                                                     email='*****@*****.**',
                                                                     sex='M',
                                                                     phone='1111111111',
                                                                     is_active=True)
        self.patient = Patient.objects.create(name='User Test',
                                              email='*****@*****.**',
                                              sex='M',
                                              phone='1111111111',
                                              is_active=True)

        self.view = SentMessageDetailView()
        self.view_class = SentMessageDetailView
        self.factory = RequestFactory()
        self.client = Client()

        self.response = Response()
        self.response.user_from = self.health_professional
        self.response.user_to = self.patient
        self.response.save()

        # Create Message.
        self.message = Message()
        self.message.text = "meu texto"
        self.message.subject = "Assunto"
        self.message.user_from = self.health_professional
        self.message.user_to = self.patient
        self.message.pk = 1
        self.message.messages.add(self.response)
        self.message.save()
Esempio n. 10
0
 def save(self, sender, parent_msg=None):
     recipients = self.friends_list
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = timezone.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied",
                                   {'message': msg})
                 notification.send([r], "messages_reply_received",
                                   {'message': msg})
             else:
                 notification.send([sender], "messages_sent",
                                   {'message': msg})
                 notification.send([r], "messages_received",
                                   {'message': msg})
     return message_list
Esempio n. 11
0
 def handle(self, *args, **options):
     if options['room'] and options['from'] and options['text']:
         msg = Message()
         msg.room = options['room']
         msg.sender = options['from']
         msg.content = options['text']
         msg.save()
Esempio n. 12
0
def upload_file(request, user_id):

    if request.is_ajax():
        if request.method == 'POST':
            files = request.FILES
            attached_file = files.get('file')
            if not attached_file:
                return JsonResponse({'detail': 'File not found'}, status=400)
            msg = Message(sender=request.user, receiver_id=user_id, text='')
            msg.save()
            attch = Attachment(message=msg,
                               file=attached_file,
                               name=attached_file.name)
            attch.save()
            return JsonResponse(
                {
                    'id': msg.id,
                    'message': msg.text,
                    'filename': attached_file.name,
                    'url': attch.file.url,
                    'date': attch.date,
                },
                status=200)
        else:
            return JsonResponse({'detail': 'Bad request'}, status=400)
    else:
        return JsonResponse({'detail': 'Bad request'}, status=400)
Esempio n. 13
0
    async def get(self):
        """
        Initialize websocket connection and handle all received messages.

        """
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)
        chat_id = int(self.request.match_info.get('chat_id'))
        async for msg in ws:
            if msg.type == web.WSMsgType.TEXT:
                if msg.data == 'close':
                    await ws.close()
                else:
                    message = Message(
                        message_id=await
                        get_next_sequence_value(self.request.app['db'],
                                                "message_id"),
                        chat_id=chat_id,
                        from_user=1,
                        to_user=2,
                        date=datetime.now().strftime("%Y.%m.%d - %H:%M:%S"),
                        text=msg.data)
                    await self.request.app['db'].messages.insert_one(
                        message.to_dict())
                    await self.request.app['db'].chats.update_one(
                        {'chat_id': message.chat_id},
                        {'$push': {
                            'messages': message.message_id
                        }})
                    await ws.send_json(message.to_dict())
Esempio n. 14
0
    def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
        _response_data = {
            'lesson': chat.state.unitLesson.lesson,
            'unitLesson': chat.state.unitLesson,
            'course': chat.enroll_code.courseUnit.course,
            'author': chat.user,
            'activity': chat.state.activity,
            'is_test': chat.is_test,
            'is_preview': chat.enroll_code.isPreview,
            'is_trial': chat.is_trial,
        }
        resp = Response(**_response_data)
        resp.save()

        _data = {
            'contenttype': 'response',
            'content_id': resp.id,
            'input_type': 'options',
            # This is needed to track the last response to handle status
            'lesson_to_answer_id': chat.state.unitLesson.id,
            'chat': chat,
            'owner': chat.user,
            'kind': 'response',
            'userMessage': True,
            'is_additional': is_additional
        }
        message = Message(**_data)
        message.save()
        return message
Esempio n. 15
0
    async def get(self):
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        user = self.request.user

        for _ws in self.request.app['websockets']:
            await _ws.send_str('%s joined' % user.login)
        self.request.app['websockets'].append(ws)

        async for msg in ws:
            if msg.type == WSMsgType.TEXT:
                if msg.data == 'close':
                    await ws.close()

                else:
                    try:
                        message = Message(message=msg.data, user_id=user)
                        await message.commit()
                    except ValidationError as e:
                        print(e)
                    for _ws in self.request.app['websockets']:
                        await _ws.send_str('{"user": "******", "msg": "%s"}' %
                                           (user.login, msg.data))
            elif msg.type == WSMsgType.ERROR:
                log.debug('ws connection closed with exception %s' %
                          ws.exception())

        self.request.app['websockets'].remove(ws)
        for _ws in self.request.app['websockets']:
            await _ws.send_str('%s disconected' % user.login)
        log.debug('websocket connection closed')

        return ws
Esempio n. 16
0
def index(request):
    if request.method == "GET":
        lastSeenId = int(request.GET.get('lastSeenId', '0'))
        messages = Message.objects.all().filter(
            id__gt=lastSeenId).order_by('id')

        POPMessages = map(
            lambda m: {
                'id': m.id,
                'sender': m.sender,
                'body': m.body
            }, messages[0:1000])
        return JsonResponse({'messages': list(POPMessages)})
    if request.method == "POST":
        sender = request.POST.get('sender', None)
        body = request.POST.get('body', None)
        if sender is None or body is None:
            return JsonResponse("Sender and Body are required fields",
                                status=400)
        message = Message(sender=sender, body=body)
        message.save()

        # Limit total messages
        messages = Message.objects.all().order_by('id')
        count = messages.count()
        diff = count - settings.CHAT_MAX_MESSAGES
        if diff > 0:
            for i in range(diff):
                message = messages[0]
                message.delete()

        return JsonResponse({'status': 'Ok'})
Esempio n. 17
0
    def setUp(self):

        # Create Patient.
        self.patient = Patient.objects.create(name='Paciente',
                                              phone='1111111111',
                                              email='*****@*****.**')
        self.patient.save()

        self.professional = HealthProfessional.objects.create(
            name='Heatlh',
            crm='12345',
            email='*****@*****.**',
            sex='M',
            is_active=True)
        self.professional.save()

        self.view = ArchiveBoxPatientView()
        self.factory = RequestFactory()

        # Create Message.
        self.message = Message()
        self.message.text = "meu texto"
        self.message.subject = "Assunto"
        self.message.user_from = self.patient
        self.message.is_active_patient = False
        self.message.user_to = self.professional
        self.message.save()
Esempio n. 18
0
 def send_message(message, giphy=None):
     if message[VarNames.TIME_DIFF] < 0:
         raise ValidationError("Back to the future?")
     files = UploadedFile.objects.filter(id__in=message.get(
         VarNames.FILES),
                                         user_id=self.user_id)
     symbol = get_max_key(files)
     channel = message[VarNames.ROOM_ID]
     js_id = message[VarNames.JS_MESSAGE_ID]
     message_db = Message(sender_id=self.user_id,
                          content=message[VarNames.CONTENT],
                          symbol=symbol,
                          giphy=giphy,
                          room_id=channel)
     message_db.time -= message[VarNames.TIME_DIFF]
     res_files = []
     message_db.save()
     if files:
         images = up_files_to_img(files, message_db.id)
         res_files = MessagesCreator.prepare_img_video(
             images, message_db.id)
     prepared_message = self.create_send_message(
         message_db,
         Actions.PRINT_MESSAGE,
         res_files,
     )
     prepared_message[VarNames.JS_MESSAGE_ID] = js_id
     self.publish(prepared_message, channel)
     self.notify_offline(channel, message_db.id)
Esempio n. 19
0
def msg_consumer(message):
    # Save to model
    #room = message.content['room']

    data = json.loads(message.content['message'])
    username = data.get('username')
    msg = data.get('message')
    user = User.objects.filter(username=username).first()
    print('msg=> ', message.content)

    message_to_return = json.loads(message.content['message'])

    if data.get('action') == 'create':
        msg_obj = Message()
        msg_obj.sender_user = user
        msg_obj.message = msg
        msg_obj.save()
        message_to_return["id"] = msg_obj.id
        message_to_return["creation_date"] = datetime.datetime.strftime(
            msg_obj.creation_date, '%Y-%m-%d %H:%M:%S')

    if data.get('action') == 'delete':
        msg_obj = Message.objects.filter(id=data.get('id')).first()
        msg_obj.delete()

    # Broadcast to listening sockets
    message_to_return["action"] = data.get('action')

    Group('chat').send({'text': json.dumps(message_to_return)})
Esempio n. 20
0
    async def get(self):
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        session = await get_session(self.request)
        user = User(self.request.app.db, {'id': session.get('user')})
        login = await user.get_login()

        for _ws in self.request.app['websockets']:
            _ws.send_str('%s joined' % login)
        self.request.app['websockets'].append(ws)

        async for msg in ws:
            if msg.type == WSMsgType.TEXT:
                if msg.data == 'close':
                    await ws.close()
                else:
                    message = Message(self.request.app.db)
                    result = await message.save(user=login, msg=msg.data)
                    log.debug(result)
                    for _ws in self.request.app['websockets']:
                        await _ws.send_str('{"user": "******", "msg": "%s"}' %
                                           (login, msg.data))
            elif msg.type == WSMsgType.ERROR:
                log.debug('ws connection closed with exception %s' %
                          ws.exception())

        self.request.app['websockets'].remove(ws)
        for _ws in self.request.app['websockets']:
            _ws.send_str('%s disconected' % login)
        log.debug('websocket connection closed')

        return ws
    def setUp(self):

        self.health_professional = HealthProfessional.objects.create(
            name='User Test',
            email='*****@*****.**',
            sex='M',
            phone='1111111111',
            is_active=True)
        self.patient = Patient.objects.create(name='User Test',
                                              email='*****@*****.**',
                                              sex='M',
                                              phone='1111111111',
                                              is_active=True)

        self.view = UnarchiveMessageHealthProfessionalView()
        self.view_class = UnarchiveMessageHealthProfessionalView
        self.factory = RequestFactory()
        self.client = Client()

        # Create Message 1.
        self.message = Message()
        self.message.text = "meu texto"
        self.message.subject = "Assunto"
        self.message.user_from = self.health_professional
        self.message.user_to = self.patient
        self.message.is_active_health_professional = False
        self.message.pk = '1'
        self.message.save()
Esempio n. 22
0
def send_message(request):
    user = request.POST.get('user')
    text = request.POST.get('text')
    message = Message(
        user=user,
        text=text
    )
    message.save()
Esempio n. 23
0
 def new_message_object(self, sender, room_name, message_content):
     message = Message()
     if sender is not None:
         message.sender = sender
     message.room_name = room_name
     message.content = message_content
     message.created_at = now()
     return message
Esempio n. 24
0
 def create_message(self, message, timestamp):
     room = Room.objects.get(label=self.room_name)
     msg = Message(user=self.user,
                   room=room,
                   message=message,
                   timestamp=timestamp)
     msg.save()
     return msg
Esempio n. 25
0
    def create(self, request):
        if 'name' not in request.session or not request.session[
                'authenticated']:
            return Response({
                'success': False,
            }, status=401)

        if 'room' not in request.data or 'date' not in request.data \
                or 'message' not in request.data or 'retention_seconds' not in request.data:

            return Response(
                {
                    'message': 'Nie podano wszystkich pol.',
                    'success': False
                },
                status=400)

        room_id_qs = Room.objects.filter(name=request.data['room'])

        if not room_id_qs.exists():
            return Response(
                {
                    'message': 'Wybrany pokoj nie istnieje.',
                    'success': False
                },
                status=400)

        room = room_id_qs.get()

        if not room.participants.filter(name=request.session['name']).exists():
            return Response(
                {
                    'message': 'Nie jestes czlonkiem wybranego pokoju.',
                    'success': False
                },
                status=403)

        message = Message(
            room_id=room.id,
            author_id=request.session['profile_id'],
            date=request.data['date'],
            message=request.data['message'],
            retention_seconds=request.data['retention_seconds'],
        )
        message.save()

        data = MessageSerializer(message).data
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(f'room-{room.name}', {
            "type": "send.event",
            "data": {
                "event": data,
                "type": "room.m",
            },
        })

        return Response({'message': data})
def send_message(request):
    chat_id = request.POST.get("id_chat")
    chat = Chat.objects.get(id_chat=chat_id)
    text_message = request.POST.get("text-message-input")
    if len(text_message) > 0:
        messaggio = Message.add_this(Message(), chat, request.user,
                                     text_message)
    response = HttpResponse("200")
    return response
Esempio n. 27
0
def add():
    form = AddForm()
    if current_user.is_authenticated:
        message = Message(text=form.message.data, user_id=current_user.id)
        db.session.add(message)
        db.session.commit()
        return redirect(url_for('index'))
    else:
        return render_template('index.html', title='Home', messages=messages)
Esempio n. 28
0
def handle_my_custom_event(json, methods=['GET', 'POST']):
    if json.get('message') is not None:
        message = Message(text=json.get('message'), user_id=current_user.id)
        message = message.validate()
        json.update({'username': current_user.username})
        db.session.add(message)
        db.session.commit()
    print('received my event: ' + str(json))
    socketio.emit('my response', json, callback=messageReceived)
Esempio n. 29
0
    def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
        threads = chat.enroll_code.courseUnit.unit.unitlesson_set.filter(order__isnull=False).order_by('order')
        has_updates = {
            'enabled': False,
            'thread_id': None
        }

        for thread in threads:
            # TODO: move to a dedicated util
            response_msg = chat.message_set.filter(
                lesson_to_answer_id=thread.id,
                kind='response',
                contenttype='response',
                content_id__isnull=False).last()
            if not response_msg:
                continue
            response = response_msg.content
            is_need_help = response.status in (None, NEED_HELP_STATUS, NEED_REVIEW_STATUS)
            if is_need_help and thread.updates_count(chat) > 0:
                has_updates.update({'thread_id': thread.id})
                chat.state.set_data_attr('next_update', has_updates)
                chat.state.save_json_data()
                break

        if has_updates['thread_id']:
            text = f"""
                    You have completed this thread.
                    I have posted new messages to help you in the thread "{thread.lesson.title}".
                    Would you like to view these updates now?
                    """
        elif chat.state.parentState:
            next_lesson = None
            parent = chat.state.parentState
            while parent and not parent.fsmNode.fsm.fsm_name_is_one_of('chat'):
                parent = parent.parentState
            if parent:
                status = parent.get_data_attr('unitStatus')
                next_lesson = status.get_next_lesson().lesson.title if status.get_next_lesson() else None
            text = f"""
                    You have completed this thread.
                    Click on Continue below to view your next thread "{next_lesson}".
                    """ if next_lesson else 'You have completed this thread.'
        else:
            text = 'You have completed this thread.'

        _data = {
            'chat': chat,
            'text': text,
            'owner': chat.user,
            'input_type': 'options',
            'kind': 'button',
            'sub_kind': 'transition',
            'is_additional': is_additional
        }
        message = Message(**_data)
        message.save()
        return message
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        text = text_data_json['message']
        message = Message(text=text, room_name=self.scope['url_route']['kwargs']['room_name'])
        message.save()

        await self.channel_layer.group_send(self.room_group_name,
                                            {'type': 'chat_message',
                                             'message': MessageSerializer(message).data})