chiark / gitweb /
Merge branch 'wip.commodclass'
[ypp-sc-tools.db-test.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 HTTP::Request::Common ();
26 use POSIX;
27 use LWP::UserAgent;
28
29 use strict;
30 use warnings;
31
32 BEGIN {
33     use Exporter ();
34     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
35     $VERSION     = 1.00;
36     @ISA         = qw(Exporter);
37     @EXPORT      = qw(&parse_info_clientside &fetch_with_rsync
38                       &parse_info_serverside &parse_info_serverside_ocean
39                       %oceans %commods %clients
40                       %vessels %shotname2damage
41                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
42                       &get_our_version &check_tsv_line
43                       &pipethrough_prep &pipethrough_run
44                       &pipethrough_run_along &pipethrough_run_finish
45                       &pipethrough_run_gzip &http_useragent &version_core
46                       &http_useragent_string_map
47                       &cgipostform &yarrgpostform &cgi_get_caller
48                       &set_ctype_utf8 $masterinfoversion);
49     %EXPORT_TAGS = ( );
50
51     @EXPORT_OK   = qw();
52 }
53
54 our $masterinfoversion= 2; # version we understand.
55 #
56 # To extend the source-info.txt format:
57 #
58 #    * Commods.pm:parse_info1
59 #       add code to parse new version
60 #
61 #    * source-info.txt
62 #       add new information
63 #
64 # If new data should NOT be in master-info.txt too:
65 #
66 #    * update-master-info:process_some_info
67 #       check that code for converting source-info to master-info
68 #       removes the extra info; add code to remove it if necessary
69 #
70 #    * db-idempotent-populate
71 #       if database schema is extended, add code to copy data
72 #
73 # If new data DOES need to be in master-info.txt too:
74 #
75 #    * Commods.pm:$masterinfoversion
76 #       increment
77 #
78 #    * update-master-info:process_some_info
79 #       add code to convert new version to old, by removing
80 #       extra info conditionally depending on version
81
82 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
83 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
84 our %vessels; # eg $vessels{'War Brig'}{Shot}='medium'
85               #    $vessels{'War Brig'}{Volume}= 81000
86               #    $vessels{'War Brig'}{Mass}= 54000
87 our %shotname2damage; # eg $shotname2damage{'medium'}= 3;
88 # $sources = 's[l]b';
89 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
90
91 our %commods;
92 # eg $commods{'Fine black cloth'}{Srcs}= $sources;
93 # eg $commods{'Fine black cloth'}{Mass}= 700 [g]
94 # eg $commods{'Fine black cloth'}{Volume}= 1000 [ml]
95
96 our (%pctb_commodmap,@pctb_commodmap);
97
98 my %colours; # eg $colours{'c'}{'black'}= $sources
99 my (@rawcm, @nocm); # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
100
101 my %colour_ordvals; # $colour_ordvals{'c'}{'green'}= '30';
102 my %commodclasses; # $commodclasses{'dye'}= '3';
103
104 # IMPORTANT
105 #  when extending the format of source-info in a non-backward
106 #  compatible way, be sure to update update-master-info too.
107
108 sub parse_info1 ($$$) {
109     my ($mmfn,$src,$enoentok)= @_;
110     my $mm= new IO::File $mmfn, 'r';
111     if (!$mm) {
112         return if $enoentok && $!==&ENOENT;
113         die "$mmfn $!";
114     }
115     my @ctx= ();
116     while (<$mm>) {
117         next if m/^\s*\#/;
118         next unless m/\S/;
119         s/\s+$//;
120         if (m/^\%(\w+)$/) {
121             my $colourkind= $1;
122             @ctx= (sub {
123                 m/^(\S[^\t@]+\S)(?:\t+\@(\d+))?$/ or die;
124                 my ($colour,$order)=($1,$2);
125                 $colours{$colourkind}{$colour} .= $src;
126                 $colour_ordvals{$colourkind}{$colour}= $order
127                     if defined $order;
128             });
129         } elsif (m/^commods$/) {
130             @ctx= (sub { push @rawcm, lc $_; });
131         } elsif (m/^nocommods$/) {
132             @ctx= (sub { push @nocm, lc $_; });
133         } elsif (m/^commodclasses$/) {
134             @ctx= (sub {
135                 die unless m/^\*([-a-z]+)$/;
136                 $commodclasses{$1}= scalar keys %commodclasses;
137             });
138         } elsif (m/^ocean (\w+)$/) {
139             my $ocean= $1;
140             keys %{ $oceans{$ocean} };
141             @ctx= (sub {
142                 $ocean or die; # ref to $ocean needed to work
143                                # around a perl bug
144                 my $arch= $_;
145                 keys %{ $oceans{$ocean}{$arch} };
146                 $ctx[1]= sub {
147                     $oceans{$ocean}{$arch}{$_} .= $src;
148                 };
149             });
150         } elsif (m/^vessels$/) {
151             @ctx= (sub {
152                 return if m/^[-+|]+$/;
153                 m/^ \| \s* ([A-Z][a-z\ ]+[a-z]) \s*
154                     \| \s* (small|medium|large) \s*
155                     \| \s* ([1-9][0-9,]+) \s*
156                     \| \s* ([1-9][0-9,]+) \s*
157                     \| $/x
158                     or die;
159                 my $name= $1;
160                 my $v= { Shot => $2, Volume => $3, Mass => $4 };
161                 foreach my $vm (qw(Volume Mass)) { $v->{$vm} =~ s/,//g; }
162                 $vessels{$name}= $v;
163             });
164         } elsif (m/^shot$/) {
165             @ctx= (sub {
166                 m/^ ([a-z]+) \s+ (\d+) $/x or die;
167                 $shotname2damage{$1}= $2;
168             });
169         } elsif (m/^client (\S+.*\S)$/) {
170             my $client= $1;
171             $clients{$client}= [ ];
172             @ctx= (sub {
173                 my $bug= $_;
174                 push @{ $clients{$client} }, $bug;
175             });
176         } elsif (s/^ +//) {
177             my $indent= length $&;
178             die "wrong indent $indent" unless defined $ctx[$indent-1];
179             &{ $ctx[$indent-1] }();
180         } else {
181             die "bad syntax";
182         }
183     }
184     $mm->error and die $!;
185     close $mm or die $!;
186
187 #print Dumper(\%oceans);
188 #print Dumper(\@rawcm);
189         
190     %commods= ();
191     my $ca;
192     $ca= sub {
193         my ($s,$ss,$ordbase) = @_;
194 #print STDERR "ca($s,,".(defined $ordbase ? $ordbase : '?').")\n";
195         if ($s !~ m/\%(\w+)/) {
196             my ($name, $props) = $s =~
197                 /^(\S[^\t]*\S)(?:\t+(\S.*\S))?$/
198                 or die "bad commodspec $s";
199             return if grep { $name eq $_ } @nocm;
200             my $ucname= ucfirst $name;
201             $commods{$ucname}{Srcs} .= $ss;
202             my $c= $commods{$ucname};
203             $c->{Volume}= 1000;
204             my ($ordval, $ordclassval);
205             foreach my $prop (defined $props ? split /\s+/, $props : ()) {
206                 if ($prop =~ m/^([1-9]\d*)(k?)g$/) {
207                     $c->{Mass}= $1 * ($2 ? 1000 : 1);
208                 } elsif ($prop =~ m/^([1-9]\d*)l$/) {
209                     $c->{Volume}= $1 * 1000;
210                 } elsif ($prop =~ m/^\*([-a-z]+)$/) {
211                     $c->{Class}= $1;
212                     die "$1" unless exists $commodclasses{$1};
213                     $ordclassval= $commodclasses{$1} * 1000000;
214                 } elsif ($prop =~ m/^\@(\d+)$/) {
215                     $ordval= $1;
216                 } else {
217                     die "unknown property $prop for $ucname";
218                 }
219             }
220             if (defined $ordbase && defined $ordval && defined $ordclassval) {
221                 my $ordvalout= $ordbase + $ordval + $ordclassval;
222                 $c->{Ordval}= $ordvalout;
223 print STDERR "ordval $ordvalout $name OV=$ordval OB=$ordbase OCV=$ordclassval\n";
224             } else {
225 print STDERR "ordval NONE $name\n";
226             }
227             return;
228         }
229         die "unknown $&" unless defined $colours{$1};
230         my ($lhs,$pctlet,$rhs)= ($`,$1,$');
231         foreach my $c (keys %{ $colours{$pctlet} }) {
232             my $ordcolour= $colour_ordvals{$pctlet}{$c};
233             &$ca($lhs.$c.$rhs,
234                  $ss .'%'. $colours{$pctlet}{$c},
235                  defined($ordbase) && defined($ordcolour)
236                      ? $ordbase+$ordcolour : undef);
237         }
238     };
239     foreach (@rawcm) { &$ca($_,$src,0); }
240 }
241
242 sub parse_info_clientside () {
243     my $master= fetch_with_rsync("info-v$masterinfoversion");
244     parse_info1($master,'s',1);
245     parse_info1('_local-info.txt','s',1);
246 }
247
248 sub fetch_with_rsync ($) {
249     my ($stem) = @_;
250
251     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
252     $rsync= 'rsync' if !defined $rsync;
253
254     my $local= "_master-$stem.txt";
255     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
256     if ($src) {
257         my $remote= "$src/master-$stem.txt";
258         $!=0; system 'rsync','-Lt','--',$remote,$local;
259         die "$? $!" if $! or $?;
260     }
261     return $local;
262 }
263
264 sub parse_info_serverside () {
265     parse_info1('source-info.txt','s',0);
266 }
267 sub parse_info_serverside_ocean ($) {
268     my ($oceanname) = @_;
269     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
270     parse_info1("_ocean-".(lc $oceanname).".txt", 's',0);
271 }
272
273 sub parse_pctb_commodmap () {
274     undef %pctb_commodmap;
275     foreach my $commod (keys %commods) { $commods{$commod}{Srcs} =~ s/b//; }
276
277     my $c= new IO::File '_commodmap.tsv';
278     if (!$c) { $!==&ENOENT or die $!; return 0; }
279
280     while (<$c>) {
281         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
282         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
283         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
284         $commods{$1}{Srcs} .= 'b';
285     }
286     $c->error and die $!;
287     close $c or die $!;
288     return 1;
289 }
290
291 sub get_our_version ($$) {
292     my ($aref,$prefix) = @_;
293     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
294     $aref->{"${prefix}fixes"}= 'lastpage checkpager';
295     $aref->{"${prefix}version"}= version_core();
296     return $aref;
297     # clientname        "ypp-sc-tools"
298     # clientversion     2.1-g2e06a26  [from git-describe --tags HEAD]
299     # clientfixes       "lastpage"  [space separated list]
300 }
301
302 sub version_core () {
303     my $version= `
304         if type -p git-describe >/dev/null 2>&1; then
305                 gd=git-describe
306         else
307                 gd="git describe"
308         fi
309         \$gd --tags HEAD || echo 0unknown
310     `; $? and die $?;
311     chomp($version);
312     return $version;
313 }
314
315 sub pipethrough_prep () {
316     my $tf= IO::File::new_tmpfile() or die $!;
317     return $tf;
318 }
319
320 sub pipethrough_run_along ($$$@) {
321     my ($tf, $childprep, $cmd, @a) = @_;
322     $tf->error and die $!;
323     $tf->flush or die $!;
324     $tf->seek(0,0) or die $!;
325     my $fh= new IO::File;
326     my $child= $fh->open("-|"); defined $child or die $!;
327     if (!$child) {
328         open STDIN, "<&", $tf;
329         &$childprep() if defined $childprep;
330         exec $cmd @a; die "@a $!";
331     }
332     return $fh;
333 }
334 sub pipethrough_run_finish ($$) {
335     my ($fh, $what)= @_;
336     $fh->error and die $!;
337     close $fh or die "$what $! $?";  die $? if $?;
338 }
339
340 sub pipethrough_run ($$$@) {
341     my ($tf, $childprep, $cmd, @a) = @_;
342     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
343     my $r;
344     { undef $/; $!=0; $r= <$pt>; }
345     defined $r or die $!;
346     pipethrough_run_finish($pt, "@a");
347     return $r;
348 }
349 sub pipethrough_run_gzip ($) {
350     pipethrough_run($_[0],undef,'gzip','gzip');
351 }
352
353 sub yarrgpostform ($$) {
354     my ($ua, $form) = @_;
355     my $dest= $ENV{'YPPSC_YARRG_YARRG'};
356     get_our_version($form, 'client');
357     die unless $dest =~ m,/$,;
358     return cgipostform($ua, "${dest}commod-update-receiver", $form);
359 }    
360
361 sub cgipostform ($$$) {
362     my ($ua, $url, $form) = @_;
363     my $req= HTTP::Request::Common::POST($url,
364                                          Content => $form,
365                                          Content_Type => 'form-data');
366     if ($url =~ m,^\.?/,) {
367         my $tf= pipethrough_prep();
368         print $tf $req->content() or die $!;
369 #print STDERR "[[[",$req->content(),"]]]";
370         my $out= pipethrough_run($tf, sub {
371             $ENV{'REQUEST_METHOD'}= 'POST';
372             $ENV{'QUERY_STRING'}= '';
373             $ENV{'PATH_TRANSLATED'}= $url;
374             $ENV{'PATH_INFO'}= '';
375             $ENV{'HTTP_HOST'}= 'localhost';
376             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
377             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
378             $ENV{'DOCUMENT_ROOT'}= '.';
379             $ENV{'SCRIPT_FILENAME'}= $url;
380             $ENV{'SCRIPT_NAME'}= $url;
381             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
382
383             foreach my $f (qw(Content_Length Content_Type)) {
384                 $ENV{uc $f}= $req->header($f);
385             }
386 #system 'printenv >&2';
387         }, "$url", "$url");
388         $out =~ s/\r\n/\n/g;
389         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
390         return $';
391     } else {
392         my $resp= $ua->request($req);
393         die $resp->status_line."\n".$resp->content."\n "
394             unless $resp->is_success;
395         return $resp->content();
396     }
397 }
398
399 our %check_tsv_done;
400
401 sub check_tsv_line ($$) {
402     my ($l, $bad_data_callback) = @_;
403     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
404     
405     chomp($l) or &$bad_data('missing end-of-line');
406
407     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
408     my @v= split /\t/, $l, -1;
409     @v==6 or &$bad_data('wrong number of fields');
410     my ($commod,$stall) = @v;
411
412     !keys %commods or
413         defined $commods{$commod} or
414         &$bad_data("unknown commodity \`$commod'");
415     
416     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
417     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
418     $check_tsv_done{$commod,$stall}= 1;
419     foreach my $i (2..5) {
420         my $f= $v[$i];
421         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
422         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
423     }
424
425     foreach my $i (2,4) {
426         &$bad_data("price with no qty or vice versa (field $i)")
427             if length($v[$i]) xor length($v[$i+1]);
428     }
429     length($v[2]) or length($v[4]) or
430         &$bad_data("commodity entry with no buy or sell offer");
431     
432     return @v;
433 }
434
435 sub cgi_get_caller () {
436     my $caller= $ENV{'REMOTE_ADDR'};
437     $caller= 'LOCAL' unless defined $caller;
438
439     my $fwdf= $ENV{'HTTP_X_FORWARDED_FOR'};
440     if (defined $fwdf) {
441         $fwdf =~ s/\s//g;
442         $fwdf =~ s/[^0-9.,]/?/g;
443         $caller= "$fwdf";
444     }
445     return $caller;
446 }
447
448 sub set_ctype_utf8 () {
449     setlocale(LC_CTYPE, "en.UTF-8");
450 }
451
452 sub http_useragent_string_map ($$) {
453     my ($caller_lib_agent, $reason_style_or_caller) = @_;
454     $caller_lib_agent =~ y/A-Za-z/N-ZA-Mn-za-m/;
455     $caller_lib_agent =~ s/\s/_/g;
456     my $version= version_core();
457     return "yarrg/$version ($reason_style_or_caller)".
458            " $caller_lib_agent".
459            " (http://yarrg.chiark.net/intro)";
460 }
461
462 sub http_useragent ($) {
463     my ($who) = @_;
464     my $ua= LWP::UserAgent->new;
465     my $base= $ua->_agent();
466     $ua->agent(http_useragent_string_map($base, $who));
467     return $ua;
468 }
469
470 1;