chiark / gitweb /
WIP Much rework for new upload arrangements and new name
[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
27 use strict;
28 use warnings;
29
30 BEGIN {
31     use Exporter ();
32     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33     $VERSION     = 1.00;
34     @ISA         = qw(Exporter);
35     @EXPORT      = qw(&parse_info1 &rsync_master
36                       &parse_info_serverside &parse_info_serverside_ocean
37                       %oceans %commods %clients %routes %route_mysteries
38                       &parse_pctb_commodmap %pctb_commodmap @pctb_commodmap
39                       &get_our_version &check_tsv_line
40                       &pipethrough_prep &pipethrough_run
41                       &pipethrough_run_along &pipethrough_run_finish
42                       &pipethrough_run_gzip
43                       &cgipostform);
44     %EXPORT_TAGS = ( );
45
46     @EXPORT_OK   = qw();
47 }
48
49 our %oceans; # eg $oceans{'Midnight'}{'Ruby'}{'Eta Island'}= $sources;
50 our %commods; # eg $commods{'Fine black cloth'}= $sources;
51 our %clients; # eg $clients{'ypp-sc-tools'}= [ qw(last-page) ];
52 our %routes; # eg $routes{'Midnight'}{'Orca'}{'Tinga'}= $sources  NB abbrevs!
53 our %route_mysteries; # eg $route_mysteries{'Midnight'}{'Norse'}= 3
54 # $sources = 's[l]b';
55 #       's' = Special Circumstances; 'l' = local ; B = with Bleach
56
57 our (%pctb_commodmap,@pctb_commodmap);
58
59 my %colours; # eg $colours{'c'}{'black'}= $sources
60 my @rawcm; # eg $rawcm[0]='fine rum'; $rawcm[1]='fine %c cloth'
61
62 sub parse_info1 ($$) {
63     my ($mmfn,$src)= @_;
64     my $mm= new IO::File $mmfn, 'r' or die "$mmfn $!";
65     my @ctx= ();
66     while (<$mm>) {
67         next if m/^\s*\#/;
68         next unless m/\S/;
69         s/\s+$//;
70         if (m/^\%(\w+)$/) {
71             my $colourkind= $1;
72             @ctx= (sub { $colours{$colourkind}{lc $_} .= $src; });
73         } elsif (m/^commods$/) {
74             @ctx= (sub { push @rawcm, lc $_; });
75         } elsif (m/^ocean (\w+)$/) {
76             my $ocean= $1;
77             @ctx= (sub {
78                 $ocean or die; # ref to $ocean needed to work
79                                # around a perl bug
80                 my $arch= $_;
81                 $ctx[1]= sub {
82                     $oceans{$ocean}{$arch}{$_} .= $src;
83                 };
84             });
85         } elsif (m/^routes (\w+)$/) {
86             my $ocean= $1;
87             @ctx= (sub {
88                 m/^(\S[^\t]*\S),\s*(\S[^\t]*\S),\s*([1-9][0-9]{0,2})$/ or die;
89                 $routes{$ocean}{$1}{$2}= $3;
90             });
91         } elsif (m/^client (\S+.*\S)$/) {
92             my $client= $1;
93             $clients{$client}= [ ];
94             @ctx= (sub {
95                 my $bug= $_;
96                 push @{ $clients{$client} }, $bug;
97             });
98         } elsif (s/^ +//) {
99             my $indent= length $&;
100             die "wrong indent $indent" unless defined $ctx[$indent-1];
101             &{ $ctx[$indent-1] }();
102         } else {
103             die "bad syntax";
104         }
105     }
106     $mm->error and die $!;
107     close $mm or die $!;
108
109 #print Dumper(\%oceans);
110 #print Dumper(\@rawcm);
111         
112     %commods= ();
113     my $ca;
114     $ca= sub {
115         my ($s,$ss) = @_;
116 #print "ca($s)\n";
117         if ($s !~ m/\%(\w+)/) { $commods{ucfirst $s} .= $ss; return; }
118         die "unknown $&" unless defined $colours{$1};
119         foreach my $c (keys %{ $colours{$1} }) {
120             &$ca($`.$c.$', $ss .'%'. $colours{$1}{$c});
121         }
122     };
123     foreach (@rawcm) { &$ca($_,$src); }
124
125     foreach my $on (keys %routes) {
126         my $routes= $routes{$on};
127         my $ocean= $oceans{$on};
128         die unless defined $ocean;
129         
130         my @allislands;
131         foreach my $an (sort keys %$ocean) {
132             my $arch= $ocean->{$an};
133             push @allislands, sort keys %$arch;
134         }
135         parse_info_maproutes($on, \@allislands, $routes);
136         foreach my $route (values %$routes) {
137             parse_info_maproutes($on, \@allislands, $route);
138         }
139     }
140 }
141
142 sub parse_info_clientside () {
143     my $yarrg= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
144     return unless $yarrg;
145     my $master= fetch_with_rsync('info');
146     parse_info1($master,'s');
147     parse_info1('_local-info.txt','s');
148 }
149
150 sub fetch_with_rsync ($) {
151     my ($stem) = @_;
152
153     my $rsync= $ENV{'YPPSC_YARRG_RSYNC'};
154     $rsync= 'rsync' if !defined $rsync;
155
156     my $local= "_master-$stem.txt";
157     my $src= $ENV{'YPPSC_YARRG_DICT_UPDATE'};
158     if ($src) {
159         my $remote= "$src/master-$stem.txt";
160         $!=0; system 'rsync','-Lt','--',$remote,$local;
161         die "$? $!" if $! or $?;
162     }
163 }
164
165 sub parse_info_maproutes ($$$) {
166     my ($on, $allislands, $routemap) = @_;;
167     foreach my $k (sort keys %$routemap) {
168         my @ok= grep { index($_,$k) >= 0 } @$allislands;
169         die "ambiguous $k" if @ok>1;
170         if (!@ok) {
171             $route_mysteries{$on}{$k}++;
172             delete $routemap->{$k};
173         } elsif ($ok[0] ne $k) {
174             $routemap->{$ok[0]}= $routemap->{$k};
175             delete $routemap->{$k};
176         }
177     }
178 }
179
180 sub parse_info_serverside () {
181     parse_info1('master-info.txt','s');
182 }
183 sub parse_info_serverside_ocean ($) {
184     my ($oceanname) = @_;
185     die "unknown ocean $oceanname ?" unless exists $oceans{$oceanname};
186     parse_info1("ocean-".(lc $oceanname).".txt",'s');
187 }
188
189 sub parse_pctb_commodmap () {
190     undef %pctb_commodmap;
191     foreach my $commod (keys %commods) { $commods{$commod} =~ s/b//; }
192
193     my $c= new IO::File '_commodmap.tsv' or die $!;
194     if (!$c) { $!==&ENOENT or die $!; return 0; }
195
196     while (<$c>) {
197         m/^(\S.*\S)\t(\d+)\n$/ or die "$_";
198         die if defined $pctb_commodmap{$1};  $pctb_commodmap{$1}= $2;
199         die if defined $pctb_commodmap[$2];  $pctb_commodmap[$2]= $1;
200         $commods{$1} .= 'b';
201     }
202     $c->error and die $!;
203     close $c or die $!;
204     return 1;
205 }
206
207 sub get_our_version ($$) {
208     my ($aref,$prefix) = @_;
209     $aref->{"${prefix}name"}= 'ypp-sc-tools yarrg';
210     $aref->{"${prefix}fixes"}= 'lastpage';
211
212     my $version= `git-describe --tags HEAD`; $? and die $?;
213     chomp($version);
214     $aref->{"${prefix}version"}= $version;
215     return $aref;
216 }
217
218 sub pipethrough_prep () {
219     my $tf= IO::File::new_tmpfile() or die $!;
220     return $tf;
221 }
222
223 sub pipethrough_run_along ($$$@) {
224     my ($tf, $childprep, $cmd, @a) = @_;
225     $tf->flush or die $!;
226     $tf->seek(0,0) or die $!;
227     my $fh= new IO::File;
228     my $child= $fh->open("-|"); defined $child or die $!;
229     if (!$child) {
230         open STDIN, "<&", $tf;
231         &$childprep() if defined $childprep;
232         exec $cmd @a; die "@a $!";
233     }
234     return $fh;
235 }
236 sub pipethrough_run_finish ($$) {
237     my ($fh, $what)= @_;
238     $fh->error and die $!;
239     close $fh or die "$what $! $?";  die $? if $?;
240 }
241
242 sub pipethrough_run ($$$@) {
243     my ($tf, $childprep, $cmd, @a) = @_;
244     my $pt= pipethrough_run_along($tf,$childprep,$cmd,@a);
245     my $r;
246     { undef $/; $!=0; $r= <$pt>; }
247     defined $r or die $!;
248     pipethrough_run_finish($pt, "@a");
249     return $r;
250 }
251 sub pipethrough_run_gzip ($) {
252     pipethrough_run($_[0],undef,'gzip','gzip');
253 }
254
255 sub cgipostform ($$$) {
256     my ($ua, $url, $form) = @_;
257     my $req= HTTP::Request::Common::POST($url,
258                                          Content => $form,
259                                          Content_Type => 'form-data');
260     if ($url =~ m,^\.?/,) {
261         my $tf= pipethrough_prep();
262         print $tf $req->content() or die $!;
263 #print STDERR "[[[",$req->content(),"]]]";
264         my $out= pipethrough_run($tf, sub {
265             $ENV{'REQUEST_METHOD'}= 'POST';
266             $ENV{'QUERY_STRING'}= '';
267             $ENV{'PATH_TRANSLATED'}= $url;
268             $ENV{'PATH_INFO'}= '';
269             $ENV{'HTTP_HOST'}= 'localhost';
270             $ENV{'REMOTE_ADDR'}= '127.0.0.1';
271             $ENV{'GATEWAY_INTERFACE'}= 'CGI/1.1';
272             $ENV{'DOCUMENT_ROOT'}= '.';
273             $ENV{'SCRIPT_FILENAME'}= $url;
274             $ENV{'SCRIPT_NAME'}= $url;
275             $ENV{'HTTP_USER_AGENT'}= 'Commods.pm local test';
276
277             foreach my $f (qw(Content_Length Content_Type)) {
278                 $ENV{uc $f}= $req->header($f);
279             }
280 #system 'printenv >&2';
281         }, "$url", "$url");
282         $out =~ s/\r\n/\n/g;
283         $out =~ m,^Content-Type: text/plain.*\n\n, or die "$out ?";
284         return $';
285     } else {
286         my $resp= $ua->request($url,$req);
287         die $resp->status_line unless $resp->is_success;
288         return $resp->content();
289     }
290 }
291
292 our %check_tsv_done;
293
294 sub check_tsv_line ($$) {
295     my ($l, $bad_data_callback) = @_;
296     my $bad_data= sub { &$bad_data_callback("bad data: line $.: $_[0]"); };
297     
298     chomp($l) or &$bad_data('missing end-of-line');
299
300     $l !~ m/\P{IsPrint}/ or &$bad_data('nonprinting char(s)');
301     my @v= split /\t/, $l, -1;
302     @v==6 or &$bad_data('wrong number of fields');
303     my ($commod,$stall) = @v;
304
305     !keys %commods or
306         defined $commods{$commod} or
307         &$bad_data("unknown commodity \`$commod'");
308     
309     $stall =~ m/^\p{IsUpper}|^[0-9]/ or &$bad_data("stall not capitalised");
310     !exists $check_tsv_done{$commod,$stall} or &$bad_data("repeated data");
311     $check_tsv_done{$commod,$stall}= 1;
312     foreach my $i (2..5) {
313         my $f= $v[$i];
314         $f =~ m/^(|0|[1-9][0-9]{0,5}|\>1000)$/ or &$bad_data("bad field $i");
315         ($i % 2) or ($f !~ m/\>/) or &$bad_data("> in field $i price");
316     }
317
318     foreach my $i (2,4) {
319         &$bad_data("price with no qty or vice versa (field $i)")
320             if length($v[$i]) xor length($v[$i+1]);
321     }
322     length($v[2]) or length($v[4]) or
323         &$bad_data("commodity entry with no buy or sell offer");
324     
325     return @v;
326 }
327
328 1;