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