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