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

Revision 2285, 8.8 kB (checked in by jerome, 19 years ago)

More work done on the --sum command line option, still not finished though...

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