]> Sergey Matveev's repositories - public-inbox.git/blob - xt/net_writer-imap.t
1298b958f683ba5d40404146e8162651736fc087
[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 $folder = "INBOX.$base-$host-".strftime('%Y%m%d%H%M%S', gmtime(time)).
23                 "-$$-".sprintf('%x', int(rand(0xffffffff)));
24 my $nwr = PublicInbox::NetWriter->new;
25 chop($imap_url) if substr($imap_url, -1) eq '/';
26 my $folder_uri = PublicInbox::URIimap->new("$imap_url/$folder");
27 is($folder_uri->mailbox, $folder, 'folder correct') or
28                 BAIL_OUT "BUG: bad $$uri";
29 $nwr->add_url($$folder_uri);
30 is($nwr->errors, undef, 'no errors');
31 $nwr->{pi_cfg} = bless {}, 'PublicInbox::Config';
32
33 my $set_cred_helper = sub {
34         my ($f, $cred_set) = @_;
35         sysopen(my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) or BAIL_OUT "open $f: $!";
36         print $fh <<EOF or BAIL_OUT "print $f: $!";
37 [credential]
38         helper = $cred_set
39 EOF
40         close $fh or BAIL_OUT "close $f: $!";
41 };
42
43 # allow testers with git-credential-store configured to reuse
44 # stored credentials inside test_lei(sub {...}) when $ENV{HOME}
45 # is overridden and localized.
46 my ($cred_set, @cred_link, $tmpdir, $for_destroy);
47 chomp(my $cred_helper = `git config credential.helper 2>/dev/null`);
48 if ($cred_helper eq 'store') {
49         my $config = $ENV{XDG_CONFIG_HOME} // "$ENV{HOME}/.config";
50         for my $f ("$ENV{HOME}/.git-credentials", "$config/git/credentials") {
51                 next unless -f $f;
52                 @cred_link = ($f, '/.git-credentials');
53                 last;
54         }
55         $cred_set = qq("$cred_helper");
56 } elsif ($cred_helper =~ /\Acache(?:[ \t]|\z)/) {
57         my $cache = $ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache";
58         for my $d ("$ENV{HOME}/.git-credential-cache",
59                         "$cache/git/credential") {
60                 next unless -d $d;
61                 @cred_link = ($d, '/.git-credential-cache');
62                 $cred_set = qq("$cred_helper");
63                 last;
64         }
65 } elsif (!$cred_helper) { # make the test less painful if no creds configured
66         ($tmpdir, $for_destroy) = tmpdir;
67         my $d = "$tmpdir/.git-credential-cache";
68         mkdir($d, 0700) or BAIL_OUT $!;
69         $cred_set = "cache --timeout=60";
70         @cred_link = ($d, '/.git-credential-cache');
71 } else {
72         diag "credential.helper=$cred_helper will not be used for this test";
73 }
74
75 my $mics = do {
76         local $ENV{HOME} = $tmpdir // $ENV{HOME};
77         if ($tmpdir && $cred_set) {
78                 $set_cred_helper->("$ENV{HOME}/.gitconfig", $cred_set)
79         }
80         $nwr->imap_common_init;
81 };
82 my $mic = (values %$mics)[0];
83 my $cleanup = PublicInbox::OnDestroy->new($$, sub {
84         my $mic = $nwr->mic_get($uri);
85         $mic->delete($folder) or fail "delete $folder <$folder_uri>: $@";
86         if ($tmpdir && -f "$tmpdir/.gitconfig") {
87                 local $ENV{HOME} = $tmpdir;
88                 system(qw(git credential-cache exit));
89         }
90 });
91 my $imap_append = $nwr->can('imap_append');
92 my $smsg = bless { kw => [ 'seen' ] }, 'PublicInbox::Smsg';
93 $imap_append->($mic, $folder, undef, $smsg, eml_load('t/plack-qp.eml'));
94 $nwr->{quiet} = 1;
95 my $imap_slurp_all = sub {
96         my ($url, $uid, $kw, $eml, $res) = @_;
97         push @$res, [ $kw, $eml ];
98 };
99 $nwr->imap_each($folder_uri, $imap_slurp_all, my $res = []);
100 is(scalar(@$res), 1, 'got appended message');
101 my $plack_qp_eml = eml_load('t/plack-qp.eml');
102 is_deeply($res, [ [ [ 'seen' ], $plack_qp_eml ] ],
103         'uploaded message read back');
104 $res = $mic = $mics = undef;
105
106 test_lei(sub {
107         my ($ro_home, $cfg_path) = setup_public_inboxes;
108         my $cfg = PublicInbox::Config->new($cfg_path);
109         $cfg->each_inbox(sub {
110                 my ($ibx) = @_;
111                 lei_ok qw(add-external -q), $ibx->{inboxdir} or BAIL_OUT;
112         });
113
114         # cred_link[0] may be on a different (hopefully encrypted) FS,
115         # we only symlink to it here, so we don't copy any sensitive data
116         # into the temporary directory
117         if (@cred_link && !symlink($cred_link[0], $ENV{HOME}.$cred_link[1])) {
118                 diag "symlink @cred_link: $! (non-fatal)";
119                 $cred_set = undef;
120         }
121         $set_cred_helper->("$ENV{HOME}/.gitconfig", $cred_set) if $cred_set;
122
123         lei_ok qw(q f:qp@example.com -o), $$folder_uri;
124         $nwr->imap_each($folder_uri, $imap_slurp_all, my $res = []);
125         is(scalar(@$res), 1, 'got one deduped result') or diag explain($res);
126         is_deeply($res->[0]->[1], $plack_qp_eml,
127                         'lei q wrote expected result');
128
129         lei_ok qw(q f:matz -a -o), $$folder_uri;
130         $nwr->imap_each($folder_uri, $imap_slurp_all, my $aug = []);
131         is(scalar(@$aug), 2, '2 results after augment') or diag explain($aug);
132         my $exp = $res->[0]->[1]->as_string;
133         is(scalar(grep { $_->[1]->as_string eq $exp } @$aug), 1,
134                         'original remains after augment');
135         $exp = eml_load('t/iso-2202-jp.eml')->as_string;
136         is(scalar(grep { $_->[1]->as_string eq $exp } @$aug), 1,
137                         'new result shown after augment');
138
139         lei_ok qw(q s:thisbetternotgiveanyresult -o), $folder_uri->as_string;
140         $nwr->imap_each($folder_uri, $imap_slurp_all, my $empty = []);
141         is(scalar(@$empty), 0, 'no results w/o augment');
142
143         my $f = 't/utf8.eml'; # <testmessage@example.com>
144         $exp = eml_load($f);
145         lei_ok qw(convert -F eml -o), $$folder_uri, $f;
146         my (@uid, @res);
147         $nwr->imap_each($folder_uri, sub {
148                 my ($u, $uid, $kw, $eml) = @_;
149                 push @uid, $uid;
150                 push @res, [ $kw, $eml ];
151         });
152         is_deeply(\@res, [ [ [], $exp ] ], 'converted to IMAP destination');
153         is(scalar(@uid), 1, 'got one UID back');
154         lei_ok qw(q -o /dev/stdout m:testmessage@example.com --no-external);
155         is_deeply(json_utf8->decode($lei_out), [undef],
156                 'no results before import');
157
158         lei_ok qw(import -F eml), $f, \'import local copy w/o keywords';
159
160         $mic = $nwr->mic_for_folder($folder_uri);
161         # dummy set to ensure second set_kw clobbers
162         $nwr->imap_set_kw($mic, $uid[0], [ qw(seen answered flagged) ]
163                         )->expunge or BAIL_OUT "expunge $@";
164         $nwr->imap_set_kw($mic, $uid[0], [ 'seen' ]
165                         )->expunge or BAIL_OUT "expunge $@";
166         $mic = undef;
167         @res = ();
168         $nwr->imap_each($folder_uri, $imap_slurp_all, \@res);
169         is_deeply(\@res, [ [ ['seen'], $exp ] ], 'seen flag set') or
170                 diag explain(\@res);
171
172         lei_ok qw(q s:thisbetternotgiveanyresult -o), $folder_uri->as_string,
173                 \'clobber folder but import flag';
174         $nwr->imap_each($folder_uri, $imap_slurp_all, $empty = []);
175         is_deeply($empty, [], 'clobbered folder');
176         lei_ok qw(q -o /dev/stdout m:testmessage@example.com --no-external);
177         $res = json_utf8->decode($lei_out)->[0];
178         is_deeply([@$res{qw(m kw)}], ['testmessage@example.com', ['seen']],
179                 'kw set');
180
181         # prepare messages for watch
182         $mic = $nwr->mic_for_folder($folder_uri);
183         for my $kw (qw(Deleted Seen Answered Draft forwarded)) {
184                 my $buf = <<EOM;
185 From: x\@example.com
186 Message-ID: <$kw\@test.example.com>
187
188 EOM
189                 my $f = $kw eq 'forwarded' ? '$Forwarded' : "\\$kw";
190                 $mic->append_string($folder_uri->mailbox, $buf, $f)
191                         or BAIL_OUT "append $kw $@";
192         }
193         $mic->disconnect;
194
195         my $inboxdir = "$ENV{HOME}/wtest";
196         my @cmd = (qw(-init -Lbasic wtest), $inboxdir,
197                         qw(https://example.com/wtest wtest@example.com));
198         run_script(\@cmd) or BAIL_OUT "init wtest";
199         xsys(qw(git config), "--file=$ENV{HOME}/.public-inbox/config",
200                         'publicinbox.wtest.watch',
201                         $$folder_uri) == 0 or BAIL_OUT "git config $?";
202         my $watcherr = "$ENV{HOME}/watch.err";
203         open my $err_wr, '>>', $watcherr or BAIL_OUT $!;
204         my $pub_cfg = PublicInbox::Config->new;
205         PublicInbox::DS->Reset;
206         my $ii = PublicInbox::InboxIdle->new($pub_cfg);
207         my $cb = sub { PublicInbox::DS->SetPostLoopCallback(sub {}) };
208         my $obj = bless \$cb, 'PublicInbox::TestCommon::InboxWakeup';
209         $pub_cfg->each_inbox(sub { $_[0]->subscribe_unlock('ident', $obj) });
210         my $w = start_script(['-watch'], undef, { 2 => $err_wr });
211         diag 'waiting for initial fetch...';
212         PublicInbox::DS->EventLoop;
213         my $ibx = $pub_cfg->lookup_name('wtest');
214         my $mm = $ibx->mm;
215         ok(defined($mm->num_for('Seen@test.example.com')),
216                 '-watch takes seen message');
217         ok(defined($mm->num_for('Answered@test.example.com')),
218                 '-watch takes answered message');
219         ok(!defined($mm->num_for('Deleted@test.example.com')),
220                 '-watch ignored \\Deleted');
221         ok(!defined($mm->num_for('Draft@test.example.com')),
222                 '-watch ignored \\Draft');
223         ok(defined($mm->num_for('forwarded@test.example.com')),
224                 '-watch takes forwarded message');
225         undef $w; # done with watch
226         lei_ok qw(import), $$folder_uri;
227         lei_ok qw(q m:forwarded@test.example.com);
228         is_deeply(json_utf8->decode($lei_out)->[0]->{kw}, ['forwarded'],
229                 'forwarded kw imported from IMAP');
230 });
231
232 undef $cleanup; # remove temporary folder
233 done_testing;