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

Revision 2294, 11.2 kB (checked in by jerome, 19 years ago)

Adds a pass to use original values for uninteresting fields

  • 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 data type [%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            headers = entries[0]
128            nbheaders = len(headers)
129            fieldnumber = {}
130            fieldname = {}
131            for i in range(nbheaders) :
132                name = headers[i]
133                fieldnumber[name] = i
134                fieldname[i] = name
135               
136            if datatype == "payments" :
137                totalize = [ ("amount", float) ]
138                ignored = [ "date" ]
139                key = "username"
140               
141                fnkey = fieldnumber[key]
142                newentries = [ headers ]
143                sortedentries = entries[1:]
144                sortedentries.sort(lambda x, y, fnum=fnkey : cmp(x[fnum], y[fnum]))
145                totals = {}
146                for (k, t) in totalize :
147                    totals[k] = { "convert" : t, "value" : 0.0 }
148                prevkey = sortedentries[0][fnkey]
149                for entry in sortedentries :
150                    if entry[fnkey] != prevkey :
151                        summary = [None] * nbheaders
152                        summary[fnkey] = prevkey
153                        for ignore in ignored :
154                            summary[fieldnumber[ignore]] = '*'
155                        for k in totals.keys() :   
156                            summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
157                        for i in range(nbheaders) :   
158                            if summary[i] is None :
159                                summary[i] = entry[i]
160                        newentries.append(summary)
161                        for k in totals.keys() :   
162                            totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]])
163                    else :   
164                        for k in totals.keys() :   
165                            totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]])
166                    prevkey = entry[fnkey]   
167                summary = [None] * nbheaders
168                summary[fnkey] = prevkey
169                for ignore in ignored :
170                    summary[fieldnumber[ignore]] = '*'
171                for k in totals.keys() :   
172                    summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
173                for i in range(nbheaders) :   
174                    if summary[i] is None :
175                        summary[i] = entry[i]
176                newentries.append(summary)
177            elif datatype == "history" :
178                newentries = entries # Fake this for now
179            else :
180                raise PyKotaToolError, _("Summarizing is not implemented for the [%s] data type, sorry.") % datatype
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.