chiark / gitweb /
Normalise commodity name case (from uploads)
[ypp-sc-tools.db-live.git] / yarrg / Commods.pm
1 # This is part of ypp-sc-tools, a set of third-party tools for assisting
2 # players of Yohoho Puzzle Pirates.
3 #
4 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
20 # are used without permission.  This program is not endorsed or
21 # sponsored by Three Rings.
22
23 package Commods;
24 use IO::File;
25 use IO::Pipe;
26 use HTTP::Request::Common ();
27 use POSIX;
28 use LWP::UserAgent;
29
30 use strict;
31 use warnings;
32
33 no warnings qw(exec);
34
35 BEGIN {
36     use Exporter ();
37     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
38     $VERSION     = 1.00;
39     @ISA         = qw(Exporter);
40     @EXPORT      = qw(&parse_info_clientside &fetch_with_rsync
41                       &parse_info_serverside &parse_info_serverside_ocean
42                       %oceans %commods %clients %commodclasses
43                       %vessels %shotname2damage
44                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
45                       &get_our_version &check_tsv_line &errsan
46                       &pipethrough_prep &pipethrough_run
47                       &pipethrough_run_along &pipethrough_run_finish
48                       &pipethrough_run_gzip &http_useragent &version_core
49                       &http_useragent_string_map
50                       &cgipostform &yarrgpostform &cgi_get_caller
51                       &set_ctype_utf8 $masterinfoversion
52                       &source_tarball);
53     %EXPORT_TAGS = ( );
54
55     @EXPORT_OK   = qw();
56 }
57
58 our $masterinfoversion= 2; # version we understand.
59 #
60 # To extend the source-info.txt format:
61 #
62 #    * Commods.pm:parse_info1
63 #       add code to parse new version
64 #
65 #    * source-info.txt
66 #       add new information
67 #
68 # If new data should NOT be in master-info.txt too:
69 #
70 #    * update-master-info:process_some_info
71 #       check that code for converting source-info to master-info
72 #       removes the extra info; add code to remove it if necessary
73 #
74 #    * db-idempotent-populate
75 #       if database schema is extended, add code to copy data
76 #
77 # If new data DOES need to be in master-info.txt too:
78 #
79 #    * Commods.pm:$masterinfoversion
80 #       increment
81 #
82 #    * update-master-info:process_some_info
83 #       add code to convert new version to old, by removing
84 #       extra info conditionally depending on version
85
86 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
87 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
88 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
89               #    $vessels{'War Brig'}{Volume}= 81000
90               #    $vessels{'War Brig'}{Mass}= 54000
91 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
92 # $sources = 's[l]b';
93 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
94
95 our %commods;
96 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
97 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
98 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
99 # eg $commods{'Fine black cloth'}{Ordval}= 203921
100
101 our (%pctb_commodmap,@pctb_commodmap);
102
103 my %colours; # eg $colours{'c'}{'black'}= $sources
104 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
105
106 my %colour_ordvals; # $colour_ordvals{'c'}{'green'}= '30';
107 our %commodclasses; # $commodclasses{'dye'}= '3';
108
109 # IMPORTANT
110 #  when extending the format of source-info in a non-backward
111 #  compatible way, be sure to update update-master-info too.
112
113 sub parse_info1 ($$$) {
114     my ($mmfn,$src,$enoentok)= @_;
115     my $mm= new IO::File $mmfn, 'r';
116     if (!$mm) {
117         return if $enoentok && $!==&ENOENT;
118         die "$mmfn $!";
119     }
120     my @ctx= ();
121     while (<$mm>) {
122         next if m/^\s*\#/;
123         next unless m/\S/;
124         s/\s+$//;
125         if (m/^\%(\w+)$/) {
126             my $colourkind= $1;
127             @ctx= (sub {
128                 m/^(\S[^\t@]*\S)(?:\t+\@(\d+\+?))?$/ or die "$_ ?";
129                 my ($colour,$order)=($1,$2);
130                 $colours{$colourkind}{$colour} .= $src;
131                 if (defined $order) {
132                     $order =~ s/^(\d+)\+$/ $1  + $. * 10 /e;
133                     $colour_ordvals{$colourkind}{$colour}= $order;
134                 }
135             });
136         } elsif (m/^commods$/) {
137             @ctx= (sub { push @rawcm, lc $_; });
138         } elsif (m/^nocommods$/) {
139             @ctx= (sub { push @nocm, lc $_; });
140         } elsif (m/^commodclasses$/) {
141             @ctx= (sub {
142                 die unless m/^\*([_a-z]+)$/;
143                 $commodclasses{$1}= scalar keys %commodclasses;
144             });
145         } elsif (m/^ocean (\w+)$/) {
146             my $ocean= $1;
147             keys %{ $oceans{$ocean} };
148             @ctx= (sub {
149                 $ocean or die; # ref to $ocean needed to work
150                                # around a perl bug
151                 my $arch= $_;
152                 keys %{ $oceans{$ocean}{$arch} };
153                 $ctx[1]= sub {
154                     $oceans{$ocean}{$arch}{$_} .= $src;
155                 };
156             });
157         } elsif (m/^vessels$/) {
158             @ctx= (sub {
159                 return if m/^[-+|]+$/;
160                 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
161                     \| \s* (small|medium|large) \s*
162                     \| \s* ([1-9][0-9,]+) \s*
163                     \| \s* ([1-9][0-9,]+) \s*
164                     \| $/x
165                     or die;
166                 my $name= $1;
167                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
168                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
169                 $vessels{$name}= $v;
170             });
171         } elsif (m/^shot$/) {
172             @ctx= (sub {
173                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
174                 $shotname2damage{$1}= $2;
175             });
176         } elsif (m/^client (\S+.*\S)$/) {
177             my $client= $1;
178             $clients{$client}= [ ];
179             @ctx= (sub {
180                 my $bug= $_;
181                 push @{ $clients{$client} }, $bug;
182             });
183         } elsif (s/^ +//) {
184             my $indent= length $&;
185             die "wrong indent $indent" unless defined $ctx[$indent-1];
186             &{ $ctx[$indent-1] }();
187         } else {
188             die "bad syntax";
189         }
190     }
191     $mm->error and die $!;
192     close $mm or die $!;
193
194 #print Dumper(\%oceans);
195 #print Dumper(\@rawcm);
196         
197     %commods= ();
198     my $ca;
199     my $lnoix=0;
200     $ca= sub {
201         my ($s,$ss,$ordbase) = @_;
202 #print STDERR "ca($s,,".(defined $ordbase ? $ordbase : '?').")\n";
203         if ($s !~ m/\%(\w+)/) {
204             my ($name, $props) = $s =~
205                 /^(\S[^\t]*\S)(?:\t+(\S.*\S))?$/
206                 or die "bad commodspec $s";
207             return if grep { $name eq $_ } @nocm;
208             my $ucname= ucfirst $name;
209             $commods{$ucname}{Srcs} .= $ss;
210             my $c= $commods{$ucname};
211             $c->{Volume}= 1000;
212             $c->{Flags}= '';
213             my ($ordval, $ordclassval);
214             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
215                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
216                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
217                 } elsif ($prop =~ m/^([1-9]\d*)l$/) {
218                     $c->{Volume}= $1 * 1000;
219                 } elsif ($prop =~ m/^\*([_a-z]+)$/) {
220                     $c->{Class}= $1;
221                     die "$1" unless exists $commodclasses{$1};
222                     $ordclassval= 1e7 + $commodclasses{$1} * 1e7;
223                 } elsif ($prop =~ m/^\@(\d+\+?)$/) {
224                     $ordval= $1;
225                     $ordval =~ s/^(\d+)\+$/ $1 + $lnoix * 10 /e;
226                 } elsif ($prop =~ m/^\!([a-z]+)$/) {
227                     $c->{Flags} .= $1;
228                 } else {
229                     die "unknown property $prop for $ucname";
230                 }
231             }
232             $c->{ClassOrdval}= $ordclassval;
233             if (defined $ordbase && defined $ordval && defined $ordclassval) {
234                 my $ordvalout= $ordbase + $ordval + $ordclassval;
235                 $c->{Ordval}= $ordvalout;
236 #print STDERR "ordval $ordvalout $name OV=$ordval OB=$ordbase OCV=$ordclassval\n";
237             } else {
238 #print STDERR "ordval NONE $name\n";
239             }
240             return;
241         }
242         die "unknown $&" unless defined $colours{$1};
243         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
244         foreach my $c (keys %{ $colours{$pctlet} }) {
245             my $ordcolour= $colour_ordvals{$pctlet}{$c};
246             &$ca($lhs.$c.$rhs,
247                  $ss .'%'. $colours{$pctlet}{$c},
248                  defined($ordbase) && defined($ordcolour)
249                      ? $ordbase+$ordcolour : undef);
250         }
251     };
252     foreach (@rawcm) { $lnoix++; &$ca($_,$src,0); }
253 }
254
255 sub parse_info_clientside () {
256     my $master= fetch_with_rsync("info-v$masterinfoversion");
257     parse_info1($master,'s',1);
258     parse_info1('_local-info.txt','s',1);
259 }
260
261 sub fetch_with_rsync ($) {
262     my ($stem) = @_;
263
264     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
265     $rsync= 'rsync' if !defined $rsync;
266
267     my $local= "_master-$stem.txt";
268     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
269     if ($src) {
270         my $remote= "$src/master-$stem.txt";
271         $!=0; system 'rsync','-Lt','--',$remote,$local;
272         die "$? $!" if $! or $?;
273     }
274     return $local;
275 }
276
277 sub parse_info_serverside () {
278     parse_info1('source-info.txt','s',0);
279     parse_info1('tree-info.txt','t',1);
280 }
281 sub parse_info_serverside_ocean ($) {
282     my ($oceanname) = @_;
283     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
284     parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
285 }
286
287 sub parse_pctb_commodmap () {
288     undef %pctb_commodmap;
289     foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
290
291     my $c= new IO::File '_commodmap.tsv';
292     if (!$c) { $!==&ENOENT or die $!; return 0; }
293
294     while (<$c>) {
295         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
296         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
297         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
298         $commods{$1}{Srcs} .= 'b';
299     }
300     $c->error and die $!;
301     close $c or die $!;
302     return 1;
303 }
304
305 sub get_our_version ($$) {
306     my ($aref,$prefix) = @_;
307     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
308     $aref->{"${prefix}fixes"}= 'lastpage checkpager';
309     $aref->{"${prefix}version"}= version_core();
310     return $aref;
311     # clientname        "ypp-sc-tools"
312     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
313     # clientfixes       "lastpage"  [space separated list]
314 }
315
316 sub version_core () {
317     my $version= `
318         if type -p git-describe >/dev/null 2>&1; then
319                 gd=git-describe
320         else
321                 gd="git describe"
322         fi
323         \$gd --tags HEAD || echo 0unknown
324     `; $? and die $?;
325     chomp($version);
326     return $version;
327 }
328
329 sub pipethrough_prep () {
330     my $tf= IO::File::new_tmpfile() or die $!;
331     return $tf;
332 }
333
334 sub pipethrough_run_along ($$$@) {
335     my ($tf, $childprep, $cmd, @a) = @_;
336     $tf->error and die $!;
337     $tf->flush or die $!;
338     $tf->seek(0,0) or die $!;
339     my $fh= new IO::File;
340     my $child= $fh->open("-|"); defined $child or die $!;
341     if (!$child) {
342         open STDIN, "<&", $tf;
343         &$childprep() if defined $childprep;
344         exec $cmd @a; die "@a $!";
345     }
346     return $fh;
347 }
348 sub pipethrough_run_finish ($$) {
349     my ($fh, $what)= @_;
350     $fh->error and die $!;
351     close $fh or die "$what $! $?";  die $? if $?;
352 }
353
354 sub pipethrough_run ($$$@) {
355     my ($tf, $childprep, $cmd, @a) = @_;
356     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
357     my $r;
358     { undef $/; $!=0; $r= <$pt>; }
359     defined $r or die $!;
360     pipethrough_run_finish($pt, "@a");
361     return $r;
362 }
363 sub pipethrough_run_gzip ($) {
364     pipethrough_run($_[0],undef,'gzip','gzip');
365 }
366
367 sub yarrgpostform ($$) {
368     my ($ua, $form) = @_;
369     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
370     get_our_version($form, 'client');
371     die unless $dest =~ m,/$,;
372     return cgipostform($ua, "${dest}commod-update-receiver", $form);
373 }    
374
375 sub cgipostform ($$$) {
376     my ($ua, $url, $form) = @_;
377     my $req= HTTP::Request::Common::POST($url,
378                                          Content => $form,
379                                          Content_Type => 'form-data');
380     if ($url =~ m,^\.?/,) {
381         my $tf= pipethrough_prep();
382         print $tf $req->content() or die $!;
383 #print STDERR "[[[",$req->content(),"]]]";
384         my $out= pipethrough_run($tf, sub {
385             $ENV{'REQUEST_METHOD'}= 'POST';
386             $ENV{'QUERY_STRING'}= '';
387             $ENV{'PATH_TRANSLATED'}= $url;
388             $ENV{'PATH_INFO'}= '';
389             $ENV{'HTTP_HOST'}= 'localhost';
390             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
391             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
392             $ENV{'DOCUMENT_ROOT'}= '.';
393             $ENV{'SCRIPT_FILENAME'}= $url;
394             $ENV{'SCRIPT_NAME'}= $url;
395             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
396
397             foreach my $f (qw(Content_Length Content_Type)) {
398                 $ENV{uc $f}= $req->header($f);
399             }
400 #system 'printenv >&2';
401         }, "$url", "$url");
402         $out =~ s/\r\n/\n/g;
403         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
404         return $';
405     } else {
406         my $resp= $ua->request($req);
407         die $resp->status_line."\n".$resp->content."\n "
408             unless $resp->is_success;
409         return $resp->content();
410     }
411 }
412
413 our %check_tsv_done;
414
415 sub errsan ($) {
416     my ($value) = @_;
417     $value =~ s/[^-+\'. A-Za-z0-9]/ sprintf "\\x%02x",ord $& /ge;
418     return "\"$value\"";
419 }
420
421 sub check_tsv_line ($$) {
422     my ($l, $bad_data_callback) = @_;
423     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
424     
425     chomp($l) or &$bad_data('missing end-of-line');
426
427     $l =~ m/[\t [:graph:]]/ or &$bad_data('nonprinting char(s) '.sprintf "%#x", ord $&);
428     my @v= split /\t/, $l, -1;
429     @v==6 or &$bad_data('wrong number of fields');
430     $v[0] = ucfirst lc $v[0]; # YPP anomalously has "Rum Spice"
431     $v[1] =~ s/^\s+//; $v[1] =~ s/\s+$//; # ooo don't check :-(
432     my ($commod,$stall) = @v;
433
434     !keys %commods or
435         defined $commods{$commod} or
436         &$bad_data("unknown commodity ".errsan($commod));
437     
438     $stall =~ m/\p{IsAlnum}/ or
439         &$bad_data("stall does not contain with alphanumeric".errsan($stall));
440     !exists $check_tsv_done{$commod,$stall} or
441         &$bad_data("repeated data ".errsan($commod).",".errsan($stall));
442     $check_tsv_done{$commod,$stall}= 1;
443     foreach my $i (2..5) {
444         my $f= $v[$i];
445         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or
446             &$bad_data("bad field $i ".errsan($f));
447         ($i % 2) or ($f !~ m/\>/) or
448             &$bad_data("> in field $i price ".errsan($f));
449     }
450
451     foreach my $i (2,4) {
452         &$bad_data("price with no qty or vice versa (field $i)")
453             if length($v[$i]) xor length($v[$i+1]);
454     }
455     length($v[2]) or length($v[4]) or
456         &$bad_data("commodity entry with no buy or sell offer");
457     
458     return @v;
459 }
460
461 sub cgi_get_caller () {
462     my $caller= $ENV{'REMOTE_ADDR'};
463     $caller= 'LOCAL' unless defined $caller;
464
465     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
466     if (defined $fwdf) {
467         $fwdf =~ s/\s//g;
468         $fwdf =~ s/[^0-9.,]/?/g;
469         $caller= "$fwdf";
470     }
471     return $caller;
472 }
473
474 sub set_ctype_utf8 () {
475     setlocale(LC_CTYPE, "en.UTF-8");
476 }
477
478 sub http_useragent_string_map ($$) {
479     my ($caller_lib_agent, $reason_style_or_caller) = @_;
480     $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
481     $caller_lib_agent =~ s/\s/_/g;
482     my $version= version_core();
483     return "yarrg/$version ($reason_style_or_caller)".
484            " $caller_lib_agent".
485            " (http://yarrg.chiark.net/intro)";
486 }
487
488 sub http_useragent ($) {
489     my ($who) = @_;
490     my $ua= LWP::UserAgent->new;
491     my $base= $ua->_agent();
492     $ua->agent(http_useragent_string_map($base, $who));
493     return $ua;
494 }
495
496 sub source_tarball ($$) {
497     my ($sourcebasedir,$spitoutfn) = @_;
498
499     my $pipe= new IO::Pipe or die $!;
500     my $pid= fork();  defined $pid or die $!;
501     if (!$pid) {
502         $ENV{'YPPSC_YARRG_SRCBASE'}= $sourcebasedir;
503         $pipe->writer();
504         exec '/bin/sh','-c','
505                 cd -P "$YPPSC_YARRG_SRCBASE"
506                 (
507                  git-ls-files -z;
508                  git-ls-files -z --others --exclude-from=.gitignore;
509                  if test -d .git; then find .git -print0; fi
510                 ) | (
511                  cpio -Hustar -o --quiet -0 -R 1000:1000 || \
512                  cpio -Hustar -o --quiet -0
513                 ) | gzip
514         ';
515         die $!;
516     }
517     $pipe->reader();
518
519     my ($d, $l);
520     while ($l= read $pipe, $d, 65536) {
521         $spitoutfn->($d);
522     }
523     waitpid $pid,0;
524     defined $l or die "read pipe $!";
525     $pipe->error and die "pipe error $!";
526     close $pipe;
527     # deliberately ignore errors
528 }
529
530 1;