Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 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
966d4d4
feat: add a shared paginator that documents all seven envelope keys
Oct 25, 2026
534edad
feat: add the pages and resources management permission class
Oct 25, 2026
feb016f
feat: serve course custom pages and tabs from authoring v1
Oct 25, 2026
c7ce524
docs: mark the v0 tabs endpoints deprecated in favour of authoring v1
Oct 25, 2026
370e3ad
docs: describe what an inactive session and a superuser are allowed
Oct 26, 2026
1c681eb
docs: remove the deprecation notes from the v0 tabs docstrings
Oct 31, 2026
9c8975d
fix: refuse a null page item and a tab change that names no member
Oct 31, 2026
5f764d0
chore: import the authz constants from openedx_authz.authz
Nov 18, 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
56 changes: 56 additions & 0 deletions cms/djangoapps/contentstore/rest_api/pagination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Pagination shared by the contentstore REST API views."""

from edx_rest_framework_extensions.paginators import DefaultPagination

ENVELOPE_KEYS = ("count", "num_pages", "current_page", "start", "next", "previous", "results")


class DocumentedDefaultPagination(DefaultPagination):
"""
The standard page envelope, with a response schema describing all seven of its keys.

``DefaultPagination`` returns ``count``, ``num_pages``, ``current_page``,
``start``, ``next``, ``previous`` and ``results``, but inherits a response
schema that documents only four of them, so generated clients would drop
``num_pages``, ``current_page`` and ``start``. Pages, page sizes and the
body are exactly ``DefaultPagination``'s; only the published schema
differs. Every member carries an example, so the schema generator can wrap
a view's example item in a whole page. Once ``DefaultPagination``
documents all seven keys, use it directly instead.
"""

def get_paginated_response_schema(self, schema):
"""Describe a page whose ``results`` are items described by ``schema``."""
return {
"type": "object",
"required": list(ENVELOPE_KEYS),
"properties": {
"count": {"type": "integer", "description": "Total number of items.", "example": 25},
"num_pages": {"type": "integer", "description": "Total number of pages.", "example": 3},
"current_page": {
"type": "integer",
"description": "Number of this page, starting at 1.",
"example": 2,
},
"start": {
"type": "integer",
"description": "Zero-based index of the first item on this page.",
"example": 10,
},
"next": {
"type": "string",
"format": "uri",
"nullable": True,
"description": "Address of the next page, or null on the last page.",
"example": "https://example.com/items/?page=3",
},
"previous": {
"type": "string",
"format": "uri",
"nullable": True,
"description": "Address of the previous page, or null on the first page.",
"example": "https://example.com/items/?page=1",
},
"results": schema,
},
}
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)
27 changes: 27 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,12 @@
YoutubeTranscriptChecksViewSet,
YoutubeTranscriptImportsViewSet,
)
from cms.djangoapps.contentstore.rest_api.v1.views.advanced_settings import CourseAdvancedSettingsViewSet
from cms.djangoapps.contentstore.rest_api.v1.views.custom_pages import (
CourseCustomPageOrderViewSet,
CourseCustomPagesViewSet,
CourseTabsViewSet,
)
from cms.djangoapps.contentstore.rest_api.v1.views.video_uploads import CourseVideoUploadsViewSet

app_name = "authoring_v1"
Expand Down Expand Up @@ -50,4 +56,25 @@
),
name="xblock_detail",
),
path(
"courses/<course_key:course_key>/advanced_settings/",
CourseAdvancedSettingsViewSet.as_view({"get": "retrieve", "patch": "partial_update"}),
name="course_advanced_settings",
),
# The course is named by the required course_key query parameter.
path(
"custom_pages/",
CourseCustomPagesViewSet.as_view({"get": "list"}),
name="custom_page_list",
),
path(
"courses/<course_key:course_key>/custom_page_order/",
CourseCustomPageOrderViewSet.as_view({"put": "update"}),
name="course_custom_page_order",
),
path(
"courses/<course_key:course_key>/tabs/<str:tab_id>/",
CourseTabsViewSet.as_view({"patch": "partial_update"}),
name="course_tab_detail",
),
]
108 changes: 108 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v1/custom_pages_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""Reads and changes of a course's custom pages and tabs."""

import logging

from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.settings import api_settings

from cms.djangoapps.contentstore.views.permissions import COURSE_NOT_FOUND_MESSAGE
from cms.djangoapps.contentstore.views.tabs import edit_tab_handler, get_course_tabs, reorder_tabs_handler
from xmodule.modulestore.django import modulestore
from xmodule.tabs import CourseTabList, StaticTab

log = logging.getLogger(__name__)

# Reported under custom_pages when an item names no custom page of the course.
UNKNOWN_CUSTOM_PAGE_MESSAGE = "Each item must be the usage key of a custom page of this course."
# Reported under custom_pages when the same custom page is named twice.
REPEATED_CUSTOM_PAGE_MESSAGE = "Each custom page may be listed only once."
# Reported when the course's tabs could not be saved in the new order.
ORDER_NOT_SAVED_MESSAGE = "The custom pages could not be reordered. Their order is unchanged."
# Reported when the course has no tab with the requested identifier.
TAB_NOT_FOUND_MESSAGE = "The requested tab does not exist."
# Reported under is_hidden when the tab may not be hidden or shown.
TAB_NOT_HIDEABLE_MESSAGE = "This tab cannot be hidden or shown."


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 _custom_page_slug(course_key, usage_key):
"""
Return the ``url_slug`` a custom page of ``course_key`` named by ``usage_key`` would have, or None.

The key may carry a branch or version of the course. A key of another
course or library, or of a block that is not a custom page, gives None.
"""
if not isinstance(usage_key, BlockUsageLocator) or usage_key.block_type != "static_tab":
return None
context = usage_key.course_key
if not isinstance(context, CourseLocator):
return None
if (context.org, context.course, context.run) != (course_key.org, course_key.course, course_key.run):
return None
return usage_key.block_id


def list_custom_pages(course_key, user):
"""
Return the course's custom pages in the order of the course's tabs.

Each page carries its usage key as ``locator``. Built-in tabs are never
returned, whether or not hidden.
"""
course_block = _course_block(course_key)
return [tab for tab in get_course_tabs(course_block, user) if isinstance(tab, StaticTab)]


def reorder_custom_pages(course_key, usage_keys, user):
"""
Put the course's custom pages in the order of ``usage_keys``, as ``user``.

Custom pages not named follow the named ones in their current order. As
when Studio reorders pages, the course's tabs are then sorted by kind, so
built-in tabs take their usual places around the custom pages. Raises
``ValidationError`` when a usage key names no custom page of the course or
names one twice, and when the reordered tabs could not be saved; nothing
is stored then.
"""
course_block = _course_block(course_key)
pages = {tab.url_slug: tab for tab in course_block.tabs if isinstance(tab, StaticTab)}
named = []
for usage_key in usage_keys:
page = pages.get(_custom_page_slug(course_key, usage_key))
if page is None:
raise ValidationError({"custom_pages": [UNKNOWN_CUSTOM_PAGE_MESSAGE]})
if any(page is other for other in named):
raise ValidationError({"custom_pages": [REPEATED_CUSTOM_PAGE_MESSAGE]})
named.append(page)
rest = [page for page in pages.values() if all(page is not other for other in named)]
try:
reorder_tabs_handler(course_block, [{"tab_id": page.tab_id} for page in named + rest], user)
except ValidationError as error:
log.warning("The custom pages of course %s were not reordered: %s", course_key, error.detail)
raise ValidationError({api_settings.NON_FIELD_ERRORS_KEY: [ORDER_NOT_SAVED_MESSAGE]}) from error


def update_tab(course_key, tab_id, changes, user):
"""
Apply ``changes`` (``{"is_hidden": bool}``) to the course tab ``tab_id``, as ``user``.

Returns the tab as stored. Raises ``NotFound`` when the course has no such
tab, and ``ValidationError`` on ``is_hidden`` when the tab may not be
hidden or shown.
"""
course_block = _course_block(course_key)
tab = CourseTabList.get_tab_by_id(course_block.tabs, tab_id)
if tab is None:
raise NotFound(TAB_NOT_FOUND_MESSAGE)
if not tab.is_hideable:
raise ValidationError({"is_hidden": [TAB_NOT_HIDEABLE_MESSAGE]})
edit_tab_handler(course_block, {"tab_id_locator": {"tab_id": tab_id}, "is_hidden": changes["is_hidden"]}, user)
return tab
Loading
Loading