chiark / gitweb /
Approve client "jpctb greenend"
[ypp-sc-tools.main.git] / yarrg / commod-results-processor
1 #!/usr/bin/perl -w
2
3 # helper program for processing commodity output
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27
28 use strict (qw(vars));
29 use HTTP::Request;
30 use IO::File;
31 use POSIX;
32 use XML::Parser;
33
34 use Commods;
35
36 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Stall}
37 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Price}
38 # $commod{'Hemp'}{Buy|Sell}{'stall'}{Qty}
39 # $commod{'Hemp'}{Hold}
40
41 our @v;
42 our ($commod,$stall,%commod);
43
44 @ARGV==1 or die "You probably don't want to run this program directly.\n";
45 our ($mode) = shift @ARGV;
46
47 # ./yppsc-commod-processor tsv <t |less -x40,80,90,100,110
48
49 sub bs_read ($$) {
50     my ($bs,$c) = @_;
51     return if @v <= $c;
52     my ($price,$qty) = @v[$c..$c+1];
53     return if !length($price) && !length($qty);
54     die "$price ?" unless $price =~ m/^\d/;
55     die "$_ ?" unless length($price) && length($qty);
56     $commod{$commod}{$bs}{$stall}= {
57         Stall => $stall,
58         Price => $price,
59         Qty => $qty,
60     };
61 }
62
63 while (<>) {
64     chomp;
65     @v= split /\t/;
66 #print STDERR "[".join("|",@v)."]\n";
67     foreach (@v[2..$#v]) {
68         s/\,//g;
69         die "$_ ?" if m/.\D/;
70     }
71     ($commod,$stall) = @v;
72     bs_read(Buy,  2);
73     bs_read(Sell, 4);
74     $commod{$commod}{Hold}= $v[6]+0 if @v>6;
75 }
76
77 our $current;
78
79 sub bs_p ($$$) {
80     my ($commod,$bs,$sortmul) = @_;
81     my $ary= $current->{$bs};
82     my $r= [ ];
83 #print Dumper($ary);
84     foreach my $stall (sort {
85         $sortmul * ($ary->{$a}{Price} <=> $ary->{$b}{Price});
86     } keys %$ary) {
87         push @$r, $ary->{$stall};
88     }
89     return $r;
90 }
91
92 sub bs_p_bestprice ($) {
93     my ($l) = @_;
94     if (@$l) {
95         printf("| %-25.25s %4d", $l->[0]{Stall}, $l->[0]{Price}) or die $!;
96     } else {
97         printf("| %25s %4s","","") or die $!;
98     }
99 }
100
101 sub main__arbitrage () {
102     my @arbs= ();
103     foreach $commod (sort keys %commod) {
104         $current= $commod{$commod};
105         my @buys=  @{ bs_p($commod,Buy, -1) };
106         my @sells= @{ bs_p($commod,Sell,+1) };
107         my $profit= 0;
108         my $cqty= 0;
109         my $info= '';
110         my $arbs= [];
111         for (;;) {
112 #print Dumper($commod,\@buys,\@sells);
113             last unless @buys;
114             last unless @sells;
115             my $pricediff= $buys[0]{Price} - $sells[0]{Price};
116             last unless $pricediff > 0;
117             our $qty= 1000;
118             sub arb_check_qty (\@) {
119                 my ($verbs) = @_;
120                 my $vqty= $verbs->[0]{Qty};
121                 return if $vqty =~ m/^\>/;
122                 $qty= $vqty if $qty > $vqty;
123                 return if $vqty;
124                 my $verb= shift @$verbs;
125             }
126             arb_check_qty(@buys);
127             arb_check_qty(@sells);
128             next unless $qty;
129             my $tprofit= $qty*$pricediff;
130             $profit += $tprofit;
131             $cqty += $qty;
132             
133             $info.=
134                 sprintf("%-13.13s| %-19.19s %4d| %-19.19s %4d|%3d x%3d =%3d\n",
135                        $commod,
136                        $sells[0]{Stall},$sells[0]{Price},
137                        $buys[0]{Stall},$buys[0]{Price},
138                        $qty, $pricediff, $tprofit);
139             sub arb_subtract_qty (\@) {
140                 my ($verbs) = @_;
141                 my $verb= shift @$verbs;
142                 my $vqty= $verb->{Qty};
143                 $vqty =~ s/^\>//;
144                 unshift @$verbs, {
145                     Stall => $verb->{Stall},
146                     Price => $verb->{Price},
147                     Qty => $vqty - $qty
148                 };
149             }
150             arb_subtract_qty(@buys);
151             arb_subtract_qty(@sells);
152         }
153         next unless $profit;
154         $info.=
155             sprintf("%-13.13s| %19s %4s| %19s %4s|%3d      %4d\n",
156                     $commod, '','', '','', $cqty, $profit);
157         push @arbs, { Profit => $profit, Info => $info };
158     }
159     my $allprofit;
160
161     if (!@arbs) {
162         print "No arbitrage opportunities.\n" or die $!;
163         return;
164     }
165     my $bigdiv= <<END;
166 =============+=========================+=========================+=============
167 END
168
169     print <<END or die $!;
170
171 commodity    | seller             price| buyer              price| qty  ea prof
172 END
173
174     my $div= $bigdiv;
175     foreach my $arb (sort {
176         $b->{Profit} <=> $a->{Profit};
177     } @arbs) {
178         print $div,$arb->{Info} or die $1;
179         $div= <<END;
180 -------------+-------------------------+-------------------------+-------------
181 END
182         $allprofit += $arb->{Profit};
183     }
184     print $bigdiv or die $!;
185     printf("%-13.13s  %19s %4s  %19s %4s %-5s %7d\n",
186            '', '','', '','', 'TOTAL', $allprofit)
187         or die $!;
188 }
189
190 sub main__bestprices () {
191     foreach $commod (sort keys %commod) {
192         $current= $commod{$commod};
193         my $buys=  bs_p($commod,Buy, -1);
194         my $sells= bs_p($commod,Sell,+1);
195         printf("%-15.15s", $commod) or die $!;
196         bs_p_bestprice($buys);
197         bs_p_bestprice($sells);
198         print("\n") or die $!;
199     }
200 }
201
202 sub bs_p_tsv ($$) {
203     my ($f, $bs) = @_;
204     if (exists $current->{$bs}{$stall}) {
205         my $si= $current->{$bs}{$stall};
206         printf($f "\t%d\t%s", $si->{Price}, $si->{Qty}) or die $!;
207     } else {
208         printf($f "\t\t") or die $!;
209     }
210 }
211
212 sub write_tsv ($$) {
213     my ($f,$showhold) = @_;
214     foreach $commod (sort keys %commod) {
215         $current= $commod{$commod};
216         my %stalls;
217         map { $stalls{$_}=1; } keys %{ $current->{Buy}  };
218         map { $stalls{$_}=1; } keys %{ $current->{Sell} };
219         foreach $stall (sort keys %stalls) {
220             printf($f "%s\t%s", $commod, $stall) or die $!;
221             bs_p_tsv($f, Buy);
222             bs_p_tsv($f, Sell);
223             if ($showhold && $commod{$commod}{Hold}) {
224                 printf($f "\t%s", $commod{$commod}{Hold}) or die $!;
225             }
226             print($f "\n") or die $!;
227         }
228     }
229     $f->error and die $!;
230     $f->flush or die $!;
231 }
232
233 sub main__tsv () {
234     write_tsv(\*STDOUT,1);
235 }
236
237
238 our ($pctb) = $ENV{'YPPSC_YARRG_PCTB'};
239
240 our ($ua)= http_useragent("commod-results-processor $mode");
241
242 sub refresh_commodmap() {
243     die unless $pctb;
244     $pctb =~ s,/*$,,;
245     my $resp= $ua->get("$pctb/commodmap.php?version=2");
246     die $resp->status_line unless $resp->is_success;
247
248     my $cdata='';
249     my $incommodmap=0;
250     my $intag='';
251     my %got;
252     my $o= new IO::File "_commodmap.tsv.tmp",'w' or die $!;
253     undef %pctb_commodmap;
254
255     my $xp= new XML::Parser
256         (Handlers =>
257          {
258              Start => sub {
259                  $_=$_[1];
260 #print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
261                  if (m/^commodmap$/i) {
262                      $incommodmap++;
263                      undef %got;
264                  } elsif (m/^(?:name|index)$/i) {
265                      $cdata='';
266                      $intag=lc($_) if $incommodmap;
267 #print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
268 #                } else {
269 #print STDERR "START UNRECOGNISED\n";
270                  }
271              },
272              End => sub {
273                  $_=$_[1];
274 #print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
275                  if (m/^commodmap$/i) {
276                      $incommodmap--;
277                      die unless exists $got{'name'};
278                      die unless exists $got{'index'};
279                      die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
280                      my $index= $1;
281                      $_= $got{'name'};
282                      s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
283                      die "$_ ?" if exists $pctb_commodmap{$_};
284                      $pctb_commodmap{$_}= $index;
285                      print $o "$_\t$index\n" or die $!;
286                  } elsif (lc $_ eq $intag) {
287                      $got{$intag}= $cdata;
288                  }
289              },
290              Char => sub {
291 #print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
292                  $cdata .= $_[1];
293              }
294          }) or die;
295     my $content= $resp->content;
296
297 #    print STDERR "[[[$content]]]\n";
298     my $commodmapxmltmp= '_commodmap.xml';
299     if (!eval {
300         $xp->parse($content); 1;
301     }) {
302         open R, ">./$commodmapxmltmp" or die $!;
303         print R $content or die $!;
304         close R or die $!;
305         die "$@ parsing commodmap";
306     }
307     unlink $commodmapxmltmp or $!==&ENOENT or die $!;
308     close $o or die $!;
309     rename "_commodmap.tsv.tmp","_commodmap.tsv" or die $!;
310 }
311
312 our %newcommods;
313
314 sub read_newcommods ($) {
315     my ($file) = @_;
316     if (!open NC, "< $file") {
317         $!==&ENOENT or die $!;
318         return;
319     }
320     while (<NC>) {
321         chomp; s/^\s*//; s/\s+$//;
322         next if m/^\#/;
323         next unless m/\S/;
324         $newcommods{$_}= 1;
325     }
326     NC->error and die $!;
327     close NC or die $!;
328 }
329
330 sub refresh_newcommods() {
331     my $master= fetch_with_rsync('newcommods');
332     read_newcommods($master);
333     read_newcommods('_local-newcommods.txt');
334 }
335
336 our (%stallmap, @stallmap);
337
338 sub bs_gen_md ($$) {
339     my ($bs,$sortmul) = @_;
340     my $count= 0;
341     my $o= '';
342     
343     foreach $commod (
344                      sort { $pctb_commodmap{$a} <=> $pctb_commodmap{$b} }
345                      grep { exists $pctb_commodmap{$_} }
346                      keys %commod
347                      ) {
348 #print STDERR "COMMOD $commod\n";
349         $current= $commod{$commod};
350         my $l= bs_p($commod,$bs,$sortmul);
351         next unless @$l;
352 #print STDERR "COMMOD $commod  has ".scalar(@$l)."\n";
353         $o .= writeint($pctb_commodmap{$commod});
354         $o .= writeint(scalar @$l);
355         foreach my $cs (@$l) {
356             $stall= $cs->{Stall};
357             my $stallix= $stallmap{$stall};
358             if (!defined $stallix) {
359                 push @stallmap, $stall;
360                 $stallmap{$stall}= $stallix= @stallmap;
361 #print STDERR "STALL DEF $stallix $stall\n";
362             }
363             my $qty= $cs->{Qty};
364             $qty =~ s/^\>\s*//;
365             $o .= writeint($stallix, $cs->{Price}, $qty+0);
366             $count++;
367         }
368     }
369 #print STDERR "COMMOD $commod COUNT WAS $count\n";
370     return
371         writeint($count).$o;
372 }
373
374 sub writeint { return pack 'v*', @_; }
375
376 our (%stalltypetoabbrevmap)= qw(
377                                 Apothecary    A
378                                 Distilling    D
379                                 Furnishing    F
380                                 Ironworking   I
381                                 Shipbuilding  S
382                                 Tailoring     T
383                                 Weaving       W
384                                 );
385
386 sub genmarketdata () {
387     our $version= '005b';
388
389     parse_pctb_commodmap();
390     my @missing= grep { !exists $pctb_commodmap{$_} } keys %commod;
391     if (@missing) {
392         refresh_commodmap();
393         refresh_newcommods();
394         my $missing=0;
395         foreach $commod (sort keys %commod) {
396             next if exists $pctb_commodmap{$commod};
397             if (exists $newcommods{$commod}) {
398                 printf STDERR "Ignoring new commodity \`%s'!\n", $commod;
399             } else {
400                 printf STDERR "Unknown commodity \`%s'!\n", $commod;
401                 $missing++;
402             }
403         }
404         die "$missing unknown commoditi(es).".
405             "  See README (search for \`newcommods').\n"
406             if $missing;
407     }    
408
409     my $ob='';
410     $ob .= bs_gen_md(Buy, -1);
411     $ob .= bs_gen_md(Sell,+1);
412
413     my $ot= sprintf("$version\n".
414                     "%d\n",
415                     scalar(@stallmap));
416     foreach $stall (@stallmap) {
417         my $st= $stall;
418         if ($st =~ m/^(\S+)\'s (\S+) Stall$/) {
419             my $stkind= $stalltypetoabbrevmap{$2};
420             if (defined $stkind) {
421                 $st= "$1^$stkind";
422             } else {
423                 warn "unknown stall type $2 in $st\n";
424             }
425         }
426         $ot .= "$st\n";
427     }
428     return $ot.$ob;
429 }
430
431 sub main__genmarketdata () {
432     my $o= genmarketdata();
433     print $o or die $!;
434 }
435
436 sub save_upload_html ($$) {
437     my ($which, $resptxt) = @_;
438     open R, ">./_upload-$which.html" or die $!;
439     print R $resptxt or die $!;
440     close R or die $!;
441 }
442
443 sub gzip ($) {
444     my ($raw) = @_;
445     my $tf= pipethrough_prep();
446     print $tf $raw or die $!;
447     return pipethrough_run($tf,undef,'gzip','gzip');
448 }
449
450 sub main__uploadyarrg () {
451     my %o;
452
453     parse_info_clientside();
454
455     $o{'ocean'}= $ENV{'YPPSC_OCEAN'} or die;
456     $o{'island'}= $ENV{'YPPSC_ISLAND'} or die;
457     $o{'timestamp'}= $ENV{'YPPSC_DATA_TIMESTAMP'} or die;
458
459     my $tf= pipethrough_prep();
460     write_tsv($tf,0);
461     my $oz= pipethrough_run_gzip($tf);
462     $o{'data'}=  [ undef, 'deduped.tsv.gz',
463                     Content_Type => 'application/octet-stream',
464                     Content => $oz ];
465
466     my $respcontent= yarrgpostform($ua, \%o);
467     $respcontent =~ m/^OK\b/ or die "$respcontent ?";
468     $respcontent =~ s/^/ /mg;
469     print $respcontent,"\n";
470 }
471
472 sub main__uploadpctb () {
473     my $ocean= $ENV{'YPPSC_OCEAN'};  die unless $ocean;
474     my $island= $ENV{'YPPSC_ISLAND'};  die unless $island;
475     die unless $pctb;
476     my $o= genmarketdata();
477     $pctb =~ s,/*$,,;
478     my $url= "$pctb/upload.php";
479     my $content= {
480         'marketdata' => [ undef, "marketdata.gz",
481                           Content_Type => 'application/gzip',
482                           Content => gzip($o),
483                           ]
484                       };
485
486     print STDERR "Uploading data to $pctb...\n";
487
488     my $resp= $ua->post("$url", Content => $content,
489                         Content_Type => 'form-data');
490     die $resp->status_line unless $resp->is_success;
491
492     my $resptxt= $resp->content();
493     save_upload_html('1', $resptxt);
494
495     open R, ">./_upload-1.html" or die $!;
496     print R $resptxt or die $!;
497     close R or die $!;
498
499     my @filenames= $resptxt =~
500  m/input\s+type="hidden"\s+name="filename"\s+value=\"([_.0-9a-z]+)\"/ig;
501     @filenames or die;
502
503     my @forcerls= $resptxt =~
504  m/input\s+type="hidden"\s+name="forcereload"\s+value=\"([1-9]\d+)\"/ig;
505     @forcerls or die;
506
507     my $filename= $filenames[0];
508     my $forcerl= $forcerls[0];
509
510     $ocean= ucfirst lc $ocean;
511     my @oceanids= $resptxt =~
512  m/\<option value\=\"(\d+)\"\>$ocean\<\/option\>/;
513     @oceanids==1 or die "@oceanids ?";
514
515     my $islandid;
516     while ($resptxt =~
517  m/^islands\[\d+\]\[\d+\]\=new\s+option\(\"(.*)\"\,(\d+)\)\s*$/mig
518            ) {
519         next unless $1 eq $island;
520         $islandid= $2;
521     }
522     defined $islandid or die;
523
524     die "@filenames ?" if grep { $_ ne $filename } @filenames;
525     die "@forcerls ?" if grep { $_ ne $forcerl } @forcerls;
526
527     my $setisland= {
528     };
529
530     print STDERR "Setting ocean and island...\n";
531
532     my $siurl= ($url . "?action=setisland".
533                 "&filename=$filename".
534                 "&forcereload=$forcerl".
535                 "&ocean=$oceanids[0]".
536                 "&island=$islandid");
537     $resp= $ua->get($siurl);
538
539     die $resp->status_line unless $resp->is_success;
540
541     $resptxt= $resp->content();
542     save_upload_html('2', $resptxt);
543
544     die unless $resptxt =~ m/your uploaded data has been processed/i;
545     die unless $resptxt =~ m/your data has been integrated into the database/i;
546
547     $resptxt =~ s/\<a href=\"about:\w+\"\>[^<>]+\<\/a\>//g;
548     save_upload_html('3', $resptxt);
549
550     print "\n" or die $!;
551     system('w3m -T text/html -dump < _upload-3.html');
552     
553     print "\n" or die $!;
554 }
555
556
557 $mode =~ s/\-//;
558 &{"main__$mode"};
559 close(STDOUT) or die $!;