root / pykota / trunk / pykota / config.py @ 804

Revision 804, 7.6 kB (checked in by jalet, 21 years ago)

Typos

  • 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
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# You're welcome to redistribute this software under the
7# terms of the GNU General Public Licence version 2.0
8# or, at your option, any higher version.
9#
10# You can read the complete GNU GPL in the file COPYING
11# which should come along with this software, or visit
12# the Free Software Foundation's WEB site http://www.fsf.org
13#
14# $Id$
15#
16# $Log$
17# Revision 1.16  2003/02/17 23:01:56  jalet
18# Typos
19#
20# Revision 1.15  2003/02/17 22:55:01  jalet
21# More options can now be set per printer or globally :
22#
23#       admin
24#       adminmail
25#       gracedelay
26#       requester
27#
28# the printer option has priority when both are defined.
29#
30# Revision 1.14  2003/02/17 22:05:50  jalet
31# Storage backend now supports admin and user passwords (untested)
32#
33# Revision 1.13  2003/02/10 11:47:39  jalet
34# Moved some code down into the requesters
35#
36# Revision 1.12  2003/02/10 10:36:33  jalet
37# Small problem wrt external requester
38#
39# Revision 1.11  2003/02/10 08:50:45  jalet
40# External requester seems to be finally ok now
41#
42# Revision 1.10  2003/02/10 08:19:57  jalet
43# tell ConfigParser to return raw data, this allows our own strings
44# interpolations in the requester
45#
46# Revision 1.9  2003/02/10 00:44:38  jalet
47# Typos
48#
49# Revision 1.8  2003/02/10 00:42:17  jalet
50# External requester should be ok (untested)
51# New syntax for configuration file wrt requesters
52#
53# Revision 1.7  2003/02/09 13:05:43  jalet
54# Internationalization continues...
55#
56# Revision 1.6  2003/02/07 22:00:09  jalet
57# Bad cut&paste
58#
59# Revision 1.5  2003/02/06 23:58:05  jalet
60# repykota should be ok
61#
62# Revision 1.4  2003/02/06 09:19:02  jalet
63# More robust behavior (hopefully) when the user or printer is not managed
64# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
65# printer and/or user not 'yet?' in storage.
66#
67# Revision 1.3  2003/02/05 23:26:22  jalet
68# Incorrect handling of grace delay
69#
70# Revision 1.2  2003/02/05 23:09:20  jalet
71# Name conflict
72#
73# Revision 1.1  2003/02/05 21:28:17  jalet
74# Initial import into CVS
75#
76#
77#
78
79import sys
80import os
81import ConfigParser
82
83class PyKotaConfigError(Exception):
84    """An exception for PyKota config related stuff."""
85    def __init__(self, message = ""):
86        self.message = message
87        Exception.__init__(self, message)
88    def __repr__(self):
89        return self.message
90    __str__ = __repr__
91   
92class PyKotaConfig :
93    """A class to deal with PyKota's configuration."""
94    def __init__(self, directory) :
95        """Reads and checks the configuration file."""
96        self.filename = os.path.join(directory, "pykota.conf")
97        self.config = ConfigParser.ConfigParser()
98        self.config.read([self.filename])
99        self.checkConfiguration()
100       
101    def checkConfiguration(self) :
102        """Checks if configuration is correct.
103       
104           raises PyKotaConfigError in case a problem is detected
105        """
106        validmethods = [ "lazy" ] # TODO add more methods           
107        if self.config.get("global", "method", raw=1).lower() not in validmethods :             
108            raise PyKotaConfigError, _("Option method only supports values in %s") % str(validmethods)
109                       
110    def getPrinterNames(self) :   
111        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
112        return [pname for pname in self.config.sections() if pname != "global"]
113       
114    def getGlobalOption(self, option, ignore=0) :   
115        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
116        try :
117            return self.config.get("global", option, raw=1)
118        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
119            if ignore :
120                return
121            else :
122                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
123               
124    def getPrinterOption(self, printer, option) :   
125        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
126        globaloption = self.getGlobalOption(option, ignore=1)
127        try :
128            return self.config.get(printer, option, raw=1)
129        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
130            if globaloption is not None :
131                return globaloption
132            else :
133                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printer, self.filename)
134       
135    def getStorageBackend(self) :   
136        """Returns the storage backend information as a Python mapping."""       
137        backendinfo = {}
138        for option in [ "storagebackend", "storageserver", \
139                        "storagename", "storageadmin", \
140                        "storageuser", \
141                      ] :
142            backendinfo[option] = self.getGlobalOption(option)
143        for option in [ "storageadminpw", "storageuserpw" ] :   
144            backendinfo[option] = self.getGlobalOption(option, ignore=1)
145        return backendinfo
146       
147    def getLoggingBackend(self) :   
148        """Returns the logging backend information."""
149        validloggers = [ "stderr", "system" ] 
150        logger = self.getGlobalOption("logger").lower()
151        if logger not in validloggers :             
152            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
153        return logger   
154       
155    def getRequesterBackend(self, printer) :   
156        """Returns the requester backend to use for a given printer, with its arguments."""
157        fullrequester = self.getPrinterOption(printer, "requester")
158        try :
159            (requester, args) = [x.strip() for x in fullrequester.split('(', 1)]
160        except ValueError :   
161            raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer)
162        if args.endswith(')') :
163            args = args[:-1]
164        if not args :
165            raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer)
166        validrequesters = [ "snmp", "external" ] # TODO : add more requesters
167        if requester not in validrequesters :
168            raise PyKotaConfigError, _("Option requester for printer %s only supports values in %s") % (printer, str(validrequesters))
169        return (requester, args)
170       
171    def getPrinterPolicy(self, printer) :   
172        """Returns the default policy for the current printer."""
173        validpolicies = [ "ALLOW", "DENY" ]     
174        policy = self.getPrinterOption(printer, "policy").upper()
175        if policy not in validpolicies :
176            raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printer, str(validpolicies))
177        return policy
178       
179    def getSMTPServer(self) :   
180        """Returns the SMTP server to use to send messages to users."""
181        return self.getGlobalOption("smtpserver")
182       
183    def getAdminMail(self, printer) :   
184        """Returns the Email address of the Print Quota Administrator."""
185        return self.getPrinterOption(printer, "adminmail")
186       
187    def getAdmin(self, printer) :   
188        """Returns the full name of the Print Quota Administrator."""
189        return self.getPrinterOption(printer, "admin")
190       
191    def getGraceDelay(self, printer) :   
192        """Returns the grace delay in days."""
193        gd = self.getPrinterOption(printer, "gracedelay")
194        try :
195            return int(gd)
196        except ValueError :   
197            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
Note: See TracBrowser for help on using the browser.