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