root / pykoticon / trunk / bin / pykoticon @ 66

Revision 66, 15.8 kB (checked in by jerome, 19 years ago)

Now retrieves printers too

  • 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        import win32net
37        import win32netcon
38    except ImportError :   
39        raise ImportError, "Mark Hammond's Win32 Extensions are missing. Please install them."
40else :       
41    isWindows = 0
42    import pwd
43   
44try :   
45    import wxPython.wx
46    import wx
47    import wx.grid as gridlib
48    hasWxPython = 1
49except ImportError :   
50    hasWxPython = 0
51    raise ImportError, "wxPython for Windows is missing. Please install it."
52   
53DUMPYKOTA_URL = "http://cgi.librelogiciel.com/cgi-bin/dumpykota.cgi"
54
55def 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       
65class 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
79class 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       
98class 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           
132class 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   
202class 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        sys.stderr.write("%s\n" % dir(self))
207        self.CreateGrid(len(user.Quotas.keys()), 4)
208        self.EnableEditing(False)
209        self.SetColLabelValue(0, _("Page Counter"))
210        self.SetColLabelValue(1, _("Soft Limit"))
211        self.SetColLabelValue(2, _("Hard Limit"))
212        self.SetColLabelValue(3, _("Date Limit"))
213        attr = gridlib.GridCellAttr()
214        attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_RIGHT)
215        attr.SetReadOnly(True)
216        self.SetColAttr(0, attr)
217        self.SetColAttr(1, attr)
218        self.SetColAttr(2, attr)
219        attr = gridlib.GridCellAttr()
220        attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
221        attr.SetReadOnly(True)
222        self.SetColAttr(3, attr)
223        i = 0
224        for printername in user.Quotas.keys() :
225            quota = user.Quotas[printername]
226            self.SetRowLabelValue(i, printername)
227            self.SetCellValue(i, 0, str(quota.PageCounter))
228            self.SetCellValue(i, 1, str(quota.SoftLimit))
229            self.SetCellValue(i, 2, str(quota.HardLimit))
230            self.SetCellValue(i, 3, str(quota.DateLimit))
231            attr = gridlib.GridCellAttr()
232            colour = wx.GREEN
233            if quota.SoftLimit is not None :
234                if quota.PageCounter >= quota.SoftLimit :
235                    colour = wx.RED
236            elif quota.HardLimit is not None :       
237                if quota.PageCounter >= quota.HardLimit :
238                    colour = wx.RED
239            attr.SetBackgroundColour(colour)       
240            self.SetRowAttr(i, attr)
241            i += 1
242        self.AutoSize()
243           
244class PyKotIcon(wxPython.wx.wxFrame):
245    """Main class."""
246    def __init__(self, parent, id):
247        wxPython.wx.wxFrame.__init__(self, parent, -1, \
248               _("PyKota Print Quota for user %s") % getCurrentUserName(), \
249               size = (460, -1), \
250               style = wxPython.wx.wxDEFAULT_FRAME_STYLE \
251                     | wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE)
252        self.greenicon = wxPython.wx.wxIcon(os.path.join("..", "icons", "pykoticon-green.ico"), \
253                                  wxPython.wx.wxBITMAP_TYPE_ICO)
254        self.redicon = wxPython.wx.wxIcon(os.path.join("..", "icons", "pykoticon-red.ico"), \
255                                  wxPython.wx.wxBITMAP_TYPE_ICO)
256        self.SetIcon(self.greenicon)
257       
258        self.tbicon = wxPython.wx.wxTaskBarIcon()
259        self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
260       
261        wxPython.wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
262        wxPython.wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
263        wxPython.wx.EVT_ICONIZE(self, self.OnIconify)
264       
265        self.TBMENU_RESTORE = wx.NewId()
266        self.TBMENU_CLOSE = wx.NewId()
267        wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
268                                          self.OnTaskBarActivate)
269        wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
270                                          self.OnTaskBarClose)
271        self.menu = wxPython.wx.wxMenu()
272        self.menu.Append(self.TBMENU_RESTORE, _("Show Print Quota"))
273        self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
274       
275        wxPython.wx.EVT_CLOSE(self, self.OnClose)
276       
277        self.TBTIMER = wx.NewId()
278        self.chrono = wxPython.wx.wxTimer(self, self.TBTIMER)
279        wxPython.wx.EVT_TIMER(self, self.TBTIMER, self.OnChronoTimer)
280       
281        self.User = None
282        self.networkInterface = CGINetworkInterface(DUMPYKOTA_URL)
283        self.inTimer = False
284        self.chrono.Start(250) # first time in 0.25 second
285
286    def OnChronoTimer(self, event) :
287        """Retrieves user's data quota information."""
288        # we stop it there, needed because we want to
289        # change the delay the first time.
290        self.chrono.Stop()   
291        if self.inTimer is False : # avoids re-entrance
292            self.inTimer = True
293            self.User = self.networkInterface.getUserInfo(getCurrentUserName())
294            if self.User.LimitBy == "balance" :
295                if self.User.Balance <= 0.0 :
296                    self.tbicon.SetIcon(self.redicon, "PyKotIcon")
297                else :   
298                    self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
299            else :       
300                isRed = False
301                for q in self.User.Quotas.keys() :
302                    quota = self.User.Quotas[q]
303                    if quota.SoftLimit is not None :
304                        if quota.PageCounter >= quota.SoftLimit :
305                            isRed = True
306                            break
307                    elif quota.HardLimit is not None :       
308                        if quota.PageCounter >= quota.HardLimit :
309                            isRed = True
310                            break
311                if isRed is True :
312                    self.tbicon.SetIcon(self.redicon, "PyKotIcon")
313                else :   
314                    self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
315                if hasattr(self, "quotasgrid") :   
316                    self.quotasgrid.Close()
317                    self.quotasgrid.Destroy()
318                    del self.quotasgrid
319                self.quotasgrid = PyKotIconGrid(self, self.User)   
320            self.inTimer = False
321        # Now we want it every 3 minutes   
322        #self.chrono.Start(1000 * 60 * 3) # every 3 minutes
323        self.chrono.Start(1000 * 20) # every 20 seconds
324   
325    def OnIconify(self, event) :
326        self.Hide()
327
328    def OnTaskBarActivate(self, event) :
329        if self.IsIconized() :
330            self.Iconize(False)
331        if not self.IsShown() :
332            self.Show(True)
333        self.Raise()
334
335    def OnClose(self, event) :
336        if hasattr(self, "chrono") :
337            self.chrono.Stop()
338            del self.chrono
339        if hasattr(self, "quotasgrid") :
340            self.quotasgrid.Close()
341            self.quotasgrid.Destroy()
342            del self.quotasgrid
343        if hasattr(self, "menu") :
344            self.menu.Destroy()
345            del self.menu
346        if hasattr(self, "tbicon") :
347            self.tbicon.Destroy()
348            del self.tbicon
349        self.Destroy()
350
351    def OnTaskBarMenu(self, evt) :
352        self.tbicon.PopupMenu(self.menu)
353
354    def OnTaskBarClose(self, evt) :
355        self.Close()
356        wxPython.wx.wxGetApp().ProcessIdle()
357
358class PyKotIconApp(wxPython.wx.wxApp):
359    def OnInit(self) :
360        try :
361            frame = PyKotIcon(None, -1)
362        except :   
363            crashed()
364        else :   
365            frame.Show(True)
366        return True
367       
368def main():
369    """Program's entry point."""
370    try :
371        locale.setlocale(locale.LC_ALL, "")
372    except (locale.Error, IOError) :
373        sys.stderr.write("Problem while setting locale.\n")
374    try :
375        gettext.install("pykoticon")
376    except :
377        gettext.NullTranslations().install()
378    app = PyKotIconApp()
379    app.MainLoop()
380   
381def crashed() :   
382    """Minimal crash method."""
383    import traceback
384    lines = []
385    for line in traceback.format_exception(*sys.exc_info()) :
386        lines.extend([l for l in line.split("\n") if l])
387    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
388    sys.stderr.write(msg)
389    sys.stderr.flush()
390   
391def test() :
392    """Runs in test mode (console)."""
393    if len(sys.argv) >= 3 :
394        username = sys.argv[2] 
395    else :   
396        username = getCurrentUserName()
397    net = CGINetworkInterface(DUMPYKOTA_URL)
398    user = net.getUserInfo(username)
399    print "UserName : ", user.UserName
400    print "LimitBy : ", user.LimitBy
401    print "Balance : ", user.Balance
402    for printername in user.Quotas.keys() :
403        quota = user.Quotas[printername]
404        print "\tPrinterName : ", printername
405        print "\tPageCounter : ", quota.PageCounter
406        print "\tSoftLimit : ", quota.SoftLimit
407        print "\tHardLimit : ", quota.HardLimit
408        print "\tDateLimit : ", quota.DateLimit
409        print
410    for printername in user.Printers.keys() :
411        printer = user.Printers[printername]
412        print "\tPrinterName : ", printername
413        print "\tPrice per Page : ", printer.PricePerPage
414        print "\tPrice per Job : ", printer.PricePerJob
415        print
416       
417       
418
419if __name__ == '__main__':
420    if (len(sys.argv) >= 2) and (sys.argv[1] == "--test") :
421        test()
422    else :   
423        main()
424   
Note: See TracBrowser for help on using the browser.