diff --git a/lms/djangoapps/courseware/block_render.py b/lms/djangoapps/courseware/block_render.py index 32699bbc9276..35b24642eac8 100644 --- a/lms/djangoapps/courseware/block_render.py +++ b/lms/djangoapps/courseware/block_render.py @@ -62,6 +62,7 @@ ) from lms.djangoapps.courseware.model_data import DjangoKeyValueStore, FieldDataCache from lms.djangoapps.courseware.services import UserStateService +from lms.djangoapps.edxnotes.wrappers import wrap_with_edxnotes from lms.djangoapps.grades.api import GradesUtilService from lms.djangoapps.lms_xblock.field_data import LmsFieldData from lms.djangoapps.lms_xblock.runtime import UserTagsService, lms_applicable_aside_types, lms_wrappers_aside @@ -560,6 +561,11 @@ def inner_get_block(block: XBlock) -> XBlock | None: if settings.LICENSING: block_wrappers.append(partial(wrap_with_license, mako_service=mako_service)) + # TEMPORARY HACK to keep edXNotes working. See the docstring of wrap_with_edxnotes. + # This goes before wrap_xblock so that the edXNotes wrapper ends up inside of the XBlock's div. + if settings.ENABLE_EDXNOTES: + block_wrappers.append(partial(wrap_with_edxnotes, user, course)) + # Wrap the output display in a single div to allow for the XBlock # javascript to be bound correctly if wrap_xblock_display is True: diff --git a/lms/djangoapps/edxnotes/decorators.py b/lms/djangoapps/edxnotes/decorators.py deleted file mode 100644 index 39d5c0b076d4..000000000000 --- a/lms/djangoapps/edxnotes/decorators.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Decorators related to edXNotes. -""" - - -import json - -from django.conf import settings -from xblock.exceptions import NoSuchServiceError - -from common.djangoapps.edxmako.shortcuts import render_to_string - - -def edxnotes(cls): - """ - Decorator that makes components annotatable. - """ - original_get_html = cls.get_html - - def get_html(self, *args, **kwargs): - """ - Returns raw html for the component. - """ - # Import is placed here to avoid model import at project startup. - from .helpers import generate_uid, get_edxnotes_id_token, get_public_endpoint, get_token_url, is_feature_enabled - - if not settings.ENABLE_EDXNOTES: - return original_get_html(self, *args, **kwargs) - - runtime = getattr(self, 'block', self).runtime - if not hasattr(runtime, 'modulestore'): - return original_get_html(self, *args, **kwargs) - - is_studio = getattr(self.runtime, "is_author_mode", False) - course = getattr(self, 'block', self).runtime.modulestore.get_course(self.scope_ids.usage_id.context_key) - - # Must be disabled when: - # - in Studio - # - Harvard Annotation Tool is enabled for the course - # - the feature flag or `edxnotes` setting of the course is set to False - # - the user is not authenticated - try: - user = self.runtime.service(self, 'user').get_user_by_anonymous_id() - except NoSuchServiceError: - user = None - - if is_studio or not is_feature_enabled(course, user): - return original_get_html(self, *args, **kwargs) - else: - return render_to_string("edxnotes_wrapper.html", { - "content": original_get_html(self, *args, **kwargs), - "uid": generate_uid(), - "edxnotes_visibility": json.dumps( - getattr(self, 'edxnotes_visibility', course.edxnotes_visibility) - ), - "params": { - # Use camelCase to name keys. - "usageId": self.scope_ids.usage_id, - "courseId": course.id, - "token": get_edxnotes_id_token(user), - "tokenUrl": get_token_url(course.id), - "endpoint": get_public_endpoint(), - "debug": settings.DEBUG, - "eventStringLimit": settings.TRACK_MAX_EVENT / 6, - }, - }) - - cls.get_html = get_html - return cls diff --git a/lms/djangoapps/edxnotes/tests.py b/lms/djangoapps/edxnotes/tests.py index 8c0faf5f3752..14ec192d1f0f 100644 --- a/lms/djangoapps/edxnotes/tests.py +++ b/lms/djangoapps/edxnotes/tests.py @@ -19,6 +19,7 @@ from django.test.utils import override_settings from django.urls import reverse from oauth2_provider.models import Application +from web_fragments.fragment import Fragment from common.djangoapps.edxmako.shortcuts import render_to_string from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, SuperuserFactory, UserFactory @@ -38,12 +39,12 @@ CourseFactory, ) from xmodule.tabs import CourseTab # pylint: disable=wrong-import-order -from xmodule.tests.helpers import StubUserService # pylint: disable=wrong-import-order +from xmodule.x_module import PUBLIC_VIEW, STUDENT_VIEW # pylint: disable=wrong-import-order from . import helpers -from .decorators import edxnotes from .exceptions import EdxNotesParseError, EdxNotesServiceUnavailable from .plugins import EdxNotesTab +from .wrappers import wrap_with_edxnotes NOTES_API_EMPTY_RESPONSE = { "total": 0, @@ -74,70 +75,57 @@ def enable_edxnotes_for_the_course(course, user_id): modulestore().update_item(course, user_id) -@edxnotes -class TestProblem: - """ - Test class (fake problem) decorated by edxnotes decorator. - - The purpose of this class is to imitate any problem. - """ - def __init__(self, course, user=None): - self.scope_ids = MagicMock(usage_id=course.id.make_usage_key('test_problem', 'test_usage_id')) - user = user or UserFactory() - user_service = StubUserService(user) - self.runtime = MagicMock(service=lambda _a, _b: user_service, is_author_mode=False) - self.block = MagicMock() - self.block.runtime.modulestore.get_course.return_value = course - - def get_html(self): - """ - Imitate get_html in block. - """ - return "original_get_html" - - +@ddt.ddt @skipUnless(settings.ENABLE_EDXNOTES, "EdxNotes feature needs to be enabled.") -class EdxNotesDecoratorTest(ModuleStoreTestCase): +class EdxNotesWrapperTest(ModuleStoreTestCase): """ - Tests for edxnotes decorator. + Tests for the edxnotes XBlock wrapper. """ + ORIGINAL_CONTENT = "original_content" + def setUp(self): super().setUp() ApplicationFactory(name="edx-notes") self.course = CourseFactory(edxnotes=True, default_store=ModuleStoreEnum.Type.split) - self.user = UserFactory() - self.client.login(username=self.user.username, password=UserFactory._DEFAULT_PASSWORD) # pylint: disable=protected-access - self.problem = TestProblem(self.course, self.user) + self.user = CourseEnrollmentFactory(course_id=self.course.id).user + enable_edxnotes_for_the_course(self.course, self.user.id) + self.html_block = BlockFactory.create(parent=self.course, category="html") + self.problem_block = BlockFactory.create(parent=self.course, category="problem") + def wrap(self, block=None, user=None, course=None, view=STUDENT_VIEW): + """ + Run the wrapper on a fragment holding ORIGINAL_CONTENT, and return the resulting content. + """ + frag = Fragment(self.ORIGINAL_CONTENT) + result = wrap_with_edxnotes(user or self.user, course, block or self.html_block, view, frag, {}) + return result.content + + @ddt.data(True, False) @override_settings(ENABLE_EDXNOTES=True) @patch("lms.djangoapps.edxnotes.helpers.get_public_endpoint", autospec=True) @patch("lms.djangoapps.edxnotes.helpers.get_token_url", autospec=True) @patch("lms.djangoapps.edxnotes.helpers.get_edxnotes_id_token", autospec=True) @patch("lms.djangoapps.edxnotes.helpers.generate_uid", autospec=True) - def test_edxnotes_enabled(self, mock_generate_uid, mock_get_id_token, mock_get_token_url, mock_get_endpoint): + def test_edxnotes_enabled( + self, pass_course, mock_generate_uid, mock_get_id_token, mock_get_token_url, mock_get_endpoint + ): """ - Tests if get_html is wrapped when feature flag is on and edxnotes are - enabled for the course. + Tests that the content is wrapped when the feature flag is on and edxnotes are enabled for the + course, whether or not the caller supplies the course. """ - course = CourseFactory(edxnotes=True) - enrollment = CourseEnrollmentFactory(course_id=course.id) - user = enrollment.user - problem = TestProblem(course, user) - mock_generate_uid.return_value = "uid" mock_get_id_token.return_value = "token" mock_get_token_url.return_value = "/tokenUrl" mock_get_endpoint.return_value = "/endpoint" - enable_edxnotes_for_the_course(course, user.id) expected_context = { - "content": "original_get_html", + "content": self.ORIGINAL_CONTENT, "uid": "uid", "edxnotes_visibility": "true", "params": { - "usageId": problem.scope_ids.usage_id, - "courseId": course.id, + "usageId": self.html_block.scope_ids.usage_id, + "courseId": self.course.id, "token": "token", "tokenUrl": "/tokenUrl", "endpoint": "/endpoint", @@ -145,52 +133,62 @@ def test_edxnotes_enabled(self, mock_generate_uid, mock_get_id_token, mock_get_t "eventStringLimit": settings.TRACK_MAX_EVENT / 6, }, } - assert problem.get_html() == render_to_string('edxnotes_wrapper.html', expected_context) + course = self.course if pass_course else None + assert self.wrap(course=course) == render_to_string("edxnotes_wrapper.html", expected_context) @override_settings(ENABLE_EDXNOTES=True) def test_edxnotes_disabled_if_edxnotes_flag_is_false(self): """ - Tests that get_html is wrapped when feature flag is on, but edxnotes are - disabled for the course. + Tests that the content is not wrapped when the feature flag is on, but edxnotes are disabled + for the course. """ self.course.edxnotes = False - assert 'original_get_html' == self.problem.get_html() + assert self.wrap(course=self.course) == self.ORIGINAL_CONTENT @override_settings(ENABLE_EDXNOTES=False) def test_edxnotes_disabled(self): """ - Tests that get_html is not wrapped when feature flag is off. + Tests that the content is not wrapped when the feature flag is off. """ - assert 'original_get_html' == self.problem.get_html() + assert self.wrap() == self.ORIGINAL_CONTENT - def test_edxnotes_studio(self): + @override_settings(ENABLE_EDXNOTES=True) + def test_other_block_types_not_wrapped(self): """ - Tests that get_html is not wrapped when problem is rendered in Studio. + Tests that only HTML blocks are wrapped. """ - self.problem.runtime.is_author_mode = True - assert 'original_get_html' == self.problem.get_html() + assert self.wrap(block=self.problem_block) == self.ORIGINAL_CONTENT - def test_edxnotes_openedx_content_runtime(self): + @override_settings(ENABLE_EDXNOTES=True) + def test_other_views_not_wrapped(self): """ - Tests that get_html is not wrapped when problem is rendered by the openedx_content runtime. + Tests that only the student view is wrapped. """ - del self.problem.block.runtime.modulestore - assert 'original_get_html' == self.problem.get_html() + assert self.wrap(view=PUBLIC_VIEW) == self.ORIGINAL_CONTENT - def test_edxnotes_harvard_notes_enabled(self): + @override_settings(ENABLE_EDXNOTES=True) + def test_anonymous_user(self): """ - Tests that get_html is not wrapped when Harvard Annotation Tool is enabled. + Tests that the content is not wrapped for unauthenticated users. """ - self.course.advanced_modules = ["videoannotation", "imageannotation", "textannotation"] - enable_edxnotes_for_the_course(self.course, self.user.id) - assert 'original_get_html' == self.problem.get_html() + assert self.wrap(user=AnonymousUser()) == self.ORIGINAL_CONTENT @override_settings(ENABLE_EDXNOTES=True) - def test_anonymous_user(self): - user = AnonymousUser() - problem = TestProblem(self.course, user) - enable_edxnotes_for_the_course(self.course, None) - assert problem.get_html() == "original_get_html" + def test_rendered_through_lms_runtime(self): + """ + Tests that an HTML block rendered by the LMS is wrapped, with the wrapper inside the XBlock's div. + """ + html_block = BlockFactory.create(parent=self.course, category="html", data="

annotate me

") + request = RequestFactory().get("/") + request.user = self.user + request.session = {} + field_data_cache = FieldDataCache([self.course, html_block], self.course.id, self.user) + block = get_block_for_descriptor( + self.user, request, html_block, field_data_cache, self.course.id, course=self.course + ) + content = block.render(STUDENT_VIEW).content + assert content.index('class="xblock') < content.index('class="edx-notes-wrapper"') + assert content.index('class="edx-notes-wrapper-content"') < content.index("

annotate me

") @skipUnless(settings.ENABLE_EDXNOTES, "EdxNotes feature needs to be enabled.") diff --git a/lms/djangoapps/edxnotes/wrappers.py b/lms/djangoapps/edxnotes/wrappers.py new file mode 100644 index 000000000000..41b303570639 --- /dev/null +++ b/lms/djangoapps/edxnotes/wrappers.py @@ -0,0 +1,78 @@ +""" +XBlock wrappers related to edXNotes. +""" + + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from django.conf import settings +from django.contrib.auth.models import AnonymousUser, User # pylint: disable=imported-auth-user +from web_fragments.fragment import Fragment +from xblock.core import XBlock + +from common.djangoapps.edxmako.shortcuts import render_to_string +from xmodule.modulestore.django import modulestore +from xmodule.x_module import STUDENT_VIEW + +if TYPE_CHECKING: + from xmodule.course_block import CourseBlock + + +def wrap_with_edxnotes( # pylint: disable=unused-argument + user: User | AnonymousUser, + course: CourseBlock | None, + block: XBlock, + view: str, + frag: Fragment, + context: dict | None, +) -> Fragment: + """ + Make the student view of an HTML block annotatable by wrapping it in the edXNotes frontend. + + WARNING: This is a temporary hack. Do not use it as a pattern for new features. + + The LMS should not special-case particular block types when rendering, nor should we be building + frontend features on openedx-platform django templates. This wrapper does both. It + exists only to keep edXNotes working until edXNotes is either replaced or deprecated: + https://github.com/openedx/edx-notes-api/issues/633 + + Arguments: + user: the user who is viewing the block. + course: the block's course, if the caller has already loaded it. + block, view, frag, context: the standard XBlock wrapper arguments. + """ + # Import is placed here to avoid model import at project startup. + from .helpers import generate_uid, get_edxnotes_id_token, get_public_endpoint, get_token_url, is_feature_enabled + + annotatable_block_types = {"html"} + + if not settings.ENABLE_EDXNOTES: + return frag + if view != STUDENT_VIEW or block.scope_ids.block_type not in annotatable_block_types: + return frag + + course = course or modulestore().get_course(block.scope_ids.usage_id.context_key) + if not (course and is_feature_enabled(course, user)): + return frag + + frag.content = render_to_string("edxnotes_wrapper.html", { + "content": frag.content, + "uid": generate_uid(), + "edxnotes_visibility": json.dumps( + getattr(block, "edxnotes_visibility", course.edxnotes_visibility) + ), + "params": { + # Use camelCase to name keys. + "usageId": block.scope_ids.usage_id, + "courseId": course.id, + "token": get_edxnotes_id_token(user), + "tokenUrl": get_token_url(course.id), + "endpoint": get_public_endpoint(), + "debug": settings.DEBUG, + "eventStringLimit": settings.TRACK_MAX_EVENT / 6, + }, + }) + return frag diff --git a/xmodule/edxnotes_utils.py b/xmodule/edxnotes_utils.py deleted file mode 100644 index 655948c475cb..000000000000 --- a/xmodule/edxnotes_utils.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Utilities related to edXNotes. -""" - - -import sys - - -def edxnotes(cls): - """ - Conditional decorator that loads edxnotes only when they exist. - """ - if "lms.djangoapps.edxnotes" in sys.modules: - from lms.djangoapps.edxnotes.decorators import edxnotes as notes - return notes(cls) - else: - return cls