Ejemplo n.º 1
0
    def get(self, path):     
        try:
            path = path.strip('/')
            path, extension = os.path.splitext(path)

            contents = cache.get(path + extension)
            last_modified = cache.get(CACHE_LAST_MODIFIED_PREPEND + path + extension)

            if not contents:
                contents = ''

                ''' YUI '''
                yui_parts = '' if path.find('___yui___') < 0 else path[path.find('___yui___'):].replace('___yui___', '', 1)
                yui_parts = yui_parts if yui_parts.find('___') < 0 else yui_parts[:yui_parts.find('___')]
                rest_parts = path.replace('___yui___', '', 1).replace(yui_parts, '', 1).replace('___local___', '', 1)
                if '___theme___' in rest_parts:
                    local_parts, theme_parts = rest_parts.split('___theme___')
                else:
                    local_parts, theme_parts = rest_parts, None
                if yui_parts:
                    yui_version = '3.7.2/build/'
                    yui_absolute = 'http://yui.yahooapis.com/combo?'
                    yui_parts = yui_parts.split('__')
                    yui_parts = [(yui_version + x.replace('_', '/') + '-min' + extension) for x in yui_parts]
                    result = urlfetch.fetch(yui_absolute + '&'.join(yui_parts))
                    if result.status_code == 200:
                        contents += result.content
                    else:
                        raise Exception('NotFound')

                ''' Local '''
                filenames = [(x + extension) for x in local_parts.split('_')]
                if len(filenames) != len(utils.unique_list(filenames)):
                    raise Exception('NotFound')
                files = utils.file_search(filenames)
                if extension == '.css':
                    contents += (''.join([parse_content(open(f, 'r').read(), True) for f in files]))
                else:
                    contents += (''.join([parse_content(open(f, 'r').read()) for f in files]))

                ''' Theme '''
                if theme_parts:
                    theme_namespace, theme_parts = theme_parts.split('___')
                    filenames = [(x + extension) for x in theme_parts.split('_')]
                    if len(filenames) != len(utils.unique_list(filenames)):
                        raise Exception('NotFound')
                    elif is_local_theme_namespace(theme_namespace):
                        if extension == '.css':
                            contents += (''.join([parse_content(open('./themes/' + theme_namespace + '/' + extension.strip('.') + '/' + f, 'r').read(), True, theme_namespace) for f in filenames]))
                        else:
                            contents += (''.join([parse_content(open('./themes/' + theme_namespace + '/' + extension.strip('.') + '/' + f, 'r').read(), False, theme_namespace) for f in filenames]))
                    else:
                        t = get_custom_theme(theme_namespace)
                        for f in filenames:
                            if extension == '.css':
                                index = t.css_filenames.index(f)
                                contents += parse_content(t.css_contents[index], True, theme_namespace)
                            elif extension == '.js':
                                index = t.js_filenames.index(f)
                                contents += parse_content(t.js_contents[index], False, theme_namespace)

                cache.set(path + extension, contents)
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension, last_modified)

            if not contents.strip(): raise Exception('NotFound')

            if not last_modified:
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension, last_modified)

            content_type = 'application/javascript' if extension == '.js' else 'text/css'
            response = webapp2.Response(template.get(contents.strip()), content_type=content_type)
            response.headers['Connection'] = 'Keep-Alive'
            response.headers['Date'] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Last-Modified'] = last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Expires'] = (last_modified + timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.cache_control.no_cache = None
            response.cache_control.public = True
            response.cache_control.max_age = 604800000 # One week
            return response
        except Exception as inst:
            message = ''
            if configuration.debug_mode():
                message = '<div class="status error">' + unicode(inst) + '<br><br>' + traceback.format_exc().replace('\n', '<br><br>') + '</div>'
            response = webapp2.Response(template.get('<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1>Document or file requested by the client was not found.%s</body></html>' % message))
            response.set_status(404)
            return response
Ejemplo n.º 2
0
def html(section, main=''):
    params = {
        'VERSION': os.environ['CURRENT_VERSION_ID'],
        'user': users.get_current_user(),
        'section': section,
        'main': main,
    }

    theme_namespace_template = section.get_theme_namespace_template()

    try:
        if is_local_theme_template(theme_namespace_template):
            template_content = open(
                './themes/' +
                theme_namespace_template.replace('/', '/templates/', 1) +
                '.body', 'r').read()
        else:
            template_content = get_custom_template(theme_namespace_template)
    except TemplateDoesNotExist:
        theme_namespace_template = DEFAULT_LOCAL_THEME_TEMPLATE
        template_content = open(
            './themes/' +
            DEFAULT_LOCAL_THEME_TEMPLATE.replace('/', '/templates/', 1) +
            '.body', 'r').read()

    theme_namespace, _ = theme_namespace_template.split('/')

    body = Template('{% load filters %}' + template_content).render(
        Context(params)).strip()

    menubar = snippet('user-menubar', {
        'section': section,
        'user': users.get_current_user()
    })

    html = render_to_string('outer.html', params).replace(
        '<body></body>', '<body class="%s">%s%s</body>' %
        (' '.join(section.classes), body, menubar), 1)

    section.yuicss, section.css, section.themecss, section.yuijs, section.js, section.localthemejs = (
        utils.unique_list(x) for x in [
            section.yuicss, section.css, section.themecss, section.yuijs,
            section.js, section.localthemejs
        ])

    section.yuicss = '__'.join([
        x[:-4] if x.endswith('.css') else x for x in section.yuicss
    ]).replace('/', '_')
    section.css = '_'.join([
        x[:-4] if x.endswith('.css') else x for x in section.css
    ]).replace('/', '_')
    section.themecss = '_'.join([
        x[:-4] if x.endswith('.css') else x for x in section.themecss
    ]).replace('/', '_')
    section.yuijs = '__'.join([
        x[:-3] if x.endswith('.js') else x for x in section.yuijs
    ]).replace('/', '_')
    section.js = '_'.join([
        x[:-3] if x.endswith('.js') else x for x in section.js
    ]).replace('/', '_')
    section.localthemejs = '_'.join([
        x[:-3] if x.endswith('.js') else x for x in section.localthemejs
    ]).replace('/', '_')

    if section.yuicss: section.yuicss = '___yui___' + section.yuicss
    if section.css: section.css = '___local___' + section.css
    if section.themecss:
        section.themecss = '___theme___' + theme_namespace + '___' + section.themecss

    if section.yuijs: section.yuijs = '___yui___' + section.yuijs
    if section.js: section.js = '___local___' + section.js
    if section.localthemejs:
        section.localthemejs = '___theme___' + theme_namespace + '___' + section.localthemejs

    viewport = '<meta name="viewport" content="' + section.viewport_content + '">' if section.viewport_content else ''
    linkrel = '<link rel="stylesheet" type="text/css" href="/' + section.yuicss + section.css + section.themecss + '.css">' if section.yuicss or section.css or section.themecss else ''
    script = snippet('defer-js-load', {
        'js_file':
        '/' + section.yuijs + section.js + section.localthemejs + '.js'
    }) if section.yuijs or section.js or section.localthemejs else ''
    analytics = snippet(
        'analytics',
        {'GOOGLE_ANALYTICS_UA': section.configuration['GOOGLE_ANALYTICS_UA']
         }) if section.configuration['GOOGLE_ANALYTICS_UA'] else ''

    header_includes = viewport + linkrel + script.replace('\t', '').replace(
        '\n', '') + analytics.replace('\t', '').replace('\n', '')

    if header_includes:
        html = html.replace('</head>', '\t' + header_includes + '\n\t</head>',
                            1)

    return html.strip()
Ejemplo n.º 3
0
def html(section, main=''):
    params = {
        'VERSION': os.environ['CURRENT_VERSION_ID'],
        'user': users.get_current_user(),
        'section': section,
        'main': main,
    }

    theme_namespace_template = section.get_theme_namespace_template()

    try:
        if is_local_theme_template(theme_namespace_template):
            template_content = open('./themes/' + theme_namespace_template.replace('/', '/templates/', 1) + '.body', 'r').read()
        else:
            template_content = get_custom_template(theme_namespace_template)
    except TemplateDoesNotExist:
        theme_namespace_template = DEFAULT_LOCAL_THEME_TEMPLATE
        template_content = open('./themes/' + DEFAULT_LOCAL_THEME_TEMPLATE.replace('/', '/templates/', 1) + '.body', 'r').read()

    theme_namespace, _ = theme_namespace_template.split('/')

    body = Template('{% load filters %}' + template_content).render(Context(params)).strip()

    menubar = snippet('user-menubar', {'section': section, 'user': users.get_current_user()})

    html = render_to_string('outer.html', params).replace('<body></body>',
                                                          '<body class="%s">%s%s</body>' % (' '.join(section.classes), body, menubar),
                                                          1)

    section.yuicss, section.css, section.themecss, section.yuijs, section.js, section.localthemejs = (utils.unique_list(x) for x in [section.yuicss, section.css, section.themecss, section.yuijs, section.js, section.localthemejs])

    section.yuicss = '__'.join([x[:-4] if x.endswith('.css') else x for x in section.yuicss]).replace('/', '_')
    section.css = '_'.join([x[:-4] if x.endswith('.css') else x for x in section.css]).replace('/', '_')
    section.themecss = '_'.join([x[:-4] if x.endswith('.css') else x for x in section.themecss]).replace('/', '_')
    section.yuijs = '__'.join([x[:-3] if x.endswith('.js') else x for x in section.yuijs]).replace('/', '_')
    section.js = '_'.join([x[:-3] if x.endswith('.js') else x for x in section.js]).replace('/', '_')
    section.localthemejs = '_'.join([x[:-3] if x.endswith('.js') else x for x in section.localthemejs]).replace('/', '_')

    if section.yuicss: section.yuicss = '___yui___' + section.yuicss
    if section.css: section.css = '___local___' + section.css
    if section.themecss: section.themecss = '___theme___' + theme_namespace + '___' + section.themecss

    if section.yuijs: section.yuijs = '___yui___' + section.yuijs
    if section.js: section.js = '___local___' + section.js
    if section.localthemejs: section.localthemejs = '___theme___' + theme_namespace + '___' + section.localthemejs

    viewport = '<meta name="viewport" content="' + section.viewport_content + '">' if section.viewport_content else ''
    linkrel = '<link rel="stylesheet" type="text/css" href="/' + section.yuicss + section.css + section.themecss + '.css">' if section.yuicss or section.css or section.themecss else ''
    script = snippet('defer-js-load', {'js_file': '/' + section.yuijs + section.js + section.localthemejs + '.js'}) if section.yuijs or section.js or section.localthemejs else ''
    analytics = snippet('analytics', {'GOOGLE_ANALYTICS_UA': section.configuration['GOOGLE_ANALYTICS_UA']}) if section.configuration['GOOGLE_ANALYTICS_UA'] else ''

    header_includes = viewport + linkrel + script.replace('\t', '').replace('\n', '') + analytics.replace('\t', '').replace('\n', '')

    if header_includes:
        html = html.replace('</head>', '\t' + header_includes + '\n\t</head>', 1)

    return html.strip()
Ejemplo n.º 4
0
    def get(self, path):
        try:
            path = path.strip('/')
            path, extension = os.path.splitext(path)

            contents = cache.get(path + extension)
            last_modified = cache.get(CACHE_LAST_MODIFIED_PREPEND + path +
                                      extension)

            if not contents:
                contents = ''
                ''' YUI '''
                yui_parts = '' if path.find('___yui___') < 0 else path[
                    path.find('___yui___'):].replace('___yui___', '', 1)
                yui_parts = yui_parts if yui_parts.find(
                    '___') < 0 else yui_parts[:yui_parts.find('___')]
                rest_parts = path.replace('___yui___', '', 1).replace(
                    yui_parts, '', 1).replace('___local___', '', 1)
                if '___theme___' in rest_parts:
                    local_parts, theme_parts = rest_parts.split('___theme___')
                else:
                    local_parts, theme_parts = rest_parts, None
                if yui_parts:
                    yui_version = '3.7.2/build/'
                    yui_absolute = 'http://yui.yahooapis.com/combo?'
                    yui_parts = yui_parts.split('__')
                    yui_parts = [(yui_version + x.replace('_', '/') + '-min' +
                                  extension) for x in yui_parts]
                    result = urlfetch.fetch(yui_absolute + '&'.join(yui_parts))
                    if result.status_code == 200:
                        contents += result.content
                    else:
                        raise Exception('NotFound')
                ''' Local '''
                filenames = [(x + extension) for x in local_parts.split('_')]
                if len(filenames) != len(utils.unique_list(filenames)):
                    raise Exception('NotFound')
                files = utils.file_search(filenames)
                if extension == '.css':
                    contents += (''.join([
                        parse_content(open(f, 'r').read(), True) for f in files
                    ]))
                else:
                    contents += (''.join(
                        [parse_content(open(f, 'r').read()) for f in files]))
                ''' Theme '''
                if theme_parts:
                    theme_namespace, theme_parts = theme_parts.split('___')
                    filenames = [(x + extension)
                                 for x in theme_parts.split('_')]
                    if len(filenames) != len(utils.unique_list(filenames)):
                        raise Exception('NotFound')
                    elif is_local_theme_namespace(theme_namespace):
                        if extension == '.css':
                            contents += (''.join([
                                parse_content(
                                    open(
                                        './themes/' + theme_namespace + '/' +
                                        extension.strip('.') + '/' + f,
                                        'r').read(), True, theme_namespace)
                                for f in filenames
                            ]))
                        else:
                            contents += (''.join([
                                parse_content(
                                    open(
                                        './themes/' + theme_namespace + '/' +
                                        extension.strip('.') + '/' + f,
                                        'r').read(), False, theme_namespace)
                                for f in filenames
                            ]))
                    else:
                        t = get_custom_theme(theme_namespace)
                        for f in filenames:
                            if extension == '.css':
                                index = t.css_filenames.index(f)
                                contents += parse_content(
                                    t.css_contents[index], True,
                                    theme_namespace)
                            elif extension == '.js':
                                index = t.js_filenames.index(f)
                                contents += parse_content(
                                    t.js_contents[index], False,
                                    theme_namespace)

                cache.set(path + extension, contents)
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension,
                          last_modified)

            if not contents.strip(): raise Exception('NotFound')

            if not last_modified:
                last_modified = datetime.utcnow()
                cache.set(CACHE_LAST_MODIFIED_PREPEND + path + extension,
                          last_modified)

            content_type = 'application/javascript' if extension == '.js' else 'text/css'
            response = webapp2.Response(template.get(contents.strip()),
                                        content_type=content_type)
            response.headers['Connection'] = 'Keep-Alive'
            response.headers['Date'] = datetime.utcnow().strftime(
                "%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Last-Modified'] = last_modified.strftime(
                "%a, %d %b %Y %H:%M:%S GMT")
            response.headers['Expires'] = (
                last_modified +
                timedelta(8)).strftime("%a, %d %b %Y %H:%M:%S GMT")
            response.cache_control.no_cache = None
            response.cache_control.public = True
            response.cache_control.max_age = 604800000  # One week
            return response
        except Exception as inst:
            message = ''
            if configuration.debug_mode():
                message = '<div class="status error">' + unicode(
                    inst) + '<br><br>' + traceback.format_exc().replace(
                        '\n', '<br><br>') + '</div>'
            response = webapp2.Response(
                template.get(
                    '<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1>Document or file requested by the client was not found.%s</body></html>'
                    % message))
            response.set_status(404)
            return response