def get_courseware_topics(request, course_key, course, topic_ids): """ 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. Returns: A list of courseware topics and a set of existing topics among topic_ids. """ courseware_topics = [] existing_topic_ids = set() def get_xblock_sort_key(xblock): """ Get the sort key for the xblock (falling back to the discussion_target setting if absent) """ return xblock.sort_key or xblock.discussion_target def get_sorted_xblocks(category): """Returns key sorted xblocks by category""" return sorted(xblocks_by_category[category], key=get_xblock_sort_key) 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) for category in sorted(xblocks_by_category.keys()): children = [] for xblock in get_sorted_xblocks(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]), ) 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 get_sorted_xblocks(category)]), children, ) courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data) return courseware_topics, existing_topic_ids