api.py 40.4 KB
Newer Older
Greg Price committed
1 2 3
"""
Discussion API internal interface
"""
cahrens committed
4
import itertools
5
from collections import defaultdict
6 7 8
from urllib import urlencode
from urlparse import urlunparse

9 10 11 12 13 14 15 16
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.http import Http404
from enum import Enum
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locator import CourseKey
from rest_framework.exceptions import PermissionDenied

17
from courseware.courses import get_course_with_access
cahrens committed
18
from discussion_api.exceptions import CommentNotFoundError, DiscussionDisabledError, ThreadNotFoundError
19
from discussion_api.forms import CommentActionsForm, ThreadActionsForm
20 21 22 23
from discussion_api.permissions import (
    can_delete,
    get_editable_fields,
    get_initializable_comment_fields,
cahrens committed
24
    get_initializable_thread_fields
25
)
cahrens committed
26 27 28
from discussion_api.serializers import CommentSerializer, DiscussionTopicSerializer, ThreadSerializer, get_context
from django_comment_client.base.views import track_comment_created_event, track_thread_created_event, track_voted_event
from django_comment_client.utils import get_accessible_discussion_xblocks, get_group_id_for_user, is_commentable_divided
29 30
from django_comment_common.signals import (
    comment_created,
cahrens committed
31
    comment_deleted,
32 33
    comment_edited,
    comment_voted,
cahrens committed
34 35 36 37
    thread_created,
    thread_deleted,
    thread_edited,
    thread_voted
38
)
39
from django_comment_common.utils import get_course_discussion_settings
cahrens committed
40
from lms.djangoapps.courseware.exceptions import CourseAccessRedirect
41
from lms.djangoapps.discussion_api.pagination import DiscussionAPIPagination
42
from lms.lib.comment_client.comment import Comment
43
from lms.lib.comment_client.thread import Thread
44
from lms.lib.comment_client.utils import CommentClientRequestError
cahrens committed
45 46
from openedx.core.djangoapps.user_api.accounts.views import AccountViewSet
from openedx.core.lib.exceptions import CourseNotFoundError, DiscussionNotFoundError, PageNotFoundError
47 48 49 50 51 52 53 54 55 56 57 58


class DiscussionTopic(object):
    """
    Class for discussion topic structure
    """

    def __init__(self, topic_id, name, thread_list_url, children=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
Greg Price committed
59 60


61 62 63 64 65 66 67 68
class DiscussionEntity(Enum):
    """
    Enum for different types of discussion related entities
    """
    thread = 'thread'
    comment = 'comment'


69
def _get_course(course_key, user):
70
    """
71 72 73
    Get the course descriptor, 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.
74
    """
75 76 77
    try:
        course = get_course_with_access(user, 'load', course_key, check_if_enrolled=True)
    except Http404:
78 79 80 81 82
        # Convert 404s into CourseNotFoundErrors.
        raise CourseNotFoundError("Course not found.")
    except CourseAccessRedirect:
        # Raise course not found if the user cannot access the course
        # since it doesn't make sense to redirect an API.
83
        raise CourseNotFoundError("Course not found.")
84
    if not any([tab.type == 'discussion' and tab.is_enabled(course, user) for tab in course.tabs]):
85
        raise DiscussionDisabledError("Discussion is disabled for the course.")
86 87 88
    return course


89
def _get_thread_and_context(request, thread_id, retrieve_kwargs=None):
90 91 92 93
    """
    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
94 95
    applicable). Raises ThreadNotFoundError if the thread does not exist or the
    user cannot access it.
96 97 98
    """
    retrieve_kwargs = retrieve_kwargs or {}
    try:
99 100
        if "with_responses" not in retrieve_kwargs:
            retrieve_kwargs["with_responses"] = False
101 102 103 104
        if "mark_as_read" not in retrieve_kwargs:
            retrieve_kwargs["mark_as_read"] = False
        cc_thread = Thread(id=thread_id).retrieve(**retrieve_kwargs)
        course_key = CourseKey.from_string(cc_thread["course_id"])
105
        course = _get_course(course_key, request.user)
106
        context = get_context(course, request, cc_thread)
107
        course_discussion_settings = get_course_discussion_settings(course_key)
108 109 110
        if (
                not context["is_requester_privileged"] and
                cc_thread["group_id"] and
111
                is_commentable_divided(course.id, cc_thread["commentable_id"], course_discussion_settings)
112
        ):
113
            requester_group_id = get_group_id_for_user(request.user, course_discussion_settings)
114
            if requester_group_id is not None and cc_thread["group_id"] != requester_group_id:
115
                raise ThreadNotFoundError("Thread not found.")
116 117 118 119
        return cc_thread, context
    except CommentClientRequestError:
        # params are validated at a higher level, so the only possible request
        # error is if the thread doesn't exist
120
        raise ThreadNotFoundError("Thread not found.")
121 122


123
def _get_comment_and_context(request, comment_id):
124
    """
125 126 127
    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
128 129
    applicable). Raises CommentNotFoundError if the comment does not exist or the
    user cannot access it.
130 131 132
    """
    try:
        cc_comment = Comment(id=comment_id).retrieve()
133
        _, context = _get_thread_and_context(request, cc_comment["thread_id"])
134 135
        return cc_comment, context
    except CommentClientRequestError:
136
        raise CommentNotFoundError("Comment not found.")
137 138


139 140 141 142 143 144 145 146 147 148 149 150 151 152
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["is_requester_privileged"] or
        context["cc_requester"]["id"] == cc_content["user_id"]
    )


def get_thread_list_url(request, course_key, topic_id_list=None, following=False):
153 154 155 156
    """
    Returns the URL for the thread_list_url field, given a list of topic_ids
    """
    path = reverse("thread-list")
157 158
    query_list = (
        [("course_id", unicode(course_key))] +
159 160
        [("topic_id", topic_id) for topic_id in topic_id_list or []] +
        ([("following", following)] if following else [])
161
    )
162 163 164
    return request.build_absolute_uri(urlunparse(("", "", path, "", urlencode(query_list), "")))


165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
def get_course(request, course_key):
    """
    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

    Returns:

        The course information; see discussion_api.views.CourseView for more
        detail.

    Raises:

183 184
        CourseNotFoundError: if the course does not exist or is not accessible
        to the requesting user
185
    """
186
    course = _get_course(course_key, request.user)
187 188 189 190 191 192
    return {
        "id": unicode(course_key),
        "blackouts": [
            {"start": blackout["start"].isoformat(), "end": blackout["end"].isoformat()}
            for blackout in course.get_discussion_blackout_datetimes()
        ],
193 194
        "thread_list_url": get_thread_list_url(request, course_key),
        "following_thread_list_url": get_thread_list_url(request, course_key, following=True),
195 196 197 198 199 200
        "topics_url": request.build_absolute_uri(
            reverse("course_topics", kwargs={"course_id": course_key})
        )
    }


201
def get_courseware_topics(request, course_key, course, topic_ids):
Greg Price committed
202
    """
203
    Returns a list of topic trees for courseware-linked topics.
Greg Price committed
204 205 206

    Parameters:

207 208 209 210 211
        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.
Greg Price committed
212 213

    Returns:
214 215
        A list of courseware topics and a set of existing topics among
        topic_ids.
Greg Price committed
216 217

    """
218 219 220
    courseware_topics = []
    existing_topic_ids = set()

221
    def get_xblock_sort_key(xblock):
Greg Price committed
222
        """
223
        Get the sort key for the xblock (falling back to the discussion_target
Greg Price committed
224 225
        setting if absent)
        """
226
        return xblock.sort_key or xblock.discussion_target
227

228 229 230
    def get_sorted_xblocks(category):
        """Returns key sorted xblocks by category"""
        return sorted(xblocks_by_category[category], key=get_xblock_sort_key)
231

232 233 234 235
    discussion_xblocks = get_accessible_discussion_xblocks(course, request.user)
    xblocks_by_category = defaultdict(list)
    for xblock in discussion_xblocks:
        xblocks_by_category[xblock.discussion_category].append(xblock)
236

237
    for category in sorted(xblocks_by_category.keys()):
238
        children = []
239 240
        for xblock in get_sorted_xblocks(category):
            if not topic_ids or xblock.discussion_id in topic_ids:
241
                discussion_topic = DiscussionTopic(
242 243 244
                    xblock.discussion_id,
                    xblock.discussion_target,
                    get_thread_list_url(request, course_key, [xblock.discussion_id]),
245 246 247
                )
                children.append(discussion_topic)

248 249
                if topic_ids and xblock.discussion_id in topic_ids:
                    existing_topic_ids.add(xblock.discussion_id)
250 251 252 253 254

        if not topic_ids or children:
            discussion_topic = DiscussionTopic(
                None,
                category,
255
                get_thread_list_url(request, course_key, [item.discussion_id for item in get_sorted_xblocks(category)]),
256 257 258 259 260 261 262 263 264 265
                children,
            )
            courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data)

    return courseware_topics, existing_topic_ids


def get_non_courseware_topics(request, course_key, course, topic_ids):
    """
    Returns a list of topic trees that are not linked to courseware.
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
    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.

    Returns:
        A list of non-courseware topics and a set of existing topics among
        topic_ids.

    """
    non_courseware_topics = []
    existing_topic_ids = set()
    for name, entry in sorted(course.discussion_topics.items(), key=lambda item: item[1].get("sort_key", item[0])):
        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"]])
            )
            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, course_key, topic_ids=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
        user: The requesting user, for access control
        topic_ids: A list of topic IDs for which topic details are requested

    Returns:

        A course topic listing dictionary; see discussion_api.views.CourseTopicViews
        for more detail.

    Raises:
        DiscussionNotFoundError: If topic/s not found for given topic_ids.
    """
    course = _get_course(course_key, request.user)

    courseware_topics, existing_courseware_topic_ids = get_courseware_topics(request, course_key, course, topic_ids)
    non_courseware_topics, existing_non_courseware_topic_ids = get_non_courseware_topics(
        request, course_key, course, topic_ids
    )

    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))
            )
Greg Price committed
327 328 329 330 331

    return {
        "courseware_topics": courseware_topics,
        "non_courseware_topics": non_courseware_topics,
    }
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
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.
    """
    request.GET = request.GET.copy()  # Make a mutable copy of the GET parameters.
    request.GET['username'] = usernames
    user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data

    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.
    """
381 382 383
    users = {}
    if discussion_entity['author']:
        users[discussion_entity['author']] = _user_profile(username_profile_dict[discussion_entity['author']])
384

385 386 387 388 389
    if (
            discussion_entity_type == DiscussionEntity.comment
            and discussion_entity['endorsed']
            and discussion_entity['endorsed_by']
    ):
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
        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:
458
            if serialized_entity['author'] and serialized_entity['author'] not in usernames:
459 460 461
                usernames.append(serialized_entity['author'])
            if (
                    'endorsed' in serialized_entity and serialized_entity['endorsed'] and
462 463
                    'endorsed_by' in serialized_entity and
                    serialized_entity['endorsed_by'] and serialized_entity['endorsed_by'] not in usernames
464 465 466 467 468 469 470 471 472
            ):
                usernames.append(serialized_entity['endorsed_by'])

    results = _add_additional_response_fields(
        request, results, usernames, discussion_entity_type, include_profile_image
    )
    return results


473 474 475 476 477 478 479 480
def get_thread_list(
        request,
        course_key,
        page,
        page_size,
        topic_id_list=None,
        text_search=None,
        following=False,
481 482 483
        view=None,
        order_by="last_activity_at",
        order_direction="desc",
484
        requested_fields=None,
485
):
486 487 488 489 490 491
    """
    Return the list of all discussion threads pertaining to the given course

    Parameters:

    request: The django request objects used for build_absolute_uri
492
    course_key: The key of the course to get discussion threads for
493 494
    page: The page number (1-indexed) to retrieve
    page_size: The number of threads to retrieve per page
495
    topic_id_list: The list of topic_ids to get the discussion threads for
496
    text_search A text search query string to match
497
    following: If true, retrieve only threads the requester is following
498
    view: filters for either "unread" or "unanswered" threads
499 500 501
    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".
502 503 504
    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.
505 506
    requested_fields: Indicates which additional fields to return
        for each thread. (i.e. ['profile_image'])
507

508
    Note that topic_id_list, text_search, and following are mutually exclusive.
509 510 511 512 513

    Returns:

    A paginated result containing a list of threads; see
    discussion_api.views.ThreadViewSet for more detail.
514 515 516

    Raises:

517
    ValidationError: if an invalid value is passed for a field.
518 519
    ValueError: if more than one of the mutually exclusive parameters is
      provided
520 521
    CourseNotFoundError: if the requesting user does not have access to the requested course
    PageNotFoundError: if page requested is beyond the last
522
    """
523
    exclusive_param_count = sum(1 for param in [topic_id_list, text_search, following] if param)
524 525 526
    if exclusive_param_count > 1:  # pragma: no cover
        raise ValueError("More than one mutually exclusive param passed to get_thread_list")

527
    cc_map = {"last_activity_at": "activity", "comment_count": "comments", "vote_count": "votes"}
528 529 530 531 532
    if order_by not in cc_map:
        raise ValidationError({
            "order_by":
                ["Invalid value. '{}' must be 'last_activity_at', 'comment_count', or 'vote_count'".format(order_by)]
        })
533
    if order_direction != "desc":
534
        raise ValidationError({
535
            "order_direction": ["Invalid value. '{}' must be 'desc'".format(order_direction)]
536 537
        })

538
    course = _get_course(course_key, request.user)
539
    context = get_context(course, request)
540

541
    query_params = {
542
        "user_id": unicode(request.user.id),
543 544
        "group_id": (
            None if context["is_requester_privileged"] else
545
            get_group_id_for_user(request.user, get_course_discussion_settings(course.id))
546
        ),
547
        "page": page,
548
        "per_page": page_size,
549
        "text": text_search,
550
        "sort_key": cc_map.get(order_by),
551
    }
552 553 554 555 556 557 558 559 560

    if view:
        if view in ["unread", "unanswered"]:
            query_params[view] = "true"
        else:
            ValidationError({
                "view": ["Invalid value. '{}' must be 'unread' or 'unanswered'".format(view)]
            })

561
    if following:
562
        paginated_results = context["cc_requester"].subscribed_threads(query_params)
563 564 565 566
    else:
        query_params["course_id"] = unicode(course.id)
        query_params["commentable_ids"] = ",".join(topic_id_list) if topic_id_list else None
        query_params["text"] = text_search
567
        paginated_results = Thread.search(query_params)
568 569
    # The comments service returns the last page of results if the requested
    # page is beyond the last page, but we want be consistent with DRF's general
570
    # behavior and return a PageNotFoundError in that case
571
    if paginated_results.page != page:
572
        raise PageNotFoundError("Page not found (No results on this page).")
573

574 575 576
    results = _serialize_discussion_entities(
        request, context, paginated_results.collection, requested_fields, DiscussionEntity.thread
    )
577

578 579 580 581 582 583
    paginator = DiscussionAPIPagination(
        request,
        paginated_results.page,
        paginated_results.num_pages,
        paginated_results.thread_count
    )
584 585
    return paginator.get_paginated_response({
        "results": results,
586
        "text_search_rewrite": paginated_results.corrected_text,
587
    })
588 589


590
def get_comment_list(request, thread_id, endorsed, page, page_size, requested_fields=None):
591 592 593
    """
    Return the list of comments in the given thread.

594
    Arguments:
595 596 597 598 599 600 601 602 603 604 605 606 607 608

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        thread_id: The id of the thread to get comments for.

        endorsed: Boolean indicating whether to get endorsed or non-endorsed
          comments (or None for all comments). Must be None for a discussion
          thread and non-None for a question thread.

        page: The page number (1-indexed) to retrieve

        page_size: The number of comments to retrieve per page

609 610 611
        requested_fields: Indicates which additional fields to return for
        each comment. (i.e. ['profile_image'])

612 613 614 615 616 617
    Returns:

        A paginated result containing a list of comments; see
        discussion_api.views.CommentViewSet for more detail.
    """
    response_skip = page_size * (page - 1)
618 619 620 621
    cc_thread, context = _get_thread_and_context(
        request,
        thread_id,
        retrieve_kwargs={
622
            "with_responses": True,
623
            "recursive": False,
624 625 626 627 628
            "user_id": request.user.id,
            "response_skip": response_skip,
            "response_limit": page_size,
        }
    )
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

    # Responses to discussion threads cannot be separated by endorsed, but
    # responses to question threads must be separated by endorsed due to the
    # existing comments service interface
    if cc_thread["thread_type"] == "question":
        if endorsed is None:
            raise ValidationError({"endorsed": ["This field is required for question threads."]})
        elif endorsed:
            # CS does not apply resp_skip and resp_limit to endorsed responses
            # of a question post
            responses = cc_thread["endorsed_responses"][response_skip:(response_skip + page_size)]
            resp_total = len(cc_thread["endorsed_responses"])
        else:
            responses = cc_thread["non_endorsed_responses"]
            resp_total = cc_thread["non_endorsed_resp_total"]
    else:
        if endorsed is not None:
            raise ValidationError(
                {"endorsed": ["This field may not be specified for discussion threads."]}
            )
        responses = cc_thread["children"]
        resp_total = cc_thread["resp_total"]

    # The comments service returns the last page of results if the requested
    # page is beyond the last page, but we want be consistent with DRF's general
654
    # behavior and return a PageNotFoundError in that case
655
    if not responses and page != 1:
656
        raise PageNotFoundError("Page not found (No results on this page).")
657 658
    num_pages = (resp_total + page_size - 1) / page_size if resp_total else 1

659 660
    results = _serialize_discussion_entities(request, context, responses, requested_fields, DiscussionEntity.comment)

661
    paginator = DiscussionAPIPagination(request, page, num_pages, resp_total)
662
    return paginator.get_paginated_response(results)
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
def _check_fields(allowed_fields, data, message):
    """
    Checks that the keys given in data is in allowed_fields

    Arguments:
        allowed_fields (set): A set of allowed fields
        data (dict): The data to compare the allowed_fields against
        message (str): The message to return if there are any invalid fields

    Raises:
        ValidationError if the given data contains a key that is not in
            allowed_fields
    """
    non_allowed_fields = {field: [message] for field in data.keys() if field not in allowed_fields}
    if non_allowed_fields:
        raise ValidationError(non_allowed_fields)


def _check_initializable_thread_fields(data, context):  # pylint: disable=invalid-name
    """
    Checks if the given data contains a thread field that is not initializable
    by the requesting user

    Arguments:
        data (dict): The data to compare the allowed_fields against
        context (dict): The context appropriate for use with the thread which
            includes the requesting user

    Raises:
        ValidationError if the given data contains a thread field that is not
            initializable by the requesting user
    """
    _check_fields(
        get_initializable_thread_fields(context),
        data,
        "This field is not initializable."
    )


def _check_initializable_comment_fields(data, context):  # pylint: disable=invalid-name
    """
    Checks if the given data contains a comment field that is not initializable
    by the requesting user

    Arguments:
        data (dict): The data to compare the allowed_fields against
        context (dict): The context appropriate for use with the comment which
            includes the requesting user

    Raises:
        ValidationError if the given data contains a comment field that is not
            initializable by the requesting user
    """
    _check_fields(
        get_initializable_comment_fields(context),
        data,
        "This field is not initializable."
    )


725 726 727
def _check_editable_fields(cc_content, data, context):
    """
    Raise ValidationError if the given update data contains a field that is not
728
    editable by the requesting user
729
    """
730 731 732 733 734
    _check_fields(
        get_editable_fields(cc_content, context),
        data,
        "This field is not editable."
    )
735 736


737
def _do_extra_actions(api_content, cc_content, request_fields, actions_form, context, request):
738
    """
739
    Perform any necessary additional actions related to content creation or
740 741
    update that require a separate comments service request.
    """
742
    for field, form_value in actions_form.cleaned_data.items():
743 744
        if field in request_fields and form_value != api_content[field]:
            api_content[field] = form_value
745
            if field == "following":
746
                _handle_following_field(form_value, context["cc_requester"], cc_content)
747
            elif field == "abuse_flagged":
748 749 750
                _handle_abuse_flagged_field(form_value, context["cc_requester"], cc_content)
            elif field == "voted":
                _handle_voted_field(form_value, cc_content, api_content, request, context)
751 752
            elif field == "read":
                _handle_read_field(api_content, form_value, context["cc_requester"], cc_content)
753 754
            else:
                raise ValidationError({field: ["Invalid Key"]})
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


def _handle_following_field(form_value, user, cc_content):
    """follow/unfollow thread for the user"""
    if form_value:
        user.follow(cc_content)
    else:
        user.unfollow(cc_content)


def _handle_abuse_flagged_field(form_value, user, cc_content):
    """mark or unmark thread/comment as abused"""
    if form_value:
        cc_content.flagAbuse(user, cc_content)
    else:
        cc_content.unFlagAbuse(user, cc_content, removeAll=False)


def _handle_voted_field(form_value, cc_content, api_content, request, context):
    """vote or undo vote on thread/comment"""
    signal = thread_voted if cc_content.type == 'thread' else comment_voted
    signal.send(sender=None, user=context["request"].user, post=cc_content)
    if form_value:
        context["cc_requester"].vote(cc_content, "up")
        api_content["vote_count"] += 1
    else:
        context["cc_requester"].unvote(cc_content)
        api_content["vote_count"] -= 1
    track_voted_event(
        request, context["course"], cc_content, vote_value="up", undo_vote=False if form_value else True
    )
786 787


788 789 790 791 792 793
def _handle_read_field(api_content, form_value, user, cc_content):
    """
    Marks thread as read for the user
    """
    if form_value and not cc_content['read']:
        user.read(cc_content)
794 795 796
        # When a thread is marked as read, all of its responses and comments
        # are also marked as read.
        api_content["unread_comment_count"] = 0
797 798


799 800 801 802
def create_thread(request, thread_data):
    """
    Create a thread.

803
    Arguments:
804 805 806 807 808 809 810 811 812 813 814 815

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        thread_data: The data for the created thread.

    Returns:

        The created thread; see discussion_api.views.ThreadViewSet for more
        detail.
    """
    course_id = thread_data.get("course_id")
816
    user = request.user
817 818 819
    if not course_id:
        raise ValidationError({"course_id": ["This field is required."]})
    try:
820
        course_key = CourseKey.from_string(course_id)
821 822
        course = _get_course(course_key, user)
    except InvalidKeyError:
823 824 825
        raise ValidationError({"course_id": ["Invalid value."]})

    context = get_context(course, request)
826
    _check_initializable_thread_fields(thread_data, context)
827
    discussion_settings = get_course_discussion_settings(course_key)
828 829
    if (
            "group_id" not in thread_data and
830
            is_commentable_divided(course_key, thread_data.get("topic_id"), discussion_settings)
831 832
    ):
        thread_data = thread_data.copy()
833
        thread_data["group_id"] = get_group_id_for_user(user, discussion_settings)
834
    serializer = ThreadSerializer(data=thread_data, context=context)
835 836 837
    actions_form = ThreadActionsForm(thread_data)
    if not (serializer.is_valid() and actions_form.is_valid()):
        raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items()))
838
    serializer.save()
839
    cc_thread = serializer.instance
840
    thread_created.send(sender=None, user=user, post=cc_thread)
841
    api_thread = serializer.data
842
    _do_extra_actions(api_thread, cc_thread, thread_data.keys(), actions_form, context, request)
843

844
    track_thread_created_event(request, course, cc_thread, actions_form.cleaned_data["following"])
845

846
    return api_thread
847 848 849 850 851 852


def create_comment(request, comment_data):
    """
    Create a comment.

853
    Arguments:
854 855 856 857 858 859 860 861 862 863 864 865 866 867

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        comment_data: The data for the created comment.

    Returns:

        The created comment; see discussion_api.views.CommentViewSet for more
        detail.
    """
    thread_id = comment_data.get("thread_id")
    if not thread_id:
        raise ValidationError({"thread_id": ["This field is required."]})
868
    cc_thread, context = _get_thread_and_context(request, thread_id)
869

870 871 872 873
    # if a thread is closed; no new comments could be made to it
    if cc_thread['closed']:
        raise PermissionDenied

874
    _check_initializable_comment_fields(comment_data, context)
875
    serializer = CommentSerializer(data=comment_data, context=context)
876 877 878
    actions_form = CommentActionsForm(comment_data)
    if not (serializer.is_valid() and actions_form.is_valid()):
        raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items()))
879
    serializer.save()
880
    cc_comment = serializer.instance
881
    comment_created.send(sender=None, user=request.user, post=cc_comment)
882
    api_comment = serializer.data
883
    _do_extra_actions(api_comment, cc_comment, comment_data.keys(), actions_form, context, request)
884

885
    track_comment_created_event(request, context["course"], cc_comment, cc_thread["commentable_id"], followed=False)
886

887
    return api_comment
888 889


890 891 892 893
def update_thread(request, thread_id, update_data):
    """
    Update a thread.

894
    Arguments:
895 896 897 898 899 900 901 902 903 904 905 906 907

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        thread_id: The id for the thread to update.

        update_data: The data to update in the thread.

    Returns:

        The updated thread; see discussion_api.views.ThreadViewSet for more
        detail.
    """
908
    cc_thread, context = _get_thread_and_context(request, thread_id, retrieve_kwargs={"with_responses": True})
909
    _check_editable_fields(cc_thread, update_data, context)
910
    serializer = ThreadSerializer(cc_thread, data=update_data, partial=True, context=context)
911 912 913 914 915 916
    actions_form = ThreadActionsForm(update_data)
    if not (serializer.is_valid() and actions_form.is_valid()):
        raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items()))
    # Only save thread object if some of the edited fields are in the thread data, not extra actions
    if set(update_data) - set(actions_form.fields):
        serializer.save()
917
        # signal to update Teams when a user edits a thread
918
        thread_edited.send(sender=None, user=request.user, post=cc_thread)
919
    api_thread = serializer.data
920
    _do_extra_actions(api_thread, cc_thread, update_data.keys(), actions_form, context, request)
921 922 923 924 925

    # always return read as True (and therefore unread_comment_count=0) as reasonably
    # accurate shortcut, rather than adding additional processing.
    api_thread['read'] = True
    api_thread['unread_comment_count'] = 0
926
    return api_thread
927 928


929 930 931 932
def update_comment(request, comment_id, update_data):
    """
    Update a comment.

933
    Arguments:
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        comment_id: The id for the comment to update.

        update_data: The data to update in the comment.

    Returns:

        The updated comment; see discussion_api.views.CommentViewSet for more
        detail.

    Raises:

949 950
        CommentNotFoundError: if the comment does not exist or is not accessible
        to the requesting user
951 952 953 954 955 956 957 958

        PermissionDenied: if the comment is accessible to but not editable by
          the requesting user

        ValidationError: if there is an error applying the update (e.g. raw_body
          is empty or thread_id is included)
    """
    cc_comment, context = _get_comment_and_context(request, comment_id)
959
    _check_editable_fields(cc_comment, update_data, context)
960
    serializer = CommentSerializer(cc_comment, data=update_data, partial=True, context=context)
961 962 963
    actions_form = CommentActionsForm(update_data)
    if not (serializer.is_valid() and actions_form.is_valid()):
        raise ValidationError(dict(serializer.errors.items() + actions_form.errors.items()))
964
    # Only save comment object if some of the edited fields are in the comment data, not extra actions
965
    if set(update_data) - set(actions_form.fields):
966
        serializer.save()
967
        comment_edited.send(sender=None, user=request.user, post=cc_comment)
968
    api_comment = serializer.data
969
    _do_extra_actions(api_comment, cc_comment, update_data.keys(), actions_form, context, request)
970
    return api_comment
971 972


973
def get_thread(request, thread_id, requested_fields=None):
974 975 976 977 978 979 980 981 982 983
    """
    Retrieve a thread.

    Arguments:

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        thread_id: The id for the thread to retrieve

984 985
        requested_fields: Indicates which additional fields to return for
        thread. (i.e. ['profile_image'])
986
    """
987 988
    # Possible candidate for optimization with caching:
    #   Param with_responses=True required only to add "response_count" to response.
989 990 991
    cc_thread, context = _get_thread_and_context(
        request,
        thread_id,
992 993 994 995
        retrieve_kwargs={
            "with_responses": True,
            "user_id": unicode(request.user.id),
        }
996
    )
997
    return _serialize_discussion_entities(request, context, [cc_thread], requested_fields, DiscussionEntity.thread)[0]
998 999


1000
def get_response_comments(request, comment_id, page, page_size, requested_fields=None):
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    """
    Return the list of comments for the given thread response.

    Arguments:

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        comment_id: The id of the comment/response to get child comments for.

        page: The page number (1-indexed) to retrieve

        page_size: The number of comments to retrieve per page

1015 1016 1017
        requested_fields: Indicates which additional fields to return for
        each child comment. (i.e. ['profile_image'])

1018 1019 1020 1021 1022 1023 1024
    Returns:

        A paginated result containing a list of comments

    """
    try:
        cc_comment = Comment(id=comment_id).retrieve()
1025 1026 1027 1028
        cc_thread, context = _get_thread_and_context(
            request,
            cc_comment["thread_id"],
            retrieve_kwargs={
1029
                "with_responses": True,
1030 1031 1032
                "recursive": True,
            }
        )
1033
        if cc_thread["thread_type"] == "question":
1034
            thread_responses = itertools.chain(cc_thread["endorsed_responses"], cc_thread["non_endorsed_responses"])
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        else:
            thread_responses = cc_thread["children"]
        response_comments = []
        for response in thread_responses:
            if response["id"] == comment_id:
                response_comments = response["children"]
                break

        response_skip = page_size * (page - 1)
        paged_response_comments = response_comments[response_skip:(response_skip + page_size)]
1045 1046 1047
        if len(paged_response_comments) == 0 and page != 1:
            raise PageNotFoundError("Page not found (No results on this page).")

1048 1049 1050
        results = _serialize_discussion_entities(
            request, context, paged_response_comments, requested_fields, DiscussionEntity.comment
        )
1051 1052 1053

        comments_count = len(response_comments)
        num_pages = (comments_count + page_size - 1) / page_size if comments_count else 1
1054
        paginator = DiscussionAPIPagination(request, page, num_pages, comments_count)
1055
        return paginator.get_paginated_response(results)
1056
    except CommentClientRequestError:
1057
        raise CommentNotFoundError("Comment not found")
1058 1059


1060 1061 1062 1063
def delete_thread(request, thread_id):
    """
    Delete a thread.

1064
    Arguments:
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        thread_id: The id for the thread to delete

    Raises:

        PermissionDenied: if user does not have permission to delete thread

    """
    cc_thread, context = _get_thread_and_context(request, thread_id)
1077
    if can_delete(cc_thread, context):
1078
        cc_thread.delete()
1079
        thread_deleted.send(sender=None, user=request.user, post=cc_thread)
1080 1081
    else:
        raise PermissionDenied
1082 1083 1084 1085 1086 1087


def delete_comment(request, comment_id):
    """
    Delete a comment.

1088
    Arguments:
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

        request: The django request object used for build_absolute_uri and
          determining the requesting user.

        comment_id: The id of the comment to delete

    Raises:

        PermissionDenied: if user does not have permission to delete thread

    """
    cc_comment, context = _get_comment_and_context(request, comment_id)
1101
    if can_delete(cc_comment, context):
1102
        cc_comment.delete()
1103
        comment_deleted.send(sender=None, user=request.user, post=cc_comment)
1104 1105
    else:
        raise PermissionDenied