root / pykota / trunk / pykota / dumper.py @ 2139

Revision 2139, 7.9 kB (checked in by jerome, 19 years ago)

Added the Log keyword property

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision Log
Line 
1# PyKota Print Quota Data Dumper
2#
3# PyKota - Print Quotas for CUPS and LPRng
4#
5# (c) 2003-2004 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.3  2005/01/19 09:00:54  jalet
24# Small fix for Python2.1 and variables scopes
25#
26# Revision 1.2  2005/01/19 08:49:41  jalet
27# Now dumpykota.cgi behaves like printquota.cgi wrt the REMOTE_USER environment
28# variables if the script is username+password protected.
29# Small fix in printquota.cgi wrt ldap auth with Apache : the workaround was
30# not used everywhere.
31#
32# Revision 1.1  2005/01/08 17:03:07  jalet
33# "--format cups" output more resembling CUPS' page_log.
34# Split into a command line tool and a module, to allow easier coding of
35# a CGI interface.
36#
37#
38#
39
40import sys
41import os
42import pwd
43from mx import DateTime
44
45try :
46    import jaxml
47except ImportError :   
48    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n")
49    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n")
50    hasJAXML = 0
51else :   
52    hasJAXML = 1
53
54from pykota import version
55from pykota.tool import PyKotaTool, PyKotaToolError, N_
56
57class DumPyKota(PyKotaTool) :       
58    """A class for dumpykota."""
59    validdatatypes = { "history" : N_("History"),
60                       "users" : N_("Users"),
61                       "groups" : N_("Groups"),
62                       "printers" : N_("Printers"),
63                       "upquotas" : N_("Users Print Quotas"),
64                       "gpquotas" : N_("Users Groups Print Quotas"),
65                       "payments" : N_("History of Payments"),
66                       "pmembers" : N_("Printers Groups Membership"), 
67                       "umembers" : N_("Users Groups Membership"),
68                     }
69    validformats = { "csv" : N_("Comma Separated Values"),
70                     "ssv" : N_("Semicolon Separated Values"),
71                     "tsv" : N_("Tabulation Separated Values"),
72                     "xml" : N_("eXtensible Markup Language"),
73                     "cups" : N_("CUPS' page_log"),
74                   } 
75    validfilterkeys = [ "username",
76                        "groupname",
77                        "printername",
78                        "pgroupname",
79                      ]
80    def main(self, arguments, options, restricted=1) :
81        """Print Quota Data Dumper."""
82        if restricted and not self.config.isAdmin :
83            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
84           
85        extractonly = {}
86        for filterexp in arguments :
87            if filterexp.strip() :
88                try :
89                    (filterkey, filtervalue) = [part.strip() for part in filterexp.split("=")]
90                    if filterkey not in self.validfilterkeys :
91                        raise ValueError               
92                except ValueError :   
93                    raise PyKotaToolError, _("Invalid value [%s] for --filter command line option, see help.") % filterexp
94                else :   
95                    extractonly.update({ filterkey : filtervalue })
96           
97        datatype = options["data"]
98        if datatype not in self.validdatatypes.keys() :
99            raise PyKotaToolError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype
100                   
101        format = options["format"]
102        if (format not in self.validformats.keys()) \
103              or ((format == "cups") and (datatype != "history")) :
104            raise PyKotaToolError, _("Invalid modifier [%s] for --format command line option, see help.") % format
105           
106        if (format == "xml") and not hasJAXML :
107            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
108           
109        entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly)   
110        if entries :
111            mustclose = 0   
112            if options["output"].strip() == "-" :   
113                self.outfile = sys.stdout
114            else :   
115                self.outfile = open(options["output"], "w")
116                mustclose = 1
117               
118            retcode = getattr(self, "dump%s" % format.title())(entries, datatype)
119           
120            if mustclose :
121                self.outfile.close()
122               
123            return retcode   
124        return 0
125       
126    def dumpWithSeparator(self, separator, entries) :   
127        """Dumps datas with a separator."""
128        for entry in entries :
129            line = separator.join([ '"%s"' % field for field in entry ])
130            try :
131                self.outfile.write("%s\n" % line)
132            except IOError, msg :   
133                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
134                return -1
135        return 0       
136       
137    def dumpCsv(self, entries, dummy) :   
138        """Dumps datas with a comma as the separator."""
139        return self.dumpWithSeparator(",", entries)
140                           
141    def dumpSsv(self, entries, dummy) :   
142        """Dumps datas with a comma as the separator."""
143        return self.dumpWithSeparator(";", entries)
144                           
145    def dumpTsv(self, entries, dummy) :   
146        """Dumps datas with a comma as the separator."""
147        return self.dumpWithSeparator("\t", entries)
148       
149    def dumpCups(self, entries, dummy) :   
150        """Dumps history datas as CUPS' page_log format."""
151        fieldnames = entries[0]
152        fields = {}
153        for i in range(len(fieldnames)) :
154            fields[fieldnames[i]] = i
155        sortindex = fields["jobdate"]   
156        entries = entries[1:]
157        entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si]))
158        for entry in entries[1:] :   
159            printername = entry[fields["printername"]]
160            username = entry[fields["username"]]
161            jobid = entry[fields["jobid"]]
162            jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]])
163            gmtoffset = jobdate.gmtoffset()
164            jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour)
165            jobsize = entry[fields["jobsize"]] or 0
166            copies = entry[fields["copies"]] or 1
167            hostname = entry[fields["hostname"]] or ""
168            self.outfile.write("%s %s %s [%s] %s %s - %s\n" % (printername, username, jobid, jobdate, jobsize, copies, hostname))
169       
170    def dumpXml(self, entries, datatype) :   
171        """Dumps datas as XML."""
172        x = jaxml.XML_document(encoding="UTF-8")
173        x.pykota(version=version.__version__, author=version.__author__)
174        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
175        headers = entries[0]
176        for entry in entries[1:] :
177            x._push()
178            x.entry()
179            for i in range(len(entry)) :
180                value = str(entry[i])
181                typval = type(entry[i]).__name__
182                try :
183                    value = unicode(value, self.getCharset()).encode("UTF-8")
184                except UnicodeError :   
185                    pass
186                x.attribute(value, type=typval, name=headers[i])
187            x._pop()   
188        x._output(self.outfile)
Note: See TracBrowser for help on using the browser.