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