]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiOverview.pm
lei q: prefix --alert ops with ':' instead of '-'
[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) = @_;
55         my $opt = $lei->{opt};
56         my $dst = $opt->{output} // '-';
57         $dst = '/dev/stdout' if $dst eq '-';
58
59         my $fmt = $opt->{'format'};
60         $fmt = lc($fmt) if defined $fmt;
61         if ($dst =~ s/\A([a-z0-9]+)://is) { # e.g. Maildir:/home/user/Mail/
62                 my $ofmt = lc $1;
63                 $fmt //= $ofmt;
64                 return $lei->fail(<<"") if $fmt ne $ofmt;
65 --format=$fmt and --output=$ofmt conflict
66
67         }
68         $fmt //= 'json' if $dst eq '/dev/stdout';
69         $fmt //= detect_fmt($lei, $dst) or return;
70
71         if (index($dst, '://') < 0) { # not a URL, so assume path
72                  $dst = File::Spec->canonpath($dst);
73         } # else URL
74
75         my $self = bless { fmt => $fmt, dst => $dst }, $class;
76         $lei->{ovv} = $self;
77         my $json;
78         if ($fmt =~ /\A($JSONL|(?:concat)?json)\z/) {
79                 $json = $self->{json} = ref(PublicInbox::Config->json);
80         }
81         if ($dst eq '/dev/stdout') {
82                 my $isatty = $lei->{need_pager} = -t $lei->{1};
83                 $opt->{pretty} //= $isatty;
84                 if (!$isatty && -f _) {
85                         my $fl = fcntl($lei->{1}, F_GETFL, 0) //
86                                 return $lei->fail("fcntl(stdout): $!");
87                         ovv_out_lk_init($self) unless ($fl & O_APPEND);
88                 } else {
89                         ovv_out_lk_init($self);
90                 }
91         } elsif (!$opt->{quiet}) {
92                 $lei->{-progress} = 1;
93         }
94         if ($json) {
95                 $lei->{dedupe} //= PublicInbox::LeiDedupe->new($lei);
96         } else {
97                 # default to the cheapest sort since MUA usually resorts
98                 $opt->{'sort'} //= 'docid' if $dst ne '/dev/stdout';
99                 $lei->{l2m} = eval { PublicInbox::LeiToMail->new($lei) };
100                 return $lei->fail($@) if $@;
101                 if ($opt->{mua} && $lei->{l2m}->lock_free) {
102                         $lei->{early_mua} = 1;
103                         $opt->{alert} //= [ ':WINCH,:bell' ] if -t $lei->{1};
104                 }
105         }
106         $self;
107 }
108
109 # called once by parent
110 sub ovv_begin {
111         my ($self, $lei) = @_;
112         if ($self->{fmt} eq 'json') {
113                 $lei->out('[');
114         } # TODO HTML/Atom/...
115 }
116
117 # called once by parent (via PublicInbox::EOFpipe)
118 sub ovv_end {
119         my ($self, $lei) = @_;
120         if ($self->{fmt} eq 'json') {
121                 # JSON doesn't allow trailing commas, and preventing
122                 # trailing commas is a PITA when parallelizing outputs
123                 $lei->out("null]\n");
124         } elsif ($self->{fmt} eq 'concatjson') {
125                 $lei->out("\n");
126         }
127 }
128
129 # prepares an smsg for JSON
130 sub _unbless_smsg {
131         my ($smsg, $mitem) = @_;
132
133         delete @$smsg{qw(lines bytes num tid)};
134         $smsg->{rt} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
135         $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
136         $smsg->{pct} = get_pct($mitem) if $mitem;
137         if (my $r = delete $smsg->{references}) {
138                 $smsg->{refs} = [ map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
139         }
140         if (my $m = delete($smsg->{mid})) {
141                 $smsg->{'m'} = "<$m>";
142         }
143         for my $f (qw(from to cc)) {
144                 my $v = delete $smsg->{$f} or next;
145                 $smsg->{substr($f, 0, 1)} = pairs($v);
146         }
147         $smsg->{'s'} = delete $smsg->{subject};
148         # can we be bothered to parse From/To/Cc into arrays?
149         scalar { %$smsg }; # unbless
150 }
151
152 sub ovv_atexit_child {
153         my ($self, $lei) = @_;
154         if (my $bref = delete $lei->{ovv_buf}) {
155                 my $lk = $self->lock_for_scope;
156                 $lei->out($$bref);
157         }
158 }
159
160 # JSON module ->pretty output wastes too much vertical white space,
161 # this (IMHO) provides better use of screen real-estate while not
162 # being excessively compact:
163 sub _json_pretty {
164         my ($json, $k, $v) = @_;
165         if (ref $v eq 'ARRAY') {
166                 if (@$v) {
167                         my $sep = ",\n" . (' ' x (length($k) + 7));
168                         if (ref($v->[0])) { # f/t/c
169                                 $v = '[' . join($sep, map {
170                                         my $pair = $json->encode($_);
171                                         $pair =~ s/(null|"),"/$1, "/g;
172                                         $pair;
173                                 } @$v) . ']';
174                         } else { # references
175                                 $v = '[' . join($sep, map {
176                                         substr($json->encode([$_]), 1, -1);
177                                 } @$v) . ']';
178                         }
179                 } else {
180                         $v = '[]';
181                 }
182         }
183         qq{  "$k": }.$v;
184 }
185
186 sub ovv_each_smsg_cb { # runs in wq worker usually
187         my ($self, $lei, $ibxish) = @_;
188         my ($json, $dedupe);
189         if (my $pkg = $self->{json}) {
190                 $json = $pkg->new;
191                 $json->utf8->canonical;
192                 $json->ascii(1) if $lei->{opt}->{ascii};
193         }
194         my $l2m = $lei->{l2m};
195         if (!$l2m) {
196                 $dedupe = $lei->{dedupe} // die 'BUG: {dedupe} missing';
197                 $dedupe->prepare_dedupe;
198         }
199         $lei->{ovv_buf} = \(my $buf = '') if !$l2m;
200         if ($l2m && !$ibxish) { # remote https?:// mboxrd
201                 my $g2m = $l2m->can('git_to_mail');
202                 my $wcb = $l2m->write_cb($lei);
203                 sub {
204                         my ($smsg, undef, $eml) = @_; # no mitem in $_[1]
205                         $wcb->(undef, $smsg, $eml);
206                 };
207         } elsif ($l2m && $l2m->{-wq_s1}) {
208                 my $git_dir = $ibxish->git->{git_dir};
209                 sub {
210                         my ($smsg, $mitem) = @_;
211                         $smsg->{pct} = get_pct($mitem) if $mitem;
212                         $l2m->wq_io_do('write_mail', [], $git_dir, $smsg);
213                 }
214         } elsif ($self->{fmt} =~ /\A(concat)?json\z/ && $lei->{opt}->{pretty}) {
215                 my $EOR = ($1//'') eq 'concat' ? "\n}" : "\n},";
216                 sub { # DIY prettiness :P
217                         my ($smsg, $mitem) = @_;
218                         return if $dedupe->is_smsg_dup($smsg);
219                         $smsg = _unbless_smsg($smsg, $mitem);
220                         $buf .= "{\n";
221                         $buf .= join(",\n", map {
222                                 my $v = $smsg->{$_};
223                                 if (ref($v)) {
224                                         _json_pretty($json, $_, $v);
225                                 } else {
226                                         $v = $json->encode([$v]);
227                                         qq{  "$_": }.substr($v, 1, -1);
228                                 }
229                         } sort keys %$smsg);
230                         $buf .= $EOR;
231                         return if length($buf) < 65536;
232                         my $lk = $self->lock_for_scope;
233                         $lei->out($buf);
234                         $buf = '';
235                 }
236         } elsif ($json) {
237                 my $ORS = $self->{fmt} eq 'json' ? ",\n" : "\n"; # JSONL
238                 sub {
239                         my ($smsg, $mitem) = @_;
240                         return if $dedupe->is_smsg_dup($smsg);
241                         $buf .= $json->encode(_unbless_smsg(@_)) . $ORS;
242                         return if length($buf) < 65536;
243                         my $lk = $self->lock_for_scope;
244                         $lei->out($buf);
245                         $buf = '';
246                 }
247         } else {
248                 die "TODO: unhandled case $self->{fmt}"
249         }
250 }
251
252 no warnings 'once';
253 *DESTROY = \&ovv_out_lk_cancel;
254
255 1;