]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiOverview.pm
lei: add some labels support
[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-XXXXXX",
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 ($lei, $dst) = @_;
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");
48         } else {
49                 $lei->fail("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 return $lei->fail(<<"");
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                 return $lei->fail(<<"") if $fmt ne $ofmt;
71 --$ofmt_key=$fmt and --output=$ofmt conflict
72
73         }
74         $fmt //= 'json' if $dst eq '/dev/stdout';
75         $fmt //= detect_fmt($lei, $dst) or return;
76
77         if (index($dst, '://') < 0) { # not a URL, so assume path
78                  $dst = File::Spec->canonpath($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 ($dst eq '/dev/stdout') {
88                 my $isatty = $lei->{need_pager} = -t $lei->{1};
89                 $opt->{pretty} //= $isatty;
90                 if (!$isatty && -f _) {
91                         my $fl = fcntl($lei->{1}, F_GETFL, 0) //
92                                 return $lei->fail("fcntl(stdout): $!");
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                 # default to the cheapest sort since MUA usually resorts
104                 $opt->{'sort'} //= 'docid' if $dst ne '/dev/stdout';
105                 $lei->{l2m} = eval { PublicInbox::LeiToMail->new($lei) };
106                 return $lei->fail($@) if $@;
107                 if ($opt->{mua} && $lei->{l2m}->lock_free) {
108                         $lei->{early_mua} = 1;
109                         $opt->{alert} //= [ ':WINCH,:bell' ] if -t $lei->{1};
110                 }
111         }
112         $self;
113 }
114
115 # called once by parent
116 sub ovv_begin {
117         my ($self, $lei) = @_;
118         if ($self->{fmt} eq 'json') {
119                 $lei->out('[');
120         } # TODO HTML/Atom/...
121 }
122
123 # called once by parent (via PublicInbox::EOFpipe)
124 sub ovv_end {
125         my ($self, $lei) = @_;
126         if ($self->{fmt} eq 'json') {
127                 # JSON doesn't allow trailing commas, and preventing
128                 # trailing commas is a PITA when parallelizing outputs
129                 $lei->out("null]\n");
130         } elsif ($self->{fmt} eq 'concatjson') {
131                 $lei->out("\n");
132         }
133 }
134
135 # prepares an smsg for JSON
136 sub _unbless_smsg {
137         my ($smsg, $mitem) = @_;
138
139         # TODO: make configurable
140         # num/tid are nonsensical with multi-inbox search,
141         # lines/bytes are not generally useful
142         delete @$smsg{qw(num tid lines bytes)};
143         $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
144         $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
145         $smsg->{pct} = get_pct($mitem) if $mitem;
146         if (my $r = delete $smsg->{references}) {
147                 $smsg->{refs} = [ map { $_ } ($r =~ m/$MID_EXTRACT/go) ];
148         }
149         if (my $m = delete($smsg->{mid})) {
150                 $smsg->{'m'} = $m;
151         }
152         for my $f (qw(from to cc)) {
153                 my $v = delete $smsg->{$f} or next;
154                 $smsg->{substr($f, 0, 1)} = pairs($v);
155         }
156         $smsg->{'s'} = delete $smsg->{subject};
157         my $kw = delete($smsg->{kw});
158         scalar { %$smsg, ($kw && scalar(@$kw) ? (kw => $kw) : ()) }; # unbless
159 }
160
161 sub ovv_atexit_child {
162         my ($self, $lei) = @_;
163         if (my $bref = delete $lei->{ovv_buf}) {
164                 my $lk = $self->lock_for_scope;
165                 $lei->out($$bref);
166         }
167 }
168
169 # JSON module ->pretty output wastes too much vertical white space,
170 # this (IMHO) provides better use of screen real-estate while not
171 # being excessively compact:
172 sub _json_pretty {
173         my ($json, $k, $v) = @_;
174         if (ref $v eq 'ARRAY') {
175                 if (@$v) {
176                         my $sep = ",\n" . (' ' x (length($k) + 7));
177                         if (ref($v->[0])) { # f/t/c
178                                 $v = '[' . join($sep, map {
179                                         my $pair = $json->encode($_);
180                                         $pair =~ s/(null|"),"/$1, "/g;
181                                         $pair;
182                                 } @$v) . ']';
183                         } elsif ($k eq 'kw') { # keywords are short, one-line
184                                 $v = $json->encode($v);
185                                 $v =~ s/","/", "/g;
186                         } else { # refs, labels, ...
187                                 $v = '[' . join($sep, map {
188                                         substr($json->encode([$_]), 1, -1);
189                                 } @$v) . ']';
190                         }
191                 } else {
192                         $v = '[]';
193                 }
194         }
195         qq{  "$k": }.$v;
196 }
197
198 sub ovv_each_smsg_cb { # runs in wq worker usually
199         my ($self, $lei, $ibxish) = @_;
200         my ($json, $dedupe);
201         if (my $pkg = $self->{json}) {
202                 $json = $pkg->new;
203                 $json->utf8->canonical;
204                 $json->ascii(1) if $lei->{opt}->{ascii};
205         }
206         my $l2m = $lei->{l2m};
207         if (!$l2m) {
208                 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
209                 $dedupe->prepare_dedupe;
210         }
211         $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
212         if ($l2m && !$ibxish) { # remote https?:// mboxrd
213                 my $wcb = $l2m->write_cb($lei);
214                 sub {
215                         my ($smsg, undef, $eml) = @_; # no mitem in $_[1]
216                         $wcb->(undef, $smsg, $eml);
217                 };
218         } elsif ($l2m && $l2m->{-wq_s1}) {
219                 sub {
220                         my ($smsg, $mitem) = @_;
221                         $smsg->{pct} = get_pct($mitem) if $mitem;
222                         $l2m->wq_io_do('write_mail', [], $smsg);
223                 }
224         } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
225                 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
226                 my $lse = $lei->{sto}->search;
227                 sub { # DIY prettiness :P
228                         my ($smsg, $mitem) = @_;
229                         return if $dedupe->is_smsg_dup($smsg);
230                         $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
231                         $smsg = _unbless_smsg($smsg, $mitem);
232                         $buf .= "{\n";
233                         $buf .= join(",\n", map {
234                                 my $v = $smsg->{$_};
235                                 if (ref($v)) {
236                                         _json_pretty($json, $_, $v);
237                                 } else {
238                                         $v = $json->encode([$v]);
239                                         qq{  "$_": }.substr($v, 1, -1);
240                                 }
241                         } sort keys %$smsg);
242                         $buf .= $EOR;
243                         return if length($buf) < 65536;
244                         my $lk = $self->lock_for_scope;
245                         $lei->out($buf);
246                         $buf = '';
247                 }
248         } elsif ($json) {
249                 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
250                 my $lse = $lei->{sto}->search;
251                 sub {
252                         my ($smsg, $mitem) = @_;
253                         return if $dedupe->is_smsg_dup($smsg);
254                         $lse->xsmsg_vmd($smsg, $smsg->{L} ? undef : 1);
255                         $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
256                         return if length($buf) < 65536;
257                         my $lk = $self->lock_for_scope;
258                         $lei->out($buf);
259                         $buf = '';
260                 }
261         } else {
262                 die "TODO: unhandled case $self->{fmt}"
263         }
264 }
265
266 no warnings 'once';
267 *DESTROY = \&ovv_out_lk_cancel;
268
269 1;