## Monday, October 29, 2007

### Flickr upload

I had not used Flickr in 18 months and when I wanted to use it today my script didn't work anymore since they have changed their API significantly in the meantime. Simply updating the perl module was not enough and I found the documentation the the web to be rather cryptic. Thus as a service to the community, this is what finally worked for me:

#!/usr/bin/perl

use Flickr::API;
use Flickr::Upload;

# Path to pictures to be uploaded
my $flickrdir = '/home/robert/fotos/flickr'; my$flickr_key = 'PUT YOUR KEY HERE';
my $flickr_secret = 'PUT YOUR SECRET HERE'; my$ua = Flickr::Upload->new( {'key' => $flickr_key, 'secret' =>$flickr_secret} );
$ua->agent( "perl upload" ); my$frob = getFrob( $ua ); my$url = $ua->request_auth_url('write',$frob);
print "1. Enter the following URL into your browser\n\n",
"$url\n\n", "2. Follow the instructions on the web page\n", "3. Hit when finished.\n\n"; <>; my$auth_token = getToken( $ua,$frob );
die "Failed to get authentication token!" unless defined $auth_token; print "Token is$auth_token\n";

opendir(FLICKR, $flickrdir) || die "Cannot open flickr directory$flickrdir: $!"; while(my$fn = readdir FLICKR){
next unless $fn =~ /[^\.]/; print "$flickrdir/$fn\n";$ua->upload(
'auth_token' => $auth_token, 'photo' => "$flickrdir/$fn", 'is_family' => 1 ) or print "Failed to upload$fn!\n";

}

sub getFrob {
my $ua = shift; my$res = $ua->execute_method("flickr.auth.getFrob"); return undef unless defined$res and $res->{success}; # FIXME: error checking, please. At least look for the node named 'frob'. return$res->{tree}->{children}->[1]->{children}->[0]->{content};
}

sub getToken {
my $ua = shift; my$frob = shift;

my $res =$ua->execute_method("flickr.auth.getToken",
{ 'frob' => $frob , 'perms' => 'write'} ); return undef unless defined$res and $res->{success}; # FIXME: error checking, please. return$res->{tree}->{children}->[1]->{children}->[1]->{children}->[0]->{content};
}

You need a key and a secret which you can generate here. Of course, you also need the module

perl -MCPAN -e shell
install Flickr::Upload

Then all you have to do is to copy (or link) all pictures to be uploaded to one directory (/home/robert/fotos/flickr in my case) and run the script. It gives you an URL you have to paste into your browser and then press ok and the upload begins.

#### 2 comments:

tom said...
This comment has been removed by a blog administrator.
Brian Kohles said...

Thanks for the great code example. It helped me to get my script up & running. But I did notice that you are going through the whole frob/auth_token creation each time the script is run. I found it better to separate that out into another script. And then just past the auth_token into the upload script. The modifed versions of your script that I'm using can be found at:
link