]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei ls-search: command to list saved searches
[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         bless $cfg, 'PublicInbox::Config';
62         my $out = $cfg->get_all('lei.q.output') or return ();
63         map {;
64                 if (s!\A(?:maildir|mh|mbox.+|mmdf):!!i) {
65                         -e $_ ? $_ : (); # TODO auto-prune somewhere?
66                 } else { # IMAP, maybe JMAP
67                         $_;
68                 }
69         } @$out
70 }
71
72 sub new {
73         my ($cls, $lei, $dst) = @_;
74         my $self = bless { ale => $lei->ale }, $cls;
75         my $dir;
76         if (defined $dst) { # updating existing saved search via "lei up"
77                 my $f;
78                 $dir = $dst;
79                 output2lssdir($self, $lei, \$dir, \$f) or
80                         return $lei->fail("--save was not used with $dst cwd=".
81                                                 $lei->rel2abs('.'));
82                 $self->{-cfg} //= PublicInbox::Config::git_config_dump($f);
83                 $self->{'-f'} = $f;
84         } else { # new saved search "lei q --save"
85                 my $dst = $lei->{ovv}->{dst};
86                 $dir = lss_dir_for($lei, \$dst);
87                 require File::Path;
88                 File::Path::make_path($dir); # raises on error
89                 $self->{-cfg} = {};
90                 my $f = $self->{'-f'} = "$dir/lei.saved-search";
91                 open my $fh, '>', $f or return $lei->fail("open $f: $!");
92                 my $sq_dst = PublicInbox::Config::squote_maybe($dst);
93                 my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
94                 if (ref $q) {
95                         $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
96                 } else {
97                         $q = "\tq = ".cquote_val($q);
98                 }
99                 $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
100                 print $fh <<EOM;
101 ; to refresh with new results, run: lei up $sq_dst
102 [lei]
103 $q
104 [lei "q"]
105         output = $dst
106 EOM
107                 for my $k (ARRAY_FIELDS) {
108                         my $ary = $lei->{opt}->{$k} // next;
109                         for my $x (@$ary) {
110                                 print $fh "\t$k = ".cquote_val($x)."\n";
111                         }
112                 }
113                 for my $k (BOOL_FIELDS) {
114                         my $val = $lei->{opt}->{$k} // next;
115                         print $fh "\t$k = ".($val ? 1 : 0)."\n";
116                 }
117                 close($fh) or return $lei->fail("close $f: $!");
118         }
119         bless $self->{-cfg}, 'PublicInbox::Config';
120         $self->{lock_path} = "$self->{-f}.flock";
121         $self->{-ovf} = "$dir/over.sqlite3";
122         $self;
123 }
124
125 sub description { $_[0]->{qstr} } # for WWW
126
127 sub cfg_set { # called by LeiXSearch
128         my ($self, @args) = @_;
129         my $lk = $self->lock_for_scope; # git-config doesn't wait
130         run_die([qw(git config -f), $self->{'-f'}, @args]);
131 }
132
133 # drop-in for LeiDedupe API
134 sub is_dup {
135         my ($self, $eml, $smsg) = @_;
136         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
137         my $blob = $smsg ? $smsg->{blob} : undef;
138         return 1 if $blob && $oidx->blob_exists($blob);
139         my $lk = $self->lock_for_scope_fast;
140         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
141                 for my $docid (values %$xoids) {
142                         $oidx->add_xref3($docid, -1, $blob, '.');
143                 }
144                 $oidx->commit_lazy;
145                 1;
146         } else {
147                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
148                 unless ($smsg) {
149                         $smsg = bless {}, 'PublicInbox::Smsg';
150                         $smsg->{bytes} = 0;
151                         $smsg->populate($eml);
152                 }
153                 $oidx->begin_lazy;
154                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
155                 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
156                 $oidx->add_overview($eml, $smsg);
157                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
158                 $oidx->commit_lazy;
159                 undef;
160         }
161 }
162
163 sub prepare_dedupe {
164         my ($self) = @_;
165         $self->{oidx} //= do {
166                 my $creat = !-f $self->{-ovf};
167                 my $lk = $self->lock_for_scope; # git-config doesn't wait
168                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
169                 $oidx->{-no_fsync} = 1;
170                 $oidx->dbh;
171                 if ($creat) {
172                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
173                         $oidx->eidx_prep; # for xref3
174                 }
175                 $oidx
176         };
177 }
178
179 sub over { $_[0]->{oidx} } # for xoids_for
180
181 sub git { $_[0]->{ale}->git }
182
183 sub pause_dedupe {
184         my ($self) = @_;
185         $self->{ale}->git->cleanup;
186         my $oidx = delete($self->{oidx}) // return;
187         $oidx->commit_lazy;
188 }
189
190 sub mm { undef }
191
192 sub altid_map { {} }
193
194 sub cloneurl { [] }
195
196 # find existing directory containing a `lei.saved-search' file based on
197 # $dir_ref which is an output
198 sub output2lssdir {
199         my ($self, $lei, $dir_ref, $fn_ref) = @_;
200         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
201         my $dir = lss_dir_for($lei, \$dst);
202         my $f = "$dir/lei.saved-search";
203         if (-f $f && -r _) {
204                 $self->{-cfg} = PublicInbox::Config::git_config_dump($f);
205                 $$dir_ref = $dir;
206                 $$fn_ref = $f;
207                 return 1;
208         }
209         undef;
210 }
211
212 no warnings 'once';
213 *nntp_url = \&cloneurl;
214 *base_url = \&PublicInbox::Inbox::base_url;
215 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
216 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
217 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
218 *modified = \&PublicInbox::Inbox::modified;
219 *recent = \&PublicInbox::Inbox::recent;
220 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
221 *isrch = *search = \&mm; # TODO
222 *DESTROY = \&pause_dedupe;
223
224 1;