Coverage for src/comments_moderation/utils.py: 99%
127 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-26 08:43 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-26 08:43 +0000
1from itertools import chain
3from comments_api.constants import (
4 PARAM_ACTION,
5 PARAM_ACTION_CREATE,
6 PARAM_COMMENT,
7 PARAM_MODERATOR,
8 STATUS_SUBMITTED,
9)
10from comments_views.core.rights import AbstractUserRights
11from comments_views.core.utils import (
12 comments_credentials,
13 comments_server_url,
14 format_comment,
15 get_comment,
16 get_user_dict,
17 make_api_request,
18)
19from django.contrib import messages
20from django.contrib.auth.models import User
21from django.db.models import Q
22from django.http import HttpRequest
23from django.urls import reverse
24from ptf.model_helpers import get_article_by_doi
25from ptf.models import Collection
26from ptf.utils import send_email_from_template
28from ptf_tools.models import Invitation, InvitationExtraData
30from .rights import ModeratorUserRights
33def is_comment_moderator(user: User) -> bool:
34 """Whether the user is a comment moderator."""
35 return hasattr(user, "comment_moderator") and user.comment_moderator.is_moderator
38def update_moderation_right(
39 comment_id: int,
40 moderators: int | str,
41 rights: AbstractUserRights,
42 action: str = PARAM_ACTION_CREATE,
43 request_for_message: HttpRequest | None = None,
44) -> tuple[bool, dict]:
45 """
46 Makes a POST request to the comment server to create a new moderation entry or
47 delete an existing one.
48 """
49 post_data = {PARAM_COMMENT: comment_id, PARAM_MODERATOR: moderators}
50 query_params = rights.comment_rights_query_params()
51 query_params[PARAM_ACTION] = action
52 return make_api_request(
53 "POST",
54 comments_server_url(query_params, "moderators"),
55 request_for_message=request_for_message,
56 auth=comments_credentials(),
57 json=post_data,
58 timeout=4,
59 )
62def get_all_moderators(rights: AbstractUserRights, request: HttpRequest):
63 """
64 Gets all the existing moderators available to the given rights.
66 Returns:
67 - all_moderators: The queryset of all available moderators.
68 - moderation_rights: The moderation rights from the comment server.
69 """
70 query_params = rights.comment_rights_query_params()
72 error, moderation_rights = make_api_request(
73 "GET",
74 comments_server_url(query_params, "moderators"),
75 request_for_message=request,
76 auth=comments_credentials(),
77 )
79 base_moderators = []
80 if error:
81 moderation_rights = []
82 else:
83 # mod_right struct: {"moderator_id": x, "comment_id": x, "comment__status": x}
84 base_moderators = [m["moderator_id"] for m in moderation_rights]
86 user_collections = rights.get_user_admin_collections() + rights.get_user_staff_collections()
88 # Remove duplicates
89 user_collections = set(user_collections)
90 base_moderators = set(base_moderators)
92 moderator_filter = Q(comment_moderator__is_moderator=True) & (
93 Q(comment_moderator__collections__pid__in=user_collections) | Q(pk__in=base_moderators)
94 )
96 all_moderators = (
97 User.objects.prefetch_related("comment_moderator", "comment_moderator__collections")
98 .filter(moderator_filter)
99 .distinct()
100 .order_by("first_name", "pk")
101 )
103 return all_moderators, moderation_rights
106def update_moderator_collections(
107 rights: AbstractUserRights,
108 moderator: User,
109 collections_to_add: list[str] | None = None,
110 collections_to_delete: list[str] | None = None,
111):
112 """
113 Updates a moderator's attached collections.
114 The modified collections are limited to the rights's admin collections.
116 Params:
117 - rights: the rights of the user updating the moderator's
118 collections
119 - moderator: the moderator
120 - collections_to_add: the PIDs of the collections to add
121 - collections_to_delete: the PIDs of the collections to delete
123 """
124 if collections_to_delete is None:
125 collections_to_delete = []
126 if collections_to_add is None:
127 collections_to_add = []
128 if not is_comment_moderator(moderator) or not rights.is_admin_moderator():
129 return
131 user_collections = rights.get_user_admin_collections()
132 collections = Collection.objects.all().values("pk", "pid")
133 collections_to_delete = [
134 c["pk"]
135 for c in collections
136 if (c["pid"] in collections_to_delete and c["pid"] in user_collections)
137 ]
138 if collections_to_delete:
139 moderator.comment_moderator.collections.remove(*collections_to_delete)
141 collections_to_add = [
142 c["pk"]
143 for c in collections
144 if (c["pid"] in collections_to_add and c["pid"] in user_collections)
145 ]
146 if collections_to_add:
147 moderator.comment_moderator.collections.add(*collections_to_add)
150def merge_dict(existing: dict, update: dict):
151 """
152 Recursively merges 2 dicts by creating potential missing keys.
153 When a key is common between the 2 dicts:
154 - If the value is a dict: recursive call to merge_dict
155 - If the value is a list: the 2 lists are concatenated
156 TODO: what if list of dict/list ?
157 - If the value is something else: the value of the update overwrites the
158 existing one.
159 """
160 for k, update_v in update.items():
161 existing_v = existing.get(k)
163 if isinstance(update_v, dict):
164 if not existing_v:
165 existing_v = {}
166 elif existing_v and not isinstance(existing_v, dict):
167 raise TypeError("Cannot merge dict and non-dict objects.")
168 existing[k] = merge_dict(existing_v, update_v) if existing_v else update_v
170 elif isinstance(update_v, list):
171 if not existing_v:
172 existing_v = []
173 elif existing_v and not isinstance(existing_v, list):
174 raise TypeError("Cannot merge list and non-list objects.")
175 existing[k] = existing_v + update_v
177 else:
178 if isinstance(existing_v, dict):
179 raise TypeError("Cannot merge dict and non-dict objects.")
180 if isinstance(existing_v, list):
181 raise TypeError("Cannot merge list and non-list objects.")
182 existing[k] = update_v
184 return existing
187def get_comment_and_can_manage_moderators(
188 request: HttpRequest, rights: AbstractUserRights, comment_id: int
189) -> tuple[bool, dict]:
190 """
191 GET the requested comment and check the given rights allow moderator management.
192 Adds a message to the request if an error occurs of if the rights are insufficient.
193 """
194 error, comment = get_comment(
195 rights.comment_rights_query_params(), comment_id, request_for_message=request
196 )
197 if error:
198 return True, {}
200 users = get_user_dict()
202 format_comment(comment, rights, users)
203 if not rights.comment_can_manage_moderators(comment) or comment["status"] != STATUS_SUBMITTED:
204 messages.error(
205 request,
206 "Error: You don't have enough rights to manage the moderators of the given comment.",
207 )
208 return True, {}
210 return False, comment
213def email_moderator_assigned(request: HttpRequest, moderator: User, comment: dict):
214 """
215 Send the "Comment moderation request" mail to the provided moderator.
216 Add messages to the provided request.
217 """
218 messages.success(
219 request,
220 f"The moderator {moderator.first_name} {moderator.last_name} "
221 "has been assigned to the comment.",
222 )
223 # Send an e-mail to the moderator assigned to the comment -
224 # TODO: Maybe this should be done few times a day by a cron
225 # to avoid too many e-mails?
226 article = get_article_by_doi(comment["doi"])
227 if not article:
228 messages.warning(
229 request,
230 "The comment's article was not found on Trammel. "
231 + "No e-mail was sent to the moderator.",
232 )
233 return
235 article_title = article.title_tex if article else ""
236 context_data = {
237 "full_name": f"{moderator.first_name} {moderator.last_name}",
238 "inviter_name": f"{request.user.first_name} {request.user.last_name}",
239 "article_url": comment.get("base_url"),
240 "article_title": article_title,
241 "comment_dashboard_url": request.build_absolute_uri(reverse("comment_list")),
242 "email_signature": "The editorial team",
243 }
244 subject = f"[{comment['site_name'].upper()}] Comment moderation request"
245 send_email_from_template(
246 "mail/comment_moderator_assigned.html",
247 context_data,
248 subject,
249 to=[moderator.email],
250 from_collection=comment["site_name"],
251 )
254def get_comments_for_home(user: User) -> tuple[bool, dict]:
255 """
256 Query the comments server to get the summary of the comments data per collection.
258 Returns:
259 - `error` Whether the HTTP query was successful
260 - `data` The processed comments summary:
261 `
262 {
263 "COLID": submitted_comments_nb
264 }
265 `
267 There is no entry for a collection without any comments.
268 """
269 rights = ModeratorUserRights(user)
270 query_params = rights.comment_rights_query_params()
272 error, comments_summary = make_api_request(
273 "GET", comments_server_url(query_params, "comments-summary"), auth=comments_credentials()
274 )
275 if error:
276 return True, {}
278 data = {}
279 for col_id, col_data in comments_summary.items():
280 data[col_id] = col_data.get(STATUS_SUBMITTED, 0)
282 return False, data
285def get_pending_invitations(rights: AbstractUserRights) -> list:
286 """
287 Returns the list of pending invitations to comment moderators available to the
288 given user rights.
289 """
290 pending_invites = Invitation.objects.filter(accepted=False, extra_data__has_key="moderator")
291 invites = []
292 for invite in pending_invites:
293 collections_to_add = []
294 extra_data = InvitationExtraData(**invite.extra_data)
296 # Get all collections matching the user_collections
297 if rights.user.is_superuser: 297 ↛ 298line 297 didn't jump to line 298 because the condition on line 297 was never true
298 collections_to_add = chain.from_iterable(
299 c.pid for c in extra_data.moderator.collections
300 )
301 elif rights.is_admin_moderator():
302 collections = chain.from_iterable(c.pid for c in extra_data.moderator.collections)
303 collections_to_add = [
304 c for c in collections if c in rights.get_user_admin_collections()
305 ]
307 # Get all comments whose collection matches the user_collections
308 comments_to_add = []
309 user_collections = (
310 rights.get_user_admin_collections() or rights.get_user_staff_collections()
311 )
312 for comment in extra_data.moderator.comments:
313 if rights.user.is_superuser or comment.pid in user_collections:
314 comments_to_add.append(comment.id)
316 if collections_to_add or comments_to_add:
317 invites.append(
318 {
319 "name": f"{invite.first_name} {invite.last_name}",
320 "email": invite.email,
321 "sent": invite.sent,
322 "date_expired": invite.date_expired(),
323 "key_expired": invite.key_expired(),
324 "collections": collections_to_add,
325 "comments": comments_to_add,
326 }
327 )
329 return invites
332def get_comment_pending_invitations(comment_id: int) -> list:
333 """
334 Returns the invitations linked to the given comment ID.
335 """
336 # Not working on CI with SQLite DB backend.
337 # return Invitation.objects.filter(
338 # accepted=False,
339 # extra_data__moderator__comments__contains=[{"id": comment_id}]
340 # )
341 base_invites = Invitation.objects.filter(
342 accepted=False, extra_data__moderator__has_key="comments"
343 )
344 invites = []
345 for invite in base_invites:
346 extra_data = InvitationExtraData(**invite.extra_data)
347 if any(c.id == comment_id for c in extra_data.moderator.comments):
348 invites.append(invite)
350 return invites