]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiOverview.pm
lei inspect: show ISO8601 {rt} and {dt}, too
[public-inbox.git] / lib / PublicInbox / LeiOverview.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # per-mitem/smsg iterators for search results
5 # "ovv" => "Overview viewer"
6 package PublicInbox::LeiOverview;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use POSIX qw(strftime);
11 use Fcntl qw(F_GETFL O_APPEND);
12 use File::Spec;
13 use File::Temp ();
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;
20
21 # cf. https://en.wikipedia.org/wiki/JSON_streaming
22 my $JSONL = 'ldjson|ndjson|jsonl'; # 3 names for the same thing
23
24 sub iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
25
26 # we open this in the parent process before ->wq_io_do handoff
27 sub ovv_out_lk_init ($) {
28         my ($self) = @_;
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;
32 }
33
34 sub ovv_out_lk_cancel ($) {
35         my ($self) = @_;
36         my $lock_path = delete $self->{"lk_id.$self.$$"} or return;
37         unlink($lock_path);
38 }
39
40 sub detect_fmt ($) {
41         my ($dst) = @_;
42         if ($dst =~ m!\A([:/]+://)!) {
43                 die "$1 support not implemented, yet\n";
44         } elsif (!-e $dst || -d _) {
45                 'maildir'; # the default TODO: MH?
46         } elsif (-f _ || -p _) {
47                 die "unable to determine mbox family of $dst\n";
48         } else {
49                 die "unable to determine format of $dst\n";
50         }
51 }
52
53 sub new {
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';
59
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 die <<"";
64 --$ofmt_key=$fmt invalid with URL $dst
65
66                 $fmt = lc $1;
67         } elsif ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
68                 my $ofmt = lc $1;
69                 $fmt //= $ofmt;
70                 die <<"" if $fmt ne $ofmt;
71 --$ofmt_key=$fmt and --output=$ofmt conflict
72
73         }
74         my $devfd = $lei->path_to_fd($dst) // return;
75         $fmt //= $devfd >= 0 ? 'json' : detect_fmt($dst);
76
77         if (index($dst, '://') < 0) { # not a URL, so assume path
78                  $dst = $lei->canonpath_harder($dst);
79         } # else URL
80
81         my $self = bless { fmt => $fmt, dst => $dst }, $class;
82         $lei->{ovv} = $self;
83         my $json;
84         if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
85                 $json = $self->{json} = ref(PublicInbox::Config->json);
86         }
87         if ($devfd >= 0) {
88                 my $isatty = $lei->{need_pager} = -t $lei->{$devfd};
89                 $opt->{pretty} //= $isatty;
90                 if (!$isatty && -f _) {
91                         my $fl = fcntl($lei->{$devfd}, F_GETFL, 0) //
92                                         die("fcntl(/dev/fd/$devfd): $!\n");
93                         ovv_out_lk_init($self) unless ($fl & O_APPEND);
94                 } else {
95                         ovv_out_lk_init($self);
96                 }
97         } elsif (!$opt->{quiet}) {
98                 $lei->{-progress} = 1;
99         }
100         if ($json) {
101                 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
102         } else {
103                 $lei->{l2m} = PublicInbox::LeiToMail->new($lei);
104                 if ($opt->{mua} && $lei->{l2m}->lock_free) {
105                         $lei->{early_mua} = 1;
106                         $opt->{alert} //= [ ':WINCH,:bell' ] if -t $lei->{1};
107                 }
108         }
109         die("--shared is only for v2 inbox output\n") if
110                 $self->{fmt} ne 'v2' && $lei->{opt}->{shared};
111         $self;
112 }
113
114 # called once by parent
115 sub ovv_begin {
116         my ($self, $lei) = @_;
117         if ($self->{fmt} eq 'json') {
118                 $lei->out('[');
119         } # TODO HTML/Atom/...
120 }
121
122 # called once by parent (via PublicInbox::PktOp  '' => query_done)
123 sub ovv_end {
124         my ($self, $lei) = @_;
125         if ($self->{fmt} eq 'json') {
126                 # JSON doesn't allow trailing commas, and preventing
127                 # trailing commas is a PITA when parallelizing outputs
128                 $lei->out("null]\n");
129         } elsif ($self->{fmt} eq 'concatjson') {
130                 $lei->out("\n");
131         }
132 }
133
134 # prepares an smsg for JSON
135 sub _unbless_smsg {
136         my ($smsg, $mitem) = @_;
137
138         # TODO: make configurable
139         # num/tid are nonsensical with multi-inbox search,
140         # lines/bytes are not generally useful
141         delete @$smsg{qw(num tid lines bytes)};
142         $smsg->{rt} = iso8601(delete $smsg->{ts}); # JMAP receivedAt
143         $smsg->{dt} = iso8601(delete $smsg->{ds}); # JMAP UTCDate
144         $smsg->{pct} = get_pct($mitem) if $mitem;
145         if (my $r = delete $smsg->{references}) {
146                 $smsg->{refs} = [ map { $_ } ($r =~ m/$MID_EXTRACT/go) ];
147         }
148         if (my $m = delete($smsg->{mid})) {
149                 $smsg->{'m'} = $m;
150         }
151         for my $f (qw(from to cc)) {
152                 my $v = delete $smsg->{$f} or next;
153                 $smsg->{substr($f, 0, 1)} = pairs($v);
154         }
155         $smsg->{'s'} = delete $smsg->{subject};
156         my $kw = delete($smsg->{kw});
157         scalar { %$smsg, ($kw && scalar(@$kw) ? (kw => $kw) : ()) }; # unbless
158 }
159
160 sub ovv_atexit_child {
161         my ($self, $lei) = @_;
162         if (my $bref = delete $lei->{ovv_buf}) {
163                 my $lk = $self->lock_for_scope;
164                 $lei->out($$bref);
165         }
166 }
167
168 # JSON module ->pretty output wastes too much vertical white space,
169 # this (IMHO) provides better use of screen real-estate while not
170 # being excessively compact:
171 sub _json_pretty {
172         my ($json, $k, $v) = @_;
173         if (ref $v eq 'ARRAY') {
174                 if (@$v) {
175                         my $sep = ",\n" . (' ' x (length($k) + 7));
176                         if (ref($v->[0])) { # f/t/c
177                                 $v = '[' . join($sep, map {
178                                         my $pair = $json->encode($_);
179                                         $pair =~ s/(null|"),"/$1, "/g;
180                                         $pair;
181                                 } @$v) . ']';
182                         } elsif ($k eq 'kw') { # keywords are short, one-line
183                                 $v = $json->encode($v);
184                                 $v =~ s/","/", "/g;
185                         } else { # refs, labels, ...
186                                 $v = '[' . join($sep, map {
187                                         substr($json->encode([$_]), 1, -1);
188                                 } @$v) . ']';
189                         }
190                 } else {
191                         $v = '[]';
192                 }
193         }
194         qq{  "$k": }.$v;
195 }
196
197 sub ovv_each_smsg_cb { # runs in wq worker usually
198         my ($self, $lei) = @_;
199         my ($json, $dedupe);
200         if (my $pkg = $self->{json}) {
201                 $json = $pkg->new;
202                 $json->utf8->canonical;
203                 $json->ascii(1) if $lei->{opt}->{ascii};
204         }
205         my $l2m = $lei->{l2m};
206         if (!$l2m) {
207                 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
208                 $dedupe->prepare_dedupe;
209         }
210         $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
211         if ($l2m) {
212                 sub {
213                         my ($smsg, $mitem, $eml) = @_;
214                         $smsg->{pct} = get_pct($mitem) if $mitem;
215                         $l2m->wq_io_do('write_mail', [], $smsg, $eml);
216                 }
217         } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
218                 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
219                 my $lse = $lei->{lse};
220                 sub { # DIY prettiness :P
221                         my ($smsg, $mitem) = @_;
222                         return if $dedupe->is_smsg_dup($smsg);
223                         $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
224                         $smsg = _unbless_smsg($smsg, $mitem);
225                         $buf .= "{\n";
226                         $buf .= join(",\n", map {
227                                 my $v = $smsg->{$_};
228                                 if (ref($v)) {
229                                         _json_pretty($json, $_, $v);
230                                 } else {
231                                         $v = $json->encode([$v]);
232                                         qq{  "$_": }.substr($v, 1, -1);
233                                 }
234                         } sort keys %$smsg);
235                         $buf .= $EOR;
236                         return if length($buf) < 65536;
237                         my $lk = $self->lock_for_scope;
238                         $lei->out($buf);
239                         $buf = '';
240                 }
241         } elsif ($json) {
242                 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
243                 my $lse = $lei->{lse};
244                 sub {
245                         my ($smsg, $mitem) = @_;
246                         return if $dedupe->is_smsg_dup($smsg);
247                         $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
248                         $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
249                         return if length($buf) < 65536;
250                         my $lk = $self->lock_for_scope;
251                         $lei->out($buf);
252                         $buf = '';
253                 }
254         } else {
255                 die "TODO: unhandled case $self->{fmt}"
256         }
257 }
258
259 no warnings 'once';
260 *DESTROY = \&ovv_out_lk_cancel;
261
262 1;