1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # handles lei <q|ls-query|rm-query|mv-query> commands
5 package PublicInbox::LeiQuery;
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);
13 sub _iso8601 ($) { strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($_[0])) }
15 # prepares an smsg for JSON
16 sub _smsg_unbless ($) {
19 delete @$smsg{qw(lines bytes)};
20 $smsg->{rcvd} = _iso8601(delete $smsg->{ts}); # JMAP receivedAt
21 $smsg->{dt} = _iso8601(delete $smsg->{ds}); # JMAP UTCDate
23 if (my $r = delete $smsg->{references}) {
24 $smsg->{references} = [
25 map { "<$_>" } ($r =~ m/$MID_EXTRACT/go) ];
27 if (my $m = delete($smsg->{mid})) {
28 $smsg->{'m'} = "<$m>";
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;
40 $smsg->{'s'} = delete $smsg->{subject};
41 # can we be bothered to parse From/To/Cc into arrays?
42 scalar { %$smsg }; # unbless
45 sub _vivify_external { # _externals_each callback
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';
54 warn "W: ignoring $dir, unable to determine type\n";
58 # the main "lei q SEARCH_TERMS" method
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{"$_"}) : $_
70 $opt->{limit} //= 10000;
73 # --local is enabled by default
74 my @src = $opt->{'local'} ? ($sto->search) : ();
76 # --external is enabled by default, but allow --no-external
77 if ($opt->{external} // 1) {
78 $self->_externals_each(\&_vivify_external, \@src);
79 # {tid} is not unique between indices, so we have to search
80 # each src individually
81 if (!$opt->{thread}) {
82 require PublicInbox::LeiXSearch;
83 my $lxs = PublicInbox::LeiXSearch->new;
84 # local is always first
85 $lxs->attach_external($_) for @src;
89 my $out = $self->{output} // '-';
90 $out = 'json:/dev/stdout' if $out eq '-';
91 my $isatty = -t $self->{1};
92 $self->start_pager if $isatty;
93 my $json = substr($out, 0, 5) eq 'json:' ?
94 ref(PublicInbox::Config->json)->new : undef;
96 if ($opt->{pretty} //= $isatty) {
97 $json->pretty(1)->space_before(0);
98 $json->indent_length($opt->{indent} // 2);
100 $json->utf8; # avoid Wide character in print warnings
101 $json->ascii(1) if $opt->{ascii}; # for "\uXXXX"
105 # src: LeiXSearch || LeiSearch || Inbox
106 my %mset_opt = map { $_ => $opt->{$_} } qw(thread limit offset);
107 delete $mset_opt{limit} if $opt->{limit} < 0;
108 $mset_opt{asc} = $opt->{'reverse'} ? 1 : 0;
109 if (defined(my $sort = $opt->{'sort'})) {
110 if ($sort eq 'relevance') {
111 $mset_opt{relevance} = 1;
112 } elsif ($sort eq 'docid') {
113 $mset_opt{relevance} = $mset_opt{asc} ? -1 : -2;
114 } elsif ($sort =~ /\Areceived(?:-?[aA]t)?\z/) {
117 die "unrecognized --sort=$sort\n";
120 # $self->out($json->encode(\%mset_opt));
121 # descending docid order
122 $mset_opt{relevance} //= -2 if $opt->{thread};
123 # my $wcb = PublicInbox::LeiToMail->write_cb($out, $self);
125 # even w/o pretty, do the equivalent of a --pretty=oneline
126 # output so "lei q SEARCH_TERMS | wc -l" can be useful:
127 my $ORS = $json ? ($opt->{pretty} ? ', ' : ",\n") : "\n";
130 # we can generate too many records to hold in RAM, so we stream
131 # and fake a JSON array starting here:
132 $self->out('[') if $json;
135 delete @$smsg{qw(tid num)}; # only makes sense if single src
136 chomp($buf = $json->encode(_smsg_unbless($smsg)));
139 my $srch = $src->search;
140 my $over = $src->over;
141 my $smsg_for = $src->can('smsg_for'); # LeiXSearch
142 my $mo = { %mset_opt };
143 my $mset = $srch->mset($qstr, $mo);
146 for my $it ($mset->items) {
147 my $smsg = $smsg_for->($srch, $it) or next;
148 $self->out($buf .= $ORS) if defined $buf;
149 $smsg->{relevance} = get_pct($it);
153 my $ids = $srch->mset_to_artnums($mset, $mo);
157 ($ids->[$i++], get_pct($_));
160 while ($over && $over->expand_thread($ctx)) {
161 for my $n (@{$ctx->{xids}}) {
162 my $t = $over->get_art($n) or next;
163 if (my $p = delete $n2p{$t->{num}}) {
164 $t->{relevance} = $p;
166 $self->out($buf .= $ORS);
169 @{$ctx->{xids}} = ();
173 $self->out($buf .= "]\n"); # done