PageRenderTime 32ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/wiki/web/widgets/rss/feedparser.py

https://bitbucket.org/nagyv/openerp-addons
Python | 2860 lines | 2744 code | 48 blank | 68 comment | 102 complexity | cd573160f063f3ab691efaa196a575ff MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. """Universal feed parser
  3. Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
  4. Visit http://feedparser.org/ for the latest version
  5. Visit http://feedparser.org/docs/ for the latest documentation
  6. Required: Python 2.1 or later
  7. Recommended: Python 2.3 or later
  8. Recommended: CJKCodecs and iconv_codec <http://cjkpython.i18n.org/>
  9. """
  10. __version__ = "4.1"# + "$Revision: 1.92 $"[11:15] + "-cvs"
  11. __license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved.
  12. Redistribution and use in source and binary forms, with or without modification,
  13. are permitted provided that the following conditions are met:
  14. * Redistributions of source code must retain the above copyright notice,
  15. this list of conditions and the following disclaimer.
  16. * Redistributions in binary form must reproduce the above copyright notice,
  17. this list of conditions and the following disclaimer in the documentation
  18. and/or other materials provided with the distribution.
  19. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  20. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  23. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. POSSIBILITY OF SUCH DAMAGE."""
  30. __author__ = "Mark Pilgrim <http://diveintomark.org/>"
  31. __contributors__ = ["Jason Diamond <http://injektilo.org/>",
  32. "John Beimler <http://john.beimler.org/>",
  33. "Fazal Majid <http://www.majid.info/mylos/weblog/>",
  34. "Aaron Swartz <http://aaronsw.com/>",
  35. "Kevin Marks <http://epeus.blogspot.com/>"]
  36. _debug = 0
  37. # HTTP "User-Agent" header to send to servers when downloading feeds.
  38. # If you are embedding feedparser in a larger application, you should
  39. # change this to your application name and URL.
  40. USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__
  41. # HTTP "Accept" header to send to servers when downloading feeds. If you don't
  42. # want to send an Accept header, set this to None.
  43. 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"
  44. # List of preferred XML parsers, by SAX driver name. These will be tried first,
  45. # but if they're not installed, Python will keep searching through its own list
  46. # of pre-installed parsers until it finds one that supports everything we need.
  47. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  48. # If you want feedparser to automatically run HTML markup through HTML Tidy, set
  49. # this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
  50. # or utidylib <http://utidylib.berlios.de/>.
  51. TIDY_MARKUP = 0
  52. # List of Python interfaces for HTML Tidy, in order of preference. Only useful
  53. # if TIDY_MARKUP = 1
  54. PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
  55. # ---------- required modules (should come with any Python distribution) ----------
  56. import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2
  57. try:
  58. from cStringIO import StringIO as _StringIO
  59. except:
  60. from StringIO import StringIO as _StringIO
  61. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  62. # gzip is included with most Python distributions, but may not be available if you compiled your own
  63. try:
  64. import gzip
  65. except:
  66. gzip = None
  67. try:
  68. import zlib
  69. except:
  70. zlib = None
  71. # If a real XML parser is available, feedparser will attempt to use it. feedparser has
  72. # been tested with the built-in SAX parser, PyXML, and libxml2. On platforms where the
  73. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  74. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  75. try:
  76. import xml.sax
  77. xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  78. from xml.sax.saxutils import escape as _xmlescape
  79. _XML_AVAILABLE = 1
  80. except:
  81. _XML_AVAILABLE = 0
  82. def _xmlescape(data):
  83. data = data.replace('&', '&amp;')
  84. data = data.replace('>', '&gt;')
  85. data = data.replace('<', '&lt;')
  86. return data
  87. # base64 support for Atom feeds that contain embedded binary data
  88. try:
  89. import base64, binascii
  90. except:
  91. base64 = binascii = None
  92. # cjkcodecs and iconv_codec provide support for more character encodings.
  93. # Both are available from http://cjkpython.i18n.org/
  94. try:
  95. import cjkcodecs.aliases
  96. except:
  97. pass
  98. try:
  99. import iconv_codec
  100. except:
  101. pass
  102. # chardet library auto-detects character encodings
  103. # Download from http://chardet.feedparser.org/
  104. try:
  105. import chardet
  106. if _debug:
  107. import chardet.constants
  108. chardet.constants._debug = 1
  109. except:
  110. chardet = None
  111. # ---------- don't touch these ----------
  112. class ThingsNobodyCaresAboutButMe(Exception): pass
  113. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  114. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  115. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  116. class UndeclaredNamespace(Exception): pass
  117. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  118. sgmllib.special = re.compile('<!')
  119. sgmllib.charref = re.compile('&#(x?[0-9A-Fa-f]+)[^0-9A-Fa-f]')
  120. SUPPORTED_VERSIONS = {'': 'unknown',
  121. 'rss090': 'RSS 0.90',
  122. 'rss091n': 'RSS 0.91 (Netscape)',
  123. 'rss091u': 'RSS 0.91 (Userland)',
  124. 'rss092': 'RSS 0.92',
  125. 'rss093': 'RSS 0.93',
  126. 'rss094': 'RSS 0.94',
  127. 'rss20': 'RSS 2.0',
  128. 'rss10': 'RSS 1.0',
  129. 'rss': 'RSS (unknown version)',
  130. 'atom01': 'Atom 0.1',
  131. 'atom02': 'Atom 0.2',
  132. 'atom03': 'Atom 0.3',
  133. 'atom10': 'Atom 1.0',
  134. 'atom': 'Atom (unknown version)',
  135. 'cdf': 'CDF',
  136. 'hotrss': 'Hot RSS'
  137. }
  138. try:
  139. UserDict = dict
  140. except NameError:
  141. # Python 2.1 does not have dict
  142. from UserDict import UserDict
  143. def dict(aList):
  144. rc = {}
  145. for k, v in aList:
  146. rc[k] = v
  147. return rc
  148. class FeedParserDict(UserDict):
  149. keymap = {'channel': 'feed',
  150. 'items': 'entries',
  151. 'guid': 'id',
  152. 'date': 'updated',
  153. 'date_parsed': 'updated_parsed',
  154. 'description': ['subtitle', 'summary'],
  155. 'url': ['href'],
  156. 'modified': 'updated',
  157. 'modified_parsed': 'updated_parsed',
  158. 'issued': 'published',
  159. 'issued_parsed': 'published_parsed',
  160. 'copyright': 'rights',
  161. 'copyright_detail': 'rights_detail',
  162. 'tagline': 'subtitle',
  163. 'tagline_detail': 'subtitle_detail'}
  164. def __getitem__(self, key):
  165. if key == 'category':
  166. return UserDict.__getitem__(self, 'tags')[0]['term']
  167. if key == 'categories':
  168. return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
  169. realkey = self.keymap.get(key, key)
  170. if type(realkey) == types.ListType:
  171. for k in realkey:
  172. if UserDict.has_key(self, k):
  173. return UserDict.__getitem__(self, k)
  174. if UserDict.has_key(self, key):
  175. return UserDict.__getitem__(self, key)
  176. return UserDict.__getitem__(self, realkey)
  177. def __setitem__(self, key, value):
  178. for k in self.keymap.keys():
  179. if key == k:
  180. key = self.keymap[k]
  181. if type(key) == types.ListType:
  182. key = key[0]
  183. return UserDict.__setitem__(self, key, value)
  184. def get(self, key, default=None):
  185. if self.has_key(key):
  186. return self[key]
  187. else:
  188. return default
  189. def setdefault(self, key, value):
  190. if not self.has_key(key):
  191. self[key] = value
  192. return self[key]
  193. def has_key(self, key):
  194. try:
  195. return hasattr(self, key) or UserDict.has_key(self, key)
  196. except AttributeError:
  197. return False
  198. def __getattr__(self, key):
  199. try:
  200. return self.__dict__[key]
  201. except KeyError:
  202. pass
  203. try:
  204. assert not key.startswith('_')
  205. return self.__getitem__(key)
  206. except:
  207. raise AttributeError, "object has no attribute '%s'" % key
  208. def __setattr__(self, key, value):
  209. if key.startswith('_') or key == 'data':
  210. self.__dict__[key] = value
  211. else:
  212. return self.__setitem__(key, value)
  213. def __contains__(self, key):
  214. return self.has_key(key)
  215. def zopeCompatibilityHack():
  216. global FeedParserDict
  217. del FeedParserDict
  218. def FeedParserDict(aDict=None):
  219. rc = {}
  220. if aDict:
  221. rc.update(aDict)
  222. return rc
  223. _ebcdic_to_ascii_map = None
  224. def _ebcdic_to_ascii(s):
  225. global _ebcdic_to_ascii_map
  226. if not _ebcdic_to_ascii_map:
  227. emap = (
  228. 0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  229. 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  230. 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  231. 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  232. 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  233. 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  234. 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  235. 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  236. 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,201,
  237. 202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
  238. 209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
  239. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
  240. 123,65,66,67,68,69,70,71,72,73,232,233,234,235,236,237,
  241. 125,74,75,76,77,78,79,80,81,82,238,239,240,241,242,243,
  242. 92,159,83,84,85,86,87,88,89,90,244,245,246,247,248,249,
  243. 48,49,50,51,52,53,54,55,56,57,250,251,252,253,254,255
  244. )
  245. import string
  246. _ebcdic_to_ascii_map = string.maketrans( \
  247. ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  248. return s.translate(_ebcdic_to_ascii_map)
  249. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  250. def _urljoin(base, uri):
  251. uri = _urifixer.sub(r'\1\3', uri)
  252. return urlparse.urljoin(base, uri)
  253. class _FeedParserMixin:
  254. namespaces = {'': '',
  255. 'http://backend.userland.com/rss': '',
  256. 'http://blogs.law.harvard.edu/tech/rss': '',
  257. 'http://purl.org/rss/1.0/': '',
  258. 'http://my.netscape.com/rdf/simple/0.9/': '',
  259. 'http://example.com/newformat#': '',
  260. 'http://example.com/necho': '',
  261. 'http://purl.org/echo/': '',
  262. 'uri/of/echo/namespace#': '',
  263. 'http://purl.org/pie/': '',
  264. 'http://purl.org/atom/ns#': '',
  265. 'http://www.w3.org/2005/Atom': '',
  266. 'http://purl.org/rss/1.0/modules/rss091#': '',
  267. 'http://webns.net/mvcb/': 'admin',
  268. 'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
  269. 'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
  270. 'http://media.tangent.org/rss/1.0/': 'audio',
  271. 'http://backend.userland.com/blogChannelModule': 'blogChannel',
  272. 'http://web.resource.org/cc/': 'cc',
  273. 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  274. 'http://purl.org/rss/1.0/modules/company': 'co',
  275. 'http://purl.org/rss/1.0/modules/content/': 'content',
  276. 'http://my.theinfo.org/changed/1.0/rss/': 'cp',
  277. 'http://purl.org/dc/elements/1.1/': 'dc',
  278. 'http://purl.org/dc/terms/': 'dcterms',
  279. 'http://purl.org/rss/1.0/modules/email/': 'email',
  280. 'http://purl.org/rss/1.0/modules/event/': 'ev',
  281. 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
  282. 'http://freshmeat.net/rss/fm/': 'fm',
  283. 'http://xmlns.com/foaf/0.1/': 'foaf',
  284. 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
  285. 'http://postneo.com/icbm/': 'icbm',
  286. 'http://purl.org/rss/1.0/modules/image/': 'image',
  287. 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
  288. 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
  289. 'http://purl.org/rss/1.0/modules/link/': 'l',
  290. 'http://search.yahoo.com/mrss': 'media',
  291. 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  292. 'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
  293. 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
  294. 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
  295. 'http://purl.org/rss/1.0/modules/reference/': 'ref',
  296. 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
  297. 'http://purl.org/rss/1.0/modules/search/': 'search',
  298. 'http://purl.org/rss/1.0/modules/slash/': 'slash',
  299. 'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
  300. 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
  301. 'http://hacks.benhammersley.com/rss/streaming/': 'str',
  302. 'http://purl.org/rss/1.0/modules/subscription/': 'sub',
  303. 'http://purl.org/rss/1.0/modules/syndication/': 'sy',
  304. 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
  305. 'http://purl.org/rss/1.0/modules/threading/': 'thr',
  306. 'http://purl.org/rss/1.0/modules/textinput/': 'ti',
  307. 'http://madskills.com/public/xml/rss/module/trackback/':'trackback',
  308. 'http://wellformedweb.org/commentAPI/': 'wfw',
  309. 'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
  310. 'http://www.w3.org/1999/xhtml': 'xhtml',
  311. 'http://www.w3.org/XML/1998/namespace': 'xml',
  312. 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf'
  313. }
  314. _matchnamespaces = {}
  315. can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo']
  316. can_contain_relative_uris = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  317. can_contain_dangerous_markup = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  318. html_types = ['text/html', 'application/xhtml+xml']
  319. def __init__(self, baseuri=None, baselang=None, encoding='utf-8'):
  320. if _debug: sys.stderr.write('initializing FeedParser\n')
  321. if not self._matchnamespaces:
  322. for k, v in self.namespaces.items():
  323. self._matchnamespaces[k.lower()] = v
  324. self.feeddata = FeedParserDict() # feed-level data
  325. self.encoding = encoding # character encoding
  326. self.entries = [] # list of entry-level data
  327. self.version = '' # feed type/version, see SUPPORTED_VERSIONS
  328. self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  329. # the following are used internally to track state;
  330. # this is really out of control and should be refactored
  331. self.infeed = 0
  332. self.inentry = 0
  333. self.incontent = 0
  334. self.intextinput = 0
  335. self.inimage = 0
  336. self.inauthor = 0
  337. self.incontributor = 0
  338. self.inpublisher = 0
  339. self.insource = 0
  340. self.sourcedata = FeedParserDict()
  341. self.contentparams = FeedParserDict()
  342. self._summaryKey = None
  343. self.namespacemap = {}
  344. self.elementstack = []
  345. self.basestack = []
  346. self.langstack = []
  347. self.baseuri = baseuri or ''
  348. self.lang = baselang or None
  349. if baselang:
  350. self.feeddata['language'] = baselang
  351. def unknown_starttag(self, tag, attrs):
  352. if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
  353. # normalize attrs
  354. attrs = [(k.lower(), v) for k, v in attrs]
  355. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  356. # track xml:base and xml:lang
  357. attrsD = dict(attrs)
  358. baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  359. self.baseuri = _urljoin(self.baseuri, baseuri)
  360. lang = attrsD.get('xml:lang', attrsD.get('lang'))
  361. if lang == '':
  362. # xml:lang could be explicitly set to '', we need to capture that
  363. lang = None
  364. elif lang is None:
  365. # if no xml:lang is specified, use parent lang
  366. lang = self.lang
  367. if lang:
  368. if tag in ('feed', 'rss', 'rdf:RDF'):
  369. self.feeddata['language'] = lang
  370. self.lang = lang
  371. self.basestack.append(self.baseuri)
  372. self.langstack.append(lang)
  373. # track namespaces
  374. for prefix, uri in attrs:
  375. if prefix.startswith('xmlns:'):
  376. self.trackNamespace(prefix[6:], uri)
  377. elif prefix == 'xmlns':
  378. self.trackNamespace(None, uri)
  379. # track inline content
  380. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  381. # element declared itself as escaped markup, but it isn't really
  382. self.contentparams['type'] = 'application/xhtml+xml'
  383. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  384. # Note: probably shouldn't simply recreate localname here, but
  385. # our namespace handling isn't actually 100% correct in cases where
  386. # the feed redefines the default namespace (which is actually
  387. # the usual case for inline content, thanks Sam), so here we
  388. # cheat and just reconstruct the element based on localname
  389. # because that compensates for the bugs in our namespace handling.
  390. # This will horribly munge inline content with non-empty qnames,
  391. # but nobody actually does that, so I'm not fixing it.
  392. tag = tag.split(':')[-1]
  393. return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0)
  394. # match namespaces
  395. if tag.find(':') <> -1:
  396. prefix, suffix = tag.split(':', 1)
  397. else:
  398. prefix, suffix = '', tag
  399. prefix = self.namespacemap.get(prefix, prefix)
  400. if prefix:
  401. prefix = prefix + '_'
  402. # special hack for better tracking of empty textinput/image elements in illformed feeds
  403. if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  404. self.intextinput = 0
  405. if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  406. self.inimage = 0
  407. # call special handler (if defined) or default handler
  408. methodname = '_start_' + prefix + suffix
  409. try:
  410. method = getattr(self, methodname)
  411. return method(attrsD)
  412. except AttributeError:
  413. return self.push(prefix + suffix, 1)
  414. def unknown_endtag(self, tag):
  415. if _debug: sys.stderr.write('end %s\n' % tag)
  416. # match namespaces
  417. if tag.find(':') <> -1:
  418. prefix, suffix = tag.split(':', 1)
  419. else:
  420. prefix, suffix = '', tag
  421. prefix = self.namespacemap.get(prefix, prefix)
  422. if prefix:
  423. prefix = prefix + '_'
  424. # call special handler (if defined) or default handler
  425. methodname = '_end_' + prefix + suffix
  426. try:
  427. method = getattr(self, methodname)
  428. method()
  429. except AttributeError:
  430. self.pop(prefix + suffix)
  431. # track inline content
  432. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  433. # element declared itself as escaped markup, but it isn't really
  434. self.contentparams['type'] = 'application/xhtml+xml'
  435. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  436. tag = tag.split(':')[-1]
  437. self.handle_data('</%s>' % tag, escape=0)
  438. # track xml:base and xml:lang going out of scope
  439. if self.basestack:
  440. self.basestack.pop()
  441. if self.basestack and self.basestack[-1]:
  442. self.baseuri = self.basestack[-1]
  443. if self.langstack:
  444. self.langstack.pop()
  445. if self.langstack: # and (self.langstack[-1] is not None):
  446. self.lang = self.langstack[-1]
  447. def handle_charref(self, ref):
  448. # called for each character reference, e.g. for '&#160;', ref will be '160'
  449. if not self.elementstack: return
  450. ref = ref.lower()
  451. if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  452. text = '&#%s;' % ref
  453. else:
  454. if ref[0] == 'x':
  455. c = int(ref[1:], 16)
  456. else:
  457. c = int(ref)
  458. text = unichr(c).encode('utf-8')
  459. self.elementstack[-1][2].append(text)
  460. def handle_entityref(self, ref):
  461. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  462. if not self.elementstack: return
  463. if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref)
  464. if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  465. text = '&%s;' % ref
  466. else:
  467. # entity resolution graciously donated by Aaron Swartz
  468. def name2cp(k):
  469. import htmlentitydefs
  470. if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3
  471. return htmlentitydefs.name2codepoint[k]
  472. k = htmlentitydefs.entitydefs[k]
  473. if k.startswith('&#') and k.endswith(';'):
  474. return int(k[2:-1]) # not in latin-1
  475. return ord(k)
  476. try: name2cp(ref)
  477. except KeyError: text = '&%s;' % ref
  478. else: text = unichr(name2cp(ref)).encode('utf-8')
  479. self.elementstack[-1][2].append(text)
  480. def handle_data(self, text, escape=1):
  481. # called for each block of plain text, i.e. outside of any tag and
  482. # not containing any character or entity references
  483. if not self.elementstack: return
  484. if escape and self.contentparams.get('type') == 'application/xhtml+xml':
  485. text = _xmlescape(text)
  486. self.elementstack[-1][2].append(text)
  487. def handle_comment(self, text):
  488. # called for each comment, e.g. <!-- insert message here -->
  489. pass
  490. def handle_pi(self, text):
  491. # called for each processing instruction, e.g. <?instruction>
  492. pass
  493. def handle_decl(self, text):
  494. pass
  495. def parse_declaration(self, i):
  496. # override internal declaration handler to handle CDATA blocks
  497. if _debug: sys.stderr.write('entering parse_declaration\n')
  498. if self.rawdata[i:i+9] == '<![CDATA[':
  499. k = self.rawdata.find(']]>', i)
  500. if k == -1: k = len(self.rawdata)
  501. self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  502. return k+3
  503. else:
  504. k = self.rawdata.find('>', i)
  505. return k+1
  506. def mapContentType(self, contentType):
  507. contentType = contentType.lower()
  508. if contentType == 'text':
  509. contentType = 'text/plain'
  510. elif contentType == 'html':
  511. contentType = 'text/html'
  512. elif contentType == 'xhtml':
  513. contentType = 'application/xhtml+xml'
  514. return contentType
  515. def trackNamespace(self, prefix, uri):
  516. loweruri = uri.lower()
  517. if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
  518. self.version = 'rss090'
  519. if loweruri == 'http://purl.org/rss/1.0/' and not self.version:
  520. self.version = 'rss10'
  521. if loweruri == 'http://www.w3.org/2005/atom' and not self.version:
  522. self.version = 'atom10'
  523. if loweruri.find('backend.userland.com/rss') <> -1:
  524. # match any backend.userland.com namespace
  525. uri = 'http://backend.userland.com/rss'
  526. loweruri = uri
  527. if self._matchnamespaces.has_key(loweruri):
  528. self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  529. self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  530. else:
  531. self.namespacesInUse[prefix or ''] = uri
  532. def resolveURI(self, uri):
  533. return _urljoin(self.baseuri or '', uri)
  534. def decodeEntities(self, element, data):
  535. return data
  536. def push(self, element, expectingText):
  537. self.elementstack.append([element, expectingText, []])
  538. def pop(self, element, stripWhitespace=1):
  539. if not self.elementstack: return
  540. if self.elementstack[-1][0] != element: return
  541. element, expectingText, pieces = self.elementstack.pop()
  542. output = ''.join(pieces)
  543. if stripWhitespace:
  544. output = output.strip()
  545. if not expectingText: return output
  546. # decode base64 content
  547. if base64 and self.contentparams.get('base64', 0):
  548. try:
  549. output = base64.decodestring(output)
  550. except binascii.Error:
  551. pass
  552. except binascii.Incomplete:
  553. pass
  554. # resolve relative URIs
  555. if (element in self.can_be_relative_uri) and output:
  556. output = self.resolveURI(output)
  557. # decode entities within embedded markup
  558. if not self.contentparams.get('base64', 0):
  559. output = self.decodeEntities(element, output)
  560. # remove temporary cruft from contentparams
  561. try:
  562. del self.contentparams['mode']
  563. except KeyError:
  564. pass
  565. try:
  566. del self.contentparams['base64']
  567. except KeyError:
  568. pass
  569. # resolve relative URIs within embedded markup
  570. if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  571. if element in self.can_contain_relative_uris:
  572. output = _resolveRelativeURIs(output, self.baseuri, self.encoding)
  573. # sanitize embedded markup
  574. if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  575. if element in self.can_contain_dangerous_markup:
  576. output = _sanitizeHTML(output, self.encoding)
  577. if self.encoding and type(output) != type(u''):
  578. try:
  579. output = unicode(output, self.encoding)
  580. except:
  581. pass
  582. # categories/tags/keywords/whatever are handled in _end_category
  583. if element == 'category':
  584. return output
  585. # store output in appropriate place(s)
  586. if self.inentry and not self.insource:
  587. if element == 'content':
  588. self.entries[-1].setdefault(element, [])
  589. contentparams = copy.deepcopy(self.contentparams)
  590. contentparams['value'] = output
  591. self.entries[-1][element].append(contentparams)
  592. elif element == 'link':
  593. self.entries[-1][element] = output
  594. if output:
  595. self.entries[-1]['links'][-1]['href'] = output
  596. else:
  597. if element == 'description':
  598. element = 'summary'
  599. self.entries[-1][element] = output
  600. if self.incontent:
  601. contentparams = copy.deepcopy(self.contentparams)
  602. contentparams['value'] = output
  603. self.entries[-1][element + '_detail'] = contentparams
  604. elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage):
  605. context = self._getContext()
  606. if element == 'description':
  607. element = 'subtitle'
  608. context[element] = output
  609. if element == 'link':
  610. context['links'][-1]['href'] = output
  611. elif self.incontent:
  612. contentparams = copy.deepcopy(self.contentparams)
  613. contentparams['value'] = output
  614. context[element + '_detail'] = contentparams
  615. return output
  616. def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  617. self.incontent += 1
  618. self.contentparams = FeedParserDict({
  619. 'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  620. 'language': self.lang,
  621. 'base': self.baseuri})
  622. self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  623. self.push(tag, expectingText)
  624. def popContent(self, tag):
  625. value = self.pop(tag)
  626. self.incontent -= 1
  627. self.contentparams.clear()
  628. return value
  629. def _mapToStandardPrefix(self, name):
  630. colonpos = name.find(':')
  631. if colonpos <> -1:
  632. prefix = name[:colonpos]
  633. suffix = name[colonpos+1:]
  634. prefix = self.namespacemap.get(prefix, prefix)
  635. name = prefix + ':' + suffix
  636. return name
  637. def _getAttribute(self, attrsD, name):
  638. return attrsD.get(self._mapToStandardPrefix(name))
  639. def _isBase64(self, attrsD, contentparams):
  640. if attrsD.get('mode', '') == 'base64':
  641. return 1
  642. if self.contentparams['type'].startswith('text/'):
  643. return 0
  644. if self.contentparams['type'].endswith('+xml'):
  645. return 0
  646. if self.contentparams['type'].endswith('/xml'):
  647. return 0
  648. return 1
  649. def _itsAnHrefDamnIt(self, attrsD):
  650. href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  651. if href:
  652. try:
  653. del attrsD['url']
  654. except KeyError:
  655. pass
  656. try:
  657. del attrsD['uri']
  658. except KeyError:
  659. pass
  660. attrsD['href'] = href
  661. return attrsD
  662. def _save(self, key, value):
  663. context = self._getContext()
  664. context.setdefault(key, value)
  665. def _start_rss(self, attrsD):
  666. versionmap = {'0.91': 'rss091u',
  667. '0.92': 'rss092',
  668. '0.93': 'rss093',
  669. '0.94': 'rss094'}
  670. if not self.version:
  671. attr_version = attrsD.get('version', '')
  672. version = versionmap.get(attr_version)
  673. if version:
  674. self.version = version
  675. elif attr_version.startswith('2.'):
  676. self.version = 'rss20'
  677. else:
  678. self.version = 'rss'
  679. def _start_dlhottitles(self, attrsD):
  680. self.version = 'hotrss'
  681. def _start_channel(self, attrsD):
  682. self.infeed = 1
  683. self._cdf_common(attrsD)
  684. _start_feedinfo = _start_channel
  685. def _cdf_common(self, attrsD):
  686. if attrsD.has_key('lastmod'):
  687. self._start_modified({})
  688. self.elementstack[-1][-1] = attrsD['lastmod']
  689. self._end_modified()
  690. if attrsD.has_key('href'):
  691. self._start_link({})
  692. self.elementstack[-1][-1] = attrsD['href']
  693. self._end_link()
  694. def _start_feed(self, attrsD):
  695. self.infeed = 1
  696. versionmap = {'0.1': 'atom01',
  697. '0.2': 'atom02',
  698. '0.3': 'atom03'}
  699. if not self.version:
  700. attr_version = attrsD.get('version')
  701. version = versionmap.get(attr_version)
  702. if version:
  703. self.version = version
  704. else:
  705. self.version = 'atom'
  706. def _end_channel(self):
  707. self.infeed = 0
  708. _end_feed = _end_channel
  709. def _start_image(self, attrsD):
  710. self.inimage = 1
  711. self.push('image', 0)
  712. context = self._getContext()
  713. context.setdefault('image', FeedParserDict())
  714. def _end_image(self):
  715. self.pop('image')
  716. self.inimage = 0
  717. def _start_textinput(self, attrsD):
  718. self.intextinput = 1
  719. self.push('textinput', 0)
  720. context = self._getContext()
  721. context.setdefault('textinput', FeedParserDict())
  722. _start_textInput = _start_textinput
  723. def _end_textinput(self):
  724. self.pop('textinput')
  725. self.intextinput = 0
  726. _end_textInput = _end_textinput
  727. def _start_author(self, attrsD):
  728. self.inauthor = 1
  729. self.push('author', 1)
  730. _start_managingeditor = _start_author
  731. _start_dc_author = _start_author
  732. _start_dc_creator = _start_author
  733. _start_itunes_author = _start_author
  734. def _end_author(self):
  735. self.pop('author')
  736. self.inauthor = 0
  737. self._sync_author_detail()
  738. _end_managingeditor = _end_author
  739. _end_dc_author = _end_author
  740. _end_dc_creator = _end_author
  741. _end_itunes_author = _end_author
  742. def _start_itunes_owner(self, attrsD):
  743. self.inpublisher = 1
  744. self.push('publisher', 0)
  745. def _end_itunes_owner(self):
  746. self.pop('publisher')
  747. self.inpublisher = 0
  748. self._sync_author_detail('publisher')
  749. def _start_contributor(self, attrsD):
  750. self.incontributor = 1
  751. context = self._getContext()
  752. context.setdefault('contributors', [])
  753. context['contributors'].append(FeedParserDict())
  754. self.push('contributor', 0)
  755. def _end_contributor(self):
  756. self.pop('contributor')
  757. self.incontributor = 0
  758. def _start_dc_contributor(self, attrsD):
  759. self.incontributor = 1
  760. context = self._getContext()
  761. context.setdefault('contributors', [])
  762. context['contributors'].append(FeedParserDict())
  763. self.push('name', 0)
  764. def _end_dc_contributor(self):
  765. self._end_name()
  766. self.incontributor = 0
  767. def _start_name(self, attrsD):
  768. self.push('name', 0)
  769. _start_itunes_name = _start_name
  770. def _end_name(self):
  771. value = self.pop('name')
  772. if self.inpublisher:
  773. self._save_author('name', value, 'publisher')
  774. elif self.inauthor:
  775. self._save_author('name', value)
  776. elif self.incontributor:
  777. self._save_contributor('name', value)
  778. elif self.intextinput:
  779. context = self._getContext()
  780. context['textinput']['name'] = value
  781. _end_itunes_name = _end_name
  782. def _start_width(self, attrsD):
  783. self.push('width', 0)
  784. def _end_width(self):
  785. value = self.pop('width')
  786. try:
  787. value = int(value)
  788. except:
  789. value = 0
  790. if self.inimage:
  791. context = self._getContext()
  792. context['image']['width'] = value
  793. def _start_height(self, attrsD):
  794. self.push('height', 0)
  795. def _end_height(self):
  796. value = self.pop('height')
  797. try:
  798. value = int(value)
  799. except:
  800. value = 0
  801. if self.inimage:
  802. context = self._getContext()
  803. context['image']['height'] = value
  804. def _start_url(self, attrsD):
  805. self.push('href', 1)
  806. _start_homepage = _start_url
  807. _start_uri = _start_url
  808. def _end_url(self):
  809. value = self.pop('href')
  810. if self.inauthor:
  811. self._save_author('href', value)
  812. elif self.incontributor:
  813. self._save_contributor('href', value)
  814. elif self.inimage:
  815. context = self._getContext()
  816. context['image']['href'] = value
  817. elif self.intextinput:
  818. context = self._getContext()
  819. context['textinput']['link'] = value
  820. _end_homepage = _end_url
  821. _end_uri = _end_url
  822. def _start_email(self, attrsD):
  823. self.push('email', 0)
  824. _start_itunes_email = _start_email
  825. def _end_email(self):
  826. value = self.pop('email')
  827. if self.inpublisher:
  828. self._save_author('email', value, 'publisher')
  829. elif self.inauthor:
  830. self._save_author('email', value)
  831. elif self.incontributor:
  832. self._save_contributor('email', value)
  833. _end_itunes_email = _end_email
  834. def _getContext(self):
  835. if self.insource:
  836. context = self.sourcedata
  837. elif self.inentry:
  838. context = self.entries[-1]
  839. else:
  840. context = self.feeddata
  841. return context
  842. def _save_author(self, key, value, prefix='author'):
  843. context = self._getContext()
  844. context.setdefault(prefix + '_detail', FeedParserDict())
  845. context[prefix + '_detail'][key] = value
  846. self._sync_author_detail()
  847. def _save_contributor(self, key, value):
  848. context = self._getContext()
  849. context.setdefault('contributors', [FeedParserDict()])
  850. context['contributors'][-1][key] = value
  851. def _sync_author_detail(self, key='author'):
  852. context = self._getContext()
  853. detail = context.get('%s_detail' % key)
  854. if detail:
  855. name = detail.get('name')
  856. email = detail.get('email')
  857. if name and email:
  858. context[key] = '%s (%s)' % (name, email)
  859. elif name:
  860. context[key] = name
  861. elif email:
  862. context[key] = email
  863. else:
  864. author = context.get(key)
  865. if not author: return
  866. 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)
  867. if not emailmatch: return
  868. email = emailmatch.group(0)
  869. # probably a better way to do the following, but it passes all the tests
  870. author = author.replace(email, '')
  871. author = author.replace('()', '')
  872. author = author.strip()
  873. if author and (author[0] == '('):
  874. author = author[1:]
  875. if author and (author[-1] == ')'):
  876. author = author[:-1]
  877. author = author.strip()
  878. context.setdefault('%s_detail' % key, FeedParserDict())
  879. context['%s_detail' % key]['name'] = author
  880. context['%s_detail' % key]['email'] = email
  881. def _start_subtitle(self, attrsD):
  882. self.pushContent('subtitle', attrsD, 'text/plain', 1)
  883. _start_tagline = _start_subtitle
  884. _start_itunes_subtitle = _start_subtitle
  885. def _end_subtitle(self):
  886. self.popContent('subtitle')
  887. _end_tagline = _end_subtitle
  888. _end_itunes_subtitle = _end_subtitle
  889. def _start_rights(self, attrsD):
  890. self.pushContent('rights', attrsD, 'text/plain', 1)
  891. _start_dc_rights = _start_rights
  892. _start_copyright = _start_rights
  893. def _end_rights(self):
  894. self.popContent('rights')
  895. _end_dc_rights = _end_rights
  896. _end_copyright = _end_rights
  897. def _start_item(self, attrsD):
  898. self.entries.append(FeedParserDict())
  899. self.push('item', 0)
  900. self.inentry = 1
  901. self.guidislink = 0
  902. id = self._getAttribute(attrsD, 'rdf:about')
  903. if id:
  904. context = self._getContext()
  905. context['id'] = id
  906. self._cdf_common(attrsD)
  907. _start_entry = _start_item
  908. _start_product = _start_item
  909. def _end_item(self):
  910. self.pop('item')
  911. self.inentry = 0
  912. _end_entry = _end_item
  913. def _start_dc_language(self, attrsD):
  914. self.push('language', 1)
  915. _start_language = _start_dc_language
  916. def _end_dc_language(self):
  917. self.lang = self.pop('language')
  918. _end_language = _end_dc_language
  919. def _start_dc_publisher(self, attrsD):
  920. self.push('publisher', 1)
  921. _start_webmaster = _start_dc_publisher
  922. def _end_dc_publisher(self):
  923. self.pop('publisher')
  924. self._sync_author_detail('publisher')
  925. _end_webmaster = _end_dc_publisher
  926. def _start_published(self, attrsD):
  927. self.push('published', 1)
  928. _start_dcterms_issued = _start_published
  929. _start_issued = _start_published
  930. def _end_published(self):
  931. value = self.pop('published')
  932. self._save('published_parsed', _parse_date(value))
  933. _end_dcterms_issued = _end_published
  934. _end_issued = _end_published
  935. def _start_updated(self, attrsD):
  936. self.push('updated', 1)
  937. _start_modified = _start_updated
  938. _start_dcterms_modified = _start_updated
  939. _start_pubdate = _start_updated
  940. _start_dc_date = _start_updated
  941. def _end_updated(self):
  942. value = self.pop('updated')
  943. parsed_value = _parse_date(value)
  944. self._save('updated_parsed', parsed_value)
  945. _end_modified = _end_updated
  946. _end_dcterms_modified = _end_updated
  947. _end_pubdate = _end_updated
  948. _end_dc_date = _end_updated
  949. def _start_created(self, attrsD):
  950. self.push('created', 1)
  951. _start_dcterms_created = _start_created
  952. def _end_created(self):
  953. value = self.pop('created')
  954. self._save('created_parsed', _parse_date(value))
  955. _end_dcterms_created = _end_created
  956. def _start_expirationdate(self, attrsD):
  957. self.push('expired', 1)
  958. def _end_expirationdate(self):
  959. self._save('expired_parsed', _parse_date(self.pop('expired')))
  960. def _start_cc_license(self, attrsD):
  961. self.push('license', 1)
  962. value = self._getAttribute(attrsD, 'rdf:resource')
  963. if value:
  964. self.elementstack[-1][2].append(value)
  965. self.pop('license')
  966. def _start_creativecommons_license(self, attrsD):
  967. self.push('license', 1)
  968. def _end_creativecommons_license(self):
  969. self.pop('license')
  970. def _addTag(self, term, scheme, label):
  971. context = self._getContext()
  972. tags = context.setdefault('tags', [])
  973. if (not term) and (not scheme) and (not label): return
  974. value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  975. if value not in tags:
  976. tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label}))
  977. def _start_category(self, attrsD):
  978. if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD))
  979. term = attrsD.get('term')
  980. scheme = attrsD.get('scheme', attrsD.get('domain'))
  981. label = attrsD.get('label')
  982. self._addTag(term, scheme, label)
  983. self.push('category', 1)
  984. _start_dc_subject = _start_category
  985. _start_keywords = _start_category
  986. def _end_itunes_keywords(self):
  987. for term in self.pop('itunes_keywords').split():
  988. self._addTag(term, 'http://www.itunes.com/', None)
  989. def _start_itunes_category(self, attrsD):
  990. self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
  991. self.push('category', 1)
  992. def _end_category(self):
  993. value = self.pop('category')
  994. if not value: return
  995. context = self._getContext()
  996. tags = context['tags']
  997. if value and len(tags) and not tags[-1]['term']:
  998. tags[-1]['term'] = value
  999. else:
  1000. self._addTag(value, None, None)
  1001. _end_dc_subject = _end_category
  1002. _end_keywords = _end_category
  1003. _end_itunes_category = _end_category
  1004. def _start_cloud(self, attrsD):
  1005. self._getContext()['cloud'] = FeedParserDict(attrsD)
  1006. def _start_link(self, attrsD):
  1007. attrsD.setdefault('rel', 'alternate')
  1008. attrsD.setdefault('type', 'text/html')
  1009. attrsD = self._itsAnHrefDamnIt(attrsD)
  1010. if attrsD.has_key('href'):
  1011. attrsD['href'] = self.resolveURI(attrsD['href'])
  1012. expectingText = self.infeed or self.inentry or self.insource
  1013. context = self._getContext()
  1014. context.setdefault('links', [])
  1015. context['links'].append(FeedParserDict(attrsD))
  1016. if attrsD['rel'] == 'enclosure':
  1017. self._start_enclosure(attrsD)
  1018. if attrsD.has_key('href'):
  1019. expectingText = 0
  1020. if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1021. context['link'] = attrsD['href']
  1022. else:
  1023. self.push('link', expectingText)
  1024. _start_producturl = _start_link
  1025. def _end_link(self):
  1026. value = self.pop('link')
  1027. context = self._getContext()
  1028. if self.intextinput:
  1029. context['textinput']['link'] = value
  1030. if self.inimage:
  1031. context['image']['link'] = value
  1032. _end_producturl = _end_link
  1033. def _start_guid(self, attrsD):
  1034. self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1035. self.push('id', 1)
  1036. def _end_guid(self):
  1037. value = self.pop('id')
  1038. self._save('guidislink', self.guidislink and not self._getContext().has_key('link'))
  1039. if self.guidislink:
  1040. # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1041. # and only if the item doesn't already have a link element
  1042. self._save('link', value)
  1043. def _start_title(self, attrsD):
  1044. self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1045. _start_dc_title = _start_title
  1046. _start_media_title = _start_title
  1047. def _end_title(self):
  1048. value = self.popContent('title')
  1049. context = self._getContext()
  1050. if self.intextinput:
  1051. context['textinput']['title'] = value
  1052. elif self.inimage:
  1053. context['image']['title'] = value
  1054. _end_dc_title = _end_title
  1055. _end_media_title = _end_title
  1056. def _start_description(self, attrsD):
  1057. context = self._getContext()
  1058. if context.has_key('summary'):
  1059. self._summaryKey = 'content'
  1060. self._start_content(attrsD)
  1061. else:
  1062. self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
  1063. def _start_abstract(self, attrsD):
  1064. self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1065. def _end_description(self):
  1066. if self._summaryKey == 'content':
  1067. self._end_content()
  1068. else:
  1069. value = self.popContent('description')
  1070. context = self._getContext()
  1071. if self.intextinput:
  1072. context['textinput']['description'] = value
  1073. elif self.inimage:
  1074. context['image']['description'] = value
  1075. self._summaryKey = None
  1076. _end_abstract = _end_description
  1077. def _start_info(self, attrsD):
  1078. self.pushContent('info', attrsD, 'text/plain', 1)
  1079. _start_feedburner_browserfriendly = _start_info
  1080. def _end_info(self):
  1081. self.popContent('info')
  1082. _end_feedburner_browserfriendly = _end_info
  1083. def _start_generator(self, attrsD):
  1084. if attrsD:
  1085. attrsD = self._itsAnHrefDamnIt(attrsD)
  1086. if attrsD.has_key('href'):
  1087. attrsD['href'] = self.resolveURI(attrsD['href'])
  1088. self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1089. self.push('generator', 1)
  1090. def _end_generator(self):
  1091. value = self.pop('generator')
  1092. context = self._getContext()
  1093. if context.has_key('generator_detail'):
  1094. context['generator_detail']['name'] = value
  1095. def _start_admin_generatoragent(self, attrsD):
  1096. self.push('generator', 1)
  1097. value = self._getAttribute(attrsD, 'rdf:resource')
  1098. if value:
  1099. self.elementstack[-1][2].append(value)
  1100. self.pop('generator')
  1101. self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1102. def _start_admin_errorreportsto(self, attrsD):
  1103. self.push('errorreportsto', 1)
  1104. value = self._getAttribute(attrsD, 'rdf:resource')
  1105. if value:
  1106. self.elementstack[-1][2].append(value)
  1107. self.pop('errorreportsto')
  1108. def _start_summary(self, attrsD):
  1109. context = self._getContext()
  1110. if context.has_key('summary'):
  1111. self._summaryKey = 'content'
  1112. self._start_content(attrsD)
  1113. else:
  1114. self._summaryKey = 'summary'
  1115. self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)
  1116. _start_itunes_summary = _start_summary
  1117. def _end_summary(self):
  1118. if self._summaryKey == 'content':
  1119. self._end_content()
  1120. else:
  1121. self.popContent(self._summaryKey or 'summary')
  1122. self._summaryKey = None
  1123. _end_itunes_summary = _end_summary
  1124. def _start_enclosure(self, attrsD):
  1125. attrsD = self._itsAnHrefDamnIt(attrsD)
  1126. self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD))

Large files files are truncated, but you can click here to view the full file