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