981ddb753d6510edce449841f2db11eb8185b5bb
[xscreensaver] / driver / xscreensaver-getimage-file
1 #!/usr/bin/perl -w
2 # Copyright © 2001-2016 Jamie Zawinski <jwz@jwz.org>.
3 #
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation.  No representations are made about the suitability of this
9 # software for any purpose.  It is provided "as is" without express or 
10 # implied warranty.
11 #
12 # This program chooses a random file from under the given directory, and
13 # prints its name.  The file will be an image file whose dimensions are
14 # larger than a certain minimum size.
15 #
16 # If the directory is a URL, it is assumed to be an RSS or Atom feed.
17 # The images from that feed will be downloaded, cached, and selected from
18 # at random.  The feed will be re-polled periodically, as needed.
19 #
20 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
21 # the image to manipulate by running the "xscreensaver-getimage" program.
22 #
23 # Under X11, the "xscreensaver-getimage" program invokes this script,
24 # depending on the value of the "chooseRandomImages" and "imageDirectory"
25 # settings in the ~/.xscreensaver file (or .../app-defaults/XScreenSaver).
26 # The screen savers invoke "xscreensaver-getimage" via utils/grabclient.c,
27 # which then invokes this script.
28 #
29 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
30 # directly from utils/grabclient.c.
31 #
32 # Created: 12-Apr-01.
33
34 require 5;
35 #use diagnostics;       # Fails on some MacOS 10.5 systems
36 use strict;
37
38 use POSIX;
39 use Fcntl;
40
41 use Fcntl ':flock'; # import LOCK_* constants
42
43 use POSIX ':fcntl_h';                           # S_ISDIR was here in Perl 5.6
44 import Fcntl ':mode' unless defined &S_ISUID;   # but it is here in Perl 5.8
45         # but in Perl 5.10, both of these load, and cause errors!
46         # So we have to check for S_ISUID instead of S_ISDIR?  WTF?
47
48 use bytes;  # Larry can take Unicode and shove it up his ass sideways.
49             # Perl 5.8.0 causes us to start getting incomprehensible
50             # errors about UTF-8 all over the place without this.
51
52 use Digest::MD5 qw(md5_base64);
53
54 # Some Linux systems don't install LWP by default!
55 # Only error out if we're actually loading a URL instead of local data.
56 BEGIN { eval 'use LWP::Simple;' }
57
58
59 my $progname = $0; $progname =~ s@.*/@@g;
60 my ($version) = ('$Revision: 1.40 $' =~ m/\s(\d[.\d]+)\s/s);
61
62 my $verbose = 0;
63
64 # Whether to use MacOS X's Spotlight to generate the list of files.
65 # When set to -1, uses Spotlight if "mdfind" exists.
66 #
67 # (In my experience, this isn't actually any faster, and might not find
68 # everything if your Spotlight index is out of date, which happens often.)
69 #
70 my $use_spotlight_p = 0;
71
72 # Whether to cache the results of the last run.
73 #
74 my $cache_p = 1;
75
76 # Regenerate the cache if it is older than this many seconds.
77 #
78 my $cache_max_age = 60 * 60 * 3;   # 3 hours
79
80 # Re-poll RSS/Atom feeds when local copy is older than this many seconds.
81 #
82 my $feed_max_age = $cache_max_age;
83
84
85 # This matches files that we are allowed to use as images (case-insensitive.)
86 # Anything not matching this is ignored.  This is so you can point your
87 # imageDirectory at directory trees that have things other than images in
88 # them, but it assumes that you gave your images sensible file extensions.
89 #
90 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
91                        'tif', 'tiff', 'xbm', 'xpm');
92 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
93
94 # This matches file extensions that might occur in an image directory,
95 # and that are never used in the name of a subdirectory.  This is an
96 # optimization that prevents us from having to stat() those files to
97 # tell whether they are directories or not.  (It speeds things up a
98 # lot.  Don't give your directories stupid names.)
99 #
100 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
101    'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
102    'nef', 'pbm', 'pdf', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh', 'shtml',
103    'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
104 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
105
106
107 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
108 # this is so that you can use an image directory that contains both big
109 # images and thumbnails, and have it only select the big versions.
110 #
111 my $min_image_width  = 255;
112 my $min_image_height = 255;
113
114 my @all_files = ();         # list of "good" files we've collected
115 my %seen_inodes;            # for breaking recursive symlink loops
116
117 # For diagnostic messages:
118 #
119 my $dir_count = 1;          # number of directories seen
120 my $stat_count = 0;         # number of files/dirs stat'ed
121 my $skip_count_unstat = 0;  # number of files skipped without stat'ing
122 my $skip_count_stat = 0;    # number of files skipped after stat
123
124 sub find_all_files($);
125 sub find_all_files($) {
126   my ($dir) = @_;
127
128   print STDERR "$progname:  + reading dir $dir/...\n" if ($verbose > 1);
129
130   my $dd;
131   if (! opendir ($dd, $dir)) {
132     print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
133     return;
134   }
135   my @files = readdir ($dd);
136   closedir ($dd);
137
138   my @dirs = ();
139
140   foreach my $file (@files) {
141     next if ($file =~ m/^\./);      # silently ignore dot files/dirs
142
143     if ($file =~ m/[~%\#]$/) {      # ignore backup files (and dirs...)
144       $skip_count_unstat++;
145       print STDERR "$progname:  - skip file  $file\n" if ($verbose > 1);
146     }
147
148     $file = "$dir/$file";
149
150     if ($file =~ m/$good_file_re/io) {
151       #
152       # Assume that files ending in .jpg exist and are not directories.
153       #
154       push @all_files, $file;
155       print STDERR "$progname:  - found file $file\n" if ($verbose > 1);
156
157     } elsif ($file =~ m/$nondir_re/io) {
158       #
159       # Assume that files ending in .html are not directories.
160       #
161       $skip_count_unstat++;
162       print STDERR "$progname: -- skip file  $file\n" if ($verbose > 1);
163
164     } else {
165       #
166       # Now we need to stat the file to see if it's a subdirectory.
167       #
168       # Note: we could use the trick of checking "nlinks" on the parent
169       # directory to see if this directory contains any subdirectories,
170       # but that would exclude any symlinks to directories.
171       #
172       my @st = stat($file);
173       my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
174           $atime,$mtime,$ctime,$blksize,$blocks) = @st;
175
176       $stat_count++;
177
178       if ($#st == -1) {
179         if ($verbose) {
180           my $ll = readlink $file;
181           if (defined ($ll)) {
182             print STDERR "$progname: + dangling symlink: $file -> $ll\n";
183           } else {
184             print STDERR "$progname: + unreadable: $file\n";
185           }
186         }
187         next;
188       }
189
190       next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
191       $seen_inodes{"$dev:$ino"} = 1;
192
193       if (S_ISDIR($mode)) {
194         push @dirs, $file;
195         $dir_count++;
196         print STDERR "$progname:  + found dir  $file\n" if ($verbose > 1);
197
198       } else {
199         $skip_count_stat++;
200         print STDERR "$progname:  + skip file  $file\n" if ($verbose > 1);
201       }
202     }
203   }
204
205   foreach (@dirs) {
206     find_all_files ($_);
207   }
208 }
209
210
211 sub spotlight_all_files($) {
212   my ($dir) = @_;
213
214   my @terms = ();
215   # "public.image" matches all (indexed) images, including Photoshop, etc.
216 #  push @terms, "kMDItemContentTypeTree == 'public.image'";
217   foreach (@good_extensions) {
218
219     # kMDItemFSName hits the file system every time: much worse than "find".
220 #    push @terms, "kMDItemFSName == '*.$_'";
221
222     # kMDItemDisplayName matches against the name in the Spotlight index,
223     # but won't find files that (for whatever reason) didn't get indexed.
224     push @terms, "kMDItemDisplayName == '*.$_'";
225   }
226
227   $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi;  # quote for sh
228   my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
229
230   print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
231   @all_files = split (/[\r\n]+/, `$cmd`);
232 }
233
234
235 # If we're using cacheing, read the cache file and return its contents,
236 # if any.  This also holds an exclusive lock on the cache file, which 
237 # has the additional benefit that if two copies of this program are
238 # running at once, one will wait for the other, instead of both of
239 # them spanking the same file system at the same time.
240 #
241 my $cache_fd = undef;
242 my $cache_file_name = undef;
243 my $read_cache_p = 0;
244
245 sub read_cache($) {
246   my ($dir) = @_;
247
248   return () unless ($cache_p);
249
250   my $dd = "$ENV{HOME}/Library/Caches";    # MacOS location
251   if (-d $dd) {
252     $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
253   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
254     $dd = "$ENV{HOME}/.cache/xscreensaver";
255     if (! -d $dd) { mkdir ($dd) || error ("mkdir $dd: $!"); }
256     $cache_file_name = "$dd/xscreensaver-getimage.cache"
257   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/.tmp/ exists, use it.
258     $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
259   } else {
260     $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
261   }
262
263   print STDERR "$progname: awaiting lock: $cache_file_name\n"
264     if ($verbose > 1);
265
266   my $file = $cache_file_name;
267   open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
268   flock ($cache_fd, LOCK_EX)     || error ("unable to lock $file: $!");
269   seek ($cache_fd, 0, 0)         || error ("unable to rewind $file: $!");
270
271   my $mtime = (stat($cache_fd))[9];
272
273   if ($mtime + $cache_max_age < time) {
274     print STDERR "$progname: cache is too old\n" if ($verbose);
275     return ();
276   }
277
278   my $odir = <$cache_fd>;
279   $odir =~ s/[\r\n]+$//s if defined ($odir);
280   if (!defined ($odir) || ($dir ne $odir)) {
281     print STDERR "$progname: cache is for $odir, not $dir\n"
282       if ($verbose && $odir);
283     return ();
284   }
285
286   my @files = ();
287   while (<$cache_fd>) { 
288     s/[\r\n]+$//s;
289     push @files, "$odir/$_";
290   }
291
292   print STDERR "$progname: " . ($#files+1) . " files in cache\n"
293     if ($verbose);
294
295   $read_cache_p = 1;
296   return @files;
297 }
298
299
300 sub write_cache($) {
301   my ($dir) = @_;
302
303   return unless ($cache_p);
304
305   # If we read the cache, just close it without rewriting it.
306   # If we didn't read it, then write it now.
307
308   if (! $read_cache_p) {
309
310     truncate ($cache_fd, 0) ||
311       error ("unable to truncate $cache_file_name: $!");
312     seek ($cache_fd, 0, 0) ||
313       error ("unable to rewind $cache_file_name: $!");
314
315     if ($#all_files >= 0) {
316       print $cache_fd "$dir\n";
317       foreach (@all_files) {
318         my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
319         $f =~ s@^\Q$dir/@@so || die;  # remove $dir from front
320         print $cache_fd "$f\n";
321       }
322     }
323
324     print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
325       if ($verbose);
326   }
327
328   flock ($cache_fd, LOCK_UN) ||
329     error ("unable to unlock $cache_file_name: $!");
330   close ($cache_fd);
331   $cache_fd = undef;
332 }
333
334
335 sub html_unquote($) {
336   my ($h) = @_;
337
338   # This only needs to handle entities that occur in RSS, not full HTML.
339   my %ent = ( 'amp' => '&', 'lt' => '<', 'gt' => '>', 
340               'quot' => '"', 'apos' => "'" );
341   $h =~ s/(&(\#)?([[:alpha:]\d]+);?)/
342     {
343      my ($o, $c) = ($1, $3);
344      if (! defined($2)) {
345        $c = $ent{$c};                   # for &lt;
346      } else {
347        if ($c =~ m@^x([\dA-F]+)$@si) {  # for &#x41;
348          $c = chr(hex($1));
349        } elsif ($c =~ m@^\d+$@si) {     # for &#65;
350          $c = chr($c);
351        } else {
352          $c = undef;
353        }
354      }
355      ($c || $o);
356     }
357    /gexi;
358   return $h;
359 }
360
361
362
363 # Figure out what the proxy server should be, either from environment
364 # variables or by parsing the output of the (MacOS) program "scutil",
365 # which tells us what the system-wide proxy settings are.
366 #
367 sub set_proxy($) {
368   my ($ua) = @_;
369
370   my $proxy_data = `scutil --proxy 2>/dev/null`;
371   foreach my $proto ('http', 'https') {
372     my ($server) = ($proxy_data =~ m/\b${proto}Proxy\s*:\s*([^\s]+)/si);
373     my ($port)   = ($proxy_data =~ m/\b${proto}Port\s*:\s*([^\s]+)/si);
374     my ($enable) = ($proxy_data =~ m/\b${proto}Enable\s*:\s*([^\s]+)/si);
375
376     if ($server && $enable) {
377       # Note: this ignores the "ExceptionsList".
378       my $proto2 = 'http';
379       $ENV{"${proto}_proxy"} = ("${proto2}://" . $server .
380                                 ($port ? ":$port" : "") . "/");
381       print STDERR "$progname: MacOS $proto proxy: " .
382                    $ENV{"${proto}_proxy"} . "\n"
383         if ($verbose > 2);
384     }
385   }
386
387   $ua->env_proxy();
388 }
389
390
391 sub init_lwp() {
392   if (! defined ($LWP::Simple::ua)) {
393     error ("\n\n\tPerl is broken. Do this to repair it:\n" .
394            "\n\tsudo cpan LWP::Simple\n");
395   }
396   set_proxy ($LWP::Simple::ua);
397 }
398
399
400 # Returns a list of the image enclosures in the RSS or Atom feed.
401 # Elements of the list are references, [ "url", "guid" ].
402 #
403 sub parse_feed($);
404 sub parse_feed($) {
405   my ($url) = @_;
406
407   init_lwp();
408   $LWP::Simple::ua->agent ("$progname/$version");
409   $LWP::Simple::ua->timeout (10);  # bail sooner than the default of 3 minutes
410
411   my $body = (LWP::Simple::get($url) || '');
412
413   if ($body !~ m@^<\?xml\s@si) {
414     # Not an RSS/Atom feed.  Try RSS autodiscovery.
415
416     # (Great news, everybody: Flickr no longer provides RSS for "Sets",
417     # only for "Photostreams", and only the first 20 images of those.
418     # Thanks, assholes.)
419
420     error ("null response: $url")
421       if ($body =~ m/^\s*$/s);
422
423     error ("not an RSS or Atom feed, or HTML: $url")
424       unless ($body =~ m@<(HEAD|BODY|A|IMG)\b@si);
425
426     # Find the first <link> with RSS or Atom in it, and use that instead.
427
428     $body =~ s@<LINK\s+([^<>]*)>@{
429       my $p = $1;
430       if ($p =~ m! \b REL  \s* = \s* ['"]? alternate \b!six &&
431           $p =~ m! \b TYPE \s* = \s* ['"]? application/(atom|rss) !six &&
432           $p =~ m! \b HREF \s* = \s* ['"]  ( [^<>'"]+ ) !six
433          ) {
434         my $u2 = html_unquote ($1);
435         if ($u2 =~ m!^/!s) {
436           my ($h) = ($url =~ m!^([a-z]+://[^/]+)!si);
437           $u2 = "$h$u2";
438         }
439         print STDERR "$progname: found feed: $u2\n"
440           if ($verbose);
441         return parse_feed ($u2);
442       }
443       '';
444     }@gsexi;
445
446     error ("no RSS or Atom feed for HTML page: $url");
447   }
448
449
450   $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
451   my @items = split(/\001/, $body);
452   shift @items;
453
454   my @imgs = ();
455   my %ids;
456
457   foreach my $item (@items) {
458     my $iurl = undef;
459     my $id = undef;
460
461     # First look for <link rel="enclosure" href="...">
462     #
463     if (! $iurl) {
464       $item =~ s!(<LINK[^<>]*>)!{
465         my $link = $1;
466         my ($rel)  = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
467         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
468         my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
469
470         if ($rel && lc($rel) eq 'enclosure') {
471           if ($type) {
472             $href = undef unless ($type =~ m@^image/@si);  # omit videos
473           }
474           $iurl = html_unquote($href) if $href;
475         }
476         $link;
477       }!gsexi;
478     }
479
480     # Then look for <media:content url="...">
481     #
482     if (! $iurl) {
483       $item =~ s!(<MEDIA:CONTENT[^<>]*>)!{
484         my $link = $1;
485         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
486         $iurl = html_unquote($href) if $href;
487         $link;
488       }!gsexi;
489     }
490
491     # Then look for <enclosure url="..."/> 
492     #
493     if (! $iurl) {
494       $item =~ s!(<ENCLOSURE[^<>]*>)!{
495         my $link = $1;
496         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
497         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
498         $iurl = html_unquote($href)
499           if ($href && $type && $type =~ m@^image/@si);  # omit videos
500         $link;
501       }!gsexi;
502     }
503
504     # Ok, maybe there's an image in the <url> field?
505     #
506     if (! $iurl) {
507       $item =~ s!((<URL\b[^<>]*>)([^<>]*))!{
508         my ($all, $u2) = ($1, $3);
509         $iurl = html_unquote($u2) if ($u2 =~ m/$good_file_re/io);
510         $all;
511       }!gsexi;
512     }
513
514     # Then look for <description>... with an <img src="..."> inside.
515     #
516     if (! $iurl) {
517       $item =~ s!(<description[^<>]*>.*?</description>)!{
518         my $desc = $1;
519         $desc = html_unquote($desc);
520         my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
521         $iurl = $href if ($href);
522         $desc;
523       }!gsexi;
524     }
525
526     # Could also do <content:encoded>, but the above probably covers all
527     # of the real-world possibilities.
528
529
530     # Find a unique ID for this image, to defeat image farms.
531     # First look for <id>...</id>
532     ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
533
534     # Then look for <guid isPermaLink=...> ... </guid>
535     ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
536
537     # Then look for <link> ... </link>
538     ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
539
540
541     if ($iurl) {
542       $id = $iurl unless $id;
543       my $o = $ids{$id};
544       if (! $o) {
545         $ids{$id} = $iurl;
546         my @P = ($iurl, $id);
547         push @imgs, \@P;
548       } elsif ($iurl ne $o) {
549         print STDERR "$progname: WARNING: dup ID \"$id\"" .
550                      " for \"$o\" and \"$iurl\"\n";
551       }
552     }
553   }
554
555   return @imgs;
556 }
557
558
559 # Like md5_base64 but uses filename-safe characters.
560 #
561 sub md5_file($) {
562   my ($s) = @_;
563   $s = md5_base64($s);
564   $s =~ s@[/]@_@gs;
565   $s =~ s@[+]@-@gs;
566   return $s;
567 }
568
569
570 # Given the URL of an image, download it into the given directory
571 # and return the file name.
572 #
573 sub download_image($$$) {
574   my ($url, $uid, $dir) = @_;
575
576   my $url2 = $url;
577   $url2 =~ s/\#.*$//s;          # Omit search terms after file extension
578   $url2 =~ s/\?.*$//s;
579   my ($ext) = ($url2 =~ m@\.([a-z\d]+)$@si);
580
581   # If the feed hasn't put a sane extension on their URLs, nothing's going
582   # to work. This code assumes that file names have extensions, even the
583   # ones in the cache directory.
584   #
585   if (! $ext) {
586     print STDERR "$progname: skipping extensionless URL: $url\n"
587       if ($verbose > 1);
588     return undef;
589   }
590
591   # Don't bother downloading files that we will reject anyway.
592   #
593   if (! ($url2 =~ m/$good_file_re/io)) {
594     print STDERR "$progname: skipping non-image URL: $url\n"
595       if ($verbose > 1);
596     return undef;
597   }
598
599   my $file = md5_file ($uid);
600   $file .= '.' . lc($ext) if $ext;
601
602   # Don't bother doing If-Modified-Since to see if the URL has changed.
603   # If we have already downloaded it, assume it's good.
604   if (-f "$dir/$file") {
605     print STDERR "$progname: exists: $dir/$file for $uid / $url\n" 
606       if ($verbose > 1);
607     return $file;
608   }
609
610   # Special-case kludge for Flickr:
611   # Their RSS feeds sometimes include only the small versions of the images.
612   # So if the URL ends in one of the "small-size" letters, change it to "b".
613   #
614   #     _o  orig,  1600 +
615   #     _k  large, 2048 max
616   #     _h  large, 1600 max
617   #     _b  large, 1024 max
618   #     _c  medium, 800 max
619   #     _z  medium, 640 max
620   #     ""  medium, 500 max
621   #     _n  small,  320 max
622   #     _m  small,  240 max
623   #     _t  thumb,  100 max
624   #     _q  square, 150x150
625   #     _s  square,  75x75
626   #
627   $url =~ s@_[sqtmnzc](\.[a-z]+)$@_b$1@si
628     if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
629
630   print STDERR "$progname: downloading: $dir/$file for $uid / $url\n" 
631     if ($verbose > 1);
632   init_lwp();
633   $LWP::Simple::ua->agent ("$progname/$version");
634   my $status = LWP::Simple::mirror ($url, "$dir/$file");
635   if (!LWP::Simple::is_success ($status)) {
636     print STDERR "$progname: error $status: $url\n";   # keep going
637   }
638
639   return $file;
640 }
641
642
643 sub mirror_feed($) {
644   my ($url) = @_;
645
646   if ($url !~ m/^https?:/si) {   # not a URL: local directory.
647     return (undef, $url);
648   }
649
650   my $dir = "$ENV{HOME}/Library/Caches";    # MacOS location
651   if (-d $dir) {
652     $dir = "$dir/org.jwz.xscreensaver.feeds";
653   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
654     $dir = "$ENV{HOME}/.cache/xscreensaver";
655     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
656     $dir .= "/feeds";
657     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
658   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/.tmp/ exists, use it.
659     $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
660   } else {
661     $dir = "$ENV{HOME}/.xscreensaver-feeds";
662   }
663
664   if (! -d $dir) {
665     mkdir ($dir) || error ("mkdir $dir: $!");
666     print STDERR "$progname: mkdir $dir/\n" if ($verbose);
667   }
668
669   # MD5 for directory name to use for cache of a feed URL.
670   $dir .= '/' . md5_file ($url);
671
672   if (! -d $dir) {
673     mkdir ($dir) || error ("mkdir $dir: $!");
674     print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
675   }
676
677   # At this point, we have the directory corresponding to this URL.
678   # Now check to see if the files in it are up to date, and download
679   # them if not.
680
681   my $stamp = '.timestamp';
682   my $lock = "$dir/$stamp";
683
684   print STDERR "$progname: awaiting lock: $lock\n"
685     if ($verbose > 1);
686
687   my $mtime = ((stat($lock))[9]) || 0;
688
689   my $lock_fd;
690   open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
691   flock ($lock_fd, LOCK_EX)     || error ("unable to lock $lock: $!");
692   seek ($lock_fd, 0, 0)         || error ("unable to rewind $lock: $!");
693
694   my $poll_p = ($mtime + $feed_max_age < time);
695
696   # --no-cache cmd line arg means poll again right now.
697   $poll_p = 1 unless ($cache_p);
698
699   # Even if the cache is young, make sure there is at least one file,
700   # and re-check if not.
701   #
702   if (! $poll_p) {
703     my $count = 0;
704     opendir (my $dirh, $dir) || error ("$dir: $!");
705     foreach my $f (readdir ($dirh)) {
706       next if ($f =~ m/^\./s);
707       $count++;
708       last;
709     }
710     closedir $dirh;
711
712     if ($count <= 0) {
713       print STDERR "$progname: no files in cache of $url\n" if ($verbose);
714       $poll_p = 1;
715     }
716   }
717
718   if ($poll_p) {
719
720     print STDERR "$progname: loading $url\n" if ($verbose);
721
722     my %files;
723     opendir (my $dirh, $dir) || error ("$dir: $!");
724     foreach my $f (readdir ($dirh)) {
725       next if ($f eq '.' || $f eq '..');
726       $files{$f} = 0;  # 0 means "file exists, should be deleted"
727     }
728     closedir $dirh;
729
730     $files{$stamp} = 1;
731
732     # Download each image currently in the feed.
733     #
734     my $count = 0;
735     my @urls = parse_feed ($url);
736     print STDERR "$progname: " . ($#urls + 1) . " images\n"
737       if ($verbose > 1);
738     foreach my $p (@urls) {
739       my ($furl, $id) = @$p;
740       my $f = download_image ($furl, $id, $dir);
741       next unless $f;
742       $files{$f} = 1;    # Got it, don't delete
743       $count++;
744     }
745
746     my $empty_p = ($count <= 0);
747
748     # Now delete any files that are no longer in the feed.
749     # But if there was nothing in the feed (network failure?)
750     # then don't blow away the old files.
751     #
752     my $kept = 0;
753     foreach my $f (keys(%files)) {
754       if ($count <= 0) {
755         $kept++;
756       } elsif ($files{$f}) {
757         $kept++;
758       } else {
759         if (unlink ("$dir/$f")) {
760           print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
761         } else {
762           print STDERR "$progname: rm $dir/$f: $!\n";   # don't bail
763         }
764       }
765     }
766
767     # Both feed and cache are empty. No files at all. Bail.
768     error ("empty feed: $url") if ($kept <= 1);
769
770     # Feed is empty, but we have some files from last time. Warn.
771     print STDERR "$progname: empty feed: using cache: $url\n"
772       if ($empty_p);
773
774     $mtime = time();    # update the timestamp
775
776   } else {
777
778     # Not yet time to re-check the URL.
779     print STDERR "$progname: using cache: $url\n" if ($verbose);
780
781   }
782
783   # Unlock and update the write date on the .timestamp file.
784   #
785   truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
786   seek ($lock_fd, 0, 0)  || error ("unable to rewind $lock: $!");
787   utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
788   flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
789   close ($lock_fd);
790   $lock_fd = undef;
791   print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
792
793   # Don't bother using the imageDirectory cache.  We know that this directory
794   # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
795   # like ~/Pictures/ might.
796   #
797   $cache_p = 0;
798
799   # Return the URL and directory name of the files of that URL's local cache.
800   #
801   return ($url, $dir);
802 }
803
804
805 sub find_random_file($) {
806   my ($dir) = @_;
807
808   if ($use_spotlight_p == -1) {
809     $use_spotlight_p = 0;
810     if (-x '/usr/bin/mdfind') {
811       $use_spotlight_p = 1;
812     }
813   }
814
815   my $url;
816   ($url, $dir) = mirror_feed ($dir);
817
818   if ($url) {
819     $use_spotlight_p = 0;
820     print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
821   }
822
823   @all_files = read_cache ($dir);
824
825   if ($#all_files >= 0) {
826     # got it from the cache...
827
828   } elsif ($use_spotlight_p) {
829     print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
830     spotlight_all_files ($dir);
831     print STDERR "$progname: found " . ($#all_files+1) .
832                  " file" . ($#all_files == 0 ? "" : "s") .
833                  " via Spotlight\n"
834       if ($verbose);
835   } else {
836     print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
837     find_all_files ($dir);
838     print STDERR "$progname: " .
839                  "f=" . ($#all_files+1) . "; " .
840                  "d=$dir_count; " .
841                  "s=$stat_count; " .
842                  "skip=${skip_count_unstat}+$skip_count_stat=" .
843                   ($skip_count_unstat + $skip_count_stat) .
844                  ".\n"
845       if ($verbose);
846   }
847
848   write_cache ($dir);
849
850   if ($#all_files < 0) {
851     print STDERR "$progname: no files in $dir\n";
852     exit 1;
853   }
854
855   my $max_tries = 50;
856   for (my $i = 0; $i < $max_tries; $i++) {
857
858     my $n = int (rand ($#all_files + 1));
859     my $file = $all_files[$n];
860     if (large_enough_p ($file)) {
861       if (! $url) {
862         $file =~ s@^\Q$dir/@@so || die;  # remove $dir from front
863       }
864       return $file;
865     }
866   }
867
868   print STDERR "$progname: no suitable images in $dir " .
869                "(after $max_tries tries)\n";
870
871   # If we got here, blow away the cache.  Maybe it's stale.
872   unlink $cache_file_name if $cache_file_name;
873
874   exit 1;
875 }
876
877
878 sub large_enough_p($) {
879   my ($file) = @_;
880
881   my ($w, $h) = image_file_size ($file);
882
883   if (!defined ($h)) {
884
885     # Nonexistent files are obviously too small!
886     # Already printed $verbose message about the file not existing.
887     return 0 unless -f $file;
888
889     print STDERR "$progname: $file: unable to determine image size\n"
890       if ($verbose);
891     # Assume that unknown files are of good sizes: this will happen if
892     # they matched $good_file_re, but we don't have code to parse them.
893     # (This will also happen if the file is junk...)
894     return 1;
895   }
896
897   if ($w < $min_image_width || $h < $min_image_height) {
898     print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
899     return 0;
900   }
901
902   print STDERR "$progname: $file: $w x $h\n" if ($verbose);
903   return 1;
904 }
905
906
907
908 # Given the raw body of a GIF document, returns the dimensions of the image.
909 #
910 sub gif_size($) {
911   my ($body) = @_;
912   my $type = substr($body, 0, 6);
913   my $s;
914   return () unless ($type =~ /GIF8[7,9]a/);
915   $s = substr ($body, 6, 10);
916   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
917   return (($b<<8|$a), ($d<<8|$c));
918 }
919
920 # Given the raw body of a JPEG document, returns the dimensions of the image.
921 #
922 sub jpeg_size($) {
923   my ($body) = @_;
924   my $i = 0;
925   my $L = length($body);
926
927   my $c1 = substr($body, $i, 1); $i++;
928   my $c2 = substr($body, $i, 1); $i++;
929   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
930
931   my $ch = "0";
932   while (ord($ch) != 0xDA && $i < $L) {
933     # Find next marker, beginning with 0xFF.
934     while (ord($ch) != 0xFF) {
935       return () if (length($body) <= $i);
936       $ch = substr($body, $i, 1); $i++;
937     }
938     # markers can be padded with any number of 0xFF.
939     while (ord($ch) == 0xFF) {
940       return () if (length($body) <= $i);
941       $ch = substr($body, $i, 1); $i++;
942     }
943
944     # $ch contains the value of the marker.
945     my $marker = ord($ch);
946
947     if (($marker >= 0xC0) &&
948         ($marker <= 0xCF) &&
949         ($marker != 0xC4) &&
950         ($marker != 0xCC)) {  # it's a SOFn marker
951       $i += 3;
952       return () if (length($body) <= $i);
953       my $s = substr($body, $i, 4); $i += 4;
954       my ($a,$b,$c,$d) = unpack("C"x4, $s);
955       return (($c<<8|$d), ($a<<8|$b));
956
957     } else {
958       # We must skip variables, since FFs in variable names aren't
959       # valid JPEG markers.
960       return () if (length($body) <= $i);
961       my $s = substr($body, $i, 2); $i += 2;
962       my ($c1, $c2) = unpack ("C"x2, $s);
963       my $length = ($c1 << 8) | $c2;
964       return () if ($length < 2);
965       $i += $length-2;
966     }
967   }
968   return ();
969 }
970
971 # Given the raw body of a PNG document, returns the dimensions of the image.
972 #
973 sub png_size($) {
974   my ($body) = @_;
975   return () unless ($body =~ m/^\211PNG\r/s);
976   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
977   return () unless defined ($bits);
978   return () unless ($bits =~ /^IHDR/);
979   my ($ign, $w, $h) = unpack("a4N2", $bits);
980   return ($w, $h);
981 }
982
983
984 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
985 # of the image.
986 #
987 sub image_size($) {
988   my ($body) = @_;
989   return () if (length($body) < 10);
990   my ($w, $h) = gif_size ($body);
991   if ($w && $h) { return ($w, $h); }
992   ($w, $h) = jpeg_size ($body);
993   if ($w && $h) { return ($w, $h); }
994   # #### TODO: need image parsers for TIFF, XPM, XBM.
995   return png_size ($body);
996 }
997
998 # Returns the dimensions of the image file.
999 #
1000 sub image_file_size($) {
1001   my ($file) = @_;
1002   my $in;
1003   if (! open ($in, '<:raw', $file)) {
1004     print STDERR "$progname: $file: $!\n" if ($verbose);
1005     return ();
1006   }
1007   my $body = '';
1008   sysread ($in, $body, 1024 * 50);  # The first 50k should be enough.
1009   close $in;                        # (It's not for certain huge jpegs...
1010   return image_size ($body);        # but we know they're huge!)
1011 }
1012
1013
1014 sub error($) {
1015   my ($err) = @_;
1016   print STDERR "$progname: $err\n";
1017   exit 1;
1018 }
1019
1020 sub usage() {
1021   print STDERR "usage: $progname [--verbose] directory-or-feed-url\n\n" .
1022   "       Prints the name of a randomly-selected image file.  The directory\n" .
1023   "       is searched recursively.  Images smaller than " .
1024          "${min_image_width}x${min_image_height} are excluded.\n" .
1025   "\n" .
1026   "       The directory may also be the URL of an RSS/Atom feed.  Enclosed\n" .
1027   "       images will be downloaded and cached locally.\n" .
1028   "\n";
1029   exit 1;
1030 }
1031
1032 sub main() {
1033   my $dir = undef;
1034
1035   while ($_ = $ARGV[0]) {
1036     shift @ARGV;
1037     if    (m/^--?verbose$/s)      { $verbose++; }
1038     elsif (m/^-v+$/s)             { $verbose += length($_)-1; }
1039     elsif (m/^--?name$/s)         { }   # ignored, for compatibility
1040     elsif (m/^--?spotlight$/s)    { $use_spotlight_p = 1; }
1041     elsif (m/^--?no-spotlight$/s) { $use_spotlight_p = 0; }
1042     elsif (m/^--?cache$/s)        { $cache_p = 1; }
1043     elsif (m/^--?no-?cache$/s)    { $cache_p = 0; }
1044     elsif (m/^-./)                { usage; }
1045     elsif (!defined($dir))        { $dir = $_; }
1046     else                          { usage; }
1047   }
1048
1049   usage unless (defined($dir));
1050
1051   $dir =~ s@^feed:@http:@si;
1052
1053   if ($dir =~ m/^https?:/si) {
1054     # ok
1055   } else {
1056     $dir =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
1057     $dir =~ s@/+$@@s;              # omit trailing /
1058
1059     if (! -d $dir) {
1060       print STDERR "$progname: $dir: not a directory or URL\n";
1061       usage;
1062     }
1063   }
1064
1065   my $file = find_random_file ($dir);
1066   print STDOUT "$file\n";
1067 }
1068
1069 main;
1070 exit 0;