Debian Codegraph @

cassandane/Cassandane/Cyrus/SearchFuzzy.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Cyrus::SearchFuzzy;
41 use strict;
42 use warnings;
43 use Cwd qw(abs_path);
44 use DateTime;
45 use Data::Dumper;
46 use File::Temp qw(tempdir);
47 use File::stat;
48 use MIME::Base64 qw(encode_base64);
49 use Encode qw(decode encode);
50
51 use lib '.';
52 use base qw(Cassandane::Cyrus::TestCase);
53 use Cassandane::Util::Log;
54
55 sub new
56 {
57
58 my ($class, @args) = @_;
59 my $config = Cassandane::Config->default()->clone();
60 $config->set(
61 conversations => 'on',
62 httpallowcompress => 'no',
63 httpmodules => 'jmap',
64 );
65 my $self = $class->SUPER::new({
66 config => $config,
67 jmap => 1,
68 services => [ 'imap', 'http' ]
69 }, @args);
70
71 $self->needs('search', 'xapian');
72 return $self;
73 }
74
75 sub set_up
76 {
77 my ($self) = @_;
78 $self->SUPER::set_up();
79
80 # This will be "words" if Xapian has a CJK word-tokeniser, "ngrams"
81 # if it doesn't, or "none" if it cannot tokenise CJK at all.
82 $self->{xapian_cjk_tokens} =
83 $self->{instance}->{buildinfo}->get('search', 'xapian_cjk_tokens')
84 || "none";
85
86 xlog $self, "Xapian CJK tokeniser '$self->{xapian_cjk_tokens}' detected.\n";
87
88 my $config = $self->{instance}->{config};
89 $self->{skipdiacrit} = $config->get_bool('search_skipdiacrit', 'on');
90 $self->{fuzzyalways} = $config->get_bool('search_fuzzy_always', 'off');
91 }
92
93 sub tear_down
94 {
95 my ($self) = @_;
96 $self->SUPER::tear_down();
97 }
98
99 sub create_testmessages
100 {
101 my ($self) = @_;
102
103 xlog $self, "Generate test messages.";
104 # Some subjects with the same verb word stem
105 $self->make_message("I am running") || die;
106 $self->make_message("I run") || die;
107 $self->make_message("He runs") || die;
108
109 # Some bodies with the same word stems but different senders. We use
110 # the "connect" word stem since it it the first example on Xapian's
111 # Stemming documentation (https://xapian.org/docs/stemming.html).
112 # Mails from [email protected]...
113 my %params;
114 %params = (
115 from => Cassandane::Address->new(
116 localpart => "foo",
117 domain => "example.com"
118 ),
119 );
120 $params{'body'} ="He has connections.",
121 $self->make_message("1", %params) || die;
122 $params{'body'} = "Gonna get myself connected.";
123 $self->make_message("2", %params) || die;
124 # ...as well as from [email protected].
125 %params = (
126 from => Cassandane::Address->new(
127 localpart => "bar",
128 domain => "example.com"
129 ),
130 body => "Einstein's gravitational theory resulted in beautiful relations connecting gravitational phenomena with the geometry of space; this was an exciting idea."
131 );
132 $self->make_message("3", %params) || die;
133
134 # Create the search database.
135 xlog $self, "Run squatter";
136 $self->{instance}->run_command({cyrus => 1}, 'squatter');
137 }
138
139 sub get_snippets
140 {
141 # Previous versions of this test module used XSNIPPETS to
142 # assert snippets but this command got removed from Cyrus.
143 # Use JMAP instead.
144
145 my ($self, $folder, $uids, $filter) = @_;
146
147 my $imap = $self->{store}->get_client();
148 my $jmap = $self->{jmap};
149
150 $self->assert_not_null($jmap);
151
152 $imap->select($folder);
153 my $res = $imap->fetch($uids, ['emailid']);
154 my %emailIdToImapUid = map { $res->{$_}{emailid}[0] => $_ } keys %$res;
155
156 $res = $jmap->CallMethods([
157 ['SearchSnippet/get', {
158 filter => $filter,
159 emailIds => [ keys %emailIdToImapUid ],
160 }, 'R1'],
161 ]);
162
163 my @snippets;
164 foreach (@{$res->[0][1]{list}}) {
165 if ($_->{subject}) {
166 push(@snippets, [
167 0,
168 $emailIdToImapUid{$_->{emailId}},
169 'SUBJECT',
170 $_->{subject},
171 ]);
172 }
173 if ($_->{preview}) {
174 push(@snippets, [
175 0,
176 $emailIdToImapUid{$_->{emailId}},
177 'BODY',
178 $_->{preview},
179 ]);
180 }
181 }
182
183 return {
184 snippets => [ sort { $a->[1] <=> $b->[1] } @snippets ],
185 };
186 }
187
188 sub run_delve
189 {
190 my ($self, $dir, @args) = @_;
191 my $basedir = $self->{instance}->{basedir};
192 my @myargs = ('xapian-delve');
193 push(@myargs, @args);
194 push(@myargs, $dir);
195 $self->{instance}->run_command({redirects => {stdout => "$basedir/delve.out"}}, @myargs);
196 open(FH, "<$basedir/delve.out") || die "can't find delve.out";
197 my $data = <FH>;
198 return $data;
199 }
200
201 sub delve_docs
202 {
203 my ($self, $dir) = @_;
204 return ([], []) unless -e "$dir/iamglass";
205 my $delveout = $self->run_delve($dir, '-V0');
206 $delveout =~ s/^Value 0 for each document: //;
207 my @docs = split ' ', $delveout;
208 my @parts = map { $_ =~ /^\d+:\*P\*/ ? substr($_, 5) : () } @docs;
209 my @gdocs = map { $_ =~ /^\d+:\*G\*/ ? substr($_, 5) : () } @docs;
210 return \@gdocs, \@parts;
211 }
212
213 sub start_echo_extractor
214 {
215 my ($self, %params) = @_;
216 my $instance = $self->{instance};
217
218 xlog "Start extractor server with tracedir $params{tracedir}";
219 my $nrequests = 0;
220 my $handler = sub {
221 my ($conn, $req) = @_;
222
223 $nrequests++;
224
225 if ($params{trace_delay_seconds}) {
226 sleep $params{trace_delay_seconds};
227 }
228
229 if ($params{tracedir}) {
230 # touch trace file in tracedir
231 my @paths = split(q{/}, URI->new($req->uri)->path);
232 my $guid = pop(@paths);
233 my $fname = join(q{},
234 $params{tracedir}, "/req", $nrequests, "_", $req->method, "_$guid");
235 open(my $fh, ">", $fname) or die "Can't open > $fname: $!";
236 close $fh;
237 }
238
239 my $res;
240
241 if ($req->method eq 'HEAD') {
242 $res = HTTP::Response->new(204);
243 $res->content("");
244 } elsif ($req->method eq 'GET') {
245 $res = HTTP::Response->new(404);
246 $res->content("nope");
247 } else {
248 $res = HTTP::Response->new(200);
249 $res->content($req->content);
250 }
251
252 if ($params{response_delay_seconds}) {
253 my $secs = $params{response_delay_seconds};
254 if (ref($secs) eq 'ARRAY') {
255 $secs = ($nrequests <= scalar @$secs) ?
256 $secs->[$nrequests-1] : 0;
257 }
258 sleep $secs;
259 }
260
261 $conn->send_response($res);
262 };
263
264 my $uri = URI->new($instance->{config}->get('search_attachment_extractor_url'));
265 $instance->start_httpd($handler, $uri->port());
266 }
267
268 sub squatter_attachextract_cache_run
269 {
270 my ($self, $cachedir, @squatterArgs) = @_;
271 my $instance = $self->{instance};
272 my $imap = $self->{store}->get_client();
273
274 xlog "Append emails with identical attachments";
275 $self->make_message("msg1",
276 mime_type => "multipart/related",
277 mime_boundary => "123456789abcdef",
278 body => ""
279 ."\r\n--123456789abcdef\r\n"
280 ."Content-Type: text/plain\r\n"
281 ."\r\n"
282 ."bodyterm"
283 ."\r\n--123456789abcdef\r\n"
284 ."Content-Type: application/pdf\r\n"
285 ."\r\n"
286 ."attachterm"
287 ."\r\n--123456789abcdef--\r\n"
288 ) || die;
289 $self->make_message("msg2",
290 mime_type => "multipart/related",
291 mime_boundary => "123456789abcdef",
292 body => ""
293 ."\r\n--123456789abcdef\r\n"
294 ."Content-Type: text/plain\r\n"
295 ."\r\n"
296 ."bodyterm"
297 ."\r\n--123456789abcdef\r\n"
298 ."Content-Type: application/pdf\r\n"
299 ."\r\n"
300 ."attachterm"
301 ."\r\n--123456789abcdef--\r\n"
302 ) || die;
303
304 xlog "Run squatter with cachedir $cachedir";
305 $self->{instance}->run_command({cyrus => 1},
306 'squatter', "--attachextract-cache-dir=$cachedir", @squatterArgs);
307 }
308
309 use Cassandane::Tiny::Loader 'tiny-tests/SearchFuzzy';
310
311 1;