예제 #1
0
def catalog(request):
    """function catalog This function handles the view for the catalog page of the application.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
    Returns:
        HttpResponse: A generated http response object to the request depending on whether or not
                      the user is authenticated.
    """
    # get all lesson sets, display
    if request.method == 'POST':
        print("Attempting to open the lesson: ", request.POST)

        if user_auth(request):
            # search for lesson set
            if lesson_set_auth(request):
                print(request)
                return redirect("/tutor/tutor")
            else:
                print("lesson set auth returned false")
                return redirect("accounts:profile")
        else:
            return redirect("/accounts/settings")
    else:
        return render(request, "tutor/catalog.html",
                      {'LessonSet': MainSet.objects.all()})
예제 #2
0
def edit_assignment(request):
    """function educator This function handles the POST request for editing/deleting an assignment

    Args:
        request (HTTPRequest): A http request object created automatically by Django.

    Returns:
        HttpResponse: A generated http response object to the request.
    """

    if request.method != 'POST':
        return redirect("/educator/")

    # Get assignment
    try:
        assignment_id = request.POST.get('assignment_id', -1)
        assignment = Assignment.objects.get(id=assignment_id)
    except Assignment.DoesNotExist:
        # Assignment doesn't exist!
        return redirect('/educator/')

    # Is user valid?
    if user_auth(request):
        # Case 1: User is valid
        user_info = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        # Does user instruct the class?
        if user_auth_inst(user_info, assignment.class_key):
            # Case 1a: User is educator of class
            # Handle assignment edit
            delete = request.POST.get('delete_assignment', False)
            end_date = request.POST.get('end_date', None)

            # Basically a do: while(False) loop
            while True:
                if delete is not False:
                    # Delete the assignment
                    assignment.delete()
                    break
                if end_date is None:
                    request.session['error'] = "You must supply a due date!"
                    break
                end_date = date.fromisoformat(end_date)
                if end_date < assignment.start_date:
                    request.session[
                        'error'] = "Assignment must open before it closes!"
                    break
                assignment.end_date = end_date
                assignment.save()
                break

            return redirect(
                reverse('educator:class-view', args=[assignment.class_key_id]))
        else:
            # Case 1b: User doesn't teach class
            return redirect("/educator/")
    else:
        # Case 2: User doesn't exist in table
        return redirect("/accounts/settings")
예제 #3
0
def completed(request, index):
    """function previous This function handles retrieving the prev lesson.
        Args:
            request (HTTPRequest): A http request object created automatically by Django.
            index (int): The index of the lesson to retrieve
        Returns:
            HttpResponse: A generated http response object to the request depending on whether or not
                          the user is authenticated.
        """
    if request.method == 'GET':
        if user_auth(request):
            current_user = UserInformation.objects.get(user=User.objects.get(
                email=request.user.email))
            if not_complete(request):
                main_set = MainSet.objects.filter(
                    set_name=current_user.current_main_set)[0]

            item = main_set.lessons.all()[0]
            for count, item in enumerate(main_set.lessons.all()):
                if count == index:
                    break

            current_lesson = Lesson.objects.get(lesson_title=item.first_in_set)

            set_len = len(current_user.current_main_set.lessons.all())
            print("set len: ", set_len)
            num_done = finished_lesson_count(current_user)

            # create an ordered set
            ordered_set = current_user.current_main_set.lessons.all()
            count2 = 0
            for count2, item in enumerate(
                    current_user.current_main_set.lessons.all()):
                if item == current_user.current_lesson_set:
                    break

            if index <= count2:
                lesson_info = get_log_data(current_user, index)
                print("lesson info: ", index)
                return render(
                    request, "tutor/tutor.html", {
                        'lesson': current_lesson,
                        'lesson_code': lesson_info[0],
                        'concept': current_lesson.lesson_concept.all(),
                        'referenceSet': current_lesson.reference_set.all(),
                        'currLessonNum': current_user.current_lesson_index,
                        'setLength': set_len,
                        'finished_count': num_done,
                        'orderedSet': ordered_set,
                        'mood': lesson_info[1],
                        'past': lesson_info[2],
                        'completedLessonNum': count2,
                        'review': current_lesson.correct_feedback,
                        'index': index
                    })
            return redirect("tutor:tutor")

    return redirect("accounts:profile")
예제 #4
0
def advance_parsons_lesson(request, assignmentID):
    if request.method == 'GET':
        if user_auth(request):
            current_user = UserInformation.objects.get(user=User.objects.get(email=request.user.email))
            assignment = Assignment.objects.get(id=assignmentID)

            assignment.advance_user(current_user.id)

            return HttpResponse(status = 204)
예제 #5
0
def educator(request):
    """function educator This function handles the view for the educator page of the application.

    Args:
        request (HTTPRequest): A http request object created automatically by Django.

    Returns:
        HttpResponse: A generated http response object to the request.
    """
    # Is user valid?
    if user_auth(request):
        current_user = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        # Case 1: User is valid
        # Is user educator?
        if user_is_educator(current_user):
            # Case 1a: User is educator
            if request.method == 'POST':
                # Handle new class creation
                class_name = request.POST.get('class-name', None)
                if class_name is not None:
                    # Get unique join code
                    join_code = random.randrange(100000, 999999, 1)

                    while True:
                        try:
                            Class.objects.get(join_code=join_code)
                            join_code = random.randrange(100000, 999999, 1)
                        except Class.DoesNotExist:
                            break

                    new_class = Class(class_name=class_name,
                                      join_code=join_code)
                    new_class.save()
                    new_relation = ClassMembership(
                        user_id=current_user.id,
                        class_taking_id=new_class.id,
                        is_educator=True)
                    new_relation.save()
                    messages.info(
                        request, "Successfully created " + class_name +
                        ". Students can input the code '" + str(join_code) +
                        "' to join it.")
                return redirect("/educator")
            # Return class view
            return render(request, "educator/educator.html",
                          {'classes': get_classes_taught(current_user)})
        else:
            # Case 1b: User doesn't exist in table
            return redirect("/accounts/settings")

    else:
        # Case 2: User not valid. Go to login
        return redirect("/accounts/settings")
예제 #6
0
def edit_class(request):
    """function educator This function handles the POST request for renaming/deleting a class

    Args:
        request (HTTPRequest): A http request object created automatically by Django.

    Returns:
        HttpResponse: A generated http response object to the request.
    """

    if request.method != 'POST':
        return redirect("/educator/")

    # Get class
    try:
        class_id = request.POST.get('class_id', -1)
        class_to_edit = Class.objects.get(id=class_id)
    except Class.DoesNotExist:
        # Class doesn't exist!
        return redirect('/educator/')

    # Is user valid?
    if user_auth(request):
        # Case 1: User is valid
        user_info = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        # Does user instruct the class?
        if user_auth_inst(user_info, class_id):
            # Case 1a: User is educator of class
            # Handle class edit
            delete = request.POST.get('delete_class', False)
            new_name = request.POST.get('new_name', None)

            # Basically a do: while(False) loop
            while True:
                if delete is not False:
                    # Delete the class
                    class_to_edit.delete()
                    break
                if new_name is None:
                    request.session['error'] = "You must supply a class name!"
                    break
                class_to_edit.class_name = new_name
                class_to_edit.save()
                break

            return redirect(reverse('educator:main-view'))
        else:
            # Case 1b: User doesn't teach class
            return redirect("/educator/")
    else:
        # Case 2: User doesn't exist in table
        return redirect("/accounts/settings")
예제 #7
0
def grader(request):
    """function grader This function handles checking code sent by the JS.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
    Returns:
        JsonResponse: A JSON response informing the browser of the results and the user's current state
    """

    # Case 1: We have received a POST request submitting code (needs a lot of work)
    if request.method == 'POST':
        # Case 1a: if the user exists
        if user_auth(request):

            data = json.loads(request.body.decode('utf-8'))
            current_user = UserInformation.objects.get(user=User.objects.get(
                email=request.user.email))
            assignment = Assignment.objects.get(id=data['assignment'])
            current_lesson_set, _, current_lesson, _, is_alternate = assignment.get_user_lesson(
                current_user.id)

            # Get submitted answer. No 'Confirm', no spaces, each ends with a semicolon
            submitted_answer = re.findall("Confirm [^;]*;|ensures [^;]*;",
                                          data['code'])
            submitted_answer = ''.join(submitted_answer)

            status, lines, vcs, completion_time = asyncio.run(
                send_to_verifier(data['code']))
            # Log data
            log_data(current_user, assignment, current_lesson_set,
                     current_lesson, is_alternate, data, status, vcs,
                     completion_time)

            if status == "success":
                # Update assignment progress
                # Can use return value from advance_user to communicate to browser that assignment is completed
                assignment.advance_user(current_user.id)
                return JsonResponse(
                    browser_response(current_lesson, assignment, current_user,
                                     submitted_answer, status, lines, True,
                                     False))
            else:
                # Activate alternate if needed
                changed = assignment.alternate_check(current_user.id,
                                                     data['code'])
                return JsonResponse(
                    browser_response(current_lesson, assignment, current_user,
                                     submitted_answer, status, lines, changed,
                                     changed))
    return redirect("accounts:profile")
예제 #8
0
def assignment_auth(request, assignment_id=None):
    """function lesson_auth This function handles the auth logic for whether a student can take an assignment

    Args:
         request (HTTPRequest): A http request object created automatically by Django.
        assignment_id: An optional ID that can be input to check GET requests
    Returns:
        Boolean: A boolean to signal if the student is able to go into the assignment
    """
    if tutor_helper.user_auth(request):
        if assignment_id is None:
            assignment_id = request.POST.get("assignment_id")
        # Do we have the assignment in the DB?
        if Assignment.objects.filter(id=assignment_id).exists():
            print("HIT")
            assignment = Assignment.objects.get(id=assignment_id)
            current_user = UserInformation.objects.get(user=User.objects.get(
                email=request.user.email))

            # Is the user already taking this assignment?
            if AssignmentProgress.objects.filter(
                    assignment_key=assignment,
                    user_info_key=current_user).exists():
                print("old assignment")
                # Check that assignment hasn't been completed already
                current_lesson_set, _, current_lesson, _, _ = assignment.get_user_lesson(
                    current_user.id)
                if current_lesson_set is None or current_lesson is None:
                    print("Already completed!")
                    return False
                return True
            else:
                # Is the user in the class for this assignment?
                if ClassMembership.objects.filter(
                        user=current_user,
                        class_taking=assignment.class_key).exists():
                    progress = AssignmentProgress(user_info_key=current_user,
                                                  assignment_key=assignment)
                    progress.save()
                    print("starting new assignment")
                    return True
                print("User not in the class for this assignment!")
        else:
            print("Assignment doesn't exist!")
    else:
        print("Bad user!")
    return False
예제 #9
0
def classes(request):
    """function classes This function handles the view for the classes page of the application.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
    Returns:
        HttpResponse: A generated http response object to the request depending on whether or not
                      the user is authenticated.
    """
    if user_auth(request):
        current_user = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        if request.method == 'POST':
            # Handle class join
            class_code = request.POST.get('class-code', None)
            if class_code is not None:
                try:
                    class_to_join = Class.objects.get(join_code=class_code)
                except Class.DoesNotExist:
                    class_to_join = None
                if class_to_join is not None:
                    if ClassMembership.objects.filter(
                            user_id=current_user.id,
                            class_taking_id=class_to_join.id).exists():
                        messages.error(
                            request,
                            "You are already in " + str(class_to_join) + "!")
                    else:
                        new_relation = ClassMembership(
                            user_id=current_user.id,
                            class_taking_id=class_to_join.id,
                            is_educator=False)
                        new_relation.save()
                        messages.info(
                            request,
                            "Successfully added you to " + str(class_to_join))
                else:
                    messages.error(request, "Sorry, class code invalid!")
            else:
                messages.error(request, "Sorry, class code invalid!")
            return redirect("/tutor/classes")
        return render(request, "tutor/classes.html",
                      {'classes': get_classes(current_user)})
    else:
        return redirect("/accounts/settings")
예제 #10
0
def class_view(request, classID):
    """function class_view This function handles the view for the class page of the application.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
        classID (int): The ID of the class that's being viewed
    Returns:
        HttpResponse: A generated http response object to the request depending on whether or not
                      the user is authenticated.
    """
    if user_auth(request):
        if user_in_class_auth(
                UserInformation.objects.get(user=User.objects.get(
                    email=request.user.email)), classID):
            class_to_show = Class.objects.get(id=classID)
            return render(request, "tutor/assignments_student.html",
                          {'class': class_to_show})
        else:
            return redirect("/tutor/classes")
    else:
        return redirect("/accounts/settings")
예제 #11
0
def completed(request, index):
    """function previous This function handles retrieving the prev lesson.
        Args:
            request (HTTPRequest): A http request object created automatically by Django.
            index (int): The index of the lesson to retrieve
        Returns:
            HttpResponse: A generated http response object to the request depending on whether or not
                          the user is authenticated.
        """
    if request.method == 'GET':
        if user_auth(request):
            current_user = UserInformation.objects.get(user=User.objects.get(email=request.user.email))
            if not not_complete(request):
                current_set = current_user.completed_sets.lessons.all()
            else:
                current_set = current_user.current_lesson_set.lessons.all()
            current_lesson = Lesson.objects.get(lesson_index=index)

            set_len = current_set.filter(is_alternate=False).count()
            print(set_len)
            num_done = finished_lesson_count(current_user)

            if index <= current_user.completed_lesson_index:
                lesson_info = get_log_data(current_user, index)
                print("lesson info: ", index)
                return render(request, "tutor/tutor.html",
                              {'lesson': current_lesson,
                               'lesson_code': lesson_info[0],
                               'concept': current_lesson.lesson_concept.all(),
                               'referenceSet': current_lesson.reference_set.all(),
                               'currLessonNum': current_user.current_lesson_index,
                               'setLength': set_len,
                               'finished_count': num_done,
                               'currSet': current_set,
                               'mood': lesson_info[1],
                               'past': lesson_info[2],
                               'completedLessonNum': current_user.completed_lesson_index,
                               'review': current_lesson.correct_feedback})
            return redirect("tutor:tutor")

    return redirect("accounts:profile")
예제 #12
0
def tutor(request):
    """function tutor This function handles the view for the tutor page of the application.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
    Returns:
        HttpResponse: A generated http response object to the request depending on whether or not
                      the user is authenticated.
    """

    print(request)

    # Case 1: We have received a POST request submitting code (needs a lot of work)
    if request.method == 'POST':
        # Case 1a: if the user exists
        if user_auth(request):
            # submitted_json = json.loads(request.body.decode('utf-8'))
            # if success, return next lesson
            # if fail, do something
            # Case 1aa: if the user has not completed set

            current_user = UserInformation.objects.get(user=User.objects.get(email=request.user.email))
            print(current_user.current_lesson_name)
            current_lesson = Lesson.objects.get(lesson_name=current_user.current_lesson_name)
            print('current_lesson: ', current_lesson)
            submitted_answer = reverse_mutate(json.loads(request.body.decode('utf-8'))['answer'].replace(" ", ""), get_inv_key())
            print('submitted answer: ' + submitted_answer)
            #Need to include submitted_answer in log data because it has the original variables

            log_data(request, submitted_answer)

            status = json.loads(request.body.decode('utf-8'))['status']
            print("status: ", status)

            if status == "success":
                current_user.completed_lesson_index = current_lesson.lesson_index

                if Lesson.objects.filter(lesson_name=current_lesson.correct).exists():
                    current_user.current_lesson_index = Lesson.objects.get(
                        lesson_name=current_lesson.correct).lesson_index
                else:
                    print("Lesson does not exist")

                print("completed index: ", current_user.completed_lesson_index)
                print("current index: ", current_user.current_lesson_index)

                if Lesson.objects.filter(lesson_index=current_user.current_lesson_index).exists():
                    curr_lesson = Lesson.objects.get(lesson_index=current_user.current_lesson_index)
                    print('curr_lesson: ', current_lesson)
                    current_user.current_lesson_name = curr_lesson.lesson_name
                    current_user.save()
                    if current_user.completed_lesson_index == current_user.current_lesson_index:
                        current_user.completed_sets = current_user.current_lesson_set
                        current_user.current_lesson_set = None
                        current_user.save()
                        print("in done: ", current_user.current_lesson_set)

            # print(feedback['type'])
            # goto = alternate_lesson_check(current_lesson, feedback['type'])
            # feedback.update({'newLessonIndex': str(Lesson.objects.get(lesson_name=goto.lesson_name).lesson_index)})
            # feedback.update({'newLessonCode': Lesson.objects.get(lesson_name=goto.lesson_name).code.lesson_code})
            # feedback.update({'newLessonEx': Lesson.objects.get(lesson_name=goto.lesson_name).reason.reasoning_type})

            return JsonResponse(check_feedback(current_lesson, submitted_answer, status))

    # Case 2: We have received a GET request requesting code
    elif request.method == 'GET':
        # Ensure user exists
        # Case 2a: if the user exists
        print(not_complete(request))
        if user_auth(request) and not_complete(request):
            # Case 2aa: if the user has a current set
            current_user = UserInformation.objects.get(user=User.objects.get(email=request.user.email))
            current_set = current_user.current_lesson_set.lessons.all()
            set_len = current_set.filter(is_alternate=False).count()
            print(set_len)
            num_done = finished_lesson_count(current_user)
            # Case 2aaa: if the current set has a lesson of index that the user is on, set to current lesson
            if Lesson.objects.filter(lesson_index=current_user.current_lesson_index).exists():
                current_lesson = Lesson.objects.get(lesson_index=current_user.current_lesson_index)

                # check if mutatable then mutate:
                code_after_mutate = can_mutate(request)

                if current_lesson.reason.reasoning_type == 'MC' or current_lesson.reason.reasoning_type == 'Both':
                    return render(request, "tutor/tutor.html",
                                  {'lesson': current_lesson,
                                   'lesson_code': code_after_mutate,
                                   'concept': current_lesson.lesson_concept.all(),
                                   'referenceSet': current_lesson.reference_set.all(),
                                   'reason': current_lesson.reason.reasoning_question,
                                   'mc_set': current_lesson.reason.mc_set.all(),
                                   'currLessonNum': current_user.current_lesson_index,
                                   'completedLessonNum': current_user.completed_lesson_index,
                                   'setLength': set_len,
                                   'finished_count': num_done,
                                   'currSet': current_set,
                                   'mood': current_user.mood,
                                   'review': 'none',
                                   'screen_record': current_lesson.screen_record,
                                   'audio_record': current_lesson.audio_record,
                                   'audio_transcribe': current_lesson.audio_transcribe,
                                   'user_email': request.user.email})
                # Case 2aaab: if question is of type Text
                elif current_lesson.reason.reasoning_type == 'Text':
                    return render(request, "tutor/tutor.html",
                                  {'lesson': current_lesson,
                                   'lesson_code': code_after_mutate,
                                   'concept': current_lesson.lesson_concept.all(),
                                   'referenceSet': current_lesson.reference_set.all(),
                                   'reason': current_lesson.reason.reasoning_question,
                                   'currLessonNum': current_user.current_lesson_index,
                                   'completedLessonNum': current_user.completed_lesson_index,
                                   'setLength': set_len,
                                   'finished_count': num_done,
                                   'currSet': current_set,
                                   'mood': current_user.mood,
                                   'review': 'none',
                                   'screen_record': current_lesson.screen_record,
                                   'audio_record': current_lesson.audio_record,
                                   'audio_transcribe': current_lesson.audio_transcribe,
                                   'user_email': request.user.email})
                # Case 2aaac: if question is of type none

                return render(request, "tutor/tutor.html",
                              {'lesson': current_lesson,
                               'lesson_code': code_after_mutate,
                               'concept': current_lesson.lesson_concept.all(),
                               'referenceSet': current_lesson.reference_set.all(),
                               'currLessonNum': current_user.current_lesson_index,
                               'completedLessonNum': current_user.completed_lesson_index,
                               'setLength': set_len,
                               'finished_count': num_done,
                               'currSet': current_set,
                               'mood': current_user.mood,
                               'review': 'none',
                               'screen_record': current_lesson.screen_record,
                               'audio_record': current_lesson.audio_record,
                               'audio_transcribe': current_lesson.audio_transcribe,
                               'user_email': request.user.email})
    return redirect("accounts:profile")
예제 #13
0
def class_view_educator(request, classID):
    """function educator This function handles the view for the educator page of the application.

    Args:
        request (HTTPRequest): A http request object created automatically by Django.
        classID (int): ID of the class requested

    Returns:
        HttpResponse: A generated http response object to the request.
    """
    # Is user valid?
    if user_auth(request):
        # Case 1: User is valid
        user_info = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        # Does user instruct the class?
        if user_auth_inst(user_info, classID):
            # Case 1a: User is educator of class

            if request.method == 'POST':
                # Handle assignment creation
                main_set = request.POST.get('main_set', None)
                start_date = date.fromisoformat(
                    request.POST.get('start_date',
                                     date.today().isoformat()))
                end_date = request.POST.get('end_date', None)

                # Basically a do: while(False) loop
                while True:
                    if main_set is None:
                        messages.error(request, "You must select a main set!")
                        break
                    if end_date is None:
                        messages.error(request, "You must supply a due date!")
                        break
                    end_date = date.fromisoformat(end_date)
                    if end_date < start_date:
                        messages.error(
                            request, "Assignment must open before it closes!")
                        break
                    new_assignment = Assignment(class_key_id=classID,
                                                main_set_id=main_set,
                                                start_date=start_date,
                                                end_date=end_date)
                    new_assignment.save()
                    return redirect(
                        reverse('educator:class-view', args=[classID]))

            # Error carried from POST endpoints
            if 'error' in request.session:
                error = request.session['error']
                del request.session['error']
                messages.error(request, error)

            return render(
                request, "educator/assignments_educator.html", {
                    'class': Class.objects.get(id=classID),
                    'main_sets': MainSet.objects.filter(show=True),
                    'today': date.today().isoformat()
                })
        else:
            # Case 1b: User doesn't teach class
            return redirect("/educator/")
    else:
        # Case 2: User doesn't exist in table
        return redirect("/accounts/settings")
예제 #14
0
def promote_student(request):
    """function educator This function handles the POST request for making a student an educator

    Args:
        request (HTTPRequest): A http request object created automatically by Django.

    Returns:
        HttpResponse: A generated http response object to the request.
    """

    if request.method != 'POST':
        return redirect("/educator/")

    # Get class
    try:
        class_id = request.POST.get('class_id', -1)
        Class.objects.get(id=class_id)
    except Class.DoesNotExist:
        # Class doesn't exist!
        return redirect('/educator/')

    # Is user valid?
    if user_auth(request):
        # Case 1: User is valid
        user_info = UserInformation.objects.get(user=User.objects.get(
            email=request.user.email))
        # Does user instruct the class?
        if user_auth_inst(user_info, class_id):
            # Case 1a: User is educator of class
            # Handle promotion
            student_id = request.POST.get('student_id', None)

            # Basically a do: while(False) loop
            while True:
                if student_id is None:
                    request.session['error'] = "Server error. Try again?"
                    break

                try:
                    membership = ClassMembership.objects.get(
                        user_id=student_id, class_taking_id=class_id)
                except ClassMembership.DoesNotExist:
                    request.session['error'] = "Server error. Try again?"
                    break

                try:
                    account = UserInformation.objects.get(id=student_id)
                except UserInformation.DoesNotExist:
                    request.session['error'] = "Server error. Try again?"
                    break

                account.user_educator = True
                membership.is_educator = True
                account.save()
                membership.save()
                break

            return redirect(reverse('educator:members', args=[class_id]))
        else:
            # Case 1b: User doesn't teach class
            return redirect("/educator/")
    else:
        # Case 2: User doesn't exist in table
        return redirect("/accounts/settings")
예제 #15
0
def tutor(request):
    """function tutor This function handles the view for the tutor page of the application.
    Args:
        request (HTTPRequest): A http request object created automatically by Django.
    Returns:
        HttpResponse: A generated http response object to the request depending on whether or not
                      the user is authenticated.
    """

    print(request)

    # Case 1: We have received a POST request submitting code (needs a lot of work)
    if request.method == 'POST':
        # Case 1a: if the user exists
        if user_auth(request):
            # submitted_json = json.loads(request.body.decode('utf-8'))
            # if success, return next lesson
            # if fail, do something
            # Case 1aa: if the user has not completed set

            current_user = UserInformation.objects.get(user=User.objects.get(
                email=request.user.email))
            current_lesson = Lesson.objects.get(
                lesson_name=current_user.current_lesson_name)

            status = json.loads(request.body.decode('utf-8'))['status']
            print("status: ", status)
            submitted_answer = json.loads(
                request.body.decode('utf-8'))['answer'].replace(" ", "")

            submitted_answer = reverse_mutate(submitted_answer)

            log_data(request)
            unlock_next = False

            if status == "success":
                log_lesson(request)
                main_set = MainSet.objects.filter(
                    set_name=current_user.current_main_set)[0]
                print(main_set)

                # if they are correct in a alt lesson, find correct to send to
                print("current_lesson.is_alternate: ",
                      current_lesson.is_alternate,
                      " current_user.current_lesson_index: ",
                      current_user.current_lesson_index)
                if current_lesson.is_alternate and current_user.current_lesson_index != 0:
                    print(current_lesson.correct, "%%%%%%%%%%")
                    current_user.current_lesson_name = Lesson.objects.get(
                        lesson_name=current_lesson.correct).lesson_name
                    index = 0

                    current_set = Lesson.objects.get(
                        lesson_name=current_user.current_lesson_name)
                    print("CURRENT LESSON NAME: ", current_set, " ***** ",
                          current_user.current_lesson_set.lessons.all())

                    if current_set in current_user.current_lesson_set.lessons.all(
                    ):
                        print("PRINT LESSONS: ",
                              current_user.current_lesson_set.lessons.all())

                        #if current_user.current_lesson_name in current_user.current_lesson_set.lessons.all():
                        for index, item in enumerate(
                                current_user.current_lesson_set.lessons.all()):
                            print(index, "&&&&&&&&&", item.lesson_name)
                            if item.lesson_name == current_lesson.correct:
                                break
                        current_user.current_lesson_index = index
                    else:
                        for index, item in enumerate(main_set.lessons.all()):
                            if item == current_user.current_lesson_set:
                                break

                        next_set = LessonSet.objects.get(
                            set_name=main_set.lessons.all()[index + 1])
                        print("***************** ", next_set)
                        current_user.current_lesson_set = next_set
                        current_user.current_lesson_name = next_set.first_in_set.lesson_name
                        current_user.current_lesson_index = 0

                    current_user.save()
                    unlock_next = True
                    return JsonResponse(
                        check_feedback(current_lesson, submitted_answer,
                                       status, unlock_next))

                # find the index of the next lesson set by enumerating query set of all sets
                for index, item in enumerate(main_set.lessons.all()):
                    if item == current_user.current_lesson_set:
                        break
                # return if last set to go through
                print("|||||||", index, "|||||||", len(main_set.lessons.all()))
                if index + 1 >= len(main_set.lessons.all()):
                    current_user.completed_sets.add(
                        current_user.current_main_set)
                    current_user.current_lesson_set = None
                    current_user.current_main_set = None
                    current_user.save()
                    unlock_next = True
                    print("in done: ", current_user.current_lesson_set)
                    return JsonResponse(
                        check_feedback(current_lesson, submitted_answer,
                                       status, unlock_next))
                    # return render(request, "accounts:profile")

                next_set = LessonSet.objects.get(
                    set_name=main_set.lessons.all()[index + 1])
                current_user.current_lesson_set = next_set
                current_user.current_lesson_name = next_set.first_in_set.lesson_name
                current_user.save()

            # if a user is not successful and there are alternates available
            print(current_lesson.sub_lessons_available, "%%%%%%%%%%")
            if status != "success" and current_lesson.sub_lessons_available:
                lesson_type = check_type(current_lesson, submitted_answer,
                                         status)
                alt_lesson = alternate_lesson_check(
                    current_lesson,
                    lesson_type)  # how to set this and render new page

                # check if we changed to an alternate
                if Lesson.objects.get(
                        lesson_title=alt_lesson
                ).lesson_name != current_user.current_lesson_name:
                    unlock_next = True
                    current_user.current_lesson_name = Lesson.objects.get(
                        lesson_title=alt_lesson).lesson_name
                    for index, item in enumerate(
                            current_user.current_lesson_set.lessons.all()):
                        if item == alt_lesson:
                            break
                    current_user.current_lesson_index = index
                    current_user.save()
                    print("******* ", alt_lesson, " ", index)
            return JsonResponse(
                check_feedback(current_lesson, submitted_answer, status,
                               unlock_next))

    # Case 2: We have received a GET request requesting code
    elif request.method == 'GET':
        # Ensure user exists
        # Case 2a: if the user exists
        print("in the get")

        if user_auth(request) and not_complete(request):

            # Case 2aa: if the user has a current set
            current_user = UserInformation.objects.get(user=User.objects.get(
                email=request.user.email))

            current_set = current_user.current_lesson_set.lessons.all()
            set_len = len(current_user.current_main_set.lessons.all())
            print(set_len)
            num_done = finished_lesson_count(current_user)
            print("===============", num_done)
            # Case 2aaa: if the current set has a lesson of index that the user is on, set to current lesson

            if Lesson.objects.filter(lesson_title=current_set[
                    current_user.current_lesson_index]).exists():
                current_lesson = Lesson.objects.get(lesson_title=current_set[
                    current_user.current_lesson_index])
                print("in if 1 - Current lesson: ", current_lesson)

                # Just as we are altering the code here with mutate, this will pull the previous answer
                # to put in place for sub lessons. What identifiers do we need?

                current_lesson.code.lesson_code = can_mutate(current_lesson)
                current_lesson.code.lesson_code = replace_previous(
                    current_user, current_lesson.code.lesson_code,
                    current_lesson.is_alternate)
                # create an ordered set
                index = 0
                for index, item in enumerate(
                        current_user.current_main_set.lessons.all()):
                    if item == current_user.current_lesson_set:
                        break
                if current_lesson.reason.reasoning_type == 'MC' or current_lesson.reason.reasoning_type == 'Both':
                    return render(
                        request, "tutor/tutor.html", {
                            'lesson':
                            current_lesson,
                            'lesson_code':
                            current_lesson.code.lesson_code,
                            'concept':
                            current_lesson.lesson_concept.all(),
                            'referenceSet':
                            current_lesson.reference_set.all(),
                            'reason':
                            current_lesson.reason.reasoning_question,
                            'mc_set':
                            current_lesson.reason.mc_set.all(),
                            'currLessonNum':
                            current_user.current_lesson_index,
                            'completedLessonNum':
                            current_user.completed_lesson_index,
                            'setLength':
                            set_len,
                            'finished_count':
                            num_done,
                            'orderedSet':
                            current_user.current_main_set.lessons.all(),
                            'mood':
                            current_user.mood,
                            'review':
                            'none',
                            'screen_record':
                            current_lesson.screen_record,
                            'audio_record':
                            current_lesson.audio_record,
                            'audio_transcribe':
                            current_lesson.audio_transcribe,
                            'user_email':
                            request.user.email,
                            'index':
                            index
                        })
                # Case 2aaab: if question is of type Text
                elif current_lesson.reason.reasoning_type == 'Text':
                    return render(
                        request, "tutor/tutor.html", {
                            'lesson':
                            current_lesson,
                            'lesson_code':
                            current_lesson.code.lesson_code,
                            'concept':
                            current_lesson.lesson_concept.all(),
                            'referenceSet':
                            current_lesson.reference_set.all(),
                            'reason':
                            current_lesson.reason.reasoning_question,
                            'currLessonNum':
                            current_user.current_lesson_index,
                            'completedLessonNum':
                            current_user.completed_lesson_index,
                            'setLength':
                            set_len,
                            'finished_count':
                            num_done,
                            'orderedSet':
                            current_user.current_main_set.lessons.all(),
                            'mood':
                            current_user.mood,
                            'review':
                            'none',
                            'screen_record':
                            current_lesson.screen_record,
                            'audio_record':
                            current_lesson.audio_record,
                            'audio_transcribe':
                            current_lesson.audio_transcribe,
                            'user_email':
                            request.user.email,
                            'index':
                            index
                        })
                # Case 2aaac: if question is of type none

                return render(
                    request, "tutor/tutor.html", {
                        'lesson': current_lesson,
                        'lesson_code': current_lesson.code.lesson_code,
                        'concept': current_lesson.lesson_concept.all(),
                        'referenceSet': current_lesson.reference_set.all(),
                        'currLessonNum': current_user.current_lesson_index,
                        'completedLessonNum':
                        current_user.completed_lesson_index,
                        'setLength': set_len,
                        'finished_count': num_done,
                        'orderedSet':
                        current_user.current_main_set.lessons.all(),
                        'mood': current_user.mood,
                        'review': 'none',
                        'screen_record': current_lesson.screen_record,
                        'audio_record': current_lesson.audio_record,
                        'audio_transcribe': current_lesson.audio_transcribe,
                        'user_email': request.user.email,
                        'index': index
                    })
    return redirect("accounts:profile")