chiark / gitweb /
Export for people's convenience
[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 LWP::UserAgent;
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);
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 "$_ ?" 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     ($commod,$stall) = @v;
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                        $buys[0]{Stall},$buys[0]{Price},
133                        $sells[0]{Stall},$sells[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
231 our ($pctb) = $ENV{'YPPSC_YARRG_PCTB'};
232
233 our ($ua)= LWP::UserAgent->new;
234
235 sub refresh_commodmap() {
236     die unless $pctb;
237     $pctb =~ s,/*$,,;
238     my $resp= $ua->get("$pctb/commodmap.php?version=2");
239     die $resp->status_line unless $resp->is_success;
240
241     my $cdata='';
242     my $incommodmap=0;
243     my $intag='';
244     my %got;
245     my $o= new IO::File "_commodmap.tsv.tmp",'w' or die $!;
246     undef %pctb_commodmap;
247
248     my $xp= new XML::Parser
249         (Handlers =>
250          {
251              Start => sub {
252                  $_=$_[1];
253 #print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
254                  if (m/^commodmap$/i) {
255                      $incommodmap++;
256                      undef %got;
257                  } elsif (m/^(?:name|index)$/i) {
258                      $cdata='';
259                      $intag=lc($_) if $incommodmap;
260 #print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
261 #                } else {
262 #print STDERR "START UNRECOGNISED\n";
263                  }
264              },
265              End => sub {
266                  $_=$_[1];
267 #print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
268                  if (m/^commodmap$/i) {
269                      $incommodmap--;
270                      die unless exists $got{'name'};
271                      die unless exists $got{'index'};
272                      die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
273                      my $index= $1;
274                      $_= $got{'name'};
275                      s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
276                      die "$_ ?" if exists $pctb_commodmap{$_};
277                      $pctb_commodmap{$_}= $index;
278                      print $o "$_\t$index\n" or die $!;
279                  } elsif (lc $_ eq $intag) {
280                      $got{$intag}= $cdata;
281                  }
282              },
283              Char => sub {
284 #print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
285                  $cdata .= $_[1];
286              }
287          }) or die;
288     my $content= $resp->content;
289
290 #    print STDERR "[[[$content]]]\n";
291     $xp->parse($content);
292     close $o or die $!;
293     rename "_commodmap.tsv.tmp","_commodmap.tsv" or die $!;
294 }
295
296 our %newcommods;
297
298 sub read_newcommods ($) {
299     my ($file) = @_;
300     if (!open NC, "< $file") {
301         $!==&ENOENT or die $!;
302         return;
303     }
304     while (<NC>) {
305         chomp; s/^\s*//; s/\s+$//;
306         next if m/^\#/;
307         next unless m/\S/;
308         $newcommods{$_}= 1;
309     }
310     NC->error and die $!;
311     close NC or die $!;
312 }
313
314 sub refresh_newcommods() {
315     my $master= fetch_with_rsync('newcommods');
316     read_newcommods($master);
317     read_newcommods('_local-newcommods.txt');
318 }
319
320 our (%stallmap, @stallmap);
321
322 sub bs_gen_md ($$) {
323     my ($bs,$sortmul) = @_;
324     my $count= 0;
325     my $o= '';
326     
327     foreach $commod (
328                      sort { $pctb_commodmap{$a} <=> $pctb_commodmap{$b} }
329                      grep { exists $pctb_commodmap{$_} }
330                      keys %commod
331                      ) {
332 #print STDERR "COMMOD $commod\n";
333         $current= $commod{$commod};
334         my $l= bs_p($commod,$bs,$sortmul);
335         next unless @$l;
336 #print STDERR "COMMOD $commod  has ".scalar(@$l)."\n";
337         $o .= writeint($pctb_commodmap{$commod});
338         $o .= writeint(scalar @$l);
339         foreach my $cs (@$l) {
340             $stall= $cs->{Stall};
341             my $stallix= $stallmap{$stall};
342             if (!defined $stallix) {
343                 push @stallmap, $stall;
344                 $stallmap{$stall}= $stallix= @stallmap;
345 #print STDERR "STALL DEF $stallix $stall\n";
346             }
347             my $qty= $cs->{Qty};
348             $qty =~ s/^\>\s*//;
349             $o .= writeint($stallix, $cs->{Price}, $qty+0);
350             $count++;
351         }
352     }
353 #print STDERR "COMMOD $commod COUNT WAS $count\n";
354     return
355         writeint($count).$o;
356 }
357
358 sub writeint { return pack 'v*', @_; }
359
360 our (%stalltypetoabbrevmap)= qw(
361                                 Apothecary    A
362                                 Distilling    D
363                                 Furnishing    F
364                                 Ironworking   I
365                                 Shipbuilding  S
366                                 Tailoring     T
367                                 Weaving       W
368                                 );
369
370 sub genmarketdata () {
371     our $version= '005b';
372
373     parse_pctb_commodmap();
374     my @missing= grep { !exists $pctb_commodmap{$_} } keys %commod;
375     if (@missing) {
376         refresh_commodmap();
377         refresh_newcommods();
378         my $missing=0;
379         foreach $commod (sort keys %commod) {
380             next if exists $pctb_commodmap{$commod};
381             if (exists $newcommods{$commod}) {
382                 printf STDERR "Ignoring new commodity \`%s'!\n", $commod;
383             } else {
384                 printf STDERR "Unknown commodity \`%s'!\n", $commod;
385                 $missing++;
386             }
387         }
388         die "$missing unknown commoditi(es).".
389             "  See README (search for \`newcommods').\n"
390             if $missing;
391     }    
392
393     my $ob='';
394     $ob .= bs_gen_md(Buy, -1);
395     $ob .= bs_gen_md(Sell,+1);
396
397     my $ot= sprintf("$version\n".
398                     "%d\n",
399                     scalar(@stallmap));
400     foreach $stall (@stallmap) {
401         my $st= $stall;
402         if ($st =~ m/^(\S+)\'s (\S+) Stall$/) {
403             my $stkind= $stalltypetoabbrevmap{$2};
404             if (defined $stkind) {
405                 $st= "$1^$stkind";
406             } else {
407                 warn "unknown stall type $2 in $st\n";
408             }
409         }
410         $ot .= "$st\n";
411     }
412     return $ot.$ob;
413 }
414
415 sub main__genmarketdata () {
416     my $o= genmarketdata();
417     print $o or die $!;
418 }
419
420 sub save_upload_html ($$) {
421     my ($which, $resptxt) = @_;
422     open R, ">./_upload-$which.html" or die $!;
423     print R $resptxt or die $!;
424     close R or die $!;
425 }
426
427 sub gzip ($) {
428     my ($raw) = @_;
429     my $tf= pipethrough_prep();
430     print $tf $raw or die $!;
431     return pipethrough_run($tf,undef,'gzip','gzip');
432 }
433
434 sub main__uploadyarrg () {
435     my %o;
436
437     parse_info_clientside();
438
439     $o{'ocean'}= $ENV{'YPPSC_OCEAN'} or die;
440     $o{'island'}= $ENV{'YPPSC_ISLAND'} or die;
441     $o{'timestamp'}= $ENV{'YPPSC_DATA_TIMESTAMP'} or die;
442
443     my $tf= pipethrough_prep();
444     write_tsv($tf);
445     my $oz= pipethrough_run_gzip($tf);
446     $o{'data'}=  [ undef, 'deduped.tsv.gz',
447                     Content_Type => 'application/octet-stream',
448                     Content => $oz ];
449
450     my $respcontent= yarrgpostform($ua, \%o);
451     $respcontent =~ m/^OK\b/ or die "$respcontent ?";
452     $respcontent =~ s/^/ /mg;
453     print $respcontent,"\n";
454 }
455
456 sub main__uploadpctb () {
457     my $ocean= $ENV{'YPPSC_OCEAN'};  die unless $ocean;
458     my $island= $ENV{'YPPSC_ISLAND'};  die unless $island;
459     die unless $pctb;
460     my $o= genmarketdata();
461     $pctb =~ s,/*$,,;
462     my $url= "$pctb/upload.php";
463     my $content= {
464         'marketdata' => [ undef, "marketdata.gz",
465                           Content_Type => 'application/gzip',
466                           Content => gzip($o),
467                           ]
468                       };
469
470     print STDERR "Uploading data to $pctb...\n";
471
472     my $resp= $ua->post("$url", Content => $content,
473                         Content_Type => 'form-data');
474     die $resp->status_line unless $resp->is_success;
475
476     my $resptxt= $resp->content();
477     save_upload_html('1', $resptxt);
478
479     open R, ">./_upload-1.html" or die $!;
480     print R $resptxt or die $!;
481     close R or die $!;
482
483     my @filenames= $resptxt =~
484  m/input\s+type="hidden"\s+name="filename"\s+value=\"([_.0-9a-z]+)\"/ig;
485     @filenames or die;
486
487     my @forcerls= $resptxt =~
488  m/input\s+type="hidden"\s+name="forcereload"\s+value=\"([1-9]\d+)\"/ig;
489     @forcerls or die;
490
491     my $filename= $filenames[0];
492     my $forcerl= $forcerls[0];
493
494     $ocean= ucfirst lc $ocean;
495     my @oceanids= $resptxt =~
496  m/\<option value\=\"(\d+)\"\>$ocean\<\/option\>/;
497     @oceanids==1 or die "@oceanids ?";
498
499     my $islandid;
500     while ($resptxt =~
501  m/^islands\[\d+\]\[\d+\]\=new\s+option\(\"(.*)\"\,(\d+)\)\s*$/mig
502            ) {
503         next unless $1 eq $island;
504         $islandid= $2;
505     }
506     defined $islandid or die;
507
508     die "@filenames ?" if grep { $_ ne $filename } @filenames;
509     die "@forcerls ?" if grep { $_ ne $forcerl } @forcerls;
510
511     my $setisland= {
512     };
513
514     print STDERR "Setting ocean and island...\n";
515
516     my $siurl= ($url . "?action=setisland".
517                 "&filename=$filename".
518                 "&forcereload=$forcerl".
519                 "&ocean=$oceanids[0]".
520                 "&island=$islandid");
521     $resp= $ua->get($siurl);
522
523     die $resp->status_line unless $resp->is_success;
524
525     $resptxt= $resp->content();
526     save_upload_html('2', $resptxt);
527
528     die unless $resptxt =~ m/your uploaded data has been processed/i;
529     die unless $resptxt =~ m/your data has been integrated into the database/i;
530
531     $resptxt =~ s/\<a href=\"about:\w+\"\>[^<>]+\<\/a\>//g;
532     save_upload_html('3', $resptxt);
533
534     print "\n" or die $!;
535     system('w3m -T text/html -dump < _upload-3.html');
536     
537     print "\n" or die $!;
538 }
539
540
541 $mode =~ s/\-//;
542 &{"main__$mode"};
543 close(STDOUT) or die $!;