-
Notifications
You must be signed in to change notification settings - Fork 8
/
Client.pm
1356 lines (1155 loc) · 45.6 KB
/
Client.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Client;
use strict;
use Carp;
use Exception::Class (
'LacunaRPCException' => { fields => ['code', 'text', 'data'] }
);
use File::Path;
use File::Spec;
use JSON::PP;
use LWP::UserAgent;
use Scalar::Util qw(blessed);
use Time::Local;
use List::Util qw(min max first);
{
package LacunaRPCException;
use overload 'bool' => sub { 1 },
'""' => sub { "LacunaRPCException ".($_[0]->code).": ".($_[0]->text)."\n" },
'0+' => sub { $_[0]->code };
}
sub new {
my $base = shift;
die "Cannot make a new Client from ".ref($base)."\n"
if blessed($base) && !$base->isa("Client");
my $class = ref($base) || $base;
my $self = ref($base) ? { %$base, @_ } : { @_ };
bless($self, $class);
$self->read_config();
$self->{ua} ||= LWP::UserAgent->new();
$self->{cache_root} ||= 'cache';
$self->{total_calls} = 0;
return $self;
}
sub read_json {
my ($self, $filename, $filetype) = @_;
my $file;
# warn "filename: $filename\n";
unless (open($file, "<", $filename)) {
croak "Could not read $filetype file $filename: $!" if $filetype;
return;
}
my $json = do { local $/; <$file> };
close($file);
my $result = eval { decode_json($json) };
return $result;
}
sub write_json {
my $self = shift;
my $filename = shift;
my $filetype = shift;
my $value = shift;
my $dir = File::Spec->catpath((File::Spec->splitpath($filename))[0..1]);
-d $dir or mkpath($dir) or croak "Could not make path $dir: $!";
my $file;
open($file, ">", "$filename.$$") or croak "Could not write $filetype file $filename.$$: $!";
print $file encode_json($value);
close $file;
rename("$filename.$$", $filename) or croak "Could not rename $filetype file $filename.$$ to $filename: $!";
}
sub read_config {
my $self = shift;
croak "config not specified for Client" unless $self->{config};
my $config = $self->read_json($self->{config}, "config");
for my $key (qw(empire_name empire_password uri api_key cache_root captcha_program email_forward)) {
$self->{$key} = $config->{$key} if exists($config->{$key});
# warn "$key: $self->{$key}\n";
}
}
sub parse_time {
my $str = shift;
return timegm($6,$5,$4,$1,$2 - 1,$3) if $str =~ /^(\d+) (\d+) (20\d\d) (\d+):(\d+):(\d+) \+0000$/;
return;
}
sub format_time {
my $time = shift;
my $gm = shift;
my @elems = reverse(($gm ? gmtime($time) : localtime($time))[0..5]);
$elems[0] += 1900;
$elems[1]++;
sprintf("%4d-%02d-%02d %02d:%02d:%02d", @elems);
}
sub format_bignum {
my $num = shift;
my $str = sprintf("%0.0f ", $num);
1 while $str =~ s/(\d)(\d\d\d)(\D)/$1,$2$3/;
chop $str;
return $str;
}
sub log_call {
my $api = shift;
my $message = shift;
my $response = shift;
our $time;
our $count;
my $now = time();
if ($time ne $now) {
$time = $now;
$count = 0;
} else {
$count++;
}
my $dir = File::Spec->catdir("log", substr(format_time($time, 1), 0, 10));
-d $dir or mkpath($dir) or croak "Could not make path $dir: $!";
eval { confess("stacktrace") };
my $stack = $@;
my $password;
if ($api eq "/empire" && $message->{method} eq "login") {
my $password = $message->{params}[1];
$message->{params}[1] = "password elided";
my $pattern = $password;
$pattern =~ s/(\W)/\\$1/g;
$stack =~ s/$pattern/password elided/g;
}
my $filename = join(".", format_time($time, 1), $$, sprintf("%03d", $count), $api, $message->{method});
$filename =~ s-/--g;
$filename =~ s- -_-g;
my $pathname = File::Spec->catfile($dir, $filename);
$pathname =~ s/:/-/g if $pathname =~ /\\/;
my $file;
open($file, ">:utf8", $pathname) or croak "Could not log call: $pathname: $!";
print $file encode_json({
api => $api,
message => $message,
status => $response->status_line,
response => $response->content,
stack => $stack,
});
close($file);
if ($api eq "empire" && $message->{method} eq "login") {
$message->{params}[1] = $password;
}
}
sub call {
my $self = shift;
my $api = shift;
my $method = shift;
my @params = @_;
unshift(@params, $self->session_id) unless "$api/$method" eq "empire/login";
$api = "/$api" unless $api =~ /^\//;
my $message = { jsonrpc => "2.0", id => 1, method => $method, params => [ @params ] };
# warn "Posting to ".($self->{uri} . $api)."\n";
# warn "Content: ".encode_json($message)."\n";
my $response = $self->{ua}->post($self->{uri} . $api, Content => encode_json($message));
$self->{total_calls}++;
log_call($api, $message, $response);
my $result;
eval { $result = decode_json($response->content); };
if (!$result && $@ =~ /^malformed/) {
print $response->content;
die $@;
}
if ($result->{error} && $result->{error}{code} == 1010 && $result->{error}{message} =~ /maximum number of requests/i) {
# {
# "error" : {
# "code" : 1010,
# "data" : null,
# "message" : "You have already made the maximum number of requests (10000) you can make for one day."
# },
# "id" : 1,
# "jsonrpc" : "2.0"
# }
# warn "Request: ".encode_json($message)."\n";
warn "Out of requests. Shutting down.\n";
$self->cache_write( type => 'misc', id => 'rpc_limit', data => { rpc_exceeded => 1 } );
LacunaRPCException->throw(code => $result->{error}{code}, text => $result->{error}{message},
data => JSON::PP->new->allow_nonref->canonical->pretty->encode($result->{error}{data}));
} elsif ($result->{error} && $result->{error}{code} == 1010 && $result->{error}{message} =~ /slow down/i) {
warn "Request throttling active: $result->{error}{message}\nSleeping for 30 seconds before retry.\n";
sleep 30;
return $self->call($api, $method, @_);
} elsif ($result->{error} && $result->{error}{code} == 1016 && $self->{captcha_program}) {
warn "Captcha needed.\n";
$self->present_captcha();
return $self->call($api, $method, @_);
} elsif ($result->{error} && $result->{error}{code} == 1014 && $self->{captcha_program}) {
warn "Captcha answer incorrect.\n";
$self->present_captcha($result->{error}{data});
return "wrong";
} elsif ($result->{error}) {
# warn "Request: ".encode_json($message)."\n";
warn "Error Response: $result->{error}{code}: $result->{error}{message}\n";
LacunaRPCException->throw(code => $result->{error}{code}, text => $result->{error}{message},
data => JSON::PP->new->allow_nonref->canonical->pretty->encode($result->{error}{data}));
}
croak "Call failed: ".($response->status_line) unless $response->is_success;
croak "Call response without result" unless $result->{result};
$self->{session_id} = $result->{result}{session_id} if $result->{result}{session_id};
$self->{session_time} = time();
$self->write_session if $self->{session_id};
my $time = parse_time($result->{result}{status}{server}{time});
$result->{result}{status}{_time} = $time;
my $empire = $result->{result}{status}{empire};
if ($empire) {
$self->cache_write( type => 'empire_status', data => $empire );
eval {
my $message_id = $empire->{latest_message_id} || eval { $empire->{most_recent_message}{id} };
if ($message_id && $message_id ne $self->cache_read( type => 'mail_inbox' )->{messages}[0]{id}) {
# print "Invalidating mailbox: new $empire->{most_recent_message}{id} ne cached ".($self->cache_read( type => 'mail_inbox' )->{messages}[0]{id})."\n";
$self->cache_invalidate( type => 'mail_inbox' );
}
};
}
my $body = $result->{result}{status}{body};
if ($body) {
my @arrivals = map { parse_time($_->{date_arrives}) } @{ $body->{incoming_foreign_ships} || [] };
my $invalid = List::Util::min(time() + 3600, @arrivals);
$self->cache_write( type => 'body_status', id => $body->{id}, data => $body, invalid => $invalid );
}
return $result->{result};
}
sub read_session {
my $self = shift;
my $session = $self->cache_read( type => 'session' );
@$self{ keys %$session } = values %$session;
return;
}
sub write_session {
my $self = shift;
my $session = {
session_id => $self->{session_id},
session_time => time(),
};
$self->cache_write( type => 'session', data => $session );
return;
}
sub session_id {
my $self = shift;
# warn "Known session: $self->{session_id}\n";
return $self->{session_id} if $self->{session_time} >= time() - 3600 * 1.5;
$self->read_session();
# warn "Preexisting session: $self->{session_id}\n";
return $self->{session_id} if $self->{session_time} >= time() - 3600 * 1.5;
my $result = $self->call(empire => login => $self->{empire_name}, $self->{empire_password}, $self->{api_key});
# warn "Created session: $self->{session_id}\n";
return $self->{session_id} if $self->{session_time} >= time() - 3600 * 1.5;
croak "Couldn't get session_id";
}
sub empire_status {
my $self = shift;
my $result = $self->cache_read( type => 'empire_status', stale => 610 );
$result && return $result;
$result = $self->call(empire => login => $self->{empire_name}, $self->{empire_password}, $self->{api_key})->{status}{empire};
return $result || croak "Couldn't get empire status";
}
sub empire_public_profile {
my $self = shift;
my $id = shift;
my $result = $self->cache_read( type => 'empire_profile', id => $id, stale => 86400 );
$result && return $result;
$result = $self->call(empire => view_public_profile => $id);
$self->cache_write( type => 'empire_profile', id => $id, data => $result, invalid => time() + 86400 );
return $result;
}
sub match_planet {
my $self = shift;
my $name = shift;
my $planets = $self->empire_status->{planets};
my @candidates = grep { $planets->{$_} =~ /$name/ } keys %$planets;
return $candidates[0] if @candidates == 1;
LacunaRPCException->throw(code => 1002, text => "Planet name $name not found") unless @candidates;
LacunaRPCException->throw(code => 1002, text => "Planet name $name is ambiguous",
data => JSON::PP->new->allow_nonref->canonical->pretty->encode([ map { $planets->{$_} } @candidates ]));
}
sub body_status {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'body_status', id => $body_id, stale => 500 );
return $result if $result;
$self->cache_invalidate( type => 'buildings', id => $body_id );
$result = $self->body_buildings($body_id)->{status}{body};
return $result || croak "Couldn't get body status";
}
sub body_buildings {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'buildings', id => $body_id );
return $result if $result;
$result = $self->call(body => get_buildings => $body_id);
my @completions;
for my $building (values(%{$result->{buildings}})) {
push(@completions, parse_time($building->{pending_build}{end})) if $building->{pending_build};
push(@completions, parse_time($building->{work }{end})) if $building->{work};
}
my $invalid = List::Util::min(time() + 3600, @completions);
$self->cache_write( type => 'buildings', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub body_buildable {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'buildable', id => $body_id );
return $result if $result;
my $buildings = $self->body_buildings($body_id);
my @completions;
for my $building (values(%{$buildings->{buildings}})) {
next unless $building->{pending_build};
# next unless $building->{name} =~ /Oversight|Ore Refinery|Intelligence|University/;
push(@completions, parse_time($building->{pending_build}{end}));
}
my $body = $self->body_status($body_id);
if ($body->{incoming_foreign_ships}) {
push(@completions, map { parse_time($_->{date_arrives}) } @{$body->{incoming_foreign_ships}});
}
if ($body->{incoming_own_ships}) {
push(@completions, map { parse_time($_->{date_arrives}) } @{$body->{incoming_own_ships}});
}
my %plots;
for my $building (values %{$buildings->{buildings}}) {
$plots{$building->{x},$building->{y}} = 1;
}
my @plots;
for my $x (-5 .. 5) {
for my $y (-5 .. 5) {
# next if $x >= 3 && $y >= 3;
push(@plots, [ $x, $y ]) unless $plots{$x,$y};
}
}
$result = $self->call(body => get_buildable => $body_id, $plots[0][0], $plots[0][1]);
my $invalid = List::Util::max(time() + 30, List::Util::min(time() + 600, @completions));
$self->cache_write( type => 'buildable', id => $body_id, invalid => $invalid, data => $result );
return $result;
}
sub body_build {
my $self = shift;
my $body_id = shift;
my $building_name = shift;
my $sx = shift;
my $sy = shift;
my $url = "";
my %plots;
my $existing = $self->body_buildings($body_id);
for my $building (values %{$existing->{buildings}}) {
$plots{$building->{x},$building->{y}} = 1;
$url = $building->{url} if $building->{name} eq $building_name;
}
my @plots;
for my $x (-5 .. 5) {
for my $y (-5 .. 5) {
next if -1 <= $x && $x <= 1 && -1 <= $y && $y <= 1;
# next if $x >= 3 && $y >= 3;
push(@plots, [ $x, $y ]) unless $plots{$x,$y};
}
}
my $place = $plots[int(rand(@plots))];
$place = [ $sx, $sy ] if ($sx || $sy) && !$plots{$sx,$sy};
$url ||= $self->body_buildable($body_id)->{buildable}{$building_name}{url};
return $self->building_build($url, $body_id, @$place);
}
sub building_build {
my $self = shift;
my $url = shift;
my $body_id = shift;
my $x = shift;
my $y = shift;
# invalidate the buildable cache
$self->cache_invalidate( type => 'buildable', id => $body_id );
my $result = $self->call($url => build => $body_id, $x, $y);
if ( $result ) {
# invalidate the buildings cache
$self->cache_invalidate( type => 'buildings', id => $body_id );
$self->cache_invalidate( type => 'plans', id => $body_id );
# invalidate building caches if we upgrade oversight ministry or ore refinery
if ( $url =~ /oversite|orerefinery/ ) {
for my $id ( keys %{$self->body_buildings($result->{status}{body}{id})->{buildings}} ) {
$self->cache_invalidate( type => 'building_stats', id => $id, level => $_ ) for ( 0 .. 30 );
}
}
}
return $result;
}
sub building_demolish {
my $self = shift;
my $url = shift;
my $building_id = shift;
my $result = $self->call($url => demolish => $building_id);
$self->cache_invalidate( type => 'building_view', id => $building_id );
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'buildable', id => $result->{status}{body}{id} );
return $result;
}
sub building_upgrade {
my $self = shift;
my $url = shift;
my $building_id = shift;
if ( my $result = eval { $self->call($url => upgrade => $building_id); } ) {
$self->cache_invalidate( type => 'building_view', id => $building_id );
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'plans', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'buildable', id => $result->{status}{body}{id} ) if $url =~ /oversight|orerefinery|intelligence|university/;
# invalidate the buildings cache
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
# invalidate building caches if we upgrade oversight ministry or ore refinery
if ( $url =~ /oversite|orerefinery/ ) {
for my $id ( keys %{$self->body_buildings($result->{status}{body}{id})->{buildings}} ) {
$self->cache_invalidate( type => 'building_stats', id => $id, level => $_ ) for ( 0 .. 30 );
}
}
return $result;
}
else {
if (my $e = Exception::Class->caught('LacunaRPCException')) {
if ($e->code eq 1011 || $e->code eq 1012) {
# Not enough X in storage / production
$self->cache_invalidate( type => 'building_view', id => $building_id );
}
$e->rethrow;
}
else {
my $e = Exception::Class->caught();
ref $e ? $e->rethrow : die $e;
}
}
}
sub body_subsidize {
my $self = shift;
my $body_id = shift;
my $dev = $self->find_building($body_id, "Development Ministry");
my $result = $self->call(development => subsidize_build_queue => $dev->{id});
$self->cache_invalidate(type => "buildings", id => $body_id);
$self->cache_invalidate(type => "buildable", id => $body_id);
return $result;
}
sub halls_sacrifice {
my $self = shift;
my $hall_id = shift;
my $building_id = shift;
my $result = eval { $self->call(hallsofvrbansk => sacrifice_to_upgrade => $hall_id, $building_id); };
$self->cache_invalidate( type => 'building_view', id => $building_id );
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'plans', id => $result->{status}{body}{id} );
return $result;
}
sub building_repair {
my $self = shift;
my $url = shift;
my $building_id = shift;
my $result = $self->call($url => repair => $building_id);
if ( $result ) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'building_view', id => $building_id );
}
return $result;
}
sub building_view {
my $self = shift;
my $url = shift;
my $building_id = shift;
my $result = $self->cache_read( type => 'building_view', id => $building_id );
return $result if $result;
$result = $self->call($url, view => $building_id);
my @completions;
for my $building ($result->{building}) {
push(@completions, parse_time($building->{pending_build}{end})) if $building->{pending_build};
push(@completions, parse_time($building->{work }{end})) if $building->{work};
}
push(@completions, time() + 300) unless $result->{building}{upgrade}{can};
my $invalid = List::Util::min(time() + 3600, @completions);
$self->cache_write( type => 'building_view', id => $building_id, invalid => $invalid, data => $result );
return $result;
}
sub building_stats_for_level {
my $self = shift;
my $url = shift;
my $building_id = shift;
my $level = shift;
my $result = $self->cache_read( type => 'building_stats', id => $building_id, level => $level );
return $result if $result;
$result = $self->call($url, get_stats_for_level => $building_id, $level);
$self->cache_write( type => 'building_stats', id => $building_id, level => $level, data => $result );
return $result;
}
sub find_building {
my $self = shift;
my $where = shift;
my $name = shift;
my $level = shift;
my $buildings = $self->body_buildings($where);
my @buildings = map { { %{$buildings->{buildings}{$_}}, id => $_ } } keys(%{$buildings->{buildings}});
@buildings = grep { $_->{name} eq $name } @buildings;
@buildings = grep { $_->{level} == $level } @buildings if $level;
my @sorted = sort { $a->{level} <=> $b->{level} } @buildings;
if (wantarray()) {
return @sorted;
} else {
return $sorted[$#sorted] if @sorted;
LacunaRPCException->throw(code => 1002, text => "$name not found",
data => JSON::PP->new->allow_nonref->canonical->pretty->encode({body_id => $where, name => $name, level => $level}));
}
}
sub body_plans {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'plans', id => $body_id );
return $result if $result;
# Trade and transporter are preferred because of the inclusion of cargo size and plan_type
# The last one is not in an eval so that fundamental exceptions (e.g. login failure) propagate
$result = eval { $self->call(trade => get_plan_summary => scalar($self->find_building($body_id, "Trade Ministry" ))->{id}) } ||
eval { $self->call(transporter => get_plan_summary => scalar($self->find_building($body_id, "Subspace Transporter" ))->{id}) } ||
$self->call(planetarycommand => view_plans => scalar($self->find_building($body_id, "Planetary Command Center"))->{id});
my @arrivals;
for my $type (qw(incoming_own_ships incoming_enemy_ships incoming_ally_ships incoming_foreign_ships)) {
next unless $result->{status}{body}{$type};
for my $ship (@{$result->{status}{body}{$type}}) {
push(@arrivals, parse_time($ship->{date_arrives}));
}
}
my $invalid = List::Util::min(time() + 3600, @arrivals);
$self->cache_write( type => 'plans', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub body_waste_chain {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'waste_chain', id => $body_id );
return $result if $result;
$result = $self->call(trade => view_waste_chains => scalar($self->find_building($body_id, "Trade Ministry"))->{id});
my $invalid = time() + (23 * 3600);
$self->cache_write( type => 'waste_chain', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub add_waste_ship_to_fleet {
my $self = shift;
my $body_id = shift;
my $ship_id = shift;
my $result = $self->call(trade => add_waste_ship_to_fleet =>
scalar($self->find_building($body_id, "Trade Ministry"))->{id}, $ship_id);
$self->cache_invalidate( type => 'waste_chain', id => $body_id );
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $body_id );
return $result;
}
sub remove_waste_ship_from_fleet {
my $self = shift;
my $body_id = shift;
my $ship_id = shift;
my $result = $self->call(trade => remove_waste_ship_from_fleet =>
scalar($self->find_building($body_id, "Trade Ministry"))->{id}, $ship_id);
$self->cache_invalidate( type => 'waste_chain', id => $body_id );
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $body_id );
return $result;
}
sub scuttle_ship {
my $self = shift;
my $body_id = shift;
my $ship_id = shift;
my $result = $self->call(spaceport => scuttle_ship =>
scalar($self->find_building($body_id, "Space Port"))->{id}, $ship_id);
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $body_id );
return $result;
}
sub name_ship {
my $self = shift;
my $body_id = shift;
my $ship_id = shift;
my $name = shift;
my $result = $self->call(spaceport => name_ship =>
scalar($self->find_building($body_id, "Space Port"))->{id}, $ship_id, $name);
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $body_id );
return $result;
}
sub view_excavators {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'excavators', id => $body_id );
return $result if $result;
# Trade and transporter are preferred because of the inclusion of cargo size
# The last one is not in an eval so that fundamental exceptions (e.g. login failure) propagate
$result = $self->call(archaeology => view_excavators => scalar($self->find_building($body_id, "Archaeology Ministry"))->{id});
my @travelling;
if ($result->{travelling}) {
my $ships = $self->port_all_ships($body_id);
@travelling = grep { $_->{type} eq "excavator" && $_->{task} eq "Travelling" } @{$ships->{ships}};
if ($result->{travelling} != @travelling) {
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $body_id );
my $ships = $self->port_all_ships($body_id);
@travelling = grep { $_->{type} eq "excavator" && $_->{task} eq "Travelling" } @{$ships->{ships}};
}
}
my @arrivals = map { parse_time($_->{date_arrives}) } @travelling;
my $invalid = List::Util::min(time() + (23 * 3600), @arrivals);
$self->cache_write( type => 'excavators', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub glyph_list {
my $self = shift;
my $body_id = shift;
my $result = $self->cache_read( type => 'glyphs', id => $body_id );
return $result if $result;
# Trade and transporter are preferred because of the inclusion of cargo size
# The last one is not in an eval so that fundamental exceptions (e.g. login failure) propagate
$result = eval { $self->call(trade => get_glyph_summary => scalar($self->find_building($body_id, "Trade Ministry" ))->{id}) } ||
eval { $self->call(transporter => get_glyph_summary => scalar($self->find_building($body_id, "Subspace Transporter"))->{id}) } ||
$self->call(archaeology => get_glyph_summary => scalar($self->find_building($body_id, "Archaeology Ministry"))->{id});
my @arrivals;
for my $type (qw(incoming_own_ships incoming_enemy_ships incoming_ally_ships incoming_foreign_ships)) {
next unless $result->{status}{body}{$type};
for my $ship (@{$result->{status}{body}{$type}}) {
push(@arrivals, parse_time($ship->{date_arrives}));
}
}
my $invalid = List::Util::min(time() + 3600, @arrivals);
$self->cache_write( type => 'glyphs', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub glyph_assemble {
my $self = shift;
my $body_id = shift;
my $recipe = shift;
my $count = @_ ? shift : 1;
my $arch = $self->find_building($body_id, "Archaeology Ministry");
my $result = $self->call(archaeology => assemble_glyphs => $arch->{id}, $recipe, $count);
if ($result) {
$self->cache_invalidate( type => 'plans', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'glyphs', id => $result->{status}{body}{id} );
}
return $result;
}
sub park_party {
my $self = shift;
my $building_id = shift;
my $result = $self->call(park => throw_a_party => $building_id);
if ( $result ) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'building_view', id => $building_id );
}
return $result;
}
sub themepark_operate {
my $self = shift;
my $building_id = shift;
my $result = $self->call(themepark => operate => $building_id);
if ( $result ) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'building_view', id => $building_id );
}
return $result;
}
sub recycle_recycle {
my $self = shift;
my $building_id = shift;
my $water = shift;
my $ore = shift;
my $energy = shift;
my $type = shift || "wasterecycling";
my $result = $self->call($type => recycle => $building_id, $water, $ore, $energy, 0);
if ( $result ) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'building_view', id => $building_id );
}
return $result;
}
sub archaeology_search {
my $self = shift;
my $building_id = shift;
my $ore = shift;
my $result = $self->call(archaeology => search_for_glyph => $building_id, $ore);
if ( $result ) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'building_view', id => $building_id );
$self->cache_invalidate( type => 'glyphs', id => $result->{status}{body}{id} );
}
return $result;
}
sub ores_for_search {
my $self = shift;
my $building_id = shift;
my $result = $self->call(archaeology => get_ores_available_for_processing => $building_id);
return $result;
}
sub get_glyphs {
my $self = shift;
my $building_id = shift;
my $result = $self->call(archaeology => get_glyphs => $building_id);
return $result;
}
sub port_all_ships {
my $self = shift;
my $building_id = shift;
my $body_id;
my $planets = $self->empire_status->{planets};
if ($planets->{$building_id}) {
$body_id = $building_id;
$building_id = $self->find_building($body_id, "Space Port")->{id};
} else {
$body_id = $self->building_stats_for_level(spaceport => $building_id, 1)->{status}{body}{id};
}
my $result = $self->cache_read( type => 'spaceport_view_all_ships', id => $body_id, stale => 3600 );
return $result if $result;
my @ships;
$result = $self->call(spaceport => view_all_ships => $building_id, { no_paging => 1 });
push(@ships, @{$result->{ships}});
$result->{ships} = [ @ships ];
my @completions;
for my $ship (@{$result->{ships}}) {
if ($ship->{date_available}) {
my $available = parse_time($ship->{date_available});
push(@completions, $available) if $available > time() + 30;
}
push(@completions, parse_time($ship->{date_arrives})) if $ship->{date_arrives};
}
my $invalid = List::Util::min(time() + 3600, @completions);
$self->cache_write( type => 'spaceport_view_all_ships', id => $body_id, data => $result, invalid => $invalid );
return $result;
}
sub get_probed_stars {
my $self = shift;
my $building_id = shift;
my $result = $self->cache_read( type => 'observatory_get_probed_stars', id => $building_id );
return $result if $result;
my $page = 1;
my @stars;
for (;;) {
$result = $self->call(observatory => get_probed_stars => $building_id, $page);
push @stars, @{$result->{stars}};
last if @{$result->{stars}} < 25;
$page++;
}
$result->{stars} = \@stars;
my $invalid = time() + 600;
$self->cache_write( type => 'observatory_get_probed_stars', id => $building_id, data => $result, invalid => $invalid );
return $result;
}
sub ships_for {
my $self = shift;
my $planet = shift;
my $target = shift;
my $result = $self->call(spaceport => get_ships_for => $planet, $target);
return $result;
}
sub send_ship {
my $self = shift;
my $ship = shift;
my $target = shift;
my $result = $self->call(spaceport => send_ship => $ship, $target);
return $result;
}
sub send_fleet {
my $self = shift;
my $ships = shift;
my $target = shift;
my $result = $self->call(spaceport => send_fleet => $ships, $target);
return $result;
}
sub send_spies {
my $self = shift;
my $from = shift;
my $to = shift;
my $ship = shift;
my $spies = shift;
my $result = $self->call(spaceport => send_spies => $from, $to, $ship, $spies);
return $result;
}
sub fetch_spies {
my $self = shift;
my $from = shift;
my $to = shift;
my $ship = shift;
my $spies = shift;
my $result = $self->call(spaceport => fetch_spies => $from, $to, $ship, $spies);
return $result;
}
sub yard_queue {
my $self = shift;
my $building_id = shift;
my $result = $self->cache_read( type => 'shipyard_view_build_queue', id => $building_id );
return $result if $result;
my $page = 1;
my @ships;
for (;;) {
$result = $self->call(shipyard => view_build_queue => $building_id, $page);
push(@ships, @{$result->{ships_building}});
last if @{$result->{ships_building}} < 25;
$page++;
}
$result->{ships_building} = [ @ships ];
my @completions;
for my $ship (@{$result->{ships_building}}) {
if ($ship->{date_completed}) {
my $available = parse_time($ship->{date_completed});
push(@completions, $available) if $available > time() + 30;
}
push(@completions, parse_time($ship->{date_arrives})) if $ship->{date_arrives};
}
my $invalid = List::Util::min(time() + 3600, @completions);
$self->cache_write( type => 'shipyard_view_build_queue', id => $building_id, data => $result, invalid => $invalid );
return $result;
}
sub yard_buildable {
my $self = shift;
my $yard_id = shift;
my $result = $self->cache_read( type => 'shipyard_buildable', id => $yard_id );
return $result if $result;
$result = $self->call(shipyard => get_buildable => $yard_id);
# Building completions can affect shipyard builds
my $body_id = $result->{status}{body}{id};
my $buildings = $self->body_buildings($body_id);
my @completions;
for my $building (values(%{$buildings->{buildings}})) {
next unless $building->{pending_build};
push(@completions, parse_time($building->{pending_build}{end}));
}
my $invalid = List::Util::max(time() + 30, List::Util::min(time() + 600, @completions));
$self->cache_write( type => 'shipyard_buildable', id => $yard_id, data => $result, invalid => $invalid );
return $result;
}
sub yard_build {
my $self = shift;
my $building_id = shift;
my $type = shift;
my $count = shift || 1;
my $result = $self->call(shipyard => build_ship => $building_id, $type, $count);
$self->cache_invalidate( type => 'buildable', id => $building_id );
$self->cache_invalidate( type => 'shipyard_view_build_queue', id => $building_id );
if ($result) {
$self->cache_invalidate( type => 'buildings', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $result->{status}{body}{id} );
}
return $result;
}
sub trade_push {
my $self = shift;
my $building_id = shift;
my $target_id = shift;
my $items = shift;
my $options = shift;
my $result = $self->call(trade => push_items => $building_id, $target_id, $items, $options);
if ($result) {
$self->cache_invalidate( type => 'body_status', id => $target_id );
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $target_id );
$self->cache_invalidate( type => 'spaceport_view_all_ships', id => $result->{status}{body}{id} );
if (grep { $_->{type} eq "plan" } @$items) {
$self->cache_invalidate( type => 'plans', id => $target_id );
$self->cache_invalidate( type => 'plans', id => $result->{status}{body}{id} );
$self->cache_invalidate( type => 'buildable', id => $result->{status}{body}{id} );
}
if (grep { $_->{type} eq "glyph" } @$items) {
$self->cache_invalidate( type => 'glyphs', id => $target_id );
$self->cache_invalidate( type => 'glyphs', id => $result->{status}{body}{id} );
}
}
return $result;
}
sub transporter_push {
my $self = shift;
my $building_id = shift;
my $target_id = shift;
my $items = shift;
my $result = $self->call(transporter => push_items => $building_id, $target_id, $items);
if ($result) {