3 # helper program for processing commodity output
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
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.
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.
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/>.
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.
28 use strict (qw(vars));
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}
42 our ($commod,$stall,%commod,@commods_inorder);
44 @ARGV==1 or die "You probably don't want to run this program directly.\n";
45 our ($mode) = shift @ARGV;
47 # ./yppsc-commod-processor tsv <t |less -x40,80,90,100,110
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}= {
66 #print STDERR "[".join("|",@v)."]\n";
67 foreach (@v[2..$#v]) {
71 ($commod,$stall) = @v;
72 push @commods_inorder, $commod unless exists $commod{$commod};
75 $commod{$commod}{Hold}= $v[6]+0 if @v>6;
81 my ($commod,$bs,$sortmul) = @_;
82 my $ary= $current->{$bs};
85 foreach my $stall (sort {
86 $sortmul * ($ary->{$a}{Price} <=> $ary->{$b}{Price});
88 push @$r, $ary->{$stall};
93 sub bs_p_bestprice ($) {
96 printf("| %-25.25s %4d", $l->[0]{Stall}, $l->[0]{Price}) or die $!;
98 printf("| %25s %4s","","") or die $!;
102 sub main__arbitrage () {
104 foreach $commod (sort keys %commod) {
105 $current= $commod{$commod};
106 my @buys= @{ bs_p($commod,Buy, -1) };
107 my @sells= @{ bs_p($commod,Sell,+1) };
113 #print Dumper($commod,\@buys,\@sells);
116 my $pricediff= $buys[0]{Price} - $sells[0]{Price};
117 last unless $pricediff > 0;
119 sub arb_check_qty (\@) {
121 my $vqty= $verbs->[0]{Qty};
122 return if $vqty =~ m/^\>/;
123 $qty= $vqty if $qty > $vqty;
125 my $verb= shift @$verbs;
127 arb_check_qty(@buys);
128 arb_check_qty(@sells);
130 my $tprofit= $qty*$pricediff;
135 sprintf("%-13.13s| %-19.19s %4d| %-19.19s %4d|%3d x%3d =%3d\n",
137 $sells[0]{Stall},$sells[0]{Price},
138 $buys[0]{Stall},$buys[0]{Price},
139 $qty, $pricediff, $tprofit);
140 sub arb_subtract_qty (\@) {
142 my $verb= shift @$verbs;
143 my $vqty= $verb->{Qty};
146 Stall => $verb->{Stall},
147 Price => $verb->{Price},
151 arb_subtract_qty(@buys);
152 arb_subtract_qty(@sells);
156 sprintf("%-13.13s| %19s %4s| %19s %4s|%3d %4d\n",
157 $commod, '','', '','', $cqty, $profit);
158 push @arbs, { Profit => $profit, Info => $info };
163 print "No arbitrage opportunities.\n" or die $!;
167 =============+=========================+=========================+=============
170 print <<END or die $!;
172 commodity | seller price| buyer price| qty ea prof
176 foreach my $arb (sort {
177 $b->{Profit} <=> $a->{Profit};
179 print $div,$arb->{Info} or die $1;
181 -------------+-------------------------+-------------------------+-------------
183 $allprofit += $arb->{Profit};
185 print $bigdiv or die $!;
186 printf("%-13.13s %19s %4s %19s %4s %-5s %7d\n",
187 '', '','', '','', 'TOTAL', $allprofit)
191 sub main__bestprices () {
192 foreach $commod (sort keys %commod) {
193 $current= $commod{$commod};
194 my $buys= bs_p($commod,Buy, -1);
195 my $sells= bs_p($commod,Sell,+1);
196 printf("%-15.15s", $commod) or die $!;
197 bs_p_bestprice($buys);
198 bs_p_bestprice($sells);
199 print("\n") or die $!;
205 if (exists $current->{$bs}{$stall}) {
206 my $si= $current->{$bs}{$stall};
207 printf($f "\t%d\t%s", $si->{Price}, $si->{Qty}) or die $!;
209 printf($f "\t\t") or die $!;
214 my ($f,$showhold) = @_;
215 foreach $commod (sort keys %commod) {
216 $current= $commod{$commod};
218 map { $stalls{$_}=1; } keys %{ $current->{Buy} };
219 map { $stalls{$_}=1; } keys %{ $current->{Sell} };
220 foreach $stall (sort keys %stalls) {
221 printf($f "%s\t%s", $commod, $stall) or die $!;
224 if ($showhold && $commod{$commod}{Hold}) {
225 printf($f "\t%s", $commod{$commod}{Hold}) or die $!;
227 print($f "\n") or die $!;
230 $f->error and die $!;
235 write_tsv(\*STDOUT,1);
238 sub undef_printable { my ($ov)= @_; defined $ov ? $ov : '?'; };
240 sub commodsinorder_print1 ($$) {
241 my ($keyword,$commod) = @_;
242 printf("%s\t%-40s %10s %s",
245 undef_printable($commods{$commod}{Ordval}),
246 undef_printable($commods{$commod}{Class}))
250 sub main__commodsinorder () {
251 parse_info_serverside();
253 foreach my $commod (@commods_inorder) {
254 my $ov= $commods{$commod}{Ordval};
255 commodsinorder_print1('found',$commod);
257 if (defined $last_ov && $ov <= $last_ov) {
258 print " out-of-order" or die $!;
262 print "\n" or die $!;
264 foreach my $commod (sort {
265 undef_printable($commods{$a}{Ordval}) cmp
266 undef_printable($commods{$b}{Ordval})
268 next if exists $commod{$commod};
269 commodsinorder_print1('none',$commod);
270 print "\n" or die $!;
274 our ($pctb) = $ENV{'YPPSC_YARRG_PCTB'};
276 our ($ua)= http_useragent("commod-results-processor $mode");
278 sub refresh_commodmap() {
281 my $resp= $ua->get("$pctb/commodmap.php?version=2");
282 die $resp->status_line unless $resp->is_success;
288 my $o= new IO::File "_commodmap.tsv.tmp",'w' or die $!;
289 undef %pctb_commodmap;
291 my $xp= new XML::Parser
296 #print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
297 if (m/^commodmap$/i) {
300 } elsif (m/^(?:name|index)$/i) {
302 $intag=lc($_) if $incommodmap;
303 #print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
305 #print STDERR "START UNRECOGNISED\n";
310 #print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
311 if (m/^commodmap$/i) {
313 die unless exists $got{'name'};
314 die unless exists $got{'index'};
315 die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
318 s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
319 die "$_ ?" if exists $pctb_commodmap{$_};
320 $pctb_commodmap{$_}= $index;
321 print $o "$_\t$index\n" or die $!;
322 } elsif (lc $_ eq $intag) {
323 $got{$intag}= $cdata;
327 #print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
331 my $content= $resp->content;
333 # print STDERR "[[[$content]]]\n";
334 my $commodmapxmltmp= '_commodmap.xml';
336 $xp->parse($content); 1;
338 open R, ">./$commodmapxmltmp" or die $!;
339 print R $content or die $!;
341 die "$@ parsing commodmap";
343 unlink $commodmapxmltmp or $!==&ENOENT or die $!;
345 rename "_commodmap.tsv.tmp","_commodmap.tsv" or die $!;
350 sub read_newcommods ($) {
352 if (!open NC, "< $file") {
353 $!==&ENOENT or die $!;
357 chomp; s/^\s*//; s/\s+$//;
362 NC->error and die $!;
366 sub refresh_newcommods() {
367 my $master= fetch_with_rsync('newcommods');
368 read_newcommods($master);
369 read_newcommods('_local-newcommods.txt');
372 our (%stallmap, @stallmap);
375 my ($bs,$sortmul) = @_;
380 sort { $pctb_commodmap{$a} <=> $pctb_commodmap{$b} }
381 grep { exists $pctb_commodmap{$_} }
384 #print STDERR "COMMOD $commod\n";
385 $current= $commod{$commod};
386 my $l= bs_p($commod,$bs,$sortmul);
388 #print STDERR "COMMOD $commod has ".scalar(@$l)."\n";
389 $o .= writeint($pctb_commodmap{$commod});
390 $o .= writeint(scalar @$l);
391 foreach my $cs (@$l) {
392 $stall= $cs->{Stall};
393 my $stallix= $stallmap{$stall};
394 if (!defined $stallix) {
395 push @stallmap, $stall;
396 $stallmap{$stall}= $stallix= @stallmap;
397 #print STDERR "STALL DEF $stallix $stall\n";
401 $o .= writeint($stallix, $cs->{Price}, $qty+0);
405 #print STDERR "COMMOD $commod COUNT WAS $count\n";
410 sub writeint { return pack 'v*', @_; }
412 our (%stalltypetoabbrevmap)= qw(
422 sub genmarketdata () {
423 our $version= '005b';
425 parse_pctb_commodmap();
426 my @missing= grep { !exists $pctb_commodmap{$_} } keys %commod;
429 refresh_newcommods();
431 foreach $commod (sort keys %commod) {
432 next if exists $pctb_commodmap{$commod};
433 if (exists $newcommods{$commod}) {
434 printf STDERR "Ignoring new commodity \`%s'!\n", $commod;
436 printf STDERR "Unknown commodity \`%s'!\n", $commod;
440 die "$missing unknown commoditi(es).".
441 " See README (search for \`newcommods').\n"
446 $ob .= bs_gen_md(Buy, -1);
447 $ob .= bs_gen_md(Sell,+1);
449 my $ot= sprintf("$version\n".
452 foreach $stall (@stallmap) {
454 if ($st =~ m/^(\S+)\'s (\S+) Stall$/) {
455 my $stkind= $stalltypetoabbrevmap{$2};
456 if (defined $stkind) {
459 warn "unknown stall type $2 in $st\n";
467 sub main__genmarketdata () {
468 my $o= genmarketdata();
472 sub save_upload_html ($$) {
473 my ($which, $resptxt) = @_;
474 open R, ">./_upload-$which.html" or die $!;
475 print R $resptxt or die $!;
481 my $tf= pipethrough_prep();
482 print $tf $raw or die $!;
483 return pipethrough_run($tf,undef,'gzip','gzip');
486 sub main__uploadyarrg () {
489 parse_info_clientside();
491 $o{'ocean'}= $ENV{'YPPSC_OCEAN'} or die;
492 $o{'island'}= $ENV{'YPPSC_ISLAND'} or die;
493 $o{'timestamp'}= $ENV{'YPPSC_DATA_TIMESTAMP'} or die;
495 my $tf= pipethrough_prep();
497 my $oz= pipethrough_run_gzip($tf);
498 $o{'data'}= [ undef, 'deduped.tsv.gz',
499 Content_Type => 'application/octet-stream',
502 my $respcontent= yarrgpostform($ua, \%o);
503 $respcontent =~ m/^OK\b/ or die "$respcontent ?";
504 $respcontent =~ s/^/ /mg;
505 print $respcontent,"\n";
508 sub main__uploadpctb () {
509 my $ocean= $ENV{'YPPSC_OCEAN'}; die unless $ocean;
510 my $island= $ENV{'YPPSC_ISLAND'}; die unless $island;
512 my $o= genmarketdata();
514 my $url= "$pctb/upload.php";
516 'marketdata' => [ undef, "marketdata.gz",
517 Content_Type => 'application/gzip',
522 print STDERR "Uploading data to $pctb...\n";
524 my $resp= $ua->post("$url", Content => $content,
525 Content_Type => 'form-data');
526 die $resp->status_line unless $resp->is_success;
528 my $resptxt= $resp->content();
529 save_upload_html('1', $resptxt);
531 open R, ">./_upload-1.html" or die $!;
532 print R $resptxt or die $!;
535 my @filenames= $resptxt =~
536 m/input\s+type="hidden"\s+name="filename"\s+value=\"([_.0-9a-z]+)\"/ig;
539 my @forcerls= $resptxt =~
540 m/input\s+type="hidden"\s+name="forcereload"\s+value=\"([1-9]\d+)\"/ig;
543 my $filename= $filenames[0];
544 my $forcerl= $forcerls[0];
546 $ocean= ucfirst lc $ocean;
547 my @oceanids= $resptxt =~
548 m/\<option value\=\"(\d+)\"\>$ocean\<\/option\>/;
549 @oceanids==1 or die "@oceanids ?";
553 m/^islands\[\d+\]\[\d+\]\=new\s+option\(\"(.*)\"\,(\d+)\)\s*$/mig
555 next unless $1 eq $island;
558 defined $islandid or die;
560 die "@filenames ?" if grep { $_ ne $filename } @filenames;
561 die "@forcerls ?" if grep { $_ ne $forcerl } @forcerls;
566 print STDERR "Setting ocean and island...\n";
568 my $siurl= ($url . "?action=setisland".
569 "&filename=$filename".
570 "&forcereload=$forcerl".
571 "&ocean=$oceanids[0]".
572 "&island=$islandid");
573 $resp= $ua->get($siurl);
575 die $resp->status_line unless $resp->is_success;
577 $resptxt= $resp->content();
578 save_upload_html('2', $resptxt);
580 die unless $resptxt =~ m/your uploaded data has been processed/i;
581 die unless $resptxt =~ m/your data has been integrated into the database/i;
583 $resptxt =~ s/\<a href=\"about:\w+\"\>[^<>]+\<\/a\>//g;
584 save_upload_html('3', $resptxt);
586 print "\n" or die $!;
587 system('w3m -T text/html -dump < _upload-3.html');
589 print "\n" or die $!;
595 close(STDOUT) or die $!;