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

Revision 2163, 7.3 kB (checked in by jerome, 19 years ago)

Fixed data dumper when dumping history in CUPS' page_log format,
because we only wrote a single line with the job's size on it,
instead of one line per page with the page number on it.

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