PageRenderTime 53ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/feedparser.py

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

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