+ # Piece together historic score information, to the degree we have it.
+ if (!$historic_json_only && exists($pos_calculating->{'history'})) {
+ my %score_history = ();
+
+ my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
+ my $pos = Position->start_pos('white', 'black');
+ my $halfmove_num = 0;
+ for my $move (@{$pos_calculating->{'history'}}) {
+ my $id = id_for_pos($pos, $halfmove_num);
+ my $ref = $dbh->selectrow_hashref($q, undef, $id);
+ if (defined($ref)) {
+ $score_history{$halfmove_num} = [
+ $ref->{'score_type'},
+ $ref->{'score_value'}
+ ];
+ }
+ ++$halfmove_num;
+ ($pos) = $pos->make_pretty_move($move);
+ }
+ $q->finish;
+
+ # If at any point we are missing 10 consecutive moves,
+ # truncate the history there. This is so we don't get into
+ # a situation where we e.g. start analyzing at move 45,
+ # but we have analysis for 1. e4 from some completely different game
+ # and thus show a huge hole.
+ my $consecutive_missing = 0;
+ my $truncate_until = 0;
+ for (my $i = $halfmove_num; $i --> 0; ) {
+ if ($consecutive_missing >= 10) {
+ delete $score_history{$i};
+ next;
+ }
+ if (exists($score_history{$i})) {
+ $consecutive_missing = 0;
+ } else {
+ ++$consecutive_missing;
+ }
+ }
+
+ $json->{'score_history'} = \%score_history;
+ }
+
+ # Give out a list of other games going on. (Empty is fine.)
+ # TODO: Don't bother reading our own file, the data will be stale anyway.
+ if (!$historic_json_only) {
+ my @games = ();
+
+ my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
+ $q->execute;
+ while (my $ref = $q->fetchrow_hashref) {
+ eval {
+ my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
+ my $other_game_json = JSON::XS::decode_json($other_game_contents);
+
+ die "Missing position" if (!exists($other_game_json->{'position'}));
+ my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
+ my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
+
+ my $game = {
+ id => $ref->{'id'},
+ name => "$white–$black",
+ url => $ref->{'url'},
+ hashurl => $ref->{'hash_url'},
+ };
+ if (defined($other_game_json->{'position'}{'result'})) {
+ $game->{'result'} = $other_game_json->{'position'}{'result'};
+ } else {
+ $game->{'score'} = $other_game_json->{'score'};
+ }
+ push @games, $game;
+ };
+ if ($@) {
+ warn "Could not add external game " . $ref->{'json_path'} . ": $@";
+ }
+ }
+
+ if (scalar @games > 0) {
+ $json->{'games'} = \@games;
+ }
+ }
+
+ my $json_enc = JSON::XS->new;
+ $json_enc->canonical(1);
+ my $encoded = $json_enc->encode($json);