chiark / gitweb /
at: impl PieceSpecForOp for ()
[otter.git] / media-scraper
1 #!/usr/bin/perl -w
2 use strict;
3
4 use POSIX;
5 use IO::Handle;
6 use Carp;
7 use TOML::Parser;
8 use Data::Dumper;
9 use Time::HiRes;
10 use Digest::MD5 qw(md5_hex);
11 use File::Compare;
12
13 our $max_rate = 2; # per second
14
15 # todo: allow to read size details out of svg (maybe in daemon-otter?)
16 # todo: allow scraper method none to handle item vs filename mismatch
17
18 #print Dumper($libinfo);
19
20 open DEBUG, ">&STDERR" or die $!;
21 autoflush DEBUG 1;
22
23 sub run_curl {
24   my ($datalog, $output, $url, @xopts) = @_;
25   my @curl = (qw(curl -Ssf -L --proto-redir -all), @xopts);
26   push @curl, '-o', "$output.tmp", $url;
27   our $last_curl;
28   $last_curl //= 0.;
29   my $now = Time::HiRes::time;
30   my $delay = 1./$max_rate - ($now - $last_curl);
31   Time::HiRes::sleep $delay if $delay > 0;
32   $last_curl = $now;
33 #  print DEBUG "+ @curl\n";
34   $!=$?=0; my $r = system @curl; die "curl failed ($? $!): @curl" if $r;
35   my $logtime = strftime "%F %T UTC", gmtime time;
36   print $datalog "$logtime: downloaded into $output from $url\n"
37     or die $!;
38   rename "$output.tmp", "$output" or die "install $output: $!";
39 }
40
41 sub cfg_lookup_1 ($@) {
42   my ($dict, @keys) = @_;
43   #print DEBUG "cfg_lookup_1 ".Dumper($dict, \@keys);
44   foreach my $k (@keys) {
45     confess unless ref $dict eq 'HASH';
46     $dict = $dict->{$k};
47     return undef if !defined $dict;
48   }
49   #print DEBUG "cfg_lookup_1 (@keys) => $dict\n";
50   return $dict;
51 }
52
53 sub mk_cfg_lookup ($$@) {
54   my ($groups, $thisgroup, @keysprefix) = @_;
55   #print DEBUG "mk_cfg_lookup >@keysprefix< ".Dumper($thisgroup);
56   return sub {
57     #print DEBUG "from mk_cfg_lookup >@keysprefix< >@_<\n";
58     my $cgroup = $thisgroup;
59     for (;;) {
60       my $got = cfg_lookup_1($cgroup, @keysprefix, @_);
61       return $got if defined $got;
62       my $inherit = cfg_lookup_1($cgroup, qw(inherit));
63       return undef unless $inherit;
64       $cgroup = $groups->{$inherit};
65       confess "$inherit".Dumper($groups,$inherit)."?" unless $cgroup;
66     }
67   }
68 }
69
70 sub cfg_affixes ($$$) {
71   my ($cfg, $keybase, $middle) = @_;
72   return
73     ($cfg->("${keybase}_prefix") // '')
74     .$middle
75     .($cfg->("${keybase}_suffix") // '');
76 }
77
78 sub method_none { return sub { } }
79 sub methodlic_none { undef }
80
81 sub methodlic_wikimedia ($) {
82   my ($scraper) = @_;
83   return <<END;
84 These files were all obtained from
85     ${ \ $scraper->('site-title') }
86
87 They are all available under at least, and distributed here under,
88     ${ \ $scraper->('spdx') }
89 as well as possibly other licences.  There is NO WARRANTY.
90
91 See <file>.download-log for the original URL and download timestamp.
92 The wikitext of the File: page on the wiki is in <file>.wikitext, and
93 contains the authorship and derivation information, as well as
94 information about any alternative licence terms.
95
96 [ This LICENCE file was generated by media-scraper and should not
97   be manually edited ]
98 END
99 }
100
101 sub method_wikimedia ($$$) {
102   my ($scraper, $methname) = @_;
103   #print DEBUG "METHOD $methname...\n";
104   return sub {
105     my ($lbase, $ldest, $rstem) = @_;
106     my $rfilename = cfg_affixes $scraper, 'filename', $rstem;
107     my $url = cfg_affixes $scraper, 'url', $rfilename;
108     my $wt = "$lbase.wikitext";
109     #print DEBUG "rfilename=$rfilename url=$url .\n";
110     my $datalog = new IO::File "$lbase.download-log", '>>' or die $!;
111     print $datalog "\n" or die $!;
112     run_curl $datalog, $wt, $url;
113     open WT, "$wt" or die $!;
114     my (@lics) = @{ $scraper->('licences') };
115     s/\W/\\$&/g foreach @lics;
116     my $lic1_re = '(?:'.(join '|', @lics).')';
117     my $ok;
118     while (<WT>) {
119       s/\s+$//;
120       if (m{^ \{\{ ($lic1_re) \}\} $}xi ||
121           m{^ \{\{ self\| (?:[^{}]*\|)? ($lic1_re) (?:\|[^{}]*)? \}\} $}xi) {
122         print "licence=$1 ";
123         $ok = 1;
124         last;
125       }
126     }
127     if (!$ok) {
128       die "\nfile $wt from $url no appropriate licence $lic1_re";
129     }
130     my $hash_prefix = '';
131     if ($scraper->('data_url_hashprefix')) {
132       # https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:$wgHashedUploadDirectory
133       md5_hex($rfilename) =~ m{^((.).)} or die;
134       $hash_prefix .= "$2/$1/";
135     }
136     my $data_url = cfg_affixes $scraper, 'data_url', $hash_prefix.$rfilename;
137     run_curl $datalog, $ldest, $data_url;
138     close $datalog or die $!;
139   };
140 }
141
142 our $offline;
143
144 while (@ARGV && $ARGV[0] =~ m/^-/) {
145   $_ = shift @ARGV;
146   last if m/^-$/;
147   if (m/^--offline$/) {
148     $offline = 1;
149   } else {
150     die "bad option: \`$_'";
151   }
152 }
153
154 my $input = $ARGV[0] // die;
155 $input =~ m/\.toml$/ or die "$input ?";
156 my $basename = $`;
157 mkdir $basename or $!==EEXIST or die "mkdir $basename: $!";
158
159 my $parser = TOML::Parser->new();
160 my $libinfo = $parser->parse_file($input);
161 my $groups = $libinfo->{group};
162 my $scraper = sub { $libinfo->{scraper}{$_[0]} };
163 my $method = $scraper->('method');
164 my $method_fn = ${*::}{"method_$method"};
165
166 my $methodlic_fn = ${*::}{"methodlic_$method"};
167 my $licpath = "$basename/LICENCE";
168
169 my $method_lictext = $methodlic_fn->($scraper);
170 if (defined $method_lictext) {
171   my $licfile = new IO::File "$licpath.tmp", '>' or die $!;
172
173   print $licfile <<END, $method_lictext, <<END or die $!;
174 SPDX-License-Identifier: ${ \ $scraper->('spdx') }
175 (applies to the contents of this directory unless otherwise stated)
176
177 END
178
179 The download was done by media-scraper, controlled by $input.
180 END
181   close $licfile or die $!;
182 }
183
184 my $makepath = "$basename/files.make";
185 my $makefile = new IO::File "$makepath.tmp", '>' or die $!;
186
187 foreach my $groupname (sort keys %$groups) {
188   my $group_dict = $groups->{$groupname};
189   my $gcfg = mk_cfg_lookup($groups, $group_dict);
190   my $method_impl = $method_fn->($scraper, $method);
191   foreach (split(/\n/, $gcfg->('files'))) {
192     s/^\s+//;
193     next if m/^\#/ || m/^$/;
194     m/^(\S+)\s+(\S+)/ or die "bad line in files: \`$_'";
195     my $lministem = $1;
196     my $rministem = $2;
197
198     my $lstem = cfg_affixes $gcfg, 'item', $lministem;
199     my $rstem = cfg_affixes $gcfg, 'stem', $rministem;
200     my $lbase = "$basename/$lstem";
201     my $lupstream = "$lbase.svg";
202     my $lprocessed = "$lbase.usvg";
203
204     print DEBUG "file $lstem ";
205
206     my $process_colour = sub ($$) {
207       my ($linput, $lprocessed) = @_;
208       print $makefile <<END or die $!;
209 LIBRARY_FILES += $lprocessed
210 $lprocessed: $linput $licpath $input
211         \$(LIBRARY_PROCESS_SVG)
212 END
213     };
214
215     my $process_colours = sub {
216       my $colours = $gcfg->('colours');
217       if (!keys %$colours) {
218         $process_colour->($lupstream, $lprocessed, "");
219         return;
220       }
221       foreach my $colour (sort keys %$colours) {
222         my $cspec = $colours->{$colour};
223         my $abbrev = $cspec->{abbrev} or confess;
224         my $ncoloured = $lupstream;
225         $ncoloured =~ s/\.svg$/.coloured$&/;
226         my $outfile  = $lprocessed;
227         $ncoloured =~ s/_c/$abbrev/ or confess "$outfile ?";
228         $outfile  =~ s/_c/$abbrev/ or confess "$outfile ?";
229         my $coloured = $lupstream;
230
231         my $ci = 0;
232         my $cfp;
233         my $emitmap = sub {
234           my ($from, $to) = @_;
235           confess if $from =~ m/\W/ || $to =~ m/\W/;
236
237           $coloured = $ncoloured;
238           if (!defined $cfp) {
239             $cfp ="\$@.$ci.tmp";
240             print $makefile <<END or die $!;
241 LIBRARY_CLEAN += $ncoloured
242 $ncoloured: $lupstream Makefile $makepath
243         \$(USVG_CMD) -c - <\$< >$cfp
244 END
245           }
246           $ci++;
247           my $nfp = "\$@.$ci.tmp";
248           print $makefile <<END or die $!;
249         \$(RECOLOUR_SVG) -f '$from' -t '$to' $cfp >$nfp
250 END
251           $cfp = $nfp;
252         };
253
254         my %map = %{ $cspec->{map} // { } };
255         while (keys %map) {
256           my $from = (sort keys %map)[0];
257           my @maybe_cycle = ();
258           my $cycle;
259           for (;;) {
260             push @maybe_cycle, $from;
261             my $to = $map{$from};
262             if (!exists $map{$to}) {
263               last;
264             }
265             $from = $to;
266             if (grep { $_ eq $to } @maybe_cycle) {
267               $cycle = $to;
268               last;
269             }
270           }
271           my $emit_most = sub ($) {
272             my ($end) = @_;
273             $end //= $#maybe_cycle;
274             foreach my $i (@maybe_cycle[0..$end]) {
275               $emitmap->($i, $map{$i});
276             }
277           };
278           if (defined $cycle) {
279             my $temp = 'abcbfb'; # chosen at random
280             my $aside = $maybe_cycle[-1];
281             $emitmap->($aside, $temp);
282             $emit_most->($#maybe_cycle-1);
283             $emitmap->($temp, $map{$aside});
284             print $makefile <<END or die $!;
285 # cycle: @maybe_cycle
286 END
287           } else {
288             $emit_most->();
289           }
290           delete $map{$_} foreach @maybe_cycle;
291         }
292         if ($ci) {
293           # inkscape extensions have a tendency to write an empty
294           # file when they don't like their input or arguments
295           print $makefile <<END or die $!;
296         test -s $cfp
297         mv -f $cfp \$@
298 END
299         }
300
301         $process_colour->($coloured, $outfile);
302       }
303     };
304
305     $process_colours->();
306
307     if (stat $lupstream) {
308       print DEBUG "already.\n";
309       next;
310     }
311     die "$lupstream $!" unless $!==ENOENT;
312
313     if ($offline) {
314       print DEBUG "missing.\n";
315       warn "offline but $lupstream missing\n";
316       next;
317     }
318
319     $method_impl->($lbase, $lupstream, $rstem);
320
321     print DEBUG "done.\n";
322   }
323 }
324
325 close $makefile or die $!;
326
327 if (defined($method_lictext)) {
328   my $cmp = compare("$licpath.tmp", $licpath);
329   die if $cmp < 0;
330   if ($cmp) {
331     rename "$licpath.tmp", $licpath or die $!;
332   } else {
333     remove "$licpath.tmp";
334   }
335 }
336
337 rename "$makepath.tmp", $makepath or die $!;