PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/script.module.feedparser/lib/feedparser.py

http://queeup.googlecode.com/
Python | 3909 lines | 3660 code | 134 blank | 115 comment | 274 complexity | d2f997bd6f77911900a55698dbe5fc0d MD5 | raw file
Possible License(s): WTFPL, BSD-2-Clause

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

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