]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
nntp: implement OVER/XOVER summary in search document
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # based on notmuch, but with no concept of folders, files or flags
4 package PublicInbox::Search;
5 use strict;
6 use warnings;
7
8 # values for searching
9 use constant TS => 0; # timestamp
10 use constant NUM => 1; # NNTP article number
11 use constant BYTES => 2; # :bytes as defined in RFC 3977
12 use constant LINES => 3; # :lines as defined in RFC 3977
13
14 use Search::Xapian qw/:standard/;
15 use PublicInbox::SearchMsg;
16 use Email::MIME;
17 use PublicInbox::MID qw/mid_clean mid_compress/;
18
19 # This is English-only, everything else is non-standard and may be confused as
20 # a prefix common in patch emails
21 our $REPLY_RE = qr/^re:\s+/i;
22 our $LANG = 'english';
23
24 use constant {
25         # SCHEMA_VERSION history
26         # 0 - initial
27         # 1 - subject_path is lower-cased
28         # 2 - subject_path is mid_compress in the index, only
29         # 3 - message-ID is compressed if it includes '%' (hack!)
30         # 4 - change "Re: " normalization, avoid circular Reference ghosts
31         # 5 - subject_path drops trailing '.'
32         # 6 - preserve References: order in document data
33         # 7 - remove references and inreplyto terms
34         # 8 - remove redundant/unneeded document data
35         # 9 - disable Message-ID compression (SHA-1)
36         # 10 - optimize doc for NNTP overviews
37         SCHEMA_VERSION => 10,
38
39         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
40         # as it could become a denial-of-service vector
41         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
42 };
43
44 # setup prefixes
45 my %bool_pfx_internal = (
46         type => 'T', # "mail" or "ghost"
47         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
48 );
49
50 my %bool_pfx_external = (
51         path => 'XPATH',
52         mid => 'Q', # uniQue id (Message-ID)
53 );
54
55 my %prob_prefix = (
56         subject => 'S',
57         s => 'S', # for mairix compatibility
58         m => 'Q', # 'mid' is exact, 'm' can do partial
59 );
60
61 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
62
63 sub xpfx { $all_pfx{$_[0]} }
64
65 our %PFX2TERM_RMAP;
66 my %meta_pfx = (mid => 1, thread => 1, path => 1);
67 while (my ($k, $v) = each %all_pfx) {
68         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
69 }
70
71 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
72
73 sub xdir {
74         my (undef, $git_dir) = @_;
75         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
76 }
77
78 sub new {
79         my ($class, $git_dir) = @_;
80         my $dir = $class->xdir($git_dir);
81         my $db = Search::Xapian::Database->new($dir);
82         bless { xdb => $db, git_dir => $git_dir }, $class;
83 }
84
85 sub reopen { $_[0]->{xdb}->reopen }
86
87 # read-only
88 sub query {
89         my ($self, $query_string, $opts) = @_;
90         my $query;
91
92         $opts ||= {};
93         unless ($query_string eq '') {
94                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
95                 $opts->{relevance} = 1 unless exists $opts->{relevance};
96         }
97
98         $self->do_enquire($query, $opts);
99 }
100
101 sub get_thread {
102         my ($self, $mid, $opts) = @_;
103         my $smsg = eval { $self->lookup_message($mid) };
104
105         return { total => 0, msgs => [] } unless $smsg;
106         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
107         my $path = mid_compress($smsg->path);
108         my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
109         my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
110         $self->do_enquire($query, $opts);
111 }
112
113 sub do_enquire {
114         my ($self, $query, $opts) = @_;
115         my $enquire = $self->enquire;
116         if (defined $query) {
117                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
118         } else {
119                 $query = $mail_query;
120         }
121         $enquire->set_query($query);
122         $opts ||= {};
123         my $desc = !$opts->{asc};
124         if ($opts->{relevance}) {
125                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
126         } else {
127                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
128         }
129         my $offset = $opts->{offset} || 0;
130         my $limit = $opts->{limit} || 50;
131         my $mset = $enquire->get_mset($offset, $limit);
132         return $mset if $opts->{mset};
133         my @msgs = map {
134                 PublicInbox::SearchMsg->load_doc($_->get_document);
135         } $mset->items;
136
137         { total => $mset->get_matches_estimated, msgs => \@msgs }
138 }
139
140 # read-write
141 sub stemmer { Search::Xapian::Stem->new($LANG) }
142
143 # read-only
144 sub qp {
145         my ($self) = @_;
146
147         my $qp = $self->{query_parser};
148         return $qp if $qp;
149
150         # new parser
151         $qp = Search::Xapian::QueryParser->new;
152         $qp->set_default_op(OP_AND);
153         $qp->set_database($self->{xdb});
154         $qp->set_stemmer($self->stemmer);
155         $qp->set_stemming_strategy(STEM_SOME);
156         $qp->add_valuerangeprocessor($self->ts_range_processor);
157         $qp->add_valuerangeprocessor($self->date_range_processor);
158
159         while (my ($name, $prefix) = each %bool_pfx_external) {
160                 $qp->add_boolean_prefix($name, $prefix);
161         }
162
163         while (my ($name, $prefix) = each %prob_prefix) {
164                 $qp->add_prefix($name, $prefix);
165         }
166
167         $self->{query_parser} = $qp;
168 }
169
170 sub ts_range_processor {
171         $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
172 }
173
174 sub date_range_processor {
175         $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
176 }
177
178 sub num_range_processor {
179         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
180 }
181
182 # only used for NNTP server
183 sub query_xover {
184         my ($self, $beg, $end, $offset) = @_;
185         my $enquire = $self->enquire;
186         my $qp = Search::Xapian::QueryParser->new;
187         $qp->set_database($self->{xdb});
188         $qp->add_valuerangeprocessor($self->num_range_processor);
189         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
190         $query = Search::Xapian::Query->new(OP_AND, $mail_query, $query);
191         $enquire->set_query($query);
192         $enquire->set_sort_by_value(NUM, 0);
193         my $limit = 200;
194         my $mset = $enquire->get_mset($offset, $limit);
195         my @msgs = map {
196                 PublicInbox::SearchMsg->load_doc($_->get_document);
197         } $mset->items;
198
199         { total => $mset->get_matches_estimated, msgs => \@msgs }
200 }
201
202 sub lookup_message {
203         my ($self, $mid) = @_;
204         $mid = mid_clean($mid);
205
206         my $doc_id = $self->find_unique_doc_id('mid', $mid);
207         my $smsg;
208         if (defined $doc_id) {
209                 # raises on error:
210                 my $doc = $self->{xdb}->get_document($doc_id);
211                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
212                 $smsg->doc_id($doc_id);
213         }
214         $smsg;
215 }
216
217 sub find_unique_doc_id {
218         my ($self, $term, $value) = @_;
219
220         my ($begin, $end) = $self->find_doc_ids($term, $value);
221
222         return undef if $begin->equal($end); # not found
223
224         my $rv = $begin->get_docid;
225
226         # sanity check
227         $begin->inc;
228         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
229         $rv;
230 }
231
232 # returns begin and end PostingIterator
233 sub find_doc_ids {
234         my ($self, $term, $value) = @_;
235
236         $self->find_doc_ids_for_term(xpfx($term) . $value);
237 }
238
239 # returns begin and end PostingIterator
240 sub find_doc_ids_for_term {
241         my ($self, $term) = @_;
242         my $db = $self->{xdb};
243
244         ($db->postlist_begin($term), $db->postlist_end($term));
245 }
246
247 # normalize subjects so they are suitable as pathnames for URLs
248 sub subject_path {
249         my $subj = pop;
250         $subj = subject_normalized($subj);
251         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
252         lc($subj);
253 }
254
255 sub subject_normalized {
256         my $subj = pop;
257         $subj =~ s/\A\s+//s; # no leading space
258         $subj =~ s/\s+\z//s; # no trailing space
259         $subj =~ s/\s+/ /gs; # no redundant spaces
260         $subj =~ s/\.+\z//; # no trailing '.'
261         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
262         $subj;
263 }
264
265 # for doc data
266 sub subject_summary {
267         my $subj = pop;
268         my $max = 68;
269         if (length($subj) > $max) {
270                 my @subj = split(/\s+/, $subj);
271                 $subj = '';
272                 my $l;
273
274                 while ($l = shift @subj) {
275                         my $new = $subj . $l . ' ';
276                         last if length($new) >= $max;
277                         $subj = $new;
278                 }
279                 if ($subj ne '') {
280                         my $r = scalar @subj ? ' ...' : '';
281                         $subj =~ s/ \z/$r/s;
282                 } else {
283                         # subject has one REALLY long word, and NOT spam? wtf
284                         @subj = ($l =~ /\A(.{1,72})/);
285                         $subj = $subj[0] . ' ...';
286                 }
287         }
288         $subj;
289 }
290
291 sub enquire {
292         my ($self) = @_;
293         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
294 }
295
296 1;