Example #1
0
def rerun_course(source_course_key_string,
                 destination_course_key_string,
                 user_id,
                 fields=None):
    """
    Reruns a course in a new celery task.
    """
    # import here, at top level this import prevents the celery workers from starting up correctly
    from edxval.api import copy_course_videos

    source_course_key = CourseKey.from_string(source_course_key_string)
    destination_course_key = CourseKey.from_string(
        destination_course_key_string)
    try:
        # deserialize the payload
        fields = deserialize_fields(fields) if fields else None

        # use the split modulestore as the store for the rerun course,
        # as the Mongo modulestore doesn't support multiple runs of the same course.
        store = modulestore()
        with store.default_store('split'):
            store.clone_course(source_course_key,
                               destination_course_key,
                               user_id,
                               fields=fields)

        # set initial permissions for the user to access the course.
        initialize_permissions(destination_course_key,
                               User.objects.get(id=user_id))

        # update state: Succeeded
        CourseRerunState.objects.succeeded(course_key=destination_course_key)

        # call edxval to attach videos to the rerun
        copy_course_videos(source_course_key, destination_course_key)

        # Copy OrganizationCourse
        organization_course = OrganizationCourse.objects.filter(
            course_id=source_course_key_string).first()

        if organization_course:
            clone_instance(organization_course,
                           {'course_id': destination_course_key_string})

        # Copy RestrictedCourse
        restricted_course = RestrictedCourse.objects.filter(
            course_key=source_course_key).first()

        if restricted_course:
            country_access_rules = CountryAccessRule.objects.filter(
                restricted_course=restricted_course)
            new_restricted_course = clone_instance(
                restricted_course, {'course_key': destination_course_key})
            for country_access_rule in country_access_rules:
                clone_instance(country_access_rule,
                               {'restricted_course': new_restricted_course})

        org_data = ensure_organization(source_course_key.org)
        add_organization_course(org_data, destination_course_key)
        return "succeeded"

    except DuplicateCourseError:
        # do NOT delete the original course, only update the status
        CourseRerunState.objects.failed(course_key=destination_course_key)
        LOGGER.exception('Course Rerun Error')
        return "duplicate course"

    # catch all exceptions so we can update the state and properly cleanup the course.
    except Exception as exc:  # pylint: disable=broad-except
        # update state: Failed
        CourseRerunState.objects.failed(course_key=destination_course_key)
        LOGGER.exception('Course Rerun Error')

        try:
            # cleanup any remnants of the course
            modulestore().delete_course(destination_course_key, user_id)
        except ItemNotFoundError:
            # it's possible there was an error even before the course module was created
            pass

        return "exception: " + str(exc)
Example #2
0
def _create_library(request):
    """
    Helper method for creating a new library.
    """
    display_name = None
    try:
        display_name = request.json['display_name']
        org = request.json['org']
        ensure_organization(org)
        library = request.json.get('number', None)
        if library is None:
            library = request.json['library']
        if not user_can_create_library(request.user, org):
            raise PermissionDenied()
        store = modulestore()
        with store.default_store(ModuleStoreEnum.Type.split):
            new_lib = store.create_library(
                org=org,
                library=library,
                user_id=request.user.id,
                fields={"display_name": display_name},
            )
        # Give the user admin ("Instructor") role for this library:
        add_instructor(new_lib.location.library_key, request.user,
                       request.user)
    except PermissionDenied as error:  # pylint: disable=unused-variable
        log.info(
            "User does not have the permission to create LIBRARY in this organization."
            "User: '******' Org: '%s' LIBRARY #: '%s'.",
            request.user.id,
            org,
            library,
        )
        return JsonResponse(
            {
                'error':
                _('User does not have the permission to create library in this organization '
                  'or course creation is disabled')
            },
            status=403)
    except KeyError as error:
        log.exception("Unable to create library - missing required JSON key.")
        return JsonResponseBadRequest({
            "ErrMsg":
            _("Unable to create library - missing required field '{field}'").
            format(field=str(error))
        })
    except InvalidKeyError as error:
        log.exception("Unable to create library - invalid key.")
        return JsonResponseBadRequest({
            "ErrMsg":
            _("Unable to create library '{name}'.\n\n{err}").format(
                name=display_name, err=str(error))
        })
    except DuplicateCourseError:
        log.exception(
            "Unable to create library - one already exists with the same key.")
        return JsonResponseBadRequest({
            'ErrMsg':
            _('There is already a library defined with the same '
              'organization and library code. Please '
              'change your library code so that it is unique within your organization.'
              )
        })
    except InvalidOrganizationException:
        log.exception(
            "Unable to create library - %s is not a valid org short_name.",
            org)
        return JsonResponseBadRequest({
            'ErrMsg':
            _("'{organization_key}' is not a valid organization identifier.").
            format(organization_key=org)
        })

    lib_key_str = str(new_lib.location.library_key)
    return JsonResponse({
        'url':
        reverse_library_url('library_handler', lib_key_str),
        'library_key':
        lib_key_str,
    })