#!/usr/bin/python2.5

import codecs
import getopt
import simplejson
import os
import sys
import urllib2

# Must be run before django.template is imported
import django.conf
django.conf.settings.configure()

import django.template

SUBSCRIPTION_URL = 'http://www.google.com/reader/public/javascript-sub/user/%s/label/%s'

TEMPLATE = '''<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>DeWitt Clinton\'s Friends</title>
    <link rel="me" href="http://dewitt.unto.net/"/>
  </head>
  <body>
    <p class="vcard"><a href="http://dewitt.unto.net/" class="url" rel="me"><span class="fn">DeWitt Clinton</span></a>\'s friends and reading list:</p>
    <ul>
      {% for item in items %}
        <li class="vcard">
          <a href="{{ item.alternate.href }}" class="url" rel="friend"><span class="fn">{{ item.title }}</span></a>
        </li>
      {% endfor %}
    </ul>
  </body>
</html>
'''


def Usage():
  print 'Usage: %s [options] user_id label' % __file__
  print
  print '  This script fetches a users Google Reader subscriptions and outputs'
  print '  the result in a file as an HTML document'
  print
  print '  Required:'
  print '    user_id: The 20 digit unique id given by Google Reader'
  print '    label: Retrieve subscriptions only with this label.'
  print '  Options:'
  print '    --help -h : print this help'
  print '    --output : the output file [default: stdout]'

def FetchSubscriptions(user_id, label, output):
  assert user_id
  assert label
  url = SUBSCRIPTION_URL % (user_id, label)
  json = urllib2.urlopen(url)
  data = simplejson.load(json)
  template = django.template.Template(TEMPLATE)
  context = django.template.Context(data)
  html = template.render(context)
  if not output or output == '-':
    print html
  else:
    Save(html, output)

def Save(html, output):
  out = open(output, mode='w')
  out.write(html)
  out.close()

def main():
  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output='])
  except getopt.GetoptError:
    Usage()
    sys.exit(2)
  try:
    user_id = args[0]
    label = args[1]
  except:
    Usage()
    sys.exit(2)
  output = None
  for o, a in opts:
    if o in ("-h", "--help"):
      Usage()
      sys.exit(2)
    if o in ("-o", "--output"):
      output = a
  FetchSubscriptions(user_id, label, output)

if __name__ == "__main__":
  main()


