]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
d3a32d36b8559b3ecfb41edb18d7e085e65df39a
[public-inbox.git] / lib / PublicInbox / LeiSavedSearch.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # pretends to be like LeiDedupe and also PublicInbox::Inbox
5 package PublicInbox::LeiSavedSearch;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::Lock);
9 use PublicInbox::OverIdx;
10 use PublicInbox::LeiSearch;
11 use PublicInbox::Config;
12 use PublicInbox::Spawn qw(run_die);
13 use PublicInbox::ContentHash qw(git_sha);
14 use Digest::SHA qw(sha256_hex);
15
16 # move this to PublicInbox::Config if other things use it:
17 my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
18 sub cquote_val ($) { # cf. git-config(1)
19         my ($val) = @_;
20         $val =~ s/([\n\t\b])/$cquote{$1}/g;
21         $val;
22 }
23
24 sub ARRAY_FIELDS () { qw(only include exclude) }
25 sub BOOL_FIELDS () {
26         qw(external local remote import-remote import-before threads)
27 }
28
29 sub lss_dir_for ($$) {
30         my ($lei, $dstref) = @_;
31         my @n;
32         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
33                 require PublicInbox::URIimap;
34                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
35                 $$dstref = $$uri;
36                 @n = ($uri->mailbox);
37         } else { # basename
38                 $$dstref = $lei->rel2abs($$dstref);
39                 $$dstref .= '/' if -d $$dstref;
40                 $$dstref =~ tr!/!/!s;
41                 @n = ($$dstref =~ m{([^/]+)/*\z});
42         }
43         push @n, sha256_hex($$dstref);
44         $lei->share_path . '/saved-searches/' . join('-', @n);
45 }
46
47 sub list {
48         my ($lei, $pfx) = @_;
49         my $lss_dir = $lei->share_path.'/saved-searches/';
50         return () unless -d $lss_dir;
51         # TODO: persist the cache?  Use another format?
52         my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
53         open my $fh, '>', $f or die "open $f: $!";
54         print $fh "[include]\n";
55         for my $p (glob("$lss_dir/*/lei.saved-search")) {
56                 print $fh "\tpath = ", cquote_val($p), "\n";
57         }
58         close $fh or die "close $f: $!";
59         my $cfg = PublicInbox::Config->git_config_dump($f);
60         unlink($f);
61         my $out = $cfg->get_all('lei.q.output') or return ();
62         map {;
63                 s!\A(?:maildir|mh|mbox.+|mmdf):!!i;
64                 $_;
65         } @$out
66 }
67
68 sub new {
69         my ($cls, $lei, $dst) = @_;
70         my $self = bless { ale => $lei->ale }, $cls;
71         my $dir;
72         if (defined $dst) { # updating existing saved search via "lei up"
73                 my $f;
74                 $dir = $dst;
75                 output2lssdir($self, $lei, \$dir, \$f) or
76                         return $lei->fail("--save was not used with $dst cwd=".
77                                                 $lei->rel2abs('.'));
78                 $self->{'-f'} = $f;
79         } else { # new saved search "lei q --save"
80                 $dst = $lei->{ovv}->{dst};
81                 $dir = lss_dir_for($lei, \$dst);
82                 require File::Path;
83                 File::Path::make_path($dir); # raises on error
84                 $self->{-cfg} = {};
85                 my $f = $self->{'-f'} = "$dir/lei.saved-search";
86                 open my $fh, '>', $f or return $lei->fail("open $f: $!");
87                 my $sq_dst = PublicInbox::Config::squote_maybe($dst);
88                 my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
89                 if (ref $q) {
90                         $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
91                 } else {
92                         $q = "\tq = ".cquote_val($q);
93                 }
94                 $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
95                 print $fh <<EOM;
96 ; to refresh with new results, run: lei up $sq_dst
97 [lei]
98 $q
99 [lei "q"]
100         output = $dst
101 EOM
102                 for my $k (ARRAY_FIELDS) {
103                         my $ary = $lei->{opt}->{$k} // next;
104                         for my $x (@$ary) {
105                                 print $fh "\t$k = ".cquote_val($x)."\n";
106                         }
107                 }
108                 for my $k (BOOL_FIELDS) {
109                         my $val = $lei->{opt}->{$k} // next;
110                         print $fh "\t$k = ".($val ? 1 : 0)."\n";
111                 }
112                 close($fh) or return $lei->fail("close $f: $!");
113         }
114         $self->{lock_path} = "$self->{-f}.flock";
115         $self->{-ovf} = "$dir/over.sqlite3";
116         $self;
117 }
118
119 sub description { $_[0]->{qstr} } # for WWW
120
121 sub cfg_set { # called by LeiXSearch
122         my ($self, @args) = @_;
123         my $lk = $self->lock_for_scope; # git-config doesn't wait
124         run_die([qw(git config -f), $self->{'-f'}, @args]);
125 }
126
127 # drop-in for LeiDedupe API
128 sub is_dup {
129         my ($self, $eml, $smsg) = @_;
130         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
131         my $blob = $smsg ? $smsg->{blob} : undef;
132         return 1 if $blob && $oidx->blob_exists($blob);
133         my $lk = $self->lock_for_scope_fast;
134         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
135                 for my $docid (values %$xoids) {
136                         $oidx->add_xref3($docid, -1, $blob, '.');
137                 }
138                 $oidx->commit_lazy;
139                 1;
140         } else {
141                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
142                 unless ($smsg) {
143                         $smsg = bless {}, 'PublicInbox::Smsg';
144                         $smsg->{bytes} = 0;
145                         $smsg->populate($eml);
146                 }
147                 $oidx->begin_lazy;
148                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
149                 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
150                 $oidx->add_overview($eml, $smsg);
151                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
152                 $oidx->commit_lazy;
153                 undef;
154         }
155 }
156
157 sub prepare_dedupe {
158         my ($self) = @_;
159         $self->{oidx} //= do {
160                 my $creat = !-f $self->{-ovf};
161                 my $lk = $self->lock_for_scope; # git-config doesn't wait
162                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
163                 $oidx->{-no_fsync} = 1;
164                 $oidx->dbh;
165                 if ($creat) {
166                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
167                         $oidx->eidx_prep; # for xref3
168                 }
169                 $oidx
170         };
171 }
172
173 sub over { $_[0]->{oidx} } # for xoids_for
174
175 sub git { $_[0]->{ale}->git }
176
177 sub pause_dedupe {
178         my ($self) = @_;
179         $self->{ale}->git->cleanup;
180         my $oidx = delete($self->{oidx}) // return;
181         $oidx->commit_lazy;
182 }
183
184 sub mm { undef }
185
186 sub altid_map { {} }
187
188 sub cloneurl { [] }
189
190 # find existing directory containing a `lei.saved-search' file based on
191 # $dir_ref which is an output
192 sub output2lssdir {
193         my ($self, $lei, $dir_ref, $fn_ref) = @_;
194         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
195         my $dir = lss_dir_for($lei, \$dst);
196         my $f = "$dir/lei.saved-search";
197         if (-f $f && -r _) {
198                 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
199                 $$dir_ref = $dir;
200                 $$fn_ref = $f;
201                 return 1;
202         }
203         undef;
204 }
205
206 no warnings 'once';
207 *nntp_url = \&cloneurl;
208 *base_url = \&PublicInbox::Inbox::base_url;
209 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
210 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
211 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
212 *modified = \&PublicInbox::Inbox::modified;
213 *recent = \&PublicInbox::Inbox::recent;
214 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
215 *isrch = *search = \&mm; # TODO
216 *DESTROY = \&pause_dedupe;
217
218 1;