4718483bec420e0e11731502597069300c816cb4
[mailshears.git] / lib / common / dovecot_plugin.rb
1 require 'common/domain'
2 require 'common/filesystem'
3 require 'common/plugin'
4 require 'common/user'
5
6
7 module DovecotPlugin
8 # Code that all Dovecot plugins (Prune, Rm, Mv...) will
9 # share. That is, we implement the Plugin interface.
10 include Plugin
11
12 def initialize(cfg)
13 @domain_root = cfg.mail_root
14 end
15
16 def describe_domain(domain)
17 begin
18 domain_path = get_domain_path(domain)
19 return domain_path
20 rescue NonexistentDomainError => e
21 return "Doesn't exist: #{e.to_s}"
22 end
23 end
24
25 def describe_user(user)
26 begin
27 user_path = get_user_path(user)
28 return user_path
29 rescue NonexistentUserError => e
30 return "Doesn't exist: #{e.to_s}"
31 end
32 end
33
34
35 def domain_exists(domain)
36 domains = list_domains()
37 return domains.include?(domain)
38 end
39
40
41 protected;
42
43 def get_domain_path(domain)
44 # Return the filesystem path for the given domain.
45 # That is, the directory where its mail is stored.
46 # Only works if the domain directory exists!
47 return File.join(@domain_root, domain.to_s())
48 end
49
50
51 def get_user_path(user)
52 # Return the filesystem path of this user's mailbox.
53 domain_path = get_domain_path(user.domain())
54 return File.join(domain_path, user.localpart())
55 end
56
57
58 def list_domains()
59 return Filesystem.get_subdirs(@domain_root).map{ |d| Domain.new(d) }
60 end
61
62 def list_domains_users(domains)
63 users = []
64
65 domains.each do |domain|
66 begin
67 # Throws a NonexistentDomainError if the domain's path
68 # doesn't exist on the filesystem. In this case, we want
69 # to report zero users.
70 domain_path = get_domain_path(domain)
71 usernames = Filesystem.get_subdirs(domain_path)
72
73 usernames.each do |username|
74 users << User.new("#{username}@#{domain}")
75 end
76 rescue NonexistentDomainError
77 # Party hard.
78 end
79 end
80
81 return users
82 end
83
84
85 def list_users()
86 domains = list_domains()
87 users = list_domains_users(domains)
88 return users
89 end
90
91 end