Pass a Configuration object to each plugin's initialize().
[mailshears.git] / lib / common / dovecot_plugin.rb
1 require 'common/plugin'
2 require 'common/filesystem'
3
4 module DovecotPlugin
5 # Code that all Dovecot plugins (Prune, Rm, Mv...) will
6 # share. That is, we implement the Plugin interface.
7 include Plugin
8
9 def initialize(cfg)
10 @domain_root = cfg.mail_root
11 end
12
13 def describe_domain(domain)
14 begin
15 domain_path = get_domain_path(domain)
16 return domain_path
17 rescue NonexistentDomainError => e
18 return "Doesn't exist: #{e.to_s}"
19 end
20 end
21
22 def describe_account(account)
23 begin
24 account_path = get_account_path(account)
25 return account_path
26 rescue NonexistentAccountError => e
27 return "Doesn't exist: #{e.to_s}"
28 end
29 end
30
31
32 protected;
33
34 def get_domain_path(domain)
35 # Return the filesystem path for the given domain.
36 # That is, the directory where its mail is stored.
37 # Only works if the domain directory exists!
38 domain_path = File.join(@domain_root, domain)
39
40 if File.directory?(domain_path)
41 return domain_path
42 else
43 raise NonexistentDomainError.new(domain)
44 end
45 end
46
47
48 def get_account_path(account)
49 # Return the filesystem path of this account's mailbox.
50 # Only works if the account exists!
51 if not account.include?('@')
52 msg = "#{account}: Accounts must contain an '@' symbol."
53 raise InvalidAccountError.new(msg)
54 end
55
56 account_parts = account.split('@')
57 user_part = account_parts[0]
58 domain_part = account_parts[1]
59
60 begin
61 domain_path = get_domain_path(domain_part)
62 rescue NonexistentDomainError
63 raise NonexistentAccountError.new(account)
64 end
65
66 account_path = File.join(domain_path, user_part)
67
68 if File.directory?(account_path)
69 return account_path
70 else
71 raise NonexistentAccountError.new(account)
72 end
73 end
74
75
76 def list_domains()
77 return Filesystem.get_subdirs(@domain_root)
78 end
79
80 def list_domains_users(domains)
81 accounts = []
82
83 domains.each do |domain|
84 begin
85 # Throws a NonexistentDomainError if the domain's path
86 # doesn't exist on the filesystem. In this case, we want
87 # to report zero accounts.
88 domain_path = get_domain_path(domain)
89 usernames = Filesystem.get_subdirs(domain_path)
90
91 usernames.each do |username|
92 accounts << "#{username}@#{domain}"
93 end
94 rescue NonexistentDomainError
95 # Party hard.
96 end
97 end
98
99 return accounts
100 end
101
102
103 def list_users()
104 domains = list_domains()
105 users = list_domains_users(domains)
106 return users
107 end
108
109 end