/
search_content_ajax.py
218 lines (187 loc) · 6.93 KB
/
search_content_ajax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from ...constants import status
from ...models import (
Directory,
EventTranslation,
Feedback,
MediaFile,
POITranslation,
PushNotificationTranslation,
Region,
)
from ...utils.user_utils import search_users
if TYPE_CHECKING:
from typing import Any, Literal
from django.http import HttpRequest
from ...models.abstract_content_translation import AbstractContentTranslation
logger = logging.getLogger(__name__)
# The maximum number of results returned by `search_content_ajax`
MAX_RESULT_COUNT: int = 20
def format_object_translation(
object_translation: AbstractContentTranslation, typ: Literal["page", "event", "poi"]
) -> dict:
"""
Formats the [poi/event/page]-translation as json
:param object_translation: A translation object which has a title and a permalink
:param typ: The type of this object
:return: A dictionary with the title, path, url and type of the translation object
"""
return {
"title": object_translation.title,
"path": object_translation.path(),
"url": f"{settings.WEBAPP_URL}{object_translation.get_absolute_url()}",
"type": typ,
}
@require_POST
# pylint: disable=unused-argument,too-many-branches,too-many-statements
def search_content_ajax(
request: HttpRequest,
region_slug: str | None = None,
language_slug: str | None = None,
) -> JsonResponse:
"""Searches all pois, events and pages for the current region and returns all that
match the search query. Results which match the query in the title or slug get ranked
higher than results which only match through their text content.
:param request: The current request
:param region_slug: The slug of the current region
:param language_slug: language slug
:type language_slug: str
:raises ~django.core.exceptions.PermissionDenied: If the user has no permission to the object type
:raises AttributeError: If the request contains an object type which is unknown or if the user has no permission for it
:return: Json object containing all matching elements, of shape {title: str, url: str, type: str}
"""
region = request.region
body = json.loads(request.body.decode("utf-8"))
query = body["query_string"]
# whether to return only archived object, ignored if not applicable
archived_flag = body["archived"]
object_types = set(body.get("object_types", []))
logger.debug("Ajax call: Live search for %r with query %r", object_types, query)
results: list[dict[str, Any]] = []
user = request.user
if "event" in object_types:
if TYPE_CHECKING:
assert language_slug
object_types.remove("event")
if not user.has_perm("cms.view_event"):
raise PermissionDenied
event_translations = (
EventTranslation.search(region, language_slug, query)
.filter(event__archived=archived_flag, status=status.PUBLIC)
.select_related("event__region", "language")
)
results.extend(
format_object_translation(obj, "event") for obj in event_translations
)
if "feedback" in object_types:
object_types.remove("feedback")
if not user.has_perm("cms.view_feedback"):
raise PermissionDenied
results.extend(
{
"title": feedback.comment,
"url": None,
"type": "feedback",
}
for feedback in Feedback.search(region, query).filter(
archived=archived_flag
)
)
if "page" in object_types:
if TYPE_CHECKING:
assert language_slug
object_types.remove("page")
if not user.has_perm("cms.view_page"):
raise PermissionDenied
pages = region.pages.all().cache_tree(archived=archived_flag)
for page in pages:
page_translation = page.get_translation(language_slug)
if page_translation and (
query.lower() in page_translation.slug
or query.lower() in page_translation.title.lower()
):
results.append(format_object_translation(page_translation, "page"))
if "poi" in object_types:
if TYPE_CHECKING:
assert language_slug
object_types.remove("poi")
if not user.has_perm("cms.view_poi"):
raise PermissionDenied
poi_translations = (
POITranslation.search(region, language_slug, query)
.filter(poi__archived=archived_flag, status=status.PUBLIC)
.select_related("poi__region", "language")
)
results.extend(
format_object_translation(obj, "poi") for obj in poi_translations
)
if "push_notification" in object_types:
if TYPE_CHECKING:
assert language_slug
object_types.remove("push_notification")
if not user.has_perm("cms.view_pushnotification"):
raise PermissionDenied
results.extend(
{
"title": push_notification.title,
"url": None,
"type": "push_notification",
}
for push_notification in PushNotificationTranslation.search(
region, language_slug, query
)
)
if "region" in object_types:
object_types.remove("region")
if not user.has_perm("cms.view_region"):
raise PermissionDenied
results.extend(
{
"title": region.name,
"url": None,
"type": "region",
}
for region in Region.search(query)
)
if "user" in object_types:
object_types.remove("user")
if not user.has_perm("cms.view_user"):
raise PermissionDenied
results.extend(
{
"title": user.username,
"url": None,
"type": "user",
}
for user in search_users(region, query)
)
if "media" in object_types:
object_types.remove("media")
results.extend(
{
"title": file.name,
"url": None,
"type": "file",
}
for file in MediaFile.search(region, query)
)
results.extend(
{
"title": directory.name,
"url": None,
"type": "directory",
}
for directory in Directory.search(region, query)
)
if object_types:
raise AttributeError(f"Unexpected object type(s): {object_types}")
# sort alphabetically by title
results.sort(key=lambda k: k["title"])
return JsonResponse({"data": results[:MAX_RESULT_COUNT]})