#!/usr/bin/python

# RSS2Timeline - Translate feeds to JSON/Timeline format
#
# Demo: http://apassant.net/home/2006/07/rss2timeline/ 
# About: http://apassant.net/blog/2006/07/28/102-timeline-for-rss-feeds
#
# 2006 (c) Alexandre Passant <alex@passant.org>
# Licensed under GNU GPL
# http://www.gnu.org/licenses/gpl

import os, string, time
import feedparser
from mod_python import psp

def index(req) :
  """Index page"""
  vars = {
    "script": '',
    "body": psp.PSP(req, 'templates/index.html') 
  }
  return psp.PSP(req, 'templates/main.html', vars = vars)

def translate(req, uri=None) :
  """ Translates a feed to JSON/Timeline """
  if uri == None or string.strip(uri) == "" :
    return 'Please provide an uri'
  else :
    json = ''
    d = feedparser.parse(uri)
    e = d.encoding
    for entry in d.entries:
      link = entry.link.encode(e)
      title = string.join(entry.title.encode(e).replace("'", "\\'").split())
      content = string.join(entry.description.encode(e).replace("'", "\\'").split())
      date = time.strftime("%Y-%m-%dT%H:%M:%S", entry.updated_parsed)
      json += """  {
    'start' : '%s',
    'title' : '%s',
    'description' : '%s',
    'link' : '%s',
  },
""" %(date, title, content, link)
    return """
{
  'dateTimeFormat' : 'iso8601',
  'events' : [
  %s
  ]
}
""" %json[:-2]

def timeline(req, uri=None) :
  """ Show RSS into Timeline """
  if uri == None or not string.strip(uri) :
    return 'Please provide an uri'
  else : 
    d = feedparser.parse(uri)
    script_vars = {
      "uri" : uri,
      "date" : time.strftime("%b %d %Y 00:00:00 GMT", d.feed.updated_parsed)
    }
    vars = { 
      "script": psp.PSP(req, 'templates/timeline.js', vars = script_vars), 
      "body": psp.PSP(req, 'templates/timeline.html', vars = script_vars)
    }
    return psp.PSP(req, 'templates/main.html', vars = vars)
