chiark / gitweb /
New CommodsDatabase module for broken out DBI stuff
[ypp-sc-tools.web-live.git] / pctb / 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                 unshift @$verbs, {
139                     Stall => $verb->{Stall},
140                     Price => $verb->{Price},
141                     Qty => $verb->{Qty} - $qty
142                 };
143             }
144             arb_subtract_qty(@buys);
145             arb_subtract_qty(@sells);
146         }
147         next unless $profit;
148         $info.=
149             sprintf("%-13.13s| %19s %4s| %19s %4s|%3d      %4d\n",
150                     $commod, '','', '','', $cqty, $profit);
151         push @arbs, { Profit => $profit, Info => $info };
152     }
153     my $allprofit;
154
155     if (!@arbs) {
156         print "No arbitrage opportunities.\n" or die $!;
157         return;
158     }
159     my $bigdiv= <<END;
160 =============+=========================+=========================+=============
161 END
162
163     print <<END or die $!;
164
165 commodity    | seller             price| buyer              price| qty  ea prof
166 END
167
168     my $div= $bigdiv;
169     foreach my $arb (sort {
170         $b->{Profit} <=> $a->{Profit};
171     } @arbs) {
172         print $div,$arb->{Info} or die $1;
173         $div= <<END;
174 -------------+-------------------------+-------------------------+-------------
175 END
176         $allprofit += $arb->{Profit};
177     }
178     print $bigdiv or die $!;
179     printf("%-13.13s  %19s %4s  %19s %4s %-5s %7d\n",
180            '', '','', '','', 'TOTAL', $allprofit)
181         or die $!;
182 }
183
184 sub main__bestprices () {
185     foreach $commod (sort keys %commod) {
186         $current= $commod{$commod};
187         my $buys=  bs_p($commod,Buy, -1);
188         my $sells= bs_p($commod,Sell,+1);
189         printf("%-15.15s", $commod) or die $!;
190         bs_p_bestprice($buys);
191         bs_p_bestprice($sells);
192         print("\n") or die $!;
193     }
194 }
195
196 sub bs_p_tsv ($$) {
197     my ($f, $bs) = @_;
198     if (exists $current->{$bs}{$stall}) {
199         my $si= $current->{$bs}{$stall};
200         printf($f "\t%d\t%s", $si->{Price}, $si->{Qty}) or die $!;
201     } else {
202         printf($f "\t\t") or die $!;
203     }
204 }
205
206 sub write_tsv ($) {
207     my ($f) = @_;
208     foreach $commod (sort keys %commod) {
209         $current= $commod{$commod};
210         my %stalls;
211         map { $stalls{$_}=1; } keys %{ $current->{Buy}  };
212         map { $stalls{$_}=1; } keys %{ $current->{Sell} };
213         foreach $stall (sort keys %stalls) {
214             printf($f "%s\t%s", $commod, $stall) or die $!;
215             bs_p_tsv($f, Buy);
216             bs_p_tsv($f, Sell);
217             print($f "\n") or die $!;
218         }
219     }
220     $f->error and die $!;
221     $f->flush or die $!;
222 }
223
224 sub main__tsv () {
225     write_tsv(\*STDOUT);
226 }
227
228
229 our ($pctb) = $ENV{'YPPSC_PCTB_PCTB'};
230
231 our ($ua)= LWP::UserAgent->new;
232
233 sub refresh_commodmap() {
234     die unless $pctb;
235     $pctb =~ s,/*$,,;
236     my $resp= $ua->get("$pctb/commodmap.php?version=2");
237     die $resp->status_line unless $resp->is_success;
238
239     my $cdata='';
240     my $incommodmap=0;
241     my $intag='';
242     my %got;
243     my $o= new IO::File "_commodmap.tsv.tmp",'w' or die $!;
244     undef %pctb_commodmap;
245
246     my $xp= new XML::Parser
247         (Handlers =>
248          {
249              Start => sub {
250                  $_=$_[1];
251 #print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
252                  if (m/^commodmap$/i) {
253                      $incommodmap++;
254                      undef %got;
255                  } elsif (m/^(?:name|index)$/i) {
256                      $cdata='';
257                      $intag=lc($_) if $incommodmap;
258 #print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
259 #                } else {
260 #print STDERR "START UNRECOGNISED\n";
261                  }
262              },
263              End => sub {
264                  $_=$_[1];
265 #print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
266                  if (m/^commodmap$/i) {
267                      $incommodmap--;
268                      die unless exists $got{'name'};
269                      die unless exists $got{'index'};
270                      die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
271                      my $index= $1;
272                      $_= $got{'name'};
273                      s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
274                      die "$_ ?" if exists $pctb_commodmap{$_};
275                      $pctb_commodmap{$_}= $index;
276                      print $o "$_\t$index\n" or die $!;
277                  } elsif (lc $_ eq $intag) {
278                      $got{$intag}= $cdata;
279                  }
280              },
281              Char => sub {
282 #print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
283                  $cdata .= $_[1];
284              }
285          }) or die;
286     my $content= $resp->content;
287
288 #    print STDERR "[[[$content]]]\n";
289     $xp->parse($content);
290     close $o or die $!;
291     rename "_commodmap.tsv.tmp","_commodmap.tsv" or die $!;
292 }
293
294 our %newcommods;
295
296 sub read_newcommods ($) {
297     my ($file) = @_;
298     if (!open NC, "< $file") {
299         $!==&ENOENT or die $!;
300         return;
301     }
302     while (<NC>) {
303         chomp; s/^\s*//; s/\s+$//;
304         next if m/^\#/;
305         next unless m/\S/;
306         $newcommods{$_}= 1;
307     }
308     NC->error and die $!;
309     close NC or die $!;
310 }
311
312 sub refresh_newcommods() {
313     my $rsync= $ENV{'YPPSC_PCTB_RSYNC'};
314     $rsync= 'rsync' if !defined $rsync;
315
316     my $local= "_master-newcommods.txt";
317     my $src= $ENV{'YPPSC_PCTB_DICT_UPDATE'};
318     if ($src) {
319         my $remote= "$src/master-newcommods.txt";
320         $!=0; system 'rsync','-Lt','--',$remote,$local;
321         die "$? $!" if $! or $?;
322     }
323     read_newcommods($local);
324     read_newcommods('_local-newcommods.txt');
325 }
326
327 our (%stallmap, @stallmap);
328
329 sub bs_gen_md ($$) {
330     my ($bs,$sortmul) = @_;
331     my $count= 0;
332     my $o= '';
333     
334     foreach $commod (
335                      sort { $pctb_commodmap{$a} <=> $pctb_commodmap{$b} }
336                      grep { exists $pctb_commodmap{$_} }
337                      keys %commod
338                      ) {
339 #print STDERR "COMMOD $commod\n";
340         $current= $commod{$commod};
341         my $l= bs_p($commod,$bs,$sortmul);
342         next unless @$l;
343 #print STDERR "COMMOD $commod  has ".scalar(@$l)."\n";
344         $o .= writeint($pctb_commodmap{$commod});
345         $o .= writeint(scalar @$l);
346         foreach my $cs (@$l) {
347             $stall= $cs->{Stall};
348             my $stallix= $stallmap{$stall};
349             if (!defined $stallix) {
350                 push @stallmap, $stall;
351                 $stallmap{$stall}= $stallix= @stallmap;
352 #print STDERR "STALL DEF $stallix $stall\n";
353             }
354             my $qty= $cs->{Qty};
355             $qty =~ s/^\>\s*//;
356             $o .= writeint($stallix, $cs->{Price}, $qty+0);
357             $count++;
358         }
359     }
360 #print STDERR "COMMOD $commod COUNT WAS $count\n";
361     return
362         writeint($count).$o;
363 }
364
365 sub writeint { return pack 'v*', @_; }
366
367 our (%stalltypetoabbrevmap)= qw(
368                                 Apothecary    A
369                                 Distilling    D
370                                 Furnishing    F
371                                 Ironworking   I
372                                 Shipbuilding  S
373                                 Tailoring     T
374                                 Weaving       W
375                                 );
376
377 sub genmarketdata () {
378     our $version= '005b';
379
380     parse_pctb_commodmap();
381     my @missing= grep { !exists $pctb_commodmap{$_} } keys %commod;
382     if (@missing) {
383         refresh_commodmap();
384         refresh_newcommods();
385         my $missing=0;
386         foreach $commod (sort keys %commod) {
387             next if exists $pctb_commodmap{$commod};
388             if (exists $newcommods{$commod}) {
389                 printf STDERR "Ignoring new commodity \`%s'!\n", $commod;
390             } else {
391                 printf STDERR "Unknown commodity \`%s'!\n", $commod;
392                 $missing++;
393             }
394         }
395         die "$missing unknown commoditi(es).".
396             "  See README (search for \`newcommods').\n"
397             if $missing;
398     }    
399
400     my $ob='';
401     $ob .= bs_gen_md(Buy, -1);
402     $ob .= bs_gen_md(Sell,+1);
403
404     my $ot= sprintf("$version\n".
405                     "%d\n",
406                     scalar(@stallmap));
407     foreach $stall (@stallmap) {
408         my $st= $stall;
409         if ($st =~ m/^(\S+)\'s (\S+) Stall$/) {
410             my $stkind= $stalltypetoabbrevmap{$2};
411             if (defined $stkind) {
412                 $st= "$1^$stkind";
413             } else {
414                 warn "unknown stall type $2 in $st\n";
415             }
416         }
417         $ot .= "$st\n";
418     }
419     return $ot.$ob;
420 }
421
422 sub main__genmarketdata () {
423     my $o= genmarketdata();
424     print $o or die $!;
425 }
426
427 sub save_upload_html ($$) {
428     my ($which, $resptxt) = @_;
429     open R, ">./_upload-$which.html" or die $!;
430     print R $resptxt or die $!;
431     close R or die $!;
432 }
433
434 sub gzip ($) {
435     my ($raw) = @_;
436     my $tf= pipethrough_prep();
437     print $tf $raw or die $!;
438     return pipethrough_run($tf,undef,'gzip','gzip');
439 }
440
441 sub main__uploadyaarg () {
442     my %o;
443     $o{'ocean'}= $ENV{'YPPSC_OCEAN'} or die;
444     $o{'island'}= $ENV{'YPPSC_ISLAND'} or die;
445     $o{'timestamp'}= 10;
446     get_our_version(\%o, 'client');
447
448     my $tf= pipethrough_prep();
449     write_tsv($tf);
450     my $oz= pipethrough_run_gzip($tf);
451     $o{'data'}=  [ undef, 'deduped.tsv.gz',
452                     Content_Type => 'application/octet-stream',
453                     Content => $oz ];
454
455     my $dest= $ENV{'YPPSC_YAARG_SUBMIT'};
456
457     my $respcontent= cgipostform($ua, "$dest/commod-update-receiver", \%o);
458     $respcontent =~ m/^OK\b/ or die "$respcontent ?";
459 }
460
461 sub main__uploadpctb () {
462     my $ocean= $ENV{'YPPSC_OCEAN'};  die unless $ocean;
463     my $island= $ENV{'YPPSC_ISLAND'};  die unless $island;
464     die unless $pctb;
465     my $o= genmarketdata();
466     $pctb =~ s,/*$,,;
467     my $url= "$pctb/upload.php";
468     my $content= {
469         'marketdata' => [ undef, "marketdata.gz",
470                           Content_Type => 'application/gzip',
471                           Content => gzip($o),
472                           ]
473                       };
474
475     print STDERR "Uploading data to $pctb...\n";
476
477     my $resp= $ua->post("$url", Content => $content,
478                         Content_Type => 'form-data');
479     die $resp->status_line unless $resp->is_success;
480
481     my $resptxt= $resp->content();
482     save_upload_html('1', $resptxt);
483
484     open R, ">./_upload-1.html" or die $!;
485     print R $resptxt or die $!;
486     close R or die $!;
487
488     my @filenames= $resptxt =~
489  m/input\s+type="hidden"\s+name="filename"\s+value=\"([_.0-9a-z]+)\"/ig;
490     @filenames or die;
491
492     my @forcerls= $resptxt =~
493  m/input\s+type="hidden"\s+name="forcereload"\s+value=\"([1-9]\d+)\"/ig;
494     @forcerls or die;
495
496     my $filename= $filenames[0];
497     my $forcerl= $forcerls[0];
498
499     $ocean= ucfirst lc $ocean;
500     my @oceanids= $resptxt =~
501  m/\<option value\=\"(\d+)\"\>$ocean\<\/option\>/;
502     @oceanids==1 or die "@oceanids ?";
503
504     my $islandid;
505     while ($resptxt =~
506  m/^islands\[\d+\]\[\d+\]\=new\s+option\(\"(.*)\"\,(\d+)\)\s*$/mig
507            ) {
508         next unless $1 eq $island;
509         $islandid= $2;
510     }
511     defined $islandid or die;
512
513     die "@filenames ?" if grep { $_ ne $filename } @filenames;
514     die "@forcerls ?" if grep { $_ ne $forcerl } @forcerls;
515
516     my $setisland= {
517     };
518
519     print STDERR "Setting ocean and island...\n";
520
521     my $siurl= ($url . "?action=setisland".
522                 "&filename=$filename".
523                 "&forcereload=$forcerl".
524                 "&ocean=$oceanids[0]".
525                 "&island=$islandid");
526     $resp= $ua->get($siurl);
527
528     die $resp->status_line unless $resp->is_success;
529
530     $resptxt= $resp->content();
531     save_upload_html('2', $resptxt);
532
533     die unless $resptxt =~ m/your uploaded data has been processed/i;
534     die unless $resptxt =~ m/your data has been integrated into the database/i;
535
536     $resptxt =~ s/\<a href=\"about:\w+\"\>[^<>]+\<\/a\>//g;
537     save_upload_html('3', $resptxt);
538
539     print "\n" or die $!;
540     system('w3m -T text/html -dump < _upload-3.html');
541     
542     print "\n" or die $!;
543 }
544
545
546 $mode =~ s/\-//;
547 &{"main__$mode"};
548 close(STDOUT) or die $!;