post-image-to-tumblr.pl 18.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
#!/usr/bin/perl
#
# Copyright (c) 2012-2017 Mathieu Roy <yeupou--gnu.org>
#        http://yeupou.wordpress.com/
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
#   USA
# 
# Will go into $content (default: ~/tmp/tumblr) where two subdirs exists: 
#    queue/ and over/
# It will take the first file in queue/ (pulled with git) and post it to
# tumblr using WWW::Tumblr from https://github.com/damog/www-tumblr
# 
# If the image metadata contains a legend field (Description, Comment, etc)
# with strings beginning with # then it will assume these are tags for tumblr.
# The image metadata will be rewritten and only this specific field kept.
# If tagrequired is included in your .tumblrrc, images without proper tag
# wont be posted.
#   (run with --check-images argument just to check whether all images
#   about to be posted contains a proper tag)
#
# It will always keep a pool of 5 files in queue/, so if you had several
# files from one same source at once, you'll still have enough files to
# randomize it.
#
# If there are only few messages in the queue, it will slow down post unless
# --always-post option is set.
#
# It requires your tumblr OAuth to be setup, for instance as described
# in http://ryanwark.com/blog/posting-to-the-tumblr-v2-api-in-perl using
# the counterpart script post-image-to-tumblr-init-auth.pl
#
# ~/.tumblrrc MUST be created containing at least:
#     base_url = BLOGNAME.tumblr.com
#     consumer_key=
#     consumer_secret= 
#     token=
#     token_secret=
# It could also take the following options:
#     content= (default being ~/tmp/tumblr)
#     debug
#     always_post
#     tags_required
#
# This script was designed to run as a daily cronjob.
#
# FACULTATIVE:
# 
# To randomize feed, you may just run, in queue/ the following:
#   for i in *; do mv "$i" `mktemp --dry-run --tmpdir=. -t XXXXXXX$i`; done
#
# To clean up alphabetically order stuff, you may also run the following: 
#   count=0 && for i in *; do count=`expr $count + 1` && case $count in [0-5]) prefix=A;; [6-9]) prefix=C;; 1[0-5]) prefix=E;; 1[5-9]) prefix=G;; 2[0-9]) prefix=I;; 3[0-9]) prefix=K;; 4[0-9]) prefix=M;; 5[0-9]) prefix=O;; *) prefix=Q;; esac && mv $i $prefix`echo $i | tr A-Z a-z`; done 
#   or, better, use qrename.pl provided also on the same git repository
#   as this.

use strict;
use locale;
use Getopt::Long;
use File::HomeDir;
use File::Copy;
use File::Temp qw(tempfile);
use POSIX qw(strftime);
use URI::Encode qw(uri_encode);
use Image::ExifTool;
use WWW::Tumblr;
use Encode qw(encode decode);
use Encode::Detect::Detector;
use HTML::Entities;
use Term::ANSIColor qw(:constants);


### INIT
my $git = "/usr/bin/git";
my $convert = "/usr/bin/convert";

my @metadata_fields = ("Description", "Comment", "ImageDescription", "UserComment");
my $images_types = "png|gif|jpg|jpeg";
my %images_max_size = ("gif" => "1048576");
my $debug = 0;
my $always_post = 0;
my $no_watermark = 0;
my $watermark_proportion = 5;
my $watermark_font = "/usr/share/fonts/truetype/ttf-liberation/LiberationSerif-Bold.ttf"; # sensible default for debian from package ttf-liberation
my $tags_required = 0;

my $unlink_temp = 1;
## First thing first, user read config
my $rc = File::HomeDir->my_home()."/.tumblrrc";
my $content = File::HomeDir->my_home()."/tmp/tumblr";
my ($tumblr_base_url, $tumblr_consumer_key, $tumblr_consumer_secret, $tumblr_token, $tumblr_token_secret);
my ($workaround_login, $workaround_dir, $workaround_url);
die "Unable to read $rc, exiting" unless -r $rc;
open(RCFILE, "< $rc");
while(<RCFILE>){
    # required oauth
    $tumblr_base_url = $1 if /^base_url\s?=\s?(\S*)\s*$/i;
    $tumblr_consumer_key = $1 if /^consumer_key\s?=\s?(\S*)\s*$/i;
    $tumblr_consumer_secret = $1 if /^consumer_secret\s?=\s?(\S*)\s*$/i;
    $tumblr_token = $1 if /^token\s?=\s?(\S*)\s*$/i;
    $tumblr_token_secret = $1 if /^token_secret\s?=\s?(\S*)\s*$/i;

    # handle options
    $content = $1 if /^content\s?=\s?(.*)$/i;
    $debug = 1 if /^debug$/i;
    $always_post = 1 if /^always_?post$/i;
    $tags_required = 1 if /^tags?_required$/i;
    $no_watermark = 1 if /^no_?watermark$/i;
    $watermark_font = $1 if /^watermark_font\s?=\s?(\S*)\s*$/i;

    # workaround, see below
    $workaround_login = $1 if /^workaround_login\s?=\s?(.*)$/i;
    $workaround_dir = $1 if /^workaround_dir\s?=\s?(.*)$/i;
    $workaround_url = $1 if /^workaround_url\s?=\s?(.*)$/i;
}
close(RCFILE);
die "Unable to determine oauth info required by Tumblr API v2 (found: base_url = $tumblr_base_url ; consumer_key = $tumblr_consumer_key ; consumer_secret = $tumblr_consumer_secret ; token = $tumblr_token ; token_secret = $tumblr_token_secret) after reading $rc, exiting" unless $tumblr_consumer_key and $tumblr_consumer_secret and $tumblr_token and $tumblr_token_secret;
my $queue = $content."/queue";
my $over = $content."/over";
my $backup = $content."/public-backup";

# command line args
my ($getopt,$help,$check,$export);

eval {
    $getopt = GetOptions("debug" => \$debug,
			 "help" => \$help,
			 "check-images" => \$check,
			 "export-images:i" => \$export,  # optional numeric arg,
			 "no-watermark" => \$no_watermark,
	                 "always-post" => \$always_post);
};
$git = "/bin/echo" if $debug;
$export = "all" if $export eq 0; # if export is set, assume it is required

# help if asked
if ($help) {
    print STDERR <<EOF;
Usage: $0 [OPTIONS]

      --check-images   Go through the queue and check whether images
                       are ready to be posted (with proper #Tag and
		       not exceding certain size depending on the
		       file type).
      --export-images  Go through the already posted images (over)
                       and produce export copies with #Tag watermark,
		       to be manually uploaded on an public backup area.
		       ($backup must exists)
		       Can provide a string like YYYY or YYYYMM to retrict
		       the export.
      --always-post    Not skipping post if the number of images in the
                       queue is low.
      --debug          Not doing any git commit or moving files, but do post.
		       

This script will go through $images_types files found 
in $content 
and post to Tumblr the first one found, using auth info 
from $rc.
The first #tag will be added as watermark, provided ImageMagick is
installed.

It is designed to run as a cronjob. You could also use qrename.pl
to keep a big queue clean.

In $rc, must be set:

       base_url        All these are set with ...-init-auth.pl
       consumer_key
       consumer_secret
       token
       token_secret 

Beside auth info, you can also set:

       always_post     Not skipping post if the number of images in the
                       queue is low.
       tags_required   Ignore files with no #Tag.
       no_watermark    Do not add #Tag watermark.
       watermark_font  Path to a font or a directory containing ONLY fonts
                       that ImageMagick can use.      

Author: yeupou\@gnu.org
       http://yeupou.wordpress.com/

EOF
exit(1);
    
}

### FUNCTIONS
sub debug {
    return unless $debug;
    my $color = RESET;
    $color = BRIGHT_GREEN if $_[1] > 0;
    $color = BRIGHT_YELLOW if $_[1] > 1;
    print $color, $_[0], RESET;
}

### RUN
# keep tempfile in debug mode
$unlink_temp = 0 if $debug;

# Enter working directory
chdir($content) or die "Unable to enter $content, exiting";
debug("chdir $content\n");

# Update content with git
system($git, "pull", "--quiet");

# Enter the source directory (normally the queue)
my $source = $queue;
$source = $over if $export;  
chdir($source) or die "Unable to enter $source, exiting";
debug("chdir $source\n");

# List images
# If none found, silently exit, as an empty queue/ is not an issue.
opendir(IMAGES, $source);
my (@images, $image);
while (defined(my $image = readdir(IMAGES))) {
    next if -d $image;
    next unless -r $image;
    next unless lc($image) =~ /\.($images_types)$/i;
    push(@images, $image);
}
closedir(IMAGES);
# end here if no image found at all
exit if scalar(@images) < 1;
# end here if we only have the pool we want to keep, unless we're just 
# checking files
exit if scalar(@images) < 6 and ! $check and ! $always_post;
# if we are low on images, slow down posting
if (scalar(@images) < 63 and ! $check and ! $always_post) {
    debug(scalar(@images)." images in queue: ");
    if (scalar(@images) < 32) {
	# only for one month, post only twice per week (monday and thursday)
	debug("post only twice per week, monday and thursday\n", 2);
	exit unless (localtime(time))[6] eq 1 or (localtime(time))[6] eq 4;
    } else {
	# otherwise, post every two days (even days)
	debug("post every two days\n", 2);
	exit unless ((localtime(time))[3] % 2) == 0;
    }   
}

# List available fonts
my @fonts;
if (-e $watermark_font) {
    # font path exists
    if (-d $watermark_font) {
	# and is directory: then pick randomly one file
	opendir(FONTS, $watermark_font);
	while (defined(my $font = readdir(FONTS))) {
	    next if $font =~ /^\./; # hidden
	    next unless -f "$watermark_font/$font"; # not a plain file
	    next unless -r "$watermark_font/$font"; # cannot be read
	    next if -z "$watermark_font/$font"; # is empty
	    # it would be best to actually check if it is a font type
	    # (like file command output)
	    push(@fonts, "$watermark_font/$font");
	    debug("Font found: $font\n");
	}
	closedir(FONTS);
    } elsif (-f $watermark_font and -r $watermark_font) {
	# otherwise it means it only point to a font file,
	# list it if readable
	push(@fonts, $watermark_font);
	debug("Single font found: $watermark_font\n");
    } else {
	debug("No font found.\n", 2);
    }
}

# Now go through the list of images in sorted order.
# (vars set in this loop are necessary below, so init them outside the 
# loop)
my ($image_info, $image_type, $image_info_kept, @image_tags, $exifTool, $altered_image, $altered_image_h, %per_day);
for (sort(@images)) {
    # Variable that we'll be used until the end
    $image = $_;
    
    # if we are doing export, we might require to work on a specific year/month/day:
    # for instance with --export=2016, we skip anything not with year 2016     
    if ($export && 
	$export ne "all" && 
	$export ne substr($image, 0, length($export))){
	debug("skip $image (--export=$export)\n");
	next;
    }

    # Otherwise proceed 
    debug("\n=== $_ ===\n", 1);
    
    # Clean vars that we need outside of this loop but should actually
    # be empty for each new image we re looking at
    $image_type = "";
    $image_info = "";
    $image_info_kept = "";
    @image_tags = ();

    # Extract tumblr tag from the selected image metadata
    $exifTool = new Image::ExifTool;
    $image_info = $exifTool->ImageInfo($image);
    if ($debug) { foreach (sort keys %$image_info) { debug("Found tag $_ => $$image_info{$_}\n"); }} 
    foreach my $field (@metadata_fields) {
	# Remember which metadata field was useful to find tags
	$image_info_kept = $field;

	# Ignore if missing one or more #tag
	next unless $$image_info{$field} =~ /(^|\s)#\S/;
	
	# Split it with the # sign
	foreach (split("#", $$image_info{$field})) {
	    # ignore blank before and after
	    s/^\s+//;
	    s/\s+$//;
	    # ignore full blank
	    next if /^$/;
	    # otherwise register it
	    debug("Register ($field) tag: $_ (".detect($_).")\n", 1);
	    if (detect($_)) {
		#    with accents, we get either
		#      HTTP::Message content must be bytes at 
		#      /usr/share/perl5/HTTP/Request/Common.pm line 94.
		#    or
		#      Net::OAuth warning: your OAuth message appears to contain
		#      some multi-byte characters that need to be decoded via
		#      Encode.pm or a PerlIO layer first.  This may result in an
		#      incorrect signature. at 
		#      /usr/share/perl5/Net/OAuth/Message.pm line 106.
		#
		#    a possible workaround is be encode as HTML entities 
		#    after decoding to perl internal format (encode_entities
		#    requires encoding to be identified and defined, so 
		#    it is best to simply decode first cf.
	        #    https://bugs.debian.org/787821 )  
		#
		# save the string in perl internal format		
		push(@image_tags, decode(detect($_),$_));
	    } else {
		push(@image_tags, $_);
	    }
	}
	
	# if we found some valid #tags, dont check any other field
	last if (scalar(@image_tags) > 0);
    }

    # Check for file size, if there are limit on this type
    # (this test wont prevent the script to attempt to post the file)
    $image_type = lc($1) if $image =~ /([^\.]*)$/;
    if (exists($images_max_size{$image_type})) {
	my $image_size = -s $image;
	print "$image is bigger ($image_size) than expected for $image_type.\n"
	    if $image_size > $images_max_size{$image_type};
    }

    # error if we cannot find a tag and that is required
    if ((scalar(@image_tags) < 1 and $tags_required)) { 
	print "$image has no valid tag.\n";
	# stop here unless we are just checking
	die "exiting" unless $check; 	
    } elsif ($debug) { 
	debug("$image '$image_info_kept' field is ".$$image_info{$image_info_kept}."\n"); 
    }
    
    # now prepare the image:  if we are just checking files
    # the rest is irrelevant
    next if $check;

    # if we are doing export, we might require to work on a specific
    # year/month/day 
    # for instance with --export=2016, we skip anything not with year 
    # 2016     
    if ($export && 
	$export ne "all" && 
	$export ne substr($image, 0, length($export))){
	next;
    }
    

    # Since we'll alter the image (possibly watermark and necessarily cleaned metadata), 
    # we'll work on a temporary one
    ($altered_image_h, $altered_image) = tempfile(TMPDIR => 1,
						  SUFFIX => ".".$image_type, 
						  UNLINK => $unlink_temp);
    binmode($altered_image_h); # image is binary data
    copy($image, $altered_image_h);
    debug("Altered version to be posted: $altered_image\n");

    # build and add PNG watermark, unless ask not to or if there is no known tag
    # and imagemagick is installed
    if (-x $convert and $no_watermark < 1 and scalar(@image_tags) > 0) {	
	my @convert_font_args;
	# pick watermark font if any
	srand();
	$watermark_font = $fonts[rand @fonts];
	push(@convert_font_args, "-font", $watermark_font);
	debug("Watermark font: $watermark_font\n");
	
	# build watermark (for now minimal checks, assume files are regular) 
	my ($watermark_h, $watermark) = tempfile(SUFFIX => ".png", 
						 UNLINK => $unlink_temp);
	binmode($watermark_h);
	my $watermark_width = $$image_info{"ImageWidth"};
	my $watermark_height = $watermark_proportion * $watermark_width / 100;
	system($convert,
	       "-size", $watermark_width."x".$watermark_height,
	       "-gravity", "NorthEast",
	       "-stroke", "#454545",
	       "-fill", "#c8c8c8",
	       "-background", "transparent",
	       "-strokewidth", "1",
	       @convert_font_args,
	       "label:#".@image_tags[0],
	       $watermark);
	debug("Watermark: $watermark\n");
	
	# add watermark
	system($convert,
	       $altered_image,
	       "-coalesce",
	       "-gravity", "NorthEast",
	       "null:",
	       $watermark,
	       "-layers", "composite",
	       $altered_image);
    } else  {
	debug("Watermarking skipped: ", 2);
	debug("$convert missing\n") unless -x $convert;
	debug("no_watermark set\n") unless $no_watermark < 1;
	debug("no tag found\n") unless scalar(@image_tags) > 0;
	push(@image_tags, "notag") unless scalar(@image_tags) > 0;
    }

    # Reset image tags: tumblr gives out meaningless error 400 for some image
    # depending on it's meta data. So we're forced to remove metadata
    debug("Reset $altered_image metada except field $image_info_kept set to ".$$image_info{$image_info_kept}."\n");
    $exifTool->SetNewValue('*');
    $exifTool->SetNewValue($image_info_kept, $$image_info{$image_info_kept});
    $exifTool->WriteInfo($altered_image);
    if ($debug) {
	$image_info = $exifTool->ImageInfo($altered_image);
	foreach (sort keys %$image_info) { debug("Final tag $_ => $$image_info{$_}\n"); }
    }

    # if we are posting one image, break out of the loop now
    last unless $export;
    
    # otherwise move the temporary file to the backup area, named
    # YYYYMMDD_perday-Tag-wm  
    my $day = substr($image, 0, 8);
    $per_day{$day}++;
 
    move($altered_image, "$backup/".$day."_".$per_day{$day}."-".join("_", @image_tags)."-wm.$image_type");
    debug("mv $altered_image "."$backup/".$day."_".$per_day{$day}."-".join("_", @image_tags)."-wm.$image_type\n", 1);

    # also rename the original for consistency (also make it obvious
    # what as been already exported)
    move($image, "$over/".$day."_".$per_day{$day}."-".join("_", @image_tags).".$image_type") unless $debug;
}
    
# everything beyond as to do with actual posting
exit(0) if $check or $export;

# Now set up API contact
my $tumblr = WWW::Tumblr->new(
    consumer_key => $tumblr_consumer_key,
    secret_key =>$tumblr_consumer_secret,
    token =>  $tumblr_token,
    token_secret => $tumblr_token_secret,
    );
my $blog = $tumblr->blog($tumblr_base_url);

# And post the image
#
# BASIC POST TEST
#($blog->post(type => 'text', body => 'Delete me, I am a damned test with no tags', title => 'test') or die $blog->error->code);
#($blog->post(type => 'text', body => 'Delete me, I am a damned test with '.join(',', @image_tags), title => 'test') or die $blog->error->code);

# Direct post (see history of this file for a version that post with url)

# temporary workaround with accentued characters: post with caption
# encoded to HTML entities
my $description = join(',', @image_tags);
my $description_field = 'tags';
$description_field = 'caption' if encode_entities($description) ne $description;

($blog->post(type => 'photo',
	     $description_field => encode_entities($description),
	     data => ["$altered_image"]) 
 or die $blog->error->code." while posting $altered_image with tags ".join(',', @image_tags));

print "It was not possible to set $description as tag, it has been set as caption.\n" if $description_field eq 'caption'; 

# If we get here, we can assume everything went well. 
# Move the unaltered file in over/ and commit to git
chdir($content);
my $today = strftime("%Y%m%d", localtime);
move("$queue/$image", "$over/$today-$image") unless $debug;
debug("mv $queue/$image $over/$today-$image\n");
system($git, "add", $over);
system($git, "commit", "--quiet", "-am", "Posted by post-image-to-tumblr.pl");
system($git, "push", "--quiet");

# EOF