66
77from django .db import connection
88from django .db .models import Q
9- from django .http import HttpResponseBadRequest
109from django .utils .decorators import method_decorator
11- from kolibri_content import base_models
1210from kolibri_content import models as kolibri_content_models
1311from kolibri_content .constants .schema_versions import (
1412 CONTENT_SCHEMA_VERSION ,
1513) # Use kolibri_content
14+ from kolibri_content .constants .schema_versions import EXPORT_SCHEMA_VERSIONS
1615from kolibri_content .constants .schema_versions import (
1716 MIN_CONTENT_SCHEMA_VERSION ,
1817) # Use kolibri_content
18+ from kolibri_content .contentschema .columns import for_version
1919from kolibri_public import models # Use kolibri_public models
2020from kolibri_public .views import metadata_cache
2121from rest_framework import status
22+ from rest_framework .exceptions import ValidationError
2223from rest_framework .generics import get_object_or_404
2324from rest_framework .permissions import AllowAny
2425from rest_framework .response import Response
2728from contentcuration .utils .pagination import ValuesViewsetCursorPagination
2829
2930
30- def _get_kc_and_base_models (model ):
31+ # Clients that send no schema_version predate kolibri#15358 and may read any supported version.
32+ DEFAULT_COLUMNS = {
33+ table : tuple (
34+ dict .fromkeys (
35+ column
36+ for version in EXPORT_SCHEMA_VERSIONS
37+ for column in for_version (version )[table ]
38+ )
39+ )
40+ for table in for_version (CONTENT_SCHEMA_VERSION )
41+ }
42+
43+
44+ def _get_kc_model (model ):
3145 try :
32- kc_model = getattr (kolibri_content_models , model .__name__ )
33- base_model = getattr (base_models , model .__name__ )
46+ return getattr (kolibri_content_models , model .__name__ )
3447 except AttributeError :
3548 # This will happen if it's a M2M through model, which only exist on ContentNode
3649 through_model_name = model .__name__ .replace ("ContentNode_" , "" )
37- kc_model = getattr (
38- kolibri_content_models .ContentNode , through_model_name
39- ).through
40- # Through models are not defined for the abstract base models, so we just cheat and
41- # use these instead.
42- base_model = kc_model
43- return kc_model , base_model
50+ return getattr (kolibri_content_models .ContentNode , through_model_name ).through
4451
4552
4653class ImportMetadataPagination (ValuesViewsetCursorPagination ):
@@ -75,7 +82,20 @@ def _error_message(self, low):
7582 )
7683 return error
7784
78- def retrieve (self , request , pk = None ): # noqa: C901
85+ def _validate_content_schema (self , content_schema ):
86+ try :
87+ version = int (content_schema )
88+ except ValueError as e :
89+ raise ValidationError (
90+ "Schema version is not parseable by this version of Kolibri"
91+ ) from e
92+ if version > int (self .default_content_schema ):
93+ raise ValidationError (self ._error_message (False ))
94+ if version < int (self .min_content_schema ):
95+ raise ValidationError (self ._error_message (True ))
96+ return str (version )
97+
98+ def retrieve (self , request , pk = None ):
7999 """
80100 An endpoint to retrieve all content metadata required for importing a content node
81101 all of its ancestors, and any relevant needed metadata.
@@ -92,24 +112,13 @@ def retrieve(self, request, pk=None): # noqa: C901
92112 {"error" : "Invalid UUID format." }, status = status .HTTP_400_BAD_REQUEST
93113 )
94114
95- content_schema = request .query_params .get (
96- "schema_version" , self .default_content_schema
97- )
98-
99- try :
100- if int (content_schema ) > int (self .default_content_schema ):
101- return HttpResponseBadRequest (self ._error_message (False ))
102- if int (content_schema ) < int (self .min_content_schema ):
103- return HttpResponseBadRequest (self ._error_message (True ))
104- # Remove reference to SQLAlchemy schema bases
105- except ValueError :
106- return HttpResponseBadRequest (
107- "Schema version is not parseable by this version of Kolibri"
108- )
109- except AttributeError :
110- return HttpResponseBadRequest (
111- "Schema version is not known by this version of Kolibri"
112- )
115+ content_schema = request .query_params .get ("schema_version" )
116+ if content_schema is None :
117+ content_schema = self .default_content_schema
118+ columns = DEFAULT_COLUMNS
119+ else :
120+ content_schema = self ._validate_content_schema (content_schema )
121+ columns = for_version (content_schema )
113122
114123 # Get the model for the target node here - we do this so that we trigger a 404 immediately if the node
115124 # does not exist.
@@ -163,32 +172,17 @@ def retrieve(self, request, pk=None): # noqa: C901
163172 related ,
164173 channel_metadata ,
165174 ]:
166- # First get the kolibri_content model and base model to which this is equivalent
167- kc_model , base_model = _get_kc_and_base_models (qs .model )
168175 # Map the table name from the kolibri_public table name to the equivalent Kolibri table name
169- table_name = kc_model ._meta .db_table
170- # Tweak our introspection here to rely on Django model meta instead of SQLAlchemy
171- # Read valid field names from the combination of the base model, and the mptt tree fields
172- # of the kc_model - because the base model is abstract, it does not get the mptt fields applied
173- # to its meta fields attribute, so we need to read the actual fields from the kc_model, but filter
174- # them only to names valid for the base model.
175- field_names = {field .column for field in base_model ._meta .fields }
176- if hasattr (base_model , "_mptt_meta" ):
177- field_names .add (base_model ._mptt_meta .parent_attr )
178- field_names .add (base_model ._mptt_meta .tree_id_attr )
179- field_names .add (base_model ._mptt_meta .left_attr )
180- field_names .add (base_model ._mptt_meta .right_attr )
181- field_names .add (base_model ._mptt_meta .level_attr )
182- raw_fields = [
183- field .column
184- for field in kc_model ._meta .fields
185- if field .column in field_names
186- ]
176+ table_name = _get_kc_model (qs .model )._meta .db_table
177+ raw_fields = columns [table_name ]
178+ value_fields = raw_fields
187179 if qs .model is models .Language :
188- raw_fields = [rf for rf in raw_fields if rf != "lang_name" ] + [
189- "native_name"
180+ # Studio's Language keeps the name Kolibri calls lang_name in native_name
181+ value_fields = [
182+ "native_name" if field == "lang_name" else field
183+ for field in raw_fields
190184 ]
191- qs = qs .values (* raw_fields )
185+ qs = qs .values (* value_fields )
192186 # Avoid using the Django queryset directly, as it will coerce the database values
193187 # via its field 'from_db_value' transformers, whereas import metadata is read
194188 # directly from the database.
@@ -208,10 +202,6 @@ def retrieve(self, request, pk=None): # noqa: C901
208202 )
209203 for row in cursor
210204 ]
211- if qs .model is models .Language :
212- for lang in data [table_name ]:
213- lang ["lang_name" ] = lang ["native_name" ]
214- del lang ["native_name" ]
215205
216206 data ["schema_version" ] = content_schema
217207
0 commit comments