PageRenderTime 65ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/utils/feedparser.py

https://github.com/samuelclay/NewsBlur
Python | 3798 lines | 3466 code | 138 blank | 194 comment | 253 complexity | 9078d25558f9ab7276798be9ee90b553 MD5 | raw file
Possible License(s): MIT, GPL-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.1.3"
  9. __license__ = """
  10. Copyright (c) 2010-2013 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. "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. if key == 'category':
  276. try:
  277. return dict.__getitem__(self, 'tags')[0]['term']
  278. except IndexError:
  279. raise KeyError, "object doesn't have key 'category'"
  280. elif key == 'enclosures':
  281. norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel'])
  282. return [norel(link) for link in dict.__getitem__(self, 'links') if link['rel']==u'enclosure']
  283. elif key == 'license':
  284. for link in dict.__getitem__(self, 'links'):
  285. if link['rel']==u'license' and 'href' in link:
  286. return link['href']
  287. elif key == 'updated':
  288. # Temporarily help developers out by keeping the old
  289. # broken behavior that was reported in issue 310.
  290. # This fix was proposed in issue 328.
  291. if not dict.__contains__(self, 'updated') and \
  292. dict.__contains__(self, 'published'):
  293. warnings.warn("To avoid breaking existing software while "
  294. "fixing issue 310, a temporary mapping has been created "
  295. "from `updated` to `published` if `updated` doesn't "
  296. "exist. This fallback will be removed in a future version "
  297. "of feedparser.", DeprecationWarning)
  298. return dict.__getitem__(self, 'published')
  299. return dict.__getitem__(self, 'updated')
  300. elif key == 'updated_parsed':
  301. if not dict.__contains__(self, 'updated_parsed') and \
  302. dict.__contains__(self, 'published_parsed'):
  303. warnings.warn("To avoid breaking existing software while "
  304. "fixing issue 310, a temporary mapping has been created "
  305. "from `updated_parsed` to `published_parsed` if "
  306. "`updated_parsed` doesn't exist. This fallback will be "
  307. "removed in a future version of feedparser.",
  308. DeprecationWarning)
  309. return dict.__getitem__(self, 'published_parsed')
  310. return dict.__getitem__(self, 'updated_parsed')
  311. else:
  312. realkey = self.keymap.get(key, key)
  313. if isinstance(realkey, list):
  314. for k in realkey:
  315. if dict.__contains__(self, k):
  316. return dict.__getitem__(self, k)
  317. elif dict.__contains__(self, realkey):
  318. return dict.__getitem__(self, realkey)
  319. return dict.__getitem__(self, key)
  320. def __contains__(self, key):
  321. if key in ('updated', 'updated_parsed'):
  322. # Temporarily help developers out by keeping the old
  323. # broken behavior that was reported in issue 310.
  324. # This fix was proposed in issue 328.
  325. return dict.__contains__(self, key)
  326. try:
  327. self.__getitem__(key)
  328. except KeyError:
  329. return False
  330. else:
  331. return True
  332. has_key = __contains__
  333. def get(self, key, default=None):
  334. try:
  335. return self.__getitem__(key)
  336. except KeyError:
  337. return default
  338. def __setitem__(self, key, value):
  339. key = self.keymap.get(key, key)
  340. if isinstance(key, list):
  341. key = key[0]
  342. return dict.__setitem__(self, key, value)
  343. def setdefault(self, key, value):
  344. if key not in self:
  345. self[key] = value
  346. return value
  347. return self[key]
  348. def __getattr__(self, key):
  349. # __getattribute__() is called first; this will be called
  350. # only if an attribute was not already found
  351. try:
  352. return self.__getitem__(key)
  353. except KeyError:
  354. raise AttributeError, "object has no attribute '%s'" % key
  355. def __hash__(self):
  356. return id(self)
  357. _cp1252 = {
  358. 128: unichr(8364), # euro sign
  359. 130: unichr(8218), # single low-9 quotation mark
  360. 131: unichr( 402), # latin small letter f with hook
  361. 132: unichr(8222), # double low-9 quotation mark
  362. 133: unichr(8230), # horizontal ellipsis
  363. 134: unichr(8224), # dagger
  364. 135: unichr(8225), # double dagger
  365. 136: unichr( 710), # modifier letter circumflex accent
  366. 137: unichr(8240), # per mille sign
  367. 138: unichr( 352), # latin capital letter s with caron
  368. 139: unichr(8249), # single left-pointing angle quotation mark
  369. 140: unichr( 338), # latin capital ligature oe
  370. 142: unichr( 381), # latin capital letter z with caron
  371. 145: unichr(8216), # left single quotation mark
  372. 146: unichr(8217), # right single quotation mark
  373. 147: unichr(8220), # left double quotation mark
  374. 148: unichr(8221), # right double quotation mark
  375. 149: unichr(8226), # bullet
  376. 150: unichr(8211), # en dash
  377. 151: unichr(8212), # em dash
  378. 152: unichr( 732), # small tilde
  379. 153: unichr(8482), # trade mark sign
  380. 154: unichr( 353), # latin small letter s with caron
  381. 155: unichr(8250), # single right-pointing angle quotation mark
  382. 156: unichr( 339), # latin small ligature oe
  383. 158: unichr( 382), # latin small letter z with caron
  384. 159: unichr( 376), # latin capital letter y with diaeresis
  385. }
  386. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  387. def _urljoin(base, uri):
  388. uri = _urifixer.sub(r'\1\3', uri)
  389. if not isinstance(uri, unicode):
  390. uri = uri.decode('utf-8', 'ignore')
  391. try:
  392. uri = urlparse.urljoin(base, uri)
  393. except ValueError:
  394. uri = u''
  395. if not isinstance(uri, unicode):
  396. return uri.decode('utf-8', 'ignore')
  397. return uri
  398. class _FeedParserMixin:
  399. namespaces = {
  400. '': '',
  401. 'http://backend.userland.com/rss': '',
  402. 'http://blogs.law.harvard.edu/tech/rss': '',
  403. 'http://purl.org/rss/1.0/': '',
  404. 'http://my.netscape.com/rdf/simple/0.9/': '',
  405. 'http://example.com/newformat#': '',
  406. 'http://example.com/necho': '',
  407. 'http://purl.org/echo/': '',
  408. 'uri/of/echo/namespace#': '',
  409. 'http://purl.org/pie/': '',
  410. 'http://purl.org/atom/ns#': '',
  411. 'http://www.w3.org/2005/Atom': '',
  412. 'http://purl.org/rss/1.0/modules/rss091#': '',
  413. 'http://webns.net/mvcb/': 'admin',
  414. 'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
  415. 'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
  416. 'http://media.tangent.org/rss/1.0/': 'audio',
  417. 'http://backend.userland.com/blogChannelModule': 'blogChannel',
  418. 'http://web.resource.org/cc/': 'cc',
  419. 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  420. 'http://purl.org/rss/1.0/modules/company': 'co',
  421. 'http://purl.org/rss/1.0/modules/content/': 'content',
  422. 'http://my.theinfo.org/changed/1.0/rss/': 'cp',
  423. 'http://purl.org/dc/elements/1.1/': 'dc',
  424. 'http://purl.org/dc/terms/': 'dcterms',
  425. 'http://purl.org/rss/1.0/modules/email/': 'email',
  426. 'http://purl.org/rss/1.0/modules/event/': 'ev',
  427. 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
  428. 'http://freshmeat.net/rss/fm/': 'fm',
  429. 'http://xmlns.com/foaf/0.1/': 'foaf',
  430. 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
  431. 'http://www.georss.org/georss': 'georss',
  432. 'http://www.opengis.net/gml': 'gml',
  433. 'http://postneo.com/icbm/': 'icbm',
  434. 'http://purl.org/rss/1.0/modules/image/': 'image',
  435. 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
  436. 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
  437. 'http://purl.org/rss/1.0/modules/link/': 'l',
  438. 'http://search.yahoo.com/mrss': 'media',
  439. # Version 1.1.2 of the Media RSS spec added the trailing slash on the namespace
  440. 'http://search.yahoo.com/mrss/': 'media',
  441. 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  442. 'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
  443. 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
  444. 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
  445. 'http://purl.org/rss/1.0/modules/reference/': 'ref',
  446. 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
  447. 'http://purl.org/rss/1.0/modules/search/': 'search',
  448. 'http://purl.org/rss/1.0/modules/slash/': 'slash',
  449. 'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
  450. 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
  451. 'http://hacks.benhammersley.com/rss/streaming/': 'str',
  452. 'http://purl.org/rss/1.0/modules/subscription/': 'sub',
  453. 'http://purl.org/rss/1.0/modules/syndication/': 'sy',
  454. 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf',
  455. 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
  456. 'http://purl.org/rss/1.0/modules/threading/': 'thr',
  457. 'http://purl.org/rss/1.0/modules/textinput/': 'ti',
  458. 'http://madskills.com/public/xml/rss/module/trackback/': 'trackback',
  459. 'http://wellformedweb.org/commentAPI/': 'wfw',
  460. 'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
  461. 'http://www.w3.org/1999/xhtml': 'xhtml',
  462. 'http://www.w3.org/1999/xlink': 'xlink',
  463. 'http://www.w3.org/XML/1998/namespace': 'xml',
  464. 'http://podlove.org/simple-chapters': 'psc',
  465. }
  466. _matchnamespaces = {}
  467. can_be_relative_uri = set(['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo'])
  468. can_contain_relative_uris = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
  469. can_contain_dangerous_markup = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
  470. html_types = [u'text/html', u'application/xhtml+xml']
  471. def __init__(self, baseuri=None, baselang=None, encoding=u'utf-8'):
  472. if not self._matchnamespaces:
  473. for k, v in self.namespaces.items():
  474. self._matchnamespaces[k.lower()] = v
  475. self.feeddata = FeedParserDict() # feed-level data
  476. self.encoding = encoding # character encoding
  477. self.entries = [] # list of entry-level data
  478. self.version = u'' # feed type/version, see SUPPORTED_VERSIONS
  479. self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  480. # the following are used internally to track state;
  481. # this is really out of control and should be refactored
  482. self.infeed = 0
  483. self.inentry = 0
  484. self.incontent = 0
  485. self.intextinput = 0
  486. self.inimage = 0
  487. self.inauthor = 0
  488. self.incontributor = 0
  489. self.inpublisher = 0
  490. self.insource = 0
  491. # georss
  492. self.ingeometry = 0
  493. self.sourcedata = FeedParserDict()
  494. self.contentparams = FeedParserDict()
  495. self._summaryKey = None
  496. self.namespacemap = {}
  497. self.elementstack = []
  498. self.basestack = []
  499. self.langstack = []
  500. self.baseuri = baseuri or u''
  501. self.lang = baselang or None
  502. self.svgOK = 0
  503. self.title_depth = -1
  504. self.depth = 0
  505. # psc_chapters_flag prevents multiple psc_chapters from being
  506. # captured in a single entry or item. The transition states are
  507. # None -> True -> False. psc_chapter elements will only be
  508. # captured while it is True.
  509. self.psc_chapters_flag = None
  510. if baselang:
  511. self.feeddata['language'] = baselang.replace('_','-')
  512. # A map of the following form:
  513. # {
  514. # object_that_value_is_set_on: {
  515. # property_name: depth_of_node_property_was_extracted_from,
  516. # other_property: depth_of_node_property_was_extracted_from,
  517. # },
  518. # }
  519. self.property_depth_map = {}
  520. def _normalize_attributes(self, kv):
  521. k = kv[0].lower()
  522. v = k in ('rel', 'type') and kv[1].lower() or kv[1]
  523. # the sgml parser doesn't handle entities in attributes, nor
  524. # does it pass the attribute values through as unicode, while
  525. # strict xml parsers do -- account for this difference
  526. if isinstance(self, _LooseFeedParser):
  527. v = v.replace('&amp;', '&')
  528. if not isinstance(v, unicode):
  529. v = v.decode('utf-8')
  530. return (k, v)
  531. def unknown_starttag(self, tag, attrs):
  532. # increment depth counter
  533. self.depth += 1
  534. # normalize attrs
  535. attrs = map(self._normalize_attributes, attrs)
  536. # track xml:base and xml:lang
  537. attrsD = dict(attrs)
  538. baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  539. if not isinstance(baseuri, unicode):
  540. baseuri = baseuri.decode(self.encoding, 'ignore')
  541. # ensure that self.baseuri is always an absolute URI that
  542. # uses a whitelisted URI scheme (e.g. not `javscript:`)
  543. if self.baseuri:
  544. self.baseuri = _makeSafeAbsoluteURI(self.baseuri, baseuri) or self.baseuri
  545. else:
  546. self.baseuri = _urljoin(self.baseuri, baseuri)
  547. lang = attrsD.get('xml:lang', attrsD.get('lang'))
  548. if lang == '':
  549. # xml:lang could be explicitly set to '', we need to capture that
  550. lang = None
  551. elif lang is None:
  552. # if no xml:lang is specified, use parent lang
  553. lang = self.lang
  554. if lang:
  555. if tag in ('feed', 'rss', 'rdf:RDF'):
  556. self.feeddata['language'] = lang.replace('_','-')
  557. self.lang = lang
  558. self.basestack.append(self.baseuri)
  559. self.langstack.append(lang)
  560. # track namespaces
  561. for prefix, uri in attrs:
  562. if prefix.startswith('xmlns:'):
  563. self.trackNamespace(prefix[6:], uri)
  564. elif prefix == 'xmlns':
  565. self.trackNamespace(None, uri)
  566. # track inline content
  567. if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
  568. if tag in ('xhtml:div', 'div'):
  569. return # typepad does this 10/2007
  570. # element declared itself as escaped markup, but it isn't really
  571. self.contentparams['type'] = u'application/xhtml+xml'
  572. if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
  573. if tag.find(':') <> -1:
  574. prefix, tag = tag.split(':', 1)
  575. namespace = self.namespacesInUse.get(prefix, '')
  576. if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
  577. attrs.append(('xmlns',namespace))
  578. if tag=='svg' and namespace=='http://www.w3.org/2000/svg':
  579. attrs.append(('xmlns',namespace))
  580. if tag == 'svg':
  581. self.svgOK += 1
  582. return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0)
  583. # match namespaces
  584. if tag.find(':') <> -1:
  585. prefix, suffix = tag.split(':', 1)
  586. else:
  587. prefix, suffix = '', tag
  588. prefix = self.namespacemap.get(prefix, prefix)
  589. if prefix:
  590. prefix = prefix + '_'
  591. # special hack for better tracking of empty textinput/image elements in illformed feeds
  592. if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  593. self.intextinput = 0
  594. if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  595. self.inimage = 0
  596. # call special handler (if defined) or default handler
  597. methodname = '_start_' + prefix + suffix
  598. try:
  599. method = getattr(self, methodname)
  600. return method(attrsD)
  601. except AttributeError:
  602. # Since there's no handler or something has gone wrong we explicitly add the element and its attributes
  603. unknown_tag = prefix + suffix
  604. if len(attrsD) == 0:
  605. # No attributes so merge it into the encosing dictionary
  606. return self.push(unknown_tag, 1)
  607. else:
  608. # Has attributes so create it in its own dictionary
  609. context = self._getContext()
  610. context[unknown_tag] = attrsD
  611. def unknown_endtag(self, tag):
  612. # match namespaces
  613. if tag.find(':') <> -1:
  614. prefix, suffix = tag.split(':', 1)
  615. else:
  616. prefix, suffix = '', tag
  617. prefix = self.namespacemap.get(prefix, prefix)
  618. if prefix:
  619. prefix = prefix + '_'
  620. if suffix == 'svg' and self.svgOK:
  621. self.svgOK -= 1
  622. # call special handler (if defined) or default handler
  623. methodname = '_end_' + prefix + suffix
  624. try:
  625. if self.svgOK:
  626. raise AttributeError()
  627. method = getattr(self, methodname)
  628. method()
  629. except AttributeError:
  630. self.pop(prefix + suffix)
  631. # track inline content
  632. if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
  633. # element declared itself as escaped markup, but it isn't really
  634. if tag in ('xhtml:div', 'div'):
  635. return # typepad does this 10/2007
  636. self.contentparams['type'] = u'application/xhtml+xml'
  637. if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
  638. tag = tag.split(':')[-1]
  639. self.handle_data('</%s>' % tag, escape=0)
  640. # track xml:base and xml:lang going out of scope
  641. if self.basestack:
  642. self.basestack.pop()
  643. if self.basestack and self.basestack[-1]:
  644. self.baseuri = self.basestack[-1]
  645. if self.langstack:
  646. self.langstack.pop()
  647. if self.langstack: # and (self.langstack[-1] is not None):
  648. self.lang = self.langstack[-1]
  649. self.depth -= 1
  650. def handle_charref(self, ref):
  651. # called for each character reference, e.g. for '&#160;', ref will be '160'
  652. if not self.elementstack:
  653. return
  654. ref = ref.lower()
  655. if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  656. text = '&#%s;' % ref
  657. else:
  658. if ref[0] == 'x':
  659. c = int(ref[1:], 16)
  660. else:
  661. c = int(ref)
  662. text = unichr(c).encode('utf-8')
  663. self.elementstack[-1][2].append(text)
  664. def handle_entityref(self, ref):
  665. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  666. if not self.elementstack:
  667. return
  668. if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  669. text = '&%s;' % ref
  670. elif ref in self.entities:
  671. text = self.entities[ref]
  672. if text.startswith('&#') and text.endswith(';'):
  673. return self.handle_entityref(text)
  674. else:
  675. try:
  676. name2codepoint[ref]
  677. except KeyError:
  678. text = '&%s;' % ref
  679. else:
  680. text = unichr(name2codepoint[ref]).encode('utf-8')
  681. self.elementstack[-1][2].append(text)
  682. def handle_data(self, text, escape=1):
  683. # called for each block of plain text, i.e. outside of any tag and
  684. # not containing any character or entity references
  685. if not self.elementstack:
  686. return
  687. if escape and self.contentparams.get('type') == u'application/xhtml+xml':
  688. text = _xmlescape(text)
  689. self.elementstack[-1][2].append(text)
  690. def handle_comment(self, text):
  691. # called for each comment, e.g. <!-- insert message here -->
  692. pass
  693. def handle_pi(self, text):
  694. # called for each processing instruction, e.g. <?instruction>
  695. pass
  696. def handle_decl(self, text):
  697. pass
  698. def parse_declaration(self, i):
  699. # override internal declaration handler to handle CDATA blocks
  700. if self.rawdata[i:i+9] == '<![CDATA[':
  701. k = self.rawdata.find(']]>', i)
  702. if k == -1:
  703. # CDATA block began but didn't finish
  704. k = len(self.rawdata)
  705. return k
  706. self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  707. return k+3
  708. else:
  709. k = self.rawdata.find('>', i)
  710. if k >= 0:
  711. return k+1
  712. else:
  713. # We have an incomplete CDATA block.
  714. return k
  715. def mapContentType(self, contentType):
  716. contentType = contentType.lower()
  717. if contentType == 'text' or contentType == 'plain':
  718. contentType = u'text/plain'
  719. elif contentType == 'html':
  720. contentType = u'text/html'
  721. elif contentType == 'xhtml':
  722. contentType = u'application/xhtml+xml'
  723. return contentType
  724. def trackNamespace(self, prefix, uri):
  725. loweruri = uri.lower()
  726. if not self.version:
  727. if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/'):
  728. self.version = u'rss090'
  729. elif loweruri == 'http://purl.org/rss/1.0/':
  730. self.version = u'rss10'
  731. elif loweruri == 'http://www.w3.org/2005/atom':
  732. self.version = u'atom10'
  733. if loweruri.find(u'backend.userland.com/rss') <> -1:
  734. # match any backend.userland.com namespace
  735. uri = u'http://backend.userland.com/rss'
  736. loweruri = uri
  737. if loweruri in self._matchnamespaces:
  738. self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  739. self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  740. else:
  741. self.namespacesInUse[prefix or ''] = uri
  742. def resolveURI(self, uri):
  743. return _urljoin(self.baseuri or u'', uri)
  744. def decodeEntities(self, element, data):
  745. return data
  746. def strattrs(self, attrs):
  747. return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs])
  748. def push(self, element, expectingText):
  749. self.elementstack.append([element, expectingText, []])
  750. def pop(self, element, stripWhitespace=1):
  751. if not self.elementstack:
  752. return
  753. if self.elementstack[-1][0] != element:
  754. return
  755. element, expectingText, pieces = self.elementstack.pop()
  756. if self.version == u'atom10' and self.contentparams.get('type', u'text') == u'application/xhtml+xml':
  757. # remove enclosing child element, but only if it is a <div> and
  758. # only if all the remaining content is nested underneath it.
  759. # This means that the divs would be retained in the following:
  760. # <div>foo</div><div>bar</div>
  761. while pieces and len(pieces)>1 and not pieces[-1].strip():
  762. del pieces[-1]
  763. while pieces and len(pieces)>1 and not pieces[0].strip():
  764. del pieces[0]
  765. if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) and pieces[-1]=='</div>':
  766. depth = 0
  767. for piece in pieces[:-1]:
  768. if piece.startswith('</'):
  769. depth -= 1
  770. if depth == 0:
  771. break
  772. elif piece.startswith('<') and not piece.endswith('/>'):
  773. depth += 1
  774. else:
  775. pieces = pieces[1:-1]
  776. # Ensure each piece is a str for Python 3
  777. for (i, v) in enumerate(pieces):
  778. if not isinstance(v, unicode):
  779. pieces[i] = v.decode('utf-8')
  780. output = u''.join(pieces)
  781. if stripWhitespace:
  782. output = output.strip()
  783. if not expectingText:
  784. return output
  785. # decode base64 content
  786. if base64 and self.contentparams.get('base64', 0):
  787. try:
  788. output = _base64decode(output)
  789. except binascii.Error:
  790. pass
  791. except binascii.Incomplete:
  792. pass
  793. except TypeError:
  794. # In Python 3, base64 takes and outputs bytes, not str
  795. # This may not be the most correct way to accomplish this
  796. output = _base64decode(output.encode('utf-8')).decode('utf-8')
  797. # resolve relative URIs
  798. if (element in self.can_be_relative_uri) and output:
  799. # do not resolve guid elements with isPermalink="false"
  800. if not element == 'id' or self.guidislink:
  801. output = self.resolveURI(output)
  802. # decode entities within embedded markup
  803. if not self.contentparams.get('base64', 0):
  804. output = self.decodeEntities(element, output)
  805. # some feed formats require consumers to guess
  806. # whether the content is html or plain text
  807. if not self.version.startswith(u'atom') and self.contentparams.get('type') == u'text/plain':
  808. if self.lookslikehtml(output):
  809. self.contentparams['type'] = u'text/html'
  810. # remove temporary cruft from contentparams
  811. try:
  812. del self.contentparams['mode']
  813. except KeyError:
  814. pass
  815. try:
  816. del self.contentparams['base64']
  817. except KeyError:
  818. pass
  819. is_htmlish = self.mapContentType(self.contentparams.get('type', u'text/html')) in self.html_types
  820. # resolve relative URIs within embedded markup
  821. if is_htmlish and RESOLVE_RELATIVE_URIS:
  822. if element in self.can_contain_relative_uris:
  823. output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', u'text/html'))
  824. # sanitize embedded markup
  825. if is_htmlish and SANITIZE_HTML:
  826. if element in self.can_contain_dangerous_markup:
  827. output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', u'text/html'))
  828. if self.encoding and not isinstance(output, unicode):
  829. output = output.decode(self.encoding, 'ignore')
  830. # address common error where people take data that is already
  831. # utf-8, presume that it is iso-8859-1, and re-encode it.
  832. if self.encoding in (u'utf-8', u'utf-8_INVALID_PYTHON_3') and isinstance(output, unicode):
  833. try:
  834. output = output.encode('iso-8859-1').decode('utf-8')
  835. except (UnicodeEncodeError, UnicodeDecodeError):
  836. pass
  837. # map win-1252 extensions to the proper code points
  838. if isinstance(output, unicode):
  839. output = output.translate(_cp1252)
  840. # categories/tags/keywords/whatever are handled in _end_category
  841. if element == 'category':
  842. return output
  843. if element == 'title' and -1 < self.title_depth <= self.depth:
  844. return output
  845. # store output in appropriate place(s)
  846. if self.inentry and not self.insource:
  847. if element == 'content':
  848. self.entries[-1].setdefault(element, [])
  849. contentparams = copy.deepcopy(self.contentparams)
  850. contentparams['value'] = output
  851. self.entries[-1][element].append(contentparams)
  852. elif element == 'link':
  853. if not self.inimage:
  854. # query variables in urls in link elements are improperly
  855. # converted from `?a=1&b=2` to `?a=1&b;=2` as if they're
  856. # unhandled character references. fix this special case.
  857. output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
  858. self.entries[-1][element] = output
  859. if output:
  860. self.entries[-1]['links'][-1]['href'] = output
  861. else:
  862. if element == 'description':
  863. element = 'summary'
  864. old_value_depth = self.property_depth_map.setdefault(self.entries[-1], {}).get(element)
  865. if old_value_depth is None or self.depth <= old_value_depth:
  866. self.property_depth_map[self.entries[-1]][element] = self.depth
  867. self.entries[-1][element] = output
  868. if self.incontent:
  869. contentparams = copy.deepcopy(self.contentparams)
  870. contentparams['value'] = output
  871. self.entries[-1][element + '_detail'] = contentparams
  872. elif (self.infeed or self.insource):# and (not self.intextinput) and (not self.inimage):
  873. context = self._getContext()
  874. if element == 'description':
  875. element = 'subtitle'
  876. context[element] = output
  877. if element == 'link':
  878. # fix query variables; see above for the explanation
  879. output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
  880. context[element] = output
  881. context['links'][-1]['href'] = output
  882. elif self.incontent:
  883. contentparams = copy.deepcopy(self.contentparams)
  884. contentparams['value'] = output
  885. context[element + '_detail'] = contentparams
  886. return output
  887. def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  888. self.incontent += 1
  889. if self.lang:
  890. self.lang=self.lang.replace('_','-')
  891. self.contentparams = FeedParserDict({
  892. 'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  893. 'language': self.lang,
  894. 'base': self.baseuri})
  895. self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  896. self.push(tag, expectingText)
  897. def popContent(self, tag):
  898. value = self.pop(tag)
  899. self.incontent -= 1
  900. self.contentparams.clear()
  901. return value
  902. # a number of elements in a number of RSS variants are nominally plain
  903. # text, but this is routinely ignored. This is an attempt to detect
  904. # the most common cases. As false positives often result in silent
  905. # data loss, this function errs on the conservative side.
  906. @staticmethod
  907. def lookslikehtml(s):
  908. # must have a close tag or an entity reference to qualify
  909. if not (re.search(r'</(\w+)>',s) or re.search("&#?\w+;",s)):
  910. return
  911. # all tags must be in a restricted subset of valid HTML tags
  912. if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements,
  913. re.findall(r'</?(\w+)',s)):
  914. return
  915. # all entities must have been defined as valid HTML entities
  916. if filter(lambda e: e not in entitydefs.keys(), re.findall(r'&(\w+);', s)):
  917. return
  918. return 1
  919. def _mapToStandardPrefix(self, name):
  920. colonpos = name.find(':')
  921. if colonpos <> -1:
  922. prefix = name[:colonpos]
  923. suffix = name[colonpos+1:]
  924. prefix = self.namespacemap.get(prefix, prefix)
  925. name = prefix + ':' + suffix
  926. return name
  927. def _getAttribute(self, attrsD, name):
  928. return attrsD.get(self._mapToStandardPrefix(name))
  929. def _isBase64(self, attrsD, contentparams):
  930. if attrsD.get('mode', '') == 'base64':
  931. return 1
  932. if self.contentparams['type'].startswith(u'text/'):
  933. return 0
  934. if self.contentparams['type'].endswith(u'+xml'):
  935. return 0
  936. if self.contentparams['type'].endswith(u'/xml'):
  937. return 0
  938. return 1
  939. def _itsAnHrefDamnIt(self, attrsD):
  940. href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  941. if href:
  942. try:
  943. del attrsD['url']
  944. except KeyError:
  945. pass
  946. try:
  947. del attrsD['uri']
  948. except KeyError:
  949. pass
  950. attrsD['href'] = href
  951. return attrsD
  952. def _save(self, key, value, overwrite=False):
  953. context = self._getContext()
  954. if overwrite:
  955. context[key] = value
  956. else:
  957. context.setdefault(key, value)
  958. def _start_rss(self, attrsD):
  959. versionmap = {'0.91': u'rss091u',
  960. '0.92': u'rss092',
  961. '0.93': u'rss093',
  962. '0.94': u'rss094'}
  963. #If we're here then this is an RSS feed.
  964. #If we don't have a version or have a version that starts with something
  965. #other than RSS then there's been a mistake. Correct it.
  966. if not self.version or not self.version.startswith(u'rss'):
  967. attr_version = attrsD.get('version', '')
  968. version = versionmap.get(attr_version)
  969. if version:
  970. self.version = version
  971. elif attr_version.startswith('2.'):
  972. self.version = u'rss20'
  973. else:
  974. self.version = u'rss'
  975. def _start_channel(self, attrsD):
  976. self.infeed = 1
  977. self._cdf_common(attrsD)
  978. def _cdf_common(self, attrsD):
  979. if 'lastmod' in attrsD:
  980. self._start_modified({})
  981. self.elementstack[-1][-1] = attrsD['lastmod']
  982. self._end_modified()
  983. if 'href' in attrsD:
  984. self._start_link({})
  985. self.elementstack[-1][-1] = attrsD['href']
  986. self._end_link()
  987. def _start_feed(self, attrsD):
  988. self.infeed = 1
  989. versionmap = {'0.1': u'atom01',
  990. '0.2': u'atom02',
  991. '0.3': u'atom03'}
  992. if not self.version:
  993. attr_version = attrsD.get('version')
  994. version = versionmap.get(attr_version)
  995. if version:
  996. self.version = version
  997. else:
  998. self.version = u'atom'
  999. def _end_channel(self):
  1000. self.infeed = 0
  1001. _end_feed = _end_channel
  1002. def _start_image(self, attrsD):
  1003. context = self._getContext()
  1004. if not self.inentry:
  1005. context.setdefault('image', FeedParserDict())
  1006. self.inimage = 1
  1007. self.title_depth = -1
  1008. self.push('image', 0)
  1009. def _end_image(self):
  1010. self.pop('image')
  1011. self.inimage = 0
  1012. def _start_textinput(self, attrsD):
  1013. context = self._getContext()
  1014. context.setdefault('textinput', FeedParserDict())
  1015. self.intextinput = 1
  1016. self.title_depth = -1
  1017. self.push('textinput', 0)
  1018. _start_textInput = _start_textinput
  1019. def _end_textinput(self):
  1020. self.pop('textinput')
  1021. self.intextinput = 0
  1022. _end_textInput = _end_textinput
  1023. def _start_author(self, attrsD):
  1024. self.inauthor = 1
  1025. self.push('author', 1)
  1026. # Append a new FeedParserDict when expecting an author
  1027. context = self._getContext()
  1028. context.setdefault('authors', [])
  1029. context['authors'].append(FeedParserDict())
  1030. _start_managingeditor = _start_author
  1031. _start_dc_author = _start_author
  1032. _start_dc_creator = _start_author
  1033. _start_itunes_author = _start_author
  1034. def _end_author(self):
  1035. self.pop('author')
  1036. self.inauthor = 0
  1037. self._sync_author_detail()
  1038. _end_managingeditor = _end_author
  1039. _end_dc_author = _end_author
  1040. _end_dc_creator = _end_author
  1041. _end_itunes_author = _end_author
  1042. def _start_itunes_owner(self, attrsD):
  1043. self.inpublisher = 1
  1044. self.push('publisher', 0)
  1045. def _end_itunes_owner(self):
  1046. self.pop('publisher')
  1047. self.inpublisher = 0
  1048. self._sync_author_detail('publisher')
  1049. def _start_contributor(self, attrsD):
  1050. self.incontributor = 1
  1051. context = self._getContext()
  1052. context.setdefault('contributors', [])
  1053. context['contributors'].append(FeedParserDict())
  1054. self.push('contributor', 0)
  1055. def _end_contributor(self):
  1056. self.pop('contributor')
  1057. self.incontributor = 0
  1058. def _start_dc_contributor(self, attrsD):
  1059. self.incontributor = 1
  1060. context = self._getContext()
  1061. context.setdefault('contributors', [])
  1062. context['contributors'].append(FeedParserDict())
  1063. self.push('name', 0)
  1064. def _end_dc_contributor(self):
  1065. self._end_name()
  1066. self.incontributor = 0
  1067. def _start_name(self, attrsD):
  1068. self.push('name', 0)
  1069. _start_itunes_name = _start_name
  1070. def _end_name(self):
  1071. value = self.pop('name')
  1072. if self.inpublisher:
  1073. self._save_author('name', value, 'publisher')
  1074. elif self.inauthor:
  1075. self._save_author('name', value)
  1076. elif self.incontributor:
  1077. self._save_contributor('name', value)
  1078. elif self.intextinput:
  1079. context = self._getContext()
  1080. context['name'] = value
  1081. _end_itunes_name = _end_name
  1082. def _start_width(self, attrsD):
  1083. self.push('width', 0)
  1084. def _end_width(self):
  1085. value = self.pop('width')
  1086. try:
  1087. value = int(value)
  1088. except ValueError:
  1089. value = 0
  1090. if self.inimage:
  1091. context = self._getContext()
  1092. context['width'] = value
  1093. def _start_height(self, attrsD):
  1094. self.push('height', 0)
  1095. def _end_height(self):
  1096. value = self.pop('height')
  1097. try:
  1098. value = int(value)
  1099. except ValueError:
  1100. value = 0
  1101. if self.inimage:
  1102. context = self._getContext()
  1103. context['height'] = v

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