courses.py 15.2 KB
Newer Older
1 2 3 4 5
"""
Functions for accessing and displaying courses within the
courseware.
"""
from datetime import datetime
6
from collections import defaultdict
7 8
from fs.errors import ResourceNotFoundError
import logging
9

10
from path import Path as path
11
import pytz
12
from django.http import Http404
13
from django.conf import settings
14 15

from edxmako.shortcuts import render_to_string
16
from xmodule.modulestore.django import modulestore
Don Mitchell committed
17
from xmodule.modulestore.exceptions import ItemNotFoundError
18
from static_replace import replace_static_urls
19
from xmodule.modulestore import ModuleStoreEnum
20
from xmodule.x_module import STUDENT_VIEW
21

22
from courseware.access import has_access
23 24 25 26 27 28 29
from courseware.date_summary import (
    CourseEndDate,
    CourseStartDate,
    TodaysDate,
    VerificationDeadlineDate,
    VerifiedUpgradeDeadlineDate,
)
30 31
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module
32
from lms.djangoapps.courseware.courseware_access_exception import CoursewareAccessException
33
from student.models import CourseEnrollment
34
import branding
35

36
from opaque_keys.edx.keys import UsageKey
37
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
38
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
39

40

41
log = logging.getLogger(__name__)
42

Calen Pennington committed
43

44 45 46 47
def get_course(course_id, depth=0):
    """
    Given a course id, return the corresponding course descriptor.

Don Mitchell committed
48
    If the course does not exist, raises a ValueError.  This is appropriate
49 50 51 52 53
    for internal use.

    depth: The number of levels of children for the modulestore to cache.
    None means infinite depth.  Default is to fetch no children.
    """
Don Mitchell committed
54 55
    course = modulestore().get_course(course_id, depth=depth)
    if course is None:
56
        raise ValueError(u"Course not found: {0}".format(course_id))
57
    return course
58 59


60
def get_course_by_id(course_key, depth=0):
61
    """
62
    Given a course id, return the corresponding course descriptor.
63

Don Mitchell committed
64
    If such a course does not exist, raises a 404.
65

66
    depth: The number of levels of children for the modulestore to cache. None means infinite depth
67
    """
68 69
    with modulestore().bulk_operations(course_key):
        course = modulestore().get_course(course_key, depth=depth)
Don Mitchell committed
70 71 72
    if course:
        return course
    else:
73
        raise Http404("Course not found.")
74

75

76 77 78 79 80 81 82
class UserNotEnrolled(Http404):
    def __init__(self, course_key):
        super(UserNotEnrolled, self).__init__()
        self.course_key = course_key


def get_course_with_access(user, action, course_key, depth=0, check_if_enrolled=False):
83
    """
84
    Given a course_key, look up the corresponding course descriptor,
85 86
    check that the user has the access to perform the specified action
    on the course, and return the descriptor.
87

88
    Raises a 404 if the course_key is invalid, or the user doesn't have access.
89 90

    depth: The number of levels of children for the modulestore to cache. None means infinite depth
91 92 93

    check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
      or has staff access.
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
    course = get_course_by_id(course_key, depth)
    check_course_access(course, user, action, check_if_enrolled)
    return course


def get_course_overview_with_access(user, action, course_key, check_if_enrolled=False):
    """
    Given a course_key, look up the corresponding course overview,
    check that the user has the access to perform the specified action
    on the course, and return the course overview.

    Raises a 404 if the course_key is invalid, or the user doesn't have access.

    check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
      or has staff access.
    """
    try:
        course_overview = CourseOverview.get_from_id(course_key)
    except CourseOverview.DoesNotExist:
        raise Http404("Course not found.")
    check_course_access(course_overview, user, action, check_if_enrolled)
    return course_overview


def check_course_access(course, user, action, check_if_enrolled=False):
    """
    Check that the user has the access to perform the specified action
    on the course (CourseDescriptor|CourseOverview).

    check_if_enrolled: If true, additionally verifies that the user is either
    enrolled in the course or has staff access.
    """
    access_response = has_access(user, action, course, course.id)
128

129
    if not access_response:
130 131
        # Deliberately return a non-specific error message to avoid
        # leaking info about access control settings
132
        raise CoursewareAccessException(access_response)
133

134
    if check_if_enrolled:
135 136 137 138 139
        # Verify that the user is either enrolled in the course or a staff
        # member.  If user is not enrolled, raise UserNotEnrolled exception
        # that will be caught by middleware.
        if not ((user.id and CourseEnrollment.is_enrolled(user, course.id)) or has_access(user, 'staff', course)):
            raise UserNotEnrolled(course.id)
140 141


Don Mitchell committed
142
def find_file(filesystem, dirs, filename):
143 144 145
    """
    Looks for a filename in a list of dirs on a filesystem, in the specified order.

Don Mitchell committed
146
    filesystem: an OSFS filesystem
147 148 149 150 151
    dirs: a list of path objects
    filename: a string

    Returns d / filename if found in dir d, else raises ResourceNotFoundError.
    """
Don Mitchell committed
152 153 154
    for directory in dirs:
        filepath = path(directory) / filename
        if filesystem.exists(filepath):
155
            return filepath
156
    raise ResourceNotFoundError(u"Could not find {0}".format(filename))
157

158

159
def get_course_about_section(request, course, section_key):
160
    """
Victor Shnayder committed
161 162 163
    This returns the snippet of html to be rendered on the course about page,
    given the key for the section.

164 165 166 167 168 169 170 171 172 173 174 175
    Valid keys:
    - overview
    - short_description
    - description
    - key_dates (includes start, end, exams, etc)
    - video
    - course_staff_short
    - course_staff_extended
    - requirements
    - syllabus
    - textbook
    - faq
176
    - effort
177
    - more_info
178
    - ocw_links
179 180
    """

Victor Shnayder committed
181 182 183
    # Many of these are stored as html files instead of some semantic
    # markup. This can change without effecting this interface when we find a
    # good format for defining so many snippets of text/html.
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    html_sections = {
        'short_description',
        'description',
        'key_dates',
        'video',
        'course_staff_short',
        'course_staff_extended',
        'requirements',
        'syllabus',
        'textbook',
        'faq',
        'more_info',
        'overview',
        'effort',
        'end_date',
        'prerequisites',
        'ocw_links'
    }

    if section_key in html_sections:
205
        try:
Don Mitchell committed
206
            loc = course.location.replace(category='about', name=section_key)
207 208

            # Use an empty cache
Calen Pennington committed
209
            field_data_cache = FieldDataCache([], course.id, request.user)
210 211 212 213
            about_module = get_module(
                request.user,
                request,
                loc,
Calen Pennington committed
214
                field_data_cache,
215
                log_if_not_found=False,
216
                wrap_xmodule_display=False,
217 218
                static_asset_path=course.static_asset_path,
                course=course
219
            )
220 221 222

            html = ''

223
            if about_module is not None:
224
                try:
225
                    html = about_module.render(STUDENT_VIEW).content
226 227
                except Exception:  # pylint: disable=broad-except
                    html = render_to_string('courseware/error-message.html', None)
228
                    log.exception(
229 230 231
                        u"Error rendering course=%s, section_key=%s",
                        course, section_key
                    )
232
            return html
233 234

        except ItemNotFoundError:
235
            log.warning(
236 237
                u"Missing about section %s in course %s",
                section_key, course.location.to_deprecated_string()
238
            )
239 240 241 242
            return None

    raise KeyError("Invalid about key " + str(section_key))

243

244
def get_course_info_section_module(request, user, course, section_key):
245
    """
246
    This returns the course info module for a given section_key.
Victor Shnayder committed
247

248 249 250 251 252 253
    Valid keys:
    - handouts
    - guest_handouts
    - updates
    - guest_updates
    """
254
    usage_key = course.id.make_usage_key('course_info', section_key)
255 256

    # Use an empty cache
257
    field_data_cache = FieldDataCache([], course.id, user)
258 259

    return get_module(
260
        user,
261
        request,
262
        usage_key,
Calen Pennington committed
263
        field_data_cache,
264
        log_if_not_found=False,
265
        wrap_xmodule_display=False,
266 267
        static_asset_path=course.static_asset_path,
        course=course
268
    )
269

270

271
def get_course_info_section(request, user, course, section_key):
272 273 274
    """
    This returns the snippet of html to be rendered on the course info page,
    given the key for the section.
275

276 277 278 279 280 281
    Valid keys:
    - handouts
    - guest_handouts
    - updates
    - guest_updates
    """
282
    info_module = get_course_info_section_module(request, user, course, section_key)
283 284

    html = ''
285
    if info_module is not None:
286
        try:
287
            html = info_module.render(STUDENT_VIEW).content
288 289
        except Exception:  # pylint: disable=broad-except
            html = render_to_string('courseware/error-message.html', None)
290
            log.exception(
291 292
                u"Error rendering course_id=%s, section_key=%s",
                unicode(course.id), section_key
293
            )
294

295
    return html
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
def get_course_date_summary(course, user):
    """
    Return the snippet of HTML to be included on the course info page
    in the 'Date Summary' section.
    """
    blocks = _get_course_date_summary_blocks(course, user)
    return '\n'.join(
        b.render() for b in blocks
    )


def _get_course_date_summary_blocks(course, user):
    """
    Return the list of blocks to display on the course info page,
    sorted by date.
    """
    block_classes = (
        CourseEndDate,
        CourseStartDate,
        TodaysDate,
        VerificationDeadlineDate,
        VerifiedUpgradeDeadlineDate,
    )

    blocks = (cls(course, user) for cls in block_classes)
323 324 325 326 327 328 329 330 331 332

    def block_key_fn(block):
        """
        If the block's date is None, return the maximum datetime in order
        to force it to the end of the list of displayed blocks.
        """
        if block.date is None:
            return datetime.max.replace(tzinfo=pytz.UTC)
        return block.date
    return sorted((b for b in blocks if b.is_enabled), key=block_key_fn)
333 334


335 336
# TODO: Fix this such that these are pulled in as extra course-specific tabs.
#       arjun will address this by the end of October if no one does so prior to
337
#       then.
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
def get_course_syllabus_section(course, section_key):
    """
    This returns the snippet of html to be rendered on the syllabus page,
    given the key for the section.

    Valid keys:
    - syllabus
    - guest_syllabus
    """

    # Many of these are stored as html files instead of some semantic
    # markup. This can change without effecting this interface when we find a
    # good format for defining so many snippets of text/html.

    if section_key in ['syllabus', 'guest_syllabus']:
        try:
Don Mitchell committed
354
            filesys = course.system.resources_fs
355 356
            # first look for a run-specific version
            dirs = [path("syllabus") / course.url_name, path("syllabus")]
Don Mitchell committed
357 358
            filepath = find_file(filesys, dirs, section_key + ".html")
            with filesys.open(filepath) as html_file:
359
                return replace_static_urls(
Don Mitchell committed
360
                    html_file.read().decode('utf-8'),
361
                    getattr(course, 'data_dir', None),
362
                    course_id=course.id,
Calen Pennington committed
363
                    static_asset_path=course.static_asset_path,
364
                )
365
        except ResourceNotFoundError:
366
            log.exception(
367 368
                u"Missing syllabus section %s in course %s",
                section_key, course.location.to_deprecated_string()
369
            )
370 371 372 373
            return "! Syllabus missing !"

    raise KeyError("Invalid about key " + str(section_key))

374

375
def get_courses(user, org=None, filter_=None):
376 377 378 379
    """
    Returns a list of courses available, sorted by course.number and optionally
    filtered by org code (case-insensitive).
    """
380
    courses = branding.get_visible_courses(org=org, filter_=filter_)
381

382
    permission_name = configuration_helpers.get_value(
383 384 385 386 387
        'COURSE_CATALOG_VISIBILITY_PERMISSION',
        settings.COURSE_CATALOG_VISIBILITY_PERMISSION
    )

    courses = [c for c in courses if has_access(user, permission_name, c)]
388

389 390 391
    return courses


392 393 394 395
def get_permission_for_course_about():
    """
    Returns the CourseOverview object for the course after checking for access.
    """
396
    return configuration_helpers.get_value(
397 398 399 400 401
        'COURSE_ABOUT_VISIBILITY_PERMISSION',
        settings.COURSE_ABOUT_VISIBILITY_PERMISSION
    )


402 403 404 405 406 407 408 409 410 411
def sort_by_announcement(courses):
    """
    Sorts a list of courses by their announcement date. If the date is
    not available, sort them by their start date.
    """

    # Sort courses by how far are they from they start day
    key = lambda course: course.sorting_score
    courses = sorted(courses, key=key)

412
    return courses
413

414

415 416 417 418
def sort_by_start_date(courses):
    """
    Returns a list of courses sorted by their start date, latest first.
    """
419 420 421 422 423
    courses = sorted(
        courses,
        key=lambda course: (course.has_ended(), course.start is None, course.start),
        reverse=False
    )
424 425 426 427

    return courses


428
def get_cms_course_link(course, page='course'):
429
    """
430 431
    Returns a link to course_index for editing the course in cms,
    assuming that the course is actually cms-backed.
432
    """
433 434 435
    # This is fragile, but unfortunately the problem is that within the LMS we
    # can't use the reverse calls from the CMS
    return u"//{}/{}/{}".format(settings.CMS_BASE, page, unicode(course.id))
436 437 438 439 440 441 442


def get_cms_block_link(block, page):
    """
    Returns a link to block_index for editing the course in cms,
    assuming that the block is actually cms-backed.
    """
443 444 445
    # This is fragile, but unfortunately the problem is that within the LMS we
    # can't use the reverse calls from the CMS
    return u"//{}/{}/{}".format(settings.CMS_BASE, page, block.location)
446 447


448
def get_studio_url(course, page):
449 450
    """
    Get the Studio URL of the page that is passed in.
451 452 453

    Args:
        course (CourseDescriptor)
454 455
    """
    studio_link = None
456
    if course.course_edit_method == "Studio":
457
        studio_link = get_cms_course_link(course, page)
458
    return studio_link
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


def get_problems_in_section(section):
    """
    This returns a dict having problems in a section.
    Returning dict has problem location as keys and problem
    descriptor as values.
    """

    problem_descriptors = defaultdict()
    if not isinstance(section, UsageKey):
        section_key = UsageKey.from_string(section)
    else:
        section_key = section
    # it will be a Mongo performance boost, if you pass in a depth=3 argument here
    # as it will optimize round trips to the database to fetch all children for the current node
    section_descriptor = modulestore().get_item(section_key, depth=3)

    # iterate over section, sub-section, vertical
    for subsection in section_descriptor.get_children():
        for vertical in subsection.get_children():
            for component in vertical.get_children():
                if component.location.category == 'problem' and getattr(component, 'has_score', False):
                    problem_descriptors[unicode(component.location)] = component

    return problem_descriptors