tabs.py 9.87 KB
Newer Older
1 2 3 4 5
"""
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
6
from django.utils.translation import ugettext as _, ugettext_noop
7

8
from courseware.access import has_access
9
from courseware.entrance_exams import user_must_complete_entrance_exam
10
from openedx.core.lib.course_tabs import CourseTabPluginManager
11 12 13 14
from student.models import CourseEnrollment
from xmodule.tabs import CourseTab, CourseTabList, key_checker


15
class EnrolledTab(CourseTab):
16 17 18 19 20 21 22
    """
    A base class for any view types that require a user to be enrolled.
    """
    @classmethod
    def is_enabled(cls, course, user=None):
        if user is None:
            return True
23
        return bool(CourseEnrollment.is_enrolled(user, course.id) or has_access(user, 'staff', course, course.id))
24 25


26
class CoursewareTab(EnrolledTab):
27 28 29
    """
    The main courseware view.
    """
30
    type = 'courseware'
31
    title = ugettext_noop('Course')
32 33 34
    priority = 10
    view_name = 'courseware'
    is_movable = False
35
    is_default = False
36 37


38
class CourseInfoTab(CourseTab):
39 40 41
    """
    The course info view.
    """
42
    type = 'course_info'
43
    title = ugettext_noop('Home')
44 45 46 47
    priority = 20
    view_name = 'info'
    tab_id = 'info'
    is_movable = False
48
    is_default = False
49 50 51 52 53 54

    @classmethod
    def is_enabled(cls, course, user=None):
        return True


55
class SyllabusTab(EnrolledTab):
56 57 58
    """
    A tab for the course syllabus.
    """
59
    type = 'syllabus'
60
    title = ugettext_noop('Syllabus')
61 62
    priority = 30
    view_name = 'syllabus'
63
    allow_multiple = True
64
    is_default = False
65 66

    @classmethod
67
    def is_enabled(cls, course, user=None):
68
        if not super(SyllabusTab, cls).is_enabled(course, user=user):
69 70 71 72
            return False
        return getattr(course, 'syllabus_present', False)


73
class ProgressTab(EnrolledTab):
74 75 76
    """
    The course progress view.
    """
77
    type = 'progress'
78
    title = ugettext_noop('Progress')
79 80 81
    priority = 40
    view_name = 'progress'
    is_hideable = True
82
    is_default = False
83 84

    @classmethod
85
    def is_enabled(cls, course, user=None):
86
        if not super(ProgressTab, cls).is_enabled(course, user=user):
87 88 89 90
            return False
        return not course.hide_progress_tab


91
class TextbookTabsBase(CourseTab):
92 93 94 95
    """
    Abstract class for textbook collection tabs classes.
    """
    # Translators: 'Textbooks' refers to the tab in the course that leads to the course' textbooks
96
    title = ugettext_noop("Textbooks")
97
    is_collection = True
98
    is_default = False
99 100

    @classmethod
101
    def is_enabled(cls, course, user=None):
102 103 104 105 106 107 108 109 110 111 112
        return user is None or user.is_authenticated()

    @classmethod
    def items(cls, course):
        """
        A generator for iterating through all the SingleTextbookTab book objects associated with this
        collection of textbooks.
        """
        raise NotImplementedError()


113
class TextbookTabs(TextbookTabsBase):
114 115 116
    """
    A tab representing the collection of all textbook tabs.
    """
117
    type = 'textbooks'
118 119 120 121
    priority = None
    view_name = 'book'

    @classmethod
122
    def is_enabled(cls, course, user=None):
123
        parent_is_enabled = super(TextbookTabs, cls).is_enabled(course, user)
124 125 126 127 128 129 130 131 132 133 134 135 136
        return settings.FEATURES.get('ENABLE_TEXTBOOK') and parent_is_enabled

    @classmethod
    def items(cls, course):
        for index, textbook in enumerate(course.textbooks):
            yield SingleTextbookTab(
                name=textbook.title,
                tab_id='textbook/{0}'.format(index),
                view_name=cls.view_name,
                index=index
            )


137
class PDFTextbookTabs(TextbookTabsBase):
138 139 140
    """
    A tab representing the collection of all PDF textbook tabs.
    """
141
    type = 'pdf_textbooks'
142 143 144 145 146 147 148 149 150 151 152 153 154 155
    priority = None
    view_name = 'pdf_book'

    @classmethod
    def items(cls, course):
        for index, textbook in enumerate(course.pdf_textbooks):
            yield SingleTextbookTab(
                name=textbook['tab_title'],
                tab_id='pdftextbook/{0}'.format(index),
                view_name=cls.view_name,
                index=index
            )


156
class HtmlTextbookTabs(TextbookTabsBase):
157 158 159
    """
    A tab representing the collection of all Html textbook tabs.
    """
160
    type = 'html_textbooks'
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
    priority = None
    view_name = 'html_book'

    @classmethod
    def items(cls, course):
        for index, textbook in enumerate(course.html_textbooks):
            yield SingleTextbookTab(
                name=textbook['tab_title'],
                tab_id='htmltextbook/{0}'.format(index),
                view_name=cls.view_name,
                index=index
            )


class LinkTab(CourseTab):
    """
    Abstract class for tabs that contain external links.
    """
    link_value = ''

    def __init__(self, tab_dict=None, name=None, link=None):
        self.link_value = tab_dict['link'] if tab_dict else link

        def link_value_func(_course, _reverse_func):
            """ Returns the link_value as the link. """
            return self.link_value

        self.type = tab_dict['type']

190 191 192
        tab_dict['link_func'] = link_value_func

        super(LinkTab, self).__init__(tab_dict)
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    def __getitem__(self, key):
        if key == 'link':
            return self.link_value
        else:
            return super(LinkTab, self).__getitem__(key)

    def __setitem__(self, key, value):
        if key == 'link':
            self.link_value = value
        else:
            super(LinkTab, self).__setitem__(key, value)

    def to_json(self):
        to_json_val = super(LinkTab, self).to_json()
        to_json_val.update({'link': self.link_value})
        return to_json_val

    def __eq__(self, other):
        if not super(LinkTab, self).__eq__(other):
            return False
        return self.link_value == other.get('link')

216
    @classmethod
217
    def is_enabled(cls, course, user=None):
218 219 220 221 222 223 224 225 226 227
        return True


class ExternalDiscussionCourseTab(LinkTab):
    """
    A course tab that links to an external discussion service.
    """

    type = 'external_discussion'
    # Translators: 'Discussion' refers to the tab in the courseware that leads to the discussion forums
228
    title = ugettext_noop('Discussion')
229
    priority = None
230
    is_default = False
231 232 233 234 235 236 237 238

    @classmethod
    def validate(cls, tab_dict, raise_error=True):
        """ Validate that the tab_dict for this course tab has the necessary information to render. """
        return (super(ExternalDiscussionCourseTab, cls).validate(tab_dict, raise_error) and
                key_checker(['link'])(tab_dict, raise_error))

    @classmethod
239
    def is_enabled(cls, course, user=None):
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        if not super(ExternalDiscussionCourseTab, cls).is_enabled(course, user=user):
            return False
        return course.discussion_link


class ExternalLinkCourseTab(LinkTab):
    """
    A course tab containing an external link.
    """
    type = 'external_link'
    priority = None
    is_default = False    # An external link tab is not added to a course by default
    allow_multiple = True

    @classmethod
    def validate(cls, tab_dict, raise_error=True):
        """ Validate that the tab_dict for this course tab has the necessary information to render. """
        return (super(ExternalLinkCourseTab, cls).validate(tab_dict, raise_error) and
                key_checker(['link', 'name'])(tab_dict, raise_error))

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

class SingleTextbookTab(CourseTab):
    """
    A tab representing a single textbook.  It is created temporarily when enumerating all textbooks within a
    Textbook collection tab.  It should not be serialized or persisted.
    """
    type = 'single_textbook'
    is_movable = False
    is_collection_item = True
    priority = None

    def __init__(self, name, tab_id, view_name, index):
        def link_func(course, reverse_func, index=index):
            """ Constructs a link for textbooks from a view name, a course, and an index. """
            return reverse_func(view_name, args=[unicode(course.id), index])

276 277 278 279 280
        tab_dict = dict()
        tab_dict['name'] = name
        tab_dict['tab_id'] = tab_id
        tab_dict['link_func'] = link_func
        super(SingleTextbookTab, self).__init__(tab_dict)
281 282 283

    def to_json(self):
        raise NotImplementedError('SingleTextbookTab should not be serialized.')
284 285


286
def get_course_tab_list(request, course):
287 288 289
    """
    Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
    """
290
    user = request.user
291
    xmodule_tab_list = CourseTabList.iterate_displayable(course, user=user)
292

293 294 295
    # Now that we've loaded the tabs for this course, perform the Entrance Exam work.
    # If the user has to take an entrance exam, we'll need to hide away all but the
    # "Courseware" tab. The tab is then renamed as "Entrance Exam".
296
    course_tab_list = []
297
    must_complete_ee = user_must_complete_entrance_exam(request, user, course)
298
    for tab in xmodule_tab_list:
299
        if must_complete_ee:
300
            # Hide all of the tabs except for 'Courseware'
301
            # Rename 'Courseware' tab to 'Entrance Exam'
302
            if tab.type is not 'courseware':
303
                continue
304
            tab.name = _("Entrance Exam")
305
        course_tab_list.append(tab)
306 307 308

    # Add in any dynamic tabs, i.e. those that are not persisted
    course_tab_list += _get_dynamic_tabs(course, user)
309
    return course_tab_list
310 311 312 313 314 315 316 317 318 319


def _get_dynamic_tabs(course, user):
    """
    Returns the dynamic tab types for the current user.

    Note: dynamic tabs are those that are not persisted in the course, but are
    instead added dynamically based upon the user's role.
    """
    dynamic_tabs = list()
320
    for tab_type in CourseTabPluginManager.get_tab_types():
321
        if getattr(tab_type, "is_dynamic", False):
322
            tab = tab_type(dict())
323
            if tab.is_enabled(course, user=user):
324 325 326
                dynamic_tabs.append(tab)
    dynamic_tabs.sort(key=lambda dynamic_tab: dynamic_tab.name)
    return dynamic_tabs