root / pykota / trunk / pykota / storages / ldapstorage.py @ 1020

Revision 1020, 17.7 kB (checked in by jalet, 21 years ago)

Not implemented methods now raise an exception when called.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.4  2003/06/10 10:45:32  jalet
24# Not implemented methods now raise an exception when called.
25#
26# Revision 1.3  2003/06/06 20:49:15  jalet
27# Very latest schema. UNTESTED.
28#
29# Revision 1.2  2003/06/06 14:21:08  jalet
30# New LDAP schema.
31# Small bug fixes.
32#
33# Revision 1.1  2003/06/05 11:19:13  jalet
34# More good work on LDAP storage.
35#
36#
37#
38
39#
40# My IANA assigned number, for
41# "Conseil Internet & Logiciels Libres, J�me Alet"
42# is 16868. Use this as a base to create the LDAP schema.
43#
44
45import fnmatch
46
47from pykota.storage import PyKotaStorageError
48
49try :
50    import ldap
51except ImportError :   
52    import sys
53    # TODO : to translate or not to translate ?
54    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
55   
56class Storage :
57    def __init__(self, host, dbname, user, passwd) :
58        """Opens the LDAP connection."""
59        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
60        self.closed = 1
61        try :
62            self.database = ldap.initialize(host) 
63            self.database.simple_bind_s(user, passwd)
64            self.basedn = dbname
65        except ldap.SERVER_DOWN :   
66            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
67        else :   
68            self.closed = 0
69           
70    def __del__(self) :       
71        """Closes the database connection."""
72        if not self.closed :
73            del self.database
74            self.closed = 1
75       
76    def doSearch(self, key, fields, base="", scope=ldap.SCOPE_SUBTREE) :
77        """Does an LDAP search query."""
78        try :
79            # prepends something more restrictive at the beginning of the base dn
80            result = self.database.search_s(base or self.basedn, scope, key, fields)
81        except ldap.NO_SUCH_OBJECT :   
82            return
83        else :     
84            return result
85       
86    def getMatchingPrinters(self, printerpattern) :
87        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
88        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName"])
89        if result :
90            return [(printerid, printer["pykotaPrinterName"][0]) for (printerid, printer) in result if fnmatch.fnmatchcase(printer["pykotaPrinterName"][0], printerpattern)]
91           
92    def getPrinterId(self, printername) :       
93        """Returns a printerid given a printername."""
94        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(cn=%s)))" % (printername, printername), ["pykotaPrinterName"])
95        if result :
96            return result[0][0]
97           
98    def getPrinterPrices(self, printerid) :       
99        """Returns a printer prices per page and per job given a printerid."""
100        result = self.doSearch("(|(pykotaPrinterName=*)(cn=*))", ["pykotaPricePerPage", "pykotaPricePerJob"], base=printerid, scope=ldap.SCOPE_BASE)
101        if result :
102            return (float(result[0][1]["pykotaPricePerPage"][0]), float(result[0][1]["pykotaPricePerJob"][0]))
103           
104    def setPrinterPrices(self, printerid, perpage, perjob) :
105        """Sets prices per job and per page for a given printer."""
106        raise PyKotaStorageError, "Not implemented !"
107   
108    def getUserId(self, username) :
109        """Returns a userid given a username."""
110        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(uid=%s)))" % (username, username), ["uid"])
111        if result :
112            return result[0][0]
113           
114    def getGroupId(self, groupname) :
115        """Returns a groupid given a grupname."""
116        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(cn=%s)))" % (groupname, groupname), ["cn"])
117        if result is not None :
118            (groupid, dummy) = result[0]
119            return groupid
120           
121    def getJobHistoryId(self, jobid, userid, printerid) :       
122        """Returns the history line's id given a (jobid, userid, printerid)."""
123        raise PyKotaStorageError, "Not implemented !"
124           
125    def getPrinterUsers(self, printerid) :       
126        """Returns the list of userids and usernames which uses a given printer."""
127        # first get the printer's name from the id
128        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", "cn"], base=printerid, scope=ldap.SCOPE_BASE)
129        if result :
130            fields = result[0][1]
131            printername = (fields.get("pykotaPrinterName") or fields.get("cn"))[0]
132            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printername, ["pykotaUserName"]) 
133            if result :
134                return [(pquotauserid, fields["pykotaUserName"][0]) for (pquotauserid, fields) in result]
135       
136    def getPrinterGroups(self, printerid) :       
137        """Returns the list of groups which uses a given printer."""
138        # first get the printer's name from the id
139        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", "cn"], base=printerid, scope=ldap.SCOPE_BASE)
140        if result :
141            fields = result[0][1]
142            printername = (fields.get("pykotaPrinterName") or fields.get("cn"))[0]
143            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printername, ["pykotaGroupName"]) 
144            if result :
145                return [(pquotagroupid, fields["pykotaGroupName"][0]) for (pquotagroupid, fields) in result]
146       
147    def getGroupMembersNames(self, groupname) :       
148        """Returns the list of user's names which are member of this group."""
149        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(cn=%s)))" % (groupname, groupname), ["memberUid", "uniqueMember", "member"])
150        if result :
151            fields = result[0][1]
152            return fields.get("memberUid") or fields.get("uniqueMember") or fields.get("member")
153       
154    def getUserGroupsNames(self, userid) :       
155        """Returns the list of groups' names the user is a member of."""
156        raise PyKotaStorageError, "Not implemented !"
157       
158    def addPrinter(self, printername) :       
159        """Adds a printer to the quota storage, returns its id."""
160        raise PyKotaStorageError, "Not implemented !"
161       
162    def addUser(self, username) :       
163        """Adds a user to the quota storage, returns its id."""
164        raise PyKotaStorageError, "Not implemented !"
165       
166    def addGroup(self, groupname) :       
167        """Adds a group to the quota storage, returns its id."""
168        raise PyKotaStorageError, "Not implemented !"
169       
170    def addUserPQuota(self, username, printerid) :
171        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
172        raise PyKotaStorageError, "Not implemented !"
173       
174    def addGroupPQuota(self, groupname, printerid) :
175        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
176        raise PyKotaStorageError, "Not implemented !"
177       
178    def increaseUserBalance(self, userid, amount) :   
179        """Increases (or decreases) an user's account balance by a given amount."""
180        raise PyKotaStorageError, "Not implemented !"
181       
182    def getUserBalance(self, userquotaid) :   
183        """Returns the current account balance for a given user quota identifier."""
184        # first get the user's name from the user quota id
185        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName"], base=userquotaid, scope=ldap.SCOPE_BASE)
186        if result :
187            username = result[0][1]["pykotaUserName"][0]
188            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(uid=%s)))" % (username, username), ["pykotaBalance", "pykotaLifeTimePaid"])
189            if result :
190                fields = result[0][1]
191                return (float(fields["pykotaBalance"][0]), float(fields["pykotaLifeTimePaid"][0]))
192       
193    def getUserBalanceFromUserId(self, userid) :   
194        """Returns the current account balance for a given user id."""
195        # first get the user's name from the user id
196        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName", "uid"], base=userid, scope=ldap.SCOPE_BASE)
197        if result :
198            fields = result[0][1]
199            username = (fields.get("pykotaUserName") or fields.get("uid"))[0]
200            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(uid=%s)))" % (username, username), ["pykotaBalance", "pykotaLifeTimePaid"])
201            if result :
202                fields = result[0][1]
203                return (float(fields["pykotaBalance"][0]), float(fields["pykotaLifeTimePaid"][0]))
204       
205    def getGroupBalance(self, groupquotaid) :   
206        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
207        # first get the group's name from the group quota id
208        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName"], base=groupquotaid, scope=ldap.SCOPE_BASE)
209        if result :
210            groupname = result[0][1]["pykotaGroupName"][0]
211            members = self.getGroupMembersNames(groupname)
212            balance = lifetimepaid = 0.0
213            for member in members :
214                userid = self.getUserId(member)
215                if userid :
216                    userbal = self.getUserBalanceFromUserId(userid)
217                    if userbal :
218                        (bal, paid) = userbal
219                        balance += bal
220                        lifetimepaid += paid
221            return (balance, lifetimepaid)           
222       
223    def getUserLimitBy(self, userid) :   
224        """Returns the way in which user printing is limited."""
225        result = self.doSearch("objectClass=pykotaAccount", ["pykotaLimitBy"], base=userid, scope=ldap.SCOPE_BASE)
226        if result :
227            return result[0][1]["pykotaLimitBy"][0]
228       
229    def getGroupLimitBy(self, groupquotaid) :   
230        """Returns the way in which group printing is limited."""
231        # first get the group's name from the group quota id
232        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName"], base=groupquotaid, scope=ldap.SCOPE_BASE)
233        if result :
234            groupname = result[0][1]["pykotaGroupName"][0]
235            result = self.doSearch("(&(objectClass=pykotaGroup)(pykotaGroupName=%s))" % groupname, ["pykotaLimitBy"])
236            if result :
237                return result[0][1]["pykotaLimitBy"][0]
238       
239    def setUserBalance(self, userid, balance) :   
240        """Sets the account balance for a given user to a fixed value."""
241        raise PyKotaStorageError, "Not implemented !"
242       
243    def limitUserBy(self, userid, limitby) :   
244        """Limits a given user based either on print quota or on account balance."""
245        raise PyKotaStorageError, "Not implemented !"
246       
247    def limitGroupBy(self, groupid, limitby) :   
248        """Limits a given group based either on print quota or on sum of its users' account balances."""
249        raise PyKotaStorageError, "Not implemented !"
250       
251    def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
252        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
253        raise PyKotaStorageError, "Not implemented !"
254       
255    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
256        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
257        raise PyKotaStorageError, "Not implemented !"
258       
259    def resetUserPQuota(self, userid, printerid) :   
260        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
261        raise PyKotaStorageError, "Not implemented !"
262       
263    def resetGroupPQuota(self, groupid, printerid) :   
264        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
265        raise PyKotaStorageError, "Not implemented !"
266       
267    def updateUserPQuota(self, userid, printerid, pagecount) :
268        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
269        raise PyKotaStorageError, "Not implemented !"
270       
271    def getUserPQuota(self, userquotaid, printerid) :
272        """Returns the Print Quota information for a given (userquotaid, printerid)."""
273        # first get the user's name from the id
274        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=userquotaid, scope=ldap.SCOPE_BASE)
275        if result :
276            fields = result[0][1]
277            datelimit = fields["pykotaDateLimit"][0].strip()
278            if (not datelimit) or (datelimit.upper() == "NONE") : 
279                datelimit = None
280            return { "lifepagecounter" : int(fields["pykotaLifePageCounter"][0]), 
281                     "pagecounter" : int(fields["pykotaPageCounter"][0]),
282                     "softlimit" : int(fields["pykotaSoftLimit"][0]),
283                     "hardlimit" : int(fields["pykotaHardLimit"][0]),
284                     "datelimit" : datelimit
285                   }
286       
287    def getGroupPQuota(self, grouppquotaid, printerid) :
288        """Returns the Print Quota information for a given (grouppquotaid, printerid)."""
289        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=grouppquotaid, scope=ldap.SCOPE_BASE)
290        if result :
291            fields = result[0][1]
292            groupname = fields["pykotaGroupName"][0]
293            datelimit = fields["pykotaDateLimit"][0].strip()
294            if (not datelimit) or (datelimit.upper() == "NONE") : 
295                datelimit = None
296            quota = {
297                      "softlimit" : int(fields["pykotaSoftLimit"][0]),
298                      "hardlimit" : int(fields["pykotaHardLimit"][0]),
299                      "datelimit" : datelimit
300                    }
301            members = self.getGroupMembersNames(groupname)
302            pagecounter = lifepagecounter = 0
303            printerusers = self.getPrinterUsers(printerid)
304            if printerusers :
305                for (userid, username) in printerusers :
306                    if username in members :
307                        userpquota = self.getUserPQuota(userid, printerid)
308                        if userpquota :
309                            pagecounter += userpquota["pagecounter"]
310                            lifepagecounter += userpquota["lifepagecounter"]
311            quota.update({"pagecounter": pagecounter, "lifepagecounter": lifepagecounter})               
312            return quota
313       
314    def setUserDateLimit(self, userid, printerid, datelimit) :
315        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
316        raise PyKotaStorageError, "Not implemented !"
317       
318    def setGroupDateLimit(self, groupid, printerid, datelimit) :
319        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
320        raise PyKotaStorageError, "Not implemented !"
321       
322    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action) :
323        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
324        raise PyKotaStorageError, "Not implemented !"
325   
326    def updateJobSizeInHistory(self, historyid, jobsize) :
327        """Updates a job size in the history given the history line's id."""
328        raise PyKotaStorageError, "Not implemented !"
329   
330    def getPrinterPageCounter(self, printerid) :
331        """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
332        return # TODO
333        result = self.doSearch("objectClass=pykotaPrinterJob", ["pykotaJobHistoryId", "pykotaJobId", "uid", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobDate"], base=printerid)
334        if result :
335            pass # TODO
336       
337    def addUserToGroup(self, userid, groupid) :   
338        """Adds an user to a group."""
339        raise PyKotaStorageError, "Not implemented !"
340       
341    def deleteUser(self, userid) :   
342        """Completely deletes an user from the Quota Storage."""
343        raise PyKotaStorageError, "Not implemented !"
344       
345    def deleteGroup(self, groupid) :   
346        """Completely deletes an user from the Quota Storage."""
347        raise PyKotaStorageError, "Not implemented !"
348       
349    def computePrinterJobPrice(self, printerid, jobsize) :   
350        """Returns the price for a job on a given printer."""
351        # TODO : create a base class with things like this
352        prices = self.getPrinterPrices(printerid)
353        if prices is None :
354            perpage = perjob = 0.0
355        else :   
356            (perpage, perjob) = prices
357        return perjob + (perpage * jobsize)
Note: See TracBrowser for help on using the browser.