def _get_messages(request, sync_token, direction):
    storage = get_messages(request)
    for message in storage:
        user_name = message
        print("MESSAGE : ", message)

    print("_get_message username: "******" : ", direction)
    messages.add_message(request, messages.INFO, user_name)
    sys.stdout.flush()
    session = Session.objects.get(matrix_user_name=user_name.message)
    api = MatrixHttpApi(session.matrix_server, token=session.matrix_token)
    synced = api.get_room_messages(api.get_room_id(session.matrix_room_name),
                                   session.matrix_sync_token,
                                   direction,
                                   limit=session.message_count)
    session.matrix_sync_token = synced[sync_token]
    session.save()
    room_topic = api.get_room_topic(api.get_room_id(
        session.matrix_room_name))['topic']
    synced['chunk'] = _parse_messages(synced['chunk'])
    return synced
def chat(request, update=""):
    user_name = None
    storage = get_messages(request)
    for message in storage:
        user_name = message
        print("MESSAGE : ", message)

    if user_name != None:
        print("username: "******"LOGIN VARS")
        print("session.matrix_user_name ", session.matrix_user_name)
        print("session.matrix_room_name ", session.matrix_room_name)
        print("session.matrix_server ", session.matrix_server)
        print("session.message_count ", session.message_count)
        print("session.show_images ", session.show_images)
        sys.stdout.flush()
        api = MatrixHttpApi(session.matrix_server, token=session.matrix_token)
        print("GET_MEMBERSHIP")
        api.join_room(api.get_room_id(session.matrix_room_name))
    else:
        return HttpResponseRedirect('/')

    if request.method == 'POST':  #If the user hit send button
        try:
            print("Posting chat")
            sys.stdout.flush()
            chat_form = ChatForm(request.POST)
            if chat_form.is_valid():
                response = api.send_message(
                    api.get_room_id(session.matrix_room_name),
                    chat_form.cleaned_data['text_entered'])
                chat_form = ChatForm()
                room_topic = api.get_room_topic(
                    api.get_room_id(session.matrix_room_name))['topic']
                messages.add_message(request, messages.INFO,
                                     session.matrix_user_name)
                synced = _get_messages(request,
                                       sync_token="end",
                                       direction='f')
                session.messages = json.dumps(synced['chunk'] +
                                              jsonDec.decode(session.messages))
                session.save()
                return render(
                    request, 'client_app/chat.html', {
                        'chat_form': chat_form,
                        'name': session.matrix_user_name,
                        'messages': jsonDec.decode(session.messages),
                        'room': session.matrix_room_name,
                        'topic': room_topic,
                        'show_images': session.show_images
                    })

        except MatrixRequestError as e:
            print(str(e))
            sys.stdout.flush()
            form = NameForm(request.POST)
            return render(request, 'client_app/login.html', {
                'form': form,
                'login_error': True,
                'error_text': str(e)
            })
        else:
            return render(
                request, 'client_app/chat.html', {
                    'chat_form': chat_form,
                    'name': session.matrix_user_name,
                    'messages': jsonDec.decode(session.messages),
                    'room': session.matrix_room_name,
                    'topic': room_topic,
                    'show_images': session.show_images
                })
    if update == "":  #If not asking for an update, get first sync to server
        try:
            chat_form = ChatForm()
            synced = api.sync()
            room_topic = api.get_room_topic(
                api.get_room_id(session.matrix_room_name))['topic']
            session.matrix_sync_token = synced["next_batch"]
            messages.add_message(request, messages.INFO,
                                 session.matrix_user_name)
            synced = _get_messages(request, sync_token="start", direction='b')
            session.messages = json.dumps(synced['chunk'])
            session.save()

        except MatrixRequestError as e:
            print(str(e))
            sys.stdout.flush()
            form = NameForm(request.POST)
            return render(request, 'client_app/login.html', {
                'form': form,
                'login_error': True
            })
        else:
            return render(
                request, 'client_app/chat.html', {
                    'chat_form': chat_form,
                    'name': session.matrix_user_name,
                    'messages': jsonDec.decode(session.messages),
                    'room': session.matrix_room_name,
                    'topic': room_topic,
                    'show_images': session.show_images
                })
    else:  # update is requested so return next messages using sync token from initial sync
        chat_form = ChatForm()
        room_topic = api.get_room_topic(
            api.get_room_id(session.matrix_room_name))['topic']
        messages.add_message(request, messages.INFO, session.matrix_user_name)
        synced = _get_messages(request, sync_token="end", direction='f')
        session.messages = json.dumps(synced['chunk'] +
                                      jsonDec.decode(session.messages))
        session.save()
        return render(
            request, 'client_app/chat.html', {
                'chat_form': chat_form,
                'name': session.matrix_user_name,
                'messages': jsonDec.decode(session.messages),
                'room': session.matrix_room_name,
                'topic': room_topic,
                'show_images': session.show_images
            })