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_io_do handoff
27 sub ovv_out_lk_init ($) {
29 my $tmp = File::Temp->new("lei-ovv.dst.$$.lock-XXXX",
30 TMPDIR => 1, UNLINK => 0);
31 $self->{"lk_id.$self.$$"} = $self->{lock_path} = $tmp->filename;
34 sub ovv_out_lk_cancel ($) {
36 my $lock_path = delete $self->{"lk_id.$self.$$"} or return;
42 if ($dst =~ m!\A([:/]+://)!) {
43 $lei->fail("$1 support not implemented, yet\n");
44 } elsif (!-e $dst || -d _) {
45 'maildir'; # the default TODO: MH?
46 } elsif (-f _ || -p _) {
47 $lei->fail("unable to determine mbox family of $dst\n");
49 $lei->fail("unable to determine format of $dst\n");
54 my ($class, $lei, $ofmt_key) = @_;
55 my $opt = $lei->{opt};
56 my $dst = $opt->{output} // '-';
57 $dst = '/dev/stdout' if $dst eq '-';
58 $ofmt_key //= 'format';
60 my $fmt = $opt->{$ofmt_key};
61 $fmt = lc($fmt) if defined $fmt;
62 if ($dst =~ m!\A([a-z0-9\+]+)://!is) {
63 defined($fmt) and return $lei->fail(<<"");
64 --$ofmt_key=$fmt invalid with URL $dst
67 } elsif ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
70 return $lei->fail(<<"") if $fmt ne $ofmt;
71 --$ofmt_key=$fmt and --output=$ofmt conflict
75 my $devfd = $lei->path_to_fd($dst) // return;
76 $fmt //= $devfd >= 0 ? 'json' : (detect_fmt($lei, $dst) or return);
78 if (index($dst, '://') < 0) { # not a URL, so assume path
79 $dst = $lei->canonpath_harder($dst);
82 my $self = bless { fmt => $fmt, dst => $dst }, $class;
85 if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
86 $json = $self->{json} = ref(PublicInbox::Config->json);
89 my $isatty = $lei->{need_pager} = -t $lei->{$devfd};
90 $opt->{pretty} //= $isatty;
91 if (!$isatty && -f _) {
92 my $fl = fcntl($lei->{$devfd}, F_GETFL, 0) //
93 return $lei->fail("fcntl(stdout): $!");
94 ovv_out_lk_init($self) unless ($fl & O_APPEND);
96 ovv_out_lk_init($self);
98 } elsif (!$opt->{quiet}) {
99 $lei->{-progress} = 1;
102 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
104 $lei->{l2m} = eval { PublicInbox::LeiToMail->new($lei) };
105 return $lei->fail($@) if $@;
106 if ($opt->{mua} && $lei->{l2m}->lock_free) {
107 $lei->{early_mua} = 1;
108 $opt->{alert} //= [ ':WINCH,:bell' ] if -t $lei->{1};
111 return $lei->fail('--shared is only for v2 inbox output') if
112 $self->{fmt} ne 'v2' && $lei->{opt}->{shared};
116 # called once by parent
118 my ($self, $lei) = @_;
119 if ($self->{fmt} eq 'json') {
121 } # TODO HTML/Atom/...
124 # called once by parent (via PublicInbox::PktOp '' => query_done)
126 my ($self, $lei) = @_;
127 if ($self->{fmt} eq 'json') {
128 # JSON doesn't allow trailing commas, and preventing
129 # trailing commas is a PITA when parallelizing outputs
130 $lei->out("null]\n");
131 } elsif ($self->{fmt} eq 'concatjson') {
136 # prepares an smsg for JSON
138 my ($smsg, $mitem) = @_;
140 # TODO: make configurable
141 # num/tid are nonsensical with multi-inbox search,
142 # lines/bytes are not generally useful
143 delete @$smsg{qw(num tid lines bytes)};
144 $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
145 $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
146 $smsg->{pct} = get_pct($mitem) if $mitem;
147 if (my $r = delete $smsg->{references}) {
148 $smsg->{refs} = [ map { $_ } ($r =~ m/$MID_EXTRACT/go) ];
150 if (my $m = delete($smsg->{mid})) {
153 for my $f (qw(from to cc)) {
154 my $v = delete $smsg->{$f} or next;
155 $smsg->{substr($f, 0, 1)} = pairs($v);
157 $smsg->{'s'} = delete $smsg->{subject};
158 my $kw = delete($smsg->{kw});
159 scalar { %$smsg, ($kw && scalar(@$kw) ? (kw => $kw) : ()) }; # unbless
162 sub ovv_atexit_child {
163 my ($self, $lei) = @_;
164 if (my $bref = delete $lei->{ovv_buf}) {
165 my $lk = $self->lock_for_scope;
170 # JSON module ->pretty output wastes too much vertical white space,
171 # this (IMHO) provides better use of screen real-estate while not
172 # being excessively compact:
174 my ($json, $k, $v) = @_;
175 if (ref $v eq 'ARRAY') {
177 my $sep = ",\n" . (' ' x (length($k) + 7));
178 if (ref($v->[0])) { # f/t/c
179 $v = '[' . join($sep, map {
180 my $pair = $json->encode($_);
181 $pair =~ s/(null|"),"/$1, "/g;
184 } elsif ($k eq 'kw') { # keywords are short, one-line
185 $v = $json->encode($v);
187 } else { # refs, labels, ...
188 $v = '[' . join($sep, map {
189 substr($json->encode([$_]), 1, -1);
199 sub ovv_each_smsg_cb { # runs in wq worker usually
200 my ($self, $lei) = @_;
202 if (my $pkg = $self->{json}) {
204 $json->utf8->canonical;
205 $json->ascii(1) if $lei->{opt}->{ascii};
207 my $l2m = $lei->{l2m};
209 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
210 $dedupe->prepare_dedupe;
212 $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
215 my ($smsg, $mitem, $eml) = @_;
216 $smsg->{pct} = get_pct($mitem) if $mitem;
217 $l2m->wq_io_do('write_mail', [], $smsg, $eml);
219 } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
220 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
221 my $lse = $lei->{lse};
222 sub { # DIY prettiness :P
223 my ($smsg, $mitem) = @_;
224 return if $dedupe->is_smsg_dup($smsg);
225 $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
226 $smsg = _unbless_smsg($smsg, $mitem);
228 $buf .= join(",\n", map {
231 _json_pretty($json, $_, $v);
233 $v = $json->encode([$v]);
234 qq{ "$_": }.substr($v, 1, -1);
238 return if length($buf) < 65536;
239 my $lk = $self->lock_for_scope;
244 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
245 my $lse = $lei->{lse};
247 my ($smsg, $mitem) = @_;
248 return if $dedupe->is_smsg_dup($smsg);
249 $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
250 $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
251 return if length($buf) < 65536;
252 my $lk = $self->lock_for_scope;
257 die "TODO: unhandled case $self->{fmt}"
262 *DESTROY = \&ovv_out_lk_cancel;