PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/gluon/contrib/feedparser.py

https://code.google.com/p/web2py/
Python | 3987 lines | 3651 code | 151 blank | 185 comment | 239 complexity | 4f122411428e8da14291ebccd5df1792 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-2-Clause, MIT, BSD-3-Clause, Apache-2.0

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

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

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