Search is not available for this dataset
text
stringlengths 75
104k
|
|---|
def update_throttle_scope(self):
"""
Update throttle scope so that service user throttle rates are applied.
"""
self.scope = SERVICE_USER_SCOPE
self.rate = self.get_rate()
self.num_requests, self.duration = self.parse_rate(self.rate)
|
def get_course_final_price(self, mode, currency='$', enterprise_catalog_uuid=None):
"""
Get course mode's SKU discounted price after applying any entitlement available for this user.
Returns:
str: Discounted price of the course mode.
"""
try:
price_details = self.client.baskets.calculate.get(
sku=[mode['sku']],
username=self.user.username,
catalog=enterprise_catalog_uuid,
)
except (SlumberBaseException, ConnectionError, Timeout) as exc:
LOGGER.exception('Failed to get price details for sku %s due to: %s', mode['sku'], str(exc))
price_details = {}
price = price_details.get('total_incl_tax', mode['min_price'])
if price != mode['min_price']:
return format_price(price, currency)
return mode['original_price']
|
def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs):
"""
This method adds enterprise-specific metadata for each course.
We are adding following field in all the courses.
tpa_hint: a string for identifying Identity Provider.
enterprise_id: the UUID of the enterprise
**kwargs: any additional data one would like to add on a per-use basis.
Arguments:
enterprise_customer: The customer whose data will be used to fill the enterprise context.
course_container_key: The key used to find the container for courses in the serializer's data dictionary.
"""
enterprise_context = {
'tpa_hint': enterprise_customer and enterprise_customer.identity_provider,
'enterprise_id': enterprise_customer and str(enterprise_customer.uuid),
}
enterprise_context.update(**kwargs)
courses = []
for course in self.data[course_container_key]:
courses.append(
self.update_course(course, enterprise_customer, enterprise_context)
)
self.data[course_container_key] = courses
|
def update_course(self, course, enterprise_customer, enterprise_context):
"""
Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): Enterprise context to be added to course runs and URLs..
Returns:
(dict): Updated course metadata
"""
course['course_runs'] = self.update_course_runs(
course_runs=course.get('course_runs') or [],
enterprise_customer=enterprise_customer,
enterprise_context=enterprise_context,
)
# Update marketing urls in course metadata to include enterprise related info (i.e. our global context).
marketing_url = course.get('marketing_url')
if marketing_url:
query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))
course.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})
# Finally, add context to the course as a whole.
course.update(enterprise_context)
return course
|
def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):
"""
Update Marketing urls in course metadata and return updated course.
Arguments:
course_runs (list): List of course runs.
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): The context to inject into URLs.
Returns:
(dict): Dictionary containing updated course metadata.
"""
updated_course_runs = []
for course_run in course_runs:
track_selection_url = utils.get_course_track_selection_url(
course_run=course_run,
query_parameters=dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer)),
)
enrollment_url = enterprise_customer.get_course_run_enrollment_url(course_run.get('key'))
course_run.update({
'enrollment_url': enrollment_url,
'track_selection_url': track_selection_url,
})
# Update marketing urls in course metadata to include enterprise related info.
marketing_url = course_run.get('marketing_url')
if marketing_url:
query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))
course_run.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})
# Add updated course run to the list.
updated_course_runs.append(course_run)
return updated_course_runs
|
def export(self):
"""
Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted.
Yields a learner data object for each enrollment, containing:
* ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object.
* ``completed_date``: datetime instance containing the course/enrollment completion date; None if not complete.
"Course completion" occurs for instructor-paced courses when course certificates are issued, and
for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade.
* ``grade``: string grade recorded for the learner in the course.
"""
# Fetch the consenting enrollment data, including the enterprise_customer_user.
# Order by the course_id, to avoid fetching course API data more than we have to.
enrollment_queryset = EnterpriseCourseEnrollment.objects.select_related(
'enterprise_customer_user'
).filter(
enterprise_customer_user__enterprise_customer=self.enterprise_customer,
enterprise_customer_user__active=True,
).order_by('course_id')
# Fetch course details from the Course API, and cache between calls.
course_details = None
for enterprise_enrollment in enrollment_queryset:
course_id = enterprise_enrollment.course_id
# Fetch course details from Courses API
# pylint: disable=unsubscriptable-object
if course_details is None or course_details['course_id'] != course_id:
if self.course_api is None:
self.course_api = CourseApiClient()
course_details = self.course_api.get_course_details(course_id)
if course_details is None:
# Course not found, so we have nothing to report.
LOGGER.error("No course run details found for enrollment [%d]: [%s]",
enterprise_enrollment.pk, course_id)
continue
consent = DataSharingConsent.objects.proxied_get(
username=enterprise_enrollment.enterprise_customer_user.username,
course_id=enterprise_enrollment.course_id,
enterprise_customer=enterprise_enrollment.enterprise_customer_user.enterprise_customer
)
if not consent.granted or enterprise_enrollment.audit_reporting_disabled:
continue
# For instructor-paced courses, let the certificate determine course completion
if course_details.get('pacing') == 'instructor':
completed_date, grade, is_passing = self._collect_certificate_data(enterprise_enrollment)
# For self-paced courses, check the Grades API
else:
completed_date, grade, is_passing = self._collect_grades_data(enterprise_enrollment, course_details)
records = self.get_learner_data_records(
enterprise_enrollment=enterprise_enrollment,
completed_date=completed_date,
grade=grade,
is_passing=is_passing,
)
if records:
# There are some cases where we won't receive a record from the above
# method; right now, that should only happen if we have an Enterprise-linked
# user for the integrated channel, and transmission of that user's
# data requires an upstream user identifier that we don't have (due to a
# failure of SSO or similar). In such a case, `get_learner_data_record`
# would return None, and we'd simply skip yielding it here.
for record in records:
yield record
|
def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):
"""
Generate a learner data transmission audit with fields properly filled in.
"""
# pylint: disable=invalid-name
LearnerDataTransmissionAudit = apps.get_model('integrated_channel', 'LearnerDataTransmissionAudit')
completed_timestamp = None
course_completed = False
if completed_date is not None:
completed_timestamp = parse_datetime_to_epoch_millis(completed_date)
course_completed = is_passing
return [
LearnerDataTransmissionAudit(
enterprise_course_enrollment_id=enterprise_enrollment.id,
course_id=enterprise_enrollment.course_id,
course_completed=course_completed,
completed_timestamp=completed_timestamp,
grade=grade,
)
]
|
def _collect_certificate_data(self, enterprise_enrollment):
"""
Collect the learner completion data from the course certificate.
Used for Instructor-paced courses.
If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a
certificate will eventually be generated.
Args:
enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to
collect completion/grade data
Returns:
completed_date: Date the course was completed, this is None if course has not been completed.
grade: Current grade in the course.
is_passing: Boolean indicating if the grade is a passing grade or not.
"""
if self.certificates_api is None:
self.certificates_api = CertificatesApiClient(self.user)
course_id = enterprise_enrollment.course_id
username = enterprise_enrollment.enterprise_customer_user.user.username
try:
certificate = self.certificates_api.get_course_certificate(course_id, username)
completed_date = certificate.get('created_date')
if completed_date:
completed_date = parse_datetime(completed_date)
else:
completed_date = timezone.now()
# For consistency with _collect_grades_data, we only care about Pass/Fail grades. This could change.
is_passing = certificate.get('is_passing')
grade = self.grade_passing if is_passing else self.grade_failing
except HttpNotFoundError:
completed_date = None
grade = self.grade_incomplete
is_passing = False
return completed_date, grade, is_passing
|
def _collect_grades_data(self, enterprise_enrollment, course_details):
"""
Collect the learner completion data from the Grades API.
Used for self-paced courses.
Args:
enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to
collect completion/grade data
course_details (dict): the course details for the course in the enterprise enrollment record.
Returns:
completed_date: Date the course was completed, this is None if course has not been completed.
grade: Current grade in the course.
is_passing: Boolean indicating if the grade is a passing grade or not.
"""
if self.grades_api is None:
self.grades_api = GradesApiClient(self.user)
course_id = enterprise_enrollment.course_id
username = enterprise_enrollment.enterprise_customer_user.user.username
try:
grades_data = self.grades_api.get_course_grade(course_id, username)
except HttpNotFoundError as error:
# Grade not found, so we have nothing to report.
if hasattr(error, 'content'):
response_content = json.loads(error.content)
if response_content.get('error_code', '') == 'user_not_enrolled':
# This means the user has an enterprise enrollment record but is not enrolled in the course yet
LOGGER.info(
"User [%s] not enrolled in course [%s], enterprise enrollment [%d]",
username,
course_id,
enterprise_enrollment.pk
)
return None, None, None
LOGGER.error("No grades data found for [%d]: [%s], [%s]", enterprise_enrollment.pk, course_id, username)
return None, None, None
# Prepare to process the course end date and pass/fail grade
course_end_date = course_details.get('end')
if course_end_date is not None:
course_end_date = parse_datetime(course_end_date)
now = timezone.now()
is_passing = grades_data.get('passed')
# We can consider a course complete if:
# * the course's end date has passed
if course_end_date is not None and course_end_date < now:
completed_date = course_end_date
grade = self.grade_passing if is_passing else self.grade_failing
# * Or, the learner has a passing grade (as of now)
elif is_passing:
completed_date = now
grade = self.grade_passing
# Otherwise, the course is still in progress
else:
completed_date = None
grade = self.grade_incomplete
return completed_date, grade, is_passing
|
def get_enterprise_user_id(self, obj):
"""
Get enterprise user id from user object.
Arguments:
obj (User): Django User object
Returns:
(int): Primary Key identifier for enterprise user object.
"""
# An enterprise learner can not belong to multiple enterprise customer at the same time
# but if such scenario occurs we will pick the first.
enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()
return enterprise_learner and enterprise_learner.id
|
def get_enterprise_sso_uid(self, obj):
"""
Get enterprise SSO UID.
Arguments:
obj (User): Django User object
Returns:
(str): string containing UUID for enterprise customer's Identity Provider.
"""
# An enterprise learner can not belong to multiple enterprise customer at the same time
# but if such scenario occurs we will pick the first.
enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()
return enterprise_learner and enterprise_learner.get_remote_id()
|
def get_course_duration(self, obj):
"""
Get course's duration as a timedelta.
Arguments:
obj (CourseOverview): CourseOverview object
Returns:
(timedelta): Duration of a course.
"""
duration = obj.end - obj.start if obj.start and obj.end else None
if duration:
return strfdelta(duration, '{W} weeks {D} days.')
return ''
|
def transmit(self, payload, **kwargs):
"""
Transmit content metadata items to the integrated channel.
"""
items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload)
self._prepare_items_for_delete(items_to_delete)
prepared_items = {}
prepared_items.update(items_to_create)
prepared_items.update(items_to_update)
prepared_items.update(items_to_delete)
skip_metadata_transmission = False
for chunk in chunks(prepared_items, self.enterprise_configuration.transmission_chunk_size):
chunked_items = list(chunk.values())
if skip_metadata_transmission:
# Remove the failed items from the create/update/delete dictionaries,
# so ContentMetadataItemTransmission objects are not synchronized for
# these items below.
self._remove_failed_items(chunked_items, items_to_create, items_to_update, items_to_delete)
else:
try:
self.client.update_content_metadata(self._serialize_items(chunked_items))
except ClientError as exc:
LOGGER.error(
'Failed to update [%s] content metadata items for integrated channel [%s] [%s]',
len(chunked_items),
self.enterprise_configuration.enterprise_customer.name,
self.enterprise_configuration.channel_code,
)
LOGGER.error(exc)
# Remove the failed items from the create/update/delete dictionaries,
# so ContentMetadataItemTransmission objects are not synchronized for
# these items below.
self._remove_failed_items(chunked_items, items_to_create, items_to_update, items_to_delete)
# SAP servers throttle incoming traffic, If a request fails than the subsequent would fail too,
# So, no need to keep trying and failing. We should stop here and retry later.
skip_metadata_transmission = True
self._create_transmissions(items_to_create)
self._update_transmissions(items_to_update, transmission_map)
self._delete_transmissions(items_to_delete.keys())
|
def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete):
"""
Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.
Arguments:
failed_items (list): Failed Items to be removed.
items_to_create (dict): dict containing the items created successfully.
items_to_update (dict): dict containing the items updated successfully.
items_to_delete (dict): dict containing the items deleted successfully.
"""
for item in failed_items:
content_metadata_id = item['courseID']
items_to_create.pop(content_metadata_id, None)
items_to_update.pop(content_metadata_id, None)
items_to_delete.pop(content_metadata_id, None)
|
def parse_arguments(*args, **options): # pylint: disable=unused-argument
"""
Parse and validate arguments for send_course_enrollments command.
Arguments:
*args: Positional arguments passed to the command
**options: optional arguments passed to the command
Returns:
A tuple containing parsed values for
1. days (int): Integer showing number of days to lookup enterprise enrollments,
course completion etc and send to xAPI LRS
2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then
send xAPI statements just for this enterprise.
"""
days = options.get('days', 1)
enterprise_customer_uuid = options.get('enterprise_customer_uuid')
enterprise_customer = None
if enterprise_customer_uuid:
try:
# pylint: disable=no-member
enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid)
except EnterpriseCustomer.DoesNotExist:
raise CommandError('Enterprise customer with uuid "{enterprise_customer_uuid}" does not exist.'.format(
enterprise_customer_uuid=enterprise_customer_uuid
))
return days, enterprise_customer
|
def handle(self, *args, **options):
"""
Send xAPI statements.
"""
if not CourseEnrollment:
raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.")
days, enterprise_customer = self.parse_arguments(*args, **options)
if enterprise_customer:
try:
lrs_configuration = XAPILRSConfiguration.objects.get(
active=True,
enterprise_customer=enterprise_customer
)
except XAPILRSConfiguration.DoesNotExist:
raise CommandError('No xAPI Configuration found for "{enterprise_customer}"'.format(
enterprise_customer=enterprise_customer.name
))
# Send xAPI analytics data to the configured LRS
self.send_xapi_statements(lrs_configuration, days)
else:
for lrs_configuration in XAPILRSConfiguration.objects.filter(active=True):
self.send_xapi_statements(lrs_configuration, days)
|
def send_xapi_statements(self, lrs_configuration, days):
"""
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this number of days.
"""
for course_enrollment in self.get_course_enrollments(lrs_configuration.enterprise_customer, days):
try:
send_course_enrollment_statement(lrs_configuration, course_enrollment)
except ClientError:
LOGGER.exception(
'Client error while sending course enrollment to xAPI for'
' enterprise customer {enterprise_customer}.'.format(
enterprise_customer=lrs_configuration.enterprise_customer.name
)
)
|
def get_course_enrollments(self, enterprise_customer, days):
"""
Get course enrollments for all the learners of given enterprise customer.
Arguments:
enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners
of this enterprise customer.
days (int): Include course enrollment of this number of days.
Returns:
(list): A list of CourseEnrollment objects.
"""
return CourseEnrollment.objects.filter(
created__gt=datetime.datetime.now() - datetime.timedelta(days=days)
).filter(
user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)
)
|
def course_modal(context, course=None):
"""
Django template tag that returns course information to display in a modal.
You may pass in a particular course if you like. Otherwise, the modal will look for course context
within the parent context.
Usage:
{% course_modal %}
{% course_modal course %}
"""
if course:
context.update({
'course_image_uri': course.get('course_image_uri', ''),
'course_title': course.get('course_title', ''),
'course_level_type': course.get('course_level_type', ''),
'course_short_description': course.get('course_short_description', ''),
'course_effort': course.get('course_effort', ''),
'course_full_description': course.get('course_full_description', ''),
'expected_learning_items': course.get('expected_learning_items', []),
'staff': course.get('staff', []),
'premium_modes': course.get('premium_modes', []),
})
return context
|
def link_to_modal(link_text, index, autoescape=True): # pylint: disable=unused-argument
"""
Django template filter that returns an anchor with attributes useful for course modal selection.
General Usage:
{{ link_text|link_to_modal:index }}
Examples:
{{ course_title|link_to_modal:forloop.counter0 }}
{{ course_title|link_to_modal:3 }}
{{ view_details_text|link_to_modal:0 }}
"""
link = (
'<a'
' href="#!"'
' class="text-underline view-course-details-link"'
' id="view-course-details-link-{index}"'
' data-toggle="modal"'
' data-target="#course-details-modal-{index}"'
'>{link_text}</a>'
).format(
index=index,
link_text=link_text,
)
return mark_safe(link)
|
def handle(self, *args, **options):
"""
Unlink inactive EnterpriseCustomer(s) SAP learners.
"""
channels = self.get_integrated_channels(options)
for channel in channels:
channel_code = channel.channel_code()
channel_pk = channel.pk
if channel_code == 'SAP':
# Transmit the learner data to each integrated channel
unlink_inactive_learners.delay(channel_code, channel_pk)
|
def populate_data_sharing_consent(apps, schema_editor):
"""
Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.
"""
DataSharingConsent = apps.get_model('consent', 'DataSharingConsent')
EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment')
User = apps.get_model('auth', 'User')
for enrollment in EnterpriseCourseEnrollment.objects.all():
user = User.objects.get(pk=enrollment.enterprise_customer_user.user_id)
data_sharing_consent, __ = DataSharingConsent.objects.get_or_create(
username=user.username,
enterprise_customer=enrollment.enterprise_customer_user.enterprise_customer,
course_id=enrollment.course_id,
)
if enrollment.consent_granted is not None:
data_sharing_consent.granted = enrollment.consent_granted
else:
# Check UDSCA instead.
consent_state = enrollment.enterprise_customer_user.data_sharing_consent.first()
if consent_state is not None:
data_sharing_consent.granted = consent_state.state in ['enabled', 'external']
else:
data_sharing_consent.granted = False
data_sharing_consent.save()
|
def create_course_completion(self, user_id, payload): # pylint: disable=unused-argument
"""
Send a completion status payload to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing completion status fields per Degreed documentation.
Returns:
A tuple containing the status code and the body of the response.
Raises:
HTTPError: if we received a failure response code from Degreed
"""
return self._post(
urljoin(
self.enterprise_configuration.degreed_base_url,
self.global_degreed_config.completion_status_api_path
),
payload,
self.COMPLETION_PROVIDER_SCOPE
)
|
def delete_course_completion(self, user_id, payload): # pylint: disable=unused-argument
"""
Delete a completion status previously sent to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing the required completion status fields for deletion per Degreed documentation.
Returns:
A tuple containing the status code and the body of the response.
Raises:
HTTPError: if we received a failure response code from Degreed
"""
return self._delete(
urljoin(
self.enterprise_configuration.degreed_base_url,
self.global_degreed_config.completion_status_api_path
),
payload,
self.COMPLETION_PROVIDER_SCOPE
)
|
def _sync_content_metadata(self, serialized_data, http_method):
"""
Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
Raises:
ClientError: If Degreed API request fails.
"""
try:
status_code, response_body = getattr(self, '_' + http_method)(
urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.course_api_path),
serialized_data,
self.CONTENT_PROVIDER_SCOPE
)
except requests.exceptions.RequestException as exc:
raise ClientError(
'DegreedAPIClient request failed: {error} {message}'.format(
error=exc.__class__.__name__,
message=str(exc)
)
)
if status_code >= 400:
raise ClientError(
'DegreedAPIClient request failed with status {status_code}: {message}'.format(
status_code=status_code,
message=response_body
)
)
|
def _post(self, url, data, scope):
"""
Make a POST request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a POST request to.
data (str): The json encoded payload to POST.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCOPE`
- `COMPLETION_PROVIDER_SCOPE`
"""
self._create_session(scope)
response = self.session.post(url, data=data)
return response.status_code, response.text
|
def _delete(self, url, data, scope):
"""
Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCOPE`
- `COMPLETION_PROVIDER_SCOPE`
"""
self._create_session(scope)
response = self.session.delete(url, data=data)
return response.status_code, response.text
|
def _create_session(self, scope):
"""
Instantiate a new session object for use in connecting with Degreed
"""
now = datetime.datetime.utcnow()
if self.session is None or self.expires_at is None or now >= self.expires_at:
# Create a new session with a valid token
if self.session:
self.session.close()
oauth_access_token, expires_at = self._get_oauth_access_token(
self.enterprise_configuration.key,
self.enterprise_configuration.secret,
self.enterprise_configuration.degreed_user_id,
self.enterprise_configuration.degreed_user_password,
scope
)
session = requests.Session()
session.timeout = self.SESSION_TIMEOUT
session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token)
session.headers['content-type'] = 'application/json'
self.session = session
self.expires_at = expires_at
|
def _get_oauth_access_token(self, client_id, client_secret, user_id, user_password, scope):
""" Retrieves OAuth 2.0 access token using the client credentials grant.
Args:
client_id (str): API client ID
client_secret (str): API client secret
user_id (str): Degreed company ID
user_password (str): Degreed user password
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCOPE`
- `COMPLETION_PROVIDER_SCOPE`
Returns:
tuple: Tuple containing access token string and expiration datetime.
Raises:
HTTPError: If we received a failure response code from Degreed.
RequestException: If an unexpected response format was received that we could not parse.
"""
response = requests.post(
urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.oauth_api_path),
data={
'grant_type': 'password',
'username': user_id,
'password': user_password,
'scope': scope,
},
auth=(client_id, client_secret),
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
response.raise_for_status()
data = response.json()
try:
expires_at = data['expires_in'] + int(time.time())
return data['access_token'], datetime.datetime.utcfromtimestamp(expires_at)
except KeyError:
raise requests.RequestException(response=response)
|
def ensure_data_exists(self, request, data, error_message=None):
"""
Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.
"""
if not data:
error_message = (
error_message or "Unable to fetch API response from endpoint '{}'.".format(request.get_full_path())
)
LOGGER.error(error_message)
raise NotFound(error_message)
|
def contains_content_items(self, request, pk, course_run_ids, program_uuids):
"""
Return whether or not the specified content is available to the EnterpriseCustomer.
Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check
for their existence in the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer.
At least one course run key or program UUID value must be included in the request.
"""
enterprise_customer = self.get_object()
# Maintain plus characters in course key.
course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]
contains_content_items = False
for catalog in enterprise_customer.enterprise_customer_catalogs.all():
contains_course_runs = not course_run_ids or catalog.contains_courses(course_run_ids)
contains_program_uuids = not program_uuids or catalog.contains_programs(program_uuids)
if contains_course_runs and contains_program_uuids:
contains_content_items = True
break
return Response({'contains_content_items': contains_content_items})
|
def courses(self, request, pk=None): # pylint: disable=invalid-name,unused-argument
"""
Retrieve the list of courses contained within the catalog linked to this enterprise.
Only courses with active course runs are returned. A course run is considered active if it is currently
open for enrollment, or will open in the future.
"""
enterprise_customer = self.get_object()
self.check_object_permissions(request, enterprise_customer)
self.ensure_data_exists(
request,
enterprise_customer.catalog,
error_message="No catalog is associated with Enterprise {enterprise_name} from endpoint '{path}'.".format(
enterprise_name=enterprise_customer.name,
path=request.get_full_path()
)
)
# We have handled potential error cases and are now ready to call out to the Catalog API.
catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)
courses = catalog_api.get_paginated_catalog_courses(enterprise_customer.catalog, request.GET)
# An empty response means that there was a problem fetching data from Catalog API, since
# a Catalog with no courses has a non empty response indicating that there are no courses.
self.ensure_data_exists(
request,
courses,
error_message=(
"Unable to fetch API response for catalog courses for "
"Enterprise {enterprise_name} from endpoint '{path}'.".format(
enterprise_name=enterprise_customer.name,
path=request.get_full_path()
)
)
)
serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)
# Add enterprise related context for the courses.
serializer.update_enterprise_courses(enterprise_customer, catalog_id=enterprise_customer.catalog)
return get_paginated_response(serializer.data, request)
|
def course_enrollments(self, request, pk):
"""
Creates a course enrollment for an EnterpriseCustomerUser.
"""
enterprise_customer = self.get_object()
serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer(
data=request.data,
many=True,
context={
'enterprise_customer': enterprise_customer,
'request_user': request.user,
}
)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
|
def with_access_to(self, request, *args, **kwargs): # pylint: disable=invalid-name,unused-argument
"""
Returns the list of enterprise customers the user has a specified group permission access to.
"""
self.queryset = self.queryset.order_by('name')
enterprise_id = self.request.query_params.get('enterprise_id', None)
enterprise_slug = self.request.query_params.get('enterprise_slug', None)
enterprise_name = self.request.query_params.get('search', None)
if enterprise_id is not None:
self.queryset = self.queryset.filter(uuid=enterprise_id)
elif enterprise_slug is not None:
self.queryset = self.queryset.filter(slug=enterprise_slug)
elif enterprise_name is not None:
self.queryset = self.queryset.filter(name__icontains=enterprise_name)
return self.list(request, *args, **kwargs)
|
def entitlements(self, request, pk=None): # pylint: disable=invalid-name,unused-argument
"""
Retrieve the list of entitlements available to this learner.
Only those entitlements are returned that satisfy enterprise customer's data sharing setting.
Arguments:
request (HttpRequest): Reference to in-progress request instance.
pk (Int): Primary key value of the selected enterprise learner.
Returns:
(HttpResponse): Response object containing a list of learner's entitlements.
"""
enterprise_customer_user = self.get_object()
instance = {"entitlements": enterprise_customer_user.entitlements}
serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'request': request})
return Response(serializer.data)
|
def contains_content_items(self, request, pk, course_run_ids, program_uuids):
"""
Return whether or not the EnterpriseCustomerCatalog contains the specified content.
Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check
for their existence in the EnterpriseCustomerCatalog. At least one course run key
or program UUID value must be included in the request.
"""
enterprise_customer_catalog = self.get_object()
# Maintain plus characters in course key.
course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]
contains_content_items = True
if course_run_ids:
contains_content_items = enterprise_customer_catalog.contains_courses(course_run_ids)
if program_uuids:
contains_content_items = (
contains_content_items and
enterprise_customer_catalog.contains_programs(program_uuids)
)
return Response({'contains_content_items': contains_content_items})
|
def course_detail(self, request, pk, course_key): # pylint: disable=invalid-name,unused-argument
"""
Return the metadata for the specified course.
The course needs to be included in the specified EnterpriseCustomerCatalog
in order for metadata to be returned from this endpoint.
"""
enterprise_customer_catalog = self.get_object()
course = enterprise_customer_catalog.get_course(course_key)
if not course:
raise Http404
context = self.get_serializer_context()
context['enterprise_customer_catalog'] = enterprise_customer_catalog
serializer = serializers.CourseDetailSerializer(course, context=context)
return Response(serializer.data)
|
def course_run_detail(self, request, pk, course_id): # pylint: disable=invalid-name,unused-argument
"""
Return the metadata for the specified course run.
The course run needs to be included in the specified EnterpriseCustomerCatalog
in order for metadata to be returned from this endpoint.
"""
enterprise_customer_catalog = self.get_object()
course_run = enterprise_customer_catalog.get_course_run(course_id)
if not course_run:
raise Http404
context = self.get_serializer_context()
context['enterprise_customer_catalog'] = enterprise_customer_catalog
serializer = serializers.CourseRunDetailSerializer(course_run, context=context)
return Response(serializer.data)
|
def program_detail(self, request, pk, program_uuid): # pylint: disable=invalid-name,unused-argument
"""
Return the metadata for the specified program.
The program needs to be included in the specified EnterpriseCustomerCatalog
in order for metadata to be returned from this endpoint.
"""
enterprise_customer_catalog = self.get_object()
program = enterprise_customer_catalog.get_program(program_uuid)
if not program:
raise Http404
context = self.get_serializer_context()
context['enterprise_customer_catalog'] = enterprise_customer_catalog
serializer = serializers.ProgramDetailSerializer(program, context=context)
return Response(serializer.data)
|
def list(self, request):
"""
DRF view to list all catalogs.
Arguments:
request (HttpRequest): Current request
Returns:
(Response): DRF response object containing course catalogs.
"""
catalog_api = CourseCatalogApiClient(request.user)
catalogs = catalog_api.get_paginated_catalogs(request.GET)
self.ensure_data_exists(request, catalogs)
serializer = serializers.ResponsePaginationSerializer(catalogs)
return get_paginated_response(serializer.data, request)
|
def retrieve(self, request, pk=None): # pylint: disable=invalid-name
"""
DRF view to get catalog details.
Arguments:
request (HttpRequest): Current request
pk (int): Course catalog identifier
Returns:
(Response): DRF response object containing course catalogs.
"""
catalog_api = CourseCatalogApiClient(request.user)
catalog = catalog_api.get_catalog(pk)
self.ensure_data_exists(
request,
catalog,
error_message=(
"Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. "
"The resource you are looking for does not exist.".format(pk=pk)
)
)
serializer = self.serializer_class(catalog)
return Response(serializer.data)
|
def courses(self, request, enterprise_customer, pk=None): # pylint: disable=invalid-name
"""
Retrieve the list of courses contained within this catalog.
Only courses with active course runs are returned. A course run is considered active if it is currently
open for enrollment, or will open in the future.
"""
catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)
courses = catalog_api.get_paginated_catalog_courses(pk, request.GET)
# If the API returned an empty response, that means pagination has ended.
# An empty response can also mean that there was a problem fetching data from catalog API.
self.ensure_data_exists(
request,
courses,
error_message=(
"Unable to fetch API response for catalog courses from endpoint '{endpoint}'. "
"The resource you are looking for does not exist.".format(endpoint=request.get_full_path())
)
)
serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)
# Add enterprise related context for the courses.
serializer.update_enterprise_courses(enterprise_customer, catalog_id=pk)
return get_paginated_response(serializer.data, request)
|
def get_required_query_params(self, request):
"""
Gets ``email``, ``enterprise_name``, and ``number_of_codes``,
which are the relevant parameters for this API endpoint.
:param request: The request to this endpoint.
:return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.
"""
email = get_request_value(request, self.REQUIRED_PARAM_EMAIL, '')
enterprise_name = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_NAME, '')
number_of_codes = get_request_value(request, self.OPTIONAL_PARAM_NUMBER_OF_CODES, '')
if not (email and enterprise_name):
raise CodesAPIRequestError(
self.get_missing_params_message([
(self.REQUIRED_PARAM_EMAIL, bool(email)),
(self.REQUIRED_PARAM_ENTERPRISE_NAME, bool(enterprise_name)),
])
)
return email, enterprise_name, number_of_codes
|
def get_missing_params_message(self, parameter_state):
"""
Get a user-friendly message indicating a missing parameter for the API endpoint.
"""
params = ', '.join(name for name, present in parameter_state if not present)
return self.MISSING_REQUIRED_PARAMS_MSG.format(params)
|
def post(self, request):
"""
POST /enterprise/api/v1/request_codes
Requires a JSON object of the following format:
>>> {
>>> "email": "bob@alice.com",
>>> "enterprise_name": "IBM",
>>> "number_of_codes": "50"
>>> }
Keys:
*email*
Email of the customer who has requested more codes.
*enterprise_name*
The name of the enterprise requesting more codes.
*number_of_codes*
The number of codes requested.
"""
try:
email, enterprise_name, number_of_codes = self.get_required_query_params(request)
except CodesAPIRequestError as invalid_request:
return Response({'error': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)
subject_line = _('Code Management - Request for Codes by {token_enterprise_name}').format(
token_enterprise_name=enterprise_name
)
msg_with_codes = _('{token_email} from {token_enterprise_name} has requested {token_number_codes} additional '
'codes. Please reach out to them.').format(
token_email=email,
token_enterprise_name=enterprise_name,
token_number_codes=number_of_codes)
msg_without_codes = _('{token_email} from {token_enterprise_name} has requested additional codes.'
' Please reach out to them.').format(
token_email=email,
token_enterprise_name=enterprise_name)
app_config = apps.get_app_config("enterprise")
from_email_address = app_config.customer_success_email
cs_email = app_config.customer_success_email
data = {
self.REQUIRED_PARAM_EMAIL: email,
self.REQUIRED_PARAM_ENTERPRISE_NAME: enterprise_name,
self.OPTIONAL_PARAM_NUMBER_OF_CODES: number_of_codes,
}
try:
mail.send_mail(
subject_line,
msg_with_codes if number_of_codes else msg_without_codes,
from_email_address,
[cs_email],
fail_silently=False
)
return Response(data, status=HTTP_200_OK)
except SMTPException:
error_message = _(
'[Enterprise API] Failure in sending e-mail to {token_cs_email} for {token_email}'
' from {token_enterprise_name}'
).format(
token_cs_email=cs_email,
token_email=email,
token_enterprise_name=enterprise_name
)
LOGGER.error(error_message)
return Response(
{'error': str('Request codes email could not be sent')},
status=HTTP_500_INTERNAL_SERVER_ERROR
)
|
def transform_title(self, content_metadata_item):
"""
Return the title of the content item.
"""
title_with_locales = []
for locale in self.enterprise_configuration.get_locales():
title_with_locales.append({
'locale': locale,
'value': content_metadata_item.get('title', '')
})
return title_with_locales
|
def transform_description(self, content_metadata_item):
"""
Return the description of the content item.
"""
description_with_locales = []
for locale in self.enterprise_configuration.get_locales():
description_with_locales.append({
'locale': locale,
'value': (
content_metadata_item.get('full_description') or
content_metadata_item.get('short_description') or
content_metadata_item.get('title', '')
)
})
return description_with_locales
|
def transform_image(self, content_metadata_item):
"""
Return the image URI of the content item.
"""
image_url = ''
if content_metadata_item['content_type'] in ['course', 'program']:
image_url = content_metadata_item.get('card_image_url')
elif content_metadata_item['content_type'] == 'courserun':
image_url = content_metadata_item.get('image_url')
return image_url
|
def transform_launch_points(self, content_metadata_item):
"""
Return the content metadata item launch points.
SAPSF allows you to transmit an arry of content launch points which
are meant to represent sections of a content item which a learner can
launch into from SAPSF. Currently, we only provide a single launch
point for a content item.
"""
return [{
'providerID': self.enterprise_configuration.provider_id,
'launchURL': content_metadata_item['enrollment_url'],
'contentTitle': content_metadata_item['title'],
'contentID': self.get_content_id(content_metadata_item),
'launchType': 3, # This tells SAPSF to launch the course in a new browser window.
'mobileEnabled': True, # Always return True per ENT-1401
'mobileLaunchURL': content_metadata_item['enrollment_url'],
}]
|
def transform_courserun_title(self, content_metadata_item):
"""
Return the title of the courserun content item.
"""
title = content_metadata_item.get('title') or ''
course_run_start = content_metadata_item.get('start')
if course_run_start:
if course_available_for_enrollment(content_metadata_item):
title += ' ({starts}: {:%B %Y})'.format(
parse_lms_api_datetime(course_run_start),
starts=_('Starts')
)
else:
title += ' ({:%B %Y} - {enrollment_closed})'.format(
parse_lms_api_datetime(course_run_start),
enrollment_closed=_('Enrollment Closed')
)
title_with_locales = []
content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))
for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):
title_with_locales.append({
'locale': locale,
'value': title
})
return title_with_locales
|
def transform_courserun_description(self, content_metadata_item):
"""
Return the description of the courserun content item.
"""
description_with_locales = []
content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', ''))
for locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):
description_with_locales.append({
'locale': locale,
'value': (
content_metadata_item['full_description'] or
content_metadata_item['short_description'] or
content_metadata_item['title'] or
''
)
})
return description_with_locales
|
def transform_courserun_schedule(self, content_metadata_item):
"""
Return the schedule of the courseun content item.
"""
start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING
end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING
return [{
'startDate': parse_datetime_to_epoch_millis(start),
'endDate': parse_datetime_to_epoch_millis(end),
'active': current_time_is_in_interval(start, end)
}]
|
def get_content_id(self, content_metadata_item):
"""
Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content
"""
content_id = content_metadata_item.get('key', '')
if content_metadata_item['content_type'] == 'program':
content_id = content_metadata_item.get('uuid', '')
return content_id
|
def parse_datetime_to_epoch(datestamp, magnitude=1.0):
"""
Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude.
By default, returns seconds.
"""
parsed_datetime = parse_lms_api_datetime(datestamp)
time_since_epoch = parsed_datetime - UNIX_EPOCH
return int(time_since_epoch.total_seconds() * magnitude)
|
def current_time_is_in_interval(start, end):
"""
Determine whether the current time is on the interval [start, end].
"""
interval_start = parse_lms_api_datetime(start or UNIX_MIN_DATE_STRING)
interval_end = parse_lms_api_datetime(end or UNIX_MAX_DATE_STRING)
return interval_start <= timezone.now() <= interval_end
|
def chunks(dictionary, chunk_size):
"""
Yield successive n-sized chunks from dictionary.
"""
iterable = iter(dictionary)
for __ in range(0, len(dictionary), chunk_size):
yield {key: dictionary[key] for key in islice(iterable, chunk_size)}
|
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', input_type='timedelta'):
"""
Convert a datetime.timedelta object or a regular number to a custom-formatted string.
This function works like the strftime() method works for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Arguments:
tdelta (datetime.timedelta, int): time delta object containing the duration or an integer
to go with the input_type.
fmt (str): Expected format of the time delta. place holders can only be one of the following.
1. D to extract days from time delta
2. H to extract hours from time delta
3. M to extract months from time delta
4. S to extract seconds from timedelta
input_type (str): The input_type argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object.
Valid input_type strings:
1. 's', 'seconds',
2. 'm', 'minutes',
3. 'h', 'hours',
4. 'd', 'days',
5. 'w', 'weeks'
Returns:
(str): timedelta object interpolated into a string following the given format.
Examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
"""
# Convert tdelta to integer seconds.
if input_type == 'timedelta':
remainder = int(tdelta.total_seconds())
elif input_type in ['s', 'seconds']:
remainder = int(tdelta)
elif input_type in ['m', 'minutes']:
remainder = int(tdelta) * 60
elif input_type in ['h', 'hours']:
remainder = int(tdelta) * 3600
elif input_type in ['d', 'days']:
remainder = int(tdelta) * 86400
elif input_type in ['w', 'weeks']:
remainder = int(tdelta) * 604800
else:
raise ValueError(
'input_type is not valid. Valid input_type strings are: "timedelta", "s", "m", "h", "d", "w"'
)
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
|
def transform_description(self, content_metadata_item):
"""
Return the transformed version of the course description.
We choose one value out of the course's full description, short description, and title
depending on availability and length limits.
"""
full_description = content_metadata_item.get('full_description') or ''
if 0 < len(full_description) <= self.LONG_STRING_LIMIT: # pylint: disable=len-as-condition
return full_description
return content_metadata_item.get('short_description') or content_metadata_item.get('title') or ''
|
def logo_path(instance, filename):
"""
Delete the file if it already exist and returns the enterprise customer logo image path.
Arguments:
instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object
filename (str): file to upload
Returns:
path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()
"""
extension = os.path.splitext(filename)[1].lower()
instance_id = str(instance.id)
fullname = os.path.join("enterprise/branding/", instance_id, instance_id + "_logo" + extension)
if default_storage.exists(fullname):
default_storage.delete(fullname)
return fullname
|
def get_link_by_email(self, user_email):
"""
Return link by email.
"""
try:
user = User.objects.get(email=user_email)
try:
return self.get(user_id=user.id)
except EnterpriseCustomerUser.DoesNotExist:
pass
except User.DoesNotExist:
pass
try:
return PendingEnterpriseCustomerUser.objects.get(user_email=user_email)
except PendingEnterpriseCustomerUser.DoesNotExist:
pass
return None
|
def link_user(self, enterprise_customer, user_email):
"""
Link user email to Enterprise Customer.
If :class:`django.contrib.auth.models.User` instance with specified email does not exist,
:class:`.PendingEnterpriseCustomerUser` instance is created instead.
"""
try:
existing_user = User.objects.get(email=user_email)
self.get_or_create(enterprise_customer=enterprise_customer, user_id=existing_user.id)
except User.DoesNotExist:
PendingEnterpriseCustomerUser.objects.get_or_create(enterprise_customer=enterprise_customer,
user_email=user_email)
|
def unlink_user(self, enterprise_customer, user_email):
"""
Unlink user email from Enterprise Customer.
If :class:`django.contrib.auth.models.User` instance with specified email does not exist,
:class:`.PendingEnterpriseCustomerUser` instance is deleted instead.
Raises EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with
specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not.
Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of
:class:`django.contrib.auth.models.User` with specified email exists and corresponding
:class:`.PendingEnterpriseCustomerUser` instance does not.
"""
try:
existing_user = User.objects.get(email=user_email)
# not capturing DoesNotExist intentionally to signal to view that link does not exist
link_record = self.get(enterprise_customer=enterprise_customer, user_id=existing_user.id)
link_record.delete()
if update_user:
# Remove the SailThru flags for enterprise learner.
update_user.delay(
sailthru_vars={
'is_enterprise_learner': False,
'enterprise_name': None,
},
email=user_email
)
except User.DoesNotExist:
# not capturing DoesNotExist intentionally to signal to view that link does not exist
pending_link = PendingEnterpriseCustomerUser.objects.get(
enterprise_customer=enterprise_customer, user_email=user_email
)
pending_link.delete()
LOGGER.info(
'Enterprise learner {%s} successfully unlinked from Enterprise Customer {%s}',
user_email,
enterprise_customer.name
)
|
def enterprise_customer_uuid(self):
"""Get the enterprise customer uuid linked to the user."""
try:
enterprise_user = EnterpriseCustomerUser.objects.get(user_id=self.user.id)
except ObjectDoesNotExist:
LOGGER.warning(
'User {} has a {} assignment but is not linked to an enterprise!'.format(
self.__class__,
self.user.id
))
return None
except MultipleObjectsReturned:
LOGGER.warning(
'User {} is linked to multiple enterprises, which is not yet supported!'.format(self.user.id)
)
return None
return str(enterprise_user.enterprise_customer.uuid)
|
def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None):
"""
Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.
:param username: The user that grants consent
:param enterprise_customer_uuid: The consent requester
:param course_id (optional): A course ID to which consent may be related
:param program_uuid (optional): A program to which consent may be related
:return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.
"""
EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer') # pylint: disable=invalid-name
try:
if course_id:
return get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid)
return get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid)
except EnterpriseCustomer.DoesNotExist:
return None
|
def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object
"""
# Prevent circular imports.
DataSharingConsent = apps.get_model('consent', 'DataSharingConsent') # pylint: disable=invalid-name
return DataSharingConsent.objects.proxied_get(
username=username,
course_id=course_id,
enterprise_customer__uuid=enterprise_customer_uuid
)
|
def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a program.
:param username: The user that grants consent.
:param program_uuid: The program for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object
"""
enterprise_customer = get_enterprise_customer(enterprise_customer_uuid)
discovery_client = CourseCatalogApiServiceClient(enterprise_customer.site)
course_ids = discovery_client.get_program_course_keys(program_uuid)
child_consents = (
get_data_sharing_consent(username, enterprise_customer_uuid, course_id=individual_course_id)
for individual_course_id in course_ids
)
return ProxyDataSharingConsent.from_children(program_uuid, *child_consents)
|
def send_course_enrollment_statement(lrs_configuration, course_enrollment):
"""
Send xAPI statement for course enrollment.
Arguments:
lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.
course_enrollment (CourseEnrollment): Course enrollment object.
"""
user_details = LearnerInfoSerializer(course_enrollment.user)
course_details = CourseInfoSerializer(course_enrollment.course)
statement = LearnerCourseEnrollmentStatement(
course_enrollment.user,
course_enrollment.course,
user_details.data,
course_details.data,
)
EnterpriseXAPIClient(lrs_configuration).save_statement(statement)
|
def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade):
"""
Send xAPI statement for course completion.
Arguments:
lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.
user (User): Django User object.
course_overview (CourseOverview): Course over view object containing course details.
course_grade (CourseGrade): course grade object.
"""
user_details = LearnerInfoSerializer(user)
course_details = CourseInfoSerializer(course_overview)
statement = LearnerCourseCompletionStatement(
user,
course_overview,
user_details.data,
course_details.data,
course_grade,
)
EnterpriseXAPIClient(lrs_configuration).save_statement(statement)
|
def export(self):
"""
Return the exported and transformed content metadata as a dictionary.
"""
content_metadata_export = {}
content_metadata_items = self.enterprise_api.get_content_metadata(self.enterprise_customer)
LOGGER.info('Retrieved content metadata for enterprise [%s]', self.enterprise_customer.name)
for item in content_metadata_items:
transformed = self._transform_item(item)
LOGGER.info(
'Exporting content metadata item with plugin configuration [%s]: [%s]',
self.enterprise_configuration,
json.dumps(transformed, indent=4),
)
content_metadata_item_export = ContentMetadataItemExport(item, transformed)
content_metadata_export[content_metadata_item_export.content_id] = content_metadata_item_export
return OrderedDict(sorted(content_metadata_export.items()))
|
def _transform_item(self, content_metadata_item):
"""
Transform the provided content metadata item to the schema expected by the integrated channel.
"""
content_metadata_type = content_metadata_item['content_type']
transformed_item = {}
for integrated_channel_schema_key, edx_data_schema_key in self.DATA_TRANSFORM_MAPPING.items():
# Look for transformer functions defined on subclasses.
# Favor content type-specific functions.
transformer = (
getattr(
self,
'transform_{content_type}_{edx_data_schema_key}'.format(
content_type=content_metadata_type,
edx_data_schema_key=edx_data_schema_key
),
None
)
or
getattr(
self,
'transform_{edx_data_schema_key}'.format(
edx_data_schema_key=edx_data_schema_key
),
None
)
)
if transformer:
transformed_item[integrated_channel_schema_key] = transformer(content_metadata_item)
else:
# The concrete subclass does not define an override for the given field,
# so just use the data key to index the content metadata item dictionary.
try:
transformed_item[integrated_channel_schema_key] = content_metadata_item[edx_data_schema_key]
except KeyError:
# There may be a problem with the DATA_TRANSFORM_MAPPING on
# the concrete subclass or the concrete subclass does not implement
# the appropriate field tranformer function.
LOGGER.exception(
'Failed to transform content metadata item field [%s] for [%s]: [%s]',
edx_data_schema_key,
self.enterprise_customer.name,
content_metadata_item,
)
return transformed_item
|
def get_consent_record(self, request):
"""
Get the consent record relevant to the request at hand.
"""
username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)
return get_data_sharing_consent(
username,
enterprise_customer_uuid,
course_id=course_id,
program_uuid=program_uuid
)
|
def get_required_query_params(self, request):
"""
Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``,
which are the relevant query parameters for this API endpoint.
:param request: The request to this endpoint.
:return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.
"""
username = get_request_value(request, self.REQUIRED_PARAM_USERNAME, '')
course_id = get_request_value(request, self.REQUIRED_PARAM_COURSE_ID, '')
program_uuid = get_request_value(request, self.REQUIRED_PARAM_PROGRAM_UUID, '')
enterprise_customer_uuid = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER)
if not (username and (course_id or program_uuid) and enterprise_customer_uuid):
raise ConsentAPIRequestError(
self.get_missing_params_message([
("'username'", bool(username)),
("'enterprise_customer_uuid'", bool(enterprise_customer_uuid)),
("one of 'course_id' or 'program_uuid'", bool(course_id or program_uuid)),
])
)
return username, course_id, program_uuid, enterprise_customer_uuid
|
def get_no_record_response(self, request):
"""
Get an HTTPResponse that can be used when there's no related EnterpriseCustomer.
"""
username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)
data = {
self.REQUIRED_PARAM_USERNAME: username,
self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER: enterprise_customer_uuid,
self.CONSENT_EXISTS: False,
self.CONSENT_GRANTED: False,
self.CONSENT_REQUIRED: False,
}
if course_id:
data[self.REQUIRED_PARAM_COURSE_ID] = course_id
if program_uuid:
data[self.REQUIRED_PARAM_PROGRAM_UUID] = program_uuid
return Response(data, status=HTTP_200_OK)
|
def get(self, request):
"""
GET /consent/api/v1/data_sharing_consent?username=bob&course_id=id&enterprise_customer_uuid=uuid
*username*
The edX username from whom to get consent.
*course_id*
The course for which consent is granted.
*enterprise_customer_uuid*
The UUID of the enterprise customer that requires consent.
"""
try:
consent_record = self.get_consent_record(request)
if consent_record is None:
return self.get_no_record_response(request)
except ConsentAPIRequestError as invalid_request:
return Response({'error': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)
return Response(consent_record.serialize(), status=HTTP_200_OK)
|
def post(self, request):
"""
POST /consent/api/v1/data_sharing_consent
Requires a JSON object of the following format:
>>> {
>>> "username": "bob",
>>> "course_id": "course-v1:edX+DemoX+Demo_Course",
>>> "enterprise_customer_uuid": "enterprise-uuid-goes-right-here"
>>> }
Keys:
*username*
The edX username from whom to get consent.
*course_id*
The course for which consent is granted.
*enterprise_customer_uuid*
The UUID of the enterprise customer that requires consent.
"""
try:
consent_record = self.get_consent_record(request)
if consent_record is None:
return self.get_no_record_response(request)
if consent_record.consent_required():
# If and only if the given EnterpriseCustomer requires data sharing consent
# for the given course, then, since we've received a POST request, set the
# consent state for the EC/user/course combo.
consent_record.granted = True
# Models don't have return values when saving, but ProxyDataSharingConsent
# objects do - they should return either a model instance, or another instance
# of ProxyDataSharingConsent if representing a multi-course consent record.
consent_record = consent_record.save() or consent_record
except ConsentAPIRequestError as invalid_request:
return Response({'error': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)
return Response(consent_record.serialize())
|
def delete(self, request):
"""
DELETE /consent/api/v1/data_sharing_consent
Requires a JSON object of the following format:
>>> {
>>> "username": "bob",
>>> "course_id": "course-v1:edX+DemoX+Demo_Course",
>>> "enterprise_customer_uuid": "enterprise-uuid-goes-right-here"
>>> }
Keys:
*username*
The edX username from whom to get consent.
*course_id*
The course for which consent is granted.
*enterprise_customer_uuid*
The UUID of the enterprise customer that requires consent.
"""
try:
consent_record = self.get_consent_record(request)
if consent_record is None:
return self.get_no_record_response(request)
# We're fine with proactively refusing consent, even when there's no actual
# requirement for consent yet.
consent_record.granted = False
# Models don't have return values when saving, but ProxyDataSharingConsent
# objects do - they should return either a model instance, or another instance
# of ProxyDataSharingConsent if representing a multi-course consent record.
consent_record = consent_record.save() or consent_record
except ConsentAPIRequestError as invalid_request:
return Response({'error': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)
return Response(consent_record.serialize())
|
def ready(self):
"""
Perform other one-time initialization steps.
"""
from enterprise.signals import handle_user_post_save
from django.db.models.signals import pre_migrate, post_save
post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)
pre_migrate.connect(self._disconnect_user_post_save_for_migrations)
|
def _disconnect_user_post_save_for_migrations(self, sender, **kwargs): # pylint: disable=unused-argument
"""
Handle pre_migrate signal - disconnect User post_save handler.
"""
from django.db.models.signals import post_save
post_save.disconnect(sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)
|
def get_actor(self, username, email):
"""
Get actor for the statement.
"""
return Agent(
name=username,
mbox='mailto:{email}'.format(email=email),
)
|
def get_object(self, name, description):
"""
Get object for the statement.
"""
return Activity(
id=X_API_ACTIVITY_COURSE,
definition=ActivityDefinition(
name=LanguageMap({'en-US': (name or '').encode("ascii", "ignore").decode('ascii')}),
description=LanguageMap({'en-US': (description or '').encode("ascii", "ignore").decode('ascii')}),
),
)
|
def parse_csv(file_stream, expected_columns=None):
"""
Parse csv file and return a stream of dictionaries representing each row.
First line of CSV file must contain column headers.
Arguments:
file_stream: input file
expected_columns (set[unicode]): columns that are expected to be present
Yields:
dict: CSV line parsed into a dictionary.
"""
reader = unicodecsv.DictReader(file_stream, encoding="utf-8")
if expected_columns and set(expected_columns) - set(reader.fieldnames):
raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format(
expected_columns=", ".join(expected_columns), actual_columns=", ".join(reader.fieldnames)
))
# "yield from reader" would be nicer, but we're on python2.7 yet.
for row in reader:
yield row
|
def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False):
"""
Validate email to be linked to Enterprise Customer.
Performs two checks:
* Checks that email is valid
* Checks that it is not already linked to any Enterprise Customer
Arguments:
email (str): user email to link
raw_email (str): raw value as it was passed by user - used in error message.
message_template (str): Validation error template string.
ignore_existing (bool): If True to skip the check for an existing Enterprise Customer
Raises:
ValidationError: if email is invalid or already linked to Enterprise Customer.
Returns:
bool: Whether or not there is an existing record with the same email address.
"""
raw_email = raw_email if raw_email is not None else email
message_template = message_template if message_template is not None else ValidationMessages.INVALID_EMAIL
try:
validate_email(email)
except ValidationError:
raise ValidationError(message_template.format(argument=raw_email))
existing_record = EnterpriseCustomerUser.objects.get_link_by_email(email)
if existing_record and not ignore_existing:
raise ValidationError(ValidationMessages.USER_ALREADY_REGISTERED.format(
email=email, ec_name=existing_record.enterprise_customer.name
))
return existing_record or False
|
def get_course_runs_from_program(program):
"""
Return course runs from program data.
Arguments:
program(dict): Program data from Course Catalog API
Returns:
set: course runs in given program
"""
course_runs = set()
for course in program.get("courses", []):
for run in course.get("course_runs", []):
if "key" in run and run["key"]:
course_runs.add(run["key"])
return course_runs
|
def get_earliest_start_date_from_program(program):
"""
Get the earliest date that one of the courses in the program was available.
For the sake of emails to new learners, we treat this as the program start date.
Arguemnts:
program (dict): Program data from Course Catalog API
returns:
datetime.datetime: The date and time at which the first course started
"""
start_dates = []
for course in program.get('courses', []):
for run in course.get('course_runs', []):
if run.get('start'):
start_dates.append(parse_lms_api_datetime(run['start']))
if not start_dates:
return None
return min(start_dates)
|
def paginated_list(object_list, page, page_size=25):
"""
Returns paginated list.
Arguments:
object_list (QuerySet): A list of records to be paginated.
page (int): Current page number.
page_size (int): Number of records displayed in each paginated set.
show_all (bool): Whether to show all records.
Adopted from django/contrib/admin/templatetags/admin_list.py
https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50
"""
paginator = CustomPaginator(object_list, page_size)
try:
object_list = paginator.page(page)
except PageNotAnInteger:
object_list = paginator.page(1)
except EmptyPage:
object_list = paginator.page(paginator.num_pages)
page_range = []
page_num = object_list.number
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):
page_range.extend(range(1, PAGES_ON_ENDS + 1))
page_range.append(DOT)
page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(1, page_num + 1))
if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):
page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))
else:
page_range.extend(range(page_num + 1, paginator.num_pages + 1))
# Override page range to implement custom smart links.
object_list.paginator.page_range = page_range
return object_list
|
def clean_email_or_username(self):
"""
Clean email form field
Returns:
str: the cleaned value, converted to an email address (or an empty string)
"""
email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()
if not email_or_username:
# The field is blank; we just return the existing blank value.
return email_or_username
email = email_or_username__to__email(email_or_username)
bulk_entry = len(split_usernames_and_emails(email)) > 1
if bulk_entry:
for email in split_usernames_and_emails(email):
validate_email_to_link(
email,
None,
ValidationMessages.INVALID_EMAIL_OR_USERNAME,
ignore_existing=True
)
email = email_or_username
else:
validate_email_to_link(
email,
email_or_username,
ValidationMessages.INVALID_EMAIL_OR_USERNAME,
ignore_existing=True
)
return email
|
def clean_course(self):
"""
Verify course ID and retrieve course details.
"""
course_id = self.cleaned_data[self.Fields.COURSE].strip()
if not course_id:
return None
try:
client = EnrollmentApiClient()
return client.get_course_details(course_id)
except (HttpClientError, HttpServerError):
raise ValidationError(ValidationMessages.INVALID_COURSE_ID.format(course_id=course_id))
|
def clean_program(self):
"""
Clean program.
Try obtaining program treating form value as program UUID or title.
Returns:
dict: Program information if program found
"""
program_id = self.cleaned_data[self.Fields.PROGRAM].strip()
if not program_id:
return None
try:
client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)
program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id)
except MultipleProgramMatchError as exc:
raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))
except (HttpClientError, HttpServerError):
raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))
if not program:
raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))
if program['status'] != ProgramStatuses.ACTIVE:
raise ValidationError(
ValidationMessages.PROGRAM_IS_INACTIVE.format(program_id=program_id, status=program['status'])
)
return program
|
def clean_notify(self):
"""
Clean the notify_on_enrollment field.
"""
return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
|
def clean(self):
"""
Clean fields that depend on each other.
In this case, the form can be used to link single user or bulk link multiple users. These are mutually
exclusive modes, so this method checks that only one field is passed.
"""
cleaned_data = super(ManageLearnersForm, self).clean()
# Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods
# might "invalidate" the value and set it to None, while all we care here is if it was provided at all or not
email_or_username = self.data.get(self.Fields.EMAIL_OR_USERNAME, None)
bulk_upload_csv = self.files.get(self.Fields.BULK_UPLOAD, None)
if not email_or_username and not bulk_upload_csv:
raise ValidationError(ValidationMessages.NO_FIELDS_SPECIFIED)
if email_or_username and bulk_upload_csv:
raise ValidationError(ValidationMessages.BOTH_FIELDS_SPECIFIED)
if email_or_username:
mode = self.Modes.MODE_SINGULAR
else:
mode = self.Modes.MODE_BULK
cleaned_data[self.Fields.MODE] = mode
cleaned_data[self.Fields.NOTIFY] = self.clean_notify()
self._validate_course()
self._validate_program()
if self.data.get(self.Fields.PROGRAM, None) and self.data.get(self.Fields.COURSE, None):
raise ValidationError(ValidationMessages.COURSE_AND_PROGRAM_ERROR)
return cleaned_data
|
def _validate_course(self):
"""
Verify that the selected mode is valid for the given course .
"""
# Verify that the selected mode is valid for the given course .
course_details = self.cleaned_data.get(self.Fields.COURSE)
if course_details:
course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)
if not course_mode:
raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)
valid_course_modes = course_details["course_modes"]
if all(course_mode != mode["slug"] for mode in valid_course_modes):
error = ValidationError(ValidationMessages.COURSE_MODE_INVALID_FOR_COURSE.format(
course_mode=course_mode,
course_id=course_details["course_id"],
))
raise ValidationError({self.Fields.COURSE_MODE: error})
|
def _validate_program(self):
"""
Verify that selected mode is available for program and all courses in the program
"""
program = self.cleaned_data.get(self.Fields.PROGRAM)
if not program:
return
course_runs = get_course_runs_from_program(program)
try:
client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)
available_modes = client.get_common_course_modes(course_runs)
course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)
except (HttpClientError, HttpServerError):
raise ValidationError(
ValidationMessages.FAILED_TO_OBTAIN_COURSE_MODES.format(program_title=program.get("title"))
)
if not course_mode:
raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)
if course_mode not in available_modes:
raise ValidationError(ValidationMessages.COURSE_MODE_NOT_AVAILABLE.format(
mode=course_mode, program_title=program.get("title"), modes=", ".join(available_modes)
))
|
def get_catalog_options(self):
"""
Retrieve a list of catalog ID and name pairs.
Once retrieved, these name pairs can be used directly as a value
for the `choices` argument to a ChoiceField.
"""
# TODO: We will remove the discovery service catalog implementation
# once we have fully migrated customer's to EnterpriseCustomerCatalogs.
# For now, this code will prevent an admin from creating a new
# EnterpriseCustomer with a discovery service catalog. They will have to first
# save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer
# to add a discovery service catalog.
if hasattr(self.instance, 'site'):
catalog_api = CourseCatalogApiClient(self.user, self.instance.site)
else:
catalog_api = CourseCatalogApiClient(self.user)
catalogs = catalog_api.get_all_catalogs()
# order catalogs by name.
catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower())
return BLANK_CHOICE_DASH + [
(catalog['id'], catalog['name'],)
for catalog in catalogs
]
|
def clean(self):
"""
Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field.
"""
cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()
if 'catalog' in cleaned_data and not cleaned_data['catalog']:
cleaned_data['catalog'] = None
return cleaned_data
|
def clean(self):
"""
Final validations of model fields.
1. Validate that selected site for enterprise customer matches with the selected identity provider's site.
"""
super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()
provider_id = self.cleaned_data.get('provider_id', None)
enterprise_customer = self.cleaned_data.get('enterprise_customer', None)
if provider_id is None or enterprise_customer is None:
# field validation for either provider_id or enterprise_customer has already raised
# a validation error.
return
identity_provider = utils.get_identity_provider(provider_id)
if not identity_provider:
# This should not happen, as identity providers displayed in drop down are fetched dynamically.
message = _(
"The specified Identity Provider does not exist. For more "
"information, contact a system administrator.",
)
# Log message for debugging
logger.exception(message)
raise ValidationError(message)
if identity_provider and identity_provider.site != enterprise_customer.site:
raise ValidationError(
_(
"The site for the selected identity provider "
"({identity_provider_site}) does not match the site for "
"this enterprise customer ({enterprise_customer_site}). "
"To correct this problem, select a site that has a domain "
"of '{identity_provider_site}', or update the identity "
"provider to '{enterprise_customer_site}'."
).format(
enterprise_customer_site=enterprise_customer.site,
identity_provider_site=identity_provider.site,
),
)
|
def clean(self):
"""
Override of clean method to perform additional validation
"""
cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean()
report_customer = cleaned_data.get('enterprise_customer')
# Check that any selected catalogs are tied to the selected enterprise.
invalid_catalogs = [
'{} ({})'.format(catalog.title, catalog.uuid)
for catalog in cleaned_data.get('enterprise_customer_catalogs')
if catalog.enterprise_customer != report_customer
]
if invalid_catalogs:
message = _(
'These catalogs for reporting do not match enterprise'
'customer {enterprise_customer}: {invalid_catalogs}',
).format(
enterprise_customer=report_customer,
invalid_catalogs=invalid_catalogs,
)
self.add_error('enterprise_customer_catalogs', message)
|
def clean_channel_worker_username(self):
"""
Clean enterprise channel worker user form field
Returns:
str: the cleaned value of channel user username for transmitting courses metadata.
"""
channel_worker_username = self.cleaned_data['channel_worker_username'].strip()
try:
User.objects.get(username=channel_worker_username)
except User.DoesNotExist:
raise ValidationError(
ValidationMessages.INVALID_CHANNEL_WORKER.format(
channel_worker_username=channel_worker_username
)
)
return channel_worker_username
|
def verify_edx_resources():
"""
Ensure that all necessary resources to render the view are present.
"""
required_methods = {
'ProgramDataExtender': ProgramDataExtender,
}
for method in required_methods:
if required_methods[method] is None:
raise NotConnectedToOpenEdX(
_("The following method from the Open edX platform is necessary for this view but isn't available.")
+ "\nUnavailable: {method}".format(method=method)
)
|
def get_global_context(request, enterprise_customer):
"""
Get the set of variables that are needed by default across views.
"""
platform_name = get_configuration_value("PLATFORM_NAME", settings.PLATFORM_NAME)
# pylint: disable=no-member
return {
'enterprise_customer': enterprise_customer,
'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY,
'LANGUAGE_CODE': get_language_from_request(request),
'tagline': get_configuration_value("ENTERPRISE_TAGLINE", settings.ENTERPRISE_TAGLINE),
'platform_description': get_configuration_value(
"PLATFORM_DESCRIPTION",
settings.PLATFORM_DESCRIPTION,
),
'LMS_ROOT_URL': settings.LMS_ROOT_URL,
'platform_name': platform_name,
'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name),
'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name),
'enterprise_welcome_text': constants.ENTERPRISE_WELCOME_TEXT.format(
enterprise_customer_name=enterprise_customer.name,
platform_name=platform_name,
strong_start='<strong>',
strong_end='</strong>',
line_break='<br/>',
privacy_policy_link_start="<a href='{pp_url}' target='_blank'>".format(
pp_url=get_configuration_value('PRIVACY', 'https://www.edx.org/edx-privacy-policy', type='url'),
),
privacy_policy_link_end="</a>",
),
}
|
def get_price_text(price, request):
"""
Return the localized converted price as string (ex. '$150 USD').
If the local_currency switch is enabled and the users location has been determined this will convert the
given price based on conversion rate from the Catalog service and return a localized string
"""
if waffle.switch_is_active('local_currency') and get_localized_price_text:
return get_localized_price_text(price, request)
return format_price(price)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.