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