]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiQuery.pm
lei q: deduplicate smsg
[public-inbox.git] / lib / PublicInbox / LeiQuery.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 # handles lei <q|ls-query|rm-query|mv-query> commands
5 package PublicInbox::LeiQuery;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::MID qw($MID_EXTRACT);
9 use POSIX qw(strftime);
10 use PublicInbox::Address qw(pairs);
11 use PublicInbox::Search qw(get_pct);
12
13 sub _iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
14
15 # prepares an smsg for JSON
16 sub _smsg_unbless ($) {
17         my ($smsg) = @_;
18
19         delete @$smsg{qw(lines bytes)};
20         $smsg->{rcvd} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
21         $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
22
23         if (my $r = delete $smsg->{references}) {
24                 $smsg->{references} = [
25                                 map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
26         }
27         if (my $m = delete($smsg->{mid})) {
28                 $smsg->{'m'} = "<$m>";
29         }
30         # XXX breaking to/cc, into structured arrays or tables which
31         # distinguish "$phrase <$address>" causes pretty printing JSON
32         # to take up too much vertical space.  I can't get either
33         # Cpanel::JSON::XS or JSON::XS or jq(1) only indent when
34         # wrapping is necessary, rather than blindly indenting and
35         # adding vertical space everywhere.
36         for my $f (qw(from to cc)) {
37                 my $v = delete $smsg->{$f} or next;
38                 $smsg->{substr($f, 0, 1)} = $v;
39         }
40         $smsg->{'s'} = delete $smsg->{subject};
41         # can we be bothered to parse From/To/Cc into arrays?
42         scalar { %$smsg }; # unbless
43 }
44
45 sub _vivify_external { # _externals_each callback
46         my ($src, $dir) = @_;
47         if (-f "$dir/ei.lock") {
48                 require PublicInbox::ExtSearch;
49                 push @$src, PublicInbox::ExtSearch->new($dir);
50         } elsif (-f "$dir/inbox.lock" || -d "$dir/public-inbox") { # v2, v1
51                 require PublicInbox::Inbox;
52                 push @$src, bless { inboxdir => $dir }, 'PublicInbox::Inbox';
53         } else {
54                 warn "W: ignoring $dir, unable to determine type\n";
55         }
56 }
57
58 # the main "lei q SEARCH_TERMS" method
59 sub lei_q {
60         my ($self, @argv) = @_;
61         my $sto = $self->_lei_store(1);
62         my $cfg = $self->_lei_cfg(1);
63         my $opt = $self->{opt};
64         my $qstr = join(' ', map {;
65                 # Consider spaces in argv to be for phrase search in Xapian.
66                 # In other words, the users should need only care about
67                 # normal shell quotes and not have to learn Xapian quoting.
68                 /\s/ ? (s/\A(\w+:)// ? qq{$1"$_"} : qq{"$_"}) : $_
69         } @argv);
70         $opt->{limit} //= 10000;
71         my $lxs;
72         require PublicInbox::LeiDedupe;
73         my $dd = PublicInbox::LeiDedupe->new($self);
74
75         # --local is enabled by default
76         my @src = $opt->{'local'} ? ($sto->search) : ();
77
78         # --external is enabled by default, but allow --no-external
79         if ($opt->{external} // 1) {
80                 $self->_externals_each(\&_vivify_external, \@src);
81                 # {tid} is not unique between indices, so we have to search
82                 # each src individually
83                 if (!$opt->{thread}) {
84                         require PublicInbox::LeiXSearch;
85                         my $lxs = PublicInbox::LeiXSearch->new;
86                         # local is always first
87                         $lxs->attach_external($_) for @src;
88                         @src = ($lxs);
89                 }
90         }
91         my $out = $self->{output} // '-';
92         $out = 'json:/dev/stdout' if $out eq '-';
93         my $isatty = -t $self->{1};
94         $self->start_pager if $isatty;
95         my $json = substr($out, 0, 5) eq 'json:' ?
96                 ref(PublicInbox::Config->json)->new : undef;
97         if ($json) {
98                 if ($opt->{pretty} //= $isatty) {
99                         $json->pretty(1)->space_before(0);
100                         $json->indent_length($opt->{indent} // 2);
101                 }
102                 $json->utf8; # avoid Wide character in print warnings
103                 $json->ascii(1) if $opt->{ascii}; # for "\uXXXX"
104                 $json->canonical;
105         }
106
107         # src: LeiXSearch || LeiSearch || Inbox
108         my %mset_opt = map { $_ => $opt->{$_} } qw(thread limit offset);
109         delete $mset_opt{limit} if $opt->{limit} < 0;
110         $mset_opt{asc} = $opt->{'reverse'} ? 1 : 0;
111         if (defined(my $sort = $opt->{'sort'})) {
112                 if ($sort eq 'relevance') {
113                         $mset_opt{relevance} = 1;
114                 } elsif ($sort eq 'docid') {
115                         $mset_opt{relevance} = $mset_opt{asc} ? -1 : -2;
116                 } elsif ($sort =~ /\Areceived(?:-?[aA]t)?\z/) {
117                         # the default
118                 } else {
119                         die "unrecognized --sort=$sort\n";
120                 }
121         }
122         # $self->out($json->encode(\%mset_opt));
123         # descending docid order
124         $mset_opt{relevance} //= -2 if $opt->{thread};
125         # my $wcb = PublicInbox::LeiToMail->write_cb($out, $self);
126
127         # even w/o pretty, do the equivalent of a --pretty=oneline
128         # output so "lei q SEARCH_TERMS | wc -l" can be useful:
129         my $ORS = $json ? ($opt->{pretty} ? ', ' : ",\n") : "\n";
130         my $buf;
131
132         # we can generate too many records to hold in RAM, so we stream
133         # and fake a JSON array starting here:
134         $self->out('[') if $json;
135         my $emit_cb = sub {
136                 my ($smsg) = @_;
137                 delete @$smsg{qw(tid num)}; # only makes sense if single src
138                 chomp($buf = $json->encode(_smsg_unbless($smsg)));
139         };
140         $dd->prepare_dedupe;
141         for my $src (@src) {
142                 my $srch = $src->search;
143                 my $over = $src->over;
144                 my $smsg_for = $src->can('smsg_for'); # LeiXSearch
145                 my $mo = { %mset_opt };
146                 my $mset = $srch->mset($qstr, $mo);
147                 my $ctx = {};
148                 if ($smsg_for) {
149                         for my $it ($mset->items) {
150                                 my $smsg = $smsg_for->($srch, $it) or next;
151                                 next if $dd->is_smsg_dup($smsg);
152                                 $self->out($buf .= $ORS) if defined $buf;
153                                 $smsg->{relevance} = get_pct($it);
154                                 $emit_cb->($smsg);
155                         }
156                 } else { # --thread
157                         my $ids = $srch->mset_to_artnums($mset, $mo);
158                         $ctx->{ids} = $ids;
159                         my $i = 0;
160                         my %n2p = map {
161                                 ($ids->[$i++], get_pct($_));
162                         } $mset->items;
163                         undef $mset;
164                         while ($over && $over->expand_thread($ctx)) {
165                                 for my $n (@{$ctx->{xids}}) {
166                                         my $t = $over->get_art($n) or next;
167                                         next if $dd->is_smsg_dup($t);
168                                         if (my $p = delete $n2p{$t->{num}}) {
169                                                 $t->{relevance} = $p;
170                                         }
171                                         $self->out($buf .= $ORS);
172                                         $emit_cb->($t);
173                                 }
174                                 @{$ctx->{xids}} = ();
175                         }
176                 }
177         }
178         $self->out($buf .= "]\n"); # done
179 }
180
181 1;