+use PublicInbox::MID qw/mid_clean mid_escape/;
+use PublicInbox::Hval qw/to_filename/;
+use Email::Simple;
+use Email::MIME::Encode;
+
+sub subject_fn ($) {
+ my ($simple) = @_;
+ my $fn = $simple->header('Subject');
+ return 'no-subject' unless defined($fn);
+
+ # no need for full Email::MIME, here
+ if ($fn =~ /=\?/) {
+ eval { $fn = Encode::decode('MIME-Header', $fn) };
+ $fn = 'no-subject' if $@;
+ }
+ $fn =~ s/^re:\s+//i;
+ $fn = to_filename($fn);
+ $fn eq '' ? 'no-subject' : $fn;
+}
+
+sub mb_stream {
+ my ($more) = @_;
+ bless $more, 'PublicInbox::Mbox';
+}
+
+# called by PSGI server as body response
+sub getline {
+ my ($more) = @_; # self
+ my ($ctx, $id, $prev, $next, $cur) = @$more;
+ if ($cur) { # first
+ pop @$more;
+ return msg_str($ctx, $cur);
+ }
+ $cur = $next or return;
+ my $ibx = $ctx->{-inbox};
+ $next = $ibx->search->next_by_mid($ctx->{mid}, \$id, \$prev);
+ @$more = ($ctx, $id, $prev, $next); # $next may be undef, here
+ my $mref = $ibx->msg_by_smsg($cur) or return;
+ msg_str($ctx, Email::Simple->new($mref));
+}
+
+sub close {} # noop
+
+sub emit_raw {
+ my ($ctx) = @_;
+ my $mid = $ctx->{mid};
+ my $ibx = $ctx->{-inbox};
+ my $first;
+ my $more;
+ if (my $srch = $ibx->search) {
+ my ($id, $prev);
+ my $smsg = $srch->next_by_mid($mid, \$id, \$prev) or return;
+ my $mref = $ibx->msg_by_smsg($smsg) or return;
+ $first = Email::Simple->new($mref);
+ my $next = $srch->next_by_mid($mid, \$id, \$prev);
+ # $more is for ->getline
+ $more = [ $ctx, $id, $prev, $next, $first ] if $next;
+ } else {
+ my $mref = $ibx->msg_by_mid($mid) or return;
+ $first = Email::Simple->new($mref);
+ }
+ return unless defined $first;
+ my $fn = subject_fn($first);
+ my @hdr = ('Content-Type');
+ if ($ibx->{obfuscate}) {
+ # obfuscation is stupid, but maybe scrapers are, too...
+ push @hdr, 'application/mbox';
+ $fn .= '.mbox';
+ } else {
+ push @hdr, 'text/plain';
+ $fn .= '.txt';
+ }
+ push @hdr, 'Content-Disposition', "inline; filename=$fn";
+ [ 200, \@hdr, $more ? mb_stream($more) : [ msg_str($ctx, $first) ] ];