Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify file URL generation. #8252

Merged
merged 3 commits into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 9 additions & 15 deletions kolibri/core/assets/src/core-app/urls.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,21 @@ const urls = {
}
return generateUrl(this.__mediaUrl, { url });
},
storageUrl(fileId, extension, embeddedFilePath = '') {
zipContentUrl(fileId, extension, embeddedFilePath = '') {
const filename = `${fileId}.${extension}`;
if (['zip', 'h5p'].includes(extension)) {
if (!this.__zipContentUrl) {
throw new ReferenceError('Zipcontent Url is not defined');
}
return generateUrl(this.__zipContentUrl, {
url: `${filename}/${embeddedFilePath}`,
origin: this.__zipContentOrigin,
port: this.__zipContentPort,
});
}
if (!this.__contentUrl) {
if (!this.__zipContentUrl) {
throw new ReferenceError('Zipcontent Url is not defined');
}
return generateUrl(this.__contentUrl, { url: `${filename[0]}/${filename[1]}/${filename}` });
return generateUrl(this.__zipContentUrl, {
url: `${filename}/${embeddedFilePath}`,
origin: this.__zipContentOrigin,
port: this.__zipContentPort,
});
},
downloadUrl(fileId, extension) {
storageUrl(fileId, extension) {
const filename = `${fileId}.${extension}`;
if (!this.__contentUrl) {
throw new ReferenceError('Content Url is not defined');
throw new ReferenceError('Zipcontent Url is not defined');
}
return generateUrl(this.__contentUrl, { url: `${filename[0]}/${filename[1]}/${filename}` });
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

<script>

import urls from 'kolibri.urls';
import { getFilePresetString } from './filePresetStrings';

export default {
Expand All @@ -32,7 +31,7 @@
const label = getFilePresetString(file);
return {
label,
url: urls.downloadUrl(file.checksum, file.extension),
url: file.storage_url,
fileName: this.$tr('downloadFilename', {
resourceTitle: this.nodeTitle,
fileExtension: file.extension,
Expand Down
31 changes: 31 additions & 0 deletions kolibri/core/content/test/test_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import hashlib

from django.test import TestCase

from kolibri.core.content.models import LocalFile
from kolibri.utils.tests.helpers import override_option


class LocalFilePathsTest(TestCase):
def test_file_url_reversal(self):
from kolibri.utils.conf import OPTIONS

path_prefix = OPTIONS["Deployment"]["URL_PATH_PREFIX"]

if path_prefix != "/":
path_prefix = "/" + path_prefix

self.hash = hashlib.md5("DUMMYDATA".encode()).hexdigest()
file = LocalFile(id=self.hash, extension="otherextension", available=True)
filename = file.get_filename()
self.assertEqual(
file.get_storage_url(),
"{}content/storage/{}/{}/{}".format(
path_prefix, filename[0], filename[1], filename
),
)


@override_option("Deployment", "URL_PATH_PREFIX", "prefix_test/")
class PrefixedLocalFilesPathsTest(LocalFilePathsTest):
pass
22 changes: 0 additions & 22 deletions kolibri/core/content/test/test_zipcontent.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from django.test import TestCase
from django.utils.http import http_date

from kolibri.core.content.models import LocalFile
from kolibri.core.content.utils.paths import get_content_storage_file_path
from kolibri.core.content.zip_wsgi import generate_zip_content_response
from kolibri.core.content.zip_wsgi import INITIALIZE_HASHI_FROM_IFRAME
Expand Down Expand Up @@ -92,27 +91,6 @@ def _get_file(self, file_name, base_url=None, **kwargs):
self.environ.update(kwargs)
return generate_zip_content_response(self.environ)

def test_zip_file_url_reversal(self):
from kolibri.utils.conf import OPTIONS

path_prefix = OPTIONS["Deployment"]["ZIP_CONTENT_URL_PATH_PREFIX"]

if path_prefix != "/":
path_prefix = "/" + path_prefix
file = LocalFile(id=self.hash, extension=self.extension, available=True)
self.assertEqual(
file.get_storage_url(),
"{}content/zipcontent/{}/".format(path_prefix, self.filename),
)

def test_non_zip_file_url_reversal(self):
file = LocalFile(id=self.hash, extension="otherextension", available=True)
filename = file.get_filename()
self.assertEqual(
file.get_storage_url(),
"/content/storage/{}/{}/{}".format(filename[0], filename[1], filename),
)

def test_zip_file_internal_file_access(self):
# test reading the data from file #1 inside the zip
response = self._get_file(self.test_name_1)
Expand Down
33 changes: 9 additions & 24 deletions kolibri/core/content/utils/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
# valid storage filenames consist of 32-char hex plus a file extension
VALID_STORAGE_FILENAME = re.compile(r"[0-9a-f]{32}(-data)?\.[0-9a-z]+")

# set of file extensions that should be considered zip files and allow access to internal files
POSSIBLE_ZIPPED_FILE_EXTENSIONS = set([".zip"])


def _maybe_makedirs(path):
if not os.path.isdir(path):
Expand Down Expand Up @@ -49,7 +46,15 @@ def get_local_content_storage_file_url(obj):
The same url will also be exposed by the file serializer.
"""
if get_attribute(obj, "available"):
return get_content_storage_file_url(filename=get_content_file_name(obj))
filename = get_content_file_name(obj)
return "/{}{}/{}/{}".format(
get_content_storage_url(
conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"]
).lstrip("/"),
filename[0],
filename[1],
filename,
)
rtibbles marked this conversation as resolved.
Show resolved Hide resolved
else:
return None

Expand Down Expand Up @@ -305,23 +310,3 @@ def zip_content_static_root():

def get_hashi_path():
return "{}{}{}".format(zip_content_static_root(), HASHI, get_hashi_html_filename())


def get_content_storage_file_url(filename):
"""
Return the URL at which the specified file can be accessed. For regular files, this is a link to the static
file itself, under "/content/storage/". For "zip" files, this points to a dynamically generated view that
allows the client-side to index into the files within the zip.
"""
ext = os.path.splitext(filename)[1]
if ext in POSSIBLE_ZIPPED_FILE_EXTENSIONS:
return "{}{}/".format(get_zip_content_base_path(), filename)
else:
return "/{}{}/{}/{}".format(
get_content_storage_url(
conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"]
).lstrip("/"),
filename[0],
filename[1],
filename,
)
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@
this.hashi.initialize(
(this.extraFields && this.extraFields.contentState) || {},
this.userData,
this.defaultFile.storage_url,
this.defaultFile.extension === 'zip'
? urls.zipContentUrl(this.defaultFile.checksum, this.defaultFile.extension)
: this.defaultFile.storage_url,
this.defaultFile.checksum
);
this.$emit('startTracking');
Expand Down