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
103 changes: 5 additions & 98 deletions cms/djangoapps/contentstore/asset_storage_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import logging
import math
import re
from functools import partial
from urllib.parse import urljoin

from django.conf import settings
Expand All @@ -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
Expand All @@ -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 = {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 0 additions & 15 deletions cms/djangoapps/contentstore/exceptions.py

This file was deleted.

3 changes: 2 additions & 1 deletion cms/djangoapps/contentstore/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
4 changes: 2 additions & 2 deletions cms/djangoapps/contentstore/views/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down
2 changes: 1 addition & 1 deletion cms/djangoapps/contentstore/views/certificate_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion cms/djangoapps/contentstore/views/preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion cms/djangoapps/contentstore/views/tests/test_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
135 changes: 135 additions & 0 deletions openedx/core/djangoapps/content/file_utilities.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading