Allow the getting of a dovecot user path even if it doesn't exist.
[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_user(user)
23 begin
24 user_path = get_user_path(user)
25 return user_path
26 rescue NonexistentUserError => 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_user_path(user, existence_check = true)
49 # Return the filesystem path of this user's mailbox. With
50 # existence_check = true, it only works if the user exists!
51 # We always require that the domain exists.
52 if not user.include?('@')
53 msg = "#{user}: Users must contain an '@' symbol."
54 raise InvalidUserError.new(msg)
55 end
56
57 user_parts = user.split('@')
58 local_part = user_parts[0]
59 domain_part = user_parts[1]
60
61 begin
62 domain_path = get_domain_path(domain_part)
63 rescue NonexistentDomainError
64 raise NonexistentUserError.new(user)
65 end
66
67 user_path = File.join(domain_path, local_part)
68
69 return user_path if not existence_check
70
71 if File.directory?(user_path)
72 return user_path
73 else
74 raise NonexistentUserError.new(user)
75 end
76 end
77
78
79 def list_domains()
80 return Filesystem.get_subdirs(@domain_root)
81 end
82
83 def list_domains_users(domains)
84 users = []
85
86 domains.each do |domain|
87 begin
88 # Throws a NonexistentDomainError if the domain's path
89 # doesn't exist on the filesystem. In this case, we want
90 # to report zero users.
91 domain_path = get_domain_path(domain)
92 usernames = Filesystem.get_subdirs(domain_path)
93
94 usernames.each do |username|
95 users << "#{username}@#{domain}"
96 end
97 rescue NonexistentDomainError
98 # Party hard.
99 end
100 end
101
102 return users
103 end
104
105
106 def list_users()
107 domains = list_domains()
108 users = list_domains_users(domains)
109 return users
110 end
111
112 end