]> Sergey Matveev's repositories - public-inbox.git/blob - xt/net_writer-imap.t
lei export-kw: don't recreate deleted IMAP folders
[public-inbox.git] / xt / net_writer-imap.t
1 #!perl -w
2 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict; use v5.10.1; use PublicInbox::TestCommon;
5 use Sys::Hostname qw(hostname);
6 use POSIX qw(strftime);
7 use PublicInbox::OnDestroy;
8 use PublicInbox::URIimap;
9 use PublicInbox::Config;
10 use PublicInbox::DS;
11 use PublicInbox::InboxIdle;
12 use Fcntl qw(O_EXCL O_WRONLY O_CREAT);
13 my $imap_url = $ENV{TEST_IMAP_WRITE_URL} or
14         plan skip_all => 'TEST_IMAP_WRITE_URL unset';
15 my $uri = PublicInbox::URIimap->new($imap_url);
16 defined($uri->path) and
17         plan skip_all => "$imap_url should not be a mailbox (just host:port)";
18 require_mods('Mail::IMAPClient');
19 require_ok 'PublicInbox::NetWriter';
20 my $host = (split(/\./, hostname))[0];
21 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
22 my $SEP = $ENV{IMAP_SEPARATOR} || '.';
23 my $folder = "INBOX$SEP$base-$host-".strftime('%Y%m%d%H%M%S', gmtime(time)).
24                 "-$$-".sprintf('%x', int(rand(0xffffffff)));
25 my $nwr = PublicInbox::NetWriter->new;
26 chop($imap_url) if substr($imap_url, -1) eq '/';
27 my $folder_url = "$imap_url/$folder";
28 my $folder_uri = PublicInbox::URIimap->new($folder_url);
29 is($folder_uri->mailbox, $folder, 'folder correct') or
30                 BAIL_OUT "BUG: bad $$uri";
31 $nwr->add_url($$folder_uri);
32 is($nwr->errors, undef, 'no errors');
33 $nwr->{pi_cfg} = bless {}, 'PublicInbox::Config';
34
35 my $set_cred_helper = sub {
36         my ($f, $cred_set) = @_;
37         sysopen(my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) or BAIL_OUT "open $f: $!";
38         print $fh <<EOF or BAIL_OUT "print $f: $!";
39 [credential]
40         helper = $cred_set
41 EOF
42         close $fh or BAIL_OUT "close $f: $!";
43 };
44
45 # allow testers with git-credential-store configured to reuse
46 # stored credentials inside test_lei(sub {...}) when $ENV{HOME}
47 # is overridden and localized.
48 my ($cred_set, @cred_link, $tmpdir, $for_destroy);
49 chomp(my $cred_helper = `git config credential.helper 2>/dev/null`);
50 if ($cred_helper eq 'store') {
51         my $config = $ENV{XDG_CONFIG_HOME} // "$ENV{HOME}/.config";
52         for my $f ("$ENV{HOME}/.git-credentials", "$config/git/credentials") {
53                 next unless -f $f;
54                 @cred_link = ($f, '/.git-credentials');
55                 last;
56         }
57         $cred_set = qq("$cred_helper");
58 } elsif ($cred_helper =~ /\Acache(?:[ \t]|\z)/) {
59         my $cache = $ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache";
60         for my $d ("$ENV{HOME}/.git-credential-cache",
61                         "$cache/git/credential") {
62                 next unless -d $d;
63                 @cred_link = ($d, '/.git-credential-cache');
64                 $cred_set = qq("$cred_helper");
65                 last;
66         }
67 } elsif (!$cred_helper) { # make the test less painful if no creds configured
68         ($tmpdir, $for_destroy) = tmpdir;
69         my $d = "$tmpdir/.git-credential-cache";
70         mkdir($d, 0700) or BAIL_OUT $!;
71         $cred_set = "cache --timeout=60";
72         @cred_link = ($d, '/.git-credential-cache');
73 } else {
74         diag "credential.helper=$cred_helper will not be used for this test";
75 }
76
77 my $mics = do {
78         local $ENV{HOME} = $tmpdir // $ENV{HOME};
79         if ($tmpdir && $cred_set) {
80                 $set_cred_helper->("$ENV{HOME}/.gitconfig", $cred_set)
81         }
82         $nwr->imap_common_init;
83 };
84 my $mic = (values %$mics)[0];
85 my $cleanup = PublicInbox::OnDestroy->new($$, sub {
86         if (defined($folder)) {
87                 my $mic = $nwr->mic_get($uri);
88                 $mic->delete($folder) or
89                         fail "delete $folder <$folder_uri>: $@";
90         }
91         if ($tmpdir && -f "$tmpdir/.gitconfig") {
92                 local $ENV{HOME} = $tmpdir;
93                 system(qw(git credential-cache exit));
94         }
95 });
96 my $imap_append = $nwr->can('imap_append');
97 my $smsg = bless { kw => [ 'seen' ] }, 'PublicInbox::Smsg';
98 $imap_append->($mic, $folder, undef, $smsg, eml_load('t/plack-qp.eml'));
99 $nwr->{quiet} = 1;
100 my $imap_slurp_all = sub {
101         my ($url, $uid, $kw, $eml, $res) = @_;
102         push @$res, [ $kw, $eml ];
103 };
104 $nwr->imap_each($folder_uri, $imap_slurp_all, my $res = []);
105 is(scalar(@$res), 1, 'got appended message');
106 my $plack_qp_eml = eml_load('t/plack-qp.eml');
107 is_deeply($res, [ [ [ 'seen' ], $plack_qp_eml ] ],
108         'uploaded message read back');
109 $res = $mic = $mics = undef;
110
111 test_lei(sub {
112         my ($ro_home, $cfg_path) = setup_public_inboxes;
113         my $cfg = PublicInbox::Config->new($cfg_path);
114         $cfg->each_inbox(sub {
115                 my ($ibx) = @_;
116                 lei_ok qw(add-external -q), $ibx->{inboxdir} or BAIL_OUT;
117         });
118
119         # cred_link[0] may be on a different (hopefully encrypted) FS,
120         # we only symlink to it here, so we don't copy any sensitive data
121         # into the temporary directory
122         if (@cred_link && !symlink($cred_link[0], $ENV{HOME}.$cred_link[1])) {
123                 diag "symlink @cred_link: $! (non-fatal)";
124                 $cred_set = undef;
125         }
126         $set_cred_helper->("$ENV{HOME}/.gitconfig", $cred_set) if $cred_set;
127
128         # don't combine these two:
129         $ENV{TEST_IMAP_COMPRESS} and lei_ok qw(config imap.compress true);
130         $ENV{TEST_IMAP_DEBUG} and lei_ok qw(config imap.debug true);
131         my $proxy = $ENV{TEST_IMAP_PROXY};
132         lei_ok(qw(config imap.proxy), $proxy) if $proxy;
133
134         lei_ok qw(q f:qp@example.com -o), $folder_url;
135         $nwr->imap_each($folder_uri, $imap_slurp_all, my $res = []);
136         is(scalar(@$res), 1, 'got one deduped result') or diag explain($res);
137         is_deeply($res->[0]->[1], $plack_qp_eml,
138                         'lei q wrote expected result');
139
140         lei_ok qw(q f:matz -a -o), $folder_url;
141         $nwr->imap_each($folder_uri, $imap_slurp_all, my $aug = []);
142         is(scalar(@$aug), 2, '2 results after augment') or diag explain($aug);
143         my $exp = $res->[0]->[1]->as_string;
144         is(scalar(grep { $_->[1]->as_string eq $exp } @$aug), 1,
145                         'original remains after augment');
146         $exp = eml_load('t/iso-2202-jp.eml')->as_string;
147         is(scalar(grep { $_->[1]->as_string eq $exp } @$aug), 1,
148                         'new result shown after augment');
149
150         lei_ok qw(q s:thisbetternotgiveanyresult -o), $folder_url;
151         $nwr->imap_each($folder_uri, $imap_slurp_all, my $empty = []);
152         is(scalar(@$empty), 0, 'no results w/o augment');
153
154         my $f = 't/utf8.eml'; # <testmessage@example.com>
155         $exp = eml_load($f);
156         lei_ok qw(convert -F eml -o), $folder_url, $f;
157         my (@uid, @res);
158         $nwr->imap_each($folder_uri, sub {
159                 my ($u, $uid, $kw, $eml) = @_;
160                 push @uid, $uid;
161                 push @res, [ $kw, $eml ];
162         });
163         is_deeply(\@res, [ [ [], $exp ] ], 'converted to IMAP destination');
164         is(scalar(@uid), 1, 'got one UID back');
165         lei_ok qw(q -o /dev/stdout m:testmessage@example.com --no-external);
166         is_deeply(json_utf8->decode($lei_out), [undef],
167                 'no results before import');
168
169         lei_ok qw(import -F eml), $f, \'import local copy w/o keywords';
170
171         lei_ok 'import', $folder_url; # populate mail_sync.sqlite3
172         lei_ok qw(tag +kw:seen +kw:answered +kw:flagged), $f;
173         lei_ok 'ls-mail-sync';
174         my @ls = split(/\n/, $lei_out);
175         is(scalar(@ls), 1, 'only one folder in ls-mail-sync') or xbail(\@ls);
176         for my $l (@ls) {
177                 like($l, qr/;UIDVALIDITY=\d+\z/, 'UIDVALIDITY');
178         }
179         lei_ok 'export-kw', $folder_url;
180         $mic = $nwr->mic_for_folder($folder_uri);
181         my $flags = $mic->flags($uid[0]);
182         is_deeply([sort @$flags], [ qw(\\Answered \\Flagged \\Seen) ],
183                 'IMAP flags set by export-kw') or diag explain($flags);
184
185         # ensure this imap_set_kw clobbers
186         $nwr->imap_set_kw($mic, $uid[0], [ 'seen' ])->expunge or
187                 BAIL_OUT "expunge $@";
188         $mic = undef;
189         @res = ();
190         $nwr->imap_each($folder_uri, $imap_slurp_all, \@res);
191         is_deeply(\@res, [ [ ['seen'], $exp ] ], 'seen flag set') or
192                 diag explain(\@res);
193
194         lei_ok qw(q s:thisbetternotgiveanyresult -o), $folder_url,
195                 \'clobber folder but import flag';
196         $nwr->imap_each($folder_uri, $imap_slurp_all, $empty = []);
197         is_deeply($empty, [], 'clobbered folder');
198         lei_ok qw(q -o /dev/stdout m:testmessage@example.com --no-external);
199         $res = json_utf8->decode($lei_out)->[0];
200         is_deeply([@$res{qw(m kw)}], ['testmessage@example.com', ['seen']],
201                 'kw set');
202
203         # prepare messages for watch
204         $mic = $nwr->mic_for_folder($folder_uri);
205         for my $kw (qw(Deleted Seen Answered Draft forwarded)) {
206                 my $buf = <<EOM;
207 From: x\@example.com
208 Message-ID: <$kw\@test.example.com>
209
210 EOM
211                 my $f = $kw eq 'forwarded' ? '$Forwarded' : "\\$kw";
212                 $mic->append_string($folder_uri->mailbox, $buf, $f)
213                         or BAIL_OUT "append $kw $@";
214         }
215         $mic->disconnect;
216
217         my $inboxdir = "$ENV{HOME}/wtest";
218         my @cmd = (qw(-init -Lbasic wtest), $inboxdir,
219                         qw(https://example.com/wtest wtest@example.com));
220         run_script(\@cmd) or BAIL_OUT "init wtest";
221         xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
222                         'publicinbox.wtest.watch',
223                         $folder_url) == 0 or BAIL_OUT "git config $?";
224         my $watcherr = "$ENV{HOME}/watch.err";
225         open my $err_wr, '>>', $watcherr or BAIL_OUT $!;
226         my $pub_cfg = PublicInbox::Config->new;
227         PublicInbox::DS->Reset;
228         my $ii = PublicInbox::InboxIdle->new($pub_cfg);
229         my $cb = sub { PublicInbox::DS->SetPostLoopCallback(sub {}) };
230         my $obj = bless \$cb, 'PublicInbox::TestCommon::InboxWakeup';
231         $pub_cfg->each_inbox(sub { $_[0]->subscribe_unlock('ident', $obj) });
232         my $w = start_script(['-watch'], undef, { 2 => $err_wr });
233         diag 'waiting for initial fetch...';
234         PublicInbox::DS::event_loop();
235         my $ibx = $pub_cfg->lookup_name('wtest');
236         my $mm = $ibx->mm;
237         ok(defined($mm->num_for('Seen@test.example.com')),
238                 '-watch takes seen message');
239         ok(defined($mm->num_for('Answered@test.example.com')),
240                 '-watch takes answered message');
241         ok(!defined($mm->num_for('Deleted@test.example.com')),
242                 '-watch ignored \\Deleted');
243         ok(!defined($mm->num_for('Draft@test.example.com')),
244                 '-watch ignored \\Draft');
245         ok(defined($mm->num_for('forwarded@test.example.com')),
246                 '-watch takes forwarded message');
247         undef $w; # done with watch
248         lei_ok qw(import), $folder_url;
249         lei_ok qw(q m:forwarded@test.example.com);
250         is_deeply(json_utf8->decode($lei_out)->[0]->{kw}, ['forwarded'],
251                 'forwarded kw imported from IMAP');
252
253         lei_ok qw(q m:testmessage --no-external -o), $folder_url;
254         lei_ok qw(up), $folder_url;
255         lei_ok qw(up --all=remote);
256         $mic = $nwr->mic_get($uri);
257         $mic->delete($folder) or fail "delete $folder <$folder_uri>: $@";
258         $mic->expunge;
259         undef $mic;
260         undef $folder;
261         ok(!lei(qw(export-kw), $folder_url),
262                 'export-kw fails w/ non-existent folder');
263
264 });
265
266 undef $cleanup; # remove temporary folder
267 done_testing;