# -*- coding: utf-8 -*-
# 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 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>"
 
from trac.core import *

import inspect
from trac.wiki.api import IWikiMacroProvider
from genshi.builder import tag

from trac.util.text import to_unicode

class RSS(Component):
    """RSSを表示するためのマクロです:
    {{{
    [[RSS(url)]]
    }}}
    """

    implements(IWikiMacroProvider)

    def expand_macro(self, formatter, name, args):
        return execute(None,args,None)

    def get_macros(self):
        """Yield the name of the macro based on the class name."""
        name = self.__class__.__name__
        if name.endswith('Macro'):
            name = name[:-5]
        yield name

    def get_macro_description(self, name):
        """Return the subclass's docstring."""
        return to_unicode(inspect.getdoc(self.__class__))

    def parse_macro(self, parser, name, content):
        raise NotImplementedError

from trac.test import EnvironmentStub

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