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

Revision 2567, 11.3 kB (checked in by jerome, 19 years ago)

Now the data dumper refuse to dump into the cups format if the datatype
is not 'history'.

  • 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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, PyKotaCommandLineError, 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                       "billingcodes" : N_("Billing Codes"),
55                     }
56    validformats = { "csv" : N_("Comma Separated Values"),
57                     "ssv" : N_("Semicolon Separated Values"),
58                     "tsv" : N_("Tabulation Separated Values"),
59                     "xml" : N_("eXtensible Markup Language"),
60                     "cups" : N_("CUPS' page_log"),
61                   } 
62    validfilterkeys = [ "username",
63                        "groupname",
64                        "printername",
65                        "pgroupname",
66                        "hostname",
67                        "billingcode",
68                        "start",
69                        "end",
70                      ]
71    def main(self, arguments, options, restricted=1) :
72        """Print Quota Data Dumper."""
73        if restricted and not self.config.isAdmin :
74            raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
75           
76        extractonly = {}
77        for filterexp in arguments :
78            if filterexp.strip() :
79                try :
80                    (filterkey, filtervalue) = [part.strip() for part in filterexp.split("=")]
81                    if filterkey not in self.validfilterkeys :
82                        raise ValueError               
83                except ValueError :   
84                    raise PyKotaCommandLineError, _("Invalid filter value [%s], see help.") % filterexp
85                else :   
86                    extractonly.update({ filterkey : filtervalue })
87           
88        datatype = options["data"]
89        if datatype not in self.validdatatypes.keys() :
90            raise PyKotaCommandLineError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype
91                   
92        format = options["format"]
93        if (format not in self.validformats.keys()) \
94           or ((format == "cups") \
95              and ((datatype != "history") or options["sum"])) :
96            raise PyKotaCommandLineError, _("Invalid modifier [%s] for --format command line option, see help.") % format
97           
98        if (format == "xml") and not hasJAXML :
99            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
100           
101        if options["sum"] and datatype not in ("payments", "history") : 
102            raise PyKotaCommandLineError, _("Invalid data type [%s] for --sum command line option, see help.") % datatype
103           
104        entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly)
105        if entries :
106            mustclose = 0   
107            if options["output"].strip() == "-" :   
108                self.outfile = sys.stdout
109            else :   
110                self.outfile = open(options["output"], "w")
111                mustclose = 1
112               
113            retcode = getattr(self, "dump%s" % format.title())(self.summarizeDatas(entries, datatype, extractonly, options["sum"]), datatype)
114           
115            if mustclose :
116                self.outfile.close()
117               
118            return retcode   
119        return 0
120       
121    def summarizeDatas(self, entries, datatype, extractonly, sum=0) :   
122        """Transforms the datas into a summarized view (with totals).
123       
124           If sum is false, returns the entries unchanged.
125        """   
126        if not sum :
127            return entries
128        else :   
129            headers = entries[0]
130            nbheaders = len(headers)
131            fieldnumber = {}
132            fieldname = {}
133            for i in range(nbheaders) :
134                fieldnumber[headers[i]] = i
135           
136            if datatype == "payments" :
137                totalize = [ ("amount", float) ]
138                keys = [ "username" ]
139            else : # elif datatype == "history"
140                totalize = [ ("jobsize", int), 
141                             ("jobprice", float),
142                             ("jobsizebytes", int),
143                           ]
144                keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ]
145               
146            newentries = [ headers ]
147            sortedentries = entries[1:]
148            if keys :
149                # If we have several keys, we can sort only on the first one, because they
150                # will vary the same way.
151                sortedentries.sort(lambda x, y, fnum=fieldnumber[keys[0]] : cmp(x[fnum], y[fnum]))
152            totals = {}
153            for (k, t) in totalize :
154                totals[k] = { "convert" : t, "value" : 0.0 }
155            prevkeys = {}
156            for k in keys :
157                prevkeys[k] = sortedentries[0][fieldnumber[k]]
158            for entry in sortedentries :
159                curval = '-'.join([str(entry[fieldnumber[k]]) for k in keys])
160                prevval = '-'.join([str(prevkeys[k]) for k in keys])
161                if curval != prevval :
162                    summary = [ "*" ] * nbheaders
163                    for k in keys :
164                        summary[fieldnumber[k]] = prevkeys[k]
165                    for k in totals.keys() :   
166                        summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
167                    newentries.append(summary)
168                    for k in totals.keys() :   
169                        totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]])
170                else :   
171                    for k in totals.keys() :   
172                        totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]])
173                for k in keys :
174                    prevkeys[k] = entry[fieldnumber[k]]
175            summary = [ "*" ] * nbheaders
176            for k in keys :
177                summary[fieldnumber[k]] = prevkeys[k]
178            for k in totals.keys() :   
179                summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
180            newentries.append(summary)
181            return newentries
182           
183    def dumpWithSeparator(self, separator, entries) :   
184        """Dumps datas with a separator."""
185        for entry in entries :
186            line = []
187            for value in entry :
188                if type(value).__name__ in ("str", "NoneType") :
189                    line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"'))
190                else :   
191                    line.append(str(value))
192            try :
193                self.outfile.write("%s\n" % separator.join(line))
194            except IOError, msg :   
195                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
196                return -1
197        return 0       
198       
199    def dumpCsv(self, entries, dummy) :   
200        """Dumps datas with a comma as the separator."""
201        return self.dumpWithSeparator(",", entries)
202                           
203    def dumpSsv(self, entries, dummy) :   
204        """Dumps datas with a comma as the separator."""
205        return self.dumpWithSeparator(";", entries)
206                           
207    def dumpTsv(self, entries, dummy) :   
208        """Dumps datas with a comma as the separator."""
209        return self.dumpWithSeparator("\t", entries)
210       
211    def dumpCups(self, entries, dummy) :   
212        """Dumps history datas as CUPS' page_log format."""
213        fieldnames = entries[0]
214        fields = {}
215        for i in range(len(fieldnames)) :
216            fields[fieldnames[i]] = i
217        sortindex = fields["jobdate"]   
218        entries = entries[1:]
219        entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si]))
220        for entry in entries :   
221            printername = entry[fields["printername"]]
222            username = entry[fields["username"]]
223            jobid = entry[fields["jobid"]]
224            jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]])
225            gmtoffset = jobdate.gmtoffset()
226            jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour)
227            jobsize = entry[fields["jobsize"]] or 0
228            copies = entry[fields["copies"]] or 1
229            hostname = entry[fields["hostname"]] or ""
230            billingcode = entry[fields["billingcode"]] or "-"
231            for pagenum in range(1, jobsize+1) :
232                self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname))
233       
234    def dumpXml(self, entries, datatype) :   
235        """Dumps datas as XML."""
236        x = jaxml.XML_document(encoding="UTF-8")
237        x.pykota(version=version.__version__, author=version.__author__)
238        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
239        headers = entries[0]
240        for entry in entries[1:] :
241            x._push()
242            x.entry()
243            for (header, value) in zip(headers, entry) :
244                strvalue = str(value)
245                typval = type(value).__name__
246                if header in ("filename", "title", "options", "billingcode") \
247                          and (typval == "str") :
248                    try :
249                        strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8")
250                    except UnicodeError :   
251                        pass
252                    strvalue = saxutils.escape(strvalue, { "'" : "&apos;", \
253                                                           '"' : "&quot;" })
254                x.attribute(strvalue, type=typval, name=header)
255            x._pop()   
256        x._output(self.outfile)
Note: See TracBrowser for help on using the browser.