package EPrints::KlarasConnect::Range;

# HTTP Range / conditional request parsing for file downloads.
# One byte range only (the member app resumes a single download); a
# multi-range request is answered with the whole file, which RFC 9110
# allows.

use strict;
use warnings;

# Returns:
#   undef                       no usable Range header: send the whole file
#   { start => n, end => m }    inclusive byte positions
#   'unsatisfiable'             answer 416
sub parse
{
	my( $header, $size ) = @_;

	return undef if !defined $header || !defined $size;
	return undef if $header !~ /\A\s*bytes\s*=\s*([^,]+?)\s*\z/i;
	my $spec = $1;

	return 'unsatisfiable' if $size == 0;

	if( $spec =~ /\A([0-9]{1,18})-([0-9]{0,18})\z/ )
	{
		my( $start, $end ) = ( $1 + 0, length $2 ? $2 + 0 : $size - 1 );
		return 'unsatisfiable' if $start >= $size;
		return undef if $end < $start;
		$end = $size - 1 if $end >= $size;
		return { start => $start, end => $end };
	}

	if( $spec =~ /\A-([0-9]{1,18})\z/ )
	{
		my $n = $1 + 0;
		return 'unsatisfiable' if $n == 0;
		$n = $size if $n > $size;
		return { start => $size - $n, end => $size - 1 };
	}

	return undef;
}

# True when an If-None-Match header matches the current ETag (weak
# comparison, as RFC 9110 requires for If-None-Match).
sub not_modified
{
	my( $if_none_match, $etag ) = @_;

	return 0 if !defined $if_none_match || !defined $etag;
	return 1 if $if_none_match =~ /\A\s*\*\s*\z/;

	foreach my $tag ( split /\s*,\s*/, $if_none_match )
	{
		$tag =~ s/\A\s*(?:W\/)?//;
		$tag =~ s/\s+\z//;
		return 1 if $tag eq $etag || $tag eq qq{"$etag"};
	}
	return 0;
}

# If-Range: the range only applies when the client's validator still
# matches. A date validator is not supported (strong ETags only).
sub if_range_ok
{
	my( $if_range, $etag ) = @_;

	return 1 if !defined $if_range || !length $if_range;
	( my $tag = $if_range ) =~ s/\A\s+|\s+\z//g;
	return 0 if $tag =~ /\AW\//;
	return $tag eq qq{"$etag"} || $tag eq $etag ? 1 : 0;
}

1;
