# RSS WikiMacro for Trac
#
# Copyright(C) 2005 Masato Taruishi <taru@valinux.co.jp>
#              2007 Modified by Taku YASUI <tach@debian.or.jp>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301,USA.

import sys
from xml.dom.ext.reader import Sax2
from xml.dom import minidom
import urllib

def getText( elm, tag ):
  list = elm.childNodes
  for n in elm.childNodes:
    if n.nodeName == tag:
      c = n.childNodes[0]
      return c.data
  return None

def unescape(s):
  s = s.replace("&lt;", "<")
  s = s.replace("&gt;", ">")
  # this has to be last:
  s = s.replace("&amp;", "&")
  return s

def execute( hdf, args, env ):
  stream = urllib.urlopen(unescape(args))
  #stream = urllib.urlopen(unescape(args), proxies = {'http': 'http://localhost:8080/'})
  dom = minidom.parseString(stream.read())
  elms = dom.getElementsByTagName("item")
  title = dom.getElementsByTagName("title")
  html = u"<div><h4 style=\"margin-bottom:0px;\">%s</h4><ul style=\"margin-top:0; padding-left:2em;\">" % title[0].childNodes[0].data
  count = 0
  for elm in elms:
    if count > 10:
      break
    count += 1
    title = getText(elm, "title")
    link = getText(elm, "link")
    date = getText(elm, "pubDate")
    if link != None:
      html += u"<li><a href=\"%s\">%s</a>" % (link, title)
#      if date != None:
#        html += " - " + date;
  return html.encode('utf-8') + "</ul></div>"

if __name__ == '__main__':
  print execute( None, sys.argv[1], None )

