コード例 #1
0
ファイル: views.py プロジェクト: kodiers/quests
def send_message(request):
    """
    Save message in database. And redirect to chat room. If chat not exists - create new chat room.
    :param request: HttRequest as POST
    :return: If not errors and request POST return redirect to chat room page. Else return error page.
    """
    if request.method == 'POST':
        receiver = User.objects.get(username=request.POST['receiver'])
        sender = User.objects.get(username=request.POST['sender'])
        chats = Chat.objects.filter(users=receiver).filter(users=request.user)
        chat = None
        new_message = Messages()
        if chats.exists():
            # If chat exist get first chat room for current user and receiver
            chat = chats[0]
            old_messages = Messages.objects.filter(chat=chat).filter(new=True)
            set_new_messages_to_old(old_messages)
        else:
            chat = Chat.objects.create()
            chat.users.add(sender, receiver)
        new_message.chat = chat
        new_message.sender = sender
        new_message.text = request.POST['text']
        new_message.new = True
        new_message.save()
        chat.have_new_message = True
        chat.save()
        return redirect('/messages/chat/' + str(chat.id) +'/')
    else:
        return render_to_response('error.html', {'error': REQUEST_TYPE_ERROR}, context_instance=RequestContext(request))
コード例 #2
0
ファイル: views.py プロジェクト: kodiers/quests
def send_message_api(request):
    """
    API endpoint for tornado application (chatapp.py). Save message in database and return message object as JSON.
    :param request: HttpRequest from tornado app. Should have chat (chat.id), text (message text),
    sender (sender username) parameters
    :return: Return Message object as JSON.
    """
    if request.method == "POST":
        if request.POST['API_KEY'] == API_KEY:
            chat = Chat.objects.get(id=request.POST['chat'])
            text = request.POST['text']
            sender = User.objects.get(username=request.POST['sender'])
            if sender not in chat.users.all():
                return HttpResponse(json.dumps({'chat': chat.pk, 'Error': 'incorrect chat user'}))
            messages = Messages.objects.filter(chat=chat).filter(new=True)
            set_new_messages_to_old(messages)
            new_message = Messages()
            new_message.sender = sender
            new_message.chat = chat
            new_message.text = text
            new_message.new = True
            new_message.save()
            chat.have_new_message = True
            chat.save()
            return HttpResponse(json.dumps({
                'sender': sender.username,
                'text': text,
                'chat': chat.id,
                'datetime': new_message.datetime.strftime('%d-%m-%Y %H:%M')
            }), content_type="application/json")