From 3714d0fb11a5511ddb502b230dcb573811cba963 Mon Sep 17 00:00:00 2001 From: Maurits van Rees Date: Tue, 20 May 2008 19:57:53 +0000 Subject: [PATCH] Move new trunk into place. svn path=/feedfeeder/trunk/; revision=65293 --- Products/__init__.py | 6 + Products/feedfeeder/Extensions/AppInstall.py | 23 + Products/feedfeeder/Extensions/Install.py | 214 ++ Products/feedfeeder/Extensions/__init__.py | 1 + Products/feedfeeder/HISTORY.txt | 26 + Products/feedfeeder/README.txt | 91 + Products/feedfeeder/__init__.py | 85 + Products/feedfeeder/browser/__init__.py | 0 Products/feedfeeder/browser/configure.zcml | 46 + Products/feedfeeder/browser/feed-folder.pt | 48 + Products/feedfeeder/browser/feed-item.pt | 115 + Products/feedfeeder/browser/feed.py | 95 + Products/feedfeeder/config.py | 58 + Products/feedfeeder/configure.zcml | 31 + Products/feedfeeder/content/__init__.py | 16 + Products/feedfeeder/content/folder.py | 159 + Products/feedfeeder/content/item.py | 164 + Products/feedfeeder/contenthandler.py | 65 + Products/feedfeeder/doc/__init__.py | 1 + Products/feedfeeder/doc/feedconsuming.txt | 166 + .../feedfeeder/doc/feedfeeder-integration.txt | 291 ++ Products/feedfeeder/events.py | 16 + Products/feedfeeder/feedparser.py | 2864 +++++++++++++++++ Products/feedfeeder/i18n/feedfeeder-de.po | 43 + Products/feedfeeder/i18n/feedfeeder-eu.po | 43 + Products/feedfeeder/i18n/feedfeeder-fr.po | 53 + Products/feedfeeder/i18n/feedfeeder-nl.po | 43 + .../feedfeeder/i18n/feedfeeder-plone-de.po | 21 + .../feedfeeder/i18n/feedfeeder-plone-eu.po | 22 + .../feedfeeder/i18n/feedfeeder-plone-fr.po | 25 + .../feedfeeder/i18n/feedfeeder-plone-nl.po | 21 + Products/feedfeeder/i18n/feedfeeder-plone.pot | 21 + Products/feedfeeder/i18n/feedfeeder.pot | 52 + Products/feedfeeder/i18n/generated.pot | 38 + Products/feedfeeder/interfaces/__init__.py | 19 + Products/feedfeeder/interfaces/consumer.py | 31 + Products/feedfeeder/interfaces/container.py | 52 + .../feedfeeder/interfaces/contenthandler.py | 31 + Products/feedfeeder/interfaces/folderview.py | 31 + Products/feedfeeder/interfaces/item.py | 22 + .../feedfeeder/profiles/default/actions.xml | 16 + .../feedfeeder/profiles/default/catalog.xml | 9 + .../profiles/default/factorytool.xml | 7 + .../profiles/default/feedfeeder_various.txt | 1 + .../profiles/default/import_steps.xml | 9 + .../profiles/default/propertiestool.xml | 8 + .../feedfeeder/profiles/default/skins.xml | 11 + .../feedfeeder/profiles/default/types.xml | 7 + .../profiles/default/types/FeedFeederItem.xml | 55 + .../default/types/FeedfeederFolder.xml | 60 + Products/feedfeeder/rebuild_i18n.sh | 14 + Products/feedfeeder/setuphandlers.py | 34 + .../feedfeeder/skins/feedfeeder/feed_icon.gif | Bin 0 -> 231 bytes .../skins/feedfeeder/feed_viewlet.pt | 12 + .../skins/feedfeeder/latest_items.pt | 21 + .../feedfeeder/skins/feedfeeder/readme.txt | 8 + Products/feedfeeder/tests/MainTestCase.py | 96 + Products/feedfeeder/tests/__init__.py | 14 + Products/feedfeeder/tests/framework.py | 107 + Products/feedfeeder/tests/runalltests.py | 29 + .../feedfeeder/tests/samples/examplefeed.xml | 61 + .../feedfeeder/tests/samples/samplefeed1.xml | 53 + .../feedfeeder/tests/samples/samplefeed2.xml | 29 + .../feedfeeder/tests/samples/samplefeed3.xml | 19 + .../feedfeeder/tests/samples/samplefeed4.xml | 19 + Products/feedfeeder/tests/samples/test1.pdf | Bin 0 -> 1000 bytes Products/feedfeeder/tests/samples/test2.doc | 1 + Products/feedfeeder/tests/samples/test3.xls | 1 + .../tests/testDocIntegrationTests.py | 30 + Products/feedfeeder/tests/testDocUnitTests.py | 44 + .../feedfeeder/tests/testFeedfeederFolder.py | 62 + Products/feedfeeder/utilities.py | 230 ++ Products/feedfeeder/version.txt | 1 + docs/INSTALL.txt | 35 + docs/LICENSE.GPL | 222 ++ docs/LICENSE.txt | 16 + setup.py | 35 + 77 files changed, 6525 insertions(+) create mode 100644 Products/__init__.py create mode 100644 Products/feedfeeder/Extensions/AppInstall.py create mode 100644 Products/feedfeeder/Extensions/Install.py create mode 100644 Products/feedfeeder/Extensions/__init__.py create mode 100644 Products/feedfeeder/HISTORY.txt create mode 100644 Products/feedfeeder/README.txt create mode 100644 Products/feedfeeder/__init__.py create mode 100644 Products/feedfeeder/browser/__init__.py create mode 100644 Products/feedfeeder/browser/configure.zcml create mode 100644 Products/feedfeeder/browser/feed-folder.pt create mode 100644 Products/feedfeeder/browser/feed-item.pt create mode 100644 Products/feedfeeder/browser/feed.py create mode 100644 Products/feedfeeder/config.py create mode 100644 Products/feedfeeder/configure.zcml create mode 100644 Products/feedfeeder/content/__init__.py create mode 100644 Products/feedfeeder/content/folder.py create mode 100644 Products/feedfeeder/content/item.py create mode 100644 Products/feedfeeder/contenthandler.py create mode 100644 Products/feedfeeder/doc/__init__.py create mode 100644 Products/feedfeeder/doc/feedconsuming.txt create mode 100644 Products/feedfeeder/doc/feedfeeder-integration.txt create mode 100644 Products/feedfeeder/events.py create mode 100755 Products/feedfeeder/feedparser.py create mode 100644 Products/feedfeeder/i18n/feedfeeder-de.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-eu.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-fr.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-nl.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-plone-de.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-plone-eu.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-plone-fr.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-plone-nl.po create mode 100644 Products/feedfeeder/i18n/feedfeeder-plone.pot create mode 100644 Products/feedfeeder/i18n/feedfeeder.pot create mode 100644 Products/feedfeeder/i18n/generated.pot create mode 100644 Products/feedfeeder/interfaces/__init__.py create mode 100644 Products/feedfeeder/interfaces/consumer.py create mode 100644 Products/feedfeeder/interfaces/container.py create mode 100644 Products/feedfeeder/interfaces/contenthandler.py create mode 100644 Products/feedfeeder/interfaces/folderview.py create mode 100644 Products/feedfeeder/interfaces/item.py create mode 100644 Products/feedfeeder/profiles/default/actions.xml create mode 100644 Products/feedfeeder/profiles/default/catalog.xml create mode 100644 Products/feedfeeder/profiles/default/factorytool.xml create mode 100644 Products/feedfeeder/profiles/default/feedfeeder_various.txt create mode 100644 Products/feedfeeder/profiles/default/import_steps.xml create mode 100644 Products/feedfeeder/profiles/default/propertiestool.xml create mode 100644 Products/feedfeeder/profiles/default/skins.xml create mode 100644 Products/feedfeeder/profiles/default/types.xml create mode 100644 Products/feedfeeder/profiles/default/types/FeedFeederItem.xml create mode 100644 Products/feedfeeder/profiles/default/types/FeedfeederFolder.xml create mode 100755 Products/feedfeeder/rebuild_i18n.sh create mode 100644 Products/feedfeeder/setuphandlers.py create mode 100644 Products/feedfeeder/skins/feedfeeder/feed_icon.gif create mode 100644 Products/feedfeeder/skins/feedfeeder/feed_viewlet.pt create mode 100644 Products/feedfeeder/skins/feedfeeder/latest_items.pt create mode 100644 Products/feedfeeder/skins/feedfeeder/readme.txt create mode 100644 Products/feedfeeder/tests/MainTestCase.py create mode 100644 Products/feedfeeder/tests/__init__.py create mode 100644 Products/feedfeeder/tests/framework.py create mode 100644 Products/feedfeeder/tests/runalltests.py create mode 100644 Products/feedfeeder/tests/samples/examplefeed.xml create mode 100644 Products/feedfeeder/tests/samples/samplefeed1.xml create mode 100644 Products/feedfeeder/tests/samples/samplefeed2.xml create mode 100644 Products/feedfeeder/tests/samples/samplefeed3.xml create mode 100644 Products/feedfeeder/tests/samples/samplefeed4.xml create mode 100644 Products/feedfeeder/tests/samples/test1.pdf create mode 100644 Products/feedfeeder/tests/samples/test2.doc create mode 100644 Products/feedfeeder/tests/samples/test3.xls create mode 100644 Products/feedfeeder/tests/testDocIntegrationTests.py create mode 100644 Products/feedfeeder/tests/testDocUnitTests.py create mode 100644 Products/feedfeeder/tests/testFeedfeederFolder.py create mode 100644 Products/feedfeeder/utilities.py create mode 100644 Products/feedfeeder/version.txt create mode 100644 docs/INSTALL.txt create mode 100644 docs/LICENSE.GPL create mode 100644 docs/LICENSE.txt create mode 100644 setup.py diff --git a/Products/__init__.py b/Products/__init__.py new file mode 100644 index 0000000..f48ad10 --- /dev/null +++ b/Products/__init__.py @@ -0,0 +1,6 @@ +# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) diff --git a/Products/feedfeeder/Extensions/AppInstall.py b/Products/feedfeeder/Extensions/AppInstall.py new file mode 100644 index 0000000..e05f31c --- /dev/null +++ b/Products/feedfeeder/Extensions/AppInstall.py @@ -0,0 +1,23 @@ +from StringIO import StringIO +from Products.CMFCore.utils import getToolByName + + +def install(site): + out = StringIO() + applyGenericSetupProfile(site, out) + + +def applyGenericSetupProfile(site, out): + """Just apply our own extension profile. + """ + + setup_tool = getToolByName(site, 'portal_setup') + setup_tool.setImportContext('profile-feedfeeder:default') + print >> out, "Applying the generic setup profile for feedfeeder..." + setup_tool.runAllImportSteps(purge_old=False) + try: + setup_tool.setImportContext('profile-CMFPlone:plone') + except KeyError: + # Plone 3.0 has a different profile name + setup_tool.setImportContext('profile-Products.CMFPlone:plone') + print >> out, "Applied the generic setup profile for feedfeeder" diff --git a/Products/feedfeeder/Extensions/Install.py b/Products/feedfeeder/Extensions/Install.py new file mode 100644 index 0000000..a217532 --- /dev/null +++ b/Products/feedfeeder/Extensions/Install.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- + +import os.path +import sys +from StringIO import StringIO +from sets import Set +from App.Common import package_home +from Products.CMFCore.utils import getToolByName +from Products.CMFCore.utils import manage_addTool +from Products.ExternalMethod.ExternalMethod import ExternalMethod +from zExceptions import NotFound, BadRequest + +from Products.Archetypes.Extensions.utils import installTypes +from Products.Archetypes.Extensions.utils import install_subskin +from Products.Archetypes.config import TOOL_NAME as ARCHETYPETOOLNAME +from Products.Archetypes.atapi import listTypes +from Products.feedfeeder.config import PROJECTNAME +from Products.feedfeeder.config import product_globals as GLOBALS + +def install(self, reinstall=False): + """ External Method to install feedfeeder """ + out = StringIO() + print >> out, "Installation log of %s:" % PROJECTNAME + + # If the config contains a list of dependencies, try to install + # them. Add a list called DEPENDENCIES to your custom + # AppConfig.py (imported by config.py) to use it. + try: + from Products.feedfeeder.config import DEPENDENCIES + except: + DEPENDENCIES = [] + portal = getToolByName(self,'portal_url').getPortalObject() + quickinstaller = portal.portal_quickinstaller + for dependency in DEPENDENCIES: + print >> out, "Installing dependency %s:" % dependency + quickinstaller.installProduct(dependency) + import transaction + transaction.savepoint(optimistic=True) + + classes = listTypes(PROJECTNAME) + installTypes(self, out, + classes, + PROJECTNAME) + install_subskin(self, out, GLOBALS) + + + # try to call a workflow install method + # in 'InstallWorkflows.py' method 'installWorkflows' + try: + installWorkflows = ExternalMethod('temp', 'temp', + PROJECTNAME+'.InstallWorkflows', + 'installWorkflows').__of__(self) + except NotFound: + installWorkflows = None + + if installWorkflows: + print >>out,'Workflow Install:' + res = installWorkflows(self,out) + print >>out,res or 'no output' + else: + print >>out,'no workflow install' + + + # enable portal_factory for given types + factory_tool = getToolByName(self,'portal_factory') + factory_types=[ + "FeedConsumer", + "StandardContentHandler", + "FeedfeederFolder", + "FeedFeederItem", + ] + factory_tool.getFactoryTypes().keys() + factory_tool.manage_setPortalFactoryTypes(listOfTypeIds=factory_types) + + from Products.feedfeeder.config import STYLESHEETS + try: + portal_css = getToolByName(portal, 'portal_css') + for stylesheet in STYLESHEETS: + try: + portal_css.unregisterResource(stylesheet['id']) + except: + pass + defaults = {'id': '', + 'media': 'all', + 'enabled': True} + defaults.update(stylesheet) + portal_css.manage_addStylesheet(**defaults) + except: + # No portal_css registry + pass + from Products.feedfeeder.config import JAVASCRIPTS + try: + portal_javascripts = getToolByName(portal, 'portal_javascripts') + for javascript in JAVASCRIPTS: + try: + portal_javascripts.unregisterResource(javascript['id']) + except: + pass + defaults = {'id': ''} + defaults.update(javascript) + portal_javascripts.registerScript(**defaults) + except: + # No portal_javascripts registry + pass + + # try to call a custom install method + # in 'AppInstall.py' method 'install' + try: + install = ExternalMethod('temp', 'temp', + PROJECTNAME+'.AppInstall', 'install') + except NotFound: + install = None + + if install: + print >>out,'Custom Install:' + try: + res = install(self, reinstall) + except TypeError: + res = install(self) + if res: + print >>out,res + else: + print >>out,'no output' + else: + print >>out,'no custom install' + return out.getvalue() + +def uninstall(self, reinstall=False): + out = StringIO() + + # try to call a workflow uninstall method + # in 'InstallWorkflows.py' method 'uninstallWorkflows' + try: + uninstallWorkflows = ExternalMethod('temp', 'temp', + PROJECTNAME+'.InstallWorkflows', + 'uninstallWorkflows').__of__(self) + except NotFound: + uninstallWorkflows = None + + if uninstallWorkflows: + print >>out, 'Workflow Uninstall:' + res = uninstallWorkflows(self, out) + print >>out, res or 'no output' + else: + print >>out,'no workflow uninstall' + + # try to call a custom uninstall method + # in 'AppInstall.py' method 'uninstall' + try: + uninstall = ExternalMethod('temp', 'temp', + PROJECTNAME+'.AppInstall', 'uninstall') + except: + uninstall = None + + if uninstall: + print >>out,'Custom Uninstall:' + try: + res = uninstall(self, reinstall) + except TypeError: + res = uninstall(self) + if res: + print >>out,res + else: + print >>out,'no output' + else: + print >>out,'no custom uninstall' + + return out.getvalue() + +def beforeUninstall(self, reinstall, product, cascade): + """ try to call a custom beforeUninstall method in 'AppInstall.py' + method 'beforeUninstall' + """ + out = StringIO() + try: + beforeuninstall = ExternalMethod('temp', 'temp', + PROJECTNAME+'.AppInstall', 'beforeUninstall') + except: + beforeuninstall = [] + + if beforeuninstall: + print >>out, 'Custom beforeUninstall:' + res = beforeuninstall(self, reinstall=reinstall + , product=product + , cascade=cascade) + if res: + print >>out, res + else: + print >>out, 'no output' + else: + print >>out, 'no custom beforeUninstall' + return (out,cascade) + +def afterInstall(self, reinstall, product): + """ try to call a custom afterInstall method in 'AppInstall.py' method + 'afterInstall' + """ + out = StringIO() + try: + afterinstall = ExternalMethod('temp', 'temp', + PROJECTNAME+'.AppInstall', 'afterInstall') + except: + afterinstall = None + + if afterinstall: + print >>out, 'Custom afterInstall:' + res = afterinstall(self, product=None + , reinstall=None) + if res: + print >>out, res + else: + print >>out, 'no output' + else: + print >>out, 'no custom afterInstall' + return out diff --git a/Products/feedfeeder/Extensions/__init__.py b/Products/feedfeeder/Extensions/__init__.py new file mode 100644 index 0000000..e784eb4 --- /dev/null +++ b/Products/feedfeeder/Extensions/__init__.py @@ -0,0 +1 @@ +# make me a python module diff --git a/Products/feedfeeder/HISTORY.txt b/Products/feedfeeder/HISTORY.txt new file mode 100644 index 0000000..40c539d --- /dev/null +++ b/Products/feedfeeder/HISTORY.txt @@ -0,0 +1,26 @@ +1.0 beta 4 (unreleased) +----------------------- + +- Eggification: you can now install it as the Products.feedfeeder + egg. [maurits] + + +1.0 beta 3 (13 May 2008) +------------------------ + +- In the tests, use plone_workflow explicitly, so it is easier to test + on both Plone 2.5 and 3.0. [maurits] + +- Make update_feed_items available in the object_buttons for Plone 3, + using new small @@is_feedcontainer as condition. [maurits] + +- Avoid deprecation warnings for events and interfaces. [maurits] + +- Remove semicolon in page template that broke in Plone 3. [maurits] + +- Fix imports so they work in Plone 3 as well, without deprecation + warnings. [derstappenit] + + +1.0 beta 2 (2 January 2008) +--------------------------- diff --git a/Products/feedfeeder/README.txt b/Products/feedfeeder/README.txt new file mode 100644 index 0000000..c83d59d --- /dev/null +++ b/Products/feedfeeder/README.txt @@ -0,0 +1,91 @@ +Feedfeeder +========== + +Feedfeeder has just a few things it needs to do: + +- Read in a few ATOM feeds (not too many). + +- Create FeedfeederItems out of the entries pulled from the ATOM feeds. + Any feed items that contain enclosures will have the enclosures + pulled down and added as File items to the feed item. + +- This means figuring out which items are new, which also means having + a good ID generating mechanism. + + +Wait, no existing product? +-------------------------- + +There's a whole slew of RSS/ATOM reading products for zope and +plone. None of them seemed to be a good fit. There was only one +product that actually stored the entries in the zope database, but +that was aimed at a lot of users individually adding a lot of feeds, +so it needed either a separate ZEO process (old version) or a +standalone mysql database (new version). + +All the other products didn't store the entries in the database, were +old/unmaintained/etc. + +In a sense, we're using an existing product as we use Mark Pilgrim's +excellent feedparser (http://feedparser.org) that'll do the actual +ATOM reading for us. + + +Product name +------------ + +The product feeds the content of ATOM feeds to plone as document/file +content types. So "feedfeeder" sort of suggested itself as a funny +name. Fun is important :-) + + +Product structure +----------------- + +I'm using archgenxml to generate the boiler plate stuff. There's a +'generate.sh' shell script that'll call archgenxml for you. Nothing +fancy. + +The feedfeeder's content types are: + - folder.FeedfeederFolder + - item.FeedfeederItem + + +How it works +------------ + +A feedfeeder is a folder which contains all the previously-added feed +entries as documents or files. It has a 'feeds' attribute that +contains a list of feeds to read. + +Feedparser is called periodically (through a cron job?) to parse the +feeds. The UID of the items in the feed are converted to a suitable +filename (md5 hex hash of the atom id of the entry), that way you can +detect whether there are new items. + +New items are turned into feed items. + +Scheduled updates for feed folders + +Zope can be configured to periodically trigger a url call. +In zope.conf you can use the directive to define a schedule and url +with the following data. + + method /path_to_feedfolder/update_feed_items + period 3600 # seconds + user admin + password 123 + host localhost:8080 + + + +Tests +----- + +The look-here-first test is the doctest at 'doc/testDocIntegrationTests.txt'. + +Testing is best done with zope's zopectl. 'instancemanager + --test feedfeeder' will do that for you if you've set +up instancemanager. Otherwise 'bin/zopectl test -s +Products.feedfeeder'. + diff --git a/Products/feedfeeder/__init__.py b/Products/feedfeeder/__init__.py new file mode 100644 index 0000000..dc81194 --- /dev/null +++ b/Products/feedfeeder/__init__.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +# There are three ways to inject custom code here: +# +# - To set global configuration variables, create a file AppConfig.py. +# This will be imported in config.py, which in turn is imported in +# each generated class and in this file. +# - To perform custom initialisation after types have been registered, +# use the protected code section at the bottom of initialize(). +# - To register a customisation policy, create a file CustomizationPolicy.py +# with a method register(context) to register the policy. + +from zLOG import LOG, INFO, DEBUG + +LOG('feedfeeder', DEBUG, 'Installing Product') + +try: + import CustomizationPolicy +except ImportError: + CustomizationPolicy = None + +from Globals import package_home +from Products.CMFCore import utils as cmfutils +from Products.CMFCore import permissions +from Products.CMFCore import DirectoryView +from Products.CMFPlone.utils import ToolInit +from Products.Archetypes.atapi import * +from Products.Archetypes import listTypes +from Products.Archetypes.utils import capitalize + +import os, os.path + +from Products.feedfeeder.config import * + +DirectoryView.registerDirectory('skins', product_globals) +DirectoryView.registerDirectory('skins/feedfeeder', + product_globals) + +##code-section custom-init-head #fill in your manual code here +from Products.GenericSetup import EXTENSION +from Products.GenericSetup import profile_registry +import Products.CMFPlone.interfaces +##/code-section custom-init-head + + +def initialize(context): + ##code-section custom-init-top #fill in your manual code here + ##/code-section custom-init-top + + # imports packages and types for registration + import content + import interfaces + + import utilities + import contenthandler + + # Initialize portal content + content_types, constructors, ftis = process_types( + listTypes(PROJECTNAME), + PROJECTNAME) + + cmfutils.ContentInit( + PROJECTNAME + ' Content', + content_types = content_types, + permission = DEFAULT_ADD_CONTENT_PERMISSION, + extra_constructors = constructors, + fti = ftis, + ).initialize(context) + + # Apply customization-policy, if theres any + if CustomizationPolicy and hasattr(CustomizationPolicy, 'register'): + CustomizationPolicy.register(context) + print 'Customization policy for feedfeeder installed' + + ##code-section custom-init-bottom #fill in your manual code here + profile_registry.registerProfile( + name='default', + title='Feedfeeder', + description='Profile for Feedfeeder', + path='profiles/default', + product='feedfeeder', + profile_type=EXTENSION, + for_=Products.CMFPlone.interfaces.IPloneSiteRoot) + ##/code-section custom-init-bottom + diff --git a/Products/feedfeeder/browser/__init__.py b/Products/feedfeeder/browser/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Products/feedfeeder/browser/configure.zcml b/Products/feedfeeder/browser/configure.zcml new file mode 100644 index 0000000..bbd9677 --- /dev/null +++ b/Products/feedfeeder/browser/configure.zcml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + diff --git a/Products/feedfeeder/browser/feed-folder.pt b/Products/feedfeeder/browser/feed-folder.pt new file mode 100644 index 0000000..80bf4f5 --- /dev/null +++ b/Products/feedfeeder/browser/feed-folder.pt @@ -0,0 +1,48 @@ + + + +
+ +
+ +

+ +
+ +

+ + + + + + + + + +
+ 2006-11-10 + + My Title +
My summary
+
+ + +
+
+ + diff --git a/Products/feedfeeder/browser/feed-item.pt b/Products/feedfeeder/browser/feed-item.pt new file mode 100644 index 0000000..dafe146 --- /dev/null +++ b/Products/feedfeeder/browser/feed-item.pt @@ -0,0 +1,115 @@ + + + +
+ +
+ +

+ +
+ + + + + by + + + + — + + + + + last modified + + + August 16, 2001 + + + + — expired + + + + Object locked + + +
+ Contributors: + + Mary + +
+ + +
+ Copyleft NiceCorp Inc. +
+
+ + + +
+ +

+ +

+ This item does not have any body text, click the edit tab to change it. +

+ +
+
+
+ + +

Enclosures

+ + +
+ + +
+ + diff --git a/Products/feedfeeder/browser/feed.py b/Products/feedfeeder/browser/feed.py new file mode 100644 index 0000000..6510bde --- /dev/null +++ b/Products/feedfeeder/browser/feed.py @@ -0,0 +1,95 @@ +from zope import interface +from zope import component +from Products.feedfeeder.interfaces.consumer import IFeedConsumer +from Products.feedfeeder.interfaces.container import IFeedsContainer + +class IUpdateFeedItems(interface.Interface): + def update(): pass + + + +class IsFeedContainer(object): + + def __init__(self, context, request): + self.context = context + self.request = request + + def is_feedcontainer(self): + return IFeedsContainer.providedBy(self.context) + + +class UpdateFeedItems(object): + """A view for updating the feed items in a feed folder. + """ + + interface.implements(IUpdateFeedItems) + + def __init__(self, context, request): + self.context = context + self.request = request + + def update(self): + consumer = component.getUtility(IFeedConsumer) + consumer.retrieveFeedItems(self.context) + + def __call__(self): + self.update() + self.request.response.redirect( + self.context.absolute_url() + +"?portal_status_message=Feed+items+updated") + + +class FeedFolderView(object): + """A view for feed folders. + """ + + def __init__(self, context, request): + self.context = context + self.request = request + + @property + def items(self): + """Return all feed items. + + Currently implemented as a generator since there could + theoretically be tens of thousands of items. + """ + + listing = self.context.getFolderContents + results = listing({'sort_on': 'getFeedItemUpdated', + 'sort_order': 'descending', + 'portal_type': 'FeedFeederItem'}) + if not results and self.context.portal_type == 'Topic': + # Use the queryCatalog of the Topic itself. + results = self.context.queryCatalog( + portal_type='FeedFeederItem') + for index, x in enumerate(results): + content_url = x.getURL() + item = dict(updated_date = x.getFeedItemUpdated, + url = content_url, + content_url = content_url, + title = x.Title, + summary = x.Description, + author = x.getFeedItemAuthor, + has_text = x.getHasBody, + target_link = x.getLink, + ) + self.extraDecoration(item, x) + enclosures = x.getObjectids + + if (enclosures and enclosures is not None and + len(enclosures) == 1): + # only one enclosure? return item title but return link + # to sole enclosure, unless there is some body text. + if not int(x.getHasBody): + item['url'] = item['url'] + '/' + enclosures[0] + yield item + + def extraDecoration(self, item, brain): + pass + + def item_list(self): + return [x for x in self.items] + + def __call__(self, *args, **kwargs): + return self.index(template_id='feed-folder.html') diff --git a/Products/feedfeeder/config.py b/Products/feedfeeder/config.py new file mode 100644 index 0000000..91dc50f --- /dev/null +++ b/Products/feedfeeder/config.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- + +# Product configuration. +# +# The contents of this module will be imported into __init__.py, the +# workflow configuration and every content type module. +# +# If you wish to perform custom configuration, you may put a file +# AppConfig.py in your product's root directory. This will be included +# in this file if found. + +from Products.CMFCore.permissions import setDefaultRoles +##code-section config-head #fill in your manual code here +##/code-section config-head + + +PROJECTNAME = "feedfeeder" + +# Check for Plone 2.1 +try: + from Products.CMFPlone.migrations import v2_1 +except ImportError: + HAS_PLONE21 = False +else: + HAS_PLONE21 = True + +# Permissions +#DEFAULT_ADD_CONTENT_PERMISSION = "Add portal content" +DEFAULT_ADD_CONTENT_PERMISSION = "%s: Add" % PROJECTNAME +setDefaultRoles(DEFAULT_ADD_CONTENT_PERMISSION, ('Manager', 'Owner')) + +product_globals = globals() + +# Dependencies of Products to be installed by quick-installer +# override in custom configuration +DEPENDENCIES = [] + +# Dependend products - not quick-installed - used in testcase +# override in custom configuration +PRODUCT_DEPENDENCIES = [] + +# You can overwrite these two in an AppConfig.py: +# STYLESHEETS = [{'id': 'my_global_stylesheet.css'}, +# {'id': 'my_contenttype.css', +# 'expression': 'python:object.getTypeInfo().getId() == "MyType"'}] +# You can do the same with JAVASCRIPTS. +STYLESHEETS = [] +JAVASCRIPTS = [] + +##code-section config-bottom #fill in your manual code here +##/code-section config-bottom + + +# Load custom configuration not managed by ArchGenXML +try: + from Products.feedfeeder.AppConfig import * +except ImportError: + pass diff --git a/Products/feedfeeder/configure.zcml b/Products/feedfeeder/configure.zcml new file mode 100644 index 0000000..1cbd37d --- /dev/null +++ b/Products/feedfeeder/configure.zcml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + diff --git a/Products/feedfeeder/content/__init__.py b/Products/feedfeeder/content/__init__.py new file mode 100644 index 0000000..4954f33 --- /dev/null +++ b/Products/feedfeeder/content/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +##code-section init-module-header #fill in your manual code here +##/code-section init-module-header + + +# Subpackages +# Additional + +# Classes +import folder +import item + +##code-section init-module-footer #fill in your manual code here +##/code-section init-module-footer + diff --git a/Products/feedfeeder/content/folder.py b/Products/feedfeeder/content/folder.py new file mode 100644 index 0000000..93a65ac --- /dev/null +++ b/Products/feedfeeder/content/folder.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +from AccessControl import ClassSecurityInfo +from Products.Archetypes.atapi import * +from zope import interface +from Products.ATContentTypes.content.folder import ATBTreeFolder +from Products.feedfeeder.interfaces.container import IFeedsContainer +from Products.feedfeeder.config import * +from Products.CMFCore.utils import getToolByName + +##code-section module-header #fill in your manual code here +##/code-section module-header + +schema = Schema(( + + LinesField( + name='feeds', + widget=LinesWidget( + label='Feeds', + label_msgid='feedfeeder_label_feeds', + i18n_domain='feedfeeder', + ) + ), + + StringField( + name='defaultTransition', + vocabulary='getAvailableTransitions', + widget=SelectionWidget( + format='select', + description="When updating this feed's item the transition selected below will be performed.", + description_msgid="help_default_transition", + label='Default transition', + label_msgid='label_default_transition', + i18n_domain='feedfeeder', + ) + ), +), +) + +##code-section after-local-schema #fill in your manual code here +##/code-section after-local-schema + +FeedfeederFolder_schema = ATBTreeFolder.schema.copy() + \ + schema.copy() + +##code-section after-schema #fill in your manual code here +##/code-section after-schema + +class FeedfeederFolder(ATBTreeFolder): + """ + """ + security = ClassSecurityInfo() + # zope3 interfaces + interface.implements(IFeedsContainer) + + # This name appears in the 'add' box + archetype_name = 'Feed Folder' + + meta_type = 'FeedfeederFolder' + portal_type = 'FeedfeederFolder' + allowed_content_types = ['FeedFeederItem'] + filter_content_types = 1 + global_allow = 1 + content_icon = 'feed_icon.gif' + immediate_view = 'feed-folder.html' + default_view = 'feed-folder.html' + suppl_views = () + typeDescription = "Feed Folder" + typeDescMsgId = 'description_edit_feedfeederfolder' + + + actions = ( + + + {'action': "string:${object_url}/update_feed_items", + 'category': "object_buttons", + 'id': 'update_feed_items', + 'name': 'Update Feed Items', + 'permissions': ("View",), + 'condition': 'python:1' + }, + + + {'action': "string:$object_url/feed-folder.html", + 'category': "object", + 'id': 'view', + 'name': 'view', + 'permissions': ("View",), + 'condition': 'python:1' + }, + + + ) + + _at_rename_after_creation = True + + schema = FeedfeederFolder_schema + + ##code-section class-header #fill in your manual code here + ##/code-section class-header + + # Methods + + # Methods from Interface IFeedsContainer + + security.declarePublic('getItem') + + def getAvailableTransitions(self): + # Create a temporary object so we can ask what transitions are + # available for it. + id = 'temp_zest_temp' + self.invokeFactory('FeedFeederItem', id) + wf_tool = getToolByName(self,'portal_workflow') + transitions = wf_tool.getTransitionsFor(self[id]) + display_trans = [('', 'Keep initial state'),] + for trans in transitions: + display_trans.append( ( trans['id'], trans['name'] ) ) + # Unindex and remove the temporary object + self[id].unindexObject() + self._delOb(id) + return DisplayList(display_trans) + + def getItem(self,id): + """ + """ + if id in self.objectIds(): + return self[id] + return None + + security.declarePublic('getFeeds') + def getFeeds(self): + """ + """ + return self.feeds + + security.declarePublic('replaceItem') + def replaceItem(self,id): + """ + """ + self.manage_delObjects([id]) + return self.addItem(id) + + security.declarePublic('addItem') + def addItem(self, id): + """ + """ + self.invokeFactory('FeedFeederItem', id) + transition = self.getDefaultTransition() + if transition != '': + wf_tool = getToolByName(self,'portal_workflow') + wf_tool.doActionFor(self[id], transition, + comment='Automatic transition triggered by FeedFolder') + return self[id] + + +registerType(FeedfeederFolder, PROJECTNAME) +# end of class FeedfeederFolder + +##code-section module-footer #fill in your manual code here +##/code-section module-footer diff --git a/Products/feedfeeder/content/item.py b/Products/feedfeeder/content/item.py new file mode 100644 index 0000000..247c632 --- /dev/null +++ b/Products/feedfeeder/content/item.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +from AccessControl import ClassSecurityInfo +from Products.Archetypes.atapi import * +from zope import interface +from Products.ATContentTypes.content.folder import ATFolder +from Products.feedfeeder.interfaces.item import IFeedItem +from Products.feedfeeder.config import * +from Products.CMFCore.utils import getToolByName + +from Products.ATContentTypes.content.document import ATDocument +from DateTime import DateTime + + +copied_fields = {} +copied_fields['text'] = ATDocument.schema['text'].copy() +copied_fields['text'].required = 0 +schema = Schema(( + + StringField( + name='feedItemAuthor', + widget=StringWidget( + label='Feeditemauthor', + label_msgid='feedfeeder_label_feedItemAuthor', + i18n_domain='feedfeeder', + ) + ), + + DateTimeField( + name='feedItemUpdated', + default=DateTime('2000/01/01'), + widget=CalendarWidget( + label='Feeditemupdated', + label_msgid='feedfeeder_label_feedItemUpdated', + i18n_domain='feedfeeder', + ) + ), + + copied_fields['text'], + StringField( + name='link', + widget=StringWidget( + label='Link', + label_msgid='feedfeeder_label_link', + i18n_domain='feedfeeder', + ) + ), + + ComputedField( + name='objectids', + widget=ComputedWidget( + label='Object Ids', + label_msgid='feedfeeder_label_objectids', + i18n_domain='feedfeeder', + ) + ), + + ComputedField( + name='hasBody', + widget=ComputedWidget( + label='Has body text', + label_msgid='feedfeeder_label_hasbody', + i18n_domain='feedfeeder', + ) + ), + + StringField( + name='feedTitle', + widget=StringWidget( + label='Feed Title', + label_msgid='feedfeeder_label_feedTitle', + i18n_domain='feedfeeder', + ) + ), + +), +) + +FeedFeederItem_schema = getattr(ATFolder, 'schema', Schema(())).copy() + \ + schema.copy() + + +class FeedFeederItem(ATFolder): + """ + """ + security = ClassSecurityInfo() + # zope3 interfaces + interface.implements(IFeedItem) + + # This name appears in the 'add' box + archetype_name = 'Feed Item' + + meta_type = 'FeedFeederItem' + portal_type = 'FeedFeederItem' + allowed_content_types = ['File'] + filter_content_types = 1 + global_allow = 0 + #content_icon = 'FeedFeederItem.gif' + immediate_view = 'feed-item.html' + default_view = 'feed-item.html' + suppl_views = () + typeDescription = "Feed Item" + typeDescMsgId = 'description_edit_feedfeederitem' + + + actions = ( + + + {'action': "string:${object_url}/feed-item.html", + 'category': "object", + 'id': 'view', + 'name': 'view', + 'permissions': ("View",), + 'condition': 'python:1' + }, + + + ) + + _at_rename_after_creation = True + + schema = FeedFeederItem_schema + + + security.declarePublic('addEnclosure') + def addEnclosure(self,id): + """ + """ + self.invokeFactory('File', id) + self.reindexObject() + transition = self.getDefaultTransition() + if transition != '': + wf_tool = getToolByName(self,'portal_workflow') + # The default transition should be valid for a + # FeedFolderItem, but our File might not have the same + # transitions available. So check this. + transitions = wf_tool.getTransitionsFor(self[id]) + transition_ids = [trans['id'] for trans in transitions] + if transition in transition_ids: + wf_tool.doActionFor(self[id], transition, + comment='Automatic transition triggered by FeedFolder') + return self[id] + + security.declarePublic('remote_url') + def remote_url(self): + """Compatibility method that makes working with link checkers + easier. + """ + return self.getLink() + + security.declarePublic('getObjectids') + def getObjectids(self): + """Return the ids of enclosed objects. + """ + return self.objectIds() + + security.declarePublic('getHasBody') + def getHasBody(self): + """Return True if the object has body text. + """ + if bool(self.getText()): + return 1 + return 0 + +registerType(FeedFeederItem, PROJECTNAME) diff --git a/Products/feedfeeder/contenthandler.py b/Products/feedfeeder/contenthandler.py new file mode 100644 index 0000000..052f2d9 --- /dev/null +++ b/Products/feedfeeder/contenthandler.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- + +from Products.feedfeeder.interfaces.contenthandler import IFeedItemContentHandler +from persistent.dict import PersistentDict +from zope import interface +try: + from zope.annotation.interfaces import IAttributeAnnotatable, IAnnotations +except ImportError: + from zope.app.annotation.interfaces import IAttributeAnnotatable, IAnnotations + + +class StandardContentHandler: + """ + """ + interface.implements(IFeedItemContentHandler) + + def __init__(self, context): + self.context = context + + def apply(self, contentNode): + self.context.update(text=contentNode.toxml()) + + +class AnnotationContentHandler(object): + """A content handler that parses definition list entries to apply + zope3 style annotations to the context. + """ + + interface.implements(IFeedItemContentHandler) + + ANNO_KEY = 'feedfeeder.metadata' + + def __init__(self, context): + self.context = context + + def _extractText(self, node): + s = node.toxml().strip() + s = s[len(node.nodeName)+2:-1*(len(node.nodeName)+3)] + return s + + def apply(self, contentNode): + if not IAttributeAnnotatable.providedBy(self.context): + directly = interface.directlyProvidedBy(self.context) + interface.directlyProvides(self.context, + directly + IAttributeAnnotatable) + annotations = IAnnotations(self.context) + metadata = annotations.get(self.ANNO_KEY, None) + if metadata is None: + metadata = PersistentDict() + annotations[self.ANNO_KEY] = metadata + + for dl_el in contentNode.childNodes: + if dl_el.nodeName != 'dl': + continue + + term = None + for el in dl_el.childNodes: + if el.nodeName == 'dt': + term = self._extractText(el) + elif el.nodeName == 'dd': + definition = self._extractText(el) + metadata[term] = definition + + + diff --git a/Products/feedfeeder/doc/__init__.py b/Products/feedfeeder/doc/__init__.py new file mode 100644 index 0000000..4287ca8 --- /dev/null +++ b/Products/feedfeeder/doc/__init__.py @@ -0,0 +1 @@ +# \ No newline at end of file diff --git a/Products/feedfeeder/doc/feedconsuming.txt b/Products/feedfeeder/doc/feedconsuming.txt new file mode 100644 index 0000000..4a5d8c8 --- /dev/null +++ b/Products/feedfeeder/doc/feedconsuming.txt @@ -0,0 +1,166 @@ +Consuming Feeds +=============== + +The basic premise here is that there is a global utility available that +is capable of taking an object that either implements or adapts to +the IFeedsContainer interface. And with that object, it can retrieve +feed items and store them within the object ... typically as +(but not restricted to) child items in a folderish container. + +Mock Container +~~~~~~~~~~~~~~ + +The requirements for getting feed information and populating feed items +are pretty minimal. The class merely has to implement IFeedsContainer. + + >>> from Products.feedfeeder.interfaces.container import IFeedsContainer + >>> from Products.feedfeeder.interfaces.item import IFeedItem + >>> import zope.interface + + >>> class MockFeedsContainer(object): + ... zope.interface.implements(IFeedsContainer) + ... def __init__(self, feeds): + ... self.items = {} + ... self.feeds = feeds + ... def getFeeds(self): + ... return self.feeds + ... def addItem(self, id): + ... item = MockFeedItem() + ... self.items[id] = item + ... return item + ... def replaceItem(self, id): + ... return self.addItem(id) + ... def getItem(self,id): + ... return self.items.get(id, None) + + >>> class MockFeedItem(object): + ... zope.interface.implements(IFeedItem) + ... def __init__(self): + ... self.enclosures = {} + ... def update(self, **kwargs): + ... for key, value in kwargs.items(): + ... setattr(self, key, value) + ... def addEnclosure(self, id): + ... self.enclosures[id] = MockFeedEnclosure(id) + ... return self.enclosures[id] + ... def getText(self): + ... return self.text + ... def manage_renameObject(self, orig_id, new_id): + ... if new_id in self.enclosures.keys(): + ... raise KeyError('Enclosure with %r id already exists' % repr(new_id)) + ... self.enclosures[new_id] = self.enclosures[orig_id] + ... del self.enclosures[orig_id] + ... self.enclosures[new_id].id = new_id + ... def objectIds(self): return self.enclosures.keys() + ... def getFeedItemUpdated(self): return self.feedItemUpdated + ... def setFeedItemUpdated(self, x): self.feedItemUpdated = x + ... def getFeedItemAuthor(self): return self.feedItemAuthor + ... def setFeedItemAuthor(self, x): self.feedItemAuthor = x + ... def getFeedTitle(self): return self.feedTitle + ... def setFeedTitle(self, x): self.feedTitle = x + ... def setEffectiveDate(self, x): pass + ... def reindexObject(self): pass + + >>> class MockFeedEnclosure(object): + ... def __init__(self, id): + ... self.id = id + ... def getId(self): + ... return self.id + ... def Title(self): + ... return getattr(self, 'title', '') + ... def update(self, **kwargs): + ... for key, value in kwargs.items(): + ... setattr(self, key, value) + ... def size(self): + ... if hasattr(self, 'text'): + ... return len(self.text) + ... return len(getattr(self, 'data', '')) + ... def update_data(self, data, mime_type): + ... self.data = data + ... if hasattr(data, 'read'): + ... self.data = data.read() + ... self.mime_type = mime_type + ... def __str__(self): + ... return '' % self.id + ... __repr__ = __str__ + +Using The Utility +~~~~~~~~~~~~~~~~~ + +Lets begin by getting the proper path to our example atom feed and setting +up our mock feedscontainer. + + >>> import os + >>> import Products.feedfeeder + >>> samplesdir = os.path.dirname(Products.feedfeeder.__file__) + >>> samplesdir = os.path.join(samplesdir, 'tests', 'samples') + +Make sure the feed consumer tells us if it has been given a bad file +path. + + >>> from Products.feedfeeder import utilities + >>> consumer = utilities.FeedConsumer() + >>> container = MockFeedsContainer(['file:///foobar.xml']) + >>> consumer.retrieveFeedItems(container) + Traceback (most recent call last): + ... + IOError: Couldn't locate '/foobar.xml' + +Now lets use our utilty to build the feed items. + + >>> os.chdir(samplesdir) + >>> samplefiles = [os.path.join(samplesdir, 'samplefeed1.xml'), + ... os.path.join(samplesdir, 'samplefeed2.xml'), + ... os.path.join(samplesdir, 'samplefeed3.xml'), + ... os.path.join(samplesdir, 'samplefeed4.xml')] + >>> container = MockFeedsContainer(['file://'+x for x in samplefiles]) + >>> consumer.retrieveFeedItems(container) + >>> len(container.items) + 6 + +Make sure the content all matches up. + + >>> test_doc = container.items['0cfbced08adbdc1f3bf30b4120371b7d'] + >>> test_doc.title + u'Philips Nieuws 24 juli' + >>> test_doc.getFeedTitle() + u'Philips Research Eindhoven News (Special)' + >>> len(test_doc.enclosures) + 1 + >>> test_doc.enclosures.values()[0].size() + 1000 + +Lets check out the document's feed item metadata. + + >>> test_doc.getFeedItemAuthor() + u'Miriam Mobach' + >>> test_doc.getFeedItemUpdated() + DateTime('2006/07/21 12:00:00 GMT+0') + +There are duplicate entries in both feed1 and feed2. In the case of the +first duplicate, feed2's entry is later and thus should be the one we have. + + >>> duplicate1 = container.items['649c8553c458001dbbb9b15957d58a92'] + >>> duplicate1.text + u'
\nhello bar\n
' + +For the second duplicate, the first entry is the latest and should be +kept. + >>> duplicate2 = container.items['30ca408a75537f05d03821c64473289e'] + >>> duplicate2.text + u'
\nwoo hoo, a party!\n
' + >>> len(duplicate2.enclosures) + 2 + >>> sorted([x.id for x in duplicate2.enclosures.values()]) + [u'test2.doc', u'test3.xls'] + +Get our item that talks about the thesis defence of Reinout. + + >>> thesis = container.items['f065f774e8c28bf9f33221f290c4ca6a'] + >>> thesis.title + u'Thesis defence: 15 January 2007 15:00' + +Now someone could have added an enclosure that is actually just a link. We append that link with an "a href" to the text of the item. + + >>> thesis.getText() + u'
\nGreat news: a final thesis defence date!\n
' diff --git a/Products/feedfeeder/doc/feedfeeder-integration.txt b/Products/feedfeeder/doc/feedfeeder-integration.txt new file mode 100644 index 0000000..2f6bcc2 --- /dev/null +++ b/Products/feedfeeder/doc/feedfeeder-integration.txt @@ -0,0 +1,291 @@ +Feedfeeder Integration +====================== + +Feedfeeder uses feedparser to read in Atom feeds and to create new +documents or files if there are new items in that feed. Those new +items are created inside the feedfeederfolder itself, as it is a +folderish type. + +Lets begin by creating our feeder. + + >>> id = folder.invokeFactory('FeedfeederFolder', 'feeder') + >>> feeder = folder.feeder + +Setup some feeds. + + >>> import os + >>> import Products.feedfeeder + + >>> samplesdir = os.path.dirname(Products.feedfeeder.__file__) + >>> samplesdir = os.path.join(samplesdir, 'tests', 'samples') + >>> os.chdir(samplesdir) + >>> samplefiles = [os.path.join(samplesdir, 'samplefeed1.xml'), + ... os.path.join(samplesdir, 'samplefeed2.xml')] + >>> feeder.setFeeds(['file://'+x for x in samplefiles]) + + +Available Transitions +--------------------- + +Feed items that are added during an update can be automatically +transitioned. + +Between Plone 2.5 and 3.0 there were some changes to the workflows +which make it tricky to have tests here that pass in both cases. We +explicitly set the workflow chain for FeedFeederItems to +plone_workflow, as that is what the default for Plone 2.5. And we do +the same for Files, as we use them for enclosures:: + + >>> portal.portal_workflow.setChainForPortalTypes(['FeedFeederItem', 'File'], 'plone_workflow') + +See what transitions we have available:: + + >>> feeder.getAvailableTransitions() + + >>> self.setRoles('Manager') + >>> [trans for trans in feeder.getAvailableTransitions()] + ['', 'hide', 'submit', 'publish'] + + >>> from Products.CMFCore.utils import getToolByName + >>> wf_tool = getToolByName(folder,'portal_workflow') + >>> wf_tool.doActionFor(feeder, 'publish') + >>> [trans for trans in feeder.getAvailableTransitions()] + ['', 'hide', 'submit', 'publish'] + >>> self.setRoles('') + >>> [trans for trans in feeder.getAvailableTransitions()] + ['', 'hide', 'submit'] + + +Using Updating View +------------------- + + By default only Managers (with the ManagePortal permission) can + update FeedFolders. + + >>> self.setRoles('Manager') + >>> feeder.setDefaultTransition('publish') + >>> view = feeder.restrictedTraverse('@@update_feed_items') + >>> view.update() + >>> self.setRoles('') + +Make sure we got what we wanted. + + >>> sorted([x for x in feeder.objectIds()]) + ['0cfbced08adbdc1f3bf30b4120371b7d', '30ca408a75537f05d03821c64473289e', '649c8553c458001dbbb9b15957d58a92', 'c17db5a7fa227e2e34193c71a173dbb1'] + + >>> test_doc = feeder['30ca408a75537f05d03821c64473289e'] + >>> test_doc.title + u'Party!' + >>> test_doc.Description() + 'Party on the roof of the Mediterranean Inn' + >>> test_doc.getText() + '
\nwoo hoo, a party!\n
' + >>> enclosure = test_doc.objectValues()[0] + >>> enclosure + + +And did the automatic transition work? +For the FeedFeederItem: + + >>> chain = wf_tool.getChainFor(test_doc) + >>> status = wf_tool.getStatusOf(chain[0], test_doc) + >>> status['review_state'] + 'published' + >>> status['comments'] + 'Automatic transition triggered by FeedFolder' + +For the enclosure: + + >>> chain = wf_tool.getChainFor(enclosure) + >>> status = wf_tool.getStatusOf(chain[0], enclosure) + >>> status['review_state'] + 'published' + >>> status['comments'] + 'Automatic transition triggered by FeedFolder' + + + +Folder Listing +-------------- + +We need to make sure the items listed by the folder listing view match +up with appropriate logic. + + >>> id = folder.invokeFactory('FeedfeederFolder', 'feeder2') + >>> feeder = folder.feeder2 + >>> view = feeder.restrictedTraverse('@@feed-folder.html') + +The requirements for how things get linked is as follows: + + 1) feed item with no text and no enclosures: show feed item title and + link to feed item + 2) feed item with text: show feed item title and link to feed item + 3) feed item with text and one enclosure: show feed item title and + link to feed item + 4) feed item with no text and one enclosure: show feed item title and + link to enclosure + 5) feed item with no text and multiple enclosures: show feed item + title and link to feed item + +We have to satisfy each of these requirements. Make sure that a feed +item with no text and no enclosures still have the feed item title and +feed item url. + + >>> id = feeder.invokeFactory('FeedFeederItem', '1') + >>> feeder[id].update(title='foo') + >>> items = [x for x in view.items] + >>> len(items) + 1 + >>> items[0]['title'] + 'foo' + >>> items[0]['url'] + 'http://nohost/plone/Members/test_user_1_/feeder2/1' + +A feed item with text should have it's title and url displayed. + + >>> feeder[id].setText('abcdef') + >>> items = [x for x in view.items] + >>> len(items) + 1 + >>> items[0]['title'] + 'foo' + >>> items[0]['url'] + 'http://nohost/plone/Members/test_user_1_/feeder2/1' + +Even if the feed item has an enclosure, as long as it has text the +feed item title and url should be used. + + >>> obj = feeder[id].addEnclosure('1.1') + >>> obj.update(title='foo.bar') + >>> items = [x for x in view.items] + >>> len(items) + 1 + >>> items[0]['title'] + 'foo' + >>> items[0]['url'] + 'http://nohost/plone/Members/test_user_1_/feeder2/1' + +If there is no text in the feed item and there is one and only one +enclosure, then the feed item title and enclosure url should be used. + + >>> feeder[id].setText('') + >>> feeder[id].reindexObject() + >>> len(feeder[id].getFolderContents()) + 1 + >>> items = [x for x in view.items] + >>> len(items) + 1 + >>> items[0]['title'] + 'foo' + >>> items[0]['url'] + 'http://nohost/plone/Members/test_user_1_/feeder2/1/1.1' + +If there is no text in the feed item and there is more than one +enclosure, we should go back to simply using the title and url of the +feed item. + + >>> feeder[id].setText('') + >>> obj = feeder[id].addEnclosure('1.2') + >>> obj.update(title='foo.hello') + >>> len(feeder[id].getFolderContents()) > 1 + True + >>> items = [x for x in view.items] + >>> len(items) + 1 + >>> items[0]['title'] + 'foo' + >>> items[0]['url'] + 'http://nohost/plone/Members/test_user_1_/feeder2/1' + +Items with summaries should have summaries. Summaries come from +the description field on the content object. + + >>> feeder[id].setDescription('Test Summary') + >>> feeder[id].update(title='blatant') + >>> items = [x for x in view.items] + >>> items[0]['summary'] + 'Test Summary' + +Annotated Metadata Handler +-------------------------- + +Feedfeeder comes with an unregistered zope3 annotations based metadata +handler adapter. Essentially it scans the content of an atom entry +for a toplevel DL entry and saves the DT/DD items as annotation +values. Lets make sure that works. + + >>> from zope import component + >>> from Products.feedfeeder.interfaces.contenthandler import IFeedItemContentHandler + >>> from Products.feedfeeder.contenthandler import AnnotationContentHandler + >>> from Products.feedfeeder.interfaces.item import IFeedItem + + >>> component.provideAdapter(AnnotationContentHandler, + ... adapts=(IFeedItem,), + ... provides=IFeedItemContentHandler, + ... name=u'definition-list-metadata') + + >>> feeder.setFeeds(['file://'+os.path.join(samplesdir, 'samplefeed1.xml')]) + >>> self.setRoles('Manager') + >>> view = feeder.restrictedTraverse('@@update_feed_items') + >>> view.update() + >>> self.setRoles('') + +Now that we've retrieved the items, lets make sure the metadata we expect +is present. + + >>> try: + ... from zope.annotation import IAnnotations + ... except ImportError: + ... from zope.app.annotation import IAnnotations + >>> annotations = IAnnotations(feeder['649c8553c458001dbbb9b15957d58a92']) + >>> metadata = annotations[AnnotationContentHandler.ANNO_KEY] + >>> dict(metadata) + {u'date': u'2006-03-23'} + +Also make sure that the normal content is still available, but that +the dl with the extra data is gone. + + >>> item = feeder['649c8553c458001dbbb9b15957d58a92'] + >>> text = item.getText() + >>> 'definition-list-metadata' not in text + True + >>> 'the real text body here' in text + True + +Events +------ + +After a feed item has been consumed it fires an appropriate event to +signify this. First lets clean up the feeder. + + >>> feeder.manage_delObjects([x for x in feeder.objectIds()]) + +Make sure that event is being properly fired and handled. + + >>> class Handler: + ... event_obj = None + ... event_evt = None + ... def handle(self, event, obj): + ... self.event_obj = event + ... self.event_evt = obj + >>> handler = Handler() + + >>> from zope import component + >>> from Products.feedfeeder.interfaces.item import IFeedItemConsumedEvent + >>> component.provideHandler(handler.handle, + ... (IFeedItem, IFeedItemConsumedEvent)) + +Now that the event handler has been setup, parse in some entries and +make sure the handler is getting to handle them. + + >>> self.setRoles('Manager') + >>> view = feeder.restrictedTraverse('@@update_feed_items') + >>> view.update() + >>> self.setRoles('') + + >>> handler.event_evt + + >>> handler.event_obj + + + diff --git a/Products/feedfeeder/events.py b/Products/feedfeeder/events.py new file mode 100644 index 0000000..b01eab4 --- /dev/null +++ b/Products/feedfeeder/events.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +from zope import interface +try: + from zope.lifecycleevent import ObjectModifiedEvent +except ImportError: + # BBB for Zope 2.9 + from zope.app.event.objectevent import ObjectModifiedEvent +from Products.feedfeeder.interfaces import item as itemifaces + + +class FeedItemConsumedEvent(ObjectModifiedEvent): + """Fired when a feed item has been successfully consumed. + """ + + interface.implements(itemifaces.IFeedItemConsumedEvent) diff --git a/Products/feedfeeder/feedparser.py b/Products/feedfeeder/feedparser.py new file mode 100755 index 0000000..69c99dd --- /dev/null +++ b/Products/feedfeeder/feedparser.py @@ -0,0 +1,2864 @@ +#!/usr/bin/env python +"""Universal feed parser + +Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds + +Visit http://feedparser.org/ for the latest version +Visit http://feedparser.org/docs/ for the latest documentation + +Required: Python 2.1 or later +Recommended: Python 2.3 or later +Recommended: CJKCodecs and iconv_codec +""" + +__version__ = "4.1"# + "$Revision: 1.92 $"[11:15] + "-cvs" +__license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE.""" +__author__ = "Mark Pilgrim " +__contributors__ = ["Jason Diamond ", + "John Beimler ", + "Fazal Majid ", + "Aaron Swartz ", + "Kevin Marks "] +_debug = 0 + +# HTTP "User-Agent" header to send to servers when downloading feeds. +# If you are embedding feedparser in a larger application, you should +# change this to your application name and URL. +USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__ + +# HTTP "Accept" header to send to servers when downloading feeds. If you don't +# want to send an Accept header, set this to None. +ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1" + +# List of preferred XML parsers, by SAX driver name. These will be tried first, +# but if they're not installed, Python will keep searching through its own list +# of pre-installed parsers until it finds one that supports everything we need. +PREFERRED_XML_PARSERS = ["drv_libxml2"] + +# If you want feedparser to automatically run HTML markup through HTML Tidy, set +# this to 1. Requires mxTidy +# or utidylib . +TIDY_MARKUP = 0 + +# List of Python interfaces for HTML Tidy, in order of preference. Only useful +# if TIDY_MARKUP = 1 +PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"] + +# ---------- required modules (should come with any Python distribution) ---------- +import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2 +try: + from cStringIO import StringIO as _StringIO +except: + from StringIO import StringIO as _StringIO + +# ---------- optional modules (feedparser will work without these, but with reduced functionality) ---------- + +# gzip is included with most Python distributions, but may not be available if you compiled your own +try: + import gzip +except: + gzip = None +try: + import zlib +except: + zlib = None + +# If a real XML parser is available, feedparser will attempt to use it. feedparser has +# been tested with the built-in SAX parser, PyXML, and libxml2. On platforms where the +# Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some +# versions of FreeBSD), feedparser will quietly fall back on regex-based parsing. +try: + import xml.sax + xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers + from xml.sax.saxutils import escape as _xmlescape + _XML_AVAILABLE = 1 +except: + _XML_AVAILABLE = 0 + def _xmlescape(data): + data = data.replace('&', '&') + data = data.replace('>', '>') + data = data.replace('<', '<') + return data + +# base64 support for Atom feeds that contain embedded binary data +try: + import base64, binascii +except: + base64 = binascii = None + +# cjkcodecs and iconv_codec provide support for more character encodings. +# Both are available from http://cjkpython.i18n.org/ +try: + import cjkcodecs.aliases +except: + pass +try: + import iconv_codec +except: + pass + +# chardet library auto-detects character encodings +# Download from http://chardet.feedparser.org/ +try: + import chardet + if _debug: + import chardet.constants + chardet.constants._debug = 1 +except: + chardet = None + +# ---------- don't touch these ---------- +class ThingsNobodyCaresAboutButMe(Exception): pass +class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass +class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass +class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass +class UndeclaredNamespace(Exception): pass + +sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') +sgmllib.special = re.compile('' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0) + + # match namespaces + if tag.find(':') <> -1: + prefix, suffix = tag.split(':', 1) + else: + prefix, suffix = '', tag + prefix = self.namespacemap.get(prefix, prefix) + if prefix: + prefix = prefix + '_' + + # special hack for better tracking of empty textinput/image elements in illformed feeds + if (not prefix) and tag not in ('title', 'link', 'description', 'name'): + self.intextinput = 0 + if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'): + self.inimage = 0 + + # call special handler (if defined) or default handler + methodname = '_start_' + prefix + suffix + try: + method = getattr(self, methodname) + return method(attrsD) + except AttributeError: + return self.push(prefix + suffix, 1) + + def unknown_endtag(self, tag): + if _debug: sys.stderr.write('end %s\n' % tag) + # match namespaces + if tag.find(':') <> -1: + prefix, suffix = tag.split(':', 1) + else: + prefix, suffix = '', tag + prefix = self.namespacemap.get(prefix, prefix) + if prefix: + prefix = prefix + '_' + + # call special handler (if defined) or default handler + methodname = '_end_' + prefix + suffix + try: + method = getattr(self, methodname) + method() + except AttributeError: + self.pop(prefix + suffix) + + # track inline content + if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'): + # element declared itself as escaped markup, but it isn't really + self.contentparams['type'] = 'application/xhtml+xml' + if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml': + tag = tag.split(':')[-1] + self.handle_data('' % tag, escape=0) + + # track xml:base and xml:lang going out of scope + if self.basestack: + self.basestack.pop() + if self.basestack and self.basestack[-1]: + self.baseuri = self.basestack[-1] + if self.langstack: + self.langstack.pop() + if self.langstack: # and (self.langstack[-1] is not None): + self.lang = self.langstack[-1] + + def handle_charref(self, ref): + # called for each character reference, e.g. for ' ', ref will be '160' + if not self.elementstack: return + ref = ref.lower() + if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'): + text = '&#%s;' % ref + else: + if ref[0] == 'x': + c = int(ref[1:], 16) + else: + c = int(ref) + text = unichr(c).encode('utf-8') + self.elementstack[-1][2].append(text) + + def handle_entityref(self, ref): + # called for each entity reference, e.g. for '©', ref will be 'copy' + if not self.elementstack: return + if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref) + if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): + text = '&%s;' % ref + else: + # entity resolution graciously donated by Aaron Swartz + def name2cp(k): + import htmlentitydefs + if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3 + return htmlentitydefs.name2codepoint[k] + k = htmlentitydefs.entitydefs[k] + if k.startswith('&#') and k.endswith(';'): + return int(k[2:-1]) # not in latin-1 + return ord(k) + try: name2cp(ref) + except KeyError: text = '&%s;' % ref + else: text = unichr(name2cp(ref)).encode('utf-8') + self.elementstack[-1][2].append(text) + + def handle_data(self, text, escape=1): + # called for each block of plain text, i.e. outside of any tag and + # not containing any character or entity references + if not self.elementstack: return + if escape and self.contentparams.get('type') == 'application/xhtml+xml': + text = _xmlescape(text) + self.elementstack[-1][2].append(text) + + def handle_comment(self, text): + # called for each comment, e.g. + pass + + def handle_pi(self, text): + # called for each processing instruction, e.g. + pass + + def handle_decl(self, text): + pass + + def parse_declaration(self, i): + # override internal declaration handler to handle CDATA blocks + if _debug: sys.stderr.write('entering parse_declaration\n') + if self.rawdata[i:i+9] == '', i) + if k == -1: k = len(self.rawdata) + self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0) + return k+3 + else: + k = self.rawdata.find('>', i) + return k+1 + + def mapContentType(self, contentType): + contentType = contentType.lower() + if contentType == 'text': + contentType = 'text/plain' + elif contentType == 'html': + contentType = 'text/html' + elif contentType == 'xhtml': + contentType = 'application/xhtml+xml' + return contentType + + def trackNamespace(self, prefix, uri): + loweruri = uri.lower() + if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version: + self.version = 'rss090' + if loweruri == 'http://purl.org/rss/1.0/' and not self.version: + self.version = 'rss10' + if loweruri == 'http://www.w3.org/2005/atom' and not self.version: + self.version = 'atom10' + if loweruri.find('backend.userland.com/rss') <> -1: + # match any backend.userland.com namespace + uri = 'http://backend.userland.com/rss' + loweruri = uri + if self._matchnamespaces.has_key(loweruri): + self.namespacemap[prefix] = self._matchnamespaces[loweruri] + self.namespacesInUse[self._matchnamespaces[loweruri]] = uri + else: + self.namespacesInUse[prefix or ''] = uri + + def resolveURI(self, uri): + return _urljoin(self.baseuri or '', uri) + + def decodeEntities(self, element, data): + return data + + def push(self, element, expectingText): + self.elementstack.append([element, expectingText, []]) + + def pop(self, element, stripWhitespace=1): + if not self.elementstack: return + if self.elementstack[-1][0] != element: return + + element, expectingText, pieces = self.elementstack.pop() + output = ''.join(pieces) + if stripWhitespace: + output = output.strip() + if not expectingText: return output + + # decode base64 content + if base64 and self.contentparams.get('base64', 0): + try: + output = base64.decodestring(output) + except binascii.Error: + pass + except binascii.Incomplete: + pass + + # resolve relative URIs + if (element in self.can_be_relative_uri) and output: + output = self.resolveURI(output) + + # decode entities within embedded markup + if not self.contentparams.get('base64', 0): + output = self.decodeEntities(element, output) + + # remove temporary cruft from contentparams + try: + del self.contentparams['mode'] + except KeyError: + pass + try: + del self.contentparams['base64'] + except KeyError: + pass + + # resolve relative URIs within embedded markup + if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: + if element in self.can_contain_relative_uris: + output = _resolveRelativeURIs(output, self.baseuri, self.encoding) + + # sanitize embedded markup + if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: + if element in self.can_contain_dangerous_markup: + output = _sanitizeHTML(output, self.encoding) + + if self.encoding and type(output) != type(u''): + try: + output = unicode(output, self.encoding) + except: + pass + + # categories/tags/keywords/whatever are handled in _end_category + if element == 'category': + return output + + # store output in appropriate place(s) + if self.inentry and not self.insource: + if element == 'content': + self.entries[-1].setdefault(element, []) + contentparams = copy.deepcopy(self.contentparams) + contentparams['value'] = output + self.entries[-1][element].append(contentparams) + elif element == 'link': + self.entries[-1][element] = output + if output: + self.entries[-1]['links'][-1]['href'] = output + else: + if element == 'description': + element = 'summary' + self.entries[-1][element] = output + if self.incontent: + contentparams = copy.deepcopy(self.contentparams) + contentparams['value'] = output + self.entries[-1][element + '_detail'] = contentparams + elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage): + context = self._getContext() + if element == 'description': + element = 'subtitle' + context[element] = output + if element == 'link': + context['links'][-1]['href'] = output + elif self.incontent: + contentparams = copy.deepcopy(self.contentparams) + contentparams['value'] = output + context[element + '_detail'] = contentparams + return output + + def pushContent(self, tag, attrsD, defaultContentType, expectingText): + self.incontent += 1 + self.contentparams = FeedParserDict({ + 'type': self.mapContentType(attrsD.get('type', defaultContentType)), + 'language': self.lang, + 'base': self.baseuri}) + self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams) + self.push(tag, expectingText) + + def popContent(self, tag): + value = self.pop(tag) + self.incontent -= 1 + self.contentparams.clear() + return value + + def _mapToStandardPrefix(self, name): + colonpos = name.find(':') + if colonpos <> -1: + prefix = name[:colonpos] + suffix = name[colonpos+1:] + prefix = self.namespacemap.get(prefix, prefix) + name = prefix + ':' + suffix + return name + + def _getAttribute(self, attrsD, name): + return attrsD.get(self._mapToStandardPrefix(name)) + + def _isBase64(self, attrsD, contentparams): + if attrsD.get('mode', '') == 'base64': + return 1 + if self.contentparams['type'].startswith('text/'): + return 0 + if self.contentparams['type'].endswith('+xml'): + return 0 + if self.contentparams['type'].endswith('/xml'): + return 0 + return 1 + + def _itsAnHrefDamnIt(self, attrsD): + href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None))) + if href: + try: + del attrsD['url'] + except KeyError: + pass + try: + del attrsD['uri'] + except KeyError: + pass + attrsD['href'] = href + return attrsD + + def _save(self, key, value): + context = self._getContext() + context.setdefault(key, value) + + def _start_rss(self, attrsD): + versionmap = {'0.91': 'rss091u', + '0.92': 'rss092', + '0.93': 'rss093', + '0.94': 'rss094'} + if not self.version: + attr_version = attrsD.get('version', '') + version = versionmap.get(attr_version) + if version: + self.version = version + elif attr_version.startswith('2.'): + self.version = 'rss20' + else: + self.version = 'rss' + + def _start_dlhottitles(self, attrsD): + self.version = 'hotrss' + + def _start_channel(self, attrsD): + self.infeed = 1 + self._cdf_common(attrsD) + _start_feedinfo = _start_channel + + def _cdf_common(self, attrsD): + if attrsD.has_key('lastmod'): + self._start_modified({}) + self.elementstack[-1][-1] = attrsD['lastmod'] + self._end_modified() + if attrsD.has_key('href'): + self._start_link({}) + self.elementstack[-1][-1] = attrsD['href'] + self._end_link() + + def _start_feed(self, attrsD): + self.infeed = 1 + versionmap = {'0.1': 'atom01', + '0.2': 'atom02', + '0.3': 'atom03'} + if not self.version: + attr_version = attrsD.get('version') + version = versionmap.get(attr_version) + if version: + self.version = version + else: + self.version = 'atom' + + def _end_channel(self): + self.infeed = 0 + _end_feed = _end_channel + + def _start_image(self, attrsD): + self.inimage = 1 + self.push('image', 0) + context = self._getContext() + context.setdefault('image', FeedParserDict()) + + def _end_image(self): + self.pop('image') + self.inimage = 0 + + def _start_textinput(self, attrsD): + self.intextinput = 1 + self.push('textinput', 0) + context = self._getContext() + context.setdefault('textinput', FeedParserDict()) + _start_textInput = _start_textinput + + def _end_textinput(self): + self.pop('textinput') + self.intextinput = 0 + _end_textInput = _end_textinput + + def _start_author(self, attrsD): + self.inauthor = 1 + self.push('author', 1) + _start_managingeditor = _start_author + _start_dc_author = _start_author + _start_dc_creator = _start_author + _start_itunes_author = _start_author + + def _end_author(self): + self.pop('author') + self.inauthor = 0 + self._sync_author_detail() + _end_managingeditor = _end_author + _end_dc_author = _end_author + _end_dc_creator = _end_author + _end_itunes_author = _end_author + + def _start_itunes_owner(self, attrsD): + self.inpublisher = 1 + self.push('publisher', 0) + + def _end_itunes_owner(self): + self.pop('publisher') + self.inpublisher = 0 + self._sync_author_detail('publisher') + + def _start_contributor(self, attrsD): + self.incontributor = 1 + context = self._getContext() + context.setdefault('contributors', []) + context['contributors'].append(FeedParserDict()) + self.push('contributor', 0) + + def _end_contributor(self): + self.pop('contributor') + self.incontributor = 0 + + def _start_dc_contributor(self, attrsD): + self.incontributor = 1 + context = self._getContext() + context.setdefault('contributors', []) + context['contributors'].append(FeedParserDict()) + self.push('name', 0) + + def _end_dc_contributor(self): + self._end_name() + self.incontributor = 0 + + def _start_name(self, attrsD): + self.push('name', 0) + _start_itunes_name = _start_name + + def _end_name(self): + value = self.pop('name') + if self.inpublisher: + self._save_author('name', value, 'publisher') + elif self.inauthor: + self._save_author('name', value) + elif self.incontributor: + self._save_contributor('name', value) + elif self.intextinput: + context = self._getContext() + context['textinput']['name'] = value + _end_itunes_name = _end_name + + def _start_width(self, attrsD): + self.push('width', 0) + + def _end_width(self): + value = self.pop('width') + try: + value = int(value) + except: + value = 0 + if self.inimage: + context = self._getContext() + context['image']['width'] = value + + def _start_height(self, attrsD): + self.push('height', 0) + + def _end_height(self): + value = self.pop('height') + try: + value = int(value) + except: + value = 0 + if self.inimage: + context = self._getContext() + context['image']['height'] = value + + def _start_url(self, attrsD): + self.push('href', 1) + _start_homepage = _start_url + _start_uri = _start_url + + def _end_url(self): + value = self.pop('href') + if self.inauthor: + self._save_author('href', value) + elif self.incontributor: + self._save_contributor('href', value) + elif self.inimage: + context = self._getContext() + context['image']['href'] = value + elif self.intextinput: + context = self._getContext() + context['textinput']['link'] = value + _end_homepage = _end_url + _end_uri = _end_url + + def _start_email(self, attrsD): + self.push('email', 0) + _start_itunes_email = _start_email + + def _end_email(self): + value = self.pop('email') + if self.inpublisher: + self._save_author('email', value, 'publisher') + elif self.inauthor: + self._save_author('email', value) + elif self.incontributor: + self._save_contributor('email', value) + _end_itunes_email = _end_email + + def _getContext(self): + if self.insource: + context = self.sourcedata + elif self.inentry: + context = self.entries[-1] + else: + context = self.feeddata + return context + + def _save_author(self, key, value, prefix='author'): + context = self._getContext() + context.setdefault(prefix + '_detail', FeedParserDict()) + context[prefix + '_detail'][key] = value + self._sync_author_detail() + + def _save_contributor(self, key, value): + context = self._getContext() + context.setdefault('contributors', [FeedParserDict()]) + context['contributors'][-1][key] = value + + def _sync_author_detail(self, key='author'): + context = self._getContext() + detail = context.get('%s_detail' % key) + if detail: + name = detail.get('name') + email = detail.get('email') + if name and email: + context[key] = '%s (%s)' % (name, email) + elif name: + context[key] = name + elif email: + context[key] = email + else: + author = context.get(key) + if not author: return + emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''', author) + if not emailmatch: return + email = emailmatch.group(0) + # probably a better way to do the following, but it passes all the tests + author = author.replace(email, '') + author = author.replace('()', '') + author = author.strip() + if author and (author[0] == '('): + author = author[1:] + if author and (author[-1] == ')'): + author = author[:-1] + author = author.strip() + context.setdefault('%s_detail' % key, FeedParserDict()) + context['%s_detail' % key]['name'] = author + context['%s_detail' % key]['email'] = email + + def _start_subtitle(self, attrsD): + self.pushContent('subtitle', attrsD, 'text/plain', 1) + _start_tagline = _start_subtitle + _start_itunes_subtitle = _start_subtitle + + def _end_subtitle(self): + self.popContent('subtitle') + _end_tagline = _end_subtitle + _end_itunes_subtitle = _end_subtitle + + def _start_rights(self, attrsD): + self.pushContent('rights', attrsD, 'text/plain', 1) + _start_dc_rights = _start_rights + _start_copyright = _start_rights + + def _end_rights(self): + self.popContent('rights') + _end_dc_rights = _end_rights + _end_copyright = _end_rights + + def _start_item(self, attrsD): + self.entries.append(FeedParserDict()) + self.push('item', 0) + self.inentry = 1 + self.guidislink = 0 + id = self._getAttribute(attrsD, 'rdf:about') + if id: + context = self._getContext() + context['id'] = id + self._cdf_common(attrsD) + _start_entry = _start_item + _start_product = _start_item + + def _end_item(self): + self.pop('item') + self.inentry = 0 + _end_entry = _end_item + + def _start_dc_language(self, attrsD): + self.push('language', 1) + _start_language = _start_dc_language + + def _end_dc_language(self): + self.lang = self.pop('language') + _end_language = _end_dc_language + + def _start_dc_publisher(self, attrsD): + self.push('publisher', 1) + _start_webmaster = _start_dc_publisher + + def _end_dc_publisher(self): + self.pop('publisher') + self._sync_author_detail('publisher') + _end_webmaster = _end_dc_publisher + + def _start_published(self, attrsD): + self.push('published', 1) + _start_dcterms_issued = _start_published + _start_issued = _start_published + + def _end_published(self): + value = self.pop('published') + self._save('published_parsed', _parse_date(value)) + _end_dcterms_issued = _end_published + _end_issued = _end_published + + def _start_updated(self, attrsD): + self.push('updated', 1) + _start_modified = _start_updated + _start_dcterms_modified = _start_updated + _start_pubdate = _start_updated + _start_dc_date = _start_updated + + def _end_updated(self): + value = self.pop('updated') + parsed_value = _parse_date(value) + self._save('updated_parsed', parsed_value) + _end_modified = _end_updated + _end_dcterms_modified = _end_updated + _end_pubdate = _end_updated + _end_dc_date = _end_updated + + def _start_created(self, attrsD): + self.push('created', 1) + _start_dcterms_created = _start_created + + def _end_created(self): + value = self.pop('created') + self._save('created_parsed', _parse_date(value)) + _end_dcterms_created = _end_created + + def _start_expirationdate(self, attrsD): + self.push('expired', 1) + + def _end_expirationdate(self): + self._save('expired_parsed', _parse_date(self.pop('expired'))) + + def _start_cc_license(self, attrsD): + self.push('license', 1) + value = self._getAttribute(attrsD, 'rdf:resource') + if value: + self.elementstack[-1][2].append(value) + self.pop('license') + + def _start_creativecommons_license(self, attrsD): + self.push('license', 1) + + def _end_creativecommons_license(self): + self.pop('license') + + def _addTag(self, term, scheme, label): + context = self._getContext() + tags = context.setdefault('tags', []) + if (not term) and (not scheme) and (not label): return + value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label}) + if value not in tags: + tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label})) + + def _start_category(self, attrsD): + if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD)) + term = attrsD.get('term') + scheme = attrsD.get('scheme', attrsD.get('domain')) + label = attrsD.get('label') + self._addTag(term, scheme, label) + self.push('category', 1) + _start_dc_subject = _start_category + _start_keywords = _start_category + + def _end_itunes_keywords(self): + for term in self.pop('itunes_keywords').split(): + self._addTag(term, 'http://www.itunes.com/', None) + + def _start_itunes_category(self, attrsD): + self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None) + self.push('category', 1) + + def _end_category(self): + value = self.pop('category') + if not value: return + context = self._getContext() + tags = context['tags'] + if value and len(tags) and not tags[-1]['term']: + tags[-1]['term'] = value + else: + self._addTag(value, None, None) + _end_dc_subject = _end_category + _end_keywords = _end_category + _end_itunes_category = _end_category + + def _start_cloud(self, attrsD): + self._getContext()['cloud'] = FeedParserDict(attrsD) + + def _start_link(self, attrsD): + attrsD.setdefault('rel', 'alternate') + attrsD.setdefault('type', 'text/html') + attrsD = self._itsAnHrefDamnIt(attrsD) + if attrsD.has_key('href'): + attrsD['href'] = self.resolveURI(attrsD['href']) + expectingText = self.infeed or self.inentry or self.insource + context = self._getContext() + context.setdefault('links', []) + context['links'].append(FeedParserDict(attrsD)) + if attrsD['rel'] == 'enclosure': + self._start_enclosure(attrsD) + if attrsD.has_key('href'): + expectingText = 0 + if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types): + context['link'] = attrsD['href'] + else: + self.push('link', expectingText) + _start_producturl = _start_link + + def _end_link(self): + value = self.pop('link') + context = self._getContext() + if self.intextinput: + context['textinput']['link'] = value + if self.inimage: + context['image']['link'] = value + _end_producturl = _end_link + + def _start_guid(self, attrsD): + self.guidislink = (attrsD.get('ispermalink', 'true') == 'true') + self.push('id', 1) + + def _end_guid(self): + value = self.pop('id') + self._save('guidislink', self.guidislink and not self._getContext().has_key('link')) + if self.guidislink: + # guid acts as link, but only if 'ispermalink' is not present or is 'true', + # and only if the item doesn't already have a link element + self._save('link', value) + + def _start_title(self, attrsD): + self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource) + _start_dc_title = _start_title + _start_media_title = _start_title + + def _end_title(self): + value = self.popContent('title') + context = self._getContext() + if self.intextinput: + context['textinput']['title'] = value + elif self.inimage: + context['image']['title'] = value + _end_dc_title = _end_title + _end_media_title = _end_title + + def _start_description(self, attrsD): + context = self._getContext() + if context.has_key('summary'): + self._summaryKey = 'content' + self._start_content(attrsD) + else: + self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource) + + def _start_abstract(self, attrsD): + self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource) + + def _end_description(self): + if self._summaryKey == 'content': + self._end_content() + else: + value = self.popContent('description') + context = self._getContext() + if self.intextinput: + context['textinput']['description'] = value + elif self.inimage: + context['image']['description'] = value + self._summaryKey = None + _end_abstract = _end_description + + def _start_info(self, attrsD): + self.pushContent('info', attrsD, 'text/plain', 1) + _start_feedburner_browserfriendly = _start_info + + def _end_info(self): + self.popContent('info') + _end_feedburner_browserfriendly = _end_info + + def _start_generator(self, attrsD): + if attrsD: + attrsD = self._itsAnHrefDamnIt(attrsD) + if attrsD.has_key('href'): + attrsD['href'] = self.resolveURI(attrsD['href']) + self._getContext()['generator_detail'] = FeedParserDict(attrsD) + self.push('generator', 1) + + def _end_generator(self): + value = self.pop('generator') + context = self._getContext() + if context.has_key('generator_detail'): + context['generator_detail']['name'] = value + + def _start_admin_generatoragent(self, attrsD): + self.push('generator', 1) + value = self._getAttribute(attrsD, 'rdf:resource') + if value: + self.elementstack[-1][2].append(value) + self.pop('generator') + self._getContext()['generator_detail'] = FeedParserDict({'href': value}) + + def _start_admin_errorreportsto(self, attrsD): + self.push('errorreportsto', 1) + value = self._getAttribute(attrsD, 'rdf:resource') + if value: + self.elementstack[-1][2].append(value) + self.pop('errorreportsto') + + def _start_summary(self, attrsD): + context = self._getContext() + if context.has_key('summary'): + self._summaryKey = 'content' + self._start_content(attrsD) + else: + self._summaryKey = 'summary' + self.pushContent(self._summaryKey, attrsD, 'text/plain', 1) + _start_itunes_summary = _start_summary + + def _end_summary(self): + if self._summaryKey == 'content': + self._end_content() + else: + self.popContent(self._summaryKey or 'summary') + self._summaryKey = None + _end_itunes_summary = _end_summary + + def _start_enclosure(self, attrsD): + attrsD = self._itsAnHrefDamnIt(attrsD) + self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD)) + href = attrsD.get('href') + if href: + context = self._getContext() + if not context.get('id'): + context['id'] = href + + def _start_source(self, attrsD): + self.insource = 1 + + def _end_source(self): + self.insource = 0 + self._getContext()['source'] = copy.deepcopy(self.sourcedata) + self.sourcedata.clear() + + def _start_content(self, attrsD): + self.pushContent('content', attrsD, 'text/plain', 1) + src = attrsD.get('src') + if src: + self.contentparams['src'] = src + self.push('content', 1) + + def _start_prodlink(self, attrsD): + self.pushContent('content', attrsD, 'text/html', 1) + + def _start_body(self, attrsD): + self.pushContent('content', attrsD, 'application/xhtml+xml', 1) + _start_xhtml_body = _start_body + + def _start_content_encoded(self, attrsD): + self.pushContent('content', attrsD, 'text/html', 1) + _start_fullitem = _start_content_encoded + + def _end_content(self): + copyToDescription = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types) + value = self.popContent('content') + if copyToDescription: + self._save('description', value) + _end_body = _end_content + _end_xhtml_body = _end_content + _end_content_encoded = _end_content + _end_fullitem = _end_content + _end_prodlink = _end_content + + def _start_itunes_image(self, attrsD): + self.push('itunes_image', 0) + self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')}) + _start_itunes_link = _start_itunes_image + + def _end_itunes_block(self): + value = self.pop('itunes_block', 0) + self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0 + + def _end_itunes_explicit(self): + value = self.pop('itunes_explicit', 0) + self._getContext()['itunes_explicit'] = (value == 'yes') and 1 or 0 + +if _XML_AVAILABLE: + class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler): + def __init__(self, baseuri, baselang, encoding): + if _debug: sys.stderr.write('trying StrictFeedParser\n') + xml.sax.handler.ContentHandler.__init__(self) + _FeedParserMixin.__init__(self, baseuri, baselang, encoding) + self.bozo = 0 + self.exc = None + + def startPrefixMapping(self, prefix, uri): + self.trackNamespace(prefix, uri) + + def startElementNS(self, name, qname, attrs): + namespace, localname = name + lowernamespace = str(namespace or '').lower() + if lowernamespace.find('backend.userland.com/rss') <> -1: + # match any backend.userland.com namespace + namespace = 'http://backend.userland.com/rss' + lowernamespace = namespace + if qname and qname.find(':') > 0: + givenprefix = qname.split(':')[0] + else: + givenprefix = None + prefix = self._matchnamespaces.get(lowernamespace, givenprefix) + if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and not self.namespacesInUse.has_key(givenprefix): + raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix + if prefix: + localname = prefix + ':' + localname + localname = str(localname).lower() + if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % (qname, namespace, givenprefix, prefix, attrs.items(), localname)) + + # qname implementation is horribly broken in Python 2.1 (it + # doesn't report any), and slightly broken in Python 2.2 (it + # doesn't report the xml: namespace). So we match up namespaces + # with a known list first, and then possibly override them with + # the qnames the SAX parser gives us (if indeed it gives us any + # at all). Thanks to MatejC for helping me test this and + # tirelessly telling me that it didn't work yet. + attrsD = {} + for (namespace, attrlocalname), attrvalue in attrs._attrs.items(): + lowernamespace = (namespace or '').lower() + prefix = self._matchnamespaces.get(lowernamespace, '') + if prefix: + attrlocalname = prefix + ':' + attrlocalname + attrsD[str(attrlocalname).lower()] = attrvalue + for qname in attrs.getQNames(): + attrsD[str(qname).lower()] = attrs.getValueByQName(qname) + self.unknown_starttag(localname, attrsD.items()) + + def characters(self, text): + self.handle_data(text) + + def endElementNS(self, name, qname): + namespace, localname = name + lowernamespace = str(namespace or '').lower() + if qname and qname.find(':') > 0: + givenprefix = qname.split(':')[0] + else: + givenprefix = '' + prefix = self._matchnamespaces.get(lowernamespace, givenprefix) + if prefix: + localname = prefix + ':' + localname + localname = str(localname).lower() + self.unknown_endtag(localname) + + def error(self, exc): + self.bozo = 1 + self.exc = exc + + def fatalError(self, exc): + self.error(exc) + raise exc + +class _BaseHTMLProcessor(sgmllib.SGMLParser): + elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', + 'img', 'input', 'isindex', 'link', 'meta', 'param'] + + def __init__(self, encoding): + self.encoding = encoding + if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding) + sgmllib.SGMLParser.__init__(self) + + def reset(self): + self.pieces = [] + sgmllib.SGMLParser.reset(self) + + def _shorttag_replace(self, match): + tag = match.group(1) + if tag in self.elements_no_end_tag: + return '<' + tag + ' />' + else: + return '<' + tag + '>' + + def feed(self, data): + data = re.compile(r'', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace + data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) + data = data.replace(''', "'") + data = data.replace('"', '"') + if self.encoding and type(data) == type(u''): + data = data.encode(self.encoding) + sgmllib.SGMLParser.feed(self, data) + + def normalize_attrs(self, attrs): + # utility method to be called by descendants + attrs = [(k.lower(), v) for k, v in attrs] + attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] + return attrs + + def unknown_starttag(self, tag, attrs): + # called for each start tag + # attrs is a list of (attr, value) tuples + # e.g. for
, tag='pre', attrs=[('class', 'screen')]
+        if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
+        uattrs = []
+        # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
+        for key, value in attrs:
+            if type(value) != type(u''):
+                value = unicode(value, self.encoding)
+            uattrs.append((unicode(key, self.encoding), value))
+        strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
+        if tag in self.elements_no_end_tag:
+            self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
+        else:
+            self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
+
+    def unknown_endtag(self, tag):
+        # called for each end tag, e.g. for 
, tag will be 'pre' + # Reconstruct the original end tag. + if tag not in self.elements_no_end_tag: + self.pieces.append("" % locals()) + + def handle_charref(self, ref): + # called for each character reference, e.g. for ' ', ref will be '160' + # Reconstruct the original character reference. + self.pieces.append('&#%(ref)s;' % locals()) + + def handle_entityref(self, ref): + # called for each entity reference, e.g. for '©', ref will be 'copy' + # Reconstruct the original entity reference. + self.pieces.append('&%(ref)s;' % locals()) + + def handle_data(self, text): + # called for each block of plain text, i.e. outside of any tag and + # not containing any character or entity references + # Store the original text verbatim. + if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text) + self.pieces.append(text) + + def handle_comment(self, text): + # called for each HTML comment, e.g. + # Reconstruct the original comment. + self.pieces.append('' % locals()) + + def handle_pi(self, text): + # called for each processing instruction, e.g. + # Reconstruct original processing instruction. + self.pieces.append('' % locals()) + + def handle_decl(self, text): + # called for the DOCTYPE, if present, e.g. + # + # Reconstruct original DOCTYPE + self.pieces.append('' % locals()) + + _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match + def _scan_name(self, i, declstartpos): + rawdata = self.rawdata + n = len(rawdata) + if i == n: + return None, -1 + m = self._new_declname_match(rawdata, i) + if m: + s = m.group() + name = s.strip() + if (i + len(s)) == n: + return None, -1 # end of buffer + return name.lower(), m.end() + else: + self.handle_data(rawdata) +# self.updatepos(declstartpos, i) + return None, -1 + + def output(self): + '''Return processed HTML as a single string''' + return ''.join([str(p) for p in self.pieces]) + +class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor): + def __init__(self, baseuri, baselang, encoding): + sgmllib.SGMLParser.__init__(self) + _FeedParserMixin.__init__(self, baseuri, baselang, encoding) + + def decodeEntities(self, element, data): + data = data.replace('<', '<') + data = data.replace('<', '<') + data = data.replace('>', '>') + data = data.replace('>', '>') + data = data.replace('&', '&') + data = data.replace('&', '&') + data = data.replace('"', '"') + data = data.replace('"', '"') + data = data.replace(''', ''') + data = data.replace(''', ''') + if self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'): + data = data.replace('<', '<') + data = data.replace('>', '>') + data = data.replace('&', '&') + data = data.replace('"', '"') + data = data.replace(''', "'") + return data + +class _RelativeURIResolver(_BaseHTMLProcessor): + relative_uris = [('a', 'href'), + ('applet', 'codebase'), + ('area', 'href'), + ('blockquote', 'cite'), + ('body', 'background'), + ('del', 'cite'), + ('form', 'action'), + ('frame', 'longdesc'), + ('frame', 'src'), + ('iframe', 'longdesc'), + ('iframe', 'src'), + ('head', 'profile'), + ('img', 'longdesc'), + ('img', 'src'), + ('img', 'usemap'), + ('input', 'src'), + ('input', 'usemap'), + ('ins', 'cite'), + ('link', 'href'), + ('object', 'classid'), + ('object', 'codebase'), + ('object', 'data'), + ('object', 'usemap'), + ('q', 'cite'), + ('script', 'src')] + + def __init__(self, baseuri, encoding): + _BaseHTMLProcessor.__init__(self, encoding) + self.baseuri = baseuri + + def resolveURI(self, uri): + return _urljoin(self.baseuri, uri) + + def unknown_starttag(self, tag, attrs): + attrs = self.normalize_attrs(attrs) + attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs] + _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) + +def _resolveRelativeURIs(htmlSource, baseURI, encoding): + if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') + p = _RelativeURIResolver(baseURI, encoding) + p.feed(htmlSource) + return p.output() + +class _HTMLSanitizer(_BaseHTMLProcessor): + acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big', + 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', + 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', + 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', + 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup', + 'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike', + 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', + 'thead', 'tr', 'tt', 'u', 'ul', 'var'] + + acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', + 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', + 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols', + 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', + 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', + 'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method', + 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', + 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', + 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type', + 'usemap', 'valign', 'value', 'vspace', 'width'] + + unacceptable_elements_with_end_tag = ['script', 'applet'] + + def reset(self): + _BaseHTMLProcessor.reset(self) + self.unacceptablestack = 0 + + def unknown_starttag(self, tag, attrs): + if not tag in self.acceptable_elements: + if tag in self.unacceptable_elements_with_end_tag: + self.unacceptablestack += 1 + return + attrs = self.normalize_attrs(attrs) + attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes] + _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) + + def unknown_endtag(self, tag): + if not tag in self.acceptable_elements: + if tag in self.unacceptable_elements_with_end_tag: + self.unacceptablestack -= 1 + return + _BaseHTMLProcessor.unknown_endtag(self, tag) + + def handle_pi(self, text): + pass + + def handle_decl(self, text): + pass + + def handle_data(self, text): + if not self.unacceptablestack: + _BaseHTMLProcessor.handle_data(self, text) + +def _sanitizeHTML(htmlSource, encoding): + p = _HTMLSanitizer(encoding) + p.feed(htmlSource) + data = p.output() + if TIDY_MARKUP: + # loop through list of preferred Tidy interfaces looking for one that's installed, + # then set up a common _tidy function to wrap the interface-specific API. + _tidy = None + for tidy_interface in PREFERRED_TIDY_INTERFACES: + try: + if tidy_interface == "uTidy": + from tidy import parseString as _utidy + def _tidy(data, **kwargs): + return str(_utidy(data, **kwargs)) + break + elif tidy_interface == "mxTidy": + from mx.Tidy import Tidy as _mxtidy + def _tidy(data, **kwargs): + nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs) + return data + break + except: + pass + if _tidy: + utf8 = type(data) == type(u'') + if utf8: + data = data.encode('utf-8') + data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8") + if utf8: + data = unicode(data, 'utf-8') + if data.count(''): + data = data.split('>', 1)[1] + if data.count('= '2.3.3' + assert base64 != None + user, passw = base64.decodestring(req.headers['Authorization'].split(' ')[1]).split(':') + realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0] + self.add_password(realm, host, user, passw) + retry = self.http_error_auth_reqed('www-authenticate', host, req, headers) + self.reset_retry_count() + return retry + except: + return self.http_error_default(req, fp, code, msg, headers) + +def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): + """URL, filename, or string --> stream + + This function lets you define parsers that take any input source + (URL, pathname to local or network file, or actual data as a string) + and deal with it in a uniform manner. Returned object is guaranteed + to have all the basic stdio read methods (read, readline, readlines). + Just .close() the object when you're done with it. + + If the etag argument is supplied, it will be used as the value of an + If-None-Match request header. + + If the modified argument is supplied, it must be a tuple of 9 integers + as returned by gmtime() in the standard Python time module. This MUST + be in GMT (Greenwich Mean Time). The formatted date/time will be used + as the value of an If-Modified-Since request header. + + If the agent argument is supplied, it will be used as the value of a + User-Agent request header. + + If the referrer argument is supplied, it will be used as the value of a + Referer[sic] request header. + + If handlers is supplied, it is a list of handlers used to build a + urllib2 opener. + """ + + if hasattr(url_file_stream_or_string, 'read'): + return url_file_stream_or_string + + if url_file_stream_or_string == '-': + return sys.stdin + + # urllib does not support the 'feed' scheme -- replace with 'http' + if url_file_stream_or_string.startswith('feed://'): + url_file_stream_or_string = url_file_stream_or_string.replace('feed://', 'http://', 1) + + scheme = urlparse.urlparse(url_file_stream_or_string)[0] + + if scheme in ('http', 'https', 'ftp'): + if not agent: + agent = USER_AGENT + # test for inline user:password for basic auth + auth = None + if base64: + urltype, rest = urllib.splittype(url_file_stream_or_string) + realhost, rest = urllib.splithost(rest) + if realhost: + user_passwd, realhost = urllib.splituser(realhost) + if user_passwd: + url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest) + auth = base64.encodestring(user_passwd).strip() + # try to open with urllib2 (to use optional headers) + request = urllib2.Request(url_file_stream_or_string) + request.add_header('User-Agent', agent) + if etag: + request.add_header('If-None-Match', etag) + if modified: + # format into an RFC 1123-compliant timestamp. We can't use + # time.strftime() since the %a and %b directives can be affected + # by the current locale, but RFC 2616 states that dates must be + # in English. + short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5])) + if referrer: + request.add_header('Referer', referrer) + if gzip and zlib: + request.add_header('Accept-encoding', 'gzip, deflate') + elif gzip: + request.add_header('Accept-encoding', 'gzip') + elif zlib: + request.add_header('Accept-encoding', 'deflate') + else: + request.add_header('Accept-encoding', '') + if auth: + request.add_header('Authorization', 'Basic %s' % auth) + if ACCEPT_HEADER: + request.add_header('Accept', ACCEPT_HEADER) + request.add_header('A-IM', 'feed') # RFC 3229 support + opener = apply(urllib2.build_opener, tuple([_FeedURLHandler()] + handlers)) + opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent + try: + return opener.open(request) + finally: + opener.close() # JohnD + + # try to open with native open function (if url_file_stream_or_string is a filename) + try: + return open(url_file_stream_or_string) + except: + pass + + # treat url_file_stream_or_string as string + return _StringIO(str(url_file_stream_or_string)) + +_date_handlers = [] +def registerDateHandler(func): + '''Register a date handler function (takes string, returns 9-tuple date in GMT)''' + _date_handlers.insert(0, func) + +# ISO-8601 date parsing routines written by Fazal Majid. +# The ISO 8601 standard is very convoluted and irregular - a full ISO 8601 +# parser is beyond the scope of feedparser and would be a worthwhile addition +# to the Python library. +# A single regular expression cannot parse ISO 8601 date formats into groups +# as the standard is highly irregular (for instance is 030104 2003-01-04 or +# 0301-04-01), so we use templates instead. +# Please note the order in templates is significant because we need a +# greedy match. +_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO', + 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', + '-YY-?MM', '-OOO', '-YY', + '--MM-?DD', '--MM', + '---DD', + 'CC', ''] +_iso8601_re = [ + tmpl.replace( + 'YYYY', r'(?P\d{4})').replace( + 'YY', r'(?P\d\d)').replace( + 'MM', r'(?P[01]\d)').replace( + 'DD', r'(?P[0123]\d)').replace( + 'OOO', r'(?P[0123]\d\d)').replace( + 'CC', r'(?P\d\d$)') + + r'(T?(?P\d{2}):(?P\d{2})' + + r'(:(?P\d{2}))?' + + r'(?P[+-](?P\d{2})(:(?P\d{2}))?|Z)?)?' + for tmpl in _iso8601_tmpl] +del tmpl +_iso8601_matches = [re.compile(regex).match for regex in _iso8601_re] +del regex +def _parse_date_iso8601(dateString): + '''Parse a variety of ISO-8601-compatible formats like 20040105''' + m = None + for _iso8601_match in _iso8601_matches: + m = _iso8601_match(dateString) + if m: break + if not m: return + if m.span() == (0, 0): return + params = m.groupdict() + ordinal = params.get('ordinal', 0) + if ordinal: + ordinal = int(ordinal) + else: + ordinal = 0 + year = params.get('year', '--') + if not year or year == '--': + year = time.gmtime()[0] + elif len(year) == 2: + # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993 + year = 100 * int(time.gmtime()[0] / 100) + int(year) + else: + year = int(year) + month = params.get('month', '-') + if not month or month == '-': + # ordinals are NOT normalized by mktime, we simulate them + # by setting month=1, day=ordinal + if ordinal: + month = 1 + else: + month = time.gmtime()[1] + month = int(month) + day = params.get('day', 0) + if not day: + # see above + if ordinal: + day = ordinal + elif params.get('century', 0) or \ + params.get('year', 0) or params.get('month', 0): + day = 1 + else: + day = time.gmtime()[2] + else: + day = int(day) + # special case of the century - is the first year of the 21st century + # 2000 or 2001 ? The debate goes on... + if 'century' in params.keys(): + year = (int(params['century']) - 1) * 100 + 1 + # in ISO 8601 most fields are optional + for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']: + if not params.get(field, None): + params[field] = 0 + hour = int(params.get('hour', 0)) + minute = int(params.get('minute', 0)) + second = int(params.get('second', 0)) + # weekday is normalized by mktime(), we can ignore it + weekday = 0 + # daylight savings is complex, but not needed for feedparser's purposes + # as time zones, if specified, include mention of whether it is active + # (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and + # and most implementations have DST bugs + daylight_savings_flag = 0 + tm = [year, month, day, hour, minute, second, weekday, + ordinal, daylight_savings_flag] + # ISO 8601 time zone adjustments + tz = params.get('tz') + if tz and tz != 'Z': + if tz[0] == '-': + tm[3] += int(params.get('tzhour', 0)) + tm[4] += int(params.get('tzmin', 0)) + elif tz[0] == '+': + tm[3] -= int(params.get('tzhour', 0)) + tm[4] -= int(params.get('tzmin', 0)) + else: + return None + # Python's time.mktime() is a wrapper around the ANSI C mktime(3c) + # which is guaranteed to normalize d/m/y/h/m/s. + # Many implementations have bugs, but we'll pretend they don't. + return time.localtime(time.mktime(tm)) +registerDateHandler(_parse_date_iso8601) + +# 8-bit date handling routines written by ytrewq1. +_korean_year = u'\ub144' # b3e2 in euc-kr +_korean_month = u'\uc6d4' # bff9 in euc-kr +_korean_day = u'\uc77c' # c0cf in euc-kr +_korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr +_korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr + +_korean_onblog_date_re = \ + re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \ + (_korean_year, _korean_month, _korean_day)) +_korean_nate_date_re = \ + re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \ + (_korean_am, _korean_pm)) +def _parse_date_onblog(dateString): + '''Parse a string according to the OnBlog 8-bit date format''' + m = _korean_onblog_date_re.match(dateString) + if not m: return + w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ + {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ + 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\ + 'zonediff': '+09:00'} + if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate) + return _parse_date_w3dtf(w3dtfdate) +registerDateHandler(_parse_date_onblog) + +def _parse_date_nate(dateString): + '''Parse a string according to the Nate 8-bit date format''' + m = _korean_nate_date_re.match(dateString) + if not m: return + hour = int(m.group(5)) + ampm = m.group(4) + if (ampm == _korean_pm): + hour += 12 + hour = str(hour) + if len(hour) == 1: + hour = '0' + hour + w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ + {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ + 'hour': hour, 'minute': m.group(6), 'second': m.group(7),\ + 'zonediff': '+09:00'} + if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate) + return _parse_date_w3dtf(w3dtfdate) +registerDateHandler(_parse_date_nate) + +_mssql_date_re = \ + re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?') +def _parse_date_mssql(dateString): + '''Parse a string according to the MS SQL date format''' + m = _mssql_date_re.match(dateString) + if not m: return + w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ + {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ + 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\ + 'zonediff': '+09:00'} + if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate) + return _parse_date_w3dtf(w3dtfdate) +registerDateHandler(_parse_date_mssql) + +# Unicode strings for Greek date strings +_greek_months = \ + { \ + u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7 + u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7 + u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7 + u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7 + u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7 + u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7 + u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7 + u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7 + u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7 + u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7 + u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7 + u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7 + u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7 + u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7 + u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7 + u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7 + u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7 + u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7 + u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7 + } + +_greek_wdays = \ + { \ + u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7 + u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7 + u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7 + u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7 + u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7 + u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7 + u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7 + } + +_greek_date_format_re = \ + re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)') + +def _parse_date_greek(dateString): + '''Parse a string according to a Greek 8-bit date format.''' + m = _greek_date_format_re.match(dateString) + if not m: return + try: + wday = _greek_wdays[m.group(1)] + month = _greek_months[m.group(3)] + except: + return + rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \ + {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\ + 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\ + 'zonediff': m.group(8)} + if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date) + return _parse_date_rfc822(rfc822date) +registerDateHandler(_parse_date_greek) + +# Unicode strings for Hungarian date strings +_hungarian_months = \ + { \ + u'janu\u00e1r': u'01', # e1 in iso-8859-2 + u'febru\u00e1ri': u'02', # e1 in iso-8859-2 + u'm\u00e1rcius': u'03', # e1 in iso-8859-2 + u'\u00e1prilis': u'04', # e1 in iso-8859-2 + u'm\u00e1ujus': u'05', # e1 in iso-8859-2 + u'j\u00fanius': u'06', # fa in iso-8859-2 + u'j\u00falius': u'07', # fa in iso-8859-2 + u'augusztus': u'08', + u'szeptember': u'09', + u'okt\u00f3ber': u'10', # f3 in iso-8859-2 + u'november': u'11', + u'december': u'12', + } + +_hungarian_date_format_re = \ + re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))') + +def _parse_date_hungarian(dateString): + '''Parse a string according to a Hungarian 8-bit date format.''' + m = _hungarian_date_format_re.match(dateString) + if not m: return + try: + month = _hungarian_months[m.group(2)] + day = m.group(3) + if len(day) == 1: + day = '0' + day + hour = m.group(4) + if len(hour) == 1: + hour = '0' + hour + except: + return + w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \ + {'year': m.group(1), 'month': month, 'day': day,\ + 'hour': hour, 'minute': m.group(5),\ + 'zonediff': m.group(6)} + if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate) + return _parse_date_w3dtf(w3dtfdate) +registerDateHandler(_parse_date_hungarian) + +# W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by +# Drake and licensed under the Python license. Removed all range checking +# for month, day, hour, minute, and second, since mktime will normalize +# these later +def _parse_date_w3dtf(dateString): + def __extract_date(m): + year = int(m.group('year')) + if year < 100: + year = 100 * int(time.gmtime()[0] / 100) + int(year) + if year < 1000: + return 0, 0, 0 + julian = m.group('julian') + if julian: + julian = int(julian) + month = julian / 30 + 1 + day = julian % 30 + 1 + jday = None + while jday != julian: + t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0)) + jday = time.gmtime(t)[-2] + diff = abs(jday - julian) + if jday > julian: + if diff < day: + day = day - diff + else: + month = month - 1 + day = 31 + elif jday < julian: + if day + diff < 28: + day = day + diff + else: + month = month + 1 + return year, month, day + month = m.group('month') + day = 1 + if month is None: + month = 1 + else: + month = int(month) + day = m.group('day') + if day: + day = int(day) + else: + day = 1 + return year, month, day + + def __extract_time(m): + if not m: + return 0, 0, 0 + hours = m.group('hours') + if not hours: + return 0, 0, 0 + hours = int(hours) + minutes = int(m.group('minutes')) + seconds = m.group('seconds') + if seconds: + seconds = int(seconds) + else: + seconds = 0 + return hours, minutes, seconds + + def __extract_tzd(m): + '''Return the Time Zone Designator as an offset in seconds from UTC.''' + if not m: + return 0 + tzd = m.group('tzd') + if not tzd: + return 0 + if tzd == 'Z': + return 0 + hours = int(m.group('tzdhours')) + minutes = m.group('tzdminutes') + if minutes: + minutes = int(minutes) + else: + minutes = 0 + offset = (hours*60 + minutes) * 60 + if tzd[0] == '+': + return -offset + return offset + + __date_re = ('(?P\d\d\d\d)' + '(?:(?P-|)' + '(?:(?P\d\d\d)' + '|(?P\d\d)(?:(?P=dsep)(?P\d\d))?))?') + __tzd_re = '(?P[-+](?P\d\d)(?::?(?P\d\d))|Z)' + __tzd_rx = re.compile(__tzd_re) + __time_re = ('(?P\d\d)(?P:|)(?P\d\d)' + '(?:(?P=tsep)(?P\d\d(?:[.,]\d+)?))?' + + __tzd_re) + __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re) + __datetime_rx = re.compile(__datetime_re) + m = __datetime_rx.match(dateString) + if (m is None) or (m.group() != dateString): return + gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0) + if gmt[0] == 0: return + return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone) +registerDateHandler(_parse_date_w3dtf) + +def _parse_date_rfc822(dateString): + '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date''' + data = dateString.split() + if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames: + del data[0] + if len(data) == 4: + s = data[3] + i = s.find('+') + if i > 0: + data[3:] = [s[:i], s[i+1:]] + else: + data.append('') + dateString = " ".join(data) + if len(data) < 5: + dateString += ' 00:00:00 GMT' + tm = rfc822.parsedate_tz(dateString) + if tm: + return time.gmtime(rfc822.mktime_tz(tm)) +# rfc822.py defines several time zones, but we define some extra ones. +# 'ET' is equivalent to 'EST', etc. +_additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800} +rfc822._timezones.update(_additional_timezones) +registerDateHandler(_parse_date_rfc822) + +def _parse_date(dateString): + '''Parses a variety of date formats into a 9-tuple in GMT''' + for handler in _date_handlers: + try: + date9tuple = handler(dateString) + if not date9tuple: continue + if len(date9tuple) != 9: + if _debug: sys.stderr.write('date handler function must return 9-tuple\n') + raise ValueError + map(int, date9tuple) + return date9tuple + except Exception, e: + if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e))) + pass + return None + +def _getCharacterEncoding(http_headers, xml_data): + '''Get the character encoding of the XML document + + http_headers is a dictionary + xml_data is a raw string (not Unicode) + + This is so much trickier than it sounds, it's not even funny. + According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type + is application/xml, application/*+xml, + application/xml-external-parsed-entity, or application/xml-dtd, + the encoding given in the charset parameter of the HTTP Content-Type + takes precedence over the encoding given in the XML prefix within the + document, and defaults to 'utf-8' if neither are specified. But, if + the HTTP Content-Type is text/xml, text/*+xml, or + text/xml-external-parsed-entity, the encoding given in the XML prefix + within the document is ALWAYS IGNORED and only the encoding given in + the charset parameter of the HTTP Content-Type header should be + respected, and it defaults to 'us-ascii' if not specified. + + Furthermore, discussion on the atom-syntax mailing list with the + author of RFC 3023 leads me to the conclusion that any document + served with a Content-Type of text/* and no charset parameter + must be treated as us-ascii. (We now do this.) And also that it + must always be flagged as non-well-formed. (We now do this too.) + + If Content-Type is unspecified (input was local file or non-HTTP source) + or unrecognized (server just got it totally wrong), then go by the + encoding given in the XML prefix of the document and default to + 'iso-8859-1' as per the HTTP specification (RFC 2616). + + Then, assuming we didn't find a character encoding in the HTTP headers + (and the HTTP Content-type allowed us to look in the body), we need + to sniff the first few bytes of the XML data and try to determine + whether the encoding is ASCII-compatible. Section F of the XML + specification shows the way here: + http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info + + If the sniffed encoding is not ASCII-compatible, we need to make it + ASCII compatible so that we can sniff further into the XML declaration + to find the encoding attribute, which will tell us the true encoding. + + Of course, none of this guarantees that we will be able to parse the + feed in the declared character encoding (assuming it was declared + correctly, which many are not). CJKCodecs and iconv_codec help a lot; + you should definitely install them if you can. + http://cjkpython.i18n.org/ + ''' + + def _parseHTTPContentType(content_type): + '''takes HTTP Content-Type header and returns (content type, charset) + + If no charset is specified, returns (content type, '') + If no content type is specified, returns ('', '') + Both return parameters are guaranteed to be lowercase strings + ''' + content_type = content_type or '' + content_type, params = cgi.parse_header(content_type) + return content_type, params.get('charset', '').replace("'", '') + + sniffed_xml_encoding = '' + xml_encoding = '' + true_encoding = '' + http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type')) + # Must sniff for non-ASCII-compatible character encodings before + # searching for XML declaration. This heuristic is defined in + # section F of the XML specification: + # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info + try: + if xml_data[:4] == '\x4c\x6f\xa7\x94': + # EBCDIC + xml_data = _ebcdic_to_ascii(xml_data) + elif xml_data[:4] == '\x00\x3c\x00\x3f': + # UTF-16BE + sniffed_xml_encoding = 'utf-16be' + xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') + elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00'): + # UTF-16BE with BOM + sniffed_xml_encoding = 'utf-16be' + xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') + elif xml_data[:4] == '\x3c\x00\x3f\x00': + # UTF-16LE + sniffed_xml_encoding = 'utf-16le' + xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') + elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00'): + # UTF-16LE with BOM + sniffed_xml_encoding = 'utf-16le' + xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') + elif xml_data[:4] == '\x00\x00\x00\x3c': + # UTF-32BE + sniffed_xml_encoding = 'utf-32be' + xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') + elif xml_data[:4] == '\x3c\x00\x00\x00': + # UTF-32LE + sniffed_xml_encoding = 'utf-32le' + xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') + elif xml_data[:4] == '\x00\x00\xfe\xff': + # UTF-32BE with BOM + sniffed_xml_encoding = 'utf-32be' + xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') + elif xml_data[:4] == '\xff\xfe\x00\x00': + # UTF-32LE with BOM + sniffed_xml_encoding = 'utf-32le' + xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') + elif xml_data[:3] == '\xef\xbb\xbf': + # UTF-8 with BOM + sniffed_xml_encoding = 'utf-8' + xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') + else: + # ASCII-compatible + pass + xml_encoding_match = re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data) + except: + xml_encoding_match = None + if xml_encoding_match: + xml_encoding = xml_encoding_match.groups()[0].lower() + if sniffed_xml_encoding and (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')): + xml_encoding = sniffed_xml_encoding + acceptable_content_type = 0 + application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity') + text_content_types = ('text/xml', 'text/xml-external-parsed-entity') + if (http_content_type in application_content_types) or \ + (http_content_type.startswith('application/') and http_content_type.endswith('+xml')): + acceptable_content_type = 1 + true_encoding = http_encoding or xml_encoding or 'utf-8' + elif (http_content_type in text_content_types) or \ + (http_content_type.startswith('text/')) and http_content_type.endswith('+xml'): + acceptable_content_type = 1 + true_encoding = http_encoding or 'us-ascii' + elif http_content_type.startswith('text/'): + true_encoding = http_encoding or 'us-ascii' + elif http_headers and (not http_headers.has_key('content-type')): + true_encoding = xml_encoding or 'iso-8859-1' + else: + true_encoding = xml_encoding or 'utf-8' + return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type + +def _toUTF8(data, encoding): + '''Changes an XML data stream on the fly to specify a new encoding + + data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already + encoding is a string recognized by encodings.aliases + ''' + if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding) + # strip Byte Order Mark (if present) + if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'): + if _debug: + sys.stderr.write('stripping BOM\n') + if encoding != 'utf-16be': + sys.stderr.write('trying utf-16be instead\n') + encoding = 'utf-16be' + data = data[2:] + elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'): + if _debug: + sys.stderr.write('stripping BOM\n') + if encoding != 'utf-16le': + sys.stderr.write('trying utf-16le instead\n') + encoding = 'utf-16le' + data = data[2:] + elif data[:3] == '\xef\xbb\xbf': + if _debug: + sys.stderr.write('stripping BOM\n') + if encoding != 'utf-8': + sys.stderr.write('trying utf-8 instead\n') + encoding = 'utf-8' + data = data[3:] + elif data[:4] == '\x00\x00\xfe\xff': + if _debug: + sys.stderr.write('stripping BOM\n') + if encoding != 'utf-32be': + sys.stderr.write('trying utf-32be instead\n') + encoding = 'utf-32be' + data = data[4:] + elif data[:4] == '\xff\xfe\x00\x00': + if _debug: + sys.stderr.write('stripping BOM\n') + if encoding != 'utf-32le': + sys.stderr.write('trying utf-32le instead\n') + encoding = 'utf-32le' + data = data[4:] + newdata = unicode(data, encoding) + if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding) + declmatch = re.compile('^<\?xml[^>]*?>') + newdecl = '''''' + if declmatch.search(newdata): + newdata = declmatch.sub(newdecl, newdata) + else: + newdata = newdecl + u'\n' + newdata + return newdata.encode('utf-8') + +def _stripDoctype(data): + '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) + + rss_version may be 'rss091n' or None + stripped_data is the same XML document, minus the DOCTYPE + ''' + entity_pattern = re.compile(r']*?)>', re.MULTILINE) + data = entity_pattern.sub('', data) + doctype_pattern = re.compile(r']*?)>', re.MULTILINE) + doctype_results = doctype_pattern.findall(data) + doctype = doctype_results and doctype_results[0] or '' + if doctype.lower().count('netscape'): + version = 'rss091n' + else: + version = None + data = doctype_pattern.sub('', data) + return version, data + +def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): + '''Parse a feed from a URL, file, stream, or string''' + result = FeedParserDict() + result['feed'] = FeedParserDict() + result['entries'] = [] + if _XML_AVAILABLE: + result['bozo'] = 0 + if type(handlers) == types.InstanceType: + handlers = [handlers] + try: + f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers) + data = f.read() + except Exception, e: + result['bozo'] = 1 + result['bozo_exception'] = e + data = '' + f = None + + # if feed is gzip-compressed, decompress it + if f and data and hasattr(f, 'headers'): + if gzip and f.headers.get('content-encoding', '') == 'gzip': + try: + data = gzip.GzipFile(fileobj=_StringIO(data)).read() + except Exception, e: + # Some feeds claim to be gzipped but they're not, so + # we get garbage. Ideally, we should re-request the + # feed without the 'Accept-encoding: gzip' header, + # but we don't. + result['bozo'] = 1 + result['bozo_exception'] = e + data = '' + elif zlib and f.headers.get('content-encoding', '') == 'deflate': + try: + data = zlib.decompress(data, -zlib.MAX_WBITS) + except Exception, e: + result['bozo'] = 1 + result['bozo_exception'] = e + data = '' + + # save HTTP headers + if hasattr(f, 'info'): + info = f.info() + result['etag'] = info.getheader('ETag') + last_modified = info.getheader('Last-Modified') + if last_modified: + result['modified'] = _parse_date(last_modified) + if hasattr(f, 'url'): + result['href'] = f.url + result['status'] = 200 + if hasattr(f, 'status'): + result['status'] = f.status + if hasattr(f, 'headers'): + result['headers'] = f.headers.dict + if hasattr(f, 'close'): + f.close() + + # there are four encodings to keep track of: + # - http_encoding is the encoding declared in the Content-Type HTTP header + # - xml_encoding is the encoding declared in the ; changed +# project name +#2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree); +# removed unnecessary urllib code -- urllib2 should always be available anyway; +# return actual url, status, and full HTTP headers (as result['url'], +# result['status'], and result['headers']) if parsing a remote feed over HTTP -- +# this should pass all the HTTP tests at ; +# added the latest namespace-of-the-week for RSS 2.0 +#2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom +# User-Agent (otherwise urllib2 sends two, which confuses some servers) +#2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for +# inline and as used in some RSS 2.0 feeds +#2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or +# textInput, and also to return the character encoding (if specified) +#2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking +# nested divs within content (JohnD); fixed missing sys import (JohanS); +# fixed regular expression to capture XML character encoding (Andrei); +# added support for Atom 0.3-style links; fixed bug with textInput tracking; +# added support for cloud (MartijnP); added support for multiple +# category/dc:subject (MartijnP); normalize content model: 'description' gets +# description (which can come from description, summary, or full content if no +# description), 'content' gets dict of base/language/type/value (which can come +# from content:encoded, xhtml:body, content, or fullitem); +# fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang +# tracking; fixed bug tracking unknown tags; fixed bug tracking content when +# element is not in default namespace (like Pocketsoap feed); +# resolve relative URLs in link, guid, docs, url, comments, wfw:comment, +# wfw:commentRSS; resolve relative URLs within embedded HTML markup in +# description, xhtml:body, content, content:encoded, title, subtitle, +# summary, info, tagline, and copyright; added support for pingback and +# trackback namespaces +#2.7 - 1/5/2004 - MAP - really added support for trackback and pingback +# namespaces, as opposed to 2.6 when I said I did but didn't really; +# sanitize HTML markup within some elements; added mxTidy support (if +# installed) to tidy HTML markup within some elements; fixed indentation +# bug in _parse_date (FazalM); use socket.setdefaulttimeout if available +# (FazalM); universal date parsing and normalization (FazalM): 'created', modified', +# 'issued' are parsed into 9-tuple date format and stored in 'created_parsed', +# 'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified' +# and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa +#2.7.1 - 1/9/2004 - MAP - fixed bug handling " and '. fixed memory +# leak not closing url opener (JohnD); added dc:publisher support (MarekK); +# added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK) +#2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed
tags in +# encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL); +# fixed relative URI processing for guid (skadz); added ICBM support; added +# base64 support +#2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many +# blogspot.com sites); added _debug variable +#2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing +#3.0b3 - 1/23/2004 - MAP - parse entire feed with real XML parser (if available); +# added several new supported namespaces; fixed bug tracking naked markup in +# description; added support for enclosure; added support for source; re-added +# support for cloud which got dropped somehow; added support for expirationDate +#3.0b4 - 1/26/2004 - MAP - fixed xml:lang inheritance; fixed multiple bugs tracking +# xml:base URI, one for documents that don't define one explicitly and one for +# documents that define an outer and an inner xml:base that goes out of scope +# before the end of the document +#3.0b5 - 1/26/2004 - MAP - fixed bug parsing multiple links at feed level +#3.0b6 - 1/27/2004 - MAP - added feed type and version detection, result['version'] +# will be one of SUPPORTED_VERSIONS.keys() or empty string if unrecognized; +# added support for creativeCommons:license and cc:license; added support for +# full Atom content model in title, tagline, info, copyright, summary; fixed bug +# with gzip encoding (not always telling server we support it when we do) +#3.0b7 - 1/28/2004 - MAP - support Atom-style author element in author_detail +# (dictionary of 'name', 'url', 'email'); map author to author_detail if author +# contains name + email address +#3.0b8 - 1/28/2004 - MAP - added support for contributor +#3.0b9 - 1/29/2004 - MAP - fixed check for presence of dict function; added +# support for summary +#3.0b10 - 1/31/2004 - MAP - incorporated ISO-8601 date parsing routines from +# xml.util.iso8601 +#3.0b11 - 2/2/2004 - MAP - added 'rights' to list of elements that can contain +# dangerous markup; fiddled with decodeEntities (not right); liberalized +# date parsing even further +#3.0b12 - 2/6/2004 - MAP - fiddled with decodeEntities (still not right); +# added support to Atom 0.2 subtitle; added support for Atom content model +# in copyright; better sanitizing of dangerous HTML elements with end tags +# (script, frameset) +#3.0b13 - 2/8/2004 - MAP - better handling of empty HTML tags (br, hr, img, +# etc.) in embedded markup, in either HTML or XHTML form (
,
,
) +#3.0b14 - 2/8/2004 - MAP - fixed CDATA handling in non-wellformed feeds under +# Python 2.1 +#3.0b15 - 2/11/2004 - MAP - fixed bug resolving relative links in wfw:commentRSS; +# fixed bug capturing author and contributor URL; fixed bug resolving relative +# links in author and contributor URL; fixed bug resolvin relative links in +# generator URL; added support for recognizing RSS 1.0; passed Simon Fell's +# namespace tests, and included them permanently in the test suite with his +# permission; fixed namespace handling under Python 2.1 +#3.0b16 - 2/12/2004 - MAP - fixed support for RSS 0.90 (broken in b15) +#3.0b17 - 2/13/2004 - MAP - determine character encoding as per RFC 3023 +#3.0b18 - 2/17/2004 - MAP - always map description to summary_detail (Andrei); +# use libxml2 (if available) +#3.0b19 - 3/15/2004 - MAP - fixed bug exploding author information when author +# name was in parentheses; removed ultra-problematic mxTidy support; patch to +# workaround crash in PyXML/expat when encountering invalid entities +# (MarkMoraes); support for textinput/textInput +#3.0b20 - 4/7/2004 - MAP - added CDF support +#3.0b21 - 4/14/2004 - MAP - added Hot RSS support +#3.0b22 - 4/19/2004 - MAP - changed 'channel' to 'feed', 'item' to 'entries' in +# results dict; changed results dict to allow getting values with results.key +# as well as results[key]; work around embedded illformed HTML with half +# a DOCTYPE; work around malformed Content-Type header; if character encoding +# is wrong, try several common ones before falling back to regexes (if this +# works, bozo_exception is set to CharacterEncodingOverride); fixed character +# encoding issues in BaseHTMLProcessor by tracking encoding and converting +# from Unicode to raw strings before feeding data to sgmllib.SGMLParser; +# convert each value in results to Unicode (if possible), even if using +# regex-based parsing +#3.0b23 - 4/21/2004 - MAP - fixed UnicodeDecodeError for feeds that contain +# high-bit characters in attributes in embedded HTML in description (thanks +# Thijs van de Vossen); moved guid, date, and date_parsed to mapped keys in +# FeedParserDict; tweaked FeedParserDict.has_key to return True if asking +# about a mapped key +#3.0fc1 - 4/23/2004 - MAP - made results.entries[0].links[0] and +# results.entries[0].enclosures[0] into FeedParserDict; fixed typo that could +# cause the same encoding to be tried twice (even if it failed the first time); +# fixed DOCTYPE stripping when DOCTYPE contained entity declarations; +# better textinput and image tracking in illformed RSS 1.0 feeds +#3.0fc2 - 5/10/2004 - MAP - added and passed Sam's amp tests; added and passed +# my blink tag tests +#3.0fc3 - 6/18/2004 - MAP - fixed bug in _changeEncodingDeclaration that +# failed to parse utf-16 encoded feeds; made source into a FeedParserDict; +# duplicate admin:generatorAgent/@rdf:resource in generator_detail.url; +# added support for image; refactored parse() fallback logic to try other +# encodings if SAX parsing fails (previously it would only try other encodings +# if re-encoding failed); remove unichr madness in normalize_attrs now that +# we're properly tracking encoding in and out of BaseHTMLProcessor; set +# feed.language from root-level xml:lang; set entry.id from rdf:about; +# send Accept header +#3.0 - 6/21/2004 - MAP - don't try iso-8859-1 (can't distinguish between +# iso-8859-1 and windows-1252 anyway, and most incorrectly marked feeds are +# windows-1252); fixed regression that could cause the same encoding to be +# tried twice (even if it failed the first time) +#3.0.1 - 6/22/2004 - MAP - default to us-ascii for all text/* content types; +# recover from malformed content-type header parameter with no equals sign +# ('text/xml; charset:iso-8859-1') +#3.1 - 6/28/2004 - MAP - added and passed tests for converting HTML entities +# to Unicode equivalents in illformed feeds (aaronsw); added and +# passed tests for converting character entities to Unicode equivalents +# in illformed feeds (aaronsw); test for valid parsers when setting +# XML_AVAILABLE; make version and encoding available when server returns +# a 304; add handlers parameter to pass arbitrary urllib2 handlers (like +# digest auth or proxy support); add code to parse username/password +# out of url and send as basic authentication; expose downloading-related +# exceptions in bozo_exception (aaronsw); added __contains__ method to +# FeedParserDict (aaronsw); added publisher_detail (aaronsw) +#3.2 - 7/3/2004 - MAP - use cjkcodecs and iconv_codec if available; always +# convert feed to UTF-8 before passing to XML parser; completely revamped +# logic for determining character encoding and attempting XML parsing +# (much faster); increased default timeout to 20 seconds; test for presence +# of Location header on redirects; added tests for many alternate character +# encodings; support various EBCDIC encodings; support UTF-16BE and +# UTF16-LE with or without a BOM; support UTF-8 with a BOM; support +# UTF-32BE and UTF-32LE with or without a BOM; fixed crashing bug if no +# XML parsers are available; added support for 'Content-encoding: deflate'; +# send blank 'Accept-encoding: ' header if neither gzip nor zlib modules +# are available +#3.3 - 7/15/2004 - MAP - optimize EBCDIC to ASCII conversion; fix obscure +# problem tracking xml:base and xml:lang if element declares it, child +# doesn't, first grandchild redeclares it, and second grandchild doesn't; +# refactored date parsing; defined public registerDateHandler so callers +# can add support for additional date formats at runtime; added support +# for OnBlog, Nate, MSSQL, Greek, and Hungarian dates (ytrewq1); added +# zopeCompatibilityHack() which turns FeedParserDict into a regular +# dictionary, required for Zope compatibility, and also makes command- +# line debugging easier because pprint module formats real dictionaries +# better than dictionary-like objects; added NonXMLContentType exception, +# which is stored in bozo_exception when a feed is served with a non-XML +# media type such as 'text/plain'; respect Content-Language as default +# language if not xml:lang is present; cloud dict is now FeedParserDict; +# generator dict is now FeedParserDict; better tracking of xml:lang, +# including support for xml:lang='' to unset the current language; +# recognize RSS 1.0 feeds even when RSS 1.0 namespace is not the default +# namespace; don't overwrite final status on redirects (scenarios: +# redirecting to a URL that returns 304, redirecting to a URL that +# redirects to another URL with a different type of redirect); add +# support for HTTP 303 redirects +#4.0 - MAP - support for relative URIs in xml:base attribute; fixed +# encoding issue with mxTidy (phopkins); preliminary support for RFC 3229; +# support for Atom 1.0; support for iTunes extensions; new 'tags' for +# categories/keywords/etc. as array of dict +# {'term': term, 'scheme': scheme, 'label': label} to match Atom 1.0 +# terminology; parse RFC 822-style dates with no time; lots of other +# bug fixes +#4.1 - MAP - removed socket timeout; added support for chardet library diff --git a/Products/feedfeeder/i18n/feedfeeder-de.po b/Products/feedfeeder/i18n/feedfeeder-de.po new file mode 100644 index 0000000..ecf2aea --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-de.po @@ -0,0 +1,43 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: 2006-10-19 14:47+0200\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: de\n" +"Language-Name: German\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "Autor(in)" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "Letzte Aktualisierung" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "URLs der Feeds" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "URL des Originals" + +#. Default: "Test view showing the latest items from the feeds" +#: skins/feedfeeder/latest_items.pt +msgid "test_view_title" +msgstr "Die aktuelste einträge der Feeds (nur als Test)" + diff --git a/Products/feedfeeder/i18n/feedfeeder-eu.po b/Products/feedfeeder/i18n/feedfeeder-eu.po new file mode 100644 index 0000000..29da954 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-eu.po @@ -0,0 +1,43 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: 2007-02-16 15:17+0100\n" +"Last-Translator: Mikel Larreategi \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: eu\n" +"Language-Name: Basque\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "Egilea" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "Eguneraketa data" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "Jarioak" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "Loturak" + +#. Default: "Test view showing the latest items from the feeds" +#: skins/feedfeeder/latest_items.pt +msgid "test_view_title" +msgstr "Jarioetako azken elementuak erakusten dituen bista." + diff --git a/Products/feedfeeder/i18n/feedfeeder-fr.po b/Products/feedfeeder/i18n/feedfeeder-fr.po new file mode 100644 index 0000000..ff67525 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-fr.po @@ -0,0 +1,53 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Jul 11 09:13:40 2007\n" +"Last-Translator: Thomas Desvenain \n" +"Language-Team: Ingeniweb \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: fr\n" +"Language-Name: French\n" +"Preferred-Encodings: utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "Auteur du flux" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "Flux Rss rafraîchi" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "Flux" + +#. 'Default transition' +#: content/folder.py +msgid "label_default_transition" +msgstr "Transition par défaut" + +#. "When updating this feed's item the transition selected below will be performed." +#: content/folder.py +msgid "help_default_transition" +msgstr "La transition effectuée lorsque vous mettez à jour ce flux" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "Liens" + +#. Default: "Test view showing the latest items from the feeds" +#: skins/feedfeeder/latest_items.pt +msgid "test_view_title" +msgstr "Vue affichant les derniers items du flux" + diff --git a/Products/feedfeeder/i18n/feedfeeder-nl.po b/Products/feedfeeder/i18n/feedfeeder-nl.po new file mode 100644 index 0000000..c653d27 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-nl.po @@ -0,0 +1,43 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: 2006-10-19 14:47+0200\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: nl\n" +"Language-Name: Dutch\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "Auteur" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "Laatste wijziging" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "URLs van de feeds" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "URL (van het oorspronkelijke item)" + +#. Default: "Test view showing the latest items from the feeds" +#: skins/feedfeeder/latest_items.pt +msgid "test_view_title" +msgstr "Test overzicht: de laatste items uit de feeds" + diff --git a/Products/feedfeeder/i18n/feedfeeder-plone-de.po b/Products/feedfeeder/i18n/feedfeeder-plone-de.po new file mode 100644 index 0000000..1b646f5 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-plone-de.po @@ -0,0 +1,21 @@ +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Thu Jul 20 09:13:40 2006\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n Mirella van Teulingen \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: de\n" +"Language-Name: Deutsch\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: plone\n" + +msgid "Feed folder" +msgstr "Feed Ordner" + +msgid "Feed Item" +msgstr "" \ No newline at end of file diff --git a/Products/feedfeeder/i18n/feedfeeder-plone-eu.po b/Products/feedfeeder/i18n/feedfeeder-plone-eu.po new file mode 100644 index 0000000..3efc59c --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-plone-eu.po @@ -0,0 +1,22 @@ +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: 2007-02-16 15:13+0100\n" +"Last-Translator: Mikel Larreategi \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: eu\n" +"Language-Name: Basque\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: plone\n" + +msgid "Feed folder" +msgstr "Jario karpeta" + +msgid "Feed Item" +msgstr "Jario elementua" + diff --git a/Products/feedfeeder/i18n/feedfeeder-plone-fr.po b/Products/feedfeeder/i18n/feedfeeder-plone-fr.po new file mode 100644 index 0000000..16d0f49 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-plone-fr.po @@ -0,0 +1,25 @@ +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Jul 11 09:13:40 2007\n" +"Last-Translator: Thomas Desvenain \n" +"Language-Team: Ingeniweb \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: fr\n" +"Language-Name: French\n" +"Preferred-Encodings: utf-8\n" +"Domain: plone\n" + +msgid "Feed folder" +msgstr "Dossier de Flux Rss" + + +msgid "Feed Folder" +msgstr "Dossier de Flux Rss" + +msgid "Feed Item" +msgstr "Element Rss" \ No newline at end of file diff --git a/Products/feedfeeder/i18n/feedfeeder-plone-nl.po b/Products/feedfeeder/i18n/feedfeeder-plone-nl.po new file mode 100644 index 0000000..4de3a53 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-plone-nl.po @@ -0,0 +1,21 @@ +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Thu Jul 20 09:13:40 2006\n" +"Last-Translator: Mirella van Teulingen \n" +"Language-Team: Reinout van Rees \n Mirella van Teulingen \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: nl\n" +"Language-Name: Nederlands\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: plone\n" + +msgid "Feed folder" +msgstr "Feedmap" + +msgid "Feed Item" +msgstr "Feed Item" \ No newline at end of file diff --git a/Products/feedfeeder/i18n/feedfeeder-plone.pot b/Products/feedfeeder/i18n/feedfeeder-plone.pot new file mode 100644 index 0000000..9068fa2 --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder-plone.pot @@ -0,0 +1,21 @@ +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Thu Jul 20 09:13:40 2006\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n Mirella van Teulingen \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: en\n" +"Language-Name: English\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: plone\n" + +msgid "Feed folder" +msgstr "" + +msgid "Feed Item" +msgstr "" \ No newline at end of file diff --git a/Products/feedfeeder/i18n/feedfeeder.pot b/Products/feedfeeder/i18n/feedfeeder.pot new file mode 100644 index 0000000..3fdfe6b --- /dev/null +++ b/Products/feedfeeder/i18n/feedfeeder.pot @@ -0,0 +1,52 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: 2006-10-19 12:46+0000\n" +"PO-Revision-Date: Thu Jul 20 09:13:40 2006\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: en\n" +"Language-Name: English\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "" + +#. Default: "Test view showing the latest items from the feeds" +#: skins/feedfeeder/latest_items.pt +msgid "test_view_title" +msgstr "" + +#. 'Default transition' +#: content/folder.py +msgid "label_default_transition" +msgstr "" + +#. "When updating this feed's item the transition selected below will be performed." +#: content/folder.py +msgid "help_default_transition" +msgstr "" diff --git a/Products/feedfeeder/i18n/generated.pot b/Products/feedfeeder/i18n/generated.pot new file mode 100644 index 0000000..7dbe9e3 --- /dev/null +++ b/Products/feedfeeder/i18n/generated.pot @@ -0,0 +1,38 @@ +# ArchGenXML generated POT File +# Reinout van Rees , 2006. +msgid "" +msgstr "" +"Project-Id-Version: feedfeeder\n" +"POT-Creation-Date: Thu Jul 20 09:13:40 2006\n" +"PO-Revision-Date: Thu Jul 20 09:13:40 2006\n" +"Last-Translator: Reinout van Rees \n" +"Language-Team: Reinout van Rees \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0\n" +"Language-Code: en\n" +"Language-Name: English\n" +"Preferred-Encodings: latin1 utf-8\n" +"Domain: feedfeeder\n" + +#. Default: "Feeditemauthor" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemAuthor" +msgstr "" + +#. Default: "Feeditemupdated" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_feedItemUpdated" +msgstr "" + +#. Default: "Feeds" +#: content/FeedfeederFolder.py +msgid "feedfeeder_label_feeds" +msgstr "" + +#. Default: "Links" +#: content/FeedFeederItem.py +msgid "feedfeeder_label_link" +msgstr "" + diff --git a/Products/feedfeeder/interfaces/__init__.py b/Products/feedfeeder/interfaces/__init__.py new file mode 100644 index 0000000..a4855b7 --- /dev/null +++ b/Products/feedfeeder/interfaces/__init__.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- + +##code-section init-module-header #fill in your manual code here +##/code-section init-module-header + + +# Subpackages +# Additional + +# Classes +import container +import consumer +import item +import contenthandler +import folderview + +##code-section init-module-footer #fill in your manual code here +##/code-section init-module-footer + diff --git a/Products/feedfeeder/interfaces/consumer.py b/Products/feedfeeder/interfaces/consumer.py new file mode 100644 index 0000000..d5733e5 --- /dev/null +++ b/Products/feedfeeder/interfaces/consumer.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- + +##code-section module-header #fill in your manual code here +##/code-section module-header + + + + +from zope import interface + +class IFeedConsumer(interface.Interface): + ''' ''' + + ##code-section class-header_IFeedConsumer #fill in your manual code here + ##/code-section class-header_IFeedConsumer + + + + + def retrieveFeedItems(container): + """ + + """ + + + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + + + diff --git a/Products/feedfeeder/interfaces/container.py b/Products/feedfeeder/interfaces/container.py new file mode 100644 index 0000000..5df7edc --- /dev/null +++ b/Products/feedfeeder/interfaces/container.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +##code-section module-header #fill in your manual code here +##/code-section module-header + + + + +from zope import interface + +class IFeedsContainer(interface.Interface): + ''' ''' + + ##code-section class-header_IFeedsContainer #fill in your manual code here + ##/code-section class-header_IFeedsContainer + + + + + def getFeeds(): + """ + + """ + + + + def addItem(id): + """ + + """ + + + + def replaceItem(id): + """ + + """ + + + + def getItem(id): + """ + + """ + + + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + + + diff --git a/Products/feedfeeder/interfaces/contenthandler.py b/Products/feedfeeder/interfaces/contenthandler.py new file mode 100644 index 0000000..33b36b8 --- /dev/null +++ b/Products/feedfeeder/interfaces/contenthandler.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- + +##code-section module-header #fill in your manual code here +##/code-section module-header + + + + +from zope import interface + +class IFeedItemContentHandler(interface.Interface): + ''' ''' + + ##code-section class-header_IFeedItemContentHandler #fill in your manual code here + ##/code-section class-header_IFeedItemContentHandler + + + + + def apply(contentNode): + """ + + """ + + + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + + + diff --git a/Products/feedfeeder/interfaces/folderview.py b/Products/feedfeeder/interfaces/folderview.py new file mode 100644 index 0000000..2a3770f --- /dev/null +++ b/Products/feedfeeder/interfaces/folderview.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- + +##code-section module-header #fill in your manual code here +##/code-section module-header + + + + +from zope import interface + +class IFeedfeederFolderView(interface.Interface): + ''' ''' + + ##code-section class-header_IFeedfeederFolderView #fill in your manual code here + ##/code-section class-header_IFeedfeederFolderView + + + + + def item_list(): + """ + + """ + + + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + + + diff --git a/Products/feedfeeder/interfaces/item.py b/Products/feedfeeder/interfaces/item.py new file mode 100644 index 0000000..1209d84 --- /dev/null +++ b/Products/feedfeeder/interfaces/item.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +from zope import interface +try: + from zope.lifecycleevent import IObjectModifiedEvent +except ImportError: + # BBB for Zope 2.9 + from zope.app.event.interfaces import IObjectModifiedEvent + + +class IFeedItem(interface.Interface): + """ + """ + + def addEnclosure(id): + """Add an enclosure. + """ + +class IFeedItemConsumedEvent(IObjectModifiedEvent): + """Intended to be fired after a new feed item has been successfully + consumed. + """ diff --git a/Products/feedfeeder/profiles/default/actions.xml b/Products/feedfeeder/profiles/default/actions.xml new file mode 100644 index 0000000..b3fab37 --- /dev/null +++ b/Products/feedfeeder/profiles/default/actions.xml @@ -0,0 +1,16 @@ + + + + + Update Feed Items + + string:${object_url}/update_feed_items + + object/@@is_feedcontainer + + + + True + + + diff --git a/Products/feedfeeder/profiles/default/catalog.xml b/Products/feedfeeder/profiles/default/catalog.xml new file mode 100644 index 0000000..6aa64f4 --- /dev/null +++ b/Products/feedfeeder/profiles/default/catalog.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Products/feedfeeder/profiles/default/factorytool.xml b/Products/feedfeeder/profiles/default/factorytool.xml new file mode 100644 index 0000000..a71b842 --- /dev/null +++ b/Products/feedfeeder/profiles/default/factorytool.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Products/feedfeeder/profiles/default/feedfeeder_various.txt b/Products/feedfeeder/profiles/default/feedfeeder_various.txt new file mode 100644 index 0000000..7305a90 --- /dev/null +++ b/Products/feedfeeder/profiles/default/feedfeeder_various.txt @@ -0,0 +1 @@ +The feedfeeder_various step is run if this file is present in the profile. diff --git a/Products/feedfeeder/profiles/default/import_steps.xml b/Products/feedfeeder/profiles/default/import_steps.xml new file mode 100644 index 0000000..6832381 --- /dev/null +++ b/Products/feedfeeder/profiles/default/import_steps.xml @@ -0,0 +1,9 @@ + + + + Import steps that couldn't be mapped to other handlers. + + diff --git a/Products/feedfeeder/profiles/default/propertiestool.xml b/Products/feedfeeder/profiles/default/propertiestool.xml new file mode 100644 index 0000000..aed0390 --- /dev/null +++ b/Products/feedfeeder/profiles/default/propertiestool.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Products/feedfeeder/profiles/default/skins.xml b/Products/feedfeeder/profiles/default/skins.xml new file mode 100644 index 0000000..298407d --- /dev/null +++ b/Products/feedfeeder/profiles/default/skins.xml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/Products/feedfeeder/profiles/default/types.xml b/Products/feedfeeder/profiles/default/types.xml new file mode 100644 index 0000000..32f7547 --- /dev/null +++ b/Products/feedfeeder/profiles/default/types.xml @@ -0,0 +1,7 @@ + + + Controls the available content types in your portal + + + diff --git a/Products/feedfeeder/profiles/default/types/FeedFeederItem.xml b/Products/feedfeeder/profiles/default/types/FeedFeederItem.xml new file mode 100644 index 0000000..5ddc964 --- /dev/null +++ b/Products/feedfeeder/profiles/default/types/FeedFeederItem.xml @@ -0,0 +1,55 @@ + + + Feed Item + + + folder_icon.gif + FeedFeederItem + feedfeeder + addFeedFeederItem + feed-item.html + False + True + + + + False + feed-item.html + + + + False + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Products/feedfeeder/profiles/default/types/FeedfeederFolder.xml b/Products/feedfeeder/profiles/default/types/FeedfeederFolder.xml new file mode 100644 index 0000000..7c476bb --- /dev/null +++ b/Products/feedfeeder/profiles/default/types/FeedfeederFolder.xml @@ -0,0 +1,60 @@ + + + Feed Folder + + + folder_icon.gif + FeedfeederFolder + feedfeeder + addFeedfeederFolder + feed-folder.html + True + True + + + + False + feed-folder.html + + + + False + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Products/feedfeeder/rebuild_i18n.sh b/Products/feedfeeder/rebuild_i18n.sh new file mode 100755 index 0000000..15071f0 --- /dev/null +++ b/Products/feedfeeder/rebuild_i18n.sh @@ -0,0 +1,14 @@ +#!/bin/sh +PRODUCTNAME=feedfeeder +I18NDOMAIN=$PRODUCTNAME + +# Synchronise the .pot with the templates. +# Also merge it with generated.pot, which includes the items +# from schema.py +i18ndude rebuild-pot --pot i18n/${PRODUCTNAME}.pot --create ${I18NDOMAIN} --merge i18n/generated.pot skins/${PRODUCTNAME} + +# Synchronise the resulting .pot with the .po files +i18ndude sync --pot i18n/${PRODUCTNAME}.pot i18n/${PRODUCTNAME}*.po + +# Synchronise the plone*.po files with the hand-made plone-PRODUCTNAME.pot +#i18ndude sync --pot i18n/plone-${PRODUCTNAME}.pot i18n/plone*.po diff --git a/Products/feedfeeder/setuphandlers.py b/Products/feedfeeder/setuphandlers.py new file mode 100644 index 0000000..07ebb46 --- /dev/null +++ b/Products/feedfeeder/setuphandlers.py @@ -0,0 +1,34 @@ +from Products.CMFCore.utils import getToolByName + + +def add_indexes(site, logger): + """Add indexes. + + I have *had* it with catalog.xml for indexes. If we have to add + some code here to reindex our indexes after catalog.xml has been + imported, we might as well add some code instead to only add them + when they are not there yet. + + """ + catalog = getToolByName(site, 'portal_catalog') + indexes = catalog.indexes() + + idx = "getFeedItemUpdated" + if idx not in indexes: + # Setting index_naive_time_as_local to True does not seem + # possible with the 'extra' argument to addIndex, but True is + # the default, so we are happy. + catalog.addIndex(idx, 'DateIndex') + logger.info('Added DateIndex for %s.' % idx) + + +def importVarious(context): + # Only run step if a flag file is present + if context.readDataFile('feedfeeder_various.txt') is None: + return + logger = context.getLogger('feedfeeder') + site = context.getSite() + add_indexes(site, logger) + logger.info('feedfeeder_various step imported') + + diff --git a/Products/feedfeeder/skins/feedfeeder/feed_icon.gif b/Products/feedfeeder/skins/feedfeeder/feed_icon.gif new file mode 100644 index 0000000000000000000000000000000000000000..eba67bad9e43a6f9d0e2429878beb7da0c40c824 GIT binary patch literal 231 zcmVab_Ji}5Ue1cg`>lOSRNKKf1Y6(0?sxZ=q;3J?Wp2_X$9Mg)CR2}dkL3}2uUNdhXt^yJP7Znw6ZyOI006U;6QM>>E literal 0 HcmV?d00001 diff --git a/Products/feedfeeder/skins/feedfeeder/feed_viewlet.pt b/Products/feedfeeder/skins/feedfeeder/feed_viewlet.pt new file mode 100644 index 0000000..6373fec --- /dev/null +++ b/Products/feedfeeder/skins/feedfeeder/feed_viewlet.pt @@ -0,0 +1,12 @@ + + +
+ Title +
+ +
+ + +
diff --git a/Products/feedfeeder/skins/feedfeeder/latest_items.pt b/Products/feedfeeder/skins/feedfeeder/latest_items.pt new file mode 100644 index 0000000..f167288 --- /dev/null +++ b/Products/feedfeeder/skins/feedfeeder/latest_items.pt @@ -0,0 +1,21 @@ + + + +

+ Test view showing the latest items from the feeds +

+ + +

+

+ +

+ + + + + diff --git a/Products/feedfeeder/skins/feedfeeder/readme.txt b/Products/feedfeeder/skins/feedfeeder/readme.txt new file mode 100644 index 0000000..610d6f6 --- /dev/null +++ b/Products/feedfeeder/skins/feedfeeder/readme.txt @@ -0,0 +1,8 @@ +Directory 'skins/feedfeeder': + +Put your templates, css and javascript files in here. When first +installed, this skin layer is added to the plone skin. It is added +right below the 'custom' layer. Later, other products can move it a +little bit down, but it'll always be above the plone skin layers. So: +you can use it to overwrite plone stuff. + diff --git a/Products/feedfeeder/tests/MainTestCase.py b/Products/feedfeeder/tests/MainTestCase.py new file mode 100644 index 0000000..1f98c23 --- /dev/null +++ b/Products/feedfeeder/tests/MainTestCase.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# +# Base TestCase for feedfeeder +# + +import os, sys, code +if __name__ == '__main__': + execfile(os.path.join(sys.path[0], 'framework.py')) + +##code-section module-header #fill in your manual code here +##/code-section module-header + +from Testing import ZopeTestCase +from Products.PloneTestCase import PloneTestCase +from Products.feedfeeder.config import HAS_PLONE21 +from Products.feedfeeder.config import PRODUCT_DEPENDENCIES +from Products.feedfeeder.config import DEPENDENCIES + +# Add common dependencies +if not HAS_PLONE21: + DEPENDENCIES.append('Archetypes') + PRODUCT_DEPENDENCIES.append('MimetypesRegistry') + PRODUCT_DEPENDENCIES.append('PortalTransforms') +PRODUCT_DEPENDENCIES.append('feedfeeder') + +# Install all (product-) dependencies, install them too +for dependency in PRODUCT_DEPENDENCIES + DEPENDENCIES: + ZopeTestCase.installProduct(dependency) + +ZopeTestCase.installProduct('feedfeeder') + +PRODUCTS = list() +PRODUCTS += DEPENDENCIES +PRODUCTS.append('feedfeeder') + +testcase = PloneTestCase.PloneTestCase +##code-section module-before-plone-site-setup #fill in your manual code here +##/code-section module-before-plone-site-setup + +PloneTestCase.setupPloneSite(products=PRODUCTS) + +class MainTestCase(testcase): + """Base TestCase for feedfeeder.""" + + ##code-section class-header_MainTestCase #fill in your manual code here + ##/code-section class-header_MainTestCase + + # Commented out for now, it gets blasted at the moment anyway. + # Place it in the protected section if you need it. + #def afterSetup(self): + # """ + # """ + # pass + + def interact(self, locals=None): + """Provides an interactive shell aka console inside your testcase. + + It looks exact like in a doctestcase and you can copy and paste + code from the shell into your doctest. The locals in the testcase are + available, becasue you are in the testcase. + + In your testcase or doctest you can invoke the shell at any point by + calling:: + + >>> self.interact( locals() ) + + locals -- passed to InteractiveInterpreter.__init__() + """ + savestdout = sys.stdout + sys.stdout = sys.stderr + sys.stderr.write('='*70) + console = code.InteractiveConsole(locals) + console.interact(""" +ZopeTestCase Interactive Console +(c) BlueDynamics Alliance, Austria - 2005 + +Note: You have the same locals available as in your test-case. +""") + sys.stdout.write('\nend of ZopeTestCase Interactive Console session\n') + sys.stdout.write('='*70+'\n') + sys.stdout = savestdout + + +def test_suite(): + from unittest import TestSuite, makeSuite + suite = TestSuite() + suite.addTest(makeSuite(MainTestCase)) + return suite + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + +if __name__ == '__main__': + framework() + + diff --git a/Products/feedfeeder/tests/__init__.py b/Products/feedfeeder/tests/__init__.py new file mode 100644 index 0000000..e090ee5 --- /dev/null +++ b/Products/feedfeeder/tests/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- + +##code-section init-module-header #fill in your manual code here +##/code-section init-module-header + + +# Subpackages +# Additional + +# Classes + +##code-section init-module-footer #fill in your manual code here +##/code-section init-module-footer + diff --git a/Products/feedfeeder/tests/framework.py b/Products/feedfeeder/tests/framework.py new file mode 100644 index 0000000..c37c57a --- /dev/null +++ b/Products/feedfeeder/tests/framework.py @@ -0,0 +1,107 @@ +############################################################################## +# +# ZopeTestCase +# +# COPY THIS FILE TO YOUR 'tests' DIRECTORY. +# +# This version of framework.py will use the SOFTWARE_HOME +# environment variable to locate Zope and the Testing package. +# +# If the tests are run in an INSTANCE_HOME installation of Zope, +# Products.__path__ and sys.path with be adjusted to include the +# instance's Products and lib/python directories respectively. +# +# If you explicitly set INSTANCE_HOME prior to running the tests, +# auto-detection is disabled and the specified path will be used +# instead. +# +# If the 'tests' directory contains a custom_zodb.py file, INSTANCE_HOME +# will be adjusted to use it. +# +# If you set the ZEO_INSTANCE_HOME environment variable a ZEO setup +# is assumed, and you can attach to a running ZEO server (via the +# instance's custom_zodb.py). +# +############################################################################## +# +# The following code should be at the top of every test module: +# +# import os, sys +# if __name__ == '__main__': +# execfile(os.path.join(sys.path[0], 'framework.py')) +# +# ...and the following at the bottom: +# +# if __name__ == '__main__': +# framework() +# +############################################################################## + +__version__ = '0.2.3' + +# Save start state +# +__SOFTWARE_HOME = os.environ.get('SOFTWARE_HOME', '') +__INSTANCE_HOME = os.environ.get('INSTANCE_HOME', '') + +if __SOFTWARE_HOME.endswith(os.sep): + __SOFTWARE_HOME = os.path.dirname(__SOFTWARE_HOME) + +if __INSTANCE_HOME.endswith(os.sep): + __INSTANCE_HOME = os.path.dirname(__INSTANCE_HOME) + +# Find and import the Testing package +# +if not sys.modules.has_key('Testing'): + p0 = sys.path[0] + if p0 and __name__ == '__main__': + os.chdir(p0) + p0 = '' + s = __SOFTWARE_HOME + p = d = s and s or os.getcwd() + while d: + if os.path.isdir(os.path.join(p, 'Testing')): + zope_home = os.path.dirname(os.path.dirname(p)) + sys.path[:1] = [p0, p, zope_home] + break + p, d = s and ('','') or os.path.split(p) + else: + print 'Unable to locate Testing package.', + print 'You might need to set SOFTWARE_HOME.' + sys.exit(1) + +import Testing, unittest +execfile(os.path.join(os.path.dirname(Testing.__file__), 'common.py')) + +# Include ZopeTestCase support +# +if 1: # Create a new scope + + p = os.path.join(os.path.dirname(Testing.__file__), 'ZopeTestCase') + + if not os.path.isdir(p): + print 'Unable to locate ZopeTestCase package.', + print 'You might need to install ZopeTestCase.' + sys.exit(1) + + ztc_common = 'ztc_common.py' + ztc_common_global = os.path.join(p, ztc_common) + + f = 0 + if os.path.exists(ztc_common_global): + execfile(ztc_common_global) + f = 1 + if os.path.exists(ztc_common): + execfile(ztc_common) + f = 1 + + if not f: + print 'Unable to locate %s.' % ztc_common + sys.exit(1) + +# Debug +# +print 'SOFTWARE_HOME: %s' % os.environ.get('SOFTWARE_HOME', 'Not set') +print 'INSTANCE_HOME: %s' % os.environ.get('INSTANCE_HOME', 'Not set') +sys.stdout.flush() + diff --git a/Products/feedfeeder/tests/runalltests.py b/Products/feedfeeder/tests/runalltests.py new file mode 100644 index 0000000..99f7541 --- /dev/null +++ b/Products/feedfeeder/tests/runalltests.py @@ -0,0 +1,29 @@ +# +# Runs all tests in the current directory +# +# Execute like: +# python runalltests.py +# +# Alternatively use the testrunner: +# python /path/to/Zope/utilities/testrunner.py -qa +# + +import os, sys +if __name__ == '__main__': + execfile(os.path.join(sys.path[0], 'framework.py')) + +import unittest +TestRunner = unittest.TextTestRunner +suite = unittest.TestSuite() + +tests = os.listdir(os.curdir) +tests = [n[:-3] for n in tests if n.startswith('test') and n.endswith('.py')] + +for test in tests: + m = __import__(test) + if hasattr(m, 'test_suite'): + suite.addTest(m.test_suite()) + +if __name__ == '__main__': + TestRunner().run(suite) + diff --git a/Products/feedfeeder/tests/samples/examplefeed.xml b/Products/feedfeeder/tests/samples/examplefeed.xml new file mode 100644 index 0000000..865226b --- /dev/null +++ b/Products/feedfeeder/tests/samples/examplefeed.xml @@ -0,0 +1,61 @@ + + + + Philips Research Eindhoven News + General news of Philips Research Eindhoven - for internal use only. + + + 2006-07-24T11:30:15Z + http://resweb2.natlab.research.philips.com/NlwwNews/rss/NlwwNewsAtom.xml + + Philips Nieuws 24 juli + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6103&chk=6573 + + 2006-07-21T12:00:00Z + Miriam Mobach + + + PR-Europe News, July 21 + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6101&chk=144024 + + 2006-07-21T12:00:00Z + Nelleke Tops + + + PR-Europa Nieuws, 21 juli + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6100&chk=232342 + + 2006-07-21T12:00:00Z + Nelleke Tops + + + Bicycle service closed 17 July-7 August + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6092&chk=51342 + +
+
+

Bicycle service closed 17 July-7 August

+ +

The bicycle service in building WD-k-116 will be closed from 17 July until 7 August.

+ +
Fietsservice gesloten van 17 juli-7 augustus
+ +

De fietsservice in gebouw WD-k-116 is gesloten van 17 juli tot 7 augustus.

+ +

Louis Stravens,
+tel. 44499

+
+ +
+
+ 2006-07-18T12:00:00Z + Miriam Mobach +
+ + Philips Nieuws, 17 juli + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6090&chk=438107 + + 2006-07-17T12:00:00Z + Nelleke Tops + +
diff --git a/Products/feedfeeder/tests/samples/samplefeed1.xml b/Products/feedfeeder/tests/samples/samplefeed1.xml new file mode 100644 index 0000000..7471579 --- /dev/null +++ b/Products/feedfeeder/tests/samples/samplefeed1.xml @@ -0,0 +1,53 @@ + + + Philips Research Eindhoven News (Special) + General news of Philips Research Eindhoven - for internal use only. + 2006-07-24T11:30:15Z + http://resweb2.natlab.research.philips.com/NlwwNews/rss/NlwwNewsAtom.xml + + Philips Nieuws 24 juli + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6103&chk=6573 + + 2006-07-21T12:00:00Z + This is a sample summary + Miriam Mobach + + + PR-Europa Nieuws, 21 juli + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6100&chk=232342 + + 2006-07-21T12:00:00Z + Nelleke Tops + + + Bicycle service closed 17 July-7 August + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6092&chk=51342 + + + + 2006-07-18T12:00:00Z + Miriam Mobach + + + Party! + http://myplace.com + + + +
+woo hoo, a party! +
+
+ 2006-07-18T12:00:00Z + Party on the roof of the Mediterranean Inn + Rocky Burt +
+
diff --git a/Products/feedfeeder/tests/samples/samplefeed2.xml b/Products/feedfeeder/tests/samples/samplefeed2.xml new file mode 100644 index 0000000..d1bdeb7 --- /dev/null +++ b/Products/feedfeeder/tests/samples/samplefeed2.xml @@ -0,0 +1,29 @@ + + + Philips Research Eindhoven News + General news of Philips Research Eindhoven - for internal use only. + 2006-07-24T11:30:15Z + http://resweb2.natlab.research.philips.com/NlwwNews/rss/NlwwNewsAtom.xml + + Bicycle service closed 17 July-7 August + http://resweb2.natlab.research.philips.com/NlwwNews/NlwwViewNews.asp?NewsId=6092&chk=51342 + +
+hello bar +
+
+ 2006-08-18T12:00:00Z + Miriam Mobach +
+ + Party! + http://myplace.com + +
+boo, I hate parties +
+
+ 2006-05-18T12:00:00Z + Rocky Burt +
+
diff --git a/Products/feedfeeder/tests/samples/samplefeed3.xml b/Products/feedfeeder/tests/samples/samplefeed3.xml new file mode 100644 index 0000000..49ab08f --- /dev/null +++ b/Products/feedfeeder/tests/samples/samplefeed3.xml @@ -0,0 +1,19 @@ + + + Philips Research Eindhoven News + General news of Philips Research Eindhoven - for internal use only. + 2006-07-24T11:30:15Z + http://resweb2.natlab.research.philips.com/NlwwNews/rss/NlwwNewsAtom.xml + + Thesis defence: 15 January 2007 15:00 + vanrees1 + +
+Great news: a final thesis defence date! +
+
+ + 2006-08-18T12:00:00Z + Reinout van Rees +
+
diff --git a/Products/feedfeeder/tests/samples/samplefeed4.xml b/Products/feedfeeder/tests/samples/samplefeed4.xml new file mode 100644 index 0000000..ce40e85 --- /dev/null +++ b/Products/feedfeeder/tests/samples/samplefeed4.xml @@ -0,0 +1,19 @@ + + + Philips Research Eindhoven News + General news of Philips Research Eindhoven - for internal use only. + 2007-07-30T23:32:36Z + http://resweb2.natlab.research.philips.com/NlwwNews/rss/NlwwNewsAtom.xml + + An entry that has never been updated! + oldnews + +
+ Old news: Some posts are never updated. +
+
+ + 2007-07-30T23:32:36Z + Reinout van Rees +
+
diff --git a/Products/feedfeeder/tests/samples/test1.pdf b/Products/feedfeeder/tests/samples/test1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d5f831cc9fd1025bca0b91e3f74d81033eef7aaf GIT binary patch literal 1000 ScmXpo7zLvtFd72GJp=%)8oPl2 literal 0 HcmV?d00001 diff --git a/Products/feedfeeder/tests/samples/test2.doc b/Products/feedfeeder/tests/samples/test2.doc new file mode 100644 index 0000000..4901727 --- /dev/null +++ b/Products/feedfeeder/tests/samples/test2.doc @@ -0,0 +1 @@ +00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 \ No newline at end of file diff --git a/Products/feedfeeder/tests/samples/test3.xls b/Products/feedfeeder/tests/samples/test3.xls new file mode 100644 index 0000000..23b5f8f --- /dev/null +++ b/Products/feedfeeder/tests/samples/test3.xls @@ -0,0 +1 @@ +000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 \ No newline at end of file diff --git a/Products/feedfeeder/tests/testDocIntegrationTests.py b/Products/feedfeeder/tests/testDocIntegrationTests.py new file mode 100644 index 0000000..b7d40ea --- /dev/null +++ b/Products/feedfeeder/tests/testDocIntegrationTests.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +import os +import sys +import unittest +from Testing import ZopeTestCase +from Products.feedfeeder.tests.MainTestCase import MainTestCase + +try: + from Products.PloneTestCase.layer import PloneSite as test_layer +except: + test_layer = None + +if __name__ == '__main__': + execfile(os.path.join(sys.path[0], 'framework.py')) + +def test_suite(): + from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite + + suite = ZopeDocFileSuite('feedfeeder-integration.txt', + package='Products.feedfeeder.doc', + test_class=MainTestCase) + if test_layer is not None: + suite.layer = test_layer + + return unittest.TestSuite((suite,)) + +if __name__ == '__main__': + framework() + + diff --git a/Products/feedfeeder/tests/testDocUnitTests.py b/Products/feedfeeder/tests/testDocUnitTests.py new file mode 100644 index 0000000..8a76c9a --- /dev/null +++ b/Products/feedfeeder/tests/testDocUnitTests.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +##code-section module-header #fill in your manual code here +import unittest +from zope import component +from zope.component import testing +from zope.testing import doctestunit +##/code-section module-header + + + +class testDocUnitTests: + """ + """ + + ##code-section class-header_testDocUnitTests #fill in your manual code here + ##/code-section class-header_testDocUnitTests + + + def testDummy(self): + self.failIf(True) + + + def afterSetUp(self): + """ + """ + pass + +##code-section module-footer #fill in your manual code here +def setUp(test): + testing.setUp(test) + +def tearDown(test): + testing.tearDown(test) + +def test_suite(): + return unittest.TestSuite(( + doctestunit.DocFileSuite('feedconsuming.txt', + package='Products.feedfeeder.doc', + setUp=setUp, + tearDown=testing.tearDown), + )) +##/code-section module-footer + + diff --git a/Products/feedfeeder/tests/testFeedfeederFolder.py b/Products/feedfeeder/tests/testFeedfeederFolder.py new file mode 100644 index 0000000..551b534 --- /dev/null +++ b/Products/feedfeeder/tests/testFeedfeederFolder.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +import os, sys +if __name__ == '__main__': + execfile(os.path.join(sys.path[0], 'framework.py')) + +##code-section module-header #fill in your manual code here +##/code-section module-header + +# +# Test-cases for class(es) FeedfeederFolder +# + +from Testing import ZopeTestCase +from Products.feedfeeder.config import * +from Products.feedfeeder.tests.MainTestCase import MainTestCase + +# Import the tested classes +from Products.feedfeeder.content.folder import FeedfeederFolder + +##code-section module-beforeclass #fill in your manual code here +##/code-section module-beforeclass + + +class testFeedfeederFolder(MainTestCase): + """Test-cases for class(es) FeedfeederFolder.""" + + ##code-section class-header_testFeedfeederFolder #fill in your manual code here + ##/code-section class-header_testFeedfeederFolder + + def afterSetUp(self): + pass + + # from class FeedfeederFolder: + def test_update_feed_items(self): + pass + + # from class FeedfeederFolder: + def test_view(self): + pass + + # Manually created methods + + def test_addRetrievedFeedItem(self): + pass + + def test_downloadEntries(self): + pass + + +def test_suite(): + from unittest import TestSuite, makeSuite + suite = TestSuite() + suite.addTest(makeSuite(testFeedfeederFolder)) + return suite + +##code-section module-footer #fill in your manual code here +##/code-section module-footer + +if __name__ == '__main__': + framework() + + diff --git a/Products/feedfeeder/utilities.py b/Products/feedfeeder/utilities.py new file mode 100644 index 0000000..4cf0c7b --- /dev/null +++ b/Products/feedfeeder/utilities.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +##code-section module-header #fill in your manual code here +import urllib2 +import os +import md5 +import tempfile +from xml.dom import minidom +import feedparser +from zope import component +from zope import event +from DateTime import DateTime +from Products.feedfeeder.interfaces.container import IFeedsContainer +from Products.feedfeeder.interfaces.contenthandler import IFeedItemContentHandler +from Products.feedfeeder.events import FeedItemConsumedEvent +##/code-section module-header + +from Products.feedfeeder.interfaces.consumer import IFeedConsumer +from zope import interface + +class FeedConsumer: + """ + """ + # zope3 interfaces + interface.implements(IFeedConsumer) + + ##code-section class-header_FeedConsumer #fill in your manual code here + ##/code-section class-header_FeedConsumer + + def retrieveFeedItems(self, container): + feedContainer = IFeedsContainer(container) + for url in feedContainer.getFeeds(): + self._retrieveSingleFeed(feedContainer, url) + + + def tryRenamingEnclosure(self, enclosure, feeditem): + newId = enclosure.Title() + for x in range(1, 10): + if newId not in feeditem.objectIds(): + try: + feeditem.manage_renameObject(enclosure.getId(), + newId) + break + except: + pass + newId = '%i_%s' % (x, enclosure.Title()) + + + def _retrieveSingleFeed(self, feedContainer, url): + # feedparser doesn't understand proper file: url's + if url.startswith('file://'): + url = url[7:] + if not os.path.exists(url): + raise IOError("Couldn't locate %r" % url) + parsed = feedparser.parse(url) + for entry in parsed.entries: + try: + sig = md5.new(entry.id) + except AttributeError: + """ sometimes, + gruik rss providers send items without guid element """ + sig = md5.new(entry.link) + id = sig.hexdigest() + + updated = entry.get('updated') + published = entry.get('published') + + if updated == '': + # property may be blank if never item has never + # been updated -- use published date + updated = published + + if updated is None: + continue + + updated = DateTime(updated) + + prev = feedContainer.getItem(id) + + if prev is None: + # Completely new item, add it. + addItem = feedContainer.addItem + elif updated > prev.getFeedItemUpdated(): + # Refreshed item, replace it. + addItem = feedContainer.replaceItem + else: + # Not new, not refreshed: let it be, laddy. + continue + + obj = addItem(id) + + linkDict = getattr(entry, 'link', None) + if linkDict: + # Hey, that's not a dict at all; at least not in my test. + #link = linkDict['href'] + link = linkDict + else: + linkDict = getattr(entry, 'links', [{'href': ''}])[0] + link = linkDict['href'] + + summary = getattr(entry, 'summary' , '') + + if published is not None: + published = DateTime(published) + obj.setEffectiveDate(published) + obj.update(id=id, + title=entry.title, + description=summary, + feedItemAuthor=getattr(entry, 'author', ''), + feedItemUpdated=updated, + link=link, + feedTitle=parsed['feed'].get('title', ''), + ) + if hasattr(entry, 'content'): + content = entry.content[0] + if content['type'] in ('text/xhtml', 'application/xhtml+xml'): + # Warning: minidom.parseString needs a byte + # string, not a unicode one, so we need to + # encode it first. + # http://evanjones.ca/python-utf8.html + try: + doc = minidom.parseString(content['value'].encode('utf-8')) + except: + # Might be an ExpatError, but that is + # somewhere in a .so file, so we cannot + # specifically catch only that error. + continue + if len(doc.childNodes) > 0 and doc.firstChild.hasAttributes(): + handler = None + top = doc.firstChild + cls = top.getAttribute('class') + if cls: + handler = component.queryAdapter(obj, + IFeedItemContentHandler, + name=cls) + if handler is None: + handler = component.queryAdapter(obj, + IFeedItemContentHandler) + + if handler is None: + obj.update(text=content['value']) + else: + handler.apply(top) + # Grab the first non-
node and treat + # that as the content. + actualContent = None + for node in top.childNodes: + if node.nodeName == 'div': + actualContent = node.toxml() + obj.update(text=actualContent) + break + else: + obj.update(text=content['value']) + else: + obj.update(text=content['value']) + + if hasattr(entry, 'links'): + enclosures = [x for x in entry.links if x.rel == 'enclosure'] + real_enclosures = [x for x in enclosures if + not self.isHTMLEnclosure(x)] + + for link in real_enclosures: + enclosureSig = md5.new(link.href) + enclosureId = enclosureSig.hexdigest() + enclosure = obj.addEnclosure(enclosureId) + enclosure.update(title=enclosureId) + updateWithRemoteFile(enclosure, link) + if enclosure.Title() != enclosure.getId(): + self.tryRenamingEnclosure(enclosure, obj) + # At this moment in time, the + # rename-after-creation magic might have changed + # the ID of the file. So we recatalog the object. + obj.reindexObject() + + if obj is not None: + event.notify(FeedItemConsumedEvent(obj)) + + def isHTMLEnclosure(self, enclosure): + return enclosure.type == u'text/html' + + +##code-section module-footer #fill in your manual code here +import re +RE_FILENAME = re.compile('filename *= *(.*)') + +def updateWithRemoteFile(obj, link): + file = tempfile.TemporaryFile('w+b') + try: + remote = urllib2.urlopen(link.href.encode('utf-8')) + info = remote.info() + filename = None + if link.href.startswith('file:'): + pos = link.href.rfind('/') + if pos > -1: + filename = link.href[pos+1:] + else: + filename = link.href[5:] + + disp = info.get('Content-Disposition', None) + if disp is not None: + m = RE_FILENAME.search(disp) + if m is not None: + filename = m.group(1).strip() + + if filename is not None: + obj.update(title=filename) + + max = 2048 + sz = max + while sz == max: + buffer = remote.read(max) + sz = len(buffer) + if sz > 0: + file.write(buffer) + + file.flush() + file.seek(0) + obj.update_data(file, link.type) + file.close() + except urllib2.URLError, e: + # well, if we cannot retrieve the data, the file object will + # remain empty + pass + except OSError, e: + # well, if we cannot retrieve the data, the file object will + # remain empty + pass + +##/code-section module-footer + + diff --git a/Products/feedfeeder/version.txt b/Products/feedfeeder/version.txt new file mode 100644 index 0000000..0c4c9fc --- /dev/null +++ b/Products/feedfeeder/version.txt @@ -0,0 +1 @@ +1.0beta4 (unreleased) diff --git a/docs/INSTALL.txt b/docs/INSTALL.txt new file mode 100644 index 0000000..3a70db4 --- /dev/null +++ b/docs/INSTALL.txt @@ -0,0 +1,35 @@ +Products.feedfeeder Installation +========================== + +To install Products.feedfeeder into the global Python environment (or +a workingenv), using a traditional Zope 2 instance, you can do this: + + * When you're reading this you have probably already run + ``easy_install Products.feedfeeder``. Find out how to install setuptools + (and EasyInstall) here: + http://peak.telecommunity.com/DevCenter/EasyInstall + + * Create a file called ``Products.feedfeeder-configure.zcml`` in the + ``/path/to/instance/etc/package-includes`` directory. The file + should only contain this:: + + + + +Alternatively, if you are using zc.buildout and the plone.recipe.zope2instance +recipe to manage your project, you can do this: + + * Add ``Products.feedfeeder`` to the list of eggs to install, e.g.: + + [buildout] + ... + eggs = + ... + Products.feedfeeder + + * Re-run buildout, e.g. with: + + $ ./bin/buildout + +You can skip the ZCML slug if you are going to explicitly include the package +from another package's configure.zcml file. diff --git a/docs/LICENSE.GPL b/docs/LICENSE.GPL new file mode 100644 index 0000000..ba9543b --- /dev/null +++ b/docs/LICENSE.GPL @@ -0,0 +1,222 @@ + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/docs/LICENSE.txt b/docs/LICENSE.txt new file mode 100644 index 0000000..dafff05 --- /dev/null +++ b/docs/LICENSE.txt @@ -0,0 +1,16 @@ + Products.feedfeeder is copyright (c) 2006-2008 Zest Software + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, + MA 02111-1307 USA. diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..b5cbb1b --- /dev/null +++ b/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages +import os + +version = '1.0beta4' + +readme = open(os.path.join("Products", "feedfeeder", "README.txt")).read() +history = open(os.path.join("Products", "feedfeeder", "HISTORY.txt")).read() + +setup(name='Products.feedfeeder', + version=version, + description="Turn external feed entries into content items", + long_description= readme + "\n" + history, + # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + "Framework :: Plone", + "Programming Language :: Python", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + keywords='', + author='Zest Software', + author_email='m.van.rees@zestsoftware.nl', + url='http://plone.org/products/feedfeeder', + license='GPL', + packages=find_packages(exclude=['ez_setup']), + namespace_packages=['Products'], + include_package_data=True, + zip_safe=False, + install_requires=[ + 'setuptools', + # -*- Extra requirements: -*- + ], + entry_points=""" + # -*- Entry points: -*- + """, + )