Coverage for src / comments_views / core / utils.py: 91%
140 statements
« prev ^ index » next coverage.py v7.13.2, created at 2026-10-20 06:13 +0000
« prev ^ index » next coverage.py v7.13.2, created at 2026-10-20 06:13 +0000
1from json import JSONDecodeError
2from urllib.parse import urlencode
4import requests
5from django.conf import settings
6from django.contrib import messages
7from django.contrib.auth import get_user_model
8from django.http import HttpRequest
9from django.urls import reverse
10from django.utils.translation import gettext_lazy as _
11from requests import RequestException, Response
13from comments_api.constants import API_MESSAGE_KEY
14from comments_api.utils import parse_date
16from .app_settings import app_settings
17from .rights import AbstractUserRights
19# Default timeout (seconds) to be used when performing API requests.
20DEFAULT_TIMEOUT = 4
21DEFAULT_API_ERROR_MESSAGE = _("Error: Something went wrong. Please try again.")
24def comments_server_base_url() -> str:
25 """
26 Returns the base URL of the comment server as defined in settings.py.
27 Fallbacks to https://comments.centre-mersenne.org
28 """
29 comment_base_url = app_settings.API_BASE_URL
31 # Remove trailing slash
32 if comment_base_url[-1] == "/":
33 comment_base_url = comment_base_url[:-1]
34 return comment_base_url
37def comments_server_url(
38 query_params: dict[str, str] | None = None, url_prefix="comments", item_id=None
39) -> str:
40 """
41 Returns a formatted URL to query the comment server (API).
42 The default URL corresponds to the list of all available comments.
44 Parameters:
45 - `query_params`: A dictionnary of query parameters to be appended to the URL.
46 They are used to precisely filter the comment dataset.
47 - `comment_id`: Filters on the given comment ID
48 """
49 if query_params is None:
50 query_params = {}
51 base_url = f"{comments_server_base_url()}/api/{url_prefix}/"
52 if item_id:
53 base_url += f"{item_id}/"
54 if query_params:
55 base_url += f"?{urlencode(query_params)}"
56 return base_url
59def comments_credentials() -> tuple[str, str]:
60 """
61 Returns the current server credentials (login, password) required to authenticate
62 on the comment server.
63 """
64 credentials = app_settings.API_CREDENTIALS
65 if credentials:
66 assert isinstance(credentials, tuple) and len(credentials) == 2, (
67 "The server has malformed comments server credentials."
68 "Please provide them as `(login, password)`"
69 )
71 return credentials
73 raise AttributeError("The server is missing the comments server credentials")
76def add_api_error_message(initial_message: str, api_json_data: dict) -> str:
77 """Adds the API error description to the given string."""
78 formatted_message = initial_message
79 api_error = api_json_data.get(API_MESSAGE_KEY)
80 if api_error and isinstance(api_error, str):
81 formatted_message = f"{formatted_message}<br><br>" if formatted_message else ""
82 formatted_message += f'"{api_error}"'
84 return formatted_message
87def json_from_response(
88 response: Response, request_for_message: HttpRequest | None = None
89) -> tuple[bool, dict]:
90 """
91 Returns the JSON content of a HTTP response and whether an exception was raised
92 while doing so.
93 We consider that there's an exception if the response does not contain correctly
94 formed JSON (except HTTP 204) or if its status code >= 300.
96 Params:
97 - `response` The HTTP response to parse.
98 - `request_for_message` The current HTTP request handled by Django. Used
99 to add a message (Django) when there's an exception.
100 Don't provide it if you don't want any messages.
102 Returns:
103 - `error` Whether an exception was raised.
104 - `content` The JSON content of the HTTP response.
105 """
106 try:
107 data = response.json()
108 except JSONDecodeError:
109 # 204 No Content
110 if response.status_code == 204:
111 return (False, {})
112 if request_for_message is not None:
113 messages.error(request_for_message, DEFAULT_API_ERROR_MESSAGE)
114 return (True, {})
116 error = False
117 if response.status_code >= 300:
118 if request_for_message is not None:
119 error_message = add_api_error_message(DEFAULT_API_ERROR_MESSAGE, data)
120 messages.error(request_for_message, error_message)
121 error = True
122 return (error, data)
125def format_comment_author_name(comment: dict) -> str:
126 """
127 Formats an author name according to the comments properties.
128 """
129 author_name = comment.get("author_name", "")
131 hide_name = comment.get("hide_author_name")
132 article_author = comment.get("article_author_comment")
133 editorial_team = comment.get("editorial_team_comment")
134 extra_text = ""
136 if article_author:
137 if hide_name:
138 return _("Auteur(s) de l'article").capitalize()
139 extra_text = _("Auteur de l'article")
140 elif editorial_team:
141 extra_text = _("Équipe éditoriale")
142 if hide_name:
143 return extra_text.capitalize()
145 if not extra_text:
146 return author_name
148 return f"{author_name} ({extra_text.lower()})"
151def format_comment(
152 comment: dict, rights: AbstractUserRights | None = None, users: dict | None = None
153) -> None:
154 """
155 Format a comment data for display.
156 Formatted data includes:
157 - author display name (actual name or function)
158 - Moderation data (only if `users is provided`)
159 - comment URL
161 Params:
162 - `comment` The comment data (usually a dict constructed from
163 the JSON data).
164 - `rights` The user rights used to check access over moderation data.
165 - `users` The dictionnary of users used to map moderator IDs
166 """
167 # Format author name and parent author name
168 if users is None: 168 ↛ 170line 168 didn't jump to line 170 because the condition on line 168 was always true
169 users = {}
170 comment["author_display_name"] = format_comment_author_name(comment)
172 parent = comment.get("parent")
173 # The comment data may contain either the parent dictionnary data or
174 # just the parent ID
175 if parent and isinstance(parent, dict):
176 comment["parent"]["author_display_name"] = format_comment_author_name(parent)
178 # Format author provider link (only ORCID right now)
179 author_provider = comment.get("author_provider")
180 author_provider_uid = comment.get("author_provider_uid")
181 if author_provider and author_provider.lower() == "orcid" and author_provider_uid: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true
182 comment["author_provider_link"] = f"{app_settings.ORCID_BASE_URL}{author_provider_uid}/"
184 # Parse dates for display
185 date_submitted = comment.get("date_submitted")
186 if date_submitted: 186 ↛ 189line 186 didn't jump to line 189 because the condition on line 186 was always true
187 comment["date_submitted"] = parse_date(date_submitted)
189 moderation_data = comment.get("moderation_data")
190 if moderation_data: 190 ↛ 209line 190 didn't jump to line 209 because the condition on line 190 was always true
191 if moderation_data.get("date_moderated"): 191 ↛ 196line 191 didn't jump to line 196 because the condition on line 191 was always true
192 comment["moderation_data"]["date_moderated"] = parse_date(
193 moderation_data.get("date_moderated")
194 )
196 moderator_id = moderation_data.get("moderator")
197 if ( 197 ↛ 206line 197 didn't jump to line 206 because the condition on line 197 was never true
198 moderator_id
199 and moderator_id in users
200 and rights
201 and (
202 rights.comment_can_manage_moderators(comment)
203 or getattr(rights.user, "is_superuser", False)
204 )
205 ):
206 comment["moderation_data"]["moderated_by"] = users[moderator_id]
208 # Format comment link
209 base_url = comment.get("base_url")
210 if base_url: 210 ↛ 223line 210 didn't jump to line 223 because the condition on line 210 was always true
211 # Remove potential trailing slash
212 if base_url[-1] == "/":
213 base_url = base_url[:-1]
214 article_route = reverse("article", kwargs={"aid": comment["doi"]})
215 # If a site has an URL prefix, we need to discard it from the article_route,
216 # it should already be present in base_url.
217 url_prefix = getattr(settings, "SITE_URL_PREFIX", None)
218 if url_prefix: 218 ↛ 221line 218 didn't jump to line 221 because the condition on line 218 was always true
219 url_prefix = f"/{url_prefix}"
220 article_route = article_route.removeprefix(url_prefix)
221 comment["base_url"] = f"{base_url}{article_route}"
223 if rights: 223 ↛ 224line 223 didn't jump to line 224 because the condition on line 223 was never true
224 comment["can_moderate"] = rights.comment_can_moderate(comment)
226 # Get the moderators
227 if rights and users: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 moderators = comment.get("moderators")
229 if moderators and (
230 rights.comment_can_manage_moderators(comment)
231 or getattr(rights.user, "is_superuser", False)
232 ):
233 comment["moderators_processed"] = {
234 moderator_id: users[moderator_id]
235 for moderator_id in moderators
236 if moderator_id in users
237 }
240def get_user_dict() -> dict[int, dict[str, str]]:
241 """
242 Return a dict of users indexed by the user's pk.
243 A value is a dict of the user's `pk`, `first_name`, `last_name` and `email`
244 """
245 users = get_user_model().objects.all().values("pk", "first_name", "last_name", "email")
246 return {u["pk"]: u for u in users}
249def api_request_wrapper(http_method: str, url: str, **kwargs) -> Response | None:
250 """
251 Light wrapper around `get`, `post`, and `put` methods of the `requests` library:
252 - Catch any `RequestException`.
253 - Add a default timeout to the request if no `timeout` was provided.
255 Params:
256 - `http_method` The HTTP method to use for the request
257 (get, post, put, head or delete).
259 Returns:
260 - `response` The `Response` object if no `RequestException` was raised,
261 else `None`.
262 """
263 if "timeout" not in kwargs: 263 ↛ 266line 263 didn't jump to line 266 because the condition on line 263 was always true
264 # (connect timeout, read timeout)
265 kwargs["timeout"] = (4, 7)
266 http_method = http_method.upper()
267 try:
268 if http_method == "GET":
269 response = requests.get(url, **kwargs)
270 elif http_method == "POST":
271 response = requests.post(url, **kwargs)
272 elif http_method == "PUT":
273 response = requests.put(url, **kwargs)
274 # Other HTTP methods are not used. They can be added above
275 # The timeout kwarg is only available for HEAD and DELETE
276 else:
277 raise ValueError(f"Wrong argument for 'http_method': '{http_method}'")
278 except RequestException:
279 response = None
281 return response
284def make_api_request(
285 http_method: str, url: str, request_for_message: HttpRequest | None = None, **kwargs
286) -> tuple[bool, dict]:
287 """
288 Performs the HTTP request to the provided URL and return whether an exception was
289 raised and the JSON content of the response. \\
290 Catched exceptions are any `RequestException` or `JSONDecodeError`. \\
291 Any additional kwargs are passed directly to the `requests` library.
293 Params:
294 - `http_method` The HTTP method to use for the request
295 (get, post, put, head or delete).
296 - `url` The URL to request.
297 - `request_for_message` The current HTTP request handled by Django. Used
298 to add a message (Django) when there's an exception.
299 Don't provide it if you don't want any messages.
301 Returns:
302 - `error` Whether an exception was raised.
303 - `content` The JSON content of the HTTP response.
304 """
305 response = api_request_wrapper(http_method, url, **kwargs)
307 if response is None:
308 if request_for_message is not None:
309 messages.error(request_for_message, DEFAULT_API_ERROR_MESSAGE)
310 return True, {}
312 return json_from_response(response, request_for_message)
315def get_comment(
316 query_params: dict[str, str],
317 id: int,
318 request_for_message: HttpRequest | None = None,
319) -> tuple[bool, dict]:
320 """
321 Make an HTTP request to retrieve the requested comment. Commodity wrapper
322 around `make_api_request`.
324 Params:
325 - `query_params` Query parameters for the API URL.
326 - `id` The comment's ID.
327 - `request_for_message` The current HTTP request handled by Django. Used
328 to add a message (Django) when there's an exception.
329 Don't provide it if you don't want any messages.
331 Returns:
332 - `error` Whether an exception was raised.
333 - `content` The JSON content of the HTTP response.
334 """
335 return make_api_request(
336 "GET",
337 comments_server_url(query_params, item_id=id),
338 request_for_message,
339 auth=comments_credentials(),
340 )