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