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

Revision 2016, 7.5 kB (checked in by jalet, 19 years ago)

"--format cups" output more resembling CUPS' page_log.
Split into a command line tool and a module, to allow easier coding of
a CGI interface.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • 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
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.1  2005/01/08 17:03:07  jalet
24# "--format cups" output more resembling CUPS' page_log.
25# Split into a command line tool and a module, to allow easier coding of
26# a CGI interface.
27#
28#
29#
30
31import sys
32import os
33import pwd
34from mx import DateTime
35
36try :
37    import jaxml
38except ImportError :   
39    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n")
40    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n")
41    hasJAXML = 0
42else :   
43    hasJAXML = 1
44
45from pykota import version
46from pykota.tool import PyKotaTool, PyKotaToolError, N_
47
48class DumPyKota(PyKotaTool) :       
49    """A class for dumpykota."""
50    validdatatypes = { "history" : N_("History"),
51                       "users" : N_("Users"),
52                       "groups" : N_("Groups"),
53                       "printers" : N_("Printers"),
54                       "upquotas" : N_("Users Print Quotas"),
55                       "gpquotas" : N_("Users Groups Print Quotas"),
56                       "payments" : N_("History of Payments"),
57                       "pmembers" : N_("Printers Groups Membership"), 
58                       "umembers" : N_("Users Groups Membership"),
59                     }
60    validformats = { "csv" : N_("Comma Separated Values"),
61                     "ssv" : N_("Semicolon Separated Values"),
62                     "tsv" : N_("Tabulation Separated Values"),
63                     "xml" : N_("eXtensible Markup Language"),
64                     "cups" : N_("CUPS' page_log"),
65                   } 
66    validfilterkeys = [ "username",
67                        "groupname",
68                        "printername",
69                        "pgroupname",
70                      ]
71    def main(self, arguments, options) :
72        """Print Quota Data Dumper."""
73        if not self.config.isAdmin :
74            raise PyKotaToolError, "%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 PyKotaToolError, _("Invalid value [%s] for --filter command line option, 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 PyKotaToolError, _("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") and (datatype != "history")) :
95            raise PyKotaToolError, _("Invalid modifier [%s] for --format command line option, see help.") % format
96           
97        if (format == "xml") and not hasJAXML :
98            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
99           
100        entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly)   
101        if entries :
102            mustclose = 0   
103            if options["output"].strip() == "-" :   
104                self.outfile = sys.stdout
105            else :   
106                self.outfile = open(options["output"], "w")
107                mustclose = 1
108               
109            retcode = getattr(self, "dump%s" % format.title())(entries, datatype)
110           
111            if mustclose :
112                self.outfile.close()
113               
114            return retcode   
115        return 0
116       
117    def dumpWithSeparator(self, separator, entries) :   
118        """Dumps datas with a separator."""
119        for entry in entries :
120            line = separator.join([ '"%s"' % field for field in entry ])
121            try :
122                self.outfile.write("%s\n" % line)
123            except IOError, msg :   
124                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
125                return -1
126        return 0       
127       
128    def dumpCsv(self, entries, dummy) :   
129        """Dumps datas with a comma as the separator."""
130        return self.dumpWithSeparator(",", entries)
131                           
132    def dumpSsv(self, entries, dummy) :   
133        """Dumps datas with a comma as the separator."""
134        return self.dumpWithSeparator(";", entries)
135                           
136    def dumpTsv(self, entries, dummy) :   
137        """Dumps datas with a comma as the separator."""
138        return self.dumpWithSeparator("\t", entries)
139       
140    def dumpCups(self, entries, dummy) :   
141        """Dumps history datas as CUPS' page_log format."""
142        fieldnames = entries[0]
143        fields = {}
144        for i in range(len(fieldnames)) :
145            fields[fieldnames[i]] = i
146        sortindex = fields["jobdate"]   
147        entries = entries[1:]
148        entries.sort(lambda m,n : cmp(m[sortindex], n[sortindex]))
149        for entry in entries[1:] :   
150            printername = entry[fields["printername"]]
151            username = entry[fields["username"]]
152            jobid = entry[fields["jobid"]]
153            jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]])
154            gmtoffset = jobdate.gmtoffset()
155            jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour)
156            jobsize = entry[fields["jobsize"]] or 0
157            copies = entry[fields["copies"]] or 1
158            hostname = entry[fields["hostname"]] or ""
159            self.outfile.write("%s %s %s [%s] %s %s - %s\n" % (printername, username, jobid, jobdate, jobsize, copies, hostname))
160       
161    def dumpXml(self, entries, datatype) :   
162        """Dumps datas as XML."""
163        x = jaxml.XML_document(encoding="UTF-8")
164        x.pykota(version=version.__version__, author=version.__author__)
165        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
166        headers = entries[0]
167        for entry in entries[1:] :
168            x._push()
169            x.entry()
170            for i in range(len(entry)) :
171                value = str(entry[i])
172                typval = type(entry[i]).__name__
173                try :
174                    value = unicode(value, self.getCharset()).encode("UTF-8")
175                except UnicodeError :   
176                    pass
177                x.attribute(value, type=typval, name=headers[i])
178            x._pop()   
179        x._output(self.outfile)
Note: See TracBrowser for help on using the browser.