From c5530e8bfe6b19cb223856f89b8fb808b7f91792 Mon Sep 17 00:00:00 2001 From: Fox Danger Piacenti Date: Tue, 17 Nov 2026 15:51:20 -0600 Subject: [PATCH 1/2] feat: XBlock files service --- .../contentstore/asset_storage_handlers.py | 103 +------------ cms/djangoapps/contentstore/exceptions.py | 15 -- cms/djangoapps/contentstore/views/assets.py | 4 +- .../contentstore/views/certificate_manager.py | 2 +- .../contentstore/views/tests/test_assets.py | 2 +- .../core/djangoapps/content/file_utilities.py | 135 ++++++++++++++++++ openedx/core/djangoapps/content/services.py | 69 +++++++-- pyproject.toml | 5 + 8 files changed, 206 insertions(+), 129 deletions(-) delete mode 100644 cms/djangoapps/contentstore/exceptions.py create mode 100644 openedx/core/djangoapps/content/file_utilities.py diff --git a/cms/djangoapps/contentstore/asset_storage_handlers.py b/cms/djangoapps/contentstore/asset_storage_handlers.py index 97b7a8b7a3bb..bd31d91b1cd3 100644 --- a/cms/djangoapps/contentstore/asset_storage_handlers.py +++ b/cms/djangoapps/contentstore/asset_storage_handlers.py @@ -5,7 +5,6 @@ import logging import math import re -from functools import partial from urllib.parse import urljoin from django.conf import settings @@ -31,6 +30,11 @@ from common.djangoapps.util.json_request import JsonResponse from openedx.core.djangoapps.authz.constants import LegacyAuthoringPermission from openedx.core.djangoapps.authz.decorators import user_has_course_permission +from openedx.core.djangoapps.content.file_utilities import ( + AssetNotFoundException, + AssetSizeTooLargeException, + update_course_run_asset, +) from openedx.core.djangoapps.contentserver.caching import del_cached_content from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.user_api.models import UserPreference @@ -40,7 +44,6 @@ from xmodule.modulestore.django import modulestore # pylint: disable=wrong-import-order from xmodule.modulestore.exceptions import ItemNotFoundError # pylint: disable=wrong-import-order -from .exceptions import AssetNotFoundException, AssetSizeTooLargeException from .utils import get_files_uploads_url, get_response_format, request_response_format_is_json REQUEST_DEFAULTS = { @@ -517,37 +520,6 @@ def _get_assets_in_json_format(assets, course_key, assets_usage_locations_map): return assets_in_json_format -def update_course_run_asset(course_key, upload_file): - """returns contents of the uploaded file""" - course_exists_response = _get_error_if_course_does_not_exist(course_key) - - if course_exists_response is not None: - return course_exists_response - - file_metadata = _get_file_metadata_as_dictionary(upload_file) - - is_file_too_large = _check_file_size_is_too_large(file_metadata) - if is_file_too_large: - error_message = _get_file_too_large_error_message(file_metadata['filename']) - raise AssetSizeTooLargeException(error_message) - - content, temporary_file_path = _get_file_content_and_path(file_metadata, course_key) - - (thumbnail_content, thumbnail_location) = contentstore().generate_thumbnail(content, - tempfile_path=temporary_file_path) - - # delete cached thumbnail even if one couldn't be created this time (else the old thumbnail will continue to show) - del_cached_content(thumbnail_location) - - if _check_thumbnail_uploaded(thumbnail_content): - content.thumbnail_location = thumbnail_location - - contentstore().save(content) - del_cached_content(content.location) - - return content - - @require_POST @ensure_csrf_cookie @login_required @@ -599,71 +571,6 @@ def _get_error_if_course_does_not_exist(course_key): # pylint: disable=missing- return HttpResponseBadRequest() -def _get_file_metadata_as_dictionary(upload_file): # pylint: disable=missing-function-docstring - # compute a 'filename' which is similar to the location formatting; we're - # using the 'filename' nomenclature since we're using a FileSystem paradigm - # here; we're just imposing the Location string formatting expectations to - # keep things a bit more consistent - return { - 'upload_file': upload_file, - 'filename': upload_file.name, - 'mime_type': upload_file.content_type, - 'upload_file_size': get_file_size(upload_file) - } - - -def get_file_size(upload_file): - """returns the size of the uploaded file""" - # can be used for mocking test file sizes. - return upload_file.size - - -def _check_file_size_is_too_large(file_metadata): - """verifies whether file size is greater than allowed file size""" - upload_file_size = file_metadata['upload_file_size'] - maximum_file_size_in_megabytes = settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB - maximum_file_size_in_bytes = maximum_file_size_in_megabytes * 1000 ** 2 - - return upload_file_size > maximum_file_size_in_bytes - - -def _get_file_too_large_error_message(filename): - """returns formatted error message for large files""" - - return _( - 'File {filename} exceeds maximum size of ' - '{maximum_size_in_megabytes} MB.' - ).format( - filename=filename, - maximum_size_in_megabytes=settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB, - ) - - -def _get_file_content_and_path(file_metadata, course_key): - """returns contents of the uploaded file and path for temporary uploaded file""" - content_location = StaticContent.compute_location(course_key, file_metadata['filename']) - upload_file_size = str(file_metadata['upload_file_size']) - upload_file = file_metadata['upload_file'] - - file_can_be_chunked = upload_file.multiple_chunks() - - static_content_partial = partial(StaticContent, content_location, file_metadata['filename'], - file_metadata['mime_type'], length=upload_file_size) - - if file_can_be_chunked: - content = static_content_partial(upload_file.chunks()) - temporary_file_path = upload_file.temporary_file_path() - else: - content = static_content_partial(upload_file.read()) - temporary_file_path = None - return content, temporary_file_path - - -def _check_thumbnail_uploaded(thumbnail_content): - """returns whether thumbnail is None""" - return thumbnail_content is not None - - def _get_thumbnail_asset_key(asset, course_key): """returns thumbnail asset key""" # note, due to the schema change we may not have a 'thumbnail_location' in the result set diff --git a/cms/djangoapps/contentstore/exceptions.py b/cms/djangoapps/contentstore/exceptions.py deleted file mode 100644 index bf33bad8f94c..000000000000 --- a/cms/djangoapps/contentstore/exceptions.py +++ /dev/null @@ -1,15 +0,0 @@ -""" -A common module for managing exceptions. Helps to avoid circular references -""" - - -class AssetNotFoundException(Exception): - """ - Raised when asset not found - """ - - -class AssetSizeTooLargeException(Exception): - """ - Raised when the size of an uploaded asset exceeds the maximum size limit. - """ diff --git a/cms/djangoapps/contentstore/views/assets.py b/cms/djangoapps/contentstore/views/assets.py index beb378e8a759..0e6f6ca67b0d 100644 --- a/cms/djangoapps/contentstore/views/assets.py +++ b/cms/djangoapps/contentstore/views/assets.py @@ -7,9 +7,9 @@ from cms.djangoapps.contentstore.asset_storage_handlers import delete_asset as delete_asset_source_function from cms.djangoapps.contentstore.asset_storage_handlers import get_asset_json as get_asset_json_source_function from cms.djangoapps.contentstore.asset_storage_handlers import get_asset_usage_path_json, handle_assets -from cms.djangoapps.contentstore.asset_storage_handlers import get_file_size as get_file_size_source_function from cms.djangoapps.contentstore.asset_storage_handlers import update_asset as update_asset_source_function -from cms.djangoapps.contentstore.asset_storage_handlers import ( +from openedx.core.djangoapps.content.file_utilities import get_file_size as get_file_size_source_function +from openedx.core.djangoapps.content.file_utilities import ( update_course_run_asset as update_course_run_asset_source_function, ) diff --git a/cms/djangoapps/contentstore/views/certificate_manager.py b/cms/djangoapps/contentstore/views/certificate_manager.py index f5f4224d1822..12085126c946 100644 --- a/cms/djangoapps/contentstore/views/certificate_manager.py +++ b/cms/djangoapps/contentstore/views/certificate_manager.py @@ -12,8 +12,8 @@ from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.util.db import MYSQL_MAX_INT, generate_int_id +from openedx.core.djangoapps.content.file_utilities import AssetNotFoundException -from ..exceptions import AssetNotFoundException from .assets import delete_asset CERTIFICATE_SCHEMA_VERSION = 1 diff --git a/cms/djangoapps/contentstore/views/tests/test_assets.py b/cms/djangoapps/contentstore/views/tests/test_assets.py index cf894643ed72..5b6dc93b98e9 100644 --- a/cms/djangoapps/contentstore/views/tests/test_assets.py +++ b/cms/djangoapps/contentstore/views/tests/test_assets.py @@ -370,7 +370,7 @@ def test_upload_image(self): (MAX_FILE_SIZE, "justequals.file.test", 200), (MAX_FILE_SIZE + 90, "large.file.test", 413), ) - @mock.patch('cms.djangoapps.contentstore.asset_storage_handlers.get_file_size') + @mock.patch('openedx.core.djangoapps.content.file_utilities.get_file_size') def test_file_size(self, case, get_file_size): max_file_size, name, status_code = case diff --git a/openedx/core/djangoapps/content/file_utilities.py b/openedx/core/djangoapps/content/file_utilities.py new file mode 100644 index 000000000000..7f22c33da6d4 --- /dev/null +++ b/openedx/core/djangoapps/content/file_utilities.py @@ -0,0 +1,135 @@ +""" +Extracted file utilities used for adding files to courses. These are likely to +need removal once learning core asset handling is completed: + +https://github.com/openedx/openedx-core/issues/890 +https://github.com/openedx/openedx-core/pull/880 +""" + +import logging +from functools import partial + +from django.conf import settings +from django.http import HttpResponseBadRequest +from django.utils.translation import gettext as _ + +from openedx.core.djangoapps.contentserver.caching import del_cached_content +from xmodule.contentstore.content import StaticContent +from xmodule.contentstore.django import contentstore +from xmodule.modulestore.django import modulestore +from xmodule.modulestore.exceptions import ItemNotFoundError + + +def update_course_run_asset(course_key, upload_file): + """returns contents of the uploaded file""" + course_exists_response = _get_error_if_course_does_not_exist(course_key) + + if course_exists_response is not None: + return course_exists_response + + file_metadata = _get_file_metadata_as_dictionary(upload_file) + + is_file_too_large = _check_file_size_is_too_large(file_metadata) + if is_file_too_large: + error_message = _get_file_too_large_error_message(file_metadata["filename"]) + raise AssetSizeTooLargeException(error_message) + + content, temporary_file_path = _get_file_content_and_path(file_metadata, course_key) + + (thumbnail_content, thumbnail_location) = contentstore().generate_thumbnail( + content, tempfile_path=temporary_file_path + ) + + # delete cached thumbnail even if one couldn't be created this time (else the old thumbnail will continue to show) + del_cached_content(thumbnail_location) + + if _check_thumbnail_uploaded(thumbnail_content): + content.thumbnail_location = thumbnail_location + + contentstore().save(content) + del_cached_content(content.location) + + return content + + +class AssetNotFoundException(Exception): + """ + Raised when asset not found + """ + + +class AssetSizeTooLargeException(Exception): + """ + Raised when the size of an uploaded asset exceeds the maximum size limit. + """ + + +def _check_thumbnail_uploaded(thumbnail_content): + """returns whether thumbnail is None""" + return thumbnail_content is not None + + +def _get_file_content_and_path(file_metadata, course_key): + """returns contents of the uploaded file and path for temporary uploaded file""" + content_location = StaticContent.compute_location(course_key, file_metadata["filename"]) + upload_file_size = str(file_metadata["upload_file_size"]) + upload_file = file_metadata["upload_file"] + + file_can_be_chunked = upload_file.multiple_chunks() + + static_content_partial = partial( + StaticContent, content_location, file_metadata["filename"], file_metadata["mime_type"], length=upload_file_size + ) + + if file_can_be_chunked: + content = static_content_partial(upload_file.chunks()) + temporary_file_path = upload_file.temporary_file_path() + else: + content = static_content_partial(upload_file.read()) + temporary_file_path = None + return content, temporary_file_path + + +def _get_file_too_large_error_message(filename): + """returns formatted error message for large files""" + + return _("File {filename} exceeds maximum size of {maximum_size_in_megabytes} MB.").format( + filename=filename, + maximum_size_in_megabytes=settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB, + ) + + +def _get_error_if_course_does_not_exist(course_key): # pylint: disable=missing-function-docstring + try: + modulestore().get_course(course_key) + except ItemNotFoundError: + logging.error("Could not find course: %s", course_key) + return HttpResponseBadRequest() + + +def _get_file_metadata_as_dictionary(upload_file): # pylint: disable=missing-function-docstring + # compute a 'filename' which is similar to the location formatting; we're + # using the 'filename' nomenclature since we're using a FileSystem paradigm + # here; we're just imposing the Location string formatting expectations to + # keep things a bit more consistent + return { + "upload_file": upload_file, + "filename": upload_file.name, + "mime_type": upload_file.content_type, + "upload_file_size": get_file_size(upload_file), + } + + +def _check_file_size_is_too_large(file_metadata): + """verifies whether file size is greater than allowed file size""" + upload_file_size = file_metadata["upload_file_size"] + maximum_file_size_in_megabytes = settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB + maximum_file_size_in_bytes = maximum_file_size_in_megabytes * 1000**2 + + return upload_file_size > maximum_file_size_in_bytes + + +def get_file_size(upload_file): + """returns the size of the uploaded file""" + # can be used for mocking test file sizes. + return upload_file.size diff --git a/openedx/core/djangoapps/content/services.py b/openedx/core/djangoapps/content/services.py index 63d22c7d0b4b..42e9f45e9c34 100644 --- a/openedx/core/djangoapps/content/services.py +++ b/openedx/core/djangoapps/content/services.py @@ -1,14 +1,16 @@ """ Services for learning content """ + from __future__ import annotations import warnings from collections.abc import Callable from typing import Literal +from django.core.files.uploadedfile import InMemoryUploadedFile from opaque_keys.edx.keys import LearningContextKey -from opaque_keys.edx.locator import CourseLocator, LibraryLocatorV2 +from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator, LibraryLocatorV2, LibraryUsageLocatorV2 from openedx_authz.api import is_user_allowed from openedx_authz.authz import ( COURSES_CREATE_FILES, @@ -25,6 +27,7 @@ from common.djangoapps.student.auth import has_studio_read_access, has_studio_write_access from common.djangoapps.student.roles import enable_authz_course_authoring +from openedx.core.djangoapps.content.file_utilities import update_course_run_asset from openedx.core.djangoapps.content_tagging.rules import UserType COMMON_PERM_KEY = Literal[ @@ -71,7 +74,7 @@ }, "manage_updates": { "course": COURSES_MANAGE_COURSE_UPDATES, - } + }, } @@ -99,6 +102,7 @@ def _course_fallback_check(fallback_function: Callable[[UserType, CourseLocator] system if authz is disabled for a course. Remove this decorator when the old system is fully removed and AuthZ is the only way we do checks. """ + def wrapper(function): def wrapped(self: StudioPermissionsService, context_key: LearningContextKey): if isinstance(context_key, CourseLocator): @@ -106,7 +110,9 @@ def wrapped(self: StudioPermissionsService, context_key: LearningContextKey): return function(self, context_key) return fallback_function(self._user, context_key) # pylint: disable=protected-access return function(self, context_key) + return wrapped + return wrapper @@ -119,7 +125,7 @@ def __init__(self, user) -> None: self._user = user def _check_permission(self, perm_label: COMMON_PERM_KEY, context_key: LearningContextKey) -> bool: - """ Verify that a user has a specific permission for this context. """ + """Verify that a user has a specific permission for this context.""" return self._user.is_active and is_user_allowed( self._user, perm_for_key(perm_label, context_key).identifier, @@ -128,31 +134,31 @@ def _check_permission(self, perm_label: COMMON_PERM_KEY, context_key: LearningCo @_course_fallback_check(has_studio_read_access) def can_read_content(self, context_key: LearningContextKey) -> bool: - """ Can the user read the content of this course/library? """ + """Can the user read the content of this course/library?""" return self._check_permission("read_content", context_key) @_course_fallback_check(has_studio_write_access) def can_edit_content(self, context_key: LearningContextKey) -> bool: - """ Can the user edit the content of this course/library? """ + """Can the user edit the content of this course/library?""" return self._check_permission("edit_content", context_key) @_course_fallback_check(has_studio_read_access) def can_read_files(self, context_key: LearningContextKey) -> bool: - """ Can the user read files for this course/library? """ + """Can the user read files for this course/library?""" return self._check_permission("read_files", context_key) @_course_fallback_check(has_studio_write_access) def can_create_files(self, context_key: LearningContextKey) -> bool: - """ Can the user create files for this course/library? """ + """Can the user create files for this course/library?""" return self._check_permission("create_files", context_key) @_course_fallback_check(has_studio_write_access) def can_edit_files(self, context_key: LearningContextKey) -> bool: - """ Can the user edit files for this course/library? """ + """Can the user edit files for this course/library?""" return self._check_permission("edit_files", context_key) def can_read(self, context_key: LearningContextKey) -> bool: - """ Does the user have read access to the given course/library? """ + """Does the user have read access to the given course/library?""" warnings.warn( "can_read is deprecated. " "Use a more specific permission, like can_read_content or can_read_files instead. " @@ -163,7 +169,7 @@ def can_read(self, context_key: LearningContextKey) -> bool: return has_studio_read_access(self._user, context_key) def can_write(self, context_key: LearningContextKey) -> bool: - """ Does the user have write access to the given course/library? """ + """Does the user have write access to the given course/library?""" warnings.warn( "can_write is deprecated. " "Use a more specific permission, like can_edit_content, can_create_files, " @@ -175,10 +181,49 @@ def can_write(self, context_key: LearningContextKey) -> bool: return has_studio_write_access(self._user, context_key) def can_reuse_content(self, context_key: LibraryLocatorV2) -> bool: - """ Does the user have the ability to reuse content from this library? """ + """Does the user have the ability to reuse content from this library?""" return self._check_permission("reuse_content", context_key) @_course_fallback_check(has_studio_write_access) def can_manage_updates(self, context_key: CourseLocator) -> bool: - """ Does the user have the ability to manage updates for this course? """ + """Does the user have the ability to manage updates for this course?""" return self._check_permission("manage_updates", context_key) + + +class FileService: + """ + Service that provides basic asset management functionality. Should be used + in conjunction with StudioPermissionsService to ensure the user has the + right to manage assets for this block and/or its context. + """ + + def __init__(self, user) -> None: + self._user = user + + def add_asset_to_block(self, usage_key: LibraryUsageLocatorV2, asset: InMemoryUploadedFile) -> str: + """ + Adds a file asset to a block, and returns the URL for the resulting asset. + """ + from openedx.core.djangoapps.content_libraries.api import add_library_block_static_asset_file + + if isinstance(usage_key, BlockUsageLocator): + raise NotImplementedError("Association of files to individual blocks not yet supported in courses.") + # Static assets with a /static/ prefix rendered by the backend have their paths + # translated to the paths for loading library assets. + path = f"static/{asset.name}" + # The path must be stored without the leading slash. + add_library_block_static_asset_file(usage_key, path, asset.read(), self._user) + return "/" + path + + def add_asset_to_context(self, usage_key: BlockUsageLocator, asset: InMemoryUploadedFile) -> str: + """ + Adds a file asset to a block, and returns the URL for the resulting asset. + """ + if isinstance(usage_key, LibraryLocatorV2): + raise NotImplementedError("Libraries do not currently allow context-wide files.") + asset = update_course_run_asset(usage_key.course_key, asset) + return asset.get_static_path_from_location(asset.location) + + # Listing, reading, and deleting not included for now, but welcome for future contribution, + # especially once Learning Core's asset support is ready. See: + # https://openedx-core--880.org.readthedocs.build/en/880/openedx_content/decisions/0013-shared-static-assets.html#openedx-content-adr-0013 diff --git a/pyproject.toml b/pyproject.toml index 7405f7ffba6b..3c6ce12d5b0f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -880,4 +880,9 @@ ignore_imports = [ # These imports will become OK once we worked on the following issue: # https://github.com/openedx/edx-platform/issues/33428 "openedx.core.djangoapps.video_config.services -> openedx.core.djangoapps.content_libraries.api", + # FIXME: the exceptions below are new issues introduced transitively to larger refactors in flight. + # Outstanding architectural issue: course file handling does not have a consistent API. + # https://github.com/openedx/openedx-core/issues/890 + # https://github.com/openedx/openedx-core/pull/880 + "openedx.core.djangoapps.content.services -> openedx.core.djangoapps.content_libraries.api", ] From ebb7ae9e335a08016d22fcd4c2633046774924bb Mon Sep 17 00:00:00 2001 From: Fox Danger Piacenti Date: Fri, 20 Nov 2026 18:37:36 -0600 Subject: [PATCH 2/2] feat: add in the files service to load --- cms/djangoapps/contentstore/utils.py | 3 ++- cms/djangoapps/contentstore/views/preview.py | 3 ++- openedx/core/djangoapps/xblock/runtime/runtime.py | 6 ++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/cms/djangoapps/contentstore/utils.py b/cms/djangoapps/contentstore/utils.py index c7647e0959b2..044ecbb2e7e0 100644 --- a/cms/djangoapps/contentstore/utils.py +++ b/cms/djangoapps/contentstore/utils.py @@ -70,7 +70,7 @@ from common.djangoapps.xblock_django.user_service import DjangoXBlockUserService from openedx.core import toggles as core_toggles from openedx.core.djangoapps.content.course_overviews.models import CourseOverview -from openedx.core.djangoapps.content.services import StudioPermissionsService +from openedx.core.djangoapps.content.services import FileService, StudioPermissionsService from openedx.core.djangoapps.content_libraries.api import get_container from openedx.core.djangoapps.content_tagging.toggles import is_tagging_feature_disabled from openedx.core.djangoapps.credit.api import get_credit_requirements, is_credit_course @@ -1273,6 +1273,7 @@ def load_services_for_studio(runtime, user): services = { "user": DjangoXBlockUserService(user), "studio_user_permissions": StudioPermissionsService(user), + "files": FileService(user), "mako": MakoService(), "settings": SettingsService(), "lti-configuration": ConfigurationService(CourseAllowPIISharingInLTIFlag), diff --git a/cms/djangoapps/contentstore/views/preview.py b/cms/djangoapps/contentstore/views/preview.py index 358aaebeb910..04abef0888c4 100644 --- a/cms/djangoapps/contentstore/views/preview.py +++ b/cms/djangoapps/contentstore/views/preview.py @@ -29,7 +29,7 @@ from common.djangoapps.student.models import anonymous_id_for_user from common.djangoapps.xblock_django.user_service import DjangoXBlockUserService from lms.djangoapps.lms_xblock.field_data import LmsFieldData -from openedx.core.djangoapps.content.services import StudioPermissionsService +from openedx.core.djangoapps.content.services import FileService, StudioPermissionsService from openedx.core.djangoapps.discussions.services import DiscussionConfigService from openedx.core.djangoapps.video_config.services import VideoConfigService from openedx.core.lib.cache_utils import CacheService @@ -210,6 +210,7 @@ def _prepare_runtime_for_preview(request, block): # This comment is left here as a note for future devs investigating similar bugs. services = { "studio_user_permissions": StudioPermissionsService(request.user), + "files": FileService(request.user), "i18n": XBlockI18nService, 'mako': mako_service, "settings": SettingsService(), diff --git a/openedx/core/djangoapps/xblock/runtime/runtime.py b/openedx/core/djangoapps/xblock/runtime/runtime.py index dc5d0696ee62..a8ce60300339 100644 --- a/openedx/core/djangoapps/xblock/runtime/runtime.py +++ b/openedx/core/djangoapps/xblock/runtime/runtime.py @@ -362,6 +362,12 @@ def service(self, block: XBlock, service_name: str): "Cannot access studio permissions service when there is no user bound to the XBlock." ) return StudioPermissionsService(self.user) + elif service_name == 'files': + from openedx.core.djangoapps.content.services import FileService + if self.user is None: + raise RuntimeError( + "Cannot access studio permissions service when there is no user bound to the XBlock." + ) # Otherwise, fall back to the base implementation which loads services # defined in the constructor: