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