# ------------------------------------------------------------------
# FlickrDown:
#   A script for downloading flickr images. 
#
# Setup:
#  1 - Get yourself a flickr API key:
#      http://www.flickr.com/services/api/misc.api_keys.html
#  2 - Get a copy of flickr.py:
#      http://jamesclarke.info/projects/flickr/
#  3 - Copy this script and flickr.py to some directory
#  4 - Change FLICKR_USER below to the user you want
#  5 - Run it as:
#        python flickrdown.py your_userid your_api_key output_directory
#
#  If you want it to grab your photos on a regular basis, setup a crontab.
#  Mine looks like this:
#
# 07 * * * * python /projects/flickrdown/flickrdown.py myID myAPIkey /www/mysite/album/flickr/
#
#  which means run this script at 7 minutes after every hour. Do a web
#  search on crontab to learn more about cron.
# 
# 
# Copyright Parand Tony Darugar (tdarugar at yahoo dot com)
# 
# BSD style license (http://www.opensource.org/licenses/bsd-license.php)
#
# Last Update: May 12th, 2006: Added username commandline option


import flickr
import urllib
import sys, os, datetime

DEFAULT_FLICKR_USER    = u'tdarugar'

FLICKR_USER    = sys.argv[1]
flickr.API_KEY = sys.argv[2]
outdir         = sys.argv[3]

user = flickr.people_findByUsername(FLICKR_USER)

photos = flickr.photos_search(user_id=user.id)

fp = open(outdir + "/index.html", "w")

fp.write("""<title>%s's album</title>""" % (FLICKR_USER) )

for p in photos:
    fp.write( """<a href="%s"><img src="%s" /></a>""" % ( p._Photo__id + ".jpg" , p._Photo__id + "_t.jpg") )
    thumb = p._Photo__id + "_t.jpg"

fp.write("""<p>Generated at %s</p>""" % (datetime.datetime.now()) )

fp.close()

for p in photos:
    # http://static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg
    url = "http://static.flickr.com/%s/%s_%s_o.jpg" % ( p.server, p._Photo__id, p.secret )
    urlt = "http://static.flickr.com/%s/%s_%s_s.jpg" % ( p.server, p._Photo__id, p.secret )
    print "Downloading %s from [%s]" % (p._Photo__title, url)

    thumbfile = outdir + "/" + p._Photo__id + "_t.jpg"
    imagefile = outdir + "/" + p._Photo__id + ".jpg"
    if not os.path.isfile( thumbfile ):
        urllib.urlretrieve(urlt, thumbfile)
    else:
	print "Skipping %s" % (thumbfile)
    if not os.path.isfile(imagefile):
        urllib.urlretrieve(url, imagefile)
    else:
	print "Skipping %s" % (imagefile)

