views.py 10.8 KB
Newer Older
1 2 3 4
"""Views for the branding app. """
import logging
import urllib

5 6
from django.conf import settings
from django.core.urlresolvers import reverse
7 8 9 10
from django.core.cache import cache
from django.views.decorators.cache import cache_control
from django.http import HttpResponse, Http404
from django.utils import translation
11
from django.shortcuts import redirect
12
from django.views.decorators.csrf import ensure_csrf_cookie
13
from django.contrib.staticfiles.storage import staticfiles_storage
14

15
from edxmako.shortcuts import render_to_response
16
import student.views
17
from student.models import CourseEnrollment
18
import courseware.views.views
David Baumgold committed
19
from edxmako.shortcuts import marketing_link
20
from util.cache import cache_if_anonymous
21 22
from util.json_request import JsonResponse
import branding.api as branding_api
23
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
24 25

log = logging.getLogger(__name__)
26 27


28 29
def get_course_enrollments(user):
    """
30
    Returns the course enrollments for the passed in user within the context of current org, that
31 32 33
    is filtered by course_org_filter
    """
    enrollments = CourseEnrollment.enrollments_for_user(user)
34 35
    course_org = configuration_helpers.get_value('course_org_filter')
    if course_org:
36
        site_enrollments = [
37
            enrollment for enrollment in enrollments if enrollment.course_id.org == course_org
38 39 40 41 42 43 44 45
        ]
    else:
        site_enrollments = [
            enrollment for enrollment in enrollments
        ]
    return site_enrollments


46
@ensure_csrf_cookie
47
@cache_if_anonymous()
48 49 50 51 52
def index(request):
    '''
    Redirects to main page -- info page if user authenticated, or marketing if not
    '''

stv committed
53
    if request.user.is_authenticated():
54
        # Only redirect to dashboard if user has
55 56 57
        # courses in his/her dashboard. Otherwise UX is a bit cryptic.
        # In this case, we want to have the user stay on a course catalog
        # page to make it easier to browse for courses (and register)
58
        if configuration_helpers.get_value(
59 60
                'ALWAYS_REDIRECT_HOMEPAGE_TO_DASHBOARD_FOR_AUTHENTICATED_USER',
                settings.FEATURES.get('ALWAYS_REDIRECT_HOMEPAGE_TO_DASHBOARD_FOR_AUTHENTICATED_USER', True)):
61
            return redirect(reverse('dashboard'))
62

63
    if settings.FEATURES.get('AUTH_USE_CERTIFICATES'):
64
        from external_auth.views import ssl_login
65 66 67 68 69 70
        # Set next URL to dashboard if it isn't set to avoid
        # caching a redirect to / that causes a redirect loop on logout
        if not request.GET.get('next'):
            req_new = request.GET.copy()
            req_new['next'] = reverse('dashboard')
            request.GET = req_new
71
        return ssl_login(request)
72

73
    enable_mktg_site = configuration_helpers.get_value(
74 75 76 77 78
        'ENABLE_MKTG_SITE',
        settings.FEATURES.get('ENABLE_MKTG_SITE', False)
    )

    if enable_mktg_site:
79
        return redirect(settings.MKTG_URLS.get('ROOT'))
80

81
    domain = request.META.get('HTTP_HOST')
82 83

    # keep specialized logic for Edge until we can migrate over Edge to fully use
84
    # configuration.
85
    if domain and 'edge.edx.org' in domain:
86
        return redirect(reverse("signin_user"))
Adam Palay committed
87 88 89 90

    #  we do not expect this case to be reached in cases where
    #  marketing and edge are enabled
    return student.views.index(request, user=request.user)
91

92 93

@ensure_csrf_cookie
94
@cache_if_anonymous()
95 96
def courses(request):
    """
97 98
    Render the "find courses" page. If the marketing site is enabled, redirect
    to that. Otherwise, if subdomain branding is on, this is the university
99
    profile page. Otherwise, it's the edX courseware.views.views.courses page
100
    """
101
    enable_mktg_site = configuration_helpers.get_value(
102 103 104
        'ENABLE_MKTG_SITE',
        settings.FEATURES.get('ENABLE_MKTG_SITE', False)
    )
105 106

    if enable_mktg_site:
107
        return redirect(marketing_link('COURSES'), permanent=True)
108

109
    if not settings.FEATURES.get('COURSES_ARE_BROWSABLE'):
110 111
        raise Http404

Adam Palay committed
112
    #  we do not expect this case to be reached in cases where
113
    #  marketing is enabled or the courses are not browsable
114
    return courseware.views.views.courses(request)
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


def _footer_static_url(request, name):
    """Construct an absolute URL to a static asset. """
    return request.build_absolute_uri(staticfiles_storage.url(name))


def _footer_css_urls(request, package_name):
    """Construct absolute URLs to CSS assets in a package. """
    # We need this to work both in local development and in production.
    # Unfortunately, in local development we don't run the full asset pipeline,
    # so fully processed output files may not exist.
    # For this reason, we use the *css package* name(s), rather than the static file name
    # to identify the CSS file name(s) to include in the footer.
    # We then construct an absolute URI so that external sites (such as the marketing site)
    # can locate the assets.
    package = settings.PIPELINE_CSS.get(package_name, {})
    paths = [package['output_filename']] if not settings.DEBUG else package['source_filenames']
    return [
        _footer_static_url(request, path)
        for path in paths
    ]


def _render_footer_html(request, show_openedx_logo, include_dependencies):
    """Render the footer as HTML.

    Arguments:
        show_openedx_logo (bool): If True, include the OpenEdX logo in the rendered HTML.
        include_dependencies (bool): If True, include JavaScript and CSS dependencies.

    Returns: unicode

    """
    bidi = 'rtl' if translation.get_language_bidi() else 'ltr'
150
    css_name = settings.FOOTER_CSS['openedx'][bidi]
151 152 153 154 155 156 157 158 159

    context = {
        'hide_openedx_link': not show_openedx_logo,
        'footer_js_url': _footer_static_url(request, 'js/footer-edx.js'),
        'footer_css_urls': _footer_css_urls(request, css_name),
        'bidi': bidi,
        'include_dependencies': include_dependencies,
    }

160
    return render_to_response("footer.html", context)
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


@cache_control(must_revalidate=True, max_age=settings.FOOTER_BROWSER_CACHE_MAX_AGE)
def footer(request):
    """Retrieve the branded footer.

    This end-point provides information about the site footer,
    allowing for consistent display of the footer across other sites
    (for example, on the marketing site and blog).

    It can be used in one of two ways:
    1) A client renders the footer from a JSON description.
    2) A browser loads an HTML representation of the footer
        and injects it into the DOM.  The HTML includes
        CSS and JavaScript links.

    In case (2), we assume that the following dependencies
    are included on the page:
    a) JQuery (same version as used in edx-platform)
    b) font-awesome (same version as used in edx-platform)
    c) Open Sans web fonts

    Example: Retrieving the footer as JSON

        GET /api/branding/v1/footer
        Accepts: application/json

        {
            "navigation_links": [
                {
                  "url": "http://example.com/about",
                  "name": "about",
                  "title": "About"
                },
                # ...
            ],
            "social_links": [
                {
                    "url": "http://example.com/social",
                    "name": "facebook",
                    "icon-class": "fa-facebook-square",
202 203
                    "title": "Facebook",
                    "action": "Sign up on Facebook!"
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
                },
                # ...
            ],
            "mobile_links": [
                {
                    "url": "http://example.com/android",
                    "name": "google",
                    "image": "http://example.com/google.png",
                    "title": "Google"
                },
                # ...
            ],
            "legal_links": [
                {
                    "url": "http://example.com/terms-of-service.html",
                    "name": "terms_of_service",
                    "title': "Terms of Service"
                },
                # ...
            ],
            "openedx_link": {
                "url": "http://open.edx.org",
                "title": "Powered by Open edX",
                "image": "http://example.com/openedx.png"
            },
229
            "logo_image": "http://example.com/static/images/logo.png",
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
            "copyright": "EdX, Open edX, and the edX and Open edX logos are \
                registered trademarks or trademarks of edX Inc."
        }


    Example: Retrieving the footer as HTML

        GET /api/branding/v1/footer
        Accepts: text/html


    Example: Including the footer with the "Powered by OpenEdX" logo

        GET /api/branding/v1/footer?show-openedx-logo=1
        Accepts: text/html


    Example: Retrieving the footer in a particular language

        GET /api/branding/v1/footer?language=en
        Accepts: text/html

    Example: Retrieving the footer with all JS and CSS dependencies (for testing)

        GET /api/branding/v1/footer?include-dependencies=1
        Accepts: text/html

    """
    if not branding_api.is_enabled():
        raise Http404

    # Use the content type to decide what representation to serve
    accepts = request.META.get('HTTP_ACCEPT', '*/*')

    # Show the OpenEdX logo in the footer
    show_openedx_logo = bool(request.GET.get('show-openedx-logo', False))

    # Include JS and CSS dependencies
    # This is useful for testing the end-point directly.
    include_dependencies = bool(request.GET.get('include-dependencies', False))

    # Override the language if necessary
    language = request.GET.get('language', translation.get_language())

    # Render the footer information based on the extension
    if 'text/html' in accepts or '*/*' in accepts:
        cache_key = u"branding.footer.{params}.html".format(
            params=urllib.urlencode({
                'language': language,
                'show_openedx_logo': show_openedx_logo,
                'include_dependencies': include_dependencies,
            })
        )
        content = cache.get(cache_key)
        if content is None:
            with translation.override(language):
                content = _render_footer_html(request, show_openedx_logo, include_dependencies)
                cache.set(cache_key, content, settings.FOOTER_CACHE_TIMEOUT)
        return HttpResponse(content, status=200, content_type="text/html; charset=utf-8")

    elif 'application/json' in accepts:
        cache_key = u"branding.footer.{params}.json".format(
            params=urllib.urlencode({
                'language': language,
                'is_secure': request.is_secure(),
            })
        )
        footer_dict = cache.get(cache_key)
        if footer_dict is None:
            with translation.override(language):
                footer_dict = branding_api.get_footer(is_secure=request.is_secure())
                cache.set(cache_key, footer_dict, settings.FOOTER_CACHE_TIMEOUT)
        return JsonResponse(footer_dict, 200, content_type="application/json; charset=utf-8")

    else:
        return HttpResponse(status=406)