chiark / gitweb /
pctb renamed to yarrg: Makefile moves stuff across
[ypp-sc-tools.db-test.git] / yarrg / dictionary-update-receiver
1 #!/usr/bin/perl -w
2 #
3 # This script is invoked when the YPP SC PCTB client talks to the
4 # dictionary server.  See README.privacy.
5
6 # This is part of ypp-sc-tools, a set of third-party tools for assisting
7 # players of Yohoho Puzzle Pirates.
8 #
9 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 #
11 # This program is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
25 # are used without permission.  This program is not endorsed or
26 # sponsored by Three Rings.
27
28
29 # upload testing runes:
30 #
31 # YPPSC_PCTB_DICT_UPDATE=./ YPPSC_PCTB_DICT_SUBMIT=./ ./ypp-commodities --ocean midnight --pirate aristarchus --find-island --same --raw-tsv >raw.tsv  
32 # ./dictionary-manager --debug --approve-updates '' . .
33
34 use strict (qw(vars));
35 use POSIX;
36
37 $CGI::POST_MAX= 1024*1024;
38 $CGI::DISABLE_UPLOADS= 1;
39
40 use CGI qw/:standard -private_tempfiles/;
41 use IO::Pipe;
42 use IO::Handle;
43
44 my $aadepth=2;
45
46 #---------- pixmaps ----------
47
48 sub parseentryin__pixmap ($) {
49     my ($entry_in) = @_;
50     $entry_in =~
51         m/^(\S+ \- .*)\nP3\n([1-9]\d{1,3}) ([1-9]\d{1,3})\n255\n/s or die;
52     my ($def,$w,$h)= ($1, $2+0, $3+0);
53     my @d= grep { m/./ } split /\s+/, $';
54     @d == $w*$h*3 or die "$d[0]|$d[1]|...|$d[$#d-1]|$d[$#d] ?";
55     map {
56         m/\D/ and die "$& ?";
57         $_ += 0;
58         $_ >= 0 or die "$_ ?";
59         $_ <= 255 or die "$_ ?";
60     } @d;
61     my $ppm= "P3\n$w $h\n255\n";
62     my $di=0;
63     for (my $y=0; $y<$h; $y++) {
64         for (my $x=0; $x<$w; $x++, $di+=3) {
65 #print STDERR ">$x,$y,$di,",scalar(@d),"<\n";
66             $ppm .= sprintf "  %3d %3d %3d", @d[$di..$di+2];
67         }
68         $ppm .= "\n";
69     }
70
71     my $icon= pipeval($ppm,
72                          'ppmtopgm',
73                          'pnmscale -xysize 156 80',
74                          'pnmnorm -bpercent 40 -wpercent 20',
75                          'pgmtopbm -threshold',
76                          'pnminvert',
77                          'pbmtoascii -2x4');
78
79     my $whole= pipeval($ppm,
80                        'ppmtopgm',
81                        'pnmnorm -bpercent 10 -wpercent 5',
82                        'pgmtopbm -threshold',
83                        'pnminvert',
84                        'pbmtoascii');
85
86     my $entry= "$def\n$ppm";
87
88     return ('',$def,$ppm,$ppm,$def, $w,$icon,$whole,$entry);
89 }
90
91 #---------- characters ----------
92
93 sub parseentryin__char ($$) {
94     my ($ei,$h) = @_;
95     $ei =~ m/^(Digit|Upper|Lower|Word)\n([^\n]+)\n/s or die;
96     my ($ctx,$str)= ($1,$2);
97 print STDERR ">ctx=$ctx|str=$str|$'<\n";
98     my @d= grep { m/./ } split /\n/, $';
99 print STDERR ">@d<\n";
100     die if $h>100;
101     die if @d>400;
102
103     my $w= @d;
104
105     my $maxval= (1<<$aadepth)-1;
106     die 'cannot do [^0...$maxval]!' if $maxval>9;
107
108     my $pgm= "P2\n$h $w\n$maxval\n";
109     map { # x, left to right
110         m/[^0-$maxval]/ and die "$_ ?";
111         my $l= $_;
112         $l =~ s/./ $&/g;
113         $pgm .= "$l\n";
114     } @d;
115
116     my $key= join ' ', $ctx, @d;
117
118     $pgm= pipeval($pgm,
119                   "pnmflip -xy",
120                   "pnmnoraw");
121
122     my $icon= pipeval($pgm,
123                       "pnmscale -xysize 156 ".($h*4),
124                       'pgmtopbm -threshold',
125                       'pnminvert',
126                       'pbmtoascii -2x4');
127
128     my $whole= pipeval($pgm,
129                        "pnmscale 4",
130                        'pgmtopbm -fs',
131                        'pnminvert',
132                        'pbmtoascii');
133
134     my $entry= "$ctx\n$str\n$key\n";
135     
136     return ($ctx,$str,$pgm,$key,$str, $w*4,$icon,$whole,$entry);
137 }
138
139 #---------- useful stuff ----------
140
141 sub pipeval ($@) {
142     my ($val, @cmds) = @_;
143     my (@pids);
144
145     my $lastpipe;
146     
147     foreach my $cmd ('',@cmds) {
148         my $pipe= new IO::Pipe or die $!;
149         my $pid= fork();  defined $pid or die $!;
150
151         if (!$pid) {
152             $pipe->writer();
153             if (!$lastpipe) {
154                  print $pipe $val or die $!;
155                  exit 0;
156              } else {
157                  open STDIN, '<&', $lastpipe or die $!;
158                  open STDOUT, '>&', $pipe or die $!;
159                  close $lastpipe or die $!;
160                  close $pipe or die $!;
161                  exec $cmd; die $!;
162              }
163         }
164         $pipe->reader();
165         if ($lastpipe) { close $lastpipe or die $!; }
166         $lastpipe= $pipe;
167         push @pids, $pid;
168     }
169
170     $!=0; { local ($/)=undef; $val= <$lastpipe>; }
171     defined $val or die $!;
172     $lastpipe->error and die $!;  close $lastpipe or die $!;
173
174     foreach my $cmd ('(paste)', @cmds) {
175         my $pid= shift @pids;
176         waitpid($pid,0) == $pid or die "$pid $? $!";
177         $?==0 or $?==13 or die "$cmd $?";
178     }
179     return $val;
180 }
181
182 #========== main program ==========
183
184 #---------- determine properties of the submission ----------
185
186 my $version= param('version');
187 my $spec_aadepth= param('depth');
188 if ($version ne '3'  ||  $spec_aadepth ne $aadepth) {
189     print header('text/plain',
190                  "403 YPP SC PCTB client is out of date".
191                  " ($version, $spec_aadepth)");
192     print "\nYour YPP SC client is out of date.\n";
193     exit 0;
194 }
195
196 my $dict= param('dict');
197 my $entry_in= param('entry');
198 defined $entry_in or die Dump()." ?";
199
200 my $ocean= param('ocean');
201 my $pirate= param('pirate');
202 if (defined $ocean && defined $pirate) {
203     $pirate= "$ocean - $pirate";
204 } else {
205     $pirate= '';
206 }
207
208 my $caller= $ENV{'REMOTE_ADDR'};
209 $caller= 'LOCAL' unless defined $caller;
210
211 my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
212 if (defined $fwdf) {
213     $fwdf =~ s/\s//g;
214     $fwdf =~ s/[^0-9.,]/?/g;
215     $caller= "$fwdf,$pirate";
216 }
217
218 my $kind;
219 my @xa;
220
221 if ($dict =~ m/^pixmap$/) {
222     $kind= $&;
223 } elsif ($dict =~ m/^(char)([1-9]\d?)$/) {
224     ($kind,@xa)= ($1,$2);
225 } else {
226     die "$dict ?";
227 }
228 $dict= $&;
229
230 my ($ctx,$def,$image,$key,$val, $width,$icon,$whole,$entry)=
231     &{"parseentryin__$kind"}($entry_in, @xa);
232
233 my $du=$ENV{'YPPSC_DICTUPDATES'};
234 chdir $du or die "$du $!"
235     if defined $du;
236
237 my $instance= $du;
238 $instance =~ s,ypp-sc-tools,,ig;
239 $instance =~ s,ypp,,ig;
240 $instance =~ s,pctb,,ig;
241 $instance =~ s,/\W+/,/,g;
242 $instance =~ s,/+$,,;
243 $instance =~ s,^.*/,,;
244
245 #---------- compute the email to send ----------
246
247 my $whoami= `whoami`; $? and die $?;
248 chomp $whoami;
249
250 my $email= <<END
251 To: $whoami
252 Subject: pctb /$instance/ $dict $ctx $def [ypp-sc-tools]
253
254 Pirate:     $pirate
255 Caller:     $caller
256 Dictionary: $dict
257 Context:    $ctx
258 Definition: $def
259
260 END
261     ;
262
263 if (length $icon) {
264     $icon =~ s/^/ /gm;
265     $email .= "$icon\n\n";
266 }
267
268 $whole =~ s/(.*)\n/ sprintf "%-${width}s\n", $1 /mge;
269 $whole =~ s/^/|/mg;
270 $whole =~ s/\n/|\n/mg;
271 $whole =~ s/^(.*)/ ",".('_' x $width).".\n".$1 /e;
272 $whole =~ s/(.*)$/ $1."\n\`".('~' x $width)."'\n" /e;
273
274 my $lw= 79;
275
276 while ($whole =~ m/../) {
277     my $lhs= $whole;
278     $lhs =~ s/^(.{0,$lw}).*$/$1/mg;
279     $whole =~ s/^.{1,$lw}//mg;
280 #print STDERR "[[[[[$lhs########$whole]]]]]\n";
281     $email .= $lhs;
282 }
283
284 END
285     ;
286
287 my $cutline= "-8<-\n";
288 $email .= $cutline.$entry.$cutline;
289
290 #---------- prepare the database entry ----------
291
292 my $fn_t= "_update.$$-xxxxxxxxxxxxxxxx.tmp";
293 open F, "> $fn_t" or die "$fn_t $!";
294 (stat F) or die $!;
295 my $fn_i= sprintf "_update.$$-%016x.rdy", (stat _)[1];
296
297 print F "ypp-sc-tools dictionary update v3 depth=$aadepth\n";
298
299 foreach my $v ($pirate,$caller,$dict,$ctx,$def,$image,$key,$val) {
300     printf F "%d\n", length($v) or die $!;
301     print F $v,"\n" or die $!;
302 }
303
304 close F or die $!;
305
306 my @tm= localtime;
307 my $tm= strftime "%Y-%m-%d %H:%M:%S %Z", @tm;
308
309 open L, ">> _dict.log" or die $!;
310 my $ll= sprintf "%s %-6s %-31s %-31s %s", $tm, $dict, $pirate, $caller, $fn_i;
311
312 #---------- commit everything ----------
313
314 print L "$ll submit\n" or die $!;
315 L->flush or die $!;
316
317 if (eval {
318
319     open S, "|/usr/lib/sendmail -odb -oee -oi -t" or die $!;
320     print S $email or die $!;
321     $!=0; $?=0; close S or die $!; $? and die $?;
322
323     rename $fn_t, $fn_i or die "$fn_t $fn_i $!";
324
325     1;
326 }) {
327     print L "$ll stored\n" or die $!;
328 } else {
329     print L "$ll ERROR! $@\n" or die $!;
330     exit 1;
331 }
332 close L or die $!;
333
334 print header('text/plain'), "OK $fn_i\n" or die $!;