Exemple #1
0
def platform_img(ctx, url, optional_attributes=None):
    optional_attributes = optional_attributes or {}
    img_urls = {}
    add_high_res = optional_attributes.pop('high-res', False)
    is_l10n = optional_attributes.pop('l10n', False)

    for platform in ALL_FX_PLATFORMS:
        img_urls[platform] = add_string_to_image_url(url, platform)
        if add_high_res:
            img_urls[platform + '-high-res'] = convert_to_high_res(img_urls[platform])

    img_attrs = {}
    for platform, image in img_urls.iteritems():
        if is_l10n:
            image = l10n_img_file_name(ctx, image)

        if find_static(image):
            key = 'data-src-' + platform
            img_attrs[key] = static(image)

    if add_high_res:
        img_attrs['data-high-res'] = 'true'

    img_attrs.update(optional_attributes)
    attrs = ' '.join('%s="%s"' % (attr, val)
                     for attr, val in img_attrs.iteritems())

    # Don't download any image until the javascript sets it based on
    # data-src so we can do platform detection. If no js, show the
    # windows version.
    markup = ('<img class="platform-img js" src="" data-processed="false" {attrs}>'
              '<noscript><img class="platform-img win" src="{win_src}" {attrs}>'
              '</noscript>').format(attrs=attrs, win_src=img_attrs['data-src-windows'])

    return jinja2.Markup(markup)
Exemple #2
0
def render_component(path_to_source, props=None, to_static_markup=False, json_encoder=None):
    if not os.path.isabs(path_to_source):
        # If its using the manifest staticfiles storage, to the hashed name.
        # eg. js/hello.js -> js/hello.d0bf07ff5f07.js
        if isinstance(staticfiles_storage, HashedFilesMixin):
            try:
                path_to_source = staticfiles_storage.stored_name(path_to_source)
            except ValueError:
                # Couldn't find it.
                pass
        # Now resolve it to the absolute path using the finders
        path_to_source = find_static(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    try:
        html = render_core(path_to_source, props, to_static_markup, json_encoder, service_url=SERVICE_URL)
    except:
        if not FAIL_SAFE:
            raise
        log.exception('Error while rendering %s', path_to_source)
        html = ''

    return RenderedComponent(html, path_to_source, props, json_encoder)
Exemple #3
0
def render_component(path_to_source,
                     props=None,
                     to_static_markup=False,
                     json_encoder=None):
    if not os.path.isabs(path_to_source):
        # If its using the manifest staticfiles storage, to the hashed name.
        # eg. js/hello.js -> js/hello.d0bf07ff5f07.js
        if isinstance(staticfiles_storage, HashedFilesMixin):
            try:
                path_to_source = staticfiles_storage.stored_name(
                    path_to_source)
            except ValueError:
                # Couldn't find it.
                pass
        # Now resolve it to the absolute path using the finders
        path_to_source = find_static(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    try:
        html = render_core(path_to_source,
                           props,
                           to_static_markup,
                           json_encoder,
                           service_url=SERVICE_URL)
    except:
        if not FAIL_SAFE:
            raise
        log.exception('Error while rendering %s', path_to_source)
        html = ''

    return RenderedComponent(html, path_to_source, props, json_encoder)
Exemple #4
0
    def add_colophon(self, document, documents=None):
        colophon = self.find_colophon(document or documents[0])
        if colophon:
            html = self.clean_html(
                self.render_colophon(colophon, document, documents))

            # pull in any static images used in the colophon
            doc = ET.HTML(html)
            images = [
                img for img in doc.xpath('//img[@src]')
                if img.get('src').startswith('/static/')
            ]
            # rewrite paths to be relative
            for img in images:
                img.set('src', img.get('src')[1:])
            html = ET.tostring(doc)

            entry = epub.EpubHtml(uid='colophon', file_name='colophon.xhtml')
            entry.content = html
            self.book.add_item(entry)
            self.book.spine.append(entry)

            for fname in set(img.get('src') for img in images):
                local_fname = find_static(fname[7:])
                if local_fname:
                    img = epub.EpubImage()
                    img.file_name = fname
                    with open(local_fname, 'rb') as f:
                        img.content = f.read()
                    self.book.add_item(img)
Exemple #5
0
def platform_img(ctx, url, optional_attributes=None):
    optional_attributes = optional_attributes or {}
    img_urls = {}
    add_high_res = optional_attributes.pop('high-res', False)
    is_l10n = optional_attributes.pop('l10n', False)

    for platform in ALL_FX_PLATFORMS:
        img_urls[platform] = add_string_to_image_url(url, platform)
        if add_high_res:
            img_urls[platform + '-high-res'] = convert_to_high_res(img_urls[platform])

    img_attrs = {}
    for platform, image in img_urls.iteritems():
        if is_l10n:
            image = l10n_img_file_name(ctx, image)

        if find_static(image):
            key = 'data-src-' + platform
            img_attrs[key] = static(image)

    if add_high_res:
        img_attrs['data-high-res'] = 'true'

    img_attrs.update(optional_attributes)
    attrs = ' '.join('%s="%s"' % (attr, val)
                     for attr, val in img_attrs.iteritems())

    # Don't download any image until the javascript sets it based on
    # data-src so we can do platform detection. If no js, show the
    # windows version.
    markup = ('<img class="platform-img js" src="" data-processed="false" {attrs}>'
              '<noscript><img class="platform-img win" src="{win_src}" {attrs}>'
              '</noscript>').format(attrs=attrs, win_src=img_attrs['data-src-windows'])

    return jinja2.Markup(markup)
Exemple #6
0
def find_best_static(candidates, actual=True):
    """ Return the first static file that exists given a list of candidate files.
    """
    for option in candidates:
        log.debug("Looking for %s" % option)
        fname = find_static(option)
        if fname:
            log.debug("Using %s" % fname)
            return fname if actual else option
    def __init__(self, *args, **kwargs):
        context = kwargs.pop('context', self.context)
        template = kwargs.pop('template', self.template)
        stylesheet = kwargs.pop('stylesheet', self.stylesheet)

        super(TemplateEmail, self).__init__(*args, **kwargs)

        self.template = template
        self.stylesheet = find_static(stylesheet)

        self._default_context = {}
        self._override_context = context or {}
Exemple #8
0
    def find_xslt(self, document):
        """ Return the filename of an xslt template to use to render this document.

        The normal Django templating system is used to find a template. The first template
        found is used.
        """
        candidates = file_candidates(document, prefix='xsl/', suffix='.xsl')
        for option in candidates:
            log.debug("Looking for %s" % option)
            fname = find_static(option)
            if fname:
                log.debug("Using xsl %s" % fname)
                return fname

        raise ValueError("Couldn't find XSLT file to use for %s, tried: %s" % (document, candidates))
Exemple #9
0
def render_component(path_to_source, props=None, to_static_markup=False, json_encoder=None):
    if not os.path.isabs(path_to_source):
        path_to_source = find_static(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    try:
        html = render_core(path_to_source, props, to_static_markup, json_encoder, service_url=SERVICE_URL)
    except:
        if not FAIL_SAFE:
            raise
        log.exception('Error while rendering %s', path_to_source)
        html = ''

    return RenderedComponent(html, path_to_source, props, json_encoder)
Exemple #10
0
def holiday_calendars(request, template='mozorg/projects/holiday-calendars.html'):
    """Generate the table of holiday calendars from JSON."""
    calendars = []
    json_file = find_static('caldata/calendars.json')
    with open(json_file) as calendar_data:
        calendars = json.load(calendar_data)

    letters = set()
    for calendar in calendars:
        letters.add(calendar['country'][:1])

    data = {
        'calendars': sorted(calendars, key=lambda k: k['country']),
        'letters': sorted(letters),
        'CALDATA_URL': static('caldata/')
    }

    return l10n_utils.render(request, template, data)
Exemple #11
0
def holiday_calendars(request, template='mozorg/projects/holiday-calendars.html'):
    """Generate the table of holiday calendars from JSON."""
    calendars = []
    json_file = find_static('caldata/calendars.json')
    with open(json_file) as calendar_data:
        calendars = json.load(calendar_data)

    letters = set()
    for calendar in calendars:
        letters.add(calendar['country'][:1])

    data = {
        'calendars': sorted(calendars, key=lambda k: k['country']),
        'letters': sorted(letters),
        'CALDATA_URL': static('caldata/')
    }

    return l10n_utils.render(request, template, data)
Exemple #12
0
def platform_img(ctx, url, optional_attributes=None):
    optional_attributes = optional_attributes or {}
    img_urls = {}
    platforms = optional_attributes.pop("platforms", ALL_FX_PLATFORMS)
    add_high_res = optional_attributes.pop("high-res", False)
    is_l10n = optional_attributes.pop("l10n", False)

    for platform in platforms:
        img_urls[platform] = add_string_to_image_url(url, platform)
        if add_high_res:
            img_urls[platform + "-high-res"] = convert_to_high_res(
                img_urls[platform])

    img_attrs = {}
    for platform, image in img_urls.items():
        if is_l10n:
            image = l10n_img_file_name(ctx, _strip_img_prefix(image))

        if find_static(image):
            key = "data-src-" + platform
            img_attrs[key] = static(image)

    if add_high_res:
        img_attrs["data-high-res"] = "true"

    img_attrs.update(optional_attributes)
    attrs = " ".join(f'{attr}="{val}"' for attr, val in img_attrs.items())

    # Don't download any image until the javascript sets it based on
    # data-src so we can do platform detection. If no js, show the
    # windows version.
    markup = (
        '<img class="platform-img js" src="" data-processed="false" {attrs}>'
        '<noscript><img class="platform-img win" src="{win_src}" {attrs}>'
        "</noscript>").format(attrs=attrs,
                              win_src=img_attrs["data-src-windows"])

    return jinja2.Markup(markup)
Exemple #13
0
def render_component(path_to_source, props=None, to_static_markup=False, json_encoder=None, timeout=TIMEOUT):
    if not os.path.isabs(path_to_source):
        # If its using the manifest staticfiles storage, to the hashed name.
        # eg. js/hello.js -> js/hello.d0bf07ff5f07.js
        if isinstance(staticfiles_storage, HashedFilesMixin):
            try:
                path_to_source = staticfiles_storage.stored_name(path_to_source)
            except ValueError:
                # Couldn't find it.
                pass

        # first, attempt to resolve at STATIC_ROOT if the file was collected
        abs_path = os.path.join(settings.STATIC_ROOT or '', path_to_source)
        if os.path.exists(abs_path):
            path_to_source = abs_path
        else:
            # Otherwise, resolve it using finders
            path_to_source = find_static(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    try:
        html = render_core(
            path_to_source,
            props,
            to_static_markup,
            json_encoder,
            service_url=SERVICE_URL,
            timeout=timeout,
        )
    except Exception:
        if not FAIL_SAFE:
            raise
        log.exception('Error while rendering %s', path_to_source)
        html = ''

    return RenderedComponent(html, path_to_source, props, json_encoder)
Exemple #14
0
def _l10n_media_exists(type, locale, url):
    """ checks if a localized media file exists for the locale """
    return find_static(path.join(type, 'l10n', locale, url)) is not None
Exemple #15
0
def _l10n_media_exists(type, locale, url):
    """ checks if a localized media file exists for the locale """
    return find_static(path.join(type, 'l10n', locale, url)) is not None