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