Exemplo n.º 1
0
class SimpleConsumer(Consumer):
    grok.name("my.queue")

    connection_id = "test.connection"
    queue = "my.queue"

    marker = IMessage
Exemplo n.º 2
0
class PickleProducer(Producer):
    grok.name("my.picklequeue")

    connection_id = "test.connection"
    queue = "my.picklequeue"

    serializer = "application/x-python-serialize"
Exemplo n.º 3
0
class KeywordSymmetricDifference(KeywordOperator):
    """Compute symmetric difference of keywords."""

    grok.name('symmetric_difference')

    def __call__(self, operand2):
        return self.operand1.symmetric_difference(operand2)
Exemplo n.º 4
0
class SimpleProducer(Producer):
    grok.name("my.queue")

    connection_id = "test.connection"
    queue = "my.queue"

    serializer = "text/plain"
Exemplo n.º 5
0
class Message(zeit.push.message.Message):

    grok.name('twitter')

    @property
    def text(self):
        text = self.config.get('override_text')
        if not text:  # BBB
            self.get_text_from = 'short_text'
            text = super(Message, self).text
        return text

    @property
    def url(self):
        return self.add_query_params(
            super().url,
            wt_zmc='sm.int.zonaudev.twitter.ref.zeitde.redpost.link.x',
            utm_medium='sm',
            utm_source='twitter_zonaudev_int',
            utm_campaign='ref',
            utm_content='zeitde_redpost_link_x',
        )

    @property
    def log_message_details(self):
        return 'Account %s' % self.config.get('account', '-')
Exemplo n.º 6
0
class KeywordIntersection(KeywordOperator):
    """Intersect keywords."""

    grok.name('intersection')

    def __call__(self, operand2):
        return self.operand1.intersection(operand2)
Exemplo n.º 7
0
class RSSFeedContentQuery(ContentQuery):

    grok.name('rss-feed')

    def __call__(self):
        self.total_hits = 0
        feed_data = self._parse_feed()
        self.total_hits = len(feed_data)
        return feed_data

    @property
    def rss_feed(self):
        return self.context.rss_feed

    def _parse_feed(self):
        if not self.rss_feed:
            return []
        items = []
        try:
            content = self._get_feed(self.rss_feed.url, self.rss_feed.timeout)
            xml = lxml.etree.fromstring(content)
        except (requests.exceptions.RequestException,
                lxml.etree.XMLSyntaxError) as e:
            log.debug('Could not fetch feed {}: {}'.format(
                self.rss_feed.url, e))
            return []
        for item in xml.xpath('/rss/channel/item'):
            link = zeit.content.cp.blocks.rss.RSSLink(item, self.rss_feed)
            items.append(link)
        return items

    def _get_feed(self, url, timeout):
        return requests.get(url, timeout=timeout).content
Exemplo n.º 8
0
class BiWeekly(SameWeekdayBase):
    """Recurring biweekly on the same weekday."""

    grok.name('biweekly')
    weight = 11
    title = _('every other week, same weekday (e. g. each second Friday)')
    interval = TWO_WEEKS

    def _get_start_date(self):
        candiate = next_date_of_same_weekday(self.context, self.interval_start)
        # We have to compare the naive datetimes as otherwise the DST
        # difference might be computed into the difference of the two dates:
        naive_candiate = self.combine_with_time_of_context(
            candiate).replace(tzinfo=None)
        naive_context = self.context.replace(tzinfo=None)
        interval = (naive_candiate - naive_context).days
        assert interval % 7 == 0, \
            'Interval has {} days. This is {} weeks and {} days!'.format(
                interval, interval / 7, interval % 7)
        if interval % 14 != 0:
            # odd number of weeks
            candiate = next_date_of_same_weekday(
                self.context, self.interval_start + ONE_WEEK)
        return candiate

    @property
    def info(self):
        return _('${weekday} every other week',
                 mapping={'weekday': self._weekday})
Exemplo n.º 9
0
class BreadcrumbContentProvider(
        grok.MultiAdapter, zope.contentprovider.provider.ContentProviderBase):
    """Content provider rendering the breadcrumbs."""

    grok.adapter(zope.interface.Interface,
                 icemac.addressbook.browser.interfaces.IAddressBookLayer,
                 zope.interface.Interface)
    grok.provides(zope.contentprovider.interfaces.IContentProvider)
    grok.name('breadcrumbs')

    def render(self):
        return '\n'.join(self.rendered_breadcrumbs)

    @property
    def rendered_breadcrumbs(self):
        for bc in reversed(list(self.reversed_breadcrumbs)):
            yield bc.render()

    @property
    def reversed_breadcrumbs(self):
        bc = self.get_breadcrumb(self.__parent__)
        parent = bc.parent
        while parent is not None:
            if bc.show:
                yield bc
            bc = self.get_breadcrumb(parent)
            parent = bc.parent
        assert not bc.show, 'Found a root breadcrumb with show = True'

    def get_breadcrumb(self, context):
        return zope.component.getMultiAdapter((context, self.request),
                                              IBreadcrumb)
Exemplo n.º 10
0
class Yearly(RecurringDateTime):
    """Recurring on the same date each year."""

    grok.name('yearly')
    weight = 100
    title = _('yearly (e. g. 24th of December)')

    def compute(self):
        if self.context > self.interval_end:
            return  # no need to compute: there will be no results
        date = self.context
        index = 0
        # Find first date after interval_start:
        while date < self.interval_start:
            index += 1
            date = add_years(self.context, index)
        # Yield dates in the interval:
        while date < self.interval_end:
            yield date
            index += 1
            date = add_years(self.context, index)

    @property
    def info(self):
        return _('${date} every year',
                 mapping={'date': self.context.strftime('%d.%m.')})
Exemplo n.º 11
0
class PreDeployHookOpenVZ(GlobalUtility):
    implements(IPreDeployHook)
    name('pre-deploy-openvz')

    @defer.inlineCallbacks
    def execute(self, context, *args, **kw):
        @db.ro_transact
        def check_backend(context):
            return context.__parent__.backend != 'openvz'

        if (yield check_backend(context)):
            return

        cmd = args[0]
        vm_parameters = args[1]

        ctid = yield get_current_ctid()

        if ctid is not None:
            log.msg('Deploying %s to %s: hinting CTID (%s)' %
                    (context, context.__parent__, ctid),
                    system='deploy-hook-openvz')
            vm_parameters.update({'ctid': ctid + 1})
        else:
            self._action_log(
                cmd,
                'Information about current global CTID is unavailable yet, '
                'will let it use HN-local value instead',
                system='deploy-hook-openvz')
Exemplo n.º 12
0
class CommonMetadata(Converter):

    interface = zeit.cms.content.interfaces.ICommonMetadata
    # Sort ICommonMetadata first, so others can override its results
    grok.name('AAA_' + interface.__name__)

    entity_types = {
        # BBB map zeit.intrafind entity_type to retresco.
        'Person': 'person',
        'Location': 'location',
        'Organization': 'organisation',
        'free': 'keyword',
    }
    entity_types.update({x: x for x in zeit.retresco.interfaces.ENTITY_TYPES})

    def __call__(self):
        section = None
        if self.context.ressort:
            section = u'/' + self.context.ressort
            if self.context.sub_ressort:
                section += u'/' + self.context.sub_ressort
        result = {
            'title':
            self.context.title,
            'teaser':
            self.context.teaserText or self.context.title,
            # The following (top-level keys) are not strictly required,
            # but are used by TMS UI (for display and filtering).
            'supertitle':
            self.context.supertitle,
            'section':
            section,
            'author':
            u', '.join(
                [x.target.display_name for x in self.context.authorships]
                or [x for x in self.context.authors if x])
        }
        for typ in zeit.retresco.interfaces.ENTITY_TYPES:
            result['rtr_{}s'.format(typ)] = []
        for kw in self.context.keywords:
            key = 'rtr_{}s'.format(
                self.entity_types.get(kw.entity_type, 'keyword'))
            result[key].append(kw.label)

        result['payload'] = {}
        result['payload']['head'] = {
            'authors': [x.target.uniqueId for x in self.context.authorships],
        }
        result['payload']['body'] = {
            'supertitle': self.context.supertitle,
            'title': self.context.title,
            'subtitle': self.context.subtitle,
            'byline': self.context.byline,
        }
        result['payload']['teaser'] = {
            'supertitle': self.context.teaserSupertitle,
            'title': self.context.teaserTitle,
            'text': self.context.teaserText,
        }
        return result
Exemplo n.º 13
0
class OpenVzConsoleView(ConsoleView):
    context(IOpenVzConsole)
    name('webterm')

    @property
    def terminal_protocol(self):
        return OpenVzTerminalProtocol(self.context)
Exemplo n.º 14
0
class TtyConsoleView(ConsoleView):
    context(ITtyConsole)
    name('webterm')

    @property
    def terminal_protocol(self):
        return TtyTerminalProtocol(self.context)
Exemplo n.º 15
0
class KeywordUnion(KeywordOperator):
    """Union keywords."""

    grok.name('union')

    def __call__(self, operand2):
        return self.operand1.union(operand2)
Exemplo n.º 16
0
class Message(zeit.push.message.Message):

    grok.name('facebook')

    @property
    def text(self):
        text = self.config.get('override_text')
        if not text:  # BBB
            self.get_text_from = 'long_text'
            text = super(Message, self).text
        return text

    @property
    def url(self):
        return self.add_query_params(
            super().url,
            wt_zmc='sm.int.zonaudev.facebook.ref.zeitde.redpost.link.x',
            utm_medium='sm',
            utm_source='facebook_zonaudev_int',
            utm_campaign='ref',
            utm_content='zeitde_redpost_link_x',
        )

    @property
    def log_message_details(self):
        return 'Account %s' % self.config.get('account', '-')

    def _disable_message_config(self):
        push = zeit.push.interfaces.IPushMessages(self.context)
        if self.config.get('breaking_news'):
            push.set(self.config, enabled=False, breaking_news=False)
        else:
            push.set(self.config, enabled=False)
Exemplo n.º 17
0
class KeywordDifference(KeywordOperator):
    """Difference keywords."""

    grok.name('difference')

    def __call__(self, operand2):
        return self.operand1.difference(operand2)
Exemplo n.º 18
0
class Container(zeit.edit.container.TypeOnAttributeContainer,
                grok.MultiAdapter):

    grok.provides(IContainer)
    grok.adapts(IContainer, gocept.lxml.interfaces.IObjectified)
    type = 'container'
    grok.name(type)
Exemplo n.º 19
0
class PickleConsumer(Consumer):
    grok.name("my.picklequeue")

    connection_id = "test.connection"
    queue = "my.picklequeue"

    marker = IPickleMessage
Exemplo n.º 20
0
class ForbiddenPage(Page):
    name('')
    context(exceptions.HTTPForbidden)
    require('zope.Public')

    def render(self):
        return _(u"This page is protected and you don't have the credentials.")
Exemplo n.º 21
0
class Volume(Converter):
    """This adapter is for indexing actual IVolume objects. Since ICMSContent
    objects can be adapted to IVolume (finding the associated volume object),
    we explicitly restrict this here (which is different from the baseclass).
    """

    interface = zeit.content.volume.interfaces.IVolume
    grok.name(interface.__name__)

    def __new__(cls, context):
        if not cls.interface.providedBy(context):
            return None
        if sys.version_info < (3, ):
            instance = super(Converter, cls).__new__(cls, None)
        else:
            instance = super(Converter, cls).__new__(cls)
        instance.context = context
        instance.content = context
        return instance

    def __call__(self):
        result = {
            'title': self.context.teaserText or 'Ausgabe',
            'teaser': self.context.teaserText or 'Ausgabe',
        }
        covers = [{
            'id': x.get('id'),
            'product_id': x.get('product_id'),
            'href': x.get('href')
        } for x in self.context.xml.xpath('//covers/cover')]
        if covers:
            result['payload'] = {'head': {'covers': covers}}
        return result
Exemplo n.º 22
0
class Push(Converter):
    """We have to index IPushMessages.message_config explicitly, since the DAV
    property is serialized as xmlpickle, which is not queryable. Additionally,
    we transpose its structure from
    {type: typ1, key1: val1, ...}, {type: typ2, ...}, ...] to
    {
     typ1: {key1: [val1, val2, ...], ...},
     typ2: {key1: [val3, ...], ...},
    }
    to create something that can be queried.
    """

    interface = zeit.push.interfaces.IPushMessages
    grok.name(interface.__name__)

    def __call__(self):
        if not self.context.message_config:
            return {}
        result = {}
        for config in self.context.message_config:
            typ = config.pop('type', None)
            if not typ:
                continue
            config.pop('enabled', None)
            data = result.setdefault(typ, {})
            for key, value in config.items():
                data.setdefault(key, []).append(value)
        return {'payload': {'push': result}}
Exemplo n.º 23
0
class Image(Converter):

    interface = zeit.content.image.interfaces.IImageMetadata
    grok.name(interface.__name__)

    def __new__(cls, context):
        if u'/news/' in context.uniqueId:
            # skip zeit.newsimport images. Unfortunately, image(groups) have no
            # ressort or product-id with which we could filter this.
            return None
        return super(Image, cls).__new__(cls, context)

    def __call__(self):
        title = self.context.title or self.content.__name__
        return {
            # Required fields, so make sure to always index (for zeit.find).
            'title': title,
            'teaser': self.context.caption or title,
            'payload': {
                'body': {
                    'title': title,
                    'text': self.context.caption or title,
                }
            }
        }
Exemplo n.º 24
0
class TestConsumer(Consumer):
    grok.name('my.queue')

    connection_id = 'test.connection'
    queue = 'my.queue'

    marker = ITestMessage
Exemplo n.º 25
0
class HtmlEntryPoint(component.MultiAdapter):
    """ generate a index html. This html site will than
        load extjs framework with css and run the
        application.
    """
    component.name('index')
    component.adapts(IApplicationContext, IRequest)

    tmpl = loader.load('index.html')

    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        resources = fanstatic.get_needed()
        stream = self.tmpl.generate(resources=Markup(resources.render()),
                                    title=self.context.title,
                                    launcher=Markup(self.launcher()))
        self.request.response.mimetype = 'text/html'
        self.request.response.write(stream.render('html', doctype='html'))

    def launcher(self):
        """ create a js script that launch the application.
        """

        js = """
            Ext.onReady(function() {
                Ext.application('%s');
            });
        """
        return js % self.context.application
Exemplo n.º 26
0
class TestProducer(Producer):
    grok.name('my.queue')

    connection_id = 'test.connection'
    queue = 'my.queue'

    serializer = 'text/plain'
Exemplo n.º 27
0
class RequestCredentialsPlugin(component.GlobalUtility):
    """ Fetch credentials from HTTP headers.
    """
    component.name('request_credentials')

    def extractCredentials(self, request):
        """ fetch remote user in the http headers
            and create credentials with it.
        """
        session = ISession(request)
        cred = dict(login=request.params.get(FORM_LOGIN, None),
                    password=request.params.get(FORM_PASSWORD, None))
        if None in cred.values():
            if SESSION_CREDENTIALS in session:
                return session[SESSION_CREDENTIALS]
            else:
                return None
        session[SESSION_CREDENTIALS] = cred
        return cred

    def challenge(self, request):
        return False

    def logout(self, request):
        session = ISession(request)
        re = SESSION_CREDENTIALS in session
        del session[SESSION_CREDENTIALS]
        return re
Exemplo n.º 28
0
class BioReference(zeit.cms.content.reference.Reference):

    grok.implements(zeit.content.author.interfaces.IAuthorBioReference)
    grok.provides(zeit.content.author.interfaces.IAuthorBioReference)
    grok.name('authorbio')

    biography = zeit.cms.content.property.ObjectPathProperty('.biography')
Exemplo n.º 29
0
class Reference(zeit.cms.content.reference.Reference):

    grok.implements(zeit.content.author.interfaces.IAuthorReference)
    grok.provides(zeit.content.author.interfaces.IAuthorReference)
    grok.name('author')

    location = zeit.cms.content.property.ObjectPathProperty('.location')
Exemplo n.º 30
0
class BasicAuthLogoutView(LogoutView):
    context(OmsRoot)
    name('basicauthlogout')
    require('oms.nothing')

    def render_GET(self, request):
        super(BasicAuthLogoutView, self).render_GET(request)
        raise Unauthorized()
Exemplo n.º 31
0
"""
This should fail:
"""
import grokcore.component as grok
grok.name('viewname')