cd34a982529f70c09e156567e34cbcab97b7fc8e
[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_user(user)
21 principal_id = self.get_principal_id(user)
22 return "Principal ID: #{principal_id}"
23 end
24
25
26 def list_users()
27 #
28 # Produce a list of DAViCal users. This is public because it's
29 # useful for testing.
30 #
31 usernames = []
32
33 begin
34 connection = PGconn.connect(@db_host,
35 @db_port,
36 @db_opts,
37 @db_tty,
38 @db_name,
39 @db_user,
40 @db_pass)
41
42 # User #1 is the super-user, and not tied to an email address.
43 sql_query = "SELECT username FROM usr WHERE user_no > 1"
44
45 connection.query(sql_query) do |result|
46 usernames = result.field_values('username')
47 end
48
49 connection.close()
50 rescue PGError => e
51 # Pretend like we're database-agnostic in case we ever are.
52 raise DatabaseError.new(e)
53 end
54
55 return usernames.map{ |u| User.new(u) }
56 end
57
58
59 protected;
60
61 def get_principal_id(user)
62 principal_id = nil
63
64 begin
65 connection = PGconn.connect(@db_host,
66 @db_port,
67 @db_opts,
68 @db_tty,
69 @db_name,
70 @db_user,
71 @db_pass)
72
73 sql_query = "SELECT principal.principal_id "
74 sql_query += "FROM (principal INNER JOIN usr "
75 sql_query += " ON principal.user_no = usr.user_no) "
76 sql_query += "WHERE usr.username = $1;"
77
78 connection.query(sql_query, [user.to_s()]) do |result|
79 if result.num_tuples > 0
80 principal_id = result[0]['principal_id']
81 end
82 end
83
84 connection.close()
85
86 rescue PGError => e
87 # Pretend like we're database-agnostic in case we ever are.
88 raise DatabaseError.new(e)
89 end
90
91 return principal_id
92 end
93
94 end