GetRssDataAsDict.py 8.57 KB
Newer Older
Yusei Tahara's avatar
Yusei Tahara committed
1 2
from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, \
     build_opener, install_opener, urlopen, HTTPError
3
from xml.dom.minidom import parseString
Yusei Tahara's avatar
Yusei Tahara committed
4 5
import md5
from HTMLParser import HTMLParser
6
import socket
Yusei Tahara's avatar
Yusei Tahara committed
7 8 9 10 11 12 13 14

def getRssDataAsDict(url, username, password):
  passman = HTTPPasswordMgrWithDefaultRealm()
  passman.add_password(None, url, username, password)
  auth_handler = HTTPBasicAuthHandler(passman)
  opener = build_opener(auth_handler)
  install_opener(opener)
  try:
15 16 17 18 19 20 21
    default_timeout = socket.getdefaulttimeout()
    socket.setdefaulttimeout(5.0)
    try:
      file = urlopen(url)
    finally:
      socket.setdefaulttimeout(default_timeout)
      
Yusei Tahara's avatar
Yusei Tahara committed
22 23 24 25 26 27 28 29 30 31 32 33
  except IOError , e:
    return {'title': 'Connection problem, please retry later.'}
  except ValueError , e:
   return {'title': 'Please enter a valid Rss or Atom url in the preference form.' }
  except HTTPError , e:
    if hasattr(e, 'code'):
      if e.code == 401:
        return {'title': 'Unauthorized, verify your authentication.' }
      if e.code == 404:
        return {'title': 'Page not found.' }
  except :
    return {'title': 'Fetching Rss failed.' }
34 35 36
  return parseRssDataAsDict(file.read())

def parseRssDataAsDict(rss_string):
Yusei Tahara's avatar
Yusei Tahara committed
37
  try:
38
    xmlDoc = parseString(rss_string).documentElement
Yusei Tahara's avatar
Yusei Tahara committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
  except :
    return {'title': 'Parsing RSS failed.' }
  if(xmlDoc.tagName.startswith('rss') or xmlDoc.tagName.startswith('rdf') ):
    feed_data = {}
    RSSTitle = None
    if (xmlDoc.getElementsByTagName('title') and xmlDoc.getElementsByTagName('title')[0].parentNode.tagName != 'item'):
      feed_data['title'] = xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue
    if (xmlDoc.getElementsByTagName('image') and xmlDoc.getElementsByTagName('image')[0].parentNode.tagName != 'item'):
      logo = xmlDoc.getElementsByTagName('image')[0]
      if (logo.getElementsByTagName('url')):
        feed_data['logo'] = logo.getElementsByTagName('url')[0].firstChild.nodeValue
      elif(logo.getElementsByTagName('rdf:resource')):
        feed_data['logo'] = logo.getElementsByTagName('rdf:resource')[0].firstChild.nodeValue
    if (xmlDoc.getElementsByTagName('link') and xmlDoc.getElementsByTagName('link')[0].parentNode.tagName != 'item'):
      feed_data['link'] = xmlDoc.getElementsByTagName('link')[0].firstChild.nodeValue
    item_list = xmlDoc.getElementsByTagName('item')
    feed_data['items'] = []
    for item in item_list:
      message = {}
      message['other_links'] = []
      message['img'] = []
      if(item.getElementsByTagName('title') and item.getElementsByTagName('title')[0].firstChild):
        message['title'] = item.getElementsByTagName('title')[0].firstChild.nodeValue
      if(item.getElementsByTagName('link') and item.getElementsByTagName('link')[0].firstChild):
        message['link'] = item.getElementsByTagName('link')[0].firstChild.nodeValue
      if(item.getElementsByTagName('description') and item.getElementsByTagName('description')[0].firstChild):
        message['content'] = cleanHTML(item.getElementsByTagName('description')[0].firstChild.nodeValue)
      if (item.getElementsByTagName('pubDate') and item.getElementsByTagName('pubDate')[0].firstChild):
        message['date'] = item.getElementsByTagName('pubDate')[0].firstChild.nodeValue
      elif(item.getElementsByTagName('dc:date') and item.getElementsByTagName('dc:date')[0].firstChild):
        message['date'] = item.getElementsByTagName('dc:date')[0].firstChild.nodeValue
      if (item.getElementsByTagName('enclosure')):
        for enclosure in item.getElementsByTagName('enclosure'):
          if (str(enclosure.attributes['type'].nodeValue).find('image') != -1):
            message['img'].append(enclosure.attributes['url'].nodeValue)
          else:
            if (enclosure.attributes.has_key('title')):
              message['other_links'].append('<a href="'+enclosure.attributes['url'].nodeValue+'"target="_blank">'+enclosure.attributes['url'].nodeValue+'</a>')
            else:
              message['other_links'].append('<a href="'+enclosure.attributes['url'].nodeValue+'"target="_blank">'+enclosure.attributes['title'].nodeValue+'</a>')
      message['md5'] = md5.new(str(message)).hexdigest()
      feed_data['items'].append(message)
  elif(xmlDoc.tagName == 'feed'):
    feed_data = {}
    feedTitle = None
    if (xmlDoc.getElementsByTagName('title') and xmlDoc.getElementsByTagName('title')[0].parentNode.tagName != 'entry'):
      feed_data['title'] = xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue
    if (xmlDoc.getElementsByTagName('icon') and xmlDoc.getElementsByTagName('icon')[0].parentNode.tagName != 'entry'):
      feed_data['logo'] = xmlDoc.getElementsByTagName('icon')[0].firstChild.nodeValue
    item_list = xmlDoc.getElementsByTagName('entry')
    feed_data['items'] = []
    for item in item_list:
      message = {}
      if(item.getElementsByTagName('title') and item.getElementsByTagName('title')[0].firstChild):
        message['title'] = item.getElementsByTagName('title')[0].firstChild.nodeValue
      message['other_links'] = []
      message['img'] = []
      for link in item.getElementsByTagName('link'):
        if (link.attributes.has_key('rel') and link.attributes.get('rel').nodeValue == 'alternate'):
          message['link'] = link.attributes['href'].nodeValue
        elif (link.attributes.has_key('type') and link.attributes.get('type').nodeValue.find('image') != -1):
          message['img'].append(link.attributes['href'].nodeValue)
        else:
          if (link.attributes.has_key('title')):
            message['other_links'].append('<a href="'+link.attributes['href'].nodeValue+'" target="_blank">'+link.attributes['title'].nodeValue+'</a>')
          else:
            message['other_links'].append('<a href="'+link.attributes['href'].nodeValue+'"target="_blank">'+link.attributes['href'].nodeValue+'</a>')
      if (item.getElementsByTagName('content') and item.getElementsByTagName('content')[0].firstChild):
        message['content'] = stringConstructor(item.getElementsByTagName('content')[0])
      elif (item.getElementsByTagName('summary') and item.getElementsByTagName('summary')[0].firstChild):
        message['content'] = stringConstructor(item.getElementsByTagName('summary')[0])
      if (item.getElementsByTagName('updated') and item.getElementsByTagName('updated')[0].firstChild):
        message['date'] = item.getElementsByTagName('updated')[0].firstChild.nodeValue
      elif (item.getElementsByTagName('modified') and item.getElementsByTagName('modified')[0].firstChild):
        message['date'] = item.getElementsByTagName('modified')[0].firstChild.nodeValue
      message['md5'] = md5.new(str(message)).hexdigest()
      feed_data['items'].append(message)
  else:
    return {'title': 'This reader can\'t read this feed'}
  return feed_data


class HTMLCleaner(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.html = ''
    self.script = 0
  def handle_starttag(self, tag, attrs):
    if tag !='script' and tag !='input' and tag !='button' :
      self.html += '<'+tag+' '
      for attr in attrs:
        if not attr[0].startswith('on'):
          self.html += attr[0]+'=' +attr[1]+' '
      if tag=='a':
        self.html += 'target="_blank" '
      self.html += '>'
    else:
      self.script = 1
  def handle_data(self, data):
    if not self.script:
      self.html += data
  def handle_charref(self, name):
    self.html += '&#'+name+';'
  def handle_entityref(self, name):
    self.html += '&'+name+';'
  def handle_endtag(self, tag):
    if tag !='script' and tag !='input' and tag !='button' :
      self.html += '</'+tag+'>'
    else:
      self.script = 0
  def handle_startendtag(self, tag, attrs):
    if tag !='script' and tag !='input' and tag !='button' :
      self.html += '<'+tag+' '
      for attr in attrs:
        if not attr[0].startswith('on'):
          self.html += attr[0]+'=' +attr[1]+' '
      self.html += '/>'

def cleanHTML(string):
  html = ''
  parser= HTMLCleaner()
  parser.feed(string)
  return parser.html

def stringConstructor(domItem):
  string = ''
  for item in domItem.childNodes:
    if item.nodeType == 3:
      string = string + item.nodeValue
    elif item.nodeType == 1 and item.tagName != 'script' and item.tagName != 'input' and item.tagName != 'button':
      string = string + '<' + item.tagName + ' '
      if item.attributes:
        for att in item.attributes.items():
          if(not att[0].startswith('on')):
            string = string + att[0] + '=' + att[1] + ' '
      if item.tagName == 'a':
        string = string + 'target="_blank" '
      string = string + '>'
      string = string + stringConstructor(item)
      string = string + '</' + item.tagName + '>'
  return string