1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # per-mitem/smsg iterators for search results
5 # "ovv" => "Overview viewer"
6 package PublicInbox::LeiOverview;
9 use parent qw(PublicInbox::Lock);
10 use POSIX qw(strftime);
11 use Fcntl qw(F_GETFL O_APPEND);
14 use PublicInbox::MID qw($MID_EXTRACT);
15 use PublicInbox::Address qw(pairs);
16 use PublicInbox::Config;
17 use PublicInbox::Search qw(get_pct);
18 use PublicInbox::LeiDedupe;
19 use PublicInbox::LeiToMail;
21 # cf. https://en.wikipedia.org/wiki/JSON_streaming
22 my $JSONL = 'ldjson|ndjson|jsonl'; # 3 names for the same thing
24 sub _iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
26 # we open this in the parent process before ->wq_do handoff
27 sub ovv_out_lk_init ($) {
29 $self->{tmp_lk_id} = "$self.$$";
30 my $tmp = File::Temp->new("lei-ovv.dst.$$.lock-XXXXXX",
31 TMPDIR => 1, UNLINK => 0);
32 $self->{lock_path} = $tmp->filename;
35 sub ovv_out_lk_cancel ($) {
37 ($self->{tmp_lk_id}//'') eq "$self.$$" and
38 unlink(delete($self->{lock_path}));
42 my ($class, $lei) = @_;
43 my $opt = $lei->{opt};
44 my $dst = $opt->{output} // '-';
45 $dst = '/dev/stdout' if $dst eq '-';
47 my $fmt = $opt->{'format'};
48 $fmt = lc($fmt) if defined $fmt;
49 if ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
52 return $lei->fail(<<"") if $fmt ne $ofmt;
53 --format=$fmt and --output=$ofmt conflict
56 $fmt //= 'json' if $dst eq '/dev/stdout';
59 if (index($dst, '://') < 0) { # not a URL, so assume path
60 $dst = File::Spec->canonpath($dst);
63 my $self = bless { fmt => $fmt, dst => $dst }, $class;
66 if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
67 $json = $self->{json} = ref(PublicInbox::Config->json);
69 my ($isatty, $seekable);
70 if ($dst eq '/dev/stdout') {
71 $isatty = -t $lei->{1};
72 $lei->start_pager if $isatty;
73 $opt->{pretty} //= $isatty;
74 if (!$isatty && -f _) {
75 my $fl = fcntl($lei->{1}, F_GETFL, 0) //
76 return $lei->fail("fcntl(stdout): $!");
77 ovv_out_lk_init($self) unless ($fl & O_APPEND);
79 ovv_out_lk_init($self);
83 # default to the cheapest sort since MUA usually resorts
84 $lei->{opt}->{'sort'} //= 'docid' if $dst ne '/dev/stdout';
85 $lei->{l2m} = PublicInbox::LeiToMail->new($lei);
87 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
91 # called once by parent
93 my ($self, $lei) = @_;
94 if ($self->{fmt} eq 'json') {
95 print { $lei->{1} } '[';
96 } # TODO HTML/Atom/...
99 # called once by parent (via PublicInbox::EOFpipe)
101 my ($self, $lei) = @_;
102 if ($self->{fmt} eq 'json') {
103 # JSON doesn't allow trailing commas, and preventing
104 # trailing commas is a PITA when parallelizing outputs
105 print { $lei->{1} } "null]\n";
106 } elsif ($self->{fmt} eq 'concatjson') {
107 print { $lei->{1} } "\n";
111 sub ovv_atfork_child {
116 # prepares an smsg for JSON
118 my ($smsg, $mitem) = @_;
120 delete @$smsg{qw(lines bytes num tid)};
121 $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
122 $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
123 $smsg->{relevance} = get_pct($mitem) if $mitem;
125 if (my $r = delete $smsg->{references}) {
127 map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
129 if (my $m = delete($smsg->{mid})) {
130 $smsg->{'m'} = "<$m>";
132 for my $f (qw(from to cc)) {
133 my $v = delete $smsg->{$f} or next;
134 $smsg->{substr($f, 0, 1)} = pairs($v);
136 $smsg->{'s'} = delete $smsg->{subject};
137 # can we be bothered to parse From/To/Cc into arrays?
138 scalar { %$smsg }; # unbless
141 sub ovv_atexit_child {
142 my ($self, $lei) = @_;
143 if (my $git = delete $self->{git}) {
144 $git->async_wait_all;
146 if (my $bref = delete $lei->{ovv_buf}) {
147 my $out = $lei->{1} or return;
148 my $lk = $self->lock_for_scope;
153 # JSON module ->pretty output wastes too much vertical white space,
154 # this (IMHO) provides better use of screen real-estate while not
155 # being excessively compact:
157 my ($json, $k, $v) = @_;
158 if (ref $v eq 'ARRAY') {
160 my $sep = ",\n" . (' ' x (length($k) + 7));
161 if (ref($v->[0])) { # f/t/c
162 $v = '[' . join($sep, map {
163 my $pair = $json->encode($_);
164 $pair =~ s/(null|"),"/$1, "/g;
167 } else { # references
168 $v = '[' . join($sep, map {
169 substr($json->encode([$_]), 1, -1);
179 sub ovv_each_smsg_cb { # runs in wq worker usually
180 my ($self, $lei, $ibxish) = @_;
181 $lei->{ovv_buf} = \(my $buf = '');
182 delete(@$self{qw(lock_path tmp_lk_id)}) unless $lei->{-parallel};
184 $lei->{1}->autoflush(1);
185 if (my $pkg = $self->{json}) {
187 $json->utf8->canonical;
188 $json->ascii(1) if $lei->{opt}->{ascii};
190 if (my $l2m = $lei->{l2m}) {
191 my $wcb = $l2m->write_cb($lei);
192 my $git = $ibxish->git; # (LeiXSearch|Inbox|ExtSearch)->git
193 $self->{git} = $git; # for ovv_atexit_child
194 my $g2m = $l2m->can('git_to_mail');
196 my ($smsg, $mitem) = @_;
197 my $kw = []; # TODO get from mitem
198 $git->cat_async($smsg->{blob}, $g2m, [ $wcb, $kw ]);
200 } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
201 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
202 sub { # DIY prettiness :P
203 my ($smsg, $mitem) = @_;
204 $smsg = _unbless_smsg($smsg, $mitem);
206 $buf .= join(",\n", map {
209 _json_pretty($json, $_, $v);
211 $v = $json->encode([$v]);
212 qq{ "$_": }.substr($v, 1, -1);
216 if (length($buf) > 65536) {
217 my $lk = $self->lock_for_scope;
218 print { $lei->{1} } $buf;
223 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
225 my ($smsg, $mitem) = @_;
226 delete @$smsg{qw(tid num)};
227 $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
228 if (length($buf) > 65536) {
229 my $lk = $self->lock_for_scope;
230 print { $lei->{1} } $buf;
234 } elsif ($self->{fmt} eq 'oid') {
236 my ($smsg, $mitem) = @_;
242 *DESTROY = \&ovv_out_lk_cancel;