PageRenderTime 75ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/yarss2/lib/feedparser/feedparser.py

https://bitbucket.org/bendikro/deluge-yarss-plugin
Python | 4010 lines | 3673 code | 141 blank | 196 comment | 258 complexity | 6e5dbc23c3d496df9f6ad1020a2ba983 MD5 | raw file
Possible License(s): GPL-3.0, MIT, MPL-2.0, Apache-2.0, BSD-3-Clause

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

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