App-Phoebe

 view release on metacpan or  search on metacpan

script/gemini  view on Meta::CPAN

    # 1h timeout (for chat)
    $stream->timeout(3600);
    my ($header, $mimetype, $encoding);
    $stream->on(read => sub {
      my ($stream, $bytes) = @_;
      if (not $header) {
	# decide how to decode the bytes
	($header) = $bytes =~ /^(.*?)\r\n/;
	$header = decode_utf8 $header;
	warn "$header\n";
	if ($header =~ /^2\d* (?:text\/\S+)?(?:; *charset=(\S+))?$/g) {
	  # empty, or text without charset defaults to UTF-8
	  $encoding = $1 || 'UTF-8';
	}
	$bytes =~ s/^(.*?)\r\n//;
	return unless $bytes;
	if (-t STDOUT) {
	  # connected to a tty
	  if ($force) {
	    binmode(STDOUT, ":raw");
	    print $bytes;
	  } elsif ($encoding) {
	    if ($encoding eq $ENCODING_CONSOLE_OUT) {
	      print $bytes;
	    } else {
	      warn "The console takes $ENCODING_CONSOLE_OUT but this text uses $encoding, so better not print it (use --force to do it anyway)\n";
	      warn "Or even better, redirect it to a file:\n";
	      warn "gemini $uri > data.txt\n";
	      Mojo::IOLoop->stop;
	    }
	  } else {
	    my $extension = extension($header);
	    warn "Better not to print binary data to a terminal (use --force to do it anyway)\n";
	    warn "Or even better, redirect it to a file:\n";
	    warn "gemini $uri > data.$extension\n";
	    Mojo::IOLoop->stop;
	  }
	} else {
	  # connected to a file or pipe
	  binmode(STDOUT, ":raw");
	  print $bytes;
	}
      } else {
	# continuing to print
	print $bytes;
      }});
    # Write request
    warn "Requesting $uri\n" if $verbose;
    $stream->write("$uri\r\n")});

# Start event loop if necessary
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

# Helper
sub extension {
  $_ = shift;
  return 'gmi' if /text\/gemini/;
  return 'txt' if /text\/plain/;
  return 'md' if /text\/markdown/;
  return 'html' if /text\/html/;
  return 'png' if /image\/png/;
  return 'jpg' if /image\/jpeg/;
  return 'gif' if /image\/gif/;
  return 'txt';
}



( run in 0.633 second using v1.01-cache-2.11-cpan-df04353d9ac )