Exemple #1
0
def scorecard_view(request):
    auth = ApiKeyAuthentication()
    if auth.is_authenticated(request) is not True:
        return HttpResponse("Unauthorized", status=401)

    record_mobile_tracker(request, None, "scorecard", '{"en":"homepage"}')

    start_date = datetime.datetime.now() - datetime.timedelta(days=14)
    end_date = datetime.datetime.now()
    media = {
        "views": Tracker.activity_views(user=request.user, type="media", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="media", start_date=start_date, end_date=end_date),
        "points": Points.media_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    quiz = {
        "views": Tracker.activity_views(user=request.user, type="quiz", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="quiz", start_date=start_date, end_date=end_date),
        "points": Points.quiz_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    acts = {
        "views": Tracker.activity_views(user=request.user, type="page", start_date=start_date, end_date=end_date),
        "secs": Tracker.activity_secs(user=request.user, type="page", start_date=start_date, end_date=end_date),
        "points": Points.page_points(user=request.user, start_date=start_date, end_date=end_date),
    }
    total = {
        "views": acts["views"] + quiz["views"] + media["views"],
        "secs": acts["secs"] + quiz["secs"] + media["secs"],
        "points": acts["points"] + quiz["points"] + media["points"],
    }
    scorecard = {"media": media, "quiz": quiz, "acts": acts, "total": total}
    return render_to_response(
        "oppia/mobile/scorecard.html", {"scorecard": scorecard}, context_instance=RequestContext(request)
    )
    def leaderboard(self, request, **kwargs):

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if request.is_secure():
            prefix = 'https://'
        else:
            prefix = 'http://'

        response_data = {}
        response_data['generated_date'] = timezone.now()
        response_data['server'] = prefix + request.META['SERVER_NAME']
        leaderboard = Points.get_leaderboard()
        response_data['leaderboard'] = []

        for idx, leader in enumerate(leaderboard):
            leader_data = {}
            leader_data['position'] = idx + 1
            leader_data['username'] = leader.username
            leader_data['first_name'] = leader.first_name
            leader_data['last_name'] = leader.last_name
            leader_data['points'] = leader.total
            leader_data['badges'] = leader.badges
            response_data['leaderboard'].append(leader_data)

        return JsonResponse(response_data)
def tracker_callback(sender, **kwargs):

    tracker = kwargs.get('instance')
    description = None

    print tracker.uuid

    if not apply_points(tracker.user):
        return

    if tracker.course is not None and tracker.course.user == tracker.user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return

    if tracker.event not in NON_ACTIVITY_EVENTS:
        if not tracker.activity_exists():
            return

        type = 'activity_completed'
        points = OPPIA_DEFAULT_POINTS['ACTIVITY_COMPLETED']
        if tracker.get_activity_type() == "media":
            description = "Media played: " + tracker.get_activity_title()
            type = 'mediaplayed'
            if tracker.is_first_tracker_today():
                points = OPPIA_DEFAULT_POINTS['MEDIA_STARTED']
            else:
                points = 0
            points += (OPPIA_DEFAULT_POINTS['MEDIA_PLAYING_POINTS_PER_INTERVAL'] * math.floor(tracker.time_taken / OPPIA_DEFAULT_POINTS['MEDIA_PLAYING_INTERVAL']))
            if points > OPPIA_DEFAULT_POINTS['MEDIA_MAX_POINTS']:
                points = OPPIA_DEFAULT_POINTS['MEDIA_MAX_POINTS']
        else:
            description = "Activity completed: " + tracker.get_activity_title()

    if tracker.points is not None:
        points = tracker.points
        type = tracker.event
        if not description:
            description = tracker.event
    else:
        if tracker.get_activity_type() is not "media":
            if not tracker.is_first_tracker_today():
                return
            if not tracker.completed:
                return

    p = Points()
    p.points = points
    p.type = type
    p.description = description
    p.user = tracker.user
    p.course = tracker.course
    p.save()

    return
def tracker_callback(sender, **kwargs):
    tracker = kwargs.get('instance')
    if not apply_points(tracker.user):
        return
    
    if not tracker.activity_exists():
        return
    
    if tracker.course is not None and tracker.course.user == tracker.user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return
    
    cohort_teacher = Cohort.teacher_member_now(tracker.course, tracker.user)
    if cohort_teacher is not None and settings.OPPIA_TEACHERS_EARN_POINTS is False:
        return
    
    if tracker.get_activity_type() is not "media":
        if not tracker.is_first_tracker_today():
            return
        if not tracker.completed:
            return
    
    type = 'activitycompleted'
    points = settings.OPPIA_POINTS['ACTIVITY_COMPLETED']
    if tracker.get_activity_type() == "media":
        description =  "Media played: " + tracker.get_activity_title()
        type = 'mediaplayed'
        if tracker.is_first_tracker_today():
            points = settings.OPPIA_POINTS['MEDIA_STARTED']
        else:
            points = 0
        points =  (settings.OPPIA_POINTS['MEDIA_PLAYING_POINTS_PER_INTERVAL'] * math.floor(tracker.time_taken/settings.OPPIA_POINTS['MEDIA_PLAYING_INTERVAL']))
        if points > settings.OPPIA_POINTS['MEDIA_MAX_POINTS']:
            points = settings.OPPIA_POINTS['MEDIA_MAX_POINTS']
    else:
        description = "Activity completed: " + tracker.activity_title    
       
    p = Points()
    p.points = points
    p.type = type
    p.description = description
    p.user = tracker.user
    p.course = tracker.course
    p.cohort = Cohort.student_member_now(tracker.course,tracker.user)
    p.save()
    
    # @TODO test if tracker submitted on time
    
    return
def home_view(request):
    activity = []
    if request.user.is_authenticated():
        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")  
                start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d")   
                interval =  form.cleaned_data.get("interval")          
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)
        
        if interval == 'days':
            no_days = (end_date-start_date).days + 1
            
            for i in range(0,no_days,+1):
                temp = start_date + datetime.timedelta(days=i)
                day = temp.strftime("%d")
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = Tracker.objects.filter(course__isnull=False, course__is_draft=False, user__is_staff=False, course__is_archived=False,tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).count()
                activity.append([temp.strftime("%d %b %Y"),count])
        else:
            delta = relativedelta(months=+1)
            
            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                print tmp_date
                tmp_date += delta
                no_months += 1
                
            for i in range(0,no_months,+1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = Tracker.objects.filter(course__isnull=False, course__is_draft=False, user__is_staff=False, course__is_archived=False,tracker_date__month=month,tracker_date__year=year).count()
                activity.append([temp.strftime("%b %Y"),count])
    else:
        form = None
    leaderboard = Points.get_leaderboard(10)
    return render_to_response('oppia/home.html',
                              {'form': form,
                               'recent_activity':activity, 
                               'leaderboard':leaderboard}, 
                              context_instance=RequestContext(request))
def recent_activity(request, course_id):

    course, response = can_view_course_detail(request, course_id)

    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = "days"

    if request.method == "POST":
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date + " 00:00:00", "%Y-%m-%d %H:%M:%S")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date + " 23:59:59", "%Y-%m-%d %H:%M:%S")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data["start_date"] = start_date
        data["end_date"] = end_date
        data["interval"] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == "days":
        daily_stats = (
            CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)
            .values("day", "type")
            .annotate(total=Sum("total"))
        )

        dates = generate_graph_data(daily_stats, False)

    else:
        monthly_stats = (
            CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)
            .extra({"month": "month(day)", "year": "year(day)"})
            .values("month", "year", "type")
            .annotate(total=Sum("total"))
            .order_by("year", "month")
        )

        dates = generate_graph_data(monthly_stats, True)

    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response(
        "oppia/course/activity.html",
        {"course": course, "form": form, "data": dates, "leaderboard": leaderboard},
        context_instance=RequestContext(request),
    )
def scorecard_view(request):
    auth = ApiKeyAuthentication()
    if auth.is_authenticated(request) is not True:
        return HttpResponse('Unauthorized', status=401)
    start_date = datetime.datetime.now() - datetime.timedelta(days=14)
    end_date = datetime.datetime.now()
    media = {'views':Tracker.activity_views(user=request.user,type='media',start_date=start_date,end_date=end_date),
             'secs':Tracker.activity_secs(user=request.user,type='media',start_date=start_date,end_date=end_date),
             'points':Points.media_points(user=request.user,start_date=start_date,end_date=end_date)}
    quiz = {'views':Tracker.activity_views(user=request.user,type='quiz',start_date=start_date,end_date=end_date),
             'secs':Tracker.activity_secs(user=request.user,type='quiz',start_date=start_date,end_date=end_date),
             'points':Points.quiz_points(user=request.user,start_date=start_date,end_date=end_date)}
    acts = {'views':Tracker.activity_views(user=request.user,type='page',start_date=start_date,end_date=end_date),
             'secs':Tracker.activity_secs(user=request.user,type='page',start_date=start_date,end_date=end_date),
             'points':Points.page_points(user=request.user,start_date=start_date,end_date=end_date)}
    total = {'views':acts['views'] + quiz['views'] + media['views'],
             'secs': acts['secs'] + quiz['secs'] + media['secs'],
             'points': acts['points'] + quiz['points'] + media['points'],}
    scorecard = {'media':media, 'quiz':quiz, 'acts':acts, 'total': total}
    return render_to_response('oppia/mobile/scorecard.html',{ 'scorecard':scorecard }, context_instance=RequestContext(request))
def get_points(request):
    if not request.user.is_authenticated():
        return {'points': 0, 'badges':0 }
    else:
        points = Points.get_userscore(request.user)
        if points is None:
            points = 0
        badges = Award.get_userawards(request.user)
        if badges is None:
            badges = 0
    return {'points': points, 'badges':badges }
def cohort_view(request,cohort_id):
    if not request.user.is_staff:
        raise Http404  
    cohort = Cohort.objects.get(pk=cohort_id)
    
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    
    # get teacher activity
    teacher_activity = []
    no_days = (end_date-start_date).days + 1
    teachers =  User.objects.filter(participant__role=Participant.TEACHER, participant__cohort=cohort)
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        day = temp.strftime("%d")
        month = temp.strftime("%m")
        year = temp.strftime("%Y")
        count = Tracker.objects.filter(course__coursecohort__cohort=cohort, 
                                       user__is_staff=False,
                                       user__in=teachers, 
                                       tracker_date__day=day,
                                       tracker_date__month=month,
                                       tracker_date__year=year).count()
        teacher_activity.append([temp.strftime("%d %b %Y"),count])
        
    # get student activity
    student_activity = []
    no_days = (end_date-start_date).days + 1
    students =  User.objects.filter(participant__role=Participant.STUDENT, participant__cohort=cohort)    
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        day = temp.strftime("%d")
        month = temp.strftime("%m")
        year = temp.strftime("%Y")
        count = Tracker.objects.filter(course__coursecohort__cohort=cohort, 
                                       user__is_staff=False,
                                       user__in=students,  
                                       tracker_date__day=day,
                                       tracker_date__month=month,
                                       tracker_date__year=year).count()
        student_activity.append([temp.strftime("%d %b %Y"),count])
        
    # get leaderboard
    leaderboard = Points.get_cohort_leaderboard(10, cohort)
    
    
    return render_to_response('oppia/course/cohort-activity.html',
                              {'cohort':cohort,
                               'teacher_activity': teacher_activity,
                               'student_activity': student_activity, 
                               'leaderboard': leaderboard, }, 
                              context_instance=RequestContext(request))
def signup_callback(sender, **kwargs):
    user = kwargs.get('instance')
    created = kwargs.get('created')
    if created:
        p = Points()
        p.points = settings.OPPIA_POINTS['REGISTER']
        p.type = 'signup'
        p.description = "Initial registration"
        p.user = user
        p.save()
    return
Exemple #11
0
def recent_activity(request, course_id):

    course, response = can_view_course_detail(request, course_id)
    if response is not None:
        raise response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'

    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date + " 00:00:00", "%Y-%m-%d %H:%M:%S")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date + " 23:59:59", "%Y-%m-%d %H:%M:%S")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == 'days':
        daily_stats = CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date) \
                        .values('day', 'type') \
                        .annotate(total=Sum('total'))

        dates = generate_graph_data(daily_stats, False)

    else:
        monthly_stats = CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date) \
                        .extra({'month': 'month(day)', 'year': 'year(day)'}) \
                        .values('month', 'year', 'type') \
                        .annotate(total=Sum('total')) \
                        .order_by('year', 'month')

        dates = generate_graph_data(monthly_stats, True)

    leaderboard = Points.get_leaderboard(10, course)
    return render(request, 'oppia/course/activity.html',
                              {'course': course,
                               'monthly': interval == 'months',
                               'form': form,
                                'data': dates,
                                'leaderboard': leaderboard})
Exemple #12
0
def badgeaward_callback(sender, **kwargs):
    award = kwargs.get('instance')
    if not apply_points(award.user):
        return

    p = Points()
    p.points = award.badge.points
    p.type = 'badgeawarded'
    p.description = award.description
    p.user = award.user
    p.save()
    return
def home_view(request):
    activity = []
    if request.user.is_authenticated():
        startdate = datetime.datetime.now()
        staff = User.objects.filter(is_staff=True)
        for i in range(31,-1,-1):
            temp = startdate - datetime.timedelta(days=i)
            day = temp.strftime("%d")
            month = temp.strftime("%m")
            year = temp.strftime("%y")
            count = Tracker.objects.filter(tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).exclude(user_id__in=staff).count()
            activity.append([temp.strftime("%d %b %y"),count])
    leaderboard = Points.get_leaderboard(10)
    return render_to_response('oppia/home.html',{'recent_activity':activity, 'leaderboard':leaderboard}, context_instance=RequestContext(request))
def course_download_callback(sender, **kwargs):
    user = kwargs.get('user')
    course = kwargs.get('course')
    
    # check not superuser
    if user.is_superuser:
        return 
    
    if not course.is_first_download(user):
        return 
    
    p = Points()
    p.points = settings.OPPIA_POINTS['COURSE_DOWNLOADED']
    p.type = 'coursedownloaded'
    p.description = "Course downloaded: " + course.get_title()
    p.user = user
    p.course = course
    p.cohort = Cohort.student_member_now(course,user)
    p.save()
    return
def badgeaward_callback(sender, **kwargs):
    award = kwargs.get('instance')
    
    # check not superuser
    if award.user.is_superuser:
        return 
    
    p = Points()
    p.points = award.badge.points
    p.type = 'badgeawarded'
    p.description = award.description
    p.user = award.user
    p.save()
    return
def recent_activity(request,id):
    course = Course.objects.get(pk=id)
    dates = []
    startdate = datetime.datetime.now()
    staff = User.objects.filter(is_staff=True)
    for i in range(31,-1,-1):
        temp = startdate - datetime.timedelta(days=i)
        day = temp.strftime("%d")
        month = temp.strftime("%m")
        year = temp.strftime("%y")
        count_act_page = Tracker.objects.filter(course=course,type='page',tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).exclude(user_id__in=staff).count()
        count_act_quiz = Tracker.objects.filter(course=course,type='quiz',tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).exclude(user_id__in=staff).count()
        count_media = Tracker.objects.filter(course=course,type='media',tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).exclude(user_id__in=staff).count()
        dates.append([temp.strftime("%d %b %y"),count_act_page,count_act_quiz,count_media])
    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response('oppia/course/activity.html',{'course': course,'data':dates, 'leaderboard':leaderboard}, context_instance=RequestContext(request))
def leaderboard_view(request):
    lb = Points.get_leaderboard(100)
    paginator = Paginator(lb, 25) # Show 25 contacts per page

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        leaderboard = paginator.page(page)
    except (EmptyPage, InvalidPage):
        leaderboard = paginator.page(paginator.num_pages)

    return render_to_response('oppia/leaderboard.html',{'page':leaderboard}, context_instance=RequestContext(request))
def createquiz_callback(sender, **kwargs):
    quiz = kwargs.get('instance')
    created = kwargs.get('created')
    
    if not apply_points(quiz.owner):
        return
    
    if created:
        p = Points()
        p.points = settings.OPPIA_POINTS['QUIZ_CREATED']
        p.type = 'quizcreated'
        p.description = "Quiz created: " + quiz.title
        p.user = quiz.owner
        p.save()
    return
def tracker_callback(sender, **kwargs):
    tracker = kwargs.get('instance')
    
    # check not superuser
    if tracker.user.is_superuser:
        return 
    
    if not tracker.is_first_tracker_today():
        return
    
    if not tracker.activity_exists():
        return
    
    if not tracker.completed:
        return
    
    type = 'activitycompleted'
    points = settings.OPPIA_POINTS['ACTIVITY_COMPLETED']
    if tracker.get_activity_type() == "media":
        description =  "Media played: " + tracker.get_activity_title()
        type = 'mediaplayed'
        points = settings.OPPIA_POINTS['MEDIA_PLAYED']
    else:
        description = "Activity completed: " + tracker.get_activity_title()    
       
    p = Points()
    p.points = points
    p.type = type
    p.description = description
    p.user = tracker.user
    p.course = tracker.course
    p.cohort = Cohort.student_member_now(tracker.course,tracker.user)
    p.save()
    
    # test if tracker submitted on time
    
    return
def course_download_callback(sender, **kwargs):
    user = kwargs.get('user')
    course = kwargs.get('course')
    if not apply_points(user):
        return
    
    if course.user == user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return
    
    if not course.is_first_download(user):
        return 
    
    p = Points()
    p.points = settings.OPPIA_POINTS['COURSE_DOWNLOADED']
    p.type = 'coursedownloaded'
    p.description = "Course downloaded: " + course.get_title()
    p.user = user
    p.course = course
    p.save()
    return
def createquiz_callback(sender, **kwargs):
    warnings.warn(
        "oppia.signals.createquiz_callback() is deprecated and will be removed in Oppia server 0.11.0.",
        RemovedInOppia0110Warning, 2)
    quiz = kwargs.get('instance')
    created = kwargs.get('created')

    if not apply_points(quiz.owner):
        return

    if created:
        p = Points()
        p.points = OPPIA_DEFAULT_POINTS['QUIZ_CREATED']
        p.type = 'quizcreated'
        p.description = "Quiz created: " + quiz.title
        p.user = quiz.owner
        p.save()
    return
def course_download_callback(sender, **kwargs):
    warnings.warn(
        "oppia.signals.course_download_callback() is deprecated and will be removed in Oppia server 0.11.0.",
        RemovedInOppia0110Warning, 2)
    user = kwargs.get('user')
    course = kwargs.get('course')
    if not apply_points(user):
        return

    if course.user == user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return

    if not course.is_first_download(user):
        return

    p = Points()
    p.points = OPPIA_DEFAULT_POINTS['COURSE_DOWNLOADED']
    p.type = 'coursedownloaded'
    p.description = "Course downloaded: " + course.get_title()
    p.user = user
    p.course = course
    p.save()
    return
Exemple #23
0
def home_view(request):
    activity = []
    if request.user.is_authenticated():
        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")  
                start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d")   
                interval =  form.cleaned_data.get("interval")          
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)
        
        if interval == 'days':
            no_days = (end_date-start_date).days + 1
            trackers = Tracker.objects.filter(course__isnull=False, 
                                              course__is_draft=False, 
                                              user__is_staff=False, 
                                              course__is_archived=False,
                                              tracker_date__gte=start_date,
                                              tracker_date__lte=end_date).extra({'activity_date':"date(tracker_date)"}).values('activity_date').annotate(count=Count('id'))
            for i in range(0,no_days,+1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"),count])
        else:
            delta = relativedelta(months=+1)
            
            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                print tmp_date
                tmp_date += delta
                no_months += 1
                
            for i in range(0,no_months,+1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = Tracker.objects.filter(course__isnull=False,
                                               course__is_draft=False,
                                               user__is_staff=False,
                                               course__is_archived=False,
                                               tracker_date__month=month,
                                               tracker_date__year=year).count()
                activity.append([temp.strftime("%b %Y"),count])
    else:
        form = None
    leaderboard = Points.get_leaderboard(10)
    return render_to_response('oppia/home.html',
                              {'form': form,
                               'recent_activity':activity, 
                               'leaderboard':leaderboard}, 
                              context_instance=RequestContext(request))
Exemple #24
0
def home_view(request):

    activity = []
    leaderboard = None

    if request.user.is_authenticated:
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user = request.user
            up.save()

        dashboard_accessed.send(sender=None, request=request, data=None)

        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))

        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))

        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")
                start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
                interval = form.cleaned_data.get("interval")
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)

        if interval == 'days':
            no_days = (end_date - start_date).days + 1
            tracker_stats = CourseDailyStats.objects.filter(day__gte=start_date, day__lte=end_date).values('day').annotate(count=Sum('total'))

            for i in range(0, no_days, +1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in tracker_stats if dct['day'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"), count])
        else:
            delta = relativedelta(months=+1)

            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                tmp_date += delta
                no_months += 1

            for i in range(0, no_months, +1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = CourseDailyStats.objects.filter(day__month=month, day__year=year).aggregate(total=Sum('total')).get('total', 0)
                activity.append([temp.strftime("%b %Y"), 0 if count is None else count])

        leaderboard = Points.get_leaderboard(10)

    else:
        form = None

    return render(request, 'oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity,
                               'leaderboard': leaderboard})
def recent_activity(request,id):
    course = check_can_view(request, id)
    
    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'
    
    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")  
            start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d") 
            interval =  form.cleaned_data.get("interval")               
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)
    
    dates = []
    if interval == 'days':
        no_days = (end_date-start_date).days + 1
        
        for i in range(0,no_days,+1):
            temp = start_date + datetime.timedelta(days=i)
            day = temp.strftime("%d")
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(course=course,tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).values('type').annotate(total=Count('type'))
            count_activity = {'page':0, 'quiz':0, 'media':0, 'resource':0, 'monitor': 0, 'total':0}
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
            
            dates.append([temp.strftime("%d %b %y"),count_activity])
    else:
        delta = relativedelta(months=+1)  
        no_months = 0
        tmp_date = start_date
        while tmp_date <= end_date:
            print tmp_date
            tmp_date += delta
            no_months += 1
            
        for i in range(0,no_months,+1):
            temp = start_date + relativedelta(months=+i)
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(course=course,tracker_date__month=month,tracker_date__year=year).values('type').annotate(total=Count('type'))
            count_activity = {'page':0, 'quiz':0, 'media':0, 'resource':0, 'monitor': 0, 'total':0}
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
            
            dates.append([temp.strftime("%b %y"),count_activity])
        
        
    leaderboard = Points.get_leaderboard(10, course)
    nav = get_nav(course,request.user)
    return render_to_response('oppia/course/activity.html',
                              {'course': course,
                               'form': form,
                                'nav': nav, 
                                'data':dates, 
                                'leaderboard':leaderboard}, 
                              context_instance=RequestContext(request))
 def dehydrate_quiz_points(self,bundle):
     start_date = datetime.datetime.now() - datetime.timedelta(days=14)
     end_date = datetime.datetime.now()
     return Points.quiz_points(user=bundle.obj,start_date=start_date,end_date=end_date)
Exemple #27
0
def quizattempt_callback(sender, **kwargs):
    quiz_attempt = kwargs.get('instance')

    quiz = quiz_attempt.quiz

    # find out if this quiz is part of a course
    course = None
    digest = quiz_attempt.get_quiz_digest()
    if digest is not None:
        # TODO - what are chances of 2 courses having the exact same activity? and what to do if they do?
        acts = Activity.objects.filter(digest=digest)
        for a in acts:
            course = a.section.course

    if quiz_attempt.points is not None:
        p = Points()
        p.points = quiz_attempt.points
        p.type = 'quiz_attempt'
        p.user = quiz_attempt.user
        p.description = quiz_attempt.event
        p.course = course
        p.save()
        return

    # Check user doesn't own the quiz
    if quiz.owner == quiz_attempt.user:
        return

    if not apply_points(quiz_attempt.user):
        return

    # find out is user is part of the cohort for this course
    if course is not None and course.user == quiz_attempt.user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return

    if quiz_attempt.is_first_attempt():
        # If it's the first time they've attempted this quiz award points
        p = Points()
        p.points = OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT']
        p.type = 'firstattempt'
        p.user = quiz_attempt.user
        p.description = "Bonus points for your first attempt at: " + quiz.title
        p.course = course
        p.save()

        # add percentage points for their first attempt
        if quiz_attempt.get_score_percent() > 0:
            p = Points()
            p.points = quiz_attempt.get_score_percent()
            p.type = 'firstattemptscore'
            p.description = "Score for first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.save()

        # if you get 100% on first attempt get bonus of 50 points
        if quiz_attempt.get_score_percent(
        ) >= OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT_THRESHOLD']:
            p = Points()
            p.points = OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT_BONUS']
            p.type = 'firstattemptbonus'
            p.description = "Bonus points for getting 100% in first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.save()

    elif quiz_attempt.is_first_attempt_today():
        # If it's the first time today they've attempted this quiz award 10 points
        p = Points()
        p.points = OPPIA_DEFAULT_POINTS['QUIZ_ATTEMPT']
        p.type = 'quizattempt'
        p.user = quiz_attempt.user
        p.description = "Quiz attempt at: " + quiz.title
        p.course = course
        p.save()

    return
def recent_activity(request, course_id):
    course, response = can_view_course_detail(request, course_id)

    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'

    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == 'days':
        no_days = (end_date - start_date).days + 1

        for i in range(0, no_days, +1):
            temp = start_date + datetime.timedelta(days=i)
            day = temp.strftime("%d")
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(
                course=course,
                tracker_date__day=day,
                tracker_date__month=month,
                tracker_date__year=year).values('type').annotate(
                    total=Count('type'))
            count_activity = {
                'page': 0,
                'quiz': 0,
                'media': 0,
                'resource': 0,
                'monitor': 0,
                'total': 0
            }
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']

            dates.append([temp.strftime("%d %b %y"), count_activity])
    else:
        delta = relativedelta(months=+1)
        no_months = 0
        tmp_date = start_date
        while tmp_date <= end_date:
            print tmp_date
            tmp_date += delta
            no_months += 1

        for i in range(0, no_months, +1):
            temp = start_date + relativedelta(months=+i)
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(
                course=course,
                tracker_date__month=month,
                tracker_date__year=year).values('type').annotate(
                    total=Count('type'))
            count_activity = {
                'page': 0,
                'quiz': 0,
                'media': 0,
                'resource': 0,
                'monitor': 0,
                'total': 0
            }
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']

            dates.append([temp.strftime("%b %y"), count_activity])

    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response('oppia/course/activity.html', {
        'course': course,
        'form': form,
        'data': dates,
        'leaderboard': leaderboard
    },
                              context_instance=RequestContext(request))
Exemple #29
0
 def get_queryset(self):
     return Points.get_leaderboard()
 def dehydrate_points(self,bundle):
     points = Points.get_userscore(User.objects.get(username=bundle.request.user.username))
     return points
Exemple #31
0
def home_view(request):

    activity = []
    leaderboard = None

    if request.user.is_authenticated:
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user = request.user
            up.save()

        dashboard_accessed.send(sender=None, request=request, data=None)

        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))

        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))

        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")
                start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
                interval = form.cleaned_data.get("interval")
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)

        if interval == 'days':
            no_days = (end_date - start_date).days + 1
            tracker_stats = CourseDailyStats.objects.filter(day__gte=start_date, day__lte=end_date).values('day').annotate(count=Sum('total'))

            for i in range(0, no_days, +1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in tracker_stats if dct['day'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"), count])
        else:
            delta = relativedelta(months=+1)

            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                tmp_date += delta
                no_months += 1

            for i in range(0, no_months, +1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = CourseDailyStats.objects.filter(day__month=month, day__year=year).aggregate(total=Sum('total')).get('total', 0)
                activity.append([temp.strftime("%b %Y"), 0 if count is None else count])

        leaderboard = Points.get_leaderboard(10)

    else:
        form = None

    return render(request, 'oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity,
                               'leaderboard': leaderboard})
Exemple #32
0
def home_view(request):
    activity = []
    if request.user.is_authenticated():
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user= request.user
            up.save()
        
        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))
        
        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))
        
        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")  
                start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d")   
                interval =  form.cleaned_data.get("interval")          
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)
        
        if interval == 'days':
            no_days = (end_date-start_date).days + 1
            trackers = Tracker.objects.filter(course__isnull=False, 
                                              course__is_draft=False, 
                                              user__is_staff=False, 
                                              course__is_archived=False,
                                              tracker_date__gte=start_date,
                                              tracker_date__lte=end_date).extra({'activity_date':"date(tracker_date)"}).values('activity_date').annotate(count=Count('id'))
            for i in range(0,no_days,+1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"),count])
        else:
            delta = relativedelta(months=+1)
            
            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                print tmp_date
                tmp_date += delta
                no_months += 1
                
            for i in range(0,no_months,+1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = Tracker.objects.filter(course__isnull=False,
                                               course__is_draft=False,
                                               user__is_staff=False,
                                               course__is_archived=False,
                                               tracker_date__month=month,
                                               tracker_date__year=year).count()
                activity.append([temp.strftime("%b %Y"),count])
    else:
        form = None
    leaderboard = Points.get_leaderboard(10)
    return render_to_response('oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity, 
                               'leaderboard': leaderboard}, 
                              context_instance=RequestContext(request))
Exemple #33
0
 def dehydrate_quiz_points(self, bundle):
     start_date = datetime.datetime.now() - datetime.timedelta(days=14)
     end_date = datetime.datetime.now()
     return Points.quiz_points(user=bundle.obj,
                               start_date=start_date,
                               end_date=end_date)
Exemple #34
0
 def dehydrate_points(self, bundle):
     points = Points.get_userscore(bundle.request.user)
     return points
Exemple #35
0
 def dehydrate_points(self, bundle):
     points = Points.get_userscore(
         User.objects.get(username__exact=bundle.data['username']))
     return points
Exemple #36
0
def quizattempt_callback(sender, **kwargs):
    quiz_attempt = kwargs.get('instance')

    quiz = quiz_attempt.quiz

    # find out if this quiz is part of a course
    course = None
    digest = quiz_attempt.get_quiz_digest()
    if digest is not None:
        # TODO - what are chances of 2 courses having the exact same activity? and what to do if they do?
        acts = Activity.objects.filter(digest=digest)
        for a in acts:
            course = a.section.course

    if quiz_attempt.points is not None:
        p = Points()
        p.points = quiz_attempt.points
        p.type = 'quiz_attempt'
        p.user = quiz_attempt.user
        p.description = quiz_attempt.event
        p.course = course
        # Points are sent in the quiz attempt tracker, so don't save them twice
        # p.save()
        return

    # Check user doesn't own the quiz
    if quiz.owner == quiz_attempt.user:
        return

    if not apply_points(quiz_attempt.user):
        return

    # find out is user is part of the cohort for this course
    if course is not None and course.user == quiz_attempt.user and settings.OPPIA_COURSE_OWNERS_EARN_POINTS is False:
        return
     
    if quiz_attempt.is_first_attempt():
        # If it's the first time they've attempted this quiz award points
        p = Points()
        p.points = OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT']
        p.type = 'firstattempt'
        p.user = quiz_attempt.user
        p.description = "Bonus points for your first attempt at: " + quiz.title
        p.course = course
        p.save()

        # add percentage points for their first attempt
        if quiz_attempt.get_score_percent() > 0:
            p = Points()
            p.points = quiz_attempt.get_score_percent()
            p.type = 'firstattemptscore'
            p.description = "Score for first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.save()

        # if you get 100% on first attempt get bonus of 50 points
        if quiz_attempt.get_score_percent() >= OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT_THRESHOLD']:
            p = Points()
            p.points = OPPIA_DEFAULT_POINTS['QUIZ_FIRST_ATTEMPT_BONUS']
            p.type = 'firstattemptbonus'
            p.description = "Bonus points for getting 100% in first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.save()

    elif quiz_attempt.is_first_attempt_today():
        # If it's the first time today they've attempted this quiz award 10 points
        p = Points()
        p.points = OPPIA_DEFAULT_POINTS['QUIZ_ATTEMPT']
        p.type = 'quizattempt'
        p.user = quiz_attempt.user
        p.description = "Quiz attempt at: " + quiz.title
        p.course = course
        p.save()

    return
def scorecard_view(request):
    auth = ApiKeyAuthentication()
    if auth.is_authenticated(request) is not True:
        return HttpResponse('Unauthorized', status=401)

    record_mobile_tracker(request, None, 'scorecard', '{"en":"homepage"}')

    start_date = datetime.datetime.now() - datetime.timedelta(days=14)
    end_date = datetime.datetime.now()
    media = {
        'views':
        Tracker.activity_views(user=request.user,
                               type='media',
                               start_date=start_date,
                               end_date=end_date),
        'secs':
        Tracker.activity_secs(user=request.user,
                              type='media',
                              start_date=start_date,
                              end_date=end_date),
        'points':
        Points.media_points(user=request.user,
                            start_date=start_date,
                            end_date=end_date)
    }
    quiz = {
        'views':
        Tracker.activity_views(user=request.user,
                               type='quiz',
                               start_date=start_date,
                               end_date=end_date),
        'secs':
        Tracker.activity_secs(user=request.user,
                              type='quiz',
                              start_date=start_date,
                              end_date=end_date),
        'points':
        Points.quiz_points(user=request.user,
                           start_date=start_date,
                           end_date=end_date)
    }
    acts = {
        'views':
        Tracker.activity_views(user=request.user,
                               type='page',
                               start_date=start_date,
                               end_date=end_date),
        'secs':
        Tracker.activity_secs(user=request.user,
                              type='page',
                              start_date=start_date,
                              end_date=end_date),
        'points':
        Points.page_points(user=request.user,
                           start_date=start_date,
                           end_date=end_date)
    }
    total = {
        'views': acts['views'] + quiz['views'] + media['views'],
        'secs': acts['secs'] + quiz['secs'] + media['secs'],
        'points': acts['points'] + quiz['points'] + media['points'],
    }
    scorecard = {'media': media, 'quiz': quiz, 'acts': acts, 'total': total}
    return render(request, 'oppia/mobile/scorecard.html',
                  {'scorecard': scorecard})
Exemple #38
0
 def dehydrate_points(self, bundle):
     points = Points.get_userscore(
         User.objects.get(username=bundle.request.user.username))
     return points
 def dehydrate_points(self,bundle):
     points = Points.get_userscore(bundle.request.user)
     return points
 def dehydrate_points(self,bundle):
     points = Points.get_userscore(User.objects.get(username__exact=bundle.data['username']))
     return points
Exemple #41
0
def quizattempt_callback(sender, **kwargs):
    quiz_attempt = kwargs.get('instance')
    
    # Check user doesn't own the quiz
    quiz = quiz_attempt.quiz
    if quiz.owner == quiz_attempt.user:
        return
    
    # give points to quiz owner
    if quiz_attempt.is_first_attempt_today() and not quiz.owner.is_superuser:
        p = Points()
        p.points = settings.OPPIA_POINTS['QUIZ_ATTEMPT_OWNER']
        p.user = quiz.owner
        p.type = 'userquizattempt'
        p.description = quiz_attempt.user.username + " attempted your quiz: " + quiz.title
        p.save() 
     
    # check not superuser
    if quiz_attempt.user.is_superuser:
        return 
    
    # find out if this quiz is part of a course
    course = None
    digest = quiz_attempt.get_quiz_digest()
    if digest is not None:
        # TODO - what are chances of 2 courses having the exact same activity? and what to do if they do?
        acts = Activity.objects.filter(digest=digest)
        for a in acts:
            course = a.section.course
        
    # find out is user is part of the cohort for this course
    cohort = None
    if course is not None:
        cohort = Cohort.student_member_now(course,quiz_attempt.user)
              
    if quiz_attempt.is_first_attempt():
        # If it's the first time they've attempted this quiz award points
        p = Points()
        p.points = settings.OPPIA_POINTS['QUIZ_FIRST_ATTEMPT']
        p.type = 'firstattempt'
        p.user = quiz_attempt.user
        p.description = "Bonus points for your first attempt at: " + quiz.title
        p.course = course
        p.cohort = cohort
        p.save()
    
        # add percentage points for their first attempt
        if quiz_attempt.get_score_percent() > 0:
            p = Points()
            p.points = quiz_attempt.get_score_percent()
            p.type = 'firstattemptscore'
            p.description = "Score for first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.cohort = cohort
            p.save()
        
        # if you get 100% on first attempt get bonus of 50 points
        if quiz_attempt.get_score_percent() >= settings.OPPIA_POINTS['QUIZ_FIRST_ATTEMPT_THRESHOLD']:
            p = Points()
            p.points = settings.OPPIA_POINTS['QUIZ_FIRST_ATTEMPT_BONUS']
            p.type = 'firstattemptbonus'
            p.description = "Bonus points for getting 100% in first attempt at quiz: " + quiz.title
            p.user = quiz_attempt.user
            p.course = course
            p.cohort = cohort
            p.save()
            
    elif quiz_attempt.is_first_attempt_today():
        # If it's the first time today they've attempted this quiz award 10 points
        p = Points()
        p.points = settings.OPPIA_POINTS['QUIZ_ATTEMPT']
        p.type = 'quizattempt'
        p.user = quiz_attempt.user
        p.description = "Quiz attempt at: " + quiz.title
        p.course = course
        p.cohort = cohort
        p.save()
    
    return