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