Exemple #1
0
def calendar_settings_handler(request, package_id=None, branch=None, version_guid=None, block=None, tag=None):
    locator, course_module = _get_locator_and_course(
        package_id, branch, version_guid, block, request.user
    )
    if 'text/html' in request.META.get('HTTP_ACCEPT', '') and request.method == 'GET':

        return render_to_response('settings_calendar.html', {
            'package_id': package_id,
            'context_course': course_module,
            'advanced_dict': json.dumps(CourseMetadata.fetch(course_module)),
            'advanced_settings_url': locator.url_reverse('settings/calendar')
        })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            # Whether or not to filter the tabs key out of the settings metadata
            filter_tabs = _config_course_advanced_components(request, course_module)
            try:
                return JsonResponse(CourseMetadata.update_from_json(
                    course_module,
                    request.json,
                    filter_tabs=filter_tabs,
                    user=request.user,
                ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(
                    "Incorrect setting format. {}".format(err),
                    content_type="text/plain"
                )
Exemple #2
0
def advanced_settings_handler(request, package_id=None, branch=None, version_guid=None, block=None, tag=None):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts. The dict can include a "unsetKeys" entry which is a list
            of keys whose values to unset: i.e., revert to default
    """
    locator, course_module = _get_locator_and_course(package_id, branch, version_guid, block, request.user)
    if "text/html" in request.META.get("HTTP_ACCEPT", "") and request.method == "GET":

        return render_to_response(
            "settings_advanced.html",
            {
                "context_course": course_module,
                "advanced_dict": json.dumps(CourseMetadata.fetch(course_module)),
                "advanced_settings_url": locator.url_reverse("settings/advanced"),
            },
        )
    elif "application/json" in request.META.get("HTTP_ACCEPT", ""):
        if request.method == "GET":
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            # Whether or not to filter the tabs key out of the settings metadata
            filter_tabs = _config_course_advanced_components(request, course_module)
            try:
                return JsonResponse(
                    CourseMetadata.update_from_json(course_module, request.json, filter_tabs=filter_tabs)
                )
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest("Incorrect setting format. {}".format(err), content_type="text/plain")
    def test_fetch_initial_fields(self):
        test_model = CourseMetadata.fetch(self.course.location)
        self.assertIn("display_name", test_model, "Missing editable metadata field")
        self.assertEqual(test_model["display_name"], "Robot Super Course", "not expected value")

        test_model = CourseMetadata.fetch(self.fullcourse_location)
        self.assertNotIn("graceperiod", test_model, "blacklisted field leaked in")
        self.assertIn("display_name", test_model, "full missing editable metadata field")
        self.assertEqual(test_model["display_name"], "Robot Super Course", "not expected value")
        self.assertIn("rerandomize", test_model, "Missing rerandomize metadata field")
        self.assertIn("showanswer", test_model, "showanswer field ")
        self.assertIn("xqa_key", test_model, "xqa_key field ")
    def test_fetch_initial_fields(self):
        test_model = CourseMetadata.fetch(self.course)
        self.assertIn('display_name', test_model, 'Missing editable metadata field')
        self.assertEqual(test_model['display_name']['value'], self.course.display_name)

        test_model = CourseMetadata.fetch(self.fullcourse)
        self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in')
        self.assertIn('display_name', test_model, 'full missing editable metadata field')
        self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name)
        self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field')
        self.assertIn('showanswer', test_model, 'showanswer field ')
        self.assertIn('xqa_key', test_model, 'xqa_key field ')
    def test_fetch_initial_fields(self):
        test_model = CourseMetadata.fetch(self.course.location)
        self.assertIn('display_name', test_model, 'Missing editable metadata field')
        self.assertEqual(test_model['display_name'], 'Robot Super Course', "not expected value")

        test_model = CourseMetadata.fetch(self.fullcourse_location)
        self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in')
        self.assertIn('display_name', test_model, 'full missing editable metadata field')
        self.assertEqual(test_model['display_name'], 'Testing', "not expected value")
        self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field')
        self.assertIn('showanswer', test_model, 'showanswer field ')
        self.assertIn('xqa_key', test_model, 'xqa_key field ')
    def test_fetch_initial_fields(self):
        test_model = CourseMetadata.fetch(self.course)
        self.assertIn('display_name', test_model, 'Missing editable metadata field')
        self.assertEqual(test_model['display_name']['value'], self.course.display_name)

        test_model = CourseMetadata.fetch(self.fullcourse)
        self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in')
        self.assertIn('display_name', test_model, 'full missing editable metadata field')
        self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name)
        self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field')
        self.assertIn('showanswer', test_model, 'showanswer field ')
        self.assertIn('xqa_key', test_model, 'xqa_key field ')
Exemple #7
0
def advanced_settings_handler(request,
                              package_id=None,
                              branch=None,
                              version_guid=None,
                              block=None,
                              tag=None):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts. The dict can include a "unsetKeys" entry which is a list
            of keys whose values to unset: i.e., revert to default
    """
    locator, course_module = _get_locator_and_course(package_id, branch,
                                                     version_guid, block,
                                                     request.user)
    if 'text/html' in request.META.get('HTTP_ACCEPT',
                                       '') and request.method == 'GET':

        return render_to_response(
            'settings_advanced.html', {
                'context_course': course_module,
                'advanced_dict': json.dumps(
                    CourseMetadata.fetch(course_module)),
                'advanced_settings_url':
                locator.url_reverse('settings/advanced')
            })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            # Whether or not to filter the tabs key out of the settings metadata
            filter_tabs = _config_course_advanced_components(
                request, course_module)
            try:
                return JsonResponse(
                    CourseMetadata.update_from_json(
                        course_module,
                        request.json,
                        filter_tabs=filter_tabs,
                        user=request.user,
                    ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(
                    "Incorrect setting format. {}".format(err),
                    content_type="text/plain")
    def test_validate_and_update_from_json_wrong_inputs(self):
        # input incorrectly formatted data
        is_valid, errors, test_model = CourseMetadata.validate_and_update_from_json(
            self.course,
            {
                "advertised_start": {"value": 1, "display_name": "Course Advertised Start Date", },
                "days_early_for_beta": {"value": "supposed to be an integer",
                                        "display_name": "Days Early for Beta Users", },
                "advanced_modules": {"value": 1, "display_name": "Advanced Module List", },
            },
            user=self.user
        )

        # Check valid results from validate_and_update_from_json
        self.assertFalse(is_valid)
        self.assertEqual(len(errors), 3)
        self.assertFalse(test_model)

        error_keys = set([error_obj['model']['display_name'] for error_obj in errors])
        test_keys = set(['Advanced Module List', 'Course Advertised Start Date', 'Days Early for Beta Users'])
        self.assertEqual(error_keys, test_keys)

        # try fresh fetch to ensure no update happened
        fresh = modulestore().get_course(self.course.id)
        test_model = CourseMetadata.fetch(fresh)

        self.assertNotEqual(test_model['advertised_start']['value'], 1, 'advertised_start should not be updated to a wrong value')
        self.assertNotEqual(test_model['days_early_for_beta']['value'], "supposed to be an integer",
                            'days_early_for beta should not be updated to a wrong value')
 def test_update_from_json(self):
     test_model = CourseMetadata.update_from_json(
         self.course_location, {
             "advertised_start": "start A",
             "testcenter_info": {
                 "c": "test"
             },
             "days_early_for_beta": 2
         })
     self.update_check(test_model)
     # try fresh fetch to ensure persistence
     test_model = CourseMetadata.fetch(self.course_location)
     self.update_check(test_model)
     # now change some of the existing metadata
     test_model = CourseMetadata.update_from_json(
         self.course_location, {
             "advertised_start": "start B",
             "display_name": "jolly roger"
         })
     self.assertIn('display_name', test_model,
                   'Missing editable metadata field')
     self.assertEqual(test_model['display_name'], 'jolly roger',
                      "not expected value")
     self.assertIn('advertised_start', test_model,
                   'Missing revised advertised_start metadata field')
     self.assertEqual(test_model['advertised_start'], 'start B',
                      "advertised_start not expected value")
Exemple #10
0
    def test_validate_and_update_from_json_correct_inputs(self):
        is_valid, errors, test_model = CourseMetadata.validate_and_update_from_json(
            self.course, {
                "advertised_start": {
                    "value": "start A"
                },
                "days_early_for_beta": {
                    "value": 2
                },
                "advanced_modules": {
                    "value": ['combinedopenended']
                },
            },
            user=self.user)
        self.assertTrue(is_valid)
        self.assertTrue(len(errors) == 0)
        self.update_check(test_model)

        # fresh fetch to ensure persistence
        fresh = modulestore().get_course(self.course.id)
        test_model = CourseMetadata.fetch(fresh)
        self.update_check(test_model)

        # Tab gets tested in test_advanced_settings_munge_tabs
        self.assertIn('advanced_modules', test_model,
                      'Missing advanced_modules')
        self.assertEqual(test_model['advanced_modules']['value'],
                         ['combinedopenended'],
                         'advanced_module is not updated')
Exemple #11
0
 def test_update_from_json(self):
     test_model = CourseMetadata.update_from_json(self.course, {
         "advertised_start": "start A",
         "days_early_for_beta": 2,
     },
                                                  user=self.user)
     self.update_check(test_model)
     # try fresh fetch to ensure persistence
     fresh = modulestore().get_item(self.course_location)
     test_model = CourseMetadata.fetch(fresh)
     self.update_check(test_model)
     # now change some of the existing metadata
     test_model = CourseMetadata.update_from_json(
         fresh, {
             "advertised_start": "start B",
             "display_name": "jolly roger",
         },
         user=self.user)
     self.assertIn('display_name', test_model,
                   'Missing editable metadata field')
     self.assertEqual(test_model['display_name'], 'jolly roger',
                      "not expected value")
     self.assertIn('advertised_start', test_model,
                   'Missing revised advertised_start metadata field')
     self.assertEqual(test_model['advertised_start'], 'start B',
                      "advertised_start not expected value")
    def test_validate_and_update_from_json_wrong_inputs(self):
        # input incorrectly formatted data
        is_valid, errors, test_model = CourseMetadata.validate_and_update_from_json(
            self.course,
            {
                "advertised_start": {"value": 1, "display_name": "Course Advertised Start Date", },
                "days_early_for_beta": {"value": "supposed to be an integer",
                                        "display_name": "Days Early for Beta Users", },
                "advanced_modules": {"value": 1, "display_name": "Advanced Module List", },
            },
            user=self.user
        )

        # Check valid results from validate_and_update_from_json
        self.assertFalse(is_valid)
        self.assertEqual(len(errors), 3)
        self.assertFalse(test_model)

        error_keys = set([error_obj['model']['display_name'] for error_obj in errors])
        test_keys = set(['Advanced Module List', 'Course Advertised Start Date', 'Days Early for Beta Users'])
        self.assertEqual(error_keys, test_keys)

        # try fresh fetch to ensure no update happened
        fresh = modulestore().get_course(self.course.id)
        test_model = CourseMetadata.fetch(fresh)

        self.assertNotEqual(test_model['advertised_start']['value'], 1, 'advertised_start should not be updated to a wrong value')
        self.assertNotEqual(test_model['days_early_for_beta']['value'], "supposed to be an integer",
                            'days_early_for beta should not be updated to a wrong value')
 def test_update_from_json(self):
     test_model = CourseMetadata.update_from_json(
         self.course,
         {
             "advertised_start": {"value": "start A"},
             "days_early_for_beta": {"value": 2},
         },
         user=self.user
     )
     self.update_check(test_model)
     # try fresh fetch to ensure persistence
     fresh = modulestore().get_course(self.course.id)
     test_model = CourseMetadata.fetch(fresh)
     self.update_check(test_model)
     # now change some of the existing metadata
     test_model = CourseMetadata.update_from_json(
         fresh,
         {
             "advertised_start": {"value": "start B"},
             "display_name": {"value": "jolly roger"},
         },
         user=self.user
     )
     self.assertIn('display_name', test_model, 'Missing editable metadata field')
     self.assertEqual(test_model['display_name']['value'], 'jolly roger', "not expected value")
     self.assertIn('advertised_start', test_model, 'Missing revised advertised_start metadata field')
     self.assertEqual(test_model['advertised_start']['value'], 'start B', "advertised_start not expected value")
    def test_fetch_initial_fields(self):
        test_model = CourseMetadata.fetch(self.course_location)
        self.assertIn('display_name', test_model,
                      'Missing editable metadata field')
        self.assertEqual(test_model['display_name'], 'Robot Super Course',
                         "not expected value")

        test_model = CourseMetadata.fetch(self.fullcourse_location)
        self.assertNotIn('graceperiod', test_model,
                         'blacklisted field leaked in')
        self.assertIn('display_name', test_model,
                      'full missing editable metadata field')
        self.assertEqual(test_model['display_name'], 'Testing',
                         "not expected value")
        self.assertIn('rerandomize', test_model,
                      'Missing rerandomize metadata field')
        self.assertIn('showanswer', test_model, 'showanswer field ')
        self.assertIn('xqa_key', test_model, 'xqa_key field ')
Exemple #15
0
def advanced_settings_handler(request, course_key_string):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts.
    """
    course_key = CourseKey.from_string(course_key_string)
    course_module = _get_course_module(course_key, request.user)
    if 'text/html' in request.META.get('HTTP_ACCEPT',
                                       '') and request.method == 'GET':

        return render_to_response(
            'settings_advanced.html', {
                'context_course':
                course_module,
                'advanced_dict':
                json.dumps(CourseMetadata.fetch(course_module)),
                'advanced_settings_url':
                reverse_course_url('advanced_settings_handler', course_key)
            })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            try:
                # Whether or not to filter the tabs key out of the settings metadata
                filter_tabs = _config_course_advanced_components(
                    request, course_module)
                return JsonResponse(
                    CourseMetadata.update_from_json(
                        course_module,
                        request.json,
                        filter_tabs=filter_tabs,
                        user=request.user,
                    ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(django.utils.html.escape(
                    err.message),
                                              content_type="text/plain")
Exemple #16
0
def advanced_settings_handler(request, course_id=None, branch=None, version_guid=None, block=None, tag=None):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts. The dict can include a "unsetKeys" entry which is a list
            of keys whose values to unset: i.e., revert to default
    """
    locator = BlockUsageLocator(course_id=course_id, branch=branch, version_guid=version_guid, usage_id=block)
    if not has_access(request.user, locator):
        raise PermissionDenied()

    course_old_location = loc_mapper().translate_locator_to_location(locator)
    course_module = modulestore().get_item(course_old_location)

    if 'text/html' in request.META.get('HTTP_ACCEPT', '') and request.method == 'GET':

        return render_to_response('settings_advanced.html', {
            'context_course': course_module,
            'advanced_dict': json.dumps(CourseMetadata.fetch(course_module)),
            'advanced_settings_url': locator.url_reverse('settings/advanced')
        })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            # Whether or not to filter the tabs key out of the settings metadata
            filter_tabs = _config_course_advanced_components(request, course_module)
            try:
                return JsonResponse(CourseMetadata.update_from_json(
                    course_module,
                    request.json,
                    filter_tabs=filter_tabs
                ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(
                    "Incorrect setting format. {}".format(err),
                    content_type="text/plain"
                )
Exemple #17
0
def advanced_settings_handler(request, course_key_string):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts. The dict can include a "unsetKeys" entry which is a list
            of keys whose values to unset: i.e., revert to default
    """
    course_key = CourseKey.from_string(course_key_string)
    course_module = _get_course_module(course_key, request.user)
    if 'text/html' in request.META.get('HTTP_ACCEPT', '') and request.method == 'GET':

        return render_to_response('settings_advanced.html', {
            'context_course': course_module,
            'advanced_dict': json.dumps(CourseMetadata.fetch(course_module)),
            'advanced_settings_url': reverse_course_url('advanced_settings_handler', course_key)
        })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            # Whether or not to filter the tabs key out of the settings metadata
            filter_tabs = _config_course_advanced_components(request, course_module)
            try:
                return JsonResponse(CourseMetadata.update_from_json(
                    course_module,
                    request.json,
                    filter_tabs=filter_tabs,
                    user=request.user,
                ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(
                    "Incorrect setting format. {}".format(err),
                    content_type="text/plain"
                )
Exemple #18
0
def advanced_settings_handler(request, course_key_string):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts.
    """
    course_key = CourseKey.from_string(course_key_string)
    course_module = _get_course_module(course_key, request.user)
    if 'text/html' in request.META.get('HTTP_ACCEPT', '') and request.method == 'GET':

        return render_to_response('settings_advanced.html', {
            'context_course': course_module,
            'advanced_dict': json.dumps(CourseMetadata.fetch(course_module)),
            'advanced_settings_url': reverse_course_url('advanced_settings_handler', course_key)
        })
    elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
        if request.method == 'GET':
            return JsonResponse(CourseMetadata.fetch(course_module))
        else:
            try:
                # Whether or not to filter the tabs key out of the settings metadata
                filter_tabs = _config_course_advanced_components(request, course_module)
                return JsonResponse(CourseMetadata.update_from_json(
                    course_module,
                    request.json,
                    filter_tabs=filter_tabs,
                    user=request.user,
                ))
            except (TypeError, ValueError) as err:
                return HttpResponseBadRequest(
                    django.utils.html.escape(err.message),
                    content_type="text/plain"
                )
Exemple #19
0
def course_config_advanced_page(request, org, course, name):
    """
    Send models and views as well as html for editing the advanced course settings to the client.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    course_module = modulestore().get_item(location)

    return render_to_response('settings_advanced.html', {
        'context_course': course_module,
        'course_location': location,
        'advanced_dict': json.dumps(CourseMetadata.fetch(location)),
    })
Exemple #20
0
def course_config_advanced_page(request, org, course, name):
    """
    Send models and views as well as html for editing the advanced course settings to the client.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    course_module = modulestore().get_item(location)

    return render_to_response('settings_advanced.html', {
        'context_course': course_module,
        'course_location': location,
        'advanced_dict': json.dumps(CourseMetadata.fetch(location)),
    })
Exemple #21
0
def mobi_get_topics(request, course_id):
    """
    Return course topics
    """
    course_id = course_id.replace('.', '/')
    nr_transaction = newrelic.agent.current_transaction()
    try:
        course = get_course_with_access(request.user, course_id, "load_forum")
    except:
        return JsonResponse({"success": False, 'errmsg': "can not find a course with " + course_id.replace('/', '.') + " id"})


    return JsonResponse({
        "topic-list": CourseMetadata.fetch(course).pop("discussion_topics"),
        "success": True
    })
 def test_update_from_json(self):
     test_model = CourseMetadata.update_from_json(
         self.course.location,
         {"advertised_start": "start A", "testcenter_info": {"c": "test"}, "days_early_for_beta": 2},
     )
     self.update_check(test_model)
     # try fresh fetch to ensure persistence
     test_model = CourseMetadata.fetch(self.course.location)
     self.update_check(test_model)
     # now change some of the existing metadata
     test_model = CourseMetadata.update_from_json(
         self.course.location, {"advertised_start": "start B", "display_name": "jolly roger"}
     )
     self.assertIn("display_name", test_model, "Missing editable metadata field")
     self.assertEqual(test_model["display_name"], "jolly roger", "not expected value")
     self.assertIn("advertised_start", test_model, "Missing revised advertised_start metadata field")
     self.assertEqual(test_model["advertised_start"], "start B", "advertised_start not expected value")
    def test_validate_and_update_from_json_correct_inputs(self):
        is_valid, errors, test_model = CourseMetadata.validate_and_update_from_json(
            self.course,
            {
                "advertised_start": {"value": "start A"},
                "days_early_for_beta": {"value": 2},
                "advanced_modules": {"value": ['combinedopenended']},
            },
            user=self.user
        )
        self.assertTrue(is_valid)
        self.assertTrue(len(errors) == 0)
        self.update_check(test_model)

        # fresh fetch to ensure persistence
        fresh = modulestore().get_course(self.course.id)
        test_model = CourseMetadata.fetch(fresh)
        self.update_check(test_model)

        # Tab gets tested in test_advanced_settings_munge_tabs
        self.assertIn('advanced_modules', test_model, 'Missing advanced_modules')
        self.assertEqual(test_model['advanced_modules']['value'], ['combinedopenended'], 'advanced_module is not updated')
Exemple #24
0
def mobi_get_topics(request, course_id):
    """
    Return course topics
    """
    course_id = course_id.replace('.', '/')
    nr_transaction = newrelic.agent.current_transaction()
    try:
        course = get_course_with_access(request.user, course_id, "load_forum")
    except:
        return JsonResponse({
            "success":
            False,
            'errmsg':
            "can not find a course with " + course_id.replace('/', '.') + " id"
        })

    return JsonResponse({
        "topic-list":
        CourseMetadata.fetch(course).pop("discussion_topics"),
        "success":
        True
    })
Exemple #25
0
def course_advanced_updates(request, org, course, name):
    """
    restful CRUD operations on metadata. The payload is a json rep of the metadata dicts. For delete, otoh,
    the payload is either a key or a list of keys to delete.

    org, course: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    real_method = get_request_method(request)

    if real_method == 'GET':
        return HttpResponse(json.dumps(CourseMetadata.fetch(location)),
                            mimetype="application/json")
    elif real_method == 'DELETE':
        return HttpResponse(json.dumps(
            CourseMetadata.delete_key(location, json.loads(request.body))),
                            mimetype="application/json")
    elif real_method == 'POST' or real_method == 'PUT':
        # NOTE: request.POST is messed up because expect_json
        # cloned_request.POST.copy() is creating a defective entry w/ the whole payload as the key
        request_body = json.loads(request.body)
        # Whether or not to filter the tabs key out of the settings metadata
        filter_tabs = True

        # Check to see if the user instantiated any advanced components. This is a hack
        # that does the following :
        #   1) adds/removes the open ended panel tab to a course automatically if the user
        #   has indicated that they want to edit the combinedopendended or peergrading module
        #   2) adds/removes the notes panel tab to a course automatically if the user has
        #   indicated that they want the notes module enabled in their course
        # TODO refactor the above into distinct advanced policy settings
        if ADVANCED_COMPONENT_POLICY_KEY in request_body:
            # Get the course so that we can scrape current tabs
            course_module = modulestore().get_item(location)

            # Maps tab types to components
            tab_component_map = {
                'open_ended': OPEN_ENDED_COMPONENT_TYPES,
                'notes': NOTE_COMPONENT_TYPES,
            }

            # Check to see if the user instantiated any notes or open ended components
            for tab_type in tab_component_map.keys():
                component_types = tab_component_map.get(tab_type)
                found_ac_type = False
                for ac_type in component_types:
                    if ac_type in request_body[ADVANCED_COMPONENT_POLICY_KEY]:
                        # Add tab to the course if needed
                        changed, new_tabs = add_extra_panel_tab(
                            tab_type, course_module)
                        # If a tab has been added to the course, then send the metadata along to CourseMetadata.update_from_json
                        if changed:
                            course_module.tabs = new_tabs
                            request_body.update({'tabs': new_tabs})
                            # Indicate that tabs should not be filtered out of the metadata
                            filter_tabs = False
                        # Set this flag to avoid the tab removal code below.
                        found_ac_type = True
                        break
                # If we did not find a module type in the advanced settings,
                # we may need to remove the tab from the course.
                if not found_ac_type:
                    # Remove tab from the course if needed
                    changed, new_tabs = remove_extra_panel_tab(
                        tab_type, course_module)
                    if changed:
                        course_module.tabs = new_tabs
                        request_body.update({'tabs': new_tabs})
                        # Indicate that tabs should *not* be filtered out of the metadata
                        filter_tabs = False
        try:
            response_json = json.dumps(
                CourseMetadata.update_from_json(location,
                                                request_body,
                                                filter_tabs=filter_tabs))
        except (TypeError, ValueError), e:
            return HttpResponseBadRequest("Incorrect setting format. " +
                                          str(e),
                                          content_type="text/plain")

        return HttpResponse(response_json, mimetype="application/json")
 def test_edxnotes_not_present(self):
     """
     If feature flag ENABLE_EDXNOTES is off, don't show the setting at all on the Advanced Settings page.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertNotIn('edxnotes', test_model)
 def test_edxnotes_present(self):
     """
     If feature flag ENABLE_EDXNOTES is on, show the setting as a non-deprecated Advanced Setting.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertIn('edxnotes', test_model)
 def test_fetch_giturl_not_present(self):
     """
     If feature flag ENABLE_EXPORT_GIT is off, don't show the setting at all on the Advanced Settings page.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertNotIn('giturl', test_model)
 def test_fetch_giturl_present(self):
     """
     If feature flag ENABLE_EXPORT_GIT is on, show the setting as a non-deprecated Advanced Setting.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertIn('giturl', test_model)
 def test_edxnotes_not_present(self):
     """
     If feature flag ENABLE_EDXNOTES is off, don't show the setting at all on the Advanced Settings page.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertNotIn('edxnotes', test_model)
Exemple #31
0
def course_advanced_updates(request, org, course, name):
    """
    restful CRUD operations on metadata. The payload is a json rep of the metadata dicts. For delete, otoh,
    the payload is either a key or a list of keys to delete.

    org, course: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    real_method = get_request_method(request)

    if real_method == 'GET':
        return HttpResponse(json.dumps(CourseMetadata.fetch(location)),
                            mimetype="application/json")
    elif real_method == 'DELETE':
        return HttpResponse(json.dumps(CourseMetadata.delete_key(location,
                                                                 json.loads(request.body))),
                            mimetype="application/json")
    elif real_method == 'POST' or real_method == 'PUT':
        # NOTE: request.POST is messed up because expect_json
        # cloned_request.POST.copy() is creating a defective entry w/ the whole payload as the key
        request_body = json.loads(request.body)
        # Whether or not to filter the tabs key out of the settings metadata
        filter_tabs = True

        # Check to see if the user instantiated any advanced components. This is a hack
        # that does the following :
        #   1) adds/removes the open ended panel tab to a course automatically if the user
        #   has indicated that they want to edit the combinedopendended or peergrading module
        #   2) adds/removes the notes panel tab to a course automatically if the user has
        #   indicated that they want the notes module enabled in their course
        # TODO refactor the above into distinct advanced policy settings
        if ADVANCED_COMPONENT_POLICY_KEY in request_body:
            # Get the course so that we can scrape current tabs
            course_module = modulestore().get_item(location)

            # Maps tab types to components
            tab_component_map = {
                'open_ended': OPEN_ENDED_COMPONENT_TYPES,
                'notes': NOTE_COMPONENT_TYPES,
            }

            # Check to see if the user instantiated any notes or open ended components
            for tab_type in tab_component_map.keys():
                component_types = tab_component_map.get(tab_type)
                found_ac_type = False
                for ac_type in component_types:
                    if ac_type in request_body[ADVANCED_COMPONENT_POLICY_KEY]:
                        # Add tab to the course if needed
                        changed, new_tabs = add_extra_panel_tab(tab_type, course_module)
                        # If a tab has been added to the course, then send the metadata along to CourseMetadata.update_from_json
                        if changed:
                            course_module.tabs = new_tabs
                            request_body.update({'tabs': new_tabs})
                            # Indicate that tabs should not be filtered out of the metadata
                            filter_tabs = False
                        # Set this flag to avoid the tab removal code below.
                        found_ac_type = True
                        break
                # If we did not find a module type in the advanced settings,
                # we may need to remove the tab from the course.
                if not found_ac_type:
                    # Remove tab from the course if needed
                    changed, new_tabs = remove_extra_panel_tab(tab_type, course_module)
                    if changed:
                        course_module.tabs = new_tabs
                        request_body.update({'tabs': new_tabs})
                        # Indicate that tabs should *not* be filtered out of the metadata
                        filter_tabs = False
        try:
            response_json = json.dumps(CourseMetadata.update_from_json(location,
                                                                   request_body,
                                                                   filter_tabs=filter_tabs))
        except (TypeError, ValueError), e:
            return HttpResponseBadRequest("Incorrect setting format. " + str(e), content_type="text/plain")

        return HttpResponse(response_json, mimetype="application/json")
 def test_fetch_giturl_not_present(self):
     """
     If feature flag ENABLE_EXPORT_GIT is off, don't show the setting at all on the Advanced Settings page.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertNotIn('giturl', test_model)
Exemple #33
0
def custom_settings_handler(request, course_key_string):
    """
    Course settings configuration
    GET
        html: get the page
        json: get the model
    PUT, POST
        json: update the Course's settings. The payload is a json rep of the
            metadata dicts.
    """
    course_key = CourseKey.from_string(course_key_string)
    with modulestore().bulk_operations(course_key):
        course_module = get_course_and_check_access(course_key, request.user)
        if 'text/html' in request.META.get('HTTP_ACCEPT',
                                           '') and request.method == 'GET':

            return render_to_response(
                'custom_settings.html', {
                    'context_course':
                    course_module,
                    'is_new':
                    course_module.is_new,
                    'invitation_only':
                    course_module.invitation_only,
                    'visible_to_manager_only':
                    course_module.visible_to_manager_only,
                })
        elif 'application/json' in request.META.get('HTTP_ACCEPT', ''):
            if request.method == 'GET':
                return JsonResponse(CourseMetadata.fetch(course_module))
            else:
                try:
                    # validate data formats and update the course module.
                    # Note: don't update mongo yet, but wait until after any tabs are changed
                    is_valid, errors, updated_data = CourseMetadata.validate_and_update_from_json(
                        course_module,
                        request.json,
                        user=request.user,
                    )

                    if is_valid:
                        try:
                            additional_info = {
                                'is_new':
                                request.POST.get('is_new', False),
                                'invitation_only':
                                request.POST.get('invitation_only', False),
                                'visible_to_manager_only':
                                request.POST.get('visible_to_manager_only',
                                                 False)
                            }
                            CourseMetadata.update_from_dict(
                                additional_info, course_module, request.user)
                            course_search_index_handler(
                                request, course_key_string)
                        except InvalidTabsException as err:
                            log.exception(err.message)
                            response_message = [{
                                'message':
                                _('An error occurred while trying to save your tabs'
                                  ),
                                'model': {
                                    'display_name': _('Tabs Exception')
                                }
                            }]
                            return JsonResponseBadRequest(response_message)

                        return JsonResponse(updated_data)
                    else:
                        return JsonResponseBadRequest(errors)

                # Handle all errors that validation doesn't catch
                except (TypeError, ValueError, InvalidTabsException) as err:
                    return HttpResponseBadRequest(django.utils.html.escape(
                        err.message),
                                                  content_type="text/plain")
 def test_edxnotes_present(self):
     """
     If feature flag ENABLE_EDXNOTES is on, show the setting as a non-deprecated Advanced Setting.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertIn('edxnotes', test_model)
 def test_fetch_giturl_present(self):
     """
     If feature flag ENABLE_EXPORT_GIT is on, show the setting as a non-deprecated Advanced Setting.
     """
     test_model = CourseMetadata.fetch(self.fullcourse)
     self.assertIn('giturl', test_model)