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

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

Updated the FSF's address

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[2016]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
[2302]18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
[2016]19#
20# $Id$
21#
[2034]22#
[2016]23
24import sys
25import os
26import pwd
[2264]27from xml.sax import saxutils
28
[2016]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",
[2218]65                        "hostname",
66                        "billingcode",
[2266]67                        "start",
68                        "end",
[2016]69                      ]
[2032]70    def main(self, arguments, options, restricted=1) :
[2016]71        """Print Quota Data Dumper."""
[2032]72        if restricted and not self.config.isAdmin :
[2016]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 :   
[2218]83                    raise PyKotaToolError, _("Invalid filter value [%s], see help.") % filterexp
[2016]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()) \
[2296]93              or ((format == "cups") and ((datatype != "history") or options["sum"])) :
[2016]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           
[2285]99        if options["sum"] and datatype not in ("payments", "history") : 
[2286]100            raise PyKotaToolError, _("Invalid data type [%s] for --sum command line option, see help.") % datatype
[2285]101           
[2218]102        entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly)
[2016]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               
[2295]111            retcode = getattr(self, "dump%s" % format.title())(self.summarizeDatas(entries, datatype, extractonly, options["sum"]), datatype)
[2016]112           
113            if mustclose :
114                self.outfile.close()
115               
116            return retcode   
117        return 0
118       
[2295]119    def summarizeDatas(self, entries, datatype, extractonly, sum=0) :   
[2285]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 :   
[2289]127            headers = entries[0]
128            nbheaders = len(headers)
129            fieldnumber = {}
[2293]130            fieldname = {}
[2289]131            for i in range(nbheaders) :
[2295]132                fieldnumber[headers[i]] = i
133           
[2289]134            if datatype == "payments" :
[2293]135                totalize = [ ("amount", float) ]
[2295]136                keys = [ "username" ]
137            else : # elif datatype == "history"
138                totalize = [ ("jobsize", int), 
139                             ("jobprice", float),
140                             ("jobsizebytes", int),
141                           ]
142                keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ]
[2293]143               
[2295]144            newentries = [ headers ]
145            sortedentries = entries[1:]
146            if keys :
147                # If we have several keys, we can sort only on the first one, because they
148                # will vary the same way.
149                sortedentries.sort(lambda x, y, fnum=fieldnumber[keys[0]] : cmp(x[fnum], y[fnum]))
150            totals = {}
151            for (k, t) in totalize :
152                totals[k] = { "convert" : t, "value" : 0.0 }
153            prevkeys = {}
154            for k in keys :
155                prevkeys[k] = sortedentries[0][fieldnumber[k]]
156            for entry in sortedentries :
157                curval = '-'.join([str(entry[fieldnumber[k]]) for k in keys])
158                prevval = '-'.join([str(prevkeys[k]) for k in keys])
159                if curval != prevval :
160                    summary = [ "*" ] * nbheaders
161                    for k in keys :
162                        summary[fieldnumber[k]] = prevkeys[k]
163                    for k in totals.keys() :   
164                        summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
165                    newentries.append(summary)
166                    for k in totals.keys() :   
167                        totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]])
168                else :   
169                    for k in totals.keys() :   
170                        totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]])
171                for k in keys :
172                    prevkeys[k] = entry[fieldnumber[k]]
173            summary = [ "*" ] * nbheaders
174            for k in keys :
175                summary[fieldnumber[k]] = prevkeys[k]
176            for k in totals.keys() :   
177                summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"])
178            newentries.append(summary)
[2289]179            return newentries
[2285]180           
[2016]181    def dumpWithSeparator(self, separator, entries) :   
182        """Dumps datas with a separator."""
183        for entry in entries :
[2264]184            line = []
185            for value in entry :
186                if type(value).__name__ in ("str", "NoneType") :
187                    line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"'))
188                else :   
189                    line.append(str(value))
[2016]190            try :
[2264]191                self.outfile.write("%s\n" % separator.join(line))
[2016]192            except IOError, msg :   
193                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
194                return -1
195        return 0       
196       
197    def dumpCsv(self, entries, dummy) :   
198        """Dumps datas with a comma as the separator."""
199        return self.dumpWithSeparator(",", entries)
200                           
201    def dumpSsv(self, entries, dummy) :   
202        """Dumps datas with a comma as the separator."""
203        return self.dumpWithSeparator(";", entries)
204                           
205    def dumpTsv(self, entries, dummy) :   
206        """Dumps datas with a comma as the separator."""
207        return self.dumpWithSeparator("\t", entries)
208       
209    def dumpCups(self, entries, dummy) :   
210        """Dumps history datas as CUPS' page_log format."""
211        fieldnames = entries[0]
212        fields = {}
213        for i in range(len(fieldnames)) :
214            fields[fieldnames[i]] = i
215        sortindex = fields["jobdate"]   
216        entries = entries[1:]
[2034]217        entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si]))
[2219]218        for entry in entries :   
[2016]219            printername = entry[fields["printername"]]
220            username = entry[fields["username"]]
221            jobid = entry[fields["jobid"]]
222            jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]])
223            gmtoffset = jobdate.gmtoffset()
224            jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour)
225            jobsize = entry[fields["jobsize"]] or 0
226            copies = entry[fields["copies"]] or 1
227            hostname = entry[fields["hostname"]] or ""
[2217]228            billingcode = entry[fields["billingcode"]] or "-"
[2163]229            for pagenum in range(1, jobsize+1) :
[2217]230                self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname))
[2016]231       
232    def dumpXml(self, entries, datatype) :   
233        """Dumps datas as XML."""
234        x = jaxml.XML_document(encoding="UTF-8")
235        x.pykota(version=version.__version__, author=version.__author__)
236        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
237        headers = entries[0]
238        for entry in entries[1:] :
239            x._push()
240            x.entry()
[2264]241            for (header, value) in zip(headers, entry) :
242                strvalue = str(value)
243                typval = type(value).__name__
244                if header in ("filename", "title", "options", "billingcode") \
245                          and (typval == "str") :
246                    try :
247                        strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8")
248                    except UnicodeError :   
249                        pass
250                    strvalue = saxutils.escape(strvalue, { "'" : "&apos;", \
251                                                           '"' : "&quot;" })
252                x.attribute(strvalue, type=typval, name=header)
[2016]253            x._pop()   
254        x._output(self.outfile)
Note: See TracBrowser for help on using the browser.