-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
api.py
1980 lines (1651 loc) · 71.9 KB
/
api.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Discussion API internal interface
"""
from __future__ import annotations
import itertools
import re
from collections import defaultdict
from datetime import datetime
from enum import Enum
from typing import Dict, Iterable, List, Literal, Optional, Set, Tuple
from urllib.parse import urlencode, urlunparse
from pytz import UTC
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.http import Http404
from django.urls import reverse
from edx_django_utils.monitoring import function_trace
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locator import CourseKey
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
from common.djangoapps.student.roles import (
CourseInstructorRole,
CourseStaffRole,
)
from lms.djangoapps.course_api.blocks.api import get_blocks
from lms.djangoapps.courseware.courses import get_course_with_access
from lms.djangoapps.courseware.exceptions import CourseAccessRedirect
from lms.djangoapps.discussion.toggles import ENABLE_DISCUSSIONS_MFE
from lms.djangoapps.discussion.views import is_privileged_user
from openedx.core.djangoapps.discussions.models import (
DiscussionsConfiguration,
DiscussionTopicLink,
Provider,
)
from openedx.core.djangoapps.discussions.utils import get_accessible_discussion_xblocks
from openedx.core.djangoapps.django_comment_common import comment_client
from openedx.core.djangoapps.django_comment_common.comment_client.comment import Comment
from openedx.core.djangoapps.django_comment_common.comment_client.course import (
get_course_commentable_counts,
get_course_user_stats
)
from openedx.core.djangoapps.django_comment_common.comment_client.thread import Thread
from openedx.core.djangoapps.django_comment_common.comment_client.utils import (
CommentClient500Error,
CommentClientRequestError
)
from openedx.core.djangoapps.django_comment_common.models import (
FORUM_ROLE_ADMINISTRATOR,
FORUM_ROLE_COMMUNITY_TA,
FORUM_ROLE_GROUP_MODERATOR,
FORUM_ROLE_MODERATOR,
CourseDiscussionSettings,
Role
)
from openedx.core.djangoapps.django_comment_common.signals import (
comment_created,
comment_deleted,
comment_endorsed,
comment_edited,
comment_flagged,
comment_voted,
thread_created,
thread_deleted,
thread_edited,
thread_flagged,
thread_followed,
thread_voted,
thread_unfollowed
)
from openedx.core.djangoapps.user_api.accounts.api import get_account_settings
from openedx.core.lib.exceptions import CourseNotFoundError, DiscussionNotFoundError, PageNotFoundError
from xmodule.course_block import CourseBlock
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.tabs import CourseTabList
from ..django_comment_client.base.views import (
track_comment_created_event,
track_comment_deleted_event,
track_thread_created_event,
track_thread_deleted_event,
track_thread_viewed_event,
track_voted_event,
track_discussion_reported_event,
track_discussion_unreported_event,
track_forum_search_event, track_thread_followed_event
)
from ..django_comment_client.utils import (
get_group_id_for_user,
get_user_role_names,
has_discussion_privileges,
is_commentable_divided
)
from .exceptions import CommentNotFoundError, DiscussionBlackOutException, DiscussionDisabledError, ThreadNotFoundError
from .forms import CommentActionsForm, ThreadActionsForm, UserOrdering
from .pagination import DiscussionAPIPagination
from .permissions import (
can_delete,
get_editable_fields,
get_initializable_comment_fields,
get_initializable_thread_fields
)
from .serializers import (
CommentSerializer,
DiscussionTopicSerializer,
DiscussionTopicSerializerV2,
ThreadSerializer,
TopicOrdering,
UserStatsSerializer,
get_context
)
from .utils import (
AttributeDict,
add_stats_for_users_with_no_discussion_content,
create_blocks_params,
discussion_open_for_user,
get_usernames_for_course,
get_usernames_from_search_string,
set_attribute,
is_posting_allowed
)
User = get_user_model()
ThreadType = Literal["discussion", "question"]
ViewType = Literal["unread", "unanswered"]
ThreadOrderingType = Literal["last_activity_at", "comment_count", "vote_count"]
class DiscussionTopic:
"""
Class for discussion topic structure
"""
def __init__(
self,
topic_id: Optional[str],
name: str,
thread_list_url: str,
children: Optional[List[DiscussionTopic]] = None,
thread_counts: Dict[str, int] = None,
):
self.id = topic_id # pylint: disable=invalid-name
self.name = name
self.thread_list_url = thread_list_url
self.children = children or [] # children are of same type i.e. DiscussionTopic
if not children and not thread_counts:
thread_counts = {"discussion": 0, "question": 0}
self.thread_counts = thread_counts
class DiscussionEntity(Enum):
"""
Enum for different types of discussion related entities
"""
thread = 'thread'
comment = 'comment'
def _get_course(course_key: CourseKey, user: User, check_tab: bool = True) -> CourseBlock:
"""
Get the course block, raising CourseNotFoundError if the course is not found or
the user cannot access forums for the course, and DiscussionDisabledError if the
discussion tab is disabled for the course.
Using the ``check_tab`` parameter, tab checking can be skipped to perform other
access checks only.
Args:
course_key (CourseKey): course key of course to fetch
user (User): user for access checks
check_tab (bool): Whether the discussion tab should be checked
Returns:
CourseBlock: course object
"""
try:
course = get_course_with_access(user, 'load', course_key, check_if_enrolled=True)
except (Http404, CourseAccessRedirect) as err:
# Convert 404s into CourseNotFoundErrors.
# Raise course not found if the user cannot access the course
raise CourseNotFoundError("Course not found.") from err
if check_tab:
discussion_tab = CourseTabList.get_tab_by_type(course.tabs, 'discussion')
if not (discussion_tab and discussion_tab.is_enabled(course, user)):
raise DiscussionDisabledError("Discussion is disabled for the course.")
return course
def _get_thread_and_context(request, thread_id, retrieve_kwargs=None, course_id=None):
"""
Retrieve the given thread and build a serializer context for it, returning
both. This function also enforces access control for the thread (checking
both the user's access to the course and to the thread's cohort if
applicable). Raises ThreadNotFoundError if the thread does not exist or the
user cannot access it.
"""
retrieve_kwargs = retrieve_kwargs or {}
try:
if "with_responses" not in retrieve_kwargs:
retrieve_kwargs["with_responses"] = False
if "mark_as_read" not in retrieve_kwargs:
retrieve_kwargs["mark_as_read"] = False
cc_thread = Thread(id=thread_id).retrieve(course_id=course_id, **retrieve_kwargs)
course_key = CourseKey.from_string(cc_thread["course_id"])
course = _get_course(course_key, request.user)
context = get_context(course, request, cc_thread)
if retrieve_kwargs.get("flagged_comments") and not context["has_moderation_privilege"]:
raise ValidationError("Only privileged users can request flagged comments")
course_discussion_settings = CourseDiscussionSettings.get(course_key)
if (
not context["has_moderation_privilege"] and
cc_thread["group_id"] and
is_commentable_divided(course.id, cc_thread["commentable_id"], course_discussion_settings)
):
requester_group_id = get_group_id_for_user(request.user, course_discussion_settings)
if requester_group_id is not None and cc_thread["group_id"] != requester_group_id:
raise ThreadNotFoundError("Thread not found.")
return cc_thread, context
except CommentClientRequestError as err:
# params are validated at a higher level, so the only possible request
# error is if the thread doesn't exist
raise ThreadNotFoundError("Thread not found.") from err
def _get_comment_and_context(request, comment_id):
"""
Retrieve the given comment and build a serializer context for it, returning
both. This function also enforces access control for the comment (checking
both the user's access to the course and to the comment's thread's cohort if
applicable). Raises CommentNotFoundError if the comment does not exist or the
user cannot access it.
"""
try:
cc_comment = Comment(id=comment_id).retrieve()
_, context = _get_thread_and_context(request, cc_comment["thread_id"])
return cc_comment, context
except CommentClientRequestError as err:
raise CommentNotFoundError("Comment not found.") from err
def _is_user_author_or_privileged(cc_content, context):
"""
Check if the user is the author of a content object or a privileged user.
Returns:
Boolean
"""
return (
context["has_moderation_privilege"] or
context["cc_requester"]["id"] == cc_content["user_id"]
)
def get_thread_list_url(request, course_key, topic_id_list=None, following=False):
"""
Returns the URL for the thread_list_url field, given a list of topic_ids
"""
path = reverse("thread-list")
query_list = (
[("course_id", str(course_key))] +
[("topic_id", topic_id) for topic_id in topic_id_list or []] +
([("following", following)] if following else [])
)
return request.build_absolute_uri(urlunparse(("", "", path, "", urlencode(query_list), "")))
def get_course(request, course_key, check_tab=True):
"""
Return general discussion information for the course.
Parameters:
request: The django request object used for build_absolute_uri and
determining the requesting user.
course_key: The key of the course to get information for
check_tab: Whether to check if the discussion tab is enabled for the course
Returns:
The course information; see discussion.rest_api.views.CourseView for more
detail.
Raises:
CourseNotFoundError: if the course does not exist or is not accessible
to the requesting user
"""
def _format_datetime(dt):
"""
Provide backwards compatible datetime formatting.
Technically, both "2020-10-20T23:59:00Z" and "2020-10-20T23:59:00+00:00"
are ISO-8601 compliant, though the latter is preferred. We've always
just passed back whatever datetime.isoformat() generated for the
blackout dates in the get_course function (the "+00:00" format). At some
point, this broke the expectation of the mobile app code, which expects
these dates to be formatted in the same way that DRF formats the other
datetimes in this API (the "Z" format).
For the sake of compatibility, we're doing a manual substitution back to
the old format here. This is done with a replacement because it's
possible (though really not recommended) to enter blackout dates in
something other than the UTC timezone, in which case we should not do
the substitution... though really, that would probably break mobile
client parsing of the dates as well. :-P
"""
return dt.isoformat().replace('+00:00', 'Z')
course = _get_course(course_key, request.user, check_tab=check_tab)
user_roles = get_user_role_names(request.user, course_key)
course_config = DiscussionsConfiguration.get(course_key)
EDIT_REASON_CODES = getattr(settings, "DISCUSSION_MODERATION_EDIT_REASON_CODES", {})
CLOSE_REASON_CODES = getattr(settings, "DISCUSSION_MODERATION_CLOSE_REASON_CODES", {})
is_posting_enabled = is_posting_allowed(
course_config.posting_restrictions,
course.get_discussion_blackout_datetimes()
)
discussion_tab = CourseTabList.get_tab_by_type(course.tabs, 'discussion')
return {
"id": str(course_key),
"is_posting_enabled": is_posting_enabled,
"blackouts": [
{
"start": _format_datetime(blackout["start"]),
"end": _format_datetime(blackout["end"]),
}
for blackout in course.get_discussion_blackout_datetimes()
],
"thread_list_url": get_thread_list_url(request, course_key),
"following_thread_list_url": get_thread_list_url(request, course_key, following=True),
"topics_url": request.build_absolute_uri(
reverse("course_topics", kwargs={"course_id": course_key})
),
"allow_anonymous": course.allow_anonymous,
"allow_anonymous_to_peers": course.allow_anonymous_to_peers,
"user_roles": user_roles,
"has_moderation_privileges": bool(user_roles & {
FORUM_ROLE_ADMINISTRATOR,
FORUM_ROLE_MODERATOR,
FORUM_ROLE_COMMUNITY_TA,
}),
"is_group_ta": bool(user_roles & {FORUM_ROLE_GROUP_MODERATOR}),
"is_user_admin": request.user.is_staff,
"is_course_staff": CourseStaffRole(course_key).has_user(request.user),
"is_course_admin": CourseInstructorRole(course_key).has_user(request.user),
"provider": course_config.provider_type,
"enable_in_context": course_config.enable_in_context,
"group_at_subsection": course_config.plugin_configuration.get("group_at_subsection", False),
"edit_reasons": [
{"code": reason_code, "label": label}
for (reason_code, label) in EDIT_REASON_CODES.items()
],
"post_close_reasons": [
{"code": reason_code, "label": label}
for (reason_code, label) in CLOSE_REASON_CODES.items()
],
'show_discussions': bool(discussion_tab and discussion_tab.is_enabled(course, request.user)),
}
def get_courseware_topics(
request: Request,
course_key: CourseKey,
course: CourseBlock,
topic_ids: Optional[List[str]],
thread_counts: Dict[str, Dict[str, int]],
) -> Tuple[List[Dict], Set[str]]:
"""
Returns a list of topic trees for courseware-linked topics.
Parameters:
request: The django request objects used for build_absolute_uri.
course_key: The key of the course to get discussion threads for.
course: The course for which topics are requested.
topic_ids: A list of topic IDs for which details are requested.
This is optional. If None then all course topics are returned.
thread_counts: A map of the thread ids to the count of each type of thread in them
e.g. discussion, question
Returns:
A list of courseware topics and a set of existing topics among
topic_ids.
"""
courseware_topics = []
existing_topic_ids = set()
now = datetime.now(UTC)
discussion_xblocks = get_accessible_discussion_xblocks(course, request.user)
xblocks_by_category = defaultdict(list)
for xblock in discussion_xblocks:
if course.self_paced or (xblock.start and xblock.start < now):
xblocks_by_category[xblock.discussion_category].append(xblock)
def sort_categories(category_list):
"""
Sorts the given iterable containing alphanumeric correctly.
Required arguments:
category_list -- list of categories.
"""
def convert(text):
if text.isdigit():
return int(text)
return text
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(category_list, key=alphanum_key)
for category in sort_categories(xblocks_by_category.keys()):
children = []
for xblock in xblocks_by_category[category]:
if not topic_ids or xblock.discussion_id in topic_ids:
discussion_topic = DiscussionTopic(
xblock.discussion_id,
xblock.discussion_target,
get_thread_list_url(request, course_key, [xblock.discussion_id]),
None,
thread_counts.get(xblock.discussion_id),
)
children.append(discussion_topic)
if topic_ids and xblock.discussion_id in topic_ids:
existing_topic_ids.add(xblock.discussion_id)
if not topic_ids or children:
discussion_topic = DiscussionTopic(
None,
category,
get_thread_list_url(
request,
course_key,
[item.discussion_id for item in xblocks_by_category[category]],
),
children,
None,
)
courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data)
return courseware_topics, existing_topic_ids
def get_non_courseware_topics(
request: Request,
course_key: CourseKey,
course: CourseBlock,
topic_ids: Optional[List[str]],
thread_counts: Dict[str, Dict[str, int]]
) -> Tuple[List[Dict], Set[str]]:
"""
Returns a list of topic trees that are not linked to courseware.
Parameters:
request: The django request objects used for build_absolute_uri.
course_key: The key of the course to get discussion threads for.
course: The course for which topics are requested.
topic_ids: A list of topic IDs for which details are requested.
This is optional. If None then all course topics are returned.
thread_counts: A map of the thread ids to the count of each type of thread in them
e.g. discussion, question
Returns:
A list of non-courseware topics and a set of existing topics among
topic_ids.
"""
non_courseware_topics = []
existing_topic_ids = set()
topics = list(course.discussion_topics.items())
for name, entry in topics:
if not topic_ids or entry['id'] in topic_ids:
discussion_topic = DiscussionTopic(
entry["id"], name, get_thread_list_url(request, course_key, [entry["id"]]),
None,
thread_counts.get(entry["id"])
)
non_courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data)
if topic_ids and entry["id"] in topic_ids:
existing_topic_ids.add(entry["id"])
return non_courseware_topics, existing_topic_ids
def get_course_topics(request: Request, course_key: CourseKey, topic_ids: Optional[Set[str]] = None):
"""
Returns the course topic listing for the given course and user; filtered
by 'topic_ids' list if given.
Parameters:
course_key: The key of the course to get topics for
topic_ids: A list of topic IDs for which topic details are requested
Returns:
A course topic listing dictionary; see discussion.rest_api.views.CourseTopicViews
for more detail.
Raises:
DiscussionNotFoundError: If topic/s not found for given topic_ids.
"""
course = _get_course(course_key, request.user)
thread_counts = get_course_commentable_counts(course.id)
courseware_topics, existing_courseware_topic_ids = get_courseware_topics(
request, course_key, course, topic_ids, thread_counts
)
non_courseware_topics, existing_non_courseware_topic_ids = get_non_courseware_topics(
request, course_key, course, topic_ids, thread_counts,
)
if topic_ids:
not_found_topic_ids = topic_ids - (existing_courseware_topic_ids | existing_non_courseware_topic_ids)
if not_found_topic_ids:
raise DiscussionNotFoundError(
"Discussion not found for '{}'.".format(", ".join(str(id) for id in not_found_topic_ids))
)
return {
"courseware_topics": courseware_topics,
"non_courseware_topics": non_courseware_topics,
}
def get_v2_non_courseware_topics_as_v1(request, course_key, topics):
"""
Takes v2 topics list and returns v1 list of non courseware topics
"""
non_courseware_topics = []
for topic in topics:
if topic.get('usage_key', '') is None:
for key in ['usage_key', 'enabled_in_context']:
topic.pop(key)
topic.update({
'children': [],
'thread_list_url': get_thread_list_url(
request,
course_key,
topic.get('id'),
)
})
non_courseware_topics.append(topic)
return non_courseware_topics
def get_v2_courseware_topics_as_v1(request, course_key, sequentials, topics):
"""
Returns v2 courseware topics list as v1 structure
"""
courseware_topics = []
for sequential in sequentials:
children = []
for child in sequential.get('children', []):
for topic in topics:
if child == topic.get('usage_key'):
topic.update({
'children': [],
'thread_list_url': get_thread_list_url(
request,
course_key,
[topic.get('id')],
)
})
topic.pop('enabled_in_context')
children.append(AttributeDict(topic))
discussion_topic = DiscussionTopic(
None,
sequential.get('display_name'),
get_thread_list_url(
request,
course_key,
[child.id for child in children],
),
children,
None,
)
courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data)
courseware_topics = [
courseware_topic
for courseware_topic in courseware_topics
if courseware_topic.get('children', [])
]
return courseware_topics
def get_v2_course_topics_as_v1(
request: Request,
course_key: CourseKey,
topic_ids: Optional[Iterable[str]] = None,
):
"""
Returns v2 topics in v1 structure
"""
course_usage_key = modulestore().make_course_usage_key(course_key)
blocks_params = create_blocks_params(course_usage_key, request.user)
blocks = get_blocks(
request,
blocks_params['usage_key'],
blocks_params['user'],
blocks_params['depth'],
blocks_params['nav_depth'],
blocks_params['requested_fields'],
blocks_params['block_counts'],
blocks_params['student_view_data'],
blocks_params['return_type'],
blocks_params['block_types_filter'],
hide_access_denials=False,
)['blocks']
sequentials = [value for _, value in blocks.items()
if value.get('type') == "sequential"]
topics = get_course_topics_v2(course_key, request.user, topic_ids)
non_courseware_topics = get_v2_non_courseware_topics_as_v1(
request,
course_key,
topics,
)
courseware_topics = get_v2_courseware_topics_as_v1(
request,
course_key,
sequentials,
topics,
)
return {
"courseware_topics": courseware_topics,
"non_courseware_topics": non_courseware_topics,
}
def get_course_topics_v2(
course_key: CourseKey,
user: User,
topic_ids: Optional[Iterable[str]] = None,
order_by: TopicOrdering = TopicOrdering.COURSE_STRUCTURE,
) -> List[Dict]:
"""
Returns the course topic listing for the given course and user; filtered
by 'topic_ids' list if given.
Parameters:
course_key: The key of the course to get topics for
user: The requesting user, for access control
topic_ids: A list of topic IDs for which topic details are requested
order_by: The sort ordering for the returned list of topics
Returns:
A list of discussion topics for the course.
Raises:
ValidationError: If unsupported ordering is used.
"""
provider_type = DiscussionsConfiguration.get(context_key=course_key).provider_type
if provider_type in [Provider.OPEN_EDX, Provider.LEGACY]:
thread_counts = get_course_commentable_counts(course_key)
else:
thread_counts = {}
# For other providers we can't sort by activity since we don't have activity information.
if order_by == TopicOrdering.ACTIVITY:
raise ValidationError("Topic ordering type not supported")
# Check access to the course
store = modulestore()
_get_course(course_key, user=user, check_tab=False)
user_is_privileged = user.is_staff or user.roles.filter(
course_id=course_key,
name__in=[
FORUM_ROLE_MODERATOR,
FORUM_ROLE_COMMUNITY_TA,
FORUM_ROLE_ADMINISTRATOR,
]
).exists()
with store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course_key):
blocks = store.get_items(
course_key,
qualifiers={'category': 'vertical'},
fields=['usage_key', 'discussion_enabled', 'display_name'],
)
accessible_vertical_keys = []
for block in blocks:
if block.discussion_enabled and (not block.visible_to_staff_only or user_is_privileged):
accessible_vertical_keys.append(block.usage_key)
accessible_vertical_keys.append(None)
topics_query = DiscussionTopicLink.objects.filter(
context_key=course_key,
provider_id=provider_type,
)
if user_is_privileged:
topics_query = topics_query.filter(Q(usage_key__in=accessible_vertical_keys) | Q(enabled_in_context=False))
else:
topics_query = topics_query.filter(usage_key__in=accessible_vertical_keys, enabled_in_context=True)
if topic_ids:
topics_query = topics_query.filter(external_id__in=topic_ids)
if order_by == TopicOrdering.ACTIVITY:
topics_query = sorted(
topics_query,
key=lambda topic: sum(thread_counts.get(topic.external_id, {}).values()),
reverse=True,
)
elif order_by == TopicOrdering.NAME:
topics_query = topics_query.order_by('title')
else:
topics_query = topics_query.order_by('ordering')
topics_data = DiscussionTopicSerializerV2(topics_query, many=True, context={"thread_counts": thread_counts}).data
return [
topic_data
for topic_data in topics_data
if topic_data["enabled_in_context"] or sum(topic_data["thread_counts"].values())
]
def _get_user_profile_dict(request, usernames):
"""
Gets user profile details for a list of usernames and creates a dictionary with
profile details against username.
Parameters:
request: The django request object.
usernames: A string of comma separated usernames.
Returns:
A dict with username as key and user profile details as value.
"""
if usernames:
username_list = usernames.split(",")
else:
username_list = []
user_profile_details = get_account_settings(request, username_list)
return {user['username']: user for user in user_profile_details}
def _user_profile(user_profile):
"""
Returns the user profile object. For now, this just comprises the
profile_image details.
"""
return {
'profile': {
'image': user_profile['profile_image']
}
}
def _get_users(discussion_entity_type, discussion_entity, username_profile_dict):
"""
Returns users with profile details for given discussion thread/comment.
Parameters:
discussion_entity_type: DiscussionEntity Enum value for Thread or Comment.
discussion_entity: Serialized thread/comment.
username_profile_dict: A dict with user profile details against username.
Returns:
A dict of users with username as key and user profile details as value.
"""
users = {}
if discussion_entity['author']:
user_profile = username_profile_dict.get(discussion_entity['author'])
if user_profile:
users[discussion_entity['author']] = _user_profile(user_profile)
if (
discussion_entity_type == DiscussionEntity.comment
and discussion_entity['endorsed']
and discussion_entity['endorsed_by']
):
users[discussion_entity['endorsed_by']] = _user_profile(username_profile_dict[discussion_entity['endorsed_by']])
return users
def _add_additional_response_fields(
request, serialized_discussion_entities, usernames, discussion_entity_type, include_profile_image
):
"""
Adds additional data to serialized discussion thread/comment.
Parameters:
request: The django request object.
serialized_discussion_entities: A list of serialized Thread/Comment.
usernames: A list of usernames involved in threads/comments (e.g. as author or as comment endorser).
discussion_entity_type: DiscussionEntity Enum value for Thread or Comment.
include_profile_image: (boolean) True if requested_fields has 'profile_image' else False.
Returns:
A list of serialized discussion thread/comment with additional data if requested.
"""
if include_profile_image:
username_profile_dict = _get_user_profile_dict(request, usernames=','.join(usernames))
for discussion_entity in serialized_discussion_entities:
discussion_entity['users'] = _get_users(discussion_entity_type, discussion_entity, username_profile_dict)
return serialized_discussion_entities
def _include_profile_image(requested_fields):
"""
Returns True if requested_fields list has 'profile_image' entity else False
"""
return requested_fields and 'profile_image' in requested_fields
def _serialize_discussion_entities(request, context, discussion_entities, requested_fields, discussion_entity_type):
"""
It serializes Discussion Entity (Thread or Comment) and add additional data if requested.
For a given list of Thread/Comment; it serializes and add additional information to the
object as per requested_fields list (i.e. profile_image).
Parameters:
request: The django request object
context: The context appropriate for use with the thread or comment
discussion_entities: List of Thread or Comment objects
requested_fields: Indicates which additional fields to return
for each thread.
discussion_entity_type: DiscussionEntity Enum value for Thread or Comment
Returns:
A list of serialized discussion entities
"""
results = []
usernames = []
include_profile_image = _include_profile_image(requested_fields)
for entity in discussion_entities:
if discussion_entity_type == DiscussionEntity.thread:
serialized_entity = ThreadSerializer(entity, context=context).data
elif discussion_entity_type == DiscussionEntity.comment:
serialized_entity = CommentSerializer(entity, context=context).data
results.append(serialized_entity)
if include_profile_image:
if serialized_entity['author'] and serialized_entity['author'] not in usernames:
usernames.append(serialized_entity['author'])
if (
'endorsed' in serialized_entity and serialized_entity['endorsed'] and
'endorsed_by' in serialized_entity and
serialized_entity['endorsed_by'] and serialized_entity['endorsed_by'] not in usernames
):
usernames.append(serialized_entity['endorsed_by'])
results = _add_additional_response_fields(
request, results, usernames, discussion_entity_type, include_profile_image
)
return results
def get_thread_list(
request: Request,
course_key: CourseKey,
page: int,
page_size: int,
topic_id_list: List[str] = None,
text_search: Optional[str] = None,
following: Optional[bool] = False,
author: Optional[str] = None,
thread_type: Optional[ThreadType] = None,
flagged: Optional[bool] = None,
view: Optional[ViewType] = None,
order_by: ThreadOrderingType = "last_activity_at",
order_direction: Literal["desc"] = "desc",
requested_fields: Optional[List[Literal["profile_image"]]] = None,
count_flagged: bool = None,
):
"""
Return the list of all discussion threads pertaining to the given course
Parameters:
request: The django request objects used for build_absolute_uri
course_key: The key of the course to get discussion threads for
page: The page number (1-indexed) to retrieve
page_size: The number of threads to retrieve per page
count_flagged: If true, fetch the count of flagged items in each thread
topic_id_list: The list of topic_ids to get the discussion threads for
text_search A text search query string to match
following: If true, retrieve only threads the requester is following
author: If provided, retrieve only threads by this author
thread_type: filter for "discussion" or "question threads
flagged: filter for only threads that are flagged
view: filters for either "unread" or "unanswered" threads
order_by: The key in which to sort the threads by. The only values are
"last_activity_at", "comment_count", and "vote_count". The default is
"last_activity_at".
order_direction: The direction in which to sort the threads by. The default
and only value is "desc". This will be removed in a future major
version.
requested_fields: Indicates which additional fields to return
for each thread. (i.e. ['profile_image'])
Note that topic_id_list, text_search, and following are mutually exclusive.
Returns:
A paginated result containing a list of threads; see
discussion.rest_api.views.ThreadViewSet for more detail.
Raises:
PermissionDenied: If count_flagged is set but the user isn't privileged
ValidationError: if an invalid value is passed for a field.
ValueError: if more than one of the mutually exclusive parameters is
provided
CourseNotFoundError: if the requesting user does not have access to the requested course
PageNotFoundError: if page requested is beyond the last
"""
exclusive_param_count = sum(1 for param in [topic_id_list, text_search, following] if param)
if exclusive_param_count > 1: # pragma: no cover
raise ValueError("More than one mutually exclusive param passed to get_thread_list")
cc_map = {"last_activity_at": "activity", "comment_count": "comments", "vote_count": "votes"}
if order_by not in cc_map:
raise ValidationError({
"order_by":
[f"Invalid value. '{order_by}' must be 'last_activity_at', 'comment_count', or 'vote_count'"]
})
if order_direction != "desc":
raise ValidationError({
"order_direction": [f"Invalid value. '{order_direction}' must be 'desc'"]
})
course = _get_course(course_key, request.user)
context = get_context(course, request)
author_id = None
if author:
try:
author_id = User.objects.get(username=author).id
except User.DoesNotExist:
# Raising an error for a missing user leaks the presence of a username,
# so just return an empty response.
return DiscussionAPIPagination(request, 0, 1).get_paginated_response({
"results": [],
"text_search_rewrite": None,
})
if count_flagged and not context["has_moderation_privilege"]:
raise PermissionDenied("`count_flagged` can only be set by users with moderator access or higher.")
group_id = None
allowed_roles = [
FORUM_ROLE_ADMINISTRATOR,
FORUM_ROLE_COMMUNITY_TA,
FORUM_ROLE_MODERATOR,
]
if request.GET.get("group_id", None):
if Role.user_has_role_for_course(request.user, course_key, allowed_roles):
try:
group_id = int(request.GET.get("group_id", None))
except ValueError:
pass
if (group_id is None) and not context["has_moderation_privilege"]:
group_id = get_group_id_for_user(request.user, CourseDiscussionSettings.get(course.id))
query_params = {
"user_id": str(request.user.id),
"group_id": group_id,
"page": page,
"per_page": page_size,