Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
74d7843
feat: add course existence and advanced settings permission classes
Oct 25, 2026
50f187d
feat: serve course advanced settings from authoring v1
Oct 25, 2026
d16332b
docs: mark the v0 advanced settings deprecated in favour of authoring v1
Oct 25, 2026
7166b67
test: import the authoring URLconf inside the test that needs it
Oct 25, 2026
2de569d
test: align the advanced settings tests with the platform's behaviour
Oct 25, 2026
9ef9009
test: share the authoring v1 test helpers
Oct 25, 2026
b02f84c
docs: describe what an inactive session and a superuser are allowed
Oct 26, 2026
3f56f61
docs: remove the deprecation notes from the v0 advanced settings docs…
Oct 31, 2026
0c92add
fix: return the course rules' own messages for refused advanced settings
Oct 31, 2026
0517173
test: give the long-explanation check text that is not a rule message
Oct 31, 2026
cb2e32c
chore: import the authz constants from openedx_authz.authz
Nov 18, 2026
ae0e975
feat: add course content editing permission classes
Oct 25, 2026
5bffe2f
feat: serve the course optimizer from authoring v1
Oct 25, 2026
55f1a57
docs: mark the v0 course optimizer deprecated in favour of authoring v1
Oct 25, 2026
293820d
docs: remove the deprecation notes from the v0 course optimizer docst…
Oct 31, 2026
cb9e503
fix: pin the run-state enum name and measure each read with a fresh user
Oct 31, 2026
b725b37
chore: import the authz constants from openedx_authz.authz
Nov 18, 2026
3ac3665
test: assert emptiness without comparing to an empty list
Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v1/advanced_settings_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""Reads and updates of a course's advanced settings."""

import logging
import re

from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.settings import api_settings

from cms.djangoapps.contentstore.views.course import update_course_advanced_settings
from cms.djangoapps.contentstore.views.permissions import COURSE_NOT_FOUND_MESSAGE
from cms.djangoapps.models.settings.course_metadata import CourseMetadata
from xmodule.modulestore.django import modulestore

log = logging.getLogger(__name__)

# Reported under the name of a refused setting in place of any explanation
# that is not one of the course rules' own messages, such as the text of an
# exception raised while converting the value. That explanation is logged.
INVALID_SETTING_MESSAGE = "The value is not valid for this setting."
# Reported when the settings could not be saved for a reason tied to no setting.
SETTINGS_NOT_SAVED_MESSAGE = "The settings could not be saved. No setting was changed."


def _pattern(template):
"""Return a regular expression for ``template``, in which each ``{}`` stands for any text."""
return ".*".join(re.escape(part) for part in template.split("{}"))


def _any_of(patterns):
"""Return a regular expression, as one group, matching any one of ``patterns``."""
return "(?:{})".format("|".join(patterns))


def _in_order_separated_by_commas(slots):
"""Return a regular expression for one or more of ``slots``, in the given order, separated by commas."""
return _any_of(
first + "".join(f"(?:,{later})?" for later in slots[index + 1:])
for index, first in enumerate(slots)
)


# The problems the teams rules report about one team-set, joined with commas
# in this order. Each entry lists the problems that can take its place.
_TEAMSET_PROBLEMS = (
("type {} is invalid",),
("max_team_size must be greater than zero", "max_team_size cannot be greater than 500"),
("id attribute must not be empty",),
("name attribute must not be empty",),
("description attribute must not be empty",),
("extra keys: {}",),
)

_MISSING_ESCALATION_EMAIL = "Provider '{}' requires an exam escalation contact."

# The messages the course's rules in ``CourseMetadata`` write about a refused
# setting, by setting name. They are returned to the caller as written. A
# message missing here, including a rule's reworded or new message, is
# reported as ``INVALID_SETTING_MESSAGE``.
_RULE_MESSAGES = {
"teams_configuration": (
_pattern("max_team_size must be greater than zero"),
_pattern("max_team_size cannot be greater than 500"),
_pattern("duplicate ids: {}"),
_in_order_separated_by_commas([_any_of(map(_pattern, problems)) for problems in _TEAMSET_PROBLEMS]),
),
"proctoring_provider": (
_pattern("The proctoring provider cannot be modified after a course has started. Contact {} for assistance"),
_pattern("The proctoring provider configured for this course, '{}', is not valid."),
_pattern("The selected proctoring provider, {}, is not a valid provider. Please select from one of {}."),
_pattern(_MISSING_ESCALATION_EMAIL),
),
"proctoring_escalation_email": (
_pattern(_MISSING_ESCALATION_EMAIL),
),
}
_RULE_MESSAGE_PATTERNS = {name: re.compile(_any_of(patterns), re.DOTALL) for name, patterns in _RULE_MESSAGES.items()}


def is_rule_message(name, message):
"""Return whether ``message`` is one the course's rules write about the setting ``name``."""
pattern = _RULE_MESSAGE_PATTERNS.get(name)
return pattern is not None and pattern.fullmatch(message) is not None


def _course_block(course_key):
"""Return the course block of ``course_key``, or raise ``NotFound`` when the modulestore has none."""
course_block = modulestore().get_course(course_key)
if course_block is None:
raise NotFound(COURSE_NOT_FOUND_MESSAGE)
return course_block


def settings_authors_do_not_edit(course_key):
"""Return the names of the course's settings that are not edited as advanced settings."""
return frozenset(CourseMetadata.get_exclude_list_of_fields(course_key))


def get_advanced_settings(course_key, full=False):
"""
Return the advanced settings of the course, keyed by setting name.

By default only the settings course authors edit in Studio are returned;
with ``full`` every setting of the course is.
"""
course_block = _course_block(course_key)
if full:
return CourseMetadata.fetch_all(course_block)
return CourseMetadata.fetch(course_block)


def update_advanced_settings(course_key, changes, user):
"""
Apply ``changes`` (``{name: {"value": value}}``) to the course as ``user``.

Every value is validated before any is stored; when one is refused,
nothing is stored and ``ValidationError`` maps each refused setting to its
messages (see ``_errors_by_setting``).
Returns the settings course authors edit in Studio, as stored.
"""
course_block = _course_block(course_key)
try:
return update_course_advanced_settings(course_block, changes, user)
except ValidationError as error:
raise _errors_by_setting(course_key, error) from error


def _errors_by_setting(course_key, error):
"""
Return a ``ValidationError`` mapping each refused setting to its messages.

The settings validator reports one entry per problem, carrying the
setting's name and an explanation. An explanation the course's rules write
themselves (a team size limit, a proctoring rule) is returned as written.
Any other explanation, such as the text of an exception raised while
converting the value, is logged with the course and setting and returned
as ``INVALID_SETTING_MESSAGE``. A failure not tied to a setting is logged
and reported with ``SETTINGS_NOT_SAVED_MESSAGE``.
"""
detail = error.detail if isinstance(error.detail, list) else [error.detail]
by_setting = {}
unattributed = []
for entry in detail:
name = entry.get("key") if isinstance(entry, dict) else None
if not name:
unattributed.append(entry)
continue
name, explanation = str(name), str(entry.get("message", ""))
if is_rule_message(name, explanation):
message = explanation
else:
log.warning("Advanced setting %s of course %s was refused: %s", name, course_key, explanation)
message = INVALID_SETTING_MESSAGE
messages = by_setting.setdefault(name, [])
if message not in messages:
messages.append(message)
if unattributed:
log.warning("Advanced settings of course %s were not saved: %s", course_key, unattributed)
by_setting.setdefault(api_settings.NON_FIELD_ERRORS_KEY, []).append(SETTINGS_NOT_SAVED_MESSAGE)
return ValidationError(by_setting)
20 changes: 20 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v1/authoring_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
YoutubeTranscriptChecksViewSet,
YoutubeTranscriptImportsViewSet,
)
from cms.djangoapps.contentstore.rest_api.v1.views.advanced_settings import CourseAdvancedSettingsViewSet
from cms.djangoapps.contentstore.rest_api.v1.views.course_optimizer import (
CourseLinkCheckViewSet,
CoursePreviousRunLinkUpdateViewSet,
)
from cms.djangoapps.contentstore.rest_api.v1.views.video_uploads import CourseVideoUploadsViewSet

app_name = "authoring_v1"
Expand Down Expand Up @@ -50,4 +55,19 @@
),
name="xblock_detail",
),
path(
"courses/<course_key:course_key>/advanced_settings/",
CourseAdvancedSettingsViewSet.as_view({"get": "retrieve", "patch": "partial_update"}),
name="course_advanced_settings",
),
path(
"courses/<course_key:course_key>/link_check/",
CourseLinkCheckViewSet.as_view({"get": "retrieve", "post": "create"}),
name="course_link_check",
),
path(
"courses/<course_key:course_key>/previous_run_link_update/",
CoursePreviousRunLinkUpdateViewSet.as_view({"get": "retrieve", "post": "create"}),
name="course_previous_run_link_update",
),
]
139 changes: 139 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v1/course_optimizer_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""Runs of the course optimizer: link checks and updates of links to a previous course run."""

import json

from rest_framework.exceptions import NotFound
from user_tasks.models import UserTaskArtifact, UserTaskStatus

from cms.djangoapps.contentstore.core.course_optimizer_provider import (
_latest_course_link_update_task_status,
_latest_task_status,
generate_broken_links_descriptor,
get_course_link_update_data,
sort_course_sections,
)
from cms.djangoapps.contentstore.tasks import check_broken_links, update_course_rerun_links
from cms.djangoapps.contentstore.toggles import enable_course_optimizer_check_prev_run_links

# The state of a resource no run of which the caller may see.
UNINITIATED = "Uninitiated"
# The stages the link update task reports while it runs.
SCANNING = "Scanning"
UPDATING = "Updating"

# Every state a link check or a link update can report. Scanning and Updating
# are reported by link updates only.
RUN_STATES = [
UNINITIATED,
UserTaskStatus.PENDING,
UserTaskStatus.IN_PROGRESS,
SCANNING,
UPDATING,
UserTaskStatus.SUCCEEDED,
UserTaskStatus.FAILED,
UserTaskStatus.CANCELED,
UserTaskStatus.RETRYING,
]

ALL_LINKS = "all"
SINGLE_LINKS = "single"

# Reported for a link check that failed or was canceled with an error recorded.
# The recorded text can be an exception's, so it is not returned.
LINK_CHECK_ERROR_MESSAGE = "The link check could not be completed."
# Reported for each link an update run could not change, in place of the
# recorded reason, which can be an exception's text.
LINK_NOT_UPDATED_MESSAGE = "The link could not be updated."
PREVIOUS_RUN_LINK_UPDATES_DISABLED_MESSAGE = "Updating links to a previous course run is not enabled for this course."

_FAILED_STATES = (UserTaskStatus.FAILED, UserTaskStatus.CANCELED)


def start_link_check(course_key, user, language):
"""Queue a check of the links in the course, as ``user``; return the state of the queued run."""
check_broken_links.delay(user.id, str(course_key), language)
return {"status": UserTaskStatus.PENDING}


def link_check_status(request, course_key, full=False):
"""
Return the latest link check of the course that the requester may see.

Callers see their own runs; superusers see everyone's. With ``full``, the
report of a run that succeeded is added under ``output`` (``None``
otherwise).
"""
run = _latest_task_status(request, str(course_key))
if run is None:
status = {"status": UNINITIATED, "created_at": None, "error": None}
else:
failed = run.state in _FAILED_STATES and (
UserTaskArtifact.objects.filter(status=run, name="Error").exclude(text="").exists()
)
status = {
"status": run.state,
"created_at": run.created,
"error": LINK_CHECK_ERROR_MESSAGE if failed else None,
}
if full:
succeeded = run is not None and run.state == UserTaskStatus.SUCCEEDED
status["output"] = _link_check_report(request.user, course_key, run) if succeeded else None
return status


def _link_check_report(user, course_key, run):
"""The flagged links a run found, sections in course order."""
artifact = UserTaskArtifact.objects.get(status=run, name="BrokenLinks")
with artifact.file as file:
links = json.loads(file.read())
report = generate_broken_links_descriptor(links, user, course_key)
return sort_course_sections(course_key, {"LinkCheckOutput": report})["LinkCheckOutput"]


def ensure_previous_run_link_updates_enabled(course_key):
"""Raise ``NotFound`` unless links to a previous run may be updated in the course."""
if not enable_course_optimizer_check_prev_run_links(course_key):
raise NotFound(PREVIOUS_RUN_LINK_UPDATES_DISABLED_MESSAGE)


def start_previous_run_link_update(course_key, user, action, links, language):
"""
Queue an update of the course's links to its previous run, as ``user``.

``action`` is ``all`` (every such link the course has) or ``single`` (the
``links`` given). Returns the state of the queued run. Callers check
``ensure_previous_run_link_updates_enabled`` first.
"""
update_course_rerun_links.delay(user.id, str(course_key), action, [dict(link) for link in links], language)
return {"status": UserTaskStatus.PENDING}


def previous_run_link_update_status(request, course_key, full=False):
"""
Return the latest update of links to the previous run that the requester may see.

Visibility is as for link checks. With ``full``, the outcome of each link
of a run that succeeded is added under ``results`` (empty otherwise).
Callers check ``ensure_previous_run_link_updates_enabled`` first.
"""
if not full:
run = _latest_course_link_update_task_status(request, str(course_key))
return {"status": UNINITIATED if run is None else run.state}
data = get_course_link_update_data(request, str(course_key))
return {
"status": UNINITIATED if data["status"] == "uninitiated" else data["status"],
"results": [_link_update_result(result) for result in data["results"]],
}


def _link_update_result(result):
"""One link's outcome, with a fixed message in place of the recorded failure reason."""
success = bool(result["success"])
return {
"id": result["id"],
"type": result["type"],
"original_url": result.get("original_url"),
"new_url": result["new_url"],
"success": success,
"error_message": None if success else LINK_NOT_UPDATED_MESSAGE,
}
Loading
Loading