1 | #! /usr/bin/env python |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | |
---|
4 | # PyKotIcon - Windows System Tray Icon for PyKota |
---|
5 | # |
---|
6 | # (c) 2003-2004 Jerome Alet <alet@librelogiciel.com> |
---|
7 | # This program is free software; you can redistribute it and/or modify |
---|
8 | # it under the terms of the GNU General Public License as published by |
---|
9 | # the Free Software Foundation; either version 2 of the License, or |
---|
10 | # (at your option) any later version. |
---|
11 | # |
---|
12 | # This program is distributed in the hope that it will be useful, |
---|
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
15 | # GNU General Public License for more details. |
---|
16 | # |
---|
17 | # You should have received a copy of the GNU General Public License |
---|
18 | # along with this program; if not, write to the Free Software |
---|
19 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. |
---|
20 | # |
---|
21 | # $Id$ |
---|
22 | # |
---|
23 | # |
---|
24 | |
---|
25 | import sys |
---|
26 | import os |
---|
27 | import urllib |
---|
28 | import urllib2 |
---|
29 | import locale |
---|
30 | import gettext |
---|
31 | |
---|
32 | if sys.platform == "win32" : |
---|
33 | isWindows = 1 |
---|
34 | try : |
---|
35 | import win32api |
---|
36 | import win32net |
---|
37 | import win32netcon |
---|
38 | except ImportError : |
---|
39 | raise ImportError, "Mark Hammond's Win32 Extensions are missing. Please install them." |
---|
40 | else : |
---|
41 | isWindows = 0 |
---|
42 | import pwd |
---|
43 | |
---|
44 | try : |
---|
45 | import wxPython.wx |
---|
46 | import wx |
---|
47 | import wx.grid as gridlib |
---|
48 | hasWxPython = 1 |
---|
49 | except ImportError : |
---|
50 | hasWxPython = 0 |
---|
51 | raise ImportError, "wxPython for Windows is missing. Please install it." |
---|
52 | |
---|
53 | DUMPYKOTA_URL = "http://cgi.librelogiciel.com/cgi-bin/dumpykota.cgi" |
---|
54 | |
---|
55 | def getCurrentUserName() : |
---|
56 | """Retrieves the current user's name.""" |
---|
57 | if isWindows : |
---|
58 | return win32api.GetUserName() |
---|
59 | else : |
---|
60 | try : |
---|
61 | return pwd.getpwuid(os.geteuid())[0] |
---|
62 | except : |
---|
63 | return "** Unknown **" |
---|
64 | |
---|
65 | class Printer : |
---|
66 | """A class for PyKota Printers.""" |
---|
67 | def __init__(self, printername, priceperpage, priceperjob): |
---|
68 | """Initialize printer datas.""" |
---|
69 | self.PrinterName = printername |
---|
70 | try : |
---|
71 | self.PricePerPage = float(priceperpage) |
---|
72 | except (ValueError, TypeError) : |
---|
73 | self.PricePerPage = 0.0 |
---|
74 | try : |
---|
75 | self.PricePerJob = float(priceperjob) |
---|
76 | except (ValueError, TypeError) : |
---|
77 | self.PricePerJob = 0.0 |
---|
78 | |
---|
79 | class UserQuota : |
---|
80 | """A class for PyKota User Print Quota entries.""" |
---|
81 | def __init__(self, printername, pagecount, softlimit, hardlimit, datelimit): |
---|
82 | """Initialize user print quota datas.""" |
---|
83 | self.PrinterName = printername |
---|
84 | try : |
---|
85 | self.PageCounter = int(pagecount) |
---|
86 | except (ValueError, TypeError) : |
---|
87 | self.PageCounter = 0 |
---|
88 | try : |
---|
89 | self.SoftLimit = int(softlimit) |
---|
90 | except (ValueError, TypeError) : |
---|
91 | self.SoftLimit = None |
---|
92 | try : |
---|
93 | self.HardLimit = int(hardlimit) |
---|
94 | except (ValueError, TypeError) : |
---|
95 | self.HardLimit = None |
---|
96 | self.DateLimit = datelimit |
---|
97 | |
---|
98 | class User : |
---|
99 | """A class for PyKota users.""" |
---|
100 | def __init__(self, username, userinfo, userquotas, printers) : |
---|
101 | """Initialize user datas.""" |
---|
102 | self.UserName = username |
---|
103 | self.LimitBy = userinfo["limitby"][0].lower() |
---|
104 | try : |
---|
105 | self.Balance = float(userinfo["balance"][0]) |
---|
106 | except (ValueError, TypeError) : |
---|
107 | self.Balance = 0.0 |
---|
108 | try : |
---|
109 | self.LifeTimePaid = float(userinfo["lifetimepaid"][0]) |
---|
110 | except (ValueError, TypeError) : |
---|
111 | self.LifeTimePaid = 0.0 |
---|
112 | self.Printers = {} |
---|
113 | self.Quotas = {} |
---|
114 | for i in range(len(userquotas["printername"])) : |
---|
115 | printername = userquotas["printername"][i] |
---|
116 | try : |
---|
117 | pindex = printers["printername"].index(printername) |
---|
118 | except (ValueError, KeyError) : |
---|
119 | pass |
---|
120 | else : |
---|
121 | self.Printers[printername] = Printer(printername, \ |
---|
122 | printers["priceperpage"][pindex],\ |
---|
123 | printers["priceperjob"][pindex]) |
---|
124 | pagecounter = userquotas["pagecounter"][i] |
---|
125 | softlimit = userquotas["softlimit"][i] |
---|
126 | hardlimit = userquotas["hardlimit"][i] |
---|
127 | datelimit = userquotas["datelimit"][i] |
---|
128 | self.Quotas[printername] = UserQuota(printername, pagecounter, \ |
---|
129 | softlimit, hardlimit, \ |
---|
130 | datelimit) |
---|
131 | |
---|
132 | class CGINetworkInterface : |
---|
133 | """A class for all network interactions.""" |
---|
134 | def __init__(self, cgiurl, authname=None, authpw=None) : |
---|
135 | """Initialize CGI connection datas.""" |
---|
136 | self.cgiurl = cgiurl |
---|
137 | self.authname = authname |
---|
138 | self.authpw = authpw |
---|
139 | |
---|
140 | def retrieveDatas(self, arguments, fieldnames) : |
---|
141 | """Retrieve datas from the CGI script.""" |
---|
142 | args = { "report" : 1, |
---|
143 | "format" : "csv", |
---|
144 | } |
---|
145 | args.update(arguments) |
---|
146 | answer = {} |
---|
147 | try : |
---|
148 | url = "%s?%s" % (self.cgiurl, urllib.urlencode(args)) |
---|
149 | u = urllib2.urlopen(url) |
---|
150 | lines = u.readlines() |
---|
151 | except IOError, msg : |
---|
152 | raise IOError, _("Unable to retrieve %s : %s") % (url, msg) |
---|
153 | else : |
---|
154 | u.close() |
---|
155 | try : |
---|
156 | lines = [ line.strip().split(",") for line in lines ] |
---|
157 | fields = [field[1:-1] for field in lines[0]] |
---|
158 | indices = [fields.index(fname) for fname in fieldnames] |
---|
159 | answer = dict([ (fieldname, \ |
---|
160 | [ line[fields.index(fieldname)][1:-1] \ |
---|
161 | for line in lines[1:] ]) \ |
---|
162 | for fieldname in fieldnames ]) |
---|
163 | except : |
---|
164 | raise ValueError, _("Invalid datas retrieved from %s") % url |
---|
165 | return answer |
---|
166 | |
---|
167 | def getPrinters(self) : |
---|
168 | """Retrieve the printer's names.""" |
---|
169 | arguments = { "report" : 1, |
---|
170 | "format" : "csv", |
---|
171 | "datatype" : "printers", |
---|
172 | } |
---|
173 | return self.retrieveDatas(arguments, ["printername", "priceperpage", \ |
---|
174 | "priceperjob"]) |
---|
175 | |
---|
176 | def getUser(self, username) : |
---|
177 | """Retrieve the user's information.""" |
---|
178 | arguments = { "datatype" : "users", |
---|
179 | "filter" : "username=%s" % username, |
---|
180 | } |
---|
181 | return self.retrieveDatas(arguments, ("limitby", "balance", \ |
---|
182 | "lifetimepaid")) |
---|
183 | |
---|
184 | def getUserPQuotas(self, username) : |
---|
185 | """Retrieve the user's print quota information.""" |
---|
186 | arguments = { "datatype" : "upquotas", |
---|
187 | "filter" : "username=%s" % username, |
---|
188 | } |
---|
189 | return self.retrieveDatas(arguments, ("printername", "pagecounter", \ |
---|
190 | "softlimit", "hardlimit", \ |
---|
191 | "datelimit")) |
---|
192 | |
---|
193 | def getUserInfo(self, username) : |
---|
194 | """Retrieves the user account and quota information.""" |
---|
195 | info = self.getUser(username) |
---|
196 | if info : |
---|
197 | quotas = self.getUserPQuotas(username) |
---|
198 | return User(username, info, \ |
---|
199 | self.getUserPQuotas(username), \ |
---|
200 | self.getPrinters()) |
---|
201 | |
---|
202 | class PyKotIconGrid(gridlib.Grid) : |
---|
203 | """A class for user print quota entries.""" |
---|
204 | def __init__(self, parent, user) : |
---|
205 | gridlib.Grid.__init__(self, parent, -1) |
---|
206 | if user.LimitBy == "balance" : |
---|
207 | nbcols = 3 |
---|
208 | else : |
---|
209 | nbcols = 4 |
---|
210 | self.CreateGrid(len(user.Quotas.keys()), nbcols) |
---|
211 | self.EnableEditing(False) |
---|
212 | if user.LimitBy == "balance" : |
---|
213 | self.SetColLabelValue(0, _("Page Counter")) |
---|
214 | self.SetColLabelValue(1, _("Price per Page")) |
---|
215 | self.SetColLabelValue(2, _("Price per Job")) |
---|
216 | attr = gridlib.GridCellAttr() |
---|
217 | attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE) |
---|
218 | attr.SetReadOnly(True) |
---|
219 | colour = wx.GREEN |
---|
220 | if user.Balance <= 0.0 : |
---|
221 | colour = wx.RED |
---|
222 | attr.SetBackgroundColour(colour) |
---|
223 | self.SetColAttr(0, attr) |
---|
224 | attr = gridlib.GridCellAttr() |
---|
225 | attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE) |
---|
226 | attr.SetReadOnly(True) |
---|
227 | self.SetColAttr(1, attr) |
---|
228 | self.SetColAttr(2, attr) |
---|
229 | i = 0 |
---|
230 | for printername in user.Printers.keys() : |
---|
231 | printer = user.Printers[printername] |
---|
232 | quota = user.Quotas[printername] |
---|
233 | self.SetRowLabelValue(i, printername) |
---|
234 | self.SetCellValue(i, 0, str(quota.PageCounter)) |
---|
235 | self.SetCellValue(i, 1, str(printer.PricePerPage)) |
---|
236 | self.SetCellValue(i, 2, str(printer.PricePerJob)) |
---|
237 | i += 1 |
---|
238 | else : |
---|
239 | self.SetColLabelValue(0, _("Page Counter")) |
---|
240 | self.SetColLabelValue(1, _("Soft Limit")) |
---|
241 | self.SetColLabelValue(2, _("Hard Limit")) |
---|
242 | self.SetColLabelValue(3, _("Date Limit")) |
---|
243 | attr = gridlib.GridCellAttr() |
---|
244 | attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE) |
---|
245 | attr.SetReadOnly(True) |
---|
246 | self.SetColAttr(0, attr) |
---|
247 | attr = gridlib.GridCellAttr() |
---|
248 | attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE) |
---|
249 | attr.SetReadOnly(True) |
---|
250 | self.SetColAttr(1, attr) |
---|
251 | self.SetColAttr(2, attr) |
---|
252 | self.SetColAttr(3, attr) |
---|
253 | i = 0 |
---|
254 | for printername in user.Quotas.keys() : |
---|
255 | quota = user.Quotas[printername] |
---|
256 | self.SetRowLabelValue(i, printername) |
---|
257 | self.SetCellValue(i, 0, str(quota.PageCounter)) |
---|
258 | self.SetCellValue(i, 1, str(quota.SoftLimit)) |
---|
259 | self.SetCellValue(i, 2, str(quota.HardLimit)) |
---|
260 | self.SetCellValue(i, 3, str(quota.DateLimit)) |
---|
261 | colour = wx.GREEN |
---|
262 | if quota.SoftLimit is not None : |
---|
263 | if quota.PageCounter >= quota.SoftLimit : |
---|
264 | colour = wx.RED |
---|
265 | elif quota.HardLimit is not None : |
---|
266 | if quota.PageCounter >= quota.HardLimit : |
---|
267 | colour = wx.RED |
---|
268 | self.SetCellBackgroundColour(i, 0, colour) |
---|
269 | i += 1 |
---|
270 | self.AutoSize() |
---|
271 | |
---|
272 | class PyKotIcon(wxPython.wx.wxFrame): |
---|
273 | """Main class.""" |
---|
274 | def __init__(self, parent, id): |
---|
275 | wxPython.wx.wxFrame.__init__(self, parent, -1, \ |
---|
276 | _("PyKota Print Quota for user %s") % getCurrentUserName(), \ |
---|
277 | size = (460, -1), \ |
---|
278 | style = wxPython.wx.wxDEFAULT_FRAME_STYLE \ |
---|
279 | | wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE) |
---|
280 | self.greenicon = wxPython.wx.wxIcon(os.path.join("..", "icons", "pykoticon-green.ico"), \ |
---|
281 | wxPython.wx.wxBITMAP_TYPE_ICO) |
---|
282 | self.redicon = wxPython.wx.wxIcon(os.path.join("..", "icons", "pykoticon-red.ico"), \ |
---|
283 | wxPython.wx.wxBITMAP_TYPE_ICO) |
---|
284 | self.SetIcon(self.greenicon) |
---|
285 | |
---|
286 | self.tbicon = wxPython.wx.wxTaskBarIcon() |
---|
287 | self.tbicon.SetIcon(self.greenicon, "PyKotIcon") |
---|
288 | |
---|
289 | wxPython.wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate) |
---|
290 | wxPython.wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu) |
---|
291 | wxPython.wx.EVT_ICONIZE(self, self.OnIconify) |
---|
292 | |
---|
293 | self.TBMENU_RESTORE = wx.NewId() |
---|
294 | self.TBMENU_CLOSE = wx.NewId() |
---|
295 | wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \ |
---|
296 | self.OnTaskBarActivate) |
---|
297 | wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \ |
---|
298 | self.OnTaskBarClose) |
---|
299 | self.menu = wxPython.wx.wxMenu() |
---|
300 | self.menu.Append(self.TBMENU_RESTORE, _("Show Print Quota")) |
---|
301 | self.menu.Append(self.TBMENU_CLOSE, _("Quit")) |
---|
302 | |
---|
303 | wxPython.wx.EVT_CLOSE(self, self.OnClose) |
---|
304 | |
---|
305 | self.TBTIMER = wx.NewId() |
---|
306 | self.chrono = wxPython.wx.wxTimer(self, self.TBTIMER) |
---|
307 | wxPython.wx.EVT_TIMER(self, self.TBTIMER, self.OnChronoTimer) |
---|
308 | |
---|
309 | self.User = None |
---|
310 | self.networkInterface = CGINetworkInterface(DUMPYKOTA_URL) |
---|
311 | self.inTimer = False |
---|
312 | self.chrono.Start(250) # first time in 0.25 second |
---|
313 | |
---|
314 | def OnChronoTimer(self, event) : |
---|
315 | """Retrieves user's data quota information.""" |
---|
316 | # we stop it there, needed because we want to |
---|
317 | # change the delay the first time. |
---|
318 | self.chrono.Stop() |
---|
319 | if self.inTimer is False : # avoids re-entrance |
---|
320 | self.inTimer = True |
---|
321 | self.User = self.networkInterface.getUserInfo(getCurrentUserName()) |
---|
322 | if self.User.LimitBy == "balance" : |
---|
323 | if self.User.Balance <= 0.0 : |
---|
324 | self.tbicon.SetIcon(self.redicon, "PyKotIcon") |
---|
325 | else : |
---|
326 | self.tbicon.SetIcon(self.greenicon, "PyKotIcon") |
---|
327 | else : |
---|
328 | isRed = False |
---|
329 | for q in self.User.Quotas.keys() : |
---|
330 | quota = self.User.Quotas[q] |
---|
331 | if quota.SoftLimit is not None : |
---|
332 | if quota.PageCounter >= quota.SoftLimit : |
---|
333 | isRed = True |
---|
334 | break |
---|
335 | elif quota.HardLimit is not None : |
---|
336 | if quota.PageCounter >= quota.HardLimit : |
---|
337 | isRed = True |
---|
338 | break |
---|
339 | if isRed is True : |
---|
340 | self.tbicon.SetIcon(self.redicon, "PyKotIcon") |
---|
341 | else : |
---|
342 | self.tbicon.SetIcon(self.greenicon, "PyKotIcon") |
---|
343 | if hasattr(self, "quotasgrid") : |
---|
344 | self.quotasgrid.Close() |
---|
345 | self.quotasgrid.Destroy() |
---|
346 | del self.quotasgrid |
---|
347 | self.quotasgrid = PyKotIconGrid(self, self.User) |
---|
348 | self.inTimer = False |
---|
349 | # Now we want it every 3 minutes |
---|
350 | #self.chrono.Start(1000 * 60 * 3) # every 3 minutes |
---|
351 | self.chrono.Start(1000 * 20) # every 20 seconds |
---|
352 | |
---|
353 | def OnIconify(self, event) : |
---|
354 | #self.Hide() |
---|
355 | pass |
---|
356 | |
---|
357 | def OnTaskBarActivate(self, event) : |
---|
358 | if self.IsIconized() : |
---|
359 | self.Iconize(False) |
---|
360 | if not self.IsShown() : |
---|
361 | self.Show(True) |
---|
362 | self.Raise() |
---|
363 | |
---|
364 | def OnClose(self, event) : |
---|
365 | if hasattr(self, "chrono") : |
---|
366 | self.chrono.Stop() |
---|
367 | del self.chrono |
---|
368 | if hasattr(self, "quotasgrid") : |
---|
369 | self.quotasgrid.Close() |
---|
370 | self.quotasgrid.Destroy() |
---|
371 | del self.quotasgrid |
---|
372 | if hasattr(self, "menu") : |
---|
373 | self.menu.Destroy() |
---|
374 | del self.menu |
---|
375 | if hasattr(self, "tbicon") : |
---|
376 | self.tbicon.Destroy() |
---|
377 | del self.tbicon |
---|
378 | self.Destroy() |
---|
379 | |
---|
380 | def OnTaskBarMenu(self, evt) : |
---|
381 | self.tbicon.PopupMenu(self.menu) |
---|
382 | |
---|
383 | def OnTaskBarClose(self, evt) : |
---|
384 | self.Close() |
---|
385 | wxPython.wx.wxGetApp().ProcessIdle() |
---|
386 | |
---|
387 | class PyKotIconApp(wxPython.wx.wxApp): |
---|
388 | def OnInit(self) : |
---|
389 | try : |
---|
390 | frame = PyKotIcon(None, -1) |
---|
391 | except : |
---|
392 | crashed() |
---|
393 | else : |
---|
394 | frame.Show(True) |
---|
395 | return True |
---|
396 | |
---|
397 | def main(): |
---|
398 | """Program's entry point.""" |
---|
399 | try : |
---|
400 | locale.setlocale(locale.LC_ALL, "") |
---|
401 | except (locale.Error, IOError) : |
---|
402 | sys.stderr.write("Problem while setting locale.\n") |
---|
403 | try : |
---|
404 | gettext.install("pykoticon") |
---|
405 | except : |
---|
406 | gettext.NullTranslations().install() |
---|
407 | app = PyKotIconApp() |
---|
408 | app.MainLoop() |
---|
409 | |
---|
410 | def crashed() : |
---|
411 | """Minimal crash method.""" |
---|
412 | import traceback |
---|
413 | lines = [] |
---|
414 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
415 | lines.extend([l for l in line.split("\n") if l]) |
---|
416 | msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)]) |
---|
417 | sys.stderr.write(msg) |
---|
418 | sys.stderr.flush() |
---|
419 | |
---|
420 | def test() : |
---|
421 | """Runs in test mode (console).""" |
---|
422 | if len(sys.argv) >= 3 : |
---|
423 | username = sys.argv[2] |
---|
424 | else : |
---|
425 | username = getCurrentUserName() |
---|
426 | net = CGINetworkInterface(DUMPYKOTA_URL) |
---|
427 | user = net.getUserInfo(username) |
---|
428 | print "UserName : ", user.UserName |
---|
429 | print "LimitBy : ", user.LimitBy |
---|
430 | print "Balance : ", user.Balance |
---|
431 | for printername in user.Quotas.keys() : |
---|
432 | quota = user.Quotas[printername] |
---|
433 | print "\tPrinterName : ", printername |
---|
434 | print "\tPageCounter : ", quota.PageCounter |
---|
435 | print "\tSoftLimit : ", quota.SoftLimit |
---|
436 | print "\tHardLimit : ", quota.HardLimit |
---|
437 | print "\tDateLimit : ", quota.DateLimit |
---|
438 | print |
---|
439 | for printername in user.Printers.keys() : |
---|
440 | printer = user.Printers[printername] |
---|
441 | print "\tPrinterName : ", printername |
---|
442 | print "\tPrice per Page : ", printer.PricePerPage |
---|
443 | print "\tPrice per Job : ", printer.PricePerJob |
---|
444 | print |
---|
445 | |
---|
446 | |
---|
447 | |
---|
448 | if __name__ == '__main__': |
---|
449 | if (len(sys.argv) >= 2) and (sys.argv[1] == "--test") : |
---|
450 | test() |
---|
451 | else : |
---|
452 | main() |
---|
453 | |
---|