root / pykoticon / trunk / bin / pykoticon @ 77

Revision 77, 17.8 kB (checked in by jerome, 19 years ago)

URL change for testing with real datas
Cleanup script now deletes the build and dist subdirectories

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