]> git.sesse.net Git - remoteglot/commitdiff
Handle streaming PGNs, like from Lichess (although this might break non-streaming... master
authorSteinar H. Gunderson <sgunderson@bigfoot.com>
Wed, 7 Feb 2024 16:47:21 +0000 (17:47 +0100)
committerSteinar H. Gunderson <sgunderson@bigfoot.com>
Wed, 7 Feb 2024 16:47:46 +0000 (17:47 +0100)
remoteglot.pl

index f7b0456cee7f0cd316315142cca1ab6e9115d5b3..b5db356ca5dde24c1d2f7fb167448e07e4ae660c 100755 (executable)
@@ -89,7 +89,10 @@ print "Chess engine ready.\n";
 
 if (defined($remoteglotconf::target)) {
        if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
-               fetch_pgn($remoteglotconf::target);
+               my $target = $remoteglotconf::target;
+               # Convenience.
+               $target =~ s#https://lichess.org/broadcast/.*/([^/]+)?$#https://lichess.org/api/stream/broadcast/round/$1.pgn#;
+               fetch_pgn($target);
        }
 }
 
@@ -147,9 +150,14 @@ sub fetch_pgn {
                        });
                }
        } else {
-               AnyEvent::HTTP::http_get($url, sub {
-                       handle_pgn(@_, $url);
-               });
+               my $buffer = '';
+               AnyEvent::HTTP::http_get($url,
+                       on_body => sub {
+                               handle_partial_pgn(@_, \$buffer, $url);
+                       },
+                       sub {
+                               end_pgn(@_, \$buffer, $url);
+                       });
        }
 }
 
@@ -157,14 +165,32 @@ my ($last_pgn_white, $last_pgn_black);
 my @last_pgn_uci_moves = ();
 my $pgn_hysteresis_counter = 0;
 
-sub handle_pgn {
-       my ($body, $header, $url) = @_;
+sub handle_partial_pgn {
+       my ($body, $header, $buffer, $url) = @_;
 
        if ($stop_pgn_fetch) {
                $stop_pgn_fetch = 0;
                $http_timer = undef;
-               return;
+               return 0;
        }
+       $$buffer .= $body;
+       while ($$buffer =~ s/^\s*(.*)\n\n\n//s) {
+               handle_pgn($1, $url);
+       }
+       return 1;
+}
+
+sub end_pgn {
+       my ($body, $header, $buffer, $url) = @_;
+       handle_pgn($$buffer, $url);
+       $$buffer = "";
+       $http_timer = AnyEvent->timer(after => $remoteglotconf::poll_frequency, cb => sub {
+               fetch_pgn($url);
+       });
+}
+
+sub handle_pgn {
+       my ($body, $url) = @_;
 
        my $pgn = Chess::PGN::Parse->new(undef, $body);
        if (!defined($pgn)) {