Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 10 additions & 1 deletion cms/djangoapps/contentstore/rest_api/v2/authoring_urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
"""Contentstore API v2 authoring URLs."""

from django.urls import path
from django.urls import path, register_converter
from edx_rest_framework_extensions.url_converters import UsageKeyConverter

from cms.djangoapps.contentstore.rest_api.v2.views.container_children import CourseContainerChildrenViewSet
from cms.djangoapps.contentstore.rest_api.v2.views.textbooks import CourseTextbooksViewSet
from cms.djangoapps.contentstore.rest_api.v2.views.video_settings import CourseVideoSettingsViewSet

register_converter(UsageKeyConverter, "usage_key")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be needed: cms/urls.py already calls register_url_converters(), which registers usage_key along with course_key. #39274 uses <usage_key:usage_key> in this same file without registering it. Dropping these lines (and the two imports) also avoids a conflict with #39274's version of authoring_urls.py.


app_name = "authoring_v2"

urlpatterns = [
Expand All @@ -18,4 +22,9 @@
CourseVideoSettingsViewSet.as_view({"get": "retrieve"}),
name="course_video_settings",
),
path(
"containers/<usage_key:usage_key>/children/",
CourseContainerChildrenViewSet.as_view({"get": "list"}),
name="container_child_list",
),
]
130 changes: 130 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v2/container_children_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Service layer for the v2 container children endpoint."""

import logging

from rest_framework.exceptions import NotFound

from cms.djangoapps.contentstore.helpers import xblock_studio_url, xblock_type_display_name
from cms.djangoapps.contentstore.utils import (
get_user_partition_info,
get_visibility_partition_info,
get_xblock_render_error,
get_xblock_validation_messages,
)
from cms.lib.xblock.upstream_sync import UpstreamLink
from openedx.core.djangoapps.content_tagging.toggles import is_tagging_feature_disabled
from xmodule.modulestore.django import modulestore # pylint: disable=wrong-import-order
from xmodule.modulestore.exceptions import ItemNotFoundError # pylint: disable=wrong-import-order

log = logging.getLogger(__name__)

CONTAINER_NOT_FOUND_MESSAGE = "No container in this course has this key."
RENDER_ERROR_MESSAGE = "This block could not be rendered. The cause is in the server log."


def _load_container(store, usage_key):
"""
Return the container ``usage_key`` names, with its children loaded, or raise ``NotFound``.

A container is a block that can hold children and is not the course
itself. The course's own children are served by the course outline.
"""
try:
block = store.get_item(usage_key, depth=1)
except ItemNotFoundError as error:
log.info("Children of %s requested, which does not exist: %s", usage_key, error)
raise NotFound(CONTAINER_NOT_FOUND_MESSAGE) from error
if not block.has_children or block.category == "course":
log.info("Children of %s requested, which is a %s.", usage_key, block.category)
raise NotFound(CONTAINER_NOT_FOUND_MESSAGE)
return block


def _summary(child):
"""The short description of a child."""
return {
"id": str(child.location),
"category": child.category,
"display_name": child.display_name_with_default,
"display_type": xblock_type_display_name(child),
"has_children": child.has_children,
}


def _actions(container, child, can_manage_tags):
"""What the Studio unit page lets an author do with ``child``."""
is_course = child.scope_ids.usage_id.context_key.is_course
# A child that holds children and has no page of its own is edited inline,
# where copying, moving and the other whole-block actions do not apply.
show_inline = child.has_children and not xblock_studio_url(child, parent_xblock=container)
show_other_action = not show_inline and is_course
return {
"can_copy": show_other_action,
"can_duplicate": show_other_action,
"can_move": show_other_action,
"can_manage_access": show_other_action,
"can_delete": is_course,
"can_manage_tags": can_manage_tags,
}


def _render_error(request, child):
"""
The message to show for a child that fails to render, or an empty string.

The cause comes from the block's own code and may expose internals, so it
is logged with the child's key rather than returned.
"""
cause = get_xblock_render_error(request, child)
if not cause:
return ""
log.warning("Rendering %s for the children list failed: %s", child.location, cause)
return RENDER_ERROR_MESSAGE


def _detail(request, container, child, course, can_manage_tags):
"""Everything the Studio unit page shows about ``child``."""
upstream_link = UpstreamLink.try_get_for_block(child, log_error=False)
return {
"name": child.display_name_with_default,
"block_id": str(child.location),
"block_type": child.location.block_type,
"user_partition_info": get_visibility_partition_info(child, course=course),
"user_partitions": get_user_partition_info(child, course=course),
# A block with no upstream is by far the commonest case, so it is
# null rather than a record of empty fields.
"upstream_link": upstream_link.to_json(include_child_info=True) if upstream_link.upstream_ref else None,
"actions": _actions(container, child, can_manage_tags),
"validation_messages": get_xblock_validation_messages(child),
"render_error": _render_error(request, child),
}


def list_container_children(request, usage_key, full, paginate):
"""
Return the children of the container ``usage_key`` names, in the order the container stores them.

``paginate(children, build_page)`` receives every loadable child and a
function that describes one page of them; it returns the response. The
children that make up the answer are the ones that can be loaded, so a
dangling reference in the container is left out, and the fields that are
costly to work out (partitions, upstream link, validation, rendering) are
worked out for the requested page only. ``full`` selects them.

Raises ``NotFound`` when no block has the key or the block is not a
container. Nothing is written.
"""
store = modulestore()
with store.bulk_operations(usage_key.course_key):
container = _load_container(store, usage_key)
children = container.get_children()
if not full:
return paginate(children, lambda page: [_summary(child) for child in page])
# Loaded once and shared by every child, as the partitions are
# defined on the course.
course = store.get_course(usage_key.course_key)
can_manage_tags = not is_tagging_feature_disabled()
return paginate(
children,
lambda page: [_detail(request, container, child, course, can_manage_tags) for child in page],
)
43 changes: 43 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v2/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Permissions for the v2 authoring API."""

from opaque_keys.edx.locator import CourseLocator
from rest_framework.exceptions import NotFound
from rest_framework.permissions import BasePermission

from openedx.core.djangoapps.authz.constants import LegacyAuthoringPermission
from openedx.core.djangoapps.authz.decorators import user_has_course_permission
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview

try:
from openedx_authz.constants.permissions import COURSES_VIEW_COURSE
except ImportError:
COURSES_VIEW_COURSE = None

COURSE_NOT_FOUND_MESSAGE = "The requested course does not exist."


class CanViewCourse(BasePermission):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description says this branch sits on #39274 (and #39229) and uses their CanViewCourse, but the branch is a single commit on master and contains neither. This file is a copy of #39229's CanViewCourse in views/permissions.py, with a second COURSE_NOT_FOUND_MESSAGE; the view constants are copied locally too. Once #39229 merges there will be two CanViewCourse classes with the same name, and they can drift apart.

The description is also out of step with the diff. It lists edits to test_containers.py, which isn't in this PR, and the gate report was run against origin/pr/39274, so it doesn't describe this branch.

Could you either:

While here: the try/except ImportError around COURSES_VIEW_COURSE can go. The pinned openedx-authz (1.34.0) has it, and lms/djangoapps/courseware/access.py imports it directly.

"""
Allow callers who may view the course in Studio.

Reads the parsed ``course_key`` or ``usage_key`` URL argument.
Must follow ``IsAuthenticated`` in ``permission_classes``.
"""

def has_permission(self, request, view):
course_key = view.kwargs.get("course_key")
if course_key is None:
usage_key = view.kwargs.get("usage_key")
if usage_key is None:
return False
course_key = usage_key.context_key
if not isinstance(course_key, CourseLocator):
raise NotFound(COURSE_NOT_FOUND_MESSAGE)
if course_key.org is None or not CourseOverview.course_exists(course_key):
raise NotFound(COURSE_NOT_FOUND_MESSAGE)
return user_has_course_permission(
request.user,
COURSES_VIEW_COURSE.identifier if COURSES_VIEW_COURSE else "courses.view_course",
course_key,
LegacyAuthoringPermission.READ,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""Serializers for the children of a course container."""

from rest_framework import serializers

CONTAINER_MINIMAL_VIEW = "minimal"
CONTAINER_FULL_VIEW = "full"


class CourseContainerChildSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""A block placed directly in a container, as listed by default."""

id = serializers.CharField(help_text="Usage key of the block.")
category = serializers.CharField(
help_text="Block type, such as html, problem, video, vertical (unit) or split_test.",
)
display_name = serializers.CharField(help_text="Name of the block shown to authors.")
display_type = serializers.CharField(
allow_null=True,
help_text=(
"Name of the block's type shown to authors, such as Unit, Problem or Text. Null for a block type "
"that declares no display name."
),
)
has_children = serializers.BooleanField(
help_text="Whether the block can hold children, as a unit or a split test does.",
)

class Meta:
ref_name = "CourseContainerChild"


class CourseContainerChildMessageSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""A problem the block reports with its own settings."""

text = serializers.CharField(help_text="What is wrong, written for the author.")
type = serializers.CharField(help_text="Severity: warning or error.")

class Meta:
ref_name = "CourseContainerChildMessage"


class CourseContainerChildActionsSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""What an author can do with a block placed in a container."""

can_copy = serializers.BooleanField(help_text="Whether the block can be copied to the clipboard.")
can_duplicate = serializers.BooleanField(help_text="Whether the block can be duplicated in place.")
can_move = serializers.BooleanField(help_text="Whether the block can be moved to another container.")
can_manage_access = serializers.BooleanField(
help_text="Whether the block's access restrictions can be edited.",
)
can_delete = serializers.BooleanField(help_text="Whether the block can be deleted.")
can_manage_tags = serializers.BooleanField(
help_text="Whether the block can be tagged. False when tagging is turned off.",
)

class Meta:
ref_name = "CourseContainerChildActions"


class CourseContainerChildUpstreamChildSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""A block inside a linked container that can be synced from its own upstream block."""

id = serializers.CharField(help_text="Usage key of the block in the course.")
name = serializers.CharField(allow_null=True, help_text="Name of the block. Null when it has none set.")
upstream = serializers.CharField(allow_null=True, help_text="Key of the library block the block is linked to.")

class Meta:
ref_name = "CourseContainerChildUpstreamChild"


class CourseContainerChildUpstreamLinkSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""A block's link to the library block it was created from, and whether the library has moved on."""

upstream_ref = serializers.CharField(help_text="Key of the library block or container the block is linked to.")
version_synced = serializers.IntegerField(
allow_null=True,
help_text="Version of the library content the block holds. Null when the link records none.",
)
version_available = serializers.IntegerField(
allow_null=True,
help_text="Latest published version of the library content. Null when it cannot be determined.",
)
version_declined = serializers.IntegerField(
allow_null=True,
help_text="Version an author chose not to sync, if any.",
)
error_message = serializers.CharField(
allow_null=True,
help_text="Why the link cannot be followed, such as a library that no longer exists. Null for a working link.",
)
ready_to_sync = serializers.BooleanField(
help_text="Whether a newer version is available and can be synced into the block.",
)
downstream_customized = serializers.ListField(
child=serializers.CharField(),
help_text="Names of the fields the author has changed in the course, which a sync would overwrite.",
)
top_level_parent_key = serializers.CharField(
allow_null=True,
help_text=(
"Usage key of the top-level linked container this block belongs to, when it was added with one. "
"Null otherwise."
),
)
ready_to_sync_children = CourseContainerChildUpstreamChildSerializer(
many=True,
required=False,
help_text=(
"The blocks inside a linked container that have a newer version available. Present only when the "
"block is linked to a library container."
),
)

class Meta:
ref_name = "CourseContainerChildUpstreamLink"


class CourseContainerChildFullSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""A block placed directly in a container, with everything the Studio unit page shows for it."""

name = serializers.CharField(help_text="Name of the block shown to authors.")
block_id = serializers.CharField(help_text="Usage key of the block.")
block_type = serializers.CharField(help_text="Block type, such as html, problem, video or split_test.")
user_partition_info = serializers.DictField(
help_text=(
"The groups the block's visibility can be restricted to: selectable_partitions, "
"selected_partition_index (-1 when unrestricted) and selected_groups_label."
),
)
user_partitions = serializers.ListField(
child=serializers.DictField(),
help_text="The course's content groups and enrollment tracks, and which of their groups the block uses.",
)
upstream_link = CourseContainerChildUpstreamLinkSerializer(
allow_null=True,
help_text="The block's link to a library block. Null when the block is not linked to one.",
)
actions = CourseContainerChildActionsSerializer(help_text="What the requesting user's Studio lets them do.")
validation_messages = CourseContainerChildMessageSerializer(
many=True,
help_text="Problems the block reports with its own settings. Empty when there are none.",
)
render_error = serializers.CharField(
allow_blank=True,
help_text=(
"A fixed message when the block fails to render in Studio, empty when it renders. The cause is "
"recorded in the server log, not returned."
),
)

class Meta:
ref_name = "CourseContainerChildFull"


class CourseContainerChildQuerySerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Query parameters of a container children read. A parameter sent with an empty value counts as omitted."""

view = serializers.ChoiceField(
choices=[CONTAINER_MINIMAL_VIEW, CONTAINER_FULL_VIEW],
default=CONTAINER_MINIMAL_VIEW,
error_messages={"invalid_choice": "Must be minimal or full."},
help_text=(
"minimal (the default) describes each child briefly. full adds what the Studio unit page shows "
"for each: visibility groups, library link, available actions, validation messages and rendering "
"errors."
),
)

class Meta:
ref_name = "CourseContainerChildQuery"
Loading
Loading