1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # represents an IMAPD (currently a singleton),
5 # see script/public-inbox-imapd for how it is used
6 package PublicInbox::IMAPD;
8 use parent qw(PublicInbox::NNTPD);
9 use PublicInbox::InboxIdle;
10 use PublicInbox::IMAP;
11 # *UID_BLOCK = \&PublicInbox::IMAP::UID_BLOCK;
20 # accept_tls => { SSL_server => 1, ..., SSL_reuse_ctx => ... }
21 # pi_config => PublicInbox::Config
22 # idler => PublicInbox::InboxIdle
26 sub refresh_inboxlist ($) {
28 my @names = map { $_->{newsgroup} } @{delete $self->{grouplist}};
29 my %ns; # "\Noselect \HasChildren"
31 if (my @uc = grep(/[A-Z]/, @names)) {
32 warn "Uppercase not allowed for IMAP newsgroup(s):\n",
34 my %uc = map { $_ => 1 } @uc;
35 @names = grep { !$uc{$_} } @names;
39 while ($up =~ s/\.[^\.]+\z//) {
40 $ns{$up} = '\\Noselect \\HasChildren';
44 my $at = delete($ns{$_}) ? '\\HasChildren' : '\\HasNoChildren';
45 qq[* LIST ($at) "." $_\r\n]
47 push(@names, map { qq[* LIST ($ns{$_}) "." $_\r\n] } keys %ns);
49 my ($xa) = ($a =~ / (\S+)\r\n/g);
50 my ($xb) = ($b =~ / (\S+)\r\n/g);
51 length($xa) <=> length($xb);
53 $self->{inboxlist} = \@names;
56 sub imapd_refresh_ibx { # pi_config->each_inbox cb
57 my ($ibx, $imapd) = @_;
58 my $ngname = $ibx->{newsgroup} or return;
60 warn 'multiple newsgroups not supported: '.
61 join(', ', @$ngname). "\n";
62 } elsif ($ngname =~ m![^a-z0-9/_\.\-\~\@\+\=:]! ||
63 $ngname =~ /\.[0-9]+-[0-9]+\z/) {
64 warn "mailbox name invalid: `$ngname'\n";
67 my $mm = $ibx->mm or return;
69 defined($ibx->{uidvalidity} = $mm->created_at) or return;
70 $imapd->{tmp_groups}->{$ngname} = $ibx;
72 # preload to avoid fragmentation:
75 # my $max = $mm->max // 0;
76 # my $uid_min = UID_BLOCK * int($max/UID_BLOCK) + 1;
79 sub imapd_refresh_finalize {
80 my ($imapd, $pi_config) = @_;
81 $imapd->{groups} = delete $imapd->{tmp_groups};
82 $imapd->{grouplist} = [ values %{$imapd->{groups}} ];
83 refresh_inboxlist($imapd);
84 $imapd->{pi_config} = $pi_config;
85 if (my $idler = $imapd->{idler}) {
86 $idler->refresh($pi_config);
90 sub imapd_refresh_step { # pi_config->iterate_start cb
91 my ($pi_config, $section, $imapd) = @_;
92 if (defined($section)) {
93 return if $section !~ m!\Apublicinbox\.([^/]+)\z!;
94 my $ibx = $pi_config->lookup_name($1) or return;
95 imapd_refresh_ibx($ibx, $imapd);
97 imapd_refresh_finalize($imapd, $pi_config);
102 my ($self, $sig) = @_;
103 my $pi_config = PublicInbox::Config->new;
104 $self->{tmp_groups} = {};
105 if (0 && $sig) { # SIGHUP
106 $pi_config->iterate_start(\&imapd_refresh_step, $self);
107 PublicInbox::DS::requeue($pi_config); # call event_step
108 } else { # initial start
109 $pi_config->each_inbox(\&imapd_refresh_ibx, $self);
110 imapd_refresh_finalize($self, $pi_config);
115 $_[0]->{idler} //= PublicInbox::InboxIdle->new($_[0]->{pi_config});