from twisted.application import service
from twisted.python import log

from axiom import item, attributes

from ikdisplay.source import ISource

class Feed(item.Item):
    """
    A feed represents the aggregate stream of items of its sources.

    To pass notifications onto an aggregator, a Service named C{'aggregator'}
    must have been added as a subservice of the store the feed is stored in:

        >>> agg = LoggingAggregator()
        >>> agg.setName('aggregator')
        >>> agg.setServiceParent(service.IService(store))
    """

    typeName = 'Feed'

    handle = attributes.text(allowNone=False)
    title = attributes.text()
    language = attributes.text(default=u'en')

    def processNotifications(self, notifications):
        """
        Send on notifications to the aggregator.

        This finds the globally available aggregator service and passes it
        the notifications using this feed's handle.
        """
        aggregator = service.IService(self.store).getServiceNamed('aggregator')
        aggregator.processNotifications(self.handle, notifications)


    def getSources(self):
        """ The list of sources for this feed. """
        return list(self.powerupsFor(ISource))


    def getURI(self):
        return "xmpp:feeds.mediamatic.nl?node=" + self.handle



class LoggingAggregator(service.Service):

    def processNotifications(self, feed, notifications):
        for notification in notifications:
            log.msg("%s: %s" % (feed, notification))



class PubSubAggregator(service.Service):
    pubsubService = None

    def __init__(self, service):
        service.Service.__init__(self)
        self.service = service


    def processNotifications(self, feed, notifications):
        self.pubsubHandler.publishNotifications(self.service, feed,
                                                notifications)

@@ -33,16 +33,51 @@
 service%0A
+from twisted.internet import defer%0A
 from twi
@@ -1877,24 +1877,466 @@
          notifications)%0A
+%0A%0A%0Aclass AggregatorFromNotifier(service.Service):%0A%0A    maxHistory = 13%0A%0A    def __init__(self, notifier):%0A        self.notifier = notifier%0A        self.history = %5B%5D%0A%0A%0A    def processNotifications(self, feed, notifications):%0A        map(self.notifier.notify, notifications)%0A        self.history.extend(notifications)%0A        self.history = self.history%5B-self.maxHistory:%5D%0A%0A%0A    def getHistory(self):%0A        return defer.succeed(self.history)%0A

Add an aggregator service that sends notifications directly to web clients.