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
예제 #2
0
 def dehydrate(self, bundle):
     # Include full download url
     if bundle.request.is_secure():
         prefix = 'https://'
     else:
         prefix = 'http://'
     bundle.data['url'] = prefix + bundle.request.META['SERVER_NAME'] + bundle.data['resource_uri'] + 'download/'
     # make sure title is shown as json object (not string representation of one)
     bundle.data['title'] = json.loads(bundle.data['title'])
     
     try:
         bundle.data['description'] = json.loads(bundle.data['description'])
     except: 
         pass
     
     course = Course.objects.get(pk=bundle.obj.pk)
     schedule = course.get_default_schedule()
     cohort = Cohort.member_now(course,bundle.request.user)
     if cohort:
         if cohort.schedule:
             schedule = cohort.schedule
     if schedule:
         bundle.data['schedule'] = schedule.lastupdated_date.strftime("%Y%m%d%H%M%S")
         sr = ScheduleResource()
         bundle.data['schedule_uri'] = sr.get_resource_uri(schedule)
     
     return bundle
예제 #3
0
    def dehydrate(self, bundle):        
        bundle.data['url'] = bundle.request.build_absolute_uri(bundle.data['resource_uri'] + 'download/')
        
        # make sure title is shown as json object (not string representation of one)
        bundle.data['title'] = json.loads(bundle.data['title'])
        
        try:
            bundle.data['description'] = json.loads(bundle.data['description'])
        except: 
            pass
        
        course = Course.objects.get(pk=bundle.obj.pk)
        schedule = course.get_default_schedule()
        cohort = Cohort.member_now(course,bundle.request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        if schedule:
            bundle.data['schedule'] = schedule.lastupdated_date.strftime("%Y%m%d%H%M%S")
            sr = ScheduleResource()
            bundle.data['schedule_uri'] = sr.get_resource_uri(schedule)

        if course and course.user:
            bundle.data['author'] = course.user.first_name + " " + course.user.last_name
            bundle.data['username'] = course.user.username

        return bundle
예제 #4
0
    def dehydrate(self, bundle):
        # Include full download url
        if bundle.request.is_secure():
            prefix = 'https://'
        else:
            prefix = 'http://'
        bundle.data['url'] = prefix + bundle.request.META[
            'SERVER_NAME'] + bundle.data['resource_uri'] + 'download/'
        # make sure title is shown as json object (not string representation of one)
        bundle.data['title'] = json.loads(bundle.data['title'])

        try:
            bundle.data['description'] = json.loads(bundle.data['description'])
        except:
            pass

        course = Course.objects.get(pk=bundle.obj.pk)
        schedule = course.get_default_schedule()
        cohort = Cohort.member_now(course, bundle.request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        if schedule:
            bundle.data['schedule'] = schedule.lastupdated_date.strftime(
                "%Y%m%d%H%M%S")
            sr = ScheduleResource()
            bundle.data['schedule_uri'] = sr.get_resource_uri(schedule)

        return bundle
    def dehydrate(self, bundle):
        bundle.data['url'] = bundle.request.build_absolute_uri(
            bundle.data['resource_uri'] + 'download/')

        # make sure title is shown as json object (not string representation of one)
        bundle.data['title'] = json.loads(bundle.data['title'])

        try:
            bundle.data['description'] = json.loads(bundle.data['description'])
        except:
            pass

        course = Course.objects.get(pk=bundle.obj.pk)
        schedule = course.get_default_schedule()
        cohort = Cohort.member_now(course, bundle.request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        if schedule:
            bundle.data['schedule'] = schedule.lastupdated_date.strftime(
                "%Y%m%d%H%M%S")
            sr = ScheduleResource()
            bundle.data['schedule_uri'] = sr.get_resource_uri(schedule)

        return bundle
예제 #6
0
    def download_course(self, request, **kwargs):
        self.is_authenticated(request)
        self.throttle_check(request)
        
        pk = kwargs.pop('pk', None)
        try:
            if request.user.is_staff:
                course = self._meta.queryset.get(pk = pk,is_archived=False)
            else:
                course = self._meta.queryset.get(pk = pk, is_archived=False,is_draft=False)
        except Course.DoesNotExist:
            raise Http404(_(u"Course not found"))
        except ValueError:
            try:
                if request.user.is_staff:
                    course = self._meta.queryset.get(shortname = pk,is_archived=False)
                else:
                    course = self._meta.queryset.get(shortname = pk, is_archived=False,is_draft=False)
            except Course.DoesNotExist:
                raise Http404(_(u"Course not found"))
         
        file_to_download = course.getAbsPath();
        schedule = course.get_default_schedule()
        has_completed_trackers = Tracker.has_completed_trackers(course,request.user)
        cohort = Cohort.member_now(course,request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        
        # add scheduling XML file     
        if schedule or has_completed_trackers:
            file_to_download = settings.COURSE_UPLOAD_DIR +"temp/"+ str(request.user.id) + "-" + course.filename
            shutil.copy2(course.getAbsPath(), file_to_download)
            zip = zipfile.ZipFile(file_to_download,'a')
            if schedule:
                zip.writestr(course.shortname +"/schedule.xml",schedule.to_xml_string())
            if has_completed_trackers:
                zip.writestr(course.shortname +"/tracker.xml",Tracker.to_xml_string(course,request.user))
            zip.close()

        wrapper = FileWrapper(file(file_to_download))
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Length'] = os.path.getsize(file_to_download)
        response['Content-Disposition'] = 'attachment; filename="%s"' %(course.filename)
        
        # Add to tracker
        tracker = Tracker()
        tracker.user = request.user
        tracker.course = course
        tracker.type = 'download'
        tracker.data = json.dumps({'version':course.version })
        tracker.ip = request.META.get('REMOTE_ADDR','0.0.0.0')
        tracker.agent = request.META.get('HTTP_USER_AGENT','unknown')
        tracker.save()
                
        course_downloaded.send(sender=self, course=course, user=request.user)
        
        return response
예제 #7
0
def cohort_add(request):
    if not can_add_cohort(request):
        return HttpResponse('Unauthorized', status=401)

    if request.method == 'POST':
        form = CohortForm(request.POST)
        if form.is_valid():  # All validation rules pass
            cohort = Cohort()
            cohort.start_date = form.cleaned_data.get("start_date")
            cohort.end_date = form.cleaned_data.get("end_date")
            cohort.description = form.cleaned_data.get("description").strip()
            cohort.save()

            students = form.cleaned_data.get("students").strip().split(",")
            if len(students) > 0:
                for s in students:
                    try:
                        student = User.objects.get(username=s.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = student
                        participant.role = Participant.STUDENT
                        participant.save()
                    except User.DoesNotExist:
                        pass

            teachers = form.cleaned_data.get("teachers").strip().split(",")
            if len(teachers) > 0:
                for t in teachers:
                    try:
                        teacher = User.objects.get(username=t.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = teacher
                        participant.role = Participant.TEACHER
                        participant.save()
                    except User.DoesNotExist:
                        pass

            courses = form.cleaned_data.get("courses").strip().split(",")
            if len(courses) > 0:
                for c in courses:
                    try:
                        course = Course.objects.get(shortname=c.strip())
                        CourseCohort(cohort=cohort, course=course).save()
                    except Course.DoesNotExist:
                        pass

            return HttpResponseRedirect('../')  # Redirect after POST

    else:
        form = CohortForm()  # An unbound form

    return render(request, 'oppia/cohort-form.html', {
        'form': form,
    })
예제 #8
0
    def download_detail(self, request, **kwargs):
        self.is_authenticated(request)
        self.throttle_check(request)

        pk = kwargs.pop('pk', None)
        try:
            course = self._meta.queryset.get(pk=pk)
        except Course.DoesNotExist:
            raise NotFound(_(u'Course download not found'))

        file_to_download = course.getAbsPath()
        schedule = course.get_default_schedule()
        has_completed_trackers = Tracker.has_completed_trackers(
            course, request.user)
        cohort = Cohort.member_now(course, request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule

        # add scheduling XML file
        if schedule or has_completed_trackers:
            file_to_download = settings.COURSE_UPLOAD_DIR + "temp/" + str(
                request.user.id) + "-" + course.filename
            shutil.copy2(course.getAbsPath(), file_to_download)
            zip = zipfile.ZipFile(file_to_download, 'a')
            if schedule:
                zip.writestr(course.shortname + "/schedule.xml",
                             schedule.to_xml_string())
            if has_completed_trackers:
                zip.writestr(course.shortname + "/tracker.xml",
                             Tracker.to_xml_string(course, request.user))
            zip.close()

        wrapper = FileWrapper(file(file_to_download))
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Length'] = os.path.getsize(file_to_download)
        response['Content-Disposition'] = 'attachment; filename="%s"' % (
            course.filename)

        md = CourseDownload()
        md.user = request.user
        md.course = course
        md.course_version = course.version
        md.ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
        md.agent = request.META.get('HTTP_USER_AGENT', 'unknown')
        md.save()

        course_downloaded.send(sender=self, course=course, user=request.user)

        return response
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
    cohort_teacher = Cohort.teacher_member_now(course, user)
    if cohort_teacher is not None and settings.OPPIA_TEACHERS_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.cohort = Cohort.student_member_now(course,user)
    p.save()
    return
예제 #10
0
def cohort_add(request):
    if not can_add_cohort(request):
        raise PermissionDenied

    if request.method == 'POST':
        form = CohortForm(request.POST.copy())
        if form.is_valid():  # All validation rules pass
            cohort = Cohort()
            cohort.start_date = timezone.make_aware(
                datetime.datetime.strptime(form.cleaned_data.get("start_date"),
                                           constants.STR_DATE_FORMAT),
                timezone.get_current_timezone())
            cohort.end_date = timezone.make_aware(
                datetime.datetime.strptime(form.cleaned_data.get("end_date"),
                                           constants.STR_DATE_FORMAT),
                timezone.get_current_timezone())
            cohort.description = form.cleaned_data.get("description").strip()
            cohort.save()

            students = form.cleaned_data.get("students")
            cohort_add_roles(cohort, Participant.STUDENT, students)

            teachers = form.cleaned_data.get("teachers")
            cohort_add_roles(cohort, Participant.TEACHER, teachers)

            courses = form.cleaned_data.get("courses")
            cohort_add_courses(cohort, courses)

            return HttpResponseRedirect('../')  # Redirect after POST
        else:
            # If form is not valid, clean the groups data
            form.data['teachers'] = None
            form.data['courses'] = None
            form.data['students'] = None

    else:
        form = CohortForm()

    ordering, users = get_paginated_users(request)
    c_ordering, courses = get_paginated_courses(request)

    return render(
        request, 'cohort/form.html', {
            'form': form,
            'page': users,
            'courses_page': courses,
            'courses_ordering': c_ordering,
            'page_ordering': ordering,
            'users_list_template': 'select'
        })
예제 #11
0
def cohort_add(request):
    if not can_add_cohort(request):
        return HttpResponse('Unauthorized', status=401)   
    
    if request.method == 'POST':
        form = CohortForm(request.POST)
        if form.is_valid(): # All validation rules pass
            cohort = Cohort()
            cohort.start_date = form.cleaned_data.get("start_date")
            cohort.end_date = form.cleaned_data.get("end_date")
            cohort.description = form.cleaned_data.get("description").strip()
            cohort.save()
            
            students = form.cleaned_data.get("students").strip().split(",")
            if len(students) > 0:
                for s in students:
                    try:
                        student = User.objects.get(username=s.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = student
                        participant.role = Participant.STUDENT
                        participant.save()
                    except User.DoesNotExist:
                        pass
                    
            teachers = form.cleaned_data.get("teachers").strip().split(",")
            if len(teachers) > 0:
                for t in teachers:
                    try:
                        teacher = User.objects.get(username=t.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = teacher
                        participant.role = Participant.TEACHER
                        participant.save()
                    except User.DoesNotExist:
                        pass
             
            courses = form.cleaned_data.get("courses").strip().split(",")
            if len(courses) > 0:
                for c in courses:
                    try:
                        course = Course.objects.get(shortname=c.strip())
                        CourseCohort(cohort=cohort, course=course).save()
                    except Course.DoesNotExist:
                        pass
                           
            return HttpResponseRedirect('../') # Redirect after POST
           
    else:
        form = CohortForm() # An unbound form

    return render(request, 'oppia/cohort-form.html',{'form': form,})  
예제 #12
0
    def download_detail(self, request, **kwargs):
        self.is_authenticated(request)
        self.throttle_check(request)

        pk = kwargs.pop("pk", None)
        try:
            course = self._meta.queryset.get(pk=pk)
        except Course.DoesNotExist:
            raise NotFound(_(u"Course download not found"))

        file_to_download = course.getAbsPath()
        schedule = course.get_default_schedule()
        has_completed_trackers = Tracker.has_completed_trackers(course, request.user)
        cohort = Cohort.member_now(course, request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule

        # add scheduling XML file
        if schedule or has_completed_trackers:
            file_to_download = settings.COURSE_UPLOAD_DIR + "temp/" + str(request.user.id) + "-" + course.filename
            shutil.copy2(course.getAbsPath(), file_to_download)
            zip = zipfile.ZipFile(file_to_download, "a")
            if schedule:
                zip.writestr(course.shortname + "/schedule.xml", schedule.to_xml_string())
            if has_completed_trackers:
                zip.writestr(course.shortname + "/tracker.xml", Tracker.to_xml_string(course, request.user))
            zip.close()

        wrapper = FileWrapper(file(file_to_download))
        response = HttpResponse(wrapper, content_type="application/zip")
        response["Content-Length"] = os.path.getsize(file_to_download)
        response["Content-Disposition"] = 'attachment; filename="%s"' % (course.filename)

        md = CourseDownload()
        md.user = request.user
        md.course = course
        md.course_version = course.version
        md.ip = request.META.get("REMOTE_ADDR", "0.0.0.0")
        md.agent = request.META.get("HTTP_USER_AGENT", "unknown")
        md.save()

        course_downloaded.send(sender=self, course=course, user=request.user)

        return response
예제 #13
0
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
예제 #14
0
def cohort_add(request, course_id):
    course = check_owner(request, course_id)
    if request.method == "POST":
        form = CohortForm(request.POST)
        if form.is_valid():  # All validation rules pass
            cohort = Cohort()
            cohort.course = course
            cohort.start_date = form.cleaned_data.get("start_date")
            cohort.end_date = form.cleaned_data.get("end_date")
            cohort.description = form.cleaned_data.get("description").strip()
            cohort.save()

            students = form.cleaned_data.get("students").strip().split(",")
            if len(students) > 0:
                for s in students:
                    try:
                        student = User.objects.get(username=s.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = student
                        participant.role = Participant.STUDENT
                        participant.save()
                    except User.DoesNotExist:
                        pass
            teachers = form.cleaned_data.get("teachers").strip().split(",")
            if len(teachers) > 0:
                for t in teachers:
                    try:
                        teacher = User.objects.get(username=t.strip())
                        participant = Participant()
                        participant.cohort = cohort
                        participant.user = teacher
                        participant.role = Participant.TEACHER
                        participant.save()
                    except User.DoesNotExist:
                        pass
            return HttpResponseRedirect("../")  # Redirect after POST

    else:
        form = CohortForm()  # An unbound form

    return render(request, "oppia/cohort-form.html", {"course": course, "form": form})
예제 #15
0
    def dehydrate(self, bundle):
        # Include full download url
        if bundle.request.is_secure():
            prefix = "https://"
        else:
            prefix = "http://"
        bundle.data["url"] = prefix + bundle.request.META["SERVER_NAME"] + bundle.data["resource_uri"] + "download/"
        # make sure title is shown as json object (not string representation of one)
        bundle.data["title"] = json.loads(bundle.data["title"])

        course = Course.objects.get(pk=bundle.obj.pk)
        schedule = course.get_default_schedule()
        cohort = Cohort.member_now(course, bundle.request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        if schedule:
            bundle.data["schedule"] = schedule.lastupdated_date.strftime("%Y%m%d%H%M%S")
            sr = ScheduleResource()
            bundle.data["schedule_uri"] = sr.get_resource_uri(schedule)

        return bundle
예제 #16
0
    def dehydrate(self, bundle):
        bundle.data["url"] = bundle.request.build_absolute_uri(bundle.data["resource_uri"] + "download/")

        # make sure title is shown as json object (not string representation of one)
        bundle.data["title"] = json.loads(bundle.data["title"])

        try:
            bundle.data["description"] = json.loads(bundle.data["description"])
        except:
            pass

        course = Course.objects.get(pk=bundle.obj.pk)
        schedule = course.get_default_schedule()
        cohort = Cohort.member_now(course, bundle.request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule
        if schedule:
            bundle.data["schedule"] = schedule.lastupdated_date.strftime("%Y%m%d%H%M%S")
            sr = ScheduleResource()
            bundle.data["schedule_uri"] = sr.get_resource_uri(schedule)

        return bundle
예제 #17
0
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
예제 #18
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