Esempio n. 1
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. 2
0
def get_remember(message):
    u"""
    Получить напоминание.
    """
    text = None
    parameters = re.findall(
        u"Бот, напомни мне (.*) через (\d+\.?,?\d*) (секунд|минут).*$",
        message.text,
        flags=re.IGNORECASE
    )
    if parameters and parameters[0]:
        info, time, time_unit = parameters[0]
        time = re.sub(u",", u".", time, flags=re.IGNORECASE)
        time = float(time)
        if time_unit == u"минут":
            time = time * 60
        remember = Message(
            thread=message.thread,
            text=u"Напоминаю: %s" % info,
            datetime=message.datetime
        )
        remember.save()
        remember.datetime += timedelta(seconds=time)
        remember.save()

        text = u"Задачу понял и поставил себе в очередь"
    return text
Esempio n. 3
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. 4
0
class TestBoxHealthProfessional(TestCase):
    def setUp(self):

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

        self.professional2 = HealthProfessional.objects.create(
            name='UserTest',
            crm='12334',
            email='*****@*****.**',
            sex='M',
            is_active=True)

        self.patient = Patient.objects.create(name='User Test',
                                              email='*****@*****.**',
                                              sex='M',
                                              phone='1111111111',
                                              is_active=True)
        # Create Message 1.
        self.message = Message()
        self.message.text = "meu texto"
        self.message.subject = "Assunto"
        self.message.user_from = self.professional
        self.message.user_to = self.patient
        self.message.is_active_health_professional = False
        self.message.save()

        # Create Message 2.
        self.message2 = Message()
        self.message2.text = "meu texto"
        self.message2.subject = "Assunto"
        self.message2.user_from = self.professional2
        self.message2.user_to = self.patient
        self.message2.is_active_health_professional = True
        self.message2.save()

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

    def test_query_set_outbox_true(self):
        request = self.factory.get('chat/archive_box_health_professional')
        request.user = self.professional

        self.view.request = request

        query = self.view.get_queryset()
        self.assertTrue(query.exists())

    def test_query_set_outbox_false(self):
        request = self.factory.get('chat/archive_box_health_professional')
        request.user = self.professional2

        self.view.request = request

        query = self.view.get_queryset()
        self.assertFalse(query.exists())
Esempio n. 5
0
def chat_api(request):
	if request.method == 'POST':
		d = json.loads(request.body)
		msg =  d.get('msg')
		user = request.user.username
		gravatar = request.user.profile.gravatar_url
		m = Message(user=user,message=msg,gravatar=gravatar)
		m.save()


		res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar}
		data = json.dumps(res)
		return HttpResponse(data,content_type="application/json")


	# get request
	r = Message.objects.order_by('-time')[:70]
	res = []
	for msgs in reversed(r) :
		res.append({'id':msgs.id,'user':msgs.user,'msg':msgs.message,'time':msgs.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':msgs.gravatar})
	
	data = json.dumps(res)

	
	return HttpResponse(data,content_type="application/json")
Esempio n. 6
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. 7
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. 8
0
def api_bot_task(request, task_id):
    messages = []
    try:
        task = Task.objects.get(pk=task_id)
        task.status = Task.TASK_STATUS_PROCESS
        task.save()
        task_command = task.task
        args = json.loads(task.args)

        # For REMIND command we need additional argument: timestamp when task created
        if task_command == 'REMIND':
            args.append(time.mktime(task.created_at.timetuple()))

        result = Bot.run_command(task_command, args)
        task.status = Task.TASK_STATUS_COMPLETE
        task.result = json.dumps(result)
        task.save()
        cur_date = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
        # Message for send to client
        bot_message = {
            'time': cur_date, 'nick': 'Bot',
            'text': 'Результат выполнения команды {0}: {1}'.format(task_command, result)
        }
        if task_command == 'REMIND':
            bot_message['text'] = 'Напоминаю: {0}'.format(result)

        messages.append(bot_message)
        if result != -1:
            # Store messages ...
            Message.from_messages(messages)
        return JsonResponse({'result': result, 'messages': messages})
    except Task.DoesNotExist:
        return JsonResponse({'result': 0, 'error': 'Incorrect task_id'})
Esempio n. 9
0
def send_message_api(request):
    api_key = request.POST.get('api_key')

    if api_key != settings.API_KEY:
        return json_response({'error': 'API key is incorrect.'})



    sender_id = request.POST.get('sender_id')
    chat_id = request.POST.get('chat_id')
    message_text = request.POST.get('message')

    chat = Chat.objects.get(id=chat_id)
    sender = User.objects.get(id=sender_id)

    if not chat.participants.filter(id=sender_id).exists():
        return HttpResponse('You are not belong to this conversation')

    message_instance = Message()
    message_instance.sender = sender
    message_instance.text = message_text
    message_instance.save()

    chat.messages.add(message_instance)

    return json_response({'status': 'ok'})
Esempio n. 10
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. 11
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()
    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. 13
0
def save_message(request):
    if request.method == 'POST':
        message_text = request.POST.get('message_text')
        user_id = request.POST.get('user_id')

        logged_user = SocialUser.objects.get(user=request.user)
        chat_user = SocialUser.objects.get(user=User.objects.get(id=user_id))

        chat_filter = Chat.objects.filter(users=chat_user).filter(users=logged_user)
        if chat_filter:
            print "Chat instance exists!"
            print chat_filter
            for ch in chat_filter:
                chat_instance = ch
                print "--"
                print chat_instance
                print "--"
        else:
            chat_instance = Chat()
            chat_instance.save()
            chat_instance.users.add(logged_user, chat_user)
            print "Chat instance created"
            print chat_instance

        new_message = Message(author=logged_user, content=message_text, chat=chat_instance)
        new_message.save()

        return JsonResponse({'content': new_message.content,
                             'author': new_message.author.get_initials,
                             'author_id': new_message.author.user.id,
                             'timestamp': new_message.date_created_formatted})

    else:
        return JsonResponse({'message': "You didn't send with POST method, better luck next time!"})
Esempio n. 14
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. 15
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
    })
    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. 17
0
def api_bot_command(request):
    command_str = request.GET.get('command', False)
    res = Bot.parse_command_string(command_str)
    # res = Bot.parse_command_string("Бот, дай мне заголовок сайта http://ya.ru")
    # res = Bot.parse_command_string("Бот, напомни мне ололо через 5")
    cur_date = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
    messages = []
    # If command not recognized
    if res is False:
        # Messages for send to client
        user_message = {'time': cur_date, 'nick': request.session['nick'], 'text': command_str}
        bot_message = {'time': cur_date, 'nick': 'Bot', 'text': 'Команда не распознана'}
        messages.append(user_message)
        messages.append(bot_message)
        # Store messages ...
        Message.from_messages(messages)
        return JsonResponse({'task_id': 0, 'error': 'Incorrect command', 'messages': messages})
    else:
        # Right command
        task_str = getattr(Task, 'TASK_{0}'.format(res['command']))
        task = Task()
        task.task = task_str
        task.args = json.dumps(res['args'])
        task.save()

        # Messages for send to client
        user_message = {'time': cur_date, 'nick': request.session['nick'], 'text': command_str}
        bot_message = {'time': cur_date, 'nick': 'Bot', 'text': 'Команда {0} успешно добавлена'.format(res['command'])}
        messages.append(user_message)
        messages.append(bot_message)
        # Store messages ...
        Message.from_messages(messages)
        return JsonResponse({'task_id': task.pk, 'task': res['command'], 'messages': messages})
Esempio n. 18
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
Esempio n. 19
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. 20
0
def messages_view(request):
	my_messages={}
	senders=[]
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/login')
	me=Person.objects.get(user=request.user)
	friends=me.friends.all()
	if request.method=='POST':
		if request.POST.get('send') is not None:
			name=request.POST.get('friends_select')
			reciever=User.objects.get(username=name)
			message=Message(message=request.POST.get('message_text'), sender=request.user, reciever=reciever)
			message.save()
			print 'successfully sent message'
	me=Person.objects.get(user=request.user)
	inbox=Message.objects.filter(reciever=request.user)
	inbox=inbox.order_by('added').reverse()
	for m in inbox:
		sender=Person.objects.get(user=m.sender)
		my_messages[m]=sender
	args={}
	args.update(csrf(request))
	args['friends']=friends
	args['messages']=my_messages
	args['request']=request
	if request.user.is_authenticated():
		args['person']=Person.objects.filter(user=request.user)[0]
	return render_to_response('chat/message_view.html', args)
Esempio n. 21
0
def new(request):
    if request.method == 'POST':
        from_user = request.user
        to_user_username = request.POST.get('person')
        try:
            to_user = User.objects.get(username=to_user_username)
        except Exception:
            try:
                to_user_username = to_user_username[
                    to_user_username.rfind('(') + 1:len(to_user_username) - 1]
                to_user = User.objects.get(username=to_user_username)
            except Exception:
                return redirect('/messages/new/')
        message = request.POST.get('message')
        print(message)
        if len(message.strip()) == 0:
            return redirect('/messages/new/')
        if from_user != to_user:
            Message.send_message(from_user, to_user, message)
        print(from_user, to_user)
        return redirect(u'/messages/{0}/'.format(to_user_username))

    else:
        conversations = Message.get_conversations(user=request.user)
        return render(request, 'messages/new_modal.html',
                      {'conversations': conversations})
Esempio n. 22
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
Esempio n. 23
0
class TestUnarchiveMessagePatientView(TestCase):
    def setUp(self):

        self.user = Patient.objects.create(name='User Test',
                                           email='*****@*****.**',
                                           sex='M',
                                           phone='1111111111',
                                           is_active=True)
        self.view = UnarchiveMessagePatientView()
        self.view_class = UnarchiveMessagePatientView
        self.factory = RequestFactory()
        self.client = Client()
        # 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.save()

    def test_post_true(self):
        request = self.factory.post('/')

        request.user = self.user
        self.view.request = request
        self.view.object = self.message

        message = self.view_class.post(request, pk=1)
        self.assertEqual(message.status_code, 302)
    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. 25
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. 26
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. 27
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. 28
0
 def create(self, validated_data):
     user = self.context['request'].user
     recipient = get_object_or_404(
         User, username=validated_data['recipient']['username'])
     msg = Message(recipient=recipient,
                   body=validated_data['body'],
                   owner=user)
     msg.save()
     return msg
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
    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})
Esempio n. 31
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
Esempio n. 32
0
def post(request):
    message = request.POST.get('message',None)
    if message is None:
        return HttpResponseBadRequest
    new_msg = Message()
    new_msg.message = message
    new_msg.user = request.user
    new_msg.save()
    return HttpResponse(json.dumps({'success': True, 'child': new_msg.chatbox_element}), content_type='application/json')
Esempio n. 33
0
    def get(self, request, *args, **kwargs):
        from django.http import HttpResponse, Http404
        from chat.models import Message

        if request.is_ajax():
            Message.remove_favourite_messages(request.user.pk,
                                              request.GET.get("list"))
            return HttpResponse()
        raise Http404
Esempio n. 34
0
 def save(self):
     print "SAVING"
     msg = Message(owner=self.user, comptoir=self.cmptr, content=self.content, me_message=self.me_msg)
     msg.save()
     self.cmptr.last_message = msg
     self.cmptr.save()
     msg_date = msg.date.astimezone(timezone_local)
     self.date = date_to_tooltip(msg_date)
     self.mid = msg.id
Esempio n. 35
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})
Esempio n. 36
0
def save_message(**data):
    message = data.get('message')
    sender = data.get('sender')
    receiver = data.get('receiver')
    viewed = data.get('viewed')
    msg = Message(sender=sender,
                  receiver=receiver,
                  text=message,
                  viewed=viewed)
    msg.save()
    return msg
Esempio n. 37
0
 def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
     _data = {
         'chat': chat,
         'text': 'Let\'s return to your previous state.',
         'owner': chat.user,
         'input_type': 'custom',
         'kind': 'message',
         'is_additional': is_additional
     }
     message = Message(**_data)
     message.save()
     return message
Esempio n. 38
0
 def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
     _data = {
         'chat': chat,
         'text': 'There are new questions from Students. I hope it can help you.',
         'owner': chat.user,
         'input_type': 'custom',
         'kind': 'message',
         'is_additional': is_additional
     }
     message = Message(**_data)
     message.save()
     return message
Esempio n. 39
0
 def get_message(self, chat, next_lesson, is_additional, *args, **kwargs):
     _data = {
         'chat': chat,
         'text': 'There are new answers for FAQs you are interested in',
         'owner': chat.user,
         'input_type': 'custom',
         'kind': 'message',
         'is_additional': is_additional
     }
     message = Message(**_data)
     message.save()
     return message
Esempio n. 40
0
 def get_message(self, chat, next_lesson, is_additional, *args, **kwargs) -> Message:
     _data = {
         'chat': chat,
         'text': 'Have you anything else you are worried about?',
         'owner': chat.user,
         'input_type': 'custom',
         'kind': 'message',
         'is_additional': is_additional
     }
     message = Message(**_data)
     message.save()
     return message
Esempio n. 41
0
def send_message(thread_id, sender_id, message_text):
    u"""
    Отправка сообщения и создание ответв.
    """

    # Сохранение сообщения
    message = Message(
        thread_id=thread_id,
        text=message_text,
        sender_id=sender_id
    )
    message.save()

    # Создание ответа
    create_answer(message)
Esempio n. 42
0
def makemessage(request):

  #messagesCount = Message.objects.all().count()
  #if messagesCount >= 30:
   # Message.objects.all().delete()

  body_unicode = request.body.decode('utf-8')
  body = json.loads(body_unicode)
  content = body['content']
  creator = body['creator']

  msg = Message(content=content, creator=creator, post_date=timezone.now())
  msg.save()

  return HttpResponse(body)
Esempio n. 43
0
def home(request):
    message = Message.objects.all()
    if message:
        last_id = Message.objects.last().pk
        need_id = int(last_id) - 32
        messages = Message.objects.filter(id__gte=need_id).all()
    else:
        message = Message(
            user='******',
            text='Hello, user'
        )
        message.save()
        messages = Message.objects.all()

    return render(request, "chat.html", {'messages': messages})
Esempio n. 44
0
def api_message(request):
    # Greeting message
    message = Message()
    message.nick = 'Bot'
    message.text = 'Привет, {0}!'.format(request.session['nick'])
    message.save()

    messages = Message.objects.all()
    messages_format = []
    # Some operations ... Reformat data (for frontend)
    for message in messages:
        message_format = {
            'time': message.created_at.strftime('%d.%m.%Y %H:%M:%S'),
            'nick': message.nick,
            'text': message.text,
        }
        messages_format.append(message_format)

    return JsonResponse({'messages': messages_format})
def send_message(request):
    """
    ---
    request_serializer: MessageSendSerializer
    response_serializer: MessageSerializer
    responseMessages:
        - code: HTTP_DOES_NOT_EXIST
          message: doesn't exist
    """
    sdata = get_validated_serializer(request=request, serializer=MessageSendSerializer).validated_data
    user = get_user_from_validated_data(sdata)
    chat = Chat.objects.filter(Q(dialogrelations__user_1=user) | Q(dialogrelations__user_2=user)).filter(id=sdata['chat'].pk).first()
    if chat is None:
        return Response("", status=HTTP_DOES_NOT_EXIST)
    message = Message()
    message.chat = chat
    message.sender = user
    message.text = sdata['text']
    message.save()


    TCP_IP = 'localhost'
    TCP_PORT = 43455
    import json
    MSG = json.dumps(MessageContainerSerializer({ "message_type":1, "message_data":message}).data)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MSG)
    print MSG
    s.close()
    return Response(MessageSerializer(message).data, status=HTTP_OK)
Esempio n. 46
0
def messages(request, username):
    conversations = Message.get_conversations(user=request.user)
    active_conversation = username
    messages = Message.objects.filter(user=request.user, conversation__username=username)
    messages.update(is_read=True)
    for conversation in conversations:
        if conversation['user'].username == username:
            conversation['unread'] = 0
    return render(request, 'messages/inbox.html', {
        'messages': messages,
        'conversations': conversations,
        'active': active_conversation
        })
Esempio n. 47
0
def msgbox(request):
	if request.method=='POST':
		message=Message()
		message.message=request.POST.get('message')
		message.user_name= request.user.username
		message.image=request.user.profile.image
		message.save()
		return HttpResponseRedirect("http://127.0.0.1:8000/chat/index/")
Esempio n. 48
0
def send(request):
    if request.method == 'POST':
        from_user = request.user
        to_user_username = request.POST.get('to')
        to_user = User.objects.get(username=to_user_username)
        message = request.POST.get('message')
        if len(message.strip()) == 0:
            return HttpResponse()
        if from_user != to_user:
            msg = Message.send_message(from_user, to_user, message)
            return render(request, 'snippets/partial_message.html', {'message': msg})
        return HttpResponse()
    else:
        return redirect('/')
Esempio n. 49
0
def send_message(request, room_name):
	message_text = request.POST.get("message", "")
	chatuser = getChat_User(request)
	if message_text is not None and message_text != "":
		room = getRoom(room_name)
		if room is not None:
				message = Message()
				message.text = message_text
				message.chat_room = room
				message.chat_user = chatuser
				message.color = chatuser.color
				message.user_nickname = chatuser.get_name()
				message.save()
				return HttpResponse("Success")
		return HttpResponse("Invalid Room")
	return HttpResponse("No Message Text")
Esempio n. 50
0
def create_chat_api(request):
    if not request.user.is_authenticated():
        return HttpResponse('You are not loged in')

    if not request.method == 'POST':
        return HttpResponse('Request must be POST type.')

    data = json.loads(request.body.decode('utf-8'))
    username = data['username']

    recipient = User.objects.get(username=username)

    chat = Chat.objects.filter(participants=recipient).filter(participants=request.user)
    if chat.exists():
        chat = chat.first()
        return json_response({'type': constants.CHAT_ALREADY_EXISTS, 'chat_id': chat.id})

    chat = Chat.objects.create()
    chat.participants.add(request.user, recipient)
    initial_message = Message(text='{} started the conversation!'.format(request.user.username),
                              sender=request.user)
    initial_message.save()
    chat.messages.add(initial_message)

    chat_info = {
        'chat_id': chat.id,
        'last_message': initial_message.text,
        'last_message_sender_id': request.user.id,
        'last_message_timestamp': initial_message.timestamp,
        'last_message_is_read': False,
        'interlocutor_id': recipient.id,
        'interlocutor_username': recipient.username,
        'is_interlocutor_typing': False
    }

    return json_response({'type': constants.CHAT_NEW, 'chat': chat_info})
Esempio n. 51
0
def new(request):
    if request.method == 'POST':
        from_user = request.user
        to_user_username = request.POST.get('person')
        try:
            to_user = User.objects.get(username=to_user_username)
        except Exception:
            try:
                to_user_username = to_user_username[to_user_username.rfind('(')+1:len(to_user_username)-1]
                to_user = User.objects.get(username=to_user_username)
            except Exception:
                return redirect('/messages/new/')
        message = request.POST.get('message')
        print(message)
        if len(message.strip()) == 0:
            return redirect('/messages/new/')
        if from_user != to_user:
            Message.send_message(from_user, to_user, message)
        print(from_user, to_user)
        return redirect(u'/messages/{0}/'.format(to_user_username))

    else:
        conversations = Message.get_conversations(user=request.user)
        return render(request, 'messages/new_modal.html', {'conversations': conversations})
Esempio n. 52
0
def create_chat(request):
    if not request.user.is_authenticated():
        return Response('You are not logged in', status=status.HTTP_400_BAD_REQUEST)

    data = request.data
    username = data['username']

    recipient = User.objects.get(username=username)

    chat = Chat.objects.filter(participants=recipient).filter(participants=request.user)
    if chat.exists():
        chat = chat.first()
        return Response({'type': constants.CHAT_ALREADY_EXISTS, 'chat_id': chat.id})

    chat = Chat.objects.create()
    chat.participants.add(request.user, recipient)
    initial_message = Message(text='{} started the conversation!'.format(request.user.username),
                              sender=request.user)
    initial_message.save()
    chat.messages.add(initial_message)

    serializer = ChatSerializer(chat, context={'request': request})

    return Response({'type': constants.CHAT_NEW, 'chat': serializer.data})
Esempio n. 53
0
def add_message(request):
    if request.user.is_authenticated(): 
        if request.method == "POST":
            form_message = AddMessageForm(request.POST)
            if form_message.is_valid():
                user_me=User.objects.get(username__exact=request.user.username)
                
                mess= Message()
                mess.contenu=form_message.cleaned_data["message"]
                mess.auteur=user_me
                mess.date=timezone.now()
            
                mess.save()
        else:
            form_message = AddMessageForm()
    return redirect(reverse(connexion))
Esempio n. 54
0
def message(request, socket, context, message):

    try:
        action = message["action"]
        session_key = message["session_key"]
    except KeyError:
        print "Session key error."
        return

    if action == "join":
        # Try to get the user from the dictionary
        try:
            user_entry = connected_users[session_key]
        except KeyError:
            print "Key Error."
            return
        # If the user is not logged in, reject the joining
        if not user_entry[1].is_authenticated() or user_entry[1].is_anonymous():
            print "User error."
            return
        # Updating the current comptoir of the user
        connected_users[session_key] = (user_entry[0], user_entry[1], user_entry[2], message["cid"])

    elif action == "identification":
        # Identification of the new user with the session key
        identify(socket, session_key)
        # Getting user entry in the dictionary
        user_entry = connected_users[session_key]
        # Iteration on all users
        for other_user in connected_users.values():
                osock, ouser, ocmptrs, ocid = other_user[0], other_user[1], other_user[2], other_user[3]
                # Computing the common comptoirs between the new user and each other user
                common_cid = [c.id for c in set(ocmptrs).intersection(set(user_entry[2]))]
                # If there are some common comptoirs
                if len(common_cid) > 0:
                    # We notify both entites that the other is connected
                    # For the new arrivant, the notification is of type "Already connected"
                    user_entry[0].send({"type": "connected", "user": ouser.username, "cmptrs": common_cid})
                    # For the others, the notification is of type "Just arrived"
                    osock.send({"type": "joined", "user": user_entry[1].username, "cmptrs": common_cid})

    elif action == "post":
        # Get user information from dictionary
        user = connected_users[session_key][1]
        # Get cid where to post the message
        cid = message["cid"]
        # Get the corresponding comptoir object
        comptoir = Comptoir.objects.get(id=cid)
        # If the hash of the comptoir key does not match with the db
        if (comptoir.key_hash != message["hash"]):
            # We reject the message
            socket.send({"type": "error", "error_msg": "Your message was rejected because your key is not valid."})
            socket.send({"type": "ack"})
            return
        # If the message is empty, reject it
        if message["content"] == "":
            socket.send({"type": "error", "error_msg": "Your message was rejected because it is empty."})
            socket.send({"type": "ack"})
            return
        # Try to determine if this is a '/me' message or not
        try:
            me_msg = message["me_msg"]
        except KeyError:
            me_msg = False
        # Creation of a new message object
        msg = Message(owner=user, comptoir=comptoir, content=message["content"], me_message=me_msg)
        # Saving the message
        msg.save()
        # Updating last message on the comptoir
        comptoir.last_message = msg
        comptoir.save()
        # At this point the date of the message is in utc format, so we need to correct it 
        msg_local_date = msg.date.astimezone(timezone_local)
        # Iteration on each connected user to deliver the new message
        for other_user in connected_users.values():
            osock, ouser, ocmptrs, ocid = other_user[0], other_user[1], other_user[2], other_user[3]
            # if the user is the one that posted the message
            if ouser == user:
                # Send acknoledgement
                socket.send({"type": "ack"})
            # If the currently iterated user is related to the comptoir
            if comptoir in ocmptrs:
                # If the comptoir is not the one where the user is connected (and if the user is not the one
                # that posted the message)
                if ocid != cid and ouser != user:
                    # We just send an update-badge message
                    osock.send({"type": "update-badge", "cid": message["cid"], "user": user.username, "msgdate": date_to_tooltip(msg_local_date)})
                else:
                    # Else we deliver the message
                    osock.send({
                                "type": "new-message", 
                                "cid": message["cid"], 
                                "user": user.username, 
                                "content": message["content"], 
                                "me_msg": me_msg, 
                                "msgdate": date_to_tooltip(msg_local_date), 
                                "mid": msg.id,
                                })

    elif action == "edit-msg":
        # Get user from dictionary
        user = connected_users[session_key][1]
        # Get the socket of the user
        sock = connected_users[session_key][0]
        # Get cid where to edit the message
        cid = message["cid"]
        # Get the corresponding comptoir object
        comptoir = Comptoir.objects.get(id=cid)
        # Get the id of the message to edit
        mid = message["mid"]
        # Get the message object
        msg = Message.objects.get(id=mid)
        # Check the owner of the message
        if msg.owner != user:
            sock.send({"type": "error", "error_msg": "You cannot edit a message that does not belong to you. The new message has not been saved on the server."})
            return
        if msg.content != message["oldmsg"]:
            sock.send({"type": "error", "error_msg": "The edition has failed. The new message has not been saved on the server."})
            return
        # If the hash of the comptoir key does not match with the db
        if (comptoir.key_hash != message["hash"]):
            # We reject the message
            socket.send({"type": "error", "error_msg": "Edition was rejected because your key is not valid."})
            return
        # Update message content
        msg.content = message["newmsg"]
        msg.edited = True
        # Save modification
        msg.save()
        # Propagate the edition to connected users
        for other_user in connected_users.values():
            osock, ouser, ocmptrs, ocid = other_user[0], other_user[1], other_user[2], other_user[3]
            # If the currently iterated user is related to the comptoir
            if cid == ocid:
                # We notify the modification
                osock.send({"type": "edit-msg", "cid": message["cid"], "mid": mid, "content": message["newmsg"]})

    # To be commented
    elif action == "wizz":
        user = connected_users[session_key][1]
        cid = message["cid"]
        comptoir = Comptoir.objects.get(id=cid)
        context["cid"] = cid
        context["username"] = user.username

        if (comptoir.key_hash != message["hash"]):
            socket.send({"type": "error", "error_msg": "Your wizz was rejected because your key is not valid."})
        else:
            for other_user in connected_users.values(): 
                osock, ouser, ocmptrs, ocid = other_user[0], other_user[1], other_user[2], other_user[3]
                if comptoir in ocmptrs:
                    if ocid == cid:
                        osock.send({"type": "wizz", "from": user.username}) 
Esempio n. 55
0
    def get_message(self, chat, request, current=None, message=None):
        stack_pattern = QUESTION_STACK_PATTERN.format(request.user.id, chat.id)
        is_additional = chat.state.fsmNode.fsm.fsm_name_is_one_of('additional', 'resource')
        next_lesson = chat.state.unitLesson
        if self.node_name_is_one_of('LESSON'):
            input_type = 'custom'
            kind = next_lesson.lesson.kind
            try:
                if is_additional:
                    raise UnitLesson.DoesNotExist
                unitStatus = chat.state.get_data_attr('unitStatus')
                next_ul = unitStatus.unit.unitlesson_set.get(order=unitStatus.order+1)
                # Add CONTINUE button here
                if (next_ul and next_ul.lesson.kind in SIMILAR_KINDS and
                    kind in SIMILAR_KINDS or
                    next_ul.lesson.kind == Lesson.ORCT_QUESTION):
                    input_type = 'options'
                    kind = 'button'
            except UnitLesson.DoesNotExist:
                pass
            message = Message.objects.get_or_create(
                contenttype='unitlesson',
                content_id=next_lesson.id,
                chat=chat,
                owner=chat.user,
                input_type=input_type,
                kind=kind,
                is_additional=is_additional)[0]
        if self.name == 'ASK':
            SUB_KIND_TO_KIND_MAP = {
                'choices': 'button',
            }
            SUBKIND_TO_INPUT_TYPE_MAP = {
                'choices': 'options',
            }
            sub_kind = next_lesson.lesson.sub_kind
            _data = {
                'contenttype': 'unitlesson',
                'content_id': next_lesson.id,
                'chat': chat,
                'owner': chat.user,
                'input_type': 'custom', # SUBKIND_TO_INPUT_TYPE_MAP.get(sub_kind, 'custom'),
                'kind': next_lesson.lesson.kind,  # SUB_KIND_TO_KIND_MAP.get(sub_kind, next_lesson.lesson.kind),
                'is_additional': is_additional
            }
            if not self.fsm.fsm_name_is_one_of('live_chat'):
                message = Message.objects.get_or_create(**_data)[0]
            else:
                message = Message(**_data)
                message.save()

            find_crit = {
                "stack_id": stack_pattern
            }
            c_chat_stack().update_one(
                find_crit,
                {"$push": {"stack": next_lesson.id}},
                upsert=True)
            # Fallback method to pass ul_id's throught messages
            if request.session.get(stack_pattern):
                if isinstance(request.session[stack_pattern], list):
                    request.session[stack_pattern].append(next_lesson.id)
                else:
                    request.session[stack_pattern] = [request.session[stack_pattern]]
                    request.session[stack_pattern].append(next_lesson.id)
            else:
                request.session[stack_pattern] = [next_lesson.id]
        if self.node_name_is_one_of('ABORTS'):
            message = Message.objects.create(
                owner=chat.user,
                chat=chat,
                kind='message',
                input_type='custom',
                is_additional=is_additional,
                text=self.title
            )
        if self.node_name_is_one_of('GET_ABORTS'):
            message = Message.objects.get_or_create(
                            contenttype='NoneType',
                            kind='abort',
                            input_type='options',
                            chat=chat,
                            owner=chat.user,
                            userMessage=False,
                            is_additional=is_additional)[0]
        if self.node_name_is_one_of('GET_ANSWER'):
            find_crit = {
                "stack_id": stack_pattern
            }
            stack = None
            try:
                document = c_chat_stack().find_and_modify(
                    query=find_crit,
                    update={"$pop": {"stack": 1}})
                stack = document.get('stack', [])
            except ConnectionFailure:
                pass
            if request.session.get(stack_pattern):
                if isinstance(request.session[stack_pattern], list):
                    fallback_ul_id = request.session[stack_pattern].pop()
                elif isinstance(request.session[stack_pattern], int):
                    fallback_ul_id = request.session[stack_pattern]
                else:
                    fallback_ul_id = current.id
            unit_lesson_id = stack.pop() if stack else fallback_ul_id
            lesson_to_answer = UnitLesson.objects.filter(id=unit_lesson_id).first()
            _data = {
                'contenttype': 'response',
                'input_type': 'text',
                'lesson_to_answer': lesson_to_answer,
                'chat': chat,
                'owner': chat.user,
                'kind': 'response',
                'userMessage': True,
                'is_additional': is_additional
            }
            if lesson_to_answer.lesson.sub_kind == 'choices':
                _data.update(dict(
                    input_type='options',

                ))

            if not self.fsm.fsm_name_is_one_of('live_chat'):
                message = Message.objects.get_or_create(**_data)[0]
            else:
                message = Message(**_data)
                message.save()
        if self.node_name_is_one_of('CONFIDENCE'):
            # current here is Response instance
            if isinstance(current, Response):
                response_to_chk = current
                answer = current.unitLesson.get_answers().first()
            else:
                response_to_chk = message.response_to_check
                if not message.lesson_to_answer:
                    answer = message.response_to_check.unitLesson.get_answers().first()
                else:
                    answer = message.lesson_to_answer.get_answers().first()
            message = Message.objects.create(  # get_or_create
                contenttype='unitlesson',
                response_to_check=response_to_chk,
                input_type='custom',
                text=self.title,
                chat=chat,
                owner=chat.user,
                kind=answer.kind,
                is_additional=is_additional)
        if self.node_name_is_one_of('GET_CONFIDENCE'):
            _data = dict(
                contenttype='response',
                content_id=message.response_to_check.id,
                input_type='options',
                chat=chat,
                owner=chat.user,
                kind='response',
                userMessage=True,
                is_additional=is_additional,
            )
            # here was Message.objects.create for all fsm's except live_chat. for live_chat fsm here was get_or_create
            message = Message(**_data)
            message.save()
        if self.node_name_is_one_of('CORRECT_ANSWER'):
            lesson = message.response_to_check.unitLesson.lesson if chat.is_live else message.content.unitLesson.lesson
            correct_choices = lesson.get_correct_choices()
            if correct_choices:
                correct_title = lesson.get_choice_title(correct_choices[0][0])
                correct_description = lesson.get_choice_description(correct_choices[0][0])
            else:
                answer = message.content.unitLesson.get_answers().first()
                correct_title = answer.lesson.title if answer else 'Answer title'
                correct_description = mark_safe(md2html(answer.lesson.text)) if answer else 'Answer description'
            message = Message.objects.create(
                owner=chat.user,
                chat=chat,
                kind='message',
                input_type='custom',
                is_additional=is_additional,
                text="""
                    <b>You got it right, the correct answer is: {}</b>
                    <br>
                    {}
                """
                .format(correct_title, correct_description)
            )
        if self.node_name_is_one_of('INCORRECT_ANSWER'):
            lesson = message.response_to_check.unitLesson.lesson if chat.is_live else message.content.unitLesson.lesson
            correct_choices = lesson.get_correct_choices()
            if correct_choices:
                correct_title = lesson.get_choice_title(correct_choices[0][0])
                correct_description = lesson.get_choice_description(correct_choices[0][0])
            else:
                answer = message.content.unitLesson.get_answers().first()
                correct_title = answer.lesson.title if answer else 'Answer title'
                correct_description = mark_safe(md2html(answer.lesson.text)) if answer else 'Answer description'
            message = Message.objects.create(
                owner=chat.user,
                chat=chat,
                lesson_to_answer=message.response_to_check.unitLesson if chat.is_live else message.content.unitLesson,
                response_to_check=message.response_to_check if chat.is_live else current,
                kind='message',
                input_type='custom',
                is_additional=is_additional,
                text="""
                    <b>The correct answer is: {}</b>
                    <br>
                    {}
                """
                .format(correct_title, correct_description)
            )
        if self.node_name_is_one_of('INCORRECT_CHOICE'):
            lesson = message.lesson_to_answer.lesson
            selected = [int(i) for i in message.response_to_check.text.split('[selected_choices] ')[1].split()]
            incorrect_description = lesson.get_choice_description(selected[0]) if selected else ''
            my_choices = []
            for i, c in message.response_to_check.lesson.get_choices():
                if i in selected:
                    my_choices.append(c.split(' ', 1)[1])
            if not my_choices:
                my_choices.append('Nothing')
            message = Message.objects.create(
                owner=chat.user,
                chat=chat,
                kind='message',
                input_type='custom',
                is_additional=is_additional,
                text="""
                    <b>You selected: {}</b>
                    <br>
                    {}
                """
                .format(
                    my_choices[0] if len(my_choices) == 1 else '<br>' + ''.join(['<h3>{}</h3>'.format(_) for _ in my_choices]),
                    incorrect_description
                )
            )
            # here was Message.objects.create for all fsm's except live_chat. for live_chat fsm here was get_or_create
        if self.node_name_is_one_of("WAIT_ASSESS"):
            if isinstance(current, Response):
                resp_to_chk = current
            else:
                resp_to_chk = message.response_to_check
            message = Message.objects.get_or_create(
                chat=chat,
                text=self.title,
                kind='button',
                response_to_check=resp_to_chk,
                is_additional=is_additional,
                owner=chat.user,
            )[0]

        if self.node_name_is_one_of('ASSESS'):
            # current here is Response instance
            if isinstance(current, Response):
                response_to_chk = current
                answer = current.unitLesson.get_answers().first()
            else:
                response_to_chk = message.response_to_check
                if not message.lesson_to_answer:
                    answer = message.response_to_check.unitLesson.get_answers().first()
                else:
                    answer = message.lesson_to_answer.get_answers().first()
            message = Message.objects.get_or_create(
                contenttype='unitlesson',
                response_to_check=response_to_chk,
                input_type='custom',
                content_id=answer.id,
                chat=chat,
                owner=chat.user,
                kind=answer.kind,
                is_additional=is_additional)[0]
        if self.node_name_is_one_of('GET_ASSESS'):
            _data = dict(
                contenttype='response',
                content_id=message.response_to_check.id if message.response_to_check else None,
                input_type='options',
                chat=chat,
                owner=chat.user,
                kind='response',
                userMessage=True,
                is_additional=is_additional
            )
            # here was Message.objects.create for all fsm's except live_chat. for live_chat fsm here was get_or_create
            message = Message(**_data)
            message.save()

        if self.node_name_is_one_of('GRADING'):
            GraderClass = GRADERS.get(message.content.unitLesson.lesson.sub_kind)
            if GraderClass:
                grader = GraderClass(message.content.unitLesson, message.content)
                # grade method must be called to actually do the work
                grader.grade
                text = 'Your answer is {}!'.format(grader.message)
            else:
                text = "No such grader! Grading could not be applied."
            message = Message.objects.create(
                owner=chat.user,
                chat=chat,
                kind='message',
                input_type='custom',
                is_additional=is_additional,
                text=text
            )

        if self.node_name_is_one_of('STUDENTERROR'):
            resolve_message = Message.objects.filter(
                            contenttype='unitlesson',
                            content_id=next_lesson.id,
                            chat=chat,
                            owner=chat.user,
                            input_type='custom',
                            kind='message',
                            timestamp__isnull=True,
                            is_additional=True).first()
            message = Message.objects.get_or_create(
                            contenttype='unitlesson',
                            content_id=resolve_message.student_error.errorModel.id,
                            chat=chat,
                            owner=chat.user,
                            student_error=resolve_message.student_error,
                            input_type='options',
                            kind='button',
                            is_additional=True)[0]
        if self.node_name_is_one_of('RESOLVE'):
            message = Message.objects.filter(
                            contenttype='unitlesson',
                            content_id=next_lesson.id,
                            chat=chat,
                            owner=chat.user,
                            input_type='custom',
                            kind='message',
                            timestamp__isnull=True,
                            is_additional=True).first()
        if self.node_name_is_one_of('HELP_RESOLVE'):
            message = Message.objects.get_or_create(
                            contenttype='unitlesson',
                            content_id=next_lesson.id,
                            chat=chat,
                            owner=chat.user,
                            input_type='options',
                            kind='button',
                            timestamp__isnull=True,
                            is_additional=True)[0]
        if self.node_name_is_one_of('MESSAGE_NODE'):
            message = Message.objects.get_or_create(
                            chat=chat,
                            owner=chat.user,
                            text=chat.state.fsmNode.title,
                            student_error=message.student_error,
                            input_type='custom',
                            kind='message',
                            is_additional=True)[0]
        if self.node_name_is_one_of('END', 'IF_RESOURCES', 'NEED_HELP_MESSAGE', 'ASSESS_QUESTION_MESSAGE'):
            if not self.help:
                text = self.get_help(chat.state, request=None)
            else:
                text = self.help
            message = Message.objects.create(
                            response_to_check=message.response_to_check,
                            chat=chat,
                            owner=chat.user,
                            text=text,
                            input_type='custom',
                            kind='message',
                            is_additional=True)
        if self.node_name_is_one_of('GET_RESOLVE'):
                message = Message.objects.create(
                            contenttype='unitlesson',
                            content_id=next_lesson.id,
                            input_type='options',
                            chat=chat,
                            owner=chat.user,
                            student_error=message.student_error,
                            kind='response',
                            userMessage=True,
                            is_additional=is_additional)
        if self.node_name_is_one_of('ERRORS'):
            message = Message.objects.get_or_create(
                            chat=chat,
                            owner=chat.user,
                            text=''''''
                            '''Here are the most common blindspots people reported when comparing their answer vs. '''
                            '''the correct answer. Check the box(es) that seem relevant to your answer (if any).''',
                            kind='message',
                            input_type='custom',
                            is_additional=is_additional)[0]
        if self.node_name_is_one_of('GET_ERRORS'):
            uniterror = UnitError.get_by_message(message)
            message = Message.objects.get_or_create(
                            contenttype='uniterror',
                            content_id=uniterror.id,
                            input_type='options',
                            chat=chat,
                            kind='uniterror',
                            owner=chat.user,
                            userMessage=False,
                            is_additional=is_additional)[0]
        if self.node_name_is_one_of('TITLE'):
            divider = ChatDivider(text=next_lesson.lesson.title,
                                  unitlesson=next_lesson)
            divider.save()
            message = Message.objects.get_or_create(
                            contenttype='chatdivider',
                            content_id=divider.id,
                            input_type='custom',
                            type='breakpoint',
                            chat=chat,
                            owner=chat.user,
                            kind='message',
                            is_additional=is_additional)[0]
        if self.node_name_is_one_of('START_MESSAGE'):
            message = Message.objects.create(
                            input_type='options',
                            text=self.title,
                            chat=chat,
                            owner=chat.user,
                            kind='button',
                            is_additional=is_additional)
        if self.node_name_is_one_of('DIVIDER'):
            divider = ChatDivider(text=self.title)
            divider.save()
            message = Message.objects.get_or_create(
                            contenttype='chatdivider',
                            content_id=divider.id,
                            input_type='custom',
                            type='breakpoint',
                            chat=chat,
                            owner=chat.user,
                            kind='message',
                            is_additional=is_additional)[0]

        if self.node_name_is_one_of('START') and self.fsm.fsm_name_is_one_of('live_chat'):
            message = Message.objects.get_or_create(
                chat=chat,
                text=self.title,
                kind='button',
                is_additional=is_additional,
                owner=chat.user,
            )[0]

        if self.name in (
                'GET_UNIT_NAME_TITLE',
                'GET_UNIT_QUESTION',
                'GET_UNIT_ANSWER',
                'GET_HAS_UNIT_ANSWER',
        ):
            _data = dict(
                chat=chat,
                owner=chat.user,
                input_type='text',
                kind='response',
                userMessage=True,
                is_additional=is_additional
            )
            if isinstance(current, UnitLesson):
                _data['content_id'] = current.id
                # _data['text'] = current.lesson.title
                _data['contenttype'] = 'unitlesson'
            elif message and message.content:
                # _data['text'] = "current.lesson"
                _data['content_id'] = message.content_id
                _data['contenttype'] = message.contenttype

            # content_id = current.id if current else None
            message = Message.objects.create(**_data)

        if self.name in ('START', 'UNIT_NAME_TITLE', 'NOT_A_QUESTION') and self.fsm.fsm_name_is_one_of('chat_add_lesson'):
            text = "**{}** \n\n{}".format(self.title, getattr(self, 'help', '') or '')
            _data = dict(
                chat=chat,
                text=text,
                input_type='custom',
                kind='message',
                is_additional=is_additional,
                owner=chat.user,
            )
            message = Message.objects.create(**_data)

        if self.name in ('UNIT_QUESTION', 'UNIT_ANSWER') and self.fsm.fsm_name_is_one_of('chat_add_lesson'):
            text = "**{}** \n\n{}".format(self.title, getattr(self, 'help', '') or '')
            _data = dict(
                chat=chat,
                text=text,
                input_type='custom',
                kind='message',
                is_additional=is_additional,
                owner=chat.user,
            )
            if message and message.content_id:
                _data['content_id'] = message.content_id
                _data['contenttype'] = 'unitlesson'
            elif isinstance(current, UnitLesson):
                _data['content_id'] = current.id
                _data['contenttype'] = 'unitlesson'
            message = Message.objects.create(**_data)

        if self.name in ('HAS_UNIT_ANSWER', 'WELL_DONE'):
            text = "**{}** \n\n{}".format(self.title, getattr(self, 'help', '') or '')
            _data = dict(
                chat=chat,
                text=text,
                input_type='options',
                kind='message',
                owner=chat.user,
                userMessage=False,
                is_additional=is_additional
            )
            if message and message.content_id:
                _data['content_id'] = message.content_id
                _data['contenttype'] = 'unitlesson'
            message = Message.objects.create(**_data)

        if self.name in ('WELL_DONE',):
            text = "**{}** \n\n{}".format(self.title, getattr(self, 'help', '') or '')
            _data = dict(
                chat=chat,
                text=text,
                input_type='options',
                kind='button',
                owner=chat.user,
                userMessage=False,
                is_additional=is_additional
            )
            if message and message.content_id:
                _data['content_id'] = message.content_id
                _data['contenttype'] = 'unitlesson'
            message = Message.objects.create(**_data)

        # wait for RECYCLE node and  any node starting from WAIT_ except WAIT_ASSESS
        if is_wait_node(self.name):
            lookup = dict(
                chat=chat,
                text=self.title,
                kind='button',
                is_additional=False,
                owner=chat.user
            )
            message = Message.objects.get_or_create(**lookup)[0]
        return message
Esempio n. 56
0
def send(request, user):
    text = request.POST.get('msg', '')
    chat_room = ChatRoom.objects.get(name = user.chat_name)
    msg = Message(room = chat_room, content = text, author = user.user.username)
    msg.save()
Esempio n. 57
0
def send(request):
	body = request.POST['message']
	m = Message(sender="User1304", body=body)
	m.save()
	return HttpResponse('Complete')