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 | |
---|
24 | import sys |
---|
25 | import os |
---|
26 | import pwd |
---|
27 | from xml.sax import saxutils |
---|
28 | |
---|
29 | from mx import DateTime |
---|
30 | |
---|
31 | try : |
---|
32 | import jaxml |
---|
33 | except 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 |
---|
37 | else : |
---|
38 | hasJAXML = 1 |
---|
39 | |
---|
40 | from pykota import version |
---|
41 | from pykota.tool import PyKotaTool, PyKotaToolError, N_ |
---|
42 | |
---|
43 | class 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 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) |
---|
100 | if entries : |
---|
101 | mustclose = 0 |
---|
102 | if options["output"].strip() == "-" : |
---|
103 | self.outfile = sys.stdout |
---|
104 | else : |
---|
105 | self.outfile = open(options["output"], "w") |
---|
106 | mustclose = 1 |
---|
107 | |
---|
108 | retcode = getattr(self, "dump%s" % format.title())(entries, datatype) |
---|
109 | |
---|
110 | if mustclose : |
---|
111 | self.outfile.close() |
---|
112 | |
---|
113 | return retcode |
---|
114 | return 0 |
---|
115 | |
---|
116 | def dumpWithSeparator(self, separator, entries) : |
---|
117 | """Dumps datas with a separator.""" |
---|
118 | for entry in entries : |
---|
119 | line = [] |
---|
120 | for value in entry : |
---|
121 | if type(value).__name__ in ("str", "NoneType") : |
---|
122 | line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"')) |
---|
123 | else : |
---|
124 | line.append(str(value)) |
---|
125 | try : |
---|
126 | self.outfile.write("%s\n" % separator.join(line)) |
---|
127 | except IOError, msg : |
---|
128 | sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg)) |
---|
129 | return -1 |
---|
130 | return 0 |
---|
131 | |
---|
132 | def dumpCsv(self, entries, dummy) : |
---|
133 | """Dumps datas with a comma as the separator.""" |
---|
134 | return self.dumpWithSeparator(",", entries) |
---|
135 | |
---|
136 | def dumpSsv(self, entries, dummy) : |
---|
137 | """Dumps datas with a comma as the separator.""" |
---|
138 | return self.dumpWithSeparator(";", entries) |
---|
139 | |
---|
140 | def dumpTsv(self, entries, dummy) : |
---|
141 | """Dumps datas with a comma as the separator.""" |
---|
142 | return self.dumpWithSeparator("\t", entries) |
---|
143 | |
---|
144 | def dumpCups(self, entries, dummy) : |
---|
145 | """Dumps history datas as CUPS' page_log format.""" |
---|
146 | fieldnames = entries[0] |
---|
147 | fields = {} |
---|
148 | for i in range(len(fieldnames)) : |
---|
149 | fields[fieldnames[i]] = i |
---|
150 | sortindex = fields["jobdate"] |
---|
151 | entries = entries[1:] |
---|
152 | entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si])) |
---|
153 | for entry in entries : |
---|
154 | printername = entry[fields["printername"]] |
---|
155 | username = entry[fields["username"]] |
---|
156 | jobid = entry[fields["jobid"]] |
---|
157 | jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]]) |
---|
158 | gmtoffset = jobdate.gmtoffset() |
---|
159 | jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour) |
---|
160 | jobsize = entry[fields["jobsize"]] or 0 |
---|
161 | copies = entry[fields["copies"]] or 1 |
---|
162 | hostname = entry[fields["hostname"]] or "" |
---|
163 | billingcode = entry[fields["billingcode"]] or "-" |
---|
164 | for pagenum in range(1, jobsize+1) : |
---|
165 | self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname)) |
---|
166 | |
---|
167 | def dumpXml(self, entries, datatype) : |
---|
168 | """Dumps datas as XML.""" |
---|
169 | x = jaxml.XML_document(encoding="UTF-8") |
---|
170 | x.pykota(version=version.__version__, author=version.__author__) |
---|
171 | x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype) |
---|
172 | headers = entries[0] |
---|
173 | for entry in entries[1:] : |
---|
174 | x._push() |
---|
175 | x.entry() |
---|
176 | for (header, value) in zip(headers, entry) : |
---|
177 | strvalue = str(value) |
---|
178 | typval = type(value).__name__ |
---|
179 | if header in ("filename", "title", "options", "billingcode") \ |
---|
180 | and (typval == "str") : |
---|
181 | try : |
---|
182 | strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8") |
---|
183 | except UnicodeError : |
---|
184 | pass |
---|
185 | strvalue = saxutils.escape(strvalue, { "'" : "'", \ |
---|
186 | '"' : """ }) |
---|
187 | x.attribute(strvalue, type=typval, name=header) |
---|
188 | x._pop() |
---|
189 | x._output(self.outfile) |
---|