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 "$_ ?" unless length($price) && length($qty);
55 $commod{$commod}{$bs}{$stall}= {
65 #print STDERR "[".join("|",@v)."]\n";
66 ($commod,$stall) = @v;
67 push @commods_inorder, $commod unless exists $commod{$commod};
70 $commod{$commod}{Hold}= $v[6]+0 if @v>6;
76 my ($commod,$bs,$sortmul) = @_;
77 my $ary= $current->{$bs};
80 foreach my $stall (sort {
81 $sortmul * ($ary->{$a}{Price} <=> $ary->{$b}{Price});
83 push @$r, $ary->{$stall};
88 sub bs_p_bestprice ($) {
91 printf("| %-25.25s %4d", $l->[0]{Stall}, $l->[0]{Price}) or die $!;
93 printf("| %25s %4s","","") or die $!;
97 sub main__arbitrage () {
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) };
108 #print Dumper($commod,\@buys,\@sells);
111 my $pricediff= $buys[0]{Price} - $sells[0]{Price};
112 last unless $pricediff > 0;
114 sub arb_check_qty (\@) {
116 my $vqty= $verbs->[0]{Qty};
117 return if $vqty =~ m/^\>/;
118 $qty= $vqty if $qty > $vqty;
120 my $verb= shift @$verbs;
122 arb_check_qty(@buys);
123 arb_check_qty(@sells);
125 my $tprofit= $qty*$pricediff;
130 sprintf("%-13.13s| %-19.19s %4d| %-19.19s %4d|%3d x%3d =%3d\n",
132 $sells[0]{Stall},$sells[0]{Price},
133 $buys[0]{Stall},$buys[0]{Price},
134 $qty, $pricediff, $tprofit);
135 sub arb_subtract_qty (\@) {
137 my $verb= shift @$verbs;
138 my $vqty= $verb->{Qty};
141 Stall => $verb->{Stall},
142 Price => $verb->{Price},
146 arb_subtract_qty(@buys);
147 arb_subtract_qty(@sells);
151 sprintf("%-13.13s| %19s %4s| %19s %4s|%3d %4d\n",
152 $commod, '','', '','', $cqty, $profit);
153 push @arbs, { Profit => $profit, Info => $info };
158 print "No arbitrage opportunities.\n" or die $!;
162 =============+=========================+=========================+=============
165 print <<END or die $!;
167 commodity | seller price| buyer price| qty ea prof
171 foreach my $arb (sort {
172 $b->{Profit} <=> $a->{Profit};
174 print $div,$arb->{Info} or die $1;
176 -------------+-------------------------+-------------------------+-------------
178 $allprofit += $arb->{Profit};
180 print $bigdiv or die $!;
181 printf("%-13.13s %19s %4s %19s %4s %-5s %7d\n",
182 '', '','', '','', 'TOTAL', $allprofit)
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 $!;
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 $!;
204 printf($f "\t\t") or die $!;
210 foreach $commod (sort keys %commod) {
211 $current= $commod{$commod};
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 $!;
219 print($f "\n") or die $!;
222 $f->error and die $!;
230 sub undef_printable { my ($ov)= @_; defined $ov ? $ov : '?'; };
232 sub commodsinorder_print1 ($$) {
233 my ($keyword,$commod) = @_;
234 printf("%s\t%-40s %10s %s",
237 undef_printable($commods{$commod}{Ordval}),
238 undef_printable($commods{$commod}{Class}))
242 sub main__commodsinorder () {
243 parse_info_serverside();
245 foreach my $commod (@commods_inorder) {
246 my $ov= $commods{$commod}{Ordval};
247 commodsinorder_print1('found',$commod);
249 if (defined $last_ov && $ov <= $last_ov) {
250 print " out-of-order" or die $!;
254 print "\n" or die $!;
256 foreach my $commod (sort {
257 undef_printable($commods{$a}{Ordval}) cmp
258 undef_printable($commods{$b}{Ordval})
260 next if exists $commod{$commod};
261 commodsinorder_print1('none',$commod);
262 print "\n" or die $!;
266 our ($pctb) = $ENV{'YPPSC_YARRG_PCTB'};
268 our ($ua)= http_useragent("commod-results-processor $mode");
270 sub refresh_commodmap() {
273 my $resp= $ua->get("$pctb/commodmap.php?version=2");
274 die $resp->status_line unless $resp->is_success;
280 my $o= new IO::File "_commodmap.tsv.tmp",'w' or die $!;
281 undef %pctb_commodmap;
283 my $xp= new XML::Parser
288 #print STDERR "START [$_] intag=$intag icm=$incommodmap\n";
289 if (m/^commodmap$/i) {
292 } elsif (m/^(?:name|index)$/i) {
294 $intag=lc($_) if $incommodmap;
295 #print STDERR "START RECOGNISED $intag icm=$incommodmap\n";
297 #print STDERR "START UNRECOGNISED\n";
302 #print STDERR "END [$_] intag=$intag icm=$incommodmap\n";
303 if (m/^commodmap$/i) {
305 die unless exists $got{'name'};
306 die unless exists $got{'index'};
307 die unless $got{'index'} =~ m/^\s*([1-9]\d{0,3})\s*$/;
310 s/^\s+//; s/\s+$//; s/\n/ /g; s/\s+/ /;
311 die "$_ ?" if exists $pctb_commodmap{$_};
312 $pctb_commodmap{$_}= $index;
313 print $o "$_\t$index\n" or die $!;
314 } elsif (lc $_ eq $intag) {
315 $got{$intag}= $cdata;
319 #print STDERR "CHAR [$_[1]] intag=$intag icm=$incommodmap\n";
323 my $content= $resp->content;
325 # print STDERR "[[[$content]]]\n";
326 my $commodmapxmltmp= '_commodmap.xml';
328 $xp->parse($content); 1;
330 open R, ">./$commodmapxmltmp" or die $!;
331 print R $content or die $!;
333 die "$@ parsing commodmap";
335 unlink $commodmapxmltmp or $!==&ENOENT or die $!;
337 rename "_commodmap.tsv.tmp","_commodmap.tsv" or die $!;
342 sub read_newcommods ($) {
344 if (!open NC, "< $file") {
345 $!==&ENOENT or die $!;
349 chomp; s/^\s*//; s/\s+$//;
354 NC->error and die $!;
358 sub refresh_newcommods() {
359 my $master= fetch_with_rsync('newcommods');
360 read_newcommods($master);
361 read_newcommods('_local-newcommods.txt');
364 our (%stallmap, @stallmap);
367 my ($bs,$sortmul) = @_;
372 sort { $pctb_commodmap{$a} <=> $pctb_commodmap{$b} }
373 grep { exists $pctb_commodmap{$_} }
376 #print STDERR "COMMOD $commod\n";
377 $current= $commod{$commod};
378 my $l= bs_p($commod,$bs,$sortmul);
380 #print STDERR "COMMOD $commod has ".scalar(@$l)."\n";
381 $o .= writeint($pctb_commodmap{$commod});
382 $o .= writeint(scalar @$l);
383 foreach my $cs (@$l) {
384 $stall= $cs->{Stall};
385 my $stallix= $stallmap{$stall};
386 if (!defined $stallix) {
387 push @stallmap, $stall;
388 $stallmap{$stall}= $stallix= @stallmap;
389 #print STDERR "STALL DEF $stallix $stall\n";
393 $o .= writeint($stallix, $cs->{Price}, $qty+0);
397 #print STDERR "COMMOD $commod COUNT WAS $count\n";
402 sub writeint { return pack 'v*', @_; }
404 our (%stalltypetoabbrevmap)= qw(
414 sub genmarketdata () {
415 our $version= '005b';
417 parse_pctb_commodmap();
418 my @missing= grep { !exists $pctb_commodmap{$_} } keys %commod;
421 refresh_newcommods();
423 foreach $commod (sort keys %commod) {
424 next if exists $pctb_commodmap{$commod};
425 if (exists $newcommods{$commod}) {
426 printf STDERR "Ignoring new commodity \`%s'!\n", $commod;
428 printf STDERR "Unknown commodity \`%s'!\n", $commod;
432 die "$missing unknown commoditi(es).".
433 " See README (search for \`newcommods').\n"
438 $ob .= bs_gen_md(Buy, -1);
439 $ob .= bs_gen_md(Sell,+1);
441 my $ot= sprintf("$version\n".
444 foreach $stall (@stallmap) {
446 if ($st =~ m/^(\S+)\'s (\S+) Stall$/) {
447 my $stkind= $stalltypetoabbrevmap{$2};
448 if (defined $stkind) {
451 warn "unknown stall type $2 in $st\n";
459 sub main__genmarketdata () {
460 my $o= genmarketdata();
464 sub save_upload_html ($$) {
465 my ($which, $resptxt) = @_;
466 open R, ">./_upload-$which.html" or die $!;
467 print R $resptxt or die $!;
473 my $tf= pipethrough_prep();
474 print $tf $raw or die $!;
475 return pipethrough_run($tf,undef,'gzip','gzip');
478 sub main__uploadyarrg () {
481 parse_info_clientside();
483 $o{'ocean'}= $ENV{'YPPSC_OCEAN'} or die;
484 $o{'island'}= $ENV{'YPPSC_ISLAND'} or die;
485 $o{'timestamp'}= $ENV{'YPPSC_DATA_TIMESTAMP'} or die;
487 my $tf= pipethrough_prep();
489 my $oz= pipethrough_run_gzip($tf);
490 $o{'data'}= [ undef, 'deduped.tsv.gz',
491 Content_Type => 'application/octet-stream',
494 my $respcontent= yarrgpostform($ua, \%o);
495 $respcontent =~ m/^OK\b/ or die "$respcontent ?";
496 $respcontent =~ s/^/ /mg;
497 print $respcontent,"\n";
500 sub main__uploadpctb () {
501 my $ocean= $ENV{'YPPSC_OCEAN'}; die unless $ocean;
502 my $island= $ENV{'YPPSC_ISLAND'}; die unless $island;
504 my $o= genmarketdata();
506 my $url= "$pctb/upload.php";
508 'marketdata' => [ undef, "marketdata.gz",
509 Content_Type => 'application/gzip',
514 print STDERR "Uploading data to $pctb...\n";
516 my $resp= $ua->post("$url", Content => $content,
517 Content_Type => 'form-data');
518 die $resp->status_line unless $resp->is_success;
520 my $resptxt= $resp->content();
521 save_upload_html('1', $resptxt);
523 open R, ">./_upload-1.html" or die $!;
524 print R $resptxt or die $!;
527 my @filenames= $resptxt =~
528 m/input\s+type="hidden"\s+name="filename"\s+value=\"([_.0-9a-z]+)\"/ig;
531 my @forcerls= $resptxt =~
532 m/input\s+type="hidden"\s+name="forcereload"\s+value=\"([1-9]\d+)\"/ig;
535 my $filename= $filenames[0];
536 my $forcerl= $forcerls[0];
538 $ocean= ucfirst lc $ocean;
539 my @oceanids= $resptxt =~
540 m/\<option value\=\"(\d+)\"\>$ocean\<\/option\>/;
541 @oceanids==1 or die "@oceanids ?";
545 m/^islands\[\d+\]\[\d+\]\=new\s+option\(\"(.*)\"\,(\d+)\)\s*$/mig
547 next unless $1 eq $island;
550 defined $islandid or die;
552 die "@filenames ?" if grep { $_ ne $filename } @filenames;
553 die "@forcerls ?" if grep { $_ ne $forcerl } @forcerls;
558 print STDERR "Setting ocean and island...\n";
560 my $siurl= ($url . "?action=setisland".
561 "&filename=$filename".
562 "&forcereload=$forcerl".
563 "&ocean=$oceanids[0]".
564 "&island=$islandid");
565 $resp= $ua->get($siurl);
567 die $resp->status_line unless $resp->is_success;
569 $resptxt= $resp->content();
570 save_upload_html('2', $resptxt);
572 die unless $resptxt =~ m/your uploaded data has been processed/i;
573 die unless $resptxt =~ m/your data has been integrated into the database/i;
575 $resptxt =~ s/\<a href=\"about:\w+\"\>[^<>]+\<\/a\>//g;
576 save_upload_html('3', $resptxt);
578 print "\n" or die $!;
579 system('w3m -T text/html -dump < _upload-3.html');
581 print "\n" or die $!;
587 close(STDOUT) or die $!;