#!/usr/bin/python
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

import sys
import urllib

# From http://stuvel.eu/projects/flickrapi
import flickrapi

# To get these, sign up at: http://www.flickr.com/services/api/
flickr_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
flickr_secret = 'xxxxxxxxxxxxxxxx'

# Authenticate with flickr, or get existing cached token.
flickr = flickrapi.FlickrAPI(flickr_api_key, flickr_secret)
(token, frob) = flickr.get_token_part_one(perms='read')
if not token:
    raw_input("Authorize this script, then press 'Enter'");
flickr.get_token_part_two((token, frob))

csv_files = flickr.stats_getCSVFiles()
if csv_files.attrib['stat'] == 'fail':
    print 'flickr.stats.getCSVFiles failed'
    sys.exit(1)

u = urllib.URLopener()
for p in csv_files.getiterator('csv'):
    url = p.attrib['href']
    type = p.attrib['type']
    date = p.attrib['date']
    filename = "flickr-stats-%s-%s.csv" % (date, type)
    u.retrieve(url, filename)

