#!/usr/bin/python
# movies.py: Script to fetch movie ratings from del.icio.us
#            Trivially easy to modify to fetch other
#            del.icio.us bookmarks

# author :   Deepak Sarda
#            firstname.lastname@gmail.com
#
# config :   Some variables need to be set first
#
# NOTE:      This script uses the old del.icio.us API which has been
#            deprecated by them!
#
__author__      = 'Deepak Sarda'
__version__     = '1.0'
__copyright__   = '(c) 2005 Deepak Sarda'
__license__     = 'Public Domain'
__url__         = 'http://www.antrix.net/'

import urllib2, base64
from xml.dom import minidom

# Configure these variables as appropriate

# basedir is where the fetched bookmarks are stored
# as html formatted snippet.
# default is current directory
basedir = '.'
htmlfile = 'movie_ratings.html'

# del.icio.us username and password
username = 'johndoe'
password = 'janedoe'

# Change the request URI to fetch different bookmarks
# Refer del.icio.us documentation for details
request = urllib2.Request('http://del.icio.us/api/posts/recent?tag=movies&count=5')

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
request.add_header("Authorization", "Basic %s" % base64string)

xmlFile = urllib2.urlopen(request)
xmldoc = minidom.parse(xmlFile)
xmlFile.close()

posts = xmldoc.getElementsByTagName('post')

if posts:
    f = open('%s/%s' % (basedir, htmlfile), 'w')
    f.write('<ul>\n')

    for post in posts:
        movie = post.attributes['description'].value
        href = post.attributes['href'].value
        rating = post.attributes['extended'].value

        f.write('<li><a href="%s" title="%s rated %s">%s</a> [%s]</li>\n' %
                (href, movie, rating, movie, rating))
    f.write('\n</ul>\n')

    f.close()