Debian Codegraph @

flickr_upload

raw
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Flickr::Upload;
6 use Getopt::Long;
7 use Pod::Usage;
8
9 # get your own key and secret from https://www.flickr.com/services/api/key.gne
10 my $api_key = '8dcf37880da64acfe8e30bb1091376b7';
11 my $not_so_secret = '2f3695d0562cdac7';
12
13 my %args;
14 my @tags = ();
15 my $help = 0;
16 my $man = 0;
17 my $auth = 0;
18 my $oauth = 0;
19 my $progress = 0;
20 my $check = 0;
21 my $report = 1;
22 my $reverse = 0;
23 my $photoset;
24 my @photo_ids;
25 my $upload_config = "$ENV{HOME}/.flickrrc";
26 my $oauth_config = "$ENV{HOME}/.flickroauth.st";
27
28 if( open CONFIG, "< $upload_config" ) {
29 while( <CONFIG> ) {
30 chomp;
31 s/#.*$//; # strip comments
32
33 next unless m/^\s*([a-z_]+)=(.+)\s*$/io;
34 if( $1 eq "key" ) {
35 $api_key = $2;
36 } elsif( $1 eq "secret" ) {
37 $not_so_secret = $2;
38 } elsif( $1 eq "progress" ) {
39 $progress = $2;
40 } elsif( $1 eq "report" ) {
41 $report = $2;
42 } else {
43 $args{$1} = $2;
44 }
45 }
46 close CONFIG;
47 }
48
49 GetOptions(
50 'help|?' => \$help,
51 'man' => \$man,
52 'tag=s' => \@tags,
53 'uri=s' => sub { $args{$_[0]} = $_[1] },
54 'auth_token=s' => sub { $args{$_[0]} = $_[1] },
55 'public=i' => sub { $args{is_public} = $_[1] },
56 'friend=i' => sub { $args{is_friend} = $_[1] },
57 'family=i' => sub { $args{is_family} = $_[1] },
58 'title=s' => sub { $args{$_[0]} = $_[1] },
59 'description=s' => sub { $args{$_[0]} = $_[1] },
60 'key=s' => \$api_key,
61 'secret=s' => \$not_so_secret,
62 'auth' => \$auth,
63 'oauth' => \$oauth,
64 'progress!' => \$progress,
65 'check' => \$check,
66 'report!' => \$report,
67 'option=s' => \%args,
68 'reverse' => \$reverse,
69 'set=s' => \$photoset,
70 ) or pod2usage(2);
71 pod2usage(1) if $help;
72 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
73
74 my $version = $Flickr::Upload::VERSION;
75
76 my $ua = Flickr::Upload->new( {'key' => $api_key, 'secret' => $not_so_secret} );
77 $ua->agent( "flickr_upload/$version" );
78 $ua->env_proxy();
79
80 if( $progress ) {
81 eval {
82 require Term::ProgressBar;
83 Term::ProgressBar->import(2.00);
84 };
85 if( $@ ) {
86 # Remove duplicate newline from error, and no need for two 'at line' messages
87 chomp(my $err = $@);
88 $err =~ s/\) at .*? line.*/)/;
89 die "Term::ProgressBar needs to be installed for `--progress' to work: (error from perl: $err)";
90 }
91 }
92
93 if( $auth ) {
94 # The user wants to authenticate. There's really no nice way to handle this.
95 # So we have to spit out a URL, then hang around or something until
96 # the user hits enter, then exchange the frob for a token, then tell the user what
97 # the token is and hope they care enough to stick it into .flickrrc so they
98 # only have to go through this crap once.
99
100 # 1. get a frob
101 my $frob = getFrob( $ua );
102
103 # 2. get a url for the frob
104 my $url = $ua->request_auth_url('write', $frob);
105
106 # 3. tell the user what to do with it
107 print "1. Enter the following URL into your browser\n\n",
108 "$url\n\n",
109 "2. Follow the instructions on the web page\n",
110 "3. Hit <Enter> when finished.\n\n";
111
112 # 4. wait for enter.
113 <STDIN>;
114
115 # 5. Get the token from the frob
116 my $auth_token = getToken( $ua, $frob );
117 die "Failed to get authentication token!" unless defined $auth_token;
118
119 # 6. Tell the user what they won.
120 print "Your authentication token for this application is\n\t\t",
121 $auth_token, "\n";
122
123 exit 0;
124 }
125
126 if($oauth) {
127 # See Flickr::API SYNOPSIS on OAuth authentication, upon which this is heavily based
128 $ua = Flickr::Upload->new({
129 consumer_key => $api_key,
130 consumer_secret => $not_so_secret
131 });
132 my $response = $ua->oauth_request_token({ 'callback' => 'https://127.0.0.1/' });
133 my %request_token;
134 if($response eq 'ok') {
135 my $uri = $ua->oauth_authorize_uri({ 'perms' => 'write' });
136
137 print "Please open this URL in your browser and follow the instructions:\n\n";
138 print "$uri\n\n";
139 print "When you authorize this app, you'll be directed to a dummy URL\n";
140 print "that contains a confirmation code. Paste that URL here.\n\n";
141 print "URL: ";
142 my $input = <STDIN>;
143 chomp $input;
144
145 my ($callback_returned, $token_received) = split /\?/, $input;
146 my @params = split /\&/, $token_received;
147 foreach my $pair (@params) {
148 my ($key,$val) = split(/=/,$pair);
149 $key =~ s/oauth_//;
150 $request_token{$key}=$val;
151
152 }
153 die "Bad OAuth token received! verifier => '$request_token{verifier}', token => '$request_token{token}'\n"
154 unless $request_token{verifier} =~ /^[0-9a-f]+$/ && $request_token{verifier} =~ /^[0-9a-f-]+$/;
155 }
156 else {
157 die "Unable to initiate OAuth authorization. Response from Flickr was: '$response'\n";
158 }
159 my $ac_rc = $ua->oauth_access_token(\%request_token);
160 if($ac_rc eq 'ok') {
161 print "Saving OAuth credentials to $oauth_config\n";
162 $ua->export_storable_config($oauth_config);
163 }
164 }
165
166 if(!exists $args{'auth_token'} && -r $oauth_config) {
167 $ua = Flickr::Upload->import_storable_config($oauth_config);
168 bless $ua, 'Flickr::Upload';
169 }
170
171 die "No auth token or OAuth credentials found.\nUse --auth or --oauth to generate credentials or --auth_token to specify a token.\n"
172 unless exists $args{'auth_token'} || $ua->is_oauth;
173
174 if( $check ) {
175 exit( checkToken( $ua, $args{api_key}, $args{auth_token} ) );
176 }
177
178 die "No image specified to upload.\n" unless @ARGV;
179
180 $args{'tags'} = join( " ", @tags ) if @tags;
181
182 # pipeline things by uploading first, waiting for photo ids second.
183 $args{'async'} = 1;
184 my %tickets;
185
186 $| = 1;
187
188 my @argv = $reverse ? reverse @ARGV : @ARGV;
189
190 while( my $photo = shift @argv ) {
191 my $rc;
192
193 if ($progress) {
194 $HTTP::Request::Common::DYNAMIC_FILE_UPLOAD = 1;
195 my $photo_size = (stat($photo))[7];
196 my $req = $ua->make_upload_request( 'photo' => $photo, %args );
197 my $gen = $req->content();
198 die unless ref($gen) eq "CODE";
199
200 my $progress = Term::ProgressBar->new({
201 name => $photo,
202 count => $photo_size,
203 ETA => 'linear',
204 });
205 $progress->minor(0);
206
207 my $state;
208 my $size;
209
210 $req->content(
211 sub {
212 my $chunk = &$gen();
213
214 $size += Flickr::Upload::file_length_in_encoded_chunk(\$chunk, \$state, $photo_size);
215 $progress->update($size);
216
217 return $chunk;
218 }
219 );
220
221 $rc = $ua->upload_request( $req );
222 } else {
223 print 'Uploading ', $photo, '...';
224 $rc = $ua->upload( 'photo' => $photo, %args );
225 }
226
227 # let the caller know how many images weren't uploaded
228 exit (1+@ARGV) unless defined $rc;
229
230 # check those later
231 $tickets{$rc} = $photo;
232
233 print "\n";
234 }
235
236 # check
237 if( $report ) {
238 print "Waiting for upload results (ctrl-C if you don't care)...\n";
239 do {
240 sleep 1;
241 my @checked = $ua->check_upload( keys %tickets );
242 for( @checked ) {
243 if( $_->{complete} == 0 ) {
244 # not done yet, don't do anythig
245 } elsif( $_->{complete} == 1 ) {
246 # uploaded, got photoid
247 print "$tickets{$_->{id}} is at " .
248 "https://www.flickr.com/tools/uploader_edit.gne?ids=$_->{photoid}\n";
249 push @photo_ids, $_->{photoid};
250 delete $tickets{$_->{id}};
251 } else {
252 print "$tickets{$_->{id}} failed to get photoid\n";
253 delete $tickets{$_->{id}};
254 }
255 }
256 } while( %tickets );
257 }
258
259 if ( $photoset ) {
260 if ( scalar(@photo_ids)==0 ) {
261 warn "Cannot create photoset '$photoset', no photos were successfully uploaded (or, you didn't wait for the upload verification)\n";
262 }
263 else {
264 my $primary_photo_id = shift @photo_ids;
265 warn "Creating photoset '$photoset', primary_photo_id = $primary_photo_id\n";
266 my $photoset_id = $ua->photosets_create (
267 title => $photoset,
268 primary_photo_id => $primary_photo_id,
269 'auth_token' => $args{'auth_token'} );
270 warn "Created photoset, id = $photoset_id\n";
271
272 while ( my $photo_id = shift @photo_ids ) {
273 warn "Adding photoID $photo_id to photoset $photoset...\n";
274 my $rc = $ua->photosets_addphoto (
275 photoset_id => $photoset_id,
276 photo_id => $photo_id,
277 'auth_token' => $args{'auth_token'} );
278 warn "Adding photoID $photo_id failed...\n" unless $rc;
279 }
280 }
281 }
282
283 exit 0;
284
285 sub response_tag {
286 my $t = shift;
287 my $name = shift;
288 my $tag = shift;
289
290 return undef unless defined $t and exists $t->{'children'};
291
292 for my $n ( @{$t->{'children'}} ) {
293 next unless $n->{'name'} eq $name;
294 next unless exists $n->{'children'};
295
296 for my $m (@{$n->{'children'}} ) {
297 next unless exists $m->{'name'}
298 and $m->{'name'} eq $tag
299 and exists $m->{'children'};
300
301 return $m->{'children'}->[0]->{'content'};
302 }
303 }
304 return undef;
305 }
306
307 sub getFrob {
308 my $ua = shift;
309
310 my $res = $ua->execute_method("flickr.auth.getFrob");
311 return undef unless defined $res and $res->{success};
312
313 # FIXME: error checking, please. At least look for the node named 'frob'.
314 return $res->{tree}->{children}->[1]->{children}->[0]->{content};
315 }
316
317 sub getToken {
318 my $ua = shift;
319 my $frob = shift;
320
321 my $res = $ua->execute_method("flickr.auth.getToken",
322 { 'frob' => $frob } );
323 return undef unless defined $res and $res->{success};
324
325 # FIXME: error checking, please.
326 return $res->{tree}->{children}->[1]->{children}->[1]->{children}->[0]->{content};
327 }
328
329 sub checkToken {
330 my $ua = shift;
331 my $key = shift;
332 my $token = shift;
333
334 my $res = $ua->execute_method("flickr.auth.checkToken",
335 {
336 'auth_token' => $token,
337 'api_key' => $key,
338 } );
339
340 # FIXME: this could be parsed, but I'm not going to get too fancy
341 print $res->decoded_content();
342
343 return 0;
344 }
345
346 __END__
347
348 =head1 NAME
349
350 flickr_upload - Upload photos to C<flickr.com>
351
352 =head1 SYNOPSIS
353
354 flickr_upload [--auth] --auth_token <auth_token> [--title <title>]
355 [--description description] [--public <0|1>] [--friend <0|1>]
356 [--family <0|1>] [--tag <tag>] [--option key=value] [--progress]
357 <photos...>
358
359 =head1 DESCRIPTION
360
361 Batch image uploader for the L<Flickr.com> service.
362
363 L<flickr_upload> may also be useful for generating authentication tokens
364 against other API keys/secrets (i.e. for embedding in scripts).
365
366 =head1 OPTIONS
367
368 =over 4
369
370 =item --auth
371
372 The C<--auth> flag will cause L<flickr_upload> to generate an
373 authentication token against it's API key and secret (or, if you want,
374 your own specific key and secret). This process requires the caller
375 to have a browser handy so they can cut and paste a url. The resulting
376 token should be kept somewhere like C<~/.flickrrc> since it's necessary
377 for actually uploading images.
378
379 =item --auth_token <auth_token>
380
381 Authentication token. You B<must> get an authentication token using
382 C<--auth> before you can upload images. See the L<EXAMPLES> section.
383
384 =item --oauth
385
386 Interactively perform OAuth authorization with Flickr. The user will get a URL to visit at Flickr at which Flickr::Upload must be granted write permissions. After granting permission, the user will be redirected to a dummy URL that contains an OAuth token and verifier. This user will paste this URL at the prompt, and L<flickr_upload> will save the resulting credentials in C<~/.flickroauth.st>.
387
388 =item --title <title>
389
390 Title to use on all the images. Optional.
391
392 =item --description <description>
393
394 Description to use on all the images. Optional.
395
396 =item --public <0|1>
397
398 Override the default C<is_public> access control. Optional.
399
400 =item --friend <0|1>
401
402 Override the default C<is_friend> access control. Optional.
403
404 =item --family <0|1>
405
406 Override the default C<is_family> access control. Optional.
407
408 =item --tag <tag>
409
410 Images are tagged with C<tag>. Multiple C<--tag> options can be given, or
411 you can just put them all into a single space-separated list. If you want
412 to define a tag with spaces, the quotes have to be part of the tag itself.
413 The following works in L<bash>:
414
415 flickr_upload --tag='"tag one"' --tag='"tag two"' image.jpg
416
417 =item --reverse
418
419 Reverse the list of supplied images. Useful when uploading contents of
420 directory with sorted filenames. Following example will upload the last
421 glob expanded file as first and vice versa. The last file will appear
422 first in target photo stream.
423
424 flickr_upload --reverse *.jpg
425
426 =item --set <NAME>
427
428 After successfully uploading all photos, create a new set named "NAME", and
429 add the photos into the set. One (random) photo will be the set's thumbnail.
430
431 =item --option key=value
432
433 Flickr periodically adds new features to the uploading API, and these are
434 almost always implemented as new key/value pairs. Rather than waiting for
435 a new L<Flickr::Upload> release, you can specify any of the upload
436 API's optional arguments using C<--option>.
437
438 flick_upload --option content_type=1 --tag='cats' two_cats.jpg
439
440 You may also use C<--option> rather than L<flickr_upload>'s command-line
441 options:
442
443 flickr_upload --option is_public=1 --option title='cats' two_cats.jpg
444
445 While Flickr may add new options at any time (see
446 L<https://www.flickr.com/services/api/upload.api.html> for the most up-to-date
447 list), currently known options include:
448
449 =over 4
450
451 =item --option safety_level=<1|2|3>
452
453 Override the default C<safety_level> notation.
454 Set to 1 for Safe, 2 for Moderate, or 3 for Restricted.
455 Refer to L<https://www.flickr.com/help/filters/>.
456
457 =item --option content_type=<1|2|3>
458
459 Override the default C<content_type> notation.
460 Set to 1 for Photo, 2 for Screenshot, or 3 for Art/Illustration.
461 Refer to L<https://www.flickr.com/help/filters/>.
462
463 =item --option hidden=<1|2>
464
465 Override the default C<hidden> notation.
466 Set to 1 to keep the photo in global search results, 2 to hide from public
467 earches.
468
469 =back
470
471 Note that options unknown to Flickr will result in undefined behaviour.
472
473 =item --check
474
475 Checks the authentication token via the flickr.auth.checkToken API call.
476 This can be used to verify API keys and credentials without trying to
477 upload an image. The output is the raw results of the API call.
478
479 =item --progress, --no-progress
480
481 Display a progress bar for each upload with L<Term::ProgressBar>. That
482 optional module will have to be installed on the system.
483
484 The default is not to display a progress bar. That can be changed in
485 the configuration file:
486
487 echo progress=1 >~/.flickrrc
488
489 =item --report, --no-report
490
491 Report the status of each upload ticket after uploading the batch via
492 L<Flickr::Upload's check_upload
493 method|Flickr::Upload/check_upload>. On by default. Checking the status can
494 be canceled by pressing ctrl-C.
495
496 The default is to display a report after each upload. That can be
497 changed in the configuration file:
498
499 echo report=0 >~/.flickrrc
500
501 =item --key <api_key>
502
503 =item --secret <secret>
504
505 Your own API key and secret. This is useful if you want to use
506 L<flickr_upload> in auth mode as a token generator. You need both C<key>
507 and C<secret>. Both C<key> and C<secret> can be placed in C<~/.flickrrc>,
508 allowing to mix L<flickr_upload> with your own scripts using the same
509 API key and authentication token. Getting your own API key and secret is
510 encouraged if you're tying L<flickr_upload> to some automated process.
511
512 Note that if you do get an authentication token against your own API key
513 and secret, you'll need to specify the key and secret along with the token
514 when uploading images. The default L<flickr_upload> API key and token won't
515 work in that case.
516
517 =item <photos...>
518
519 List of photos to upload. Uploading stops as soon as a failure is detected
520 during the upload. The script exit code will indicate the number of images
521 on the command line that were not uploaded. For each uploaded image, a
522 Flickr URL will be generated. L<flickr_upload> uses asynchronous uploading
523 so while the image is usually transferred fairly quickly, it might take
524 a while before it's actually available to users. L<flickr_upload> will
525 wait around for that to complete, but be aware that delays of upwards
526 of thirty minutes have (rarely) been know to occur.
527
528 =back
529
530 =head1 EXAMPLES
531
532 First, you need to get an authentication token. This is a requirement
533 driven by how Flickr manages third-party applications:
534
535 cpb@earth:~$ flickr_upload --auth
536 1. Enter the following URL into your browser
537
538 https://www.flickr.com/services/auth?api_sig=<...>&frob=<...>&perms=write&api_key=<...>
539
540 2. Follow the instructions on the web page
541 3. Hit <Enter> when finished.
542 Your authentication token for this application is
543 <token>
544
545 Unless you like typing long numbers on the command-line, you should
546 keep the C<<token>> somewhere handy, like a configuration file:
547
548 echo auth_token=<token> >~/.flickrrc
549
550 Uploading a bunch of images is then as easy as:
551
552 flickr_upload --tag 'dog' 'kernel in a window.jpg' 'sad in sunbeam.jpg'
553
554 =head1 CONFIGURATION
555
556 To avoid having to remember authentication tokens and such (or have them
557 show up in the process table listings), default values will be read from
558 C<$HOME/.flickrrc> if it exists. Any field defined there can, of course,
559 be overridden on the command line. For example:
560
561 # my config at $HOME/.flickrrc
562 auth_token=334455
563 is_public=0
564 is_friend=1
565 is_family=1
566
567 Note, however, that these defaults override the defaults you've assigned in
568 your Flickr profile. You may want to do all that stuff in one place.
569
570 =head1 BUGS
571
572 Error handling could be better.
573
574 =head1 AUTHORS
575
576 Christophe Beauregard, L<[email protected]>.
577
578 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason, <[email protected]>.
579
580 =head1 SEE ALSO
581
582 L<flickr.com>
583
584 L<Flickr::Upload>
585
586 L<https://www.flickr.com/services/api/>
587
588 L<https://www.flickr.com/help/filters/>
589
590 =cut