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