557c1dd1b3bf18e012cdf234e6400b05d4de7925
[mailshears.git] / lib / common / davical_plugin.rb
1 require 'common/plugin'
2 require 'common/user'
3
4 module DavicalPlugin
5 # Code that all Davical plugins (Prune, Rm, Mv...) will share. That
6 # is, we implement the Plugin interface.
7 include Plugin
8
9 def initialize(cfg)
10 @db_host = cfg.davical_dbhost
11 @db_port = cfg.davical_dbport
12 @db_opts = cfg.davical_dbopts
13 @db_tty = cfg.davical_dbtty
14 @db_name = cfg.davical_dbname
15 @db_user = cfg.davical_dbuser
16 @db_pass = cfg.davical_dbpass
17 end
18
19
20 def describe_domain(domain)
21 # DAViCal doesn't have a concept of domains.
22 return domain.to_s()
23 end
24
25
26 def describe_user(user)
27 principal_id = self.get_principal_id(user)
28
29 if principal_id.nil?
30 return 'User not found'
31 else
32 return "Principal ID: #{principal_id}"
33 end
34 end
35
36
37 def list_users()
38 #
39 # Produce a list of DAViCal users. This is public because it's
40 # useful for testing.
41 #
42 usernames = []
43
44 begin
45 connection = PGconn.connect(@db_host,
46 @db_port,
47 @db_opts,
48 @db_tty,
49 @db_name,
50 @db_user,
51 @db_pass)
52
53 # User #1 is the super-user, and not tied to an email address.
54 sql_query = "SELECT username FROM usr WHERE user_no > 1"
55
56 connection.query(sql_query) do |result|
57 usernames = result.field_values('username')
58 end
59
60 connection.close()
61 rescue PGError => e
62 # Pretend like we're database-agnostic in case we ever are.
63 raise DatabaseError.new(e)
64 end
65
66 return usernames.map{ |u| User.new(u) }
67 end
68
69
70 protected;
71
72 def get_principal_id(user)
73 principal_id = nil
74
75 begin
76 connection = PGconn.connect(@db_host,
77 @db_port,
78 @db_opts,
79 @db_tty,
80 @db_name,
81 @db_user,
82 @db_pass)
83
84 sql_query = "SELECT principal.principal_id "
85 sql_query += "FROM (principal INNER JOIN usr "
86 sql_query += " ON principal.user_no = usr.user_no) "
87 sql_query += "WHERE usr.username = $1;"
88
89 connection.query(sql_query, [user.to_s()]) do |result|
90 if result.num_tuples > 0
91 principal_id = result[0]['principal_id']
92 end
93 end
94
95 connection.close()
96
97 rescue PGError => e
98 # Pretend like we're database-agnostic in case we ever are.
99 raise DatabaseError.new(e)
100 end
101
102 return principal_id
103 end
104
105 end