Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion core/collections/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,13 +861,16 @@ def _apply_cascade(self, concept_queryset, mapping_queryset, system_version, val
concept_ids = set()
mapping_ids = set()
traversed = []
viewable_by_version = {}

for concept in concept_queryset:
concept_uri = drop_version(concept.uri)
if concept_uri in traversed:
continue
traversed.append(concept_uri)
result = concept.cascade(**cascade_params)
repo_version = self._get_viewable_cascade_version(
concept, cascade_params['repo_version'], viewable_by_version)
result = concept.cascade(**{**cascade_params, 'repo_version': repo_version})
concept_ids.update(set(result['concepts'].values_list('id', flat=True)))
mapping_ids.update(set(result['mappings'].values_list('id', flat=True)))

Expand All @@ -876,6 +879,21 @@ def _apply_cascade(self, concept_queryset, mapping_queryset, system_version, val

return Concept.objects.filter(id__in=concept_ids), Mapping.objects.filter(id__in=mapping_ids)

def _get_viewable_cascade_version(self, concept, repo_version, viewable_by_version):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (PR body). The How section calls this CollectionReference._can_view_cascade_version. It also says the URL-scope block moves unchanged out of __get_search_results, but __apply_scope_filters gains the match_none branch and the 'collection' not in self.kwargs condition. Both are listed under "From the review passes", so only the How section is out of date.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the PR body: the How section names _get_viewable_cascade_version and says what __apply_scope_filters gains on the move (the match_none branch and the 'collection' not in self.kwargs condition).

"""The repo version a cascade walks (named by label, or the reference's system or value set version), if the
reference's creator can view it. A label resolves as the walk would, among the source versions that hold the
concept, and must name exactly one. Otherwise None: the walk adds only the concept, as for an unknown label.
"""
if isinstance(repo_version, str):
versions = list(concept.sources.filter(version=decode_string(repo_version))[:2])
repo_version = versions[0] if len(versions) == 1 else None
if not repo_version:
return None
key = (repo_version.__class__.__name__, repo_version.id)
if key not in viewable_by_version:
viewable_by_version[key] = repo_version.can_view_all_content(self.created_by)
return repo_version if viewable_by_version[key] else None

def get_mappings(self, system_version=None):
queryset = self.get_resource_queryset_from_system_and_valueset('mappings', system_version)
if queryset is None:
Expand Down
2 changes: 2 additions & 0 deletions core/common/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,8 @@ def get_aggregations(self, verbose=False, raw=False):
return result
self.max_score = result['score']['max']
self.total = total or 0
if not self.max_score: # no hits: no scores to bucket
return []
return self._get_score_buckets(
self.max_score, result['distribution']['buckets'], verbose)

Expand Down
108 changes: 62 additions & 46 deletions core/common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,11 @@ def get_faceted_fields(self):
) or field for field, config in es_fields.items() if config.get('facet', False)
]

@property
def url_username(self):
"""The user the URL names, the requester on the /user/ shortcut."""
return self.kwargs.get('user') or (self.request.user.username if self.user_is_self else None)

def get_facet_filters_from_kwargs(self):
kwargs = self.kwargs
filters = {}
Expand All @@ -505,7 +510,7 @@ def get_facet_filters_from_kwargs(self):
if is_collection_specified:
version = kwargs.get('version') or HEAD
filters['collection'] = kwargs['collection']
collection_owner_url = f'/users/{kwargs["user"]}/' if is_user_specified else f'/orgs/{kwargs["org"]}/'
collection_owner_url = f'/orgs/{kwargs["org"]}/' if 'org' in kwargs else f'/users/{self.url_username}/'
filters['collection_owner_url'] = collection_owner_url
if 'expansion' in self.kwargs:
filters['expansion_url'] = (f"{collection_owner_url}collections/{filters['collection']}/{version}/"
Expand Down Expand Up @@ -539,7 +544,7 @@ def get_kwargs_filters(self): # pylint: disable=too-many-branches
if is_version_specified:
container_version = self.kwargs['version']
is_latest_released = container_version == LATEST
params = {'user__username': self.kwargs.get('user'), 'organization__mnemonic': self.kwargs.get('org')}
params = {'user__username': self.url_username, 'organization__mnemonic': self.kwargs.get('org')}
if is_latest_released:
if is_source_specified:
from core.sources.models import Source
Expand Down Expand Up @@ -891,6 +896,58 @@ def is_canonical_specified(self):
self.is_concept_container_document_model() or self.is_repo_document_model()
) and self.request.query_params.get(CANONICAL_URL_REQUEST_PARAM, None)

def __apply_scope_filters(self, results): # pylint: disable=too-many-branches
"""Limits a search to what the URL names: its owner, repository and version (or the requester's orgs, on a
members view)."""
user = self.request.user
is_authenticated = user.is_authenticated
username = user.username

is_members_view = self.is_members_view()
if self.is_owner_document_model():
kwargs_filters = self.kwargs.copy()
if self.user_is_self and is_authenticated:
kwargs_filters.pop('user_is_self', None)
kwargs_filters['user'] = username
else:
kwargs_filters = self.get_kwargs_filters()
if is_members_view:
kwargs_filters['ownerType'] = 'Organization'
kwargs_filters['owner'] = self.get_members_view_org_mnemonics() or ['UNKNOWN-ORG-DUMMY']
elif self.user_is_self and is_authenticated and 'collection' not in self.kwargs:
# a collection's concepts can come from any owner's source, so only other routes filter by owner
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = username

if self.is_url_registry_document() and not is_members_view:
kwargs_filters = self.kwargs.copy()
if self.user_is_self and is_authenticated:
kwargs_filters.pop('user_is_self', None)
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = username
elif not kwargs_filters:
kwargs_filters['ownerUrl'] = '/'
else:
if 'org' in kwargs_filters:
kwargs_filters['ownerType'] = 'Organization'
kwargs_filters['owner'] = kwargs_filters.pop('org')
elif 'user' in kwargs_filters:
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = kwargs_filters.pop('user')

for key, value in kwargs_filters.items():
attr = to_snake_case(key)
if value is None: # a version that doesn't resolve, such as `latest` with no release: nothing matches
results = results.filter(Q('match_none'))
elif isinstance(value, list):
criteria = Q('term', **{attr: get(value, '0')})
for val in value[1:]:
criteria |= Q('term', **{attr: val})
results = results.filter(criteria)
else:
results = results.filter('term', **{attr: value})
return results

def __get_fuzzy_search_results(
self, source_versions=None, other_filters=None, sort=True
):
Expand All @@ -905,6 +962,8 @@ def __get_fuzzy_search_results(
results = results.query(
self.__get_source_versions_es_criterion(source_versions)
)
else:
results = self.__apply_scope_filters(results)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (PR body). Without source_version targets, this now applies the URL scope on HEAD URLs too: owner, source and source_version=HEAD under /orgs/O/sources/S/concepts/. Before, the fuzzy path had no repository filter, so a fuzzy search there matched every source's latest revisions. The body lists HEAD URLs under "Unchanged", but they belong with the behaviour change. No client sends fuzzy=true, so the impact is small.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. HEAD URLs are now under the behaviour change in the PR body: a fuzzy search on /orgs/O/sources/S/concepts/ keeps to S's HEAD, where it used to match every source's latest revisions.

results = results.query(self.get_fuzzy_search_criterion())

min_score = self.request.query_params.get('min_score') or None
Expand Down Expand Up @@ -994,50 +1053,7 @@ def __get_search_results(self, ignore_retired_filter=False, sort=True, highlight
for field, value in extras_fields_exact.items():
results = results.query("match", **{field: value}, _expand__to_dot=False)

user = self.request.user
is_authenticated = user.is_authenticated
username = user.username

is_members_view = self.is_members_view()
if self.is_owner_document_model():
kwargs_filters = self.kwargs.copy()
if self.user_is_self and is_authenticated:
kwargs_filters.pop('user_is_self', None)
kwargs_filters['user'] = username
else:
kwargs_filters = self.get_kwargs_filters()
if is_members_view:
kwargs_filters['ownerType'] = 'Organization'
kwargs_filters['owner'] = self.get_members_view_org_mnemonics() or ['UNKNOWN-ORG-DUMMY']
elif self.user_is_self and is_authenticated:
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = username

if self.is_url_registry_document() and not is_members_view:
kwargs_filters = self.kwargs.copy()
if self.user_is_self and is_authenticated:
kwargs_filters.pop('user_is_self', None)
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = username
elif not kwargs_filters:
kwargs_filters['ownerUrl'] = '/'
else:
if 'org' in kwargs_filters:
kwargs_filters['ownerType'] = 'Organization'
kwargs_filters['owner'] = kwargs_filters.pop('org')
elif 'user' in kwargs_filters:
kwargs_filters['ownerType'] = 'User'
kwargs_filters['owner'] = kwargs_filters.pop('user')

for key, value in kwargs_filters.items():
attr = to_snake_case(key)
if isinstance(value, list):
criteria = Q('term', **{attr: get(value, '0')})
for val in value[1:]:
criteria |= Q('term', **{attr: val})
results = results.filter(criteria)
else:
results = results.filter('term', **{attr: value})
results = self.__apply_scope_filters(results)

sort_attrs = self._get_sort_attribute()
if has_search_string and self.is_concept_document() and (
Expand Down
Loading
Loading