[695] | 1 | # PyKota |
---|
[1144] | 2 | # -*- coding: ISO-8859-15 -*- |
---|
[695] | 3 | # |
---|
[952] | 4 | # PyKota : Print Quotas for CUPS and LPRng |
---|
[695] | 5 | # |
---|
[2622] | 6 | # (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com> |
---|
[873] | 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. |
---|
[695] | 11 | # |
---|
[873] | 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 |
---|
[2302] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[695] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
[2066] | 23 | # |
---|
[695] | 24 | |
---|
[2266] | 25 | from mx import DateTime |
---|
| 26 | |
---|
[695] | 27 | class PyKotaStorageError(Exception): |
---|
[2717] | 28 | """An exception for database related stuff.""" |
---|
[695] | 29 | def __init__(self, message = ""): |
---|
| 30 | self.message = message |
---|
| 31 | Exception.__init__(self, message) |
---|
| 32 | def __repr__(self): |
---|
| 33 | return self.message |
---|
| 34 | __str__ = __repr__ |
---|
[759] | 35 | |
---|
[1041] | 36 | class StorageObject : |
---|
[2717] | 37 | """Object present in the database.""" |
---|
[1041] | 38 | def __init__(self, parent) : |
---|
| 39 | "Initialize minimal data.""" |
---|
| 40 | self.parent = parent |
---|
| 41 | self.ident = None |
---|
[2697] | 42 | self.Description = None |
---|
[2676] | 43 | self.isDirty = False |
---|
| 44 | self.Exists = False |
---|
[1041] | 45 | |
---|
[2696] | 46 | def setDescription(self, description=None) : |
---|
| 47 | """Sets the object's description.""" |
---|
| 48 | if description is not None : |
---|
| 49 | self.Description = str(description) |
---|
| 50 | self.isDirty = True |
---|
[2699] | 51 | |
---|
| 52 | def save(self) : |
---|
| 53 | """Saves the object to the database.""" |
---|
| 54 | if self.isDirty : |
---|
| 55 | getattr(self.parent, "save%s" % self.__class__.__name__[7:])(self) |
---|
| 56 | self.isDirty = False |
---|
[2696] | 57 | |
---|
[1041] | 58 | class StorageUser(StorageObject) : |
---|
| 59 | """User class.""" |
---|
| 60 | def __init__(self, parent, name) : |
---|
| 61 | StorageObject.__init__(self, parent) |
---|
| 62 | self.Name = name |
---|
| 63 | self.LimitBy = None |
---|
| 64 | self.AccountBalance = None |
---|
| 65 | self.LifeTimePaid = None |
---|
[1067] | 66 | self.Email = None |
---|
[2054] | 67 | self.OverCharge = 1.0 |
---|
[1522] | 68 | self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them |
---|
[2773] | 69 | self.PaymentsBacklog = [] |
---|
[1041] | 70 | |
---|
| 71 | def consumeAccountBalance(self, amount) : |
---|
| 72 | """Consumes an amount of money from the user's account balance.""" |
---|
[1269] | 73 | self.parent.decreaseUserAccountBalance(self, amount) |
---|
| 74 | self.AccountBalance = float(self.AccountBalance or 0.0) - amount |
---|
[1041] | 75 | |
---|
[2452] | 76 | def setAccountBalance(self, balance, lifetimepaid, comment="") : |
---|
[1041] | 77 | """Sets the user's account balance in case he pays more money.""" |
---|
[1522] | 78 | diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0) |
---|
[2707] | 79 | self.AccountBalance = balance |
---|
| 80 | self.LifeTimePaid = lifetimepaid |
---|
[2773] | 81 | if diff : |
---|
| 82 | self.PaymentsBacklog.append((diff, comment)) |
---|
[2707] | 83 | self.isDirty = True |
---|
[1041] | 84 | |
---|
[2773] | 85 | def save(self) : |
---|
| 86 | """Saves an user and flush its payments backlog.""" |
---|
| 87 | for (value, comment) in self.PaymentsBacklog : |
---|
| 88 | self.parent.writeNewPayment(self, value, comment) |
---|
| 89 | self.PaymentsBacklog = [] |
---|
| 90 | StorageObject.save(self) |
---|
| 91 | |
---|
[1041] | 92 | def setLimitBy(self, limitby) : |
---|
| 93 | """Sets the user's limiting factor.""" |
---|
[1062] | 94 | try : |
---|
| 95 | limitby = limitby.lower() |
---|
| 96 | except AttributeError : |
---|
| 97 | limitby = "quota" |
---|
[2452] | 98 | if limitby in ["quota", "balance", \ |
---|
| 99 | "noquota", "noprint", "nochange"] : |
---|
[1041] | 100 | self.LimitBy = limitby |
---|
[2706] | 101 | self.isDirty = True |
---|
[1041] | 102 | |
---|
[2054] | 103 | def setOverChargeFactor(self, factor) : |
---|
| 104 | """Sets the user's overcharging coefficient.""" |
---|
| 105 | self.OverCharge = factor |
---|
[2706] | 106 | self.isDirty = True |
---|
[2054] | 107 | |
---|
[1041] | 108 | def delete(self) : |
---|
[2717] | 109 | """Deletes an user from the database.""" |
---|
[2801] | 110 | self.parent.deleteUser(self) |
---|
| 111 | self.parent.flushEntry("USERS", self.Name) |
---|
| 112 | if self.parent.usecache : |
---|
| 113 | for (k, v) in self.parent.caches["USERPQUOTAS"].items() : |
---|
| 114 | if v.User.Name == self.Name : |
---|
| 115 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name)) |
---|
| 116 | self.Exists = False |
---|
| 117 | self.isDirty = False |
---|
[1041] | 118 | |
---|
| 119 | class StorageGroup(StorageObject) : |
---|
| 120 | """User class.""" |
---|
| 121 | def __init__(self, parent, name) : |
---|
| 122 | StorageObject.__init__(self, parent) |
---|
| 123 | self.Name = name |
---|
| 124 | self.LimitBy = None |
---|
| 125 | self.AccountBalance = None |
---|
| 126 | self.LifeTimePaid = None |
---|
| 127 | |
---|
| 128 | def setLimitBy(self, limitby) : |
---|
| 129 | """Sets the user's limiting factor.""" |
---|
[1062] | 130 | try : |
---|
| 131 | limitby = limitby.lower() |
---|
| 132 | except AttributeError : |
---|
| 133 | limitby = "quota" |
---|
[2452] | 134 | if limitby in ["quota", "balance", "noquota"] : |
---|
[1041] | 135 | self.LimitBy = limitby |
---|
[2706] | 136 | self.isDirty = True |
---|
[1041] | 137 | |
---|
[2706] | 138 | def addUserToGroup(self, user) : |
---|
| 139 | """Adds an user to an users group.""" |
---|
| 140 | self.parent.addUserToGroup(user, self) |
---|
| 141 | |
---|
| 142 | def delUserFromGroup(self, user) : |
---|
| 143 | """Removes an user from an users group.""" |
---|
| 144 | self.parent.delUserFromGroup(user, self) |
---|
| 145 | |
---|
[1041] | 146 | def delete(self) : |
---|
[2717] | 147 | """Deletes a group from the database.""" |
---|
[2801] | 148 | self.parent.deleteGroup(self) |
---|
| 149 | self.parent.flushEntry("GROUPS", self.Name) |
---|
| 150 | if self.parent.usecache : |
---|
| 151 | for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() : |
---|
| 152 | if v.Group.Name == self.Name : |
---|
| 153 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name)) |
---|
| 154 | self.Exists = False |
---|
| 155 | self.isDirty = False |
---|
[1041] | 156 | |
---|
| 157 | class StoragePrinter(StorageObject) : |
---|
| 158 | """Printer class.""" |
---|
| 159 | def __init__(self, parent, name) : |
---|
| 160 | StorageObject.__init__(self, parent) |
---|
| 161 | self.Name = name |
---|
| 162 | self.PricePerPage = None |
---|
| 163 | self.PricePerJob = None |
---|
[2455] | 164 | self.MaxJobSize = None |
---|
[2459] | 165 | self.PassThrough = None |
---|
[2054] | 166 | self.Coefficients = None |
---|
[1041] | 167 | |
---|
[1358] | 168 | def __getattr__(self, name) : |
---|
| 169 | """Delays data retrieval until it's really needed.""" |
---|
| 170 | if name == "LastJob" : |
---|
| 171 | self.LastJob = self.parent.getPrinterLastJob(self) |
---|
| 172 | return self.LastJob |
---|
| 173 | else : |
---|
| 174 | raise AttributeError, name |
---|
| 175 | |
---|
[2455] | 176 | def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) : |
---|
[1041] | 177 | """Adds a job to the printer's history.""" |
---|
[2455] | 178 | self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum, jobpages, jobbilling, precomputedsize, precomputedprice) |
---|
[1041] | 179 | # TODO : update LastJob object ? Probably not needed. |
---|
| 180 | |
---|
[1258] | 181 | def addPrinterToGroup(self, printer) : |
---|
| 182 | """Adds a printer to a printer group.""" |
---|
[1259] | 183 | if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) : |
---|
[1258] | 184 | self.parent.writePrinterToGroup(self, printer) |
---|
[1269] | 185 | # TODO : reset cached value for printer parents, or add new parent to cached value |
---|
[1332] | 186 | |
---|
| 187 | def delPrinterFromGroup(self, printer) : |
---|
| 188 | """Deletes a printer from a printer group.""" |
---|
[1333] | 189 | self.parent.removePrinterFromGroup(self, printer) |
---|
| 190 | # TODO : reset cached value for printer parents, or add new parent to cached value |
---|
[1258] | 191 | |
---|
[1041] | 192 | def setPrices(self, priceperpage = None, priceperjob = None) : |
---|
| 193 | """Sets the printer's prices.""" |
---|
| 194 | if priceperpage is None : |
---|
[1711] | 195 | priceperpage = self.PricePerPage or 0.0 |
---|
[1041] | 196 | else : |
---|
| 197 | self.PricePerPage = float(priceperpage) |
---|
| 198 | if priceperjob is None : |
---|
[1711] | 199 | priceperjob = self.PricePerJob or 0.0 |
---|
[1041] | 200 | else : |
---|
| 201 | self.PricePerJob = float(priceperjob) |
---|
[2686] | 202 | self.isDirty = True |
---|
[1041] | 203 | |
---|
[2686] | 204 | def setPassThrough(self, passthrough) : |
---|
| 205 | """Sets the printer's passthrough mode.""" |
---|
| 206 | self.PassThrough = passthrough |
---|
| 207 | self.isDirty = True |
---|
| 208 | |
---|
| 209 | def setMaxJobSize(self, maxjobsize) : |
---|
| 210 | """Sets the printer's maximal job size.""" |
---|
| 211 | self.MaxJobSize = maxjobsize |
---|
| 212 | self.isDirty = True |
---|
| 213 | |
---|
[1330] | 214 | def delete(self) : |
---|
[2717] | 215 | """Deletes a printer from the database.""" |
---|
[2801] | 216 | self.parent.deletePrinter(self) |
---|
| 217 | self.parent.flushEntry("PRINTERS", self.Name) |
---|
| 218 | if self.parent.usecache : |
---|
| 219 | for (k, v) in self.parent.caches["USERPQUOTAS"].items() : |
---|
| 220 | if v.Printer.Name == self.Name : |
---|
| 221 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name)) |
---|
| 222 | for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() : |
---|
| 223 | if v.Printer.Name == self.Name : |
---|
| 224 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name)) |
---|
| 225 | self.Exists = False |
---|
| 226 | self.isDirty = False |
---|
[1330] | 227 | |
---|
[1041] | 228 | class StorageUserPQuota(StorageObject) : |
---|
| 229 | """User Print Quota class.""" |
---|
| 230 | def __init__(self, parent, user, printer) : |
---|
| 231 | StorageObject.__init__(self, parent) |
---|
| 232 | self.User = user |
---|
| 233 | self.Printer = printer |
---|
| 234 | self.PageCounter = None |
---|
| 235 | self.LifePageCounter = None |
---|
| 236 | self.SoftLimit = None |
---|
| 237 | self.HardLimit = None |
---|
| 238 | self.DateLimit = None |
---|
[2054] | 239 | self.WarnCount = None |
---|
[2455] | 240 | self.MaxJobSize = None |
---|
[1041] | 241 | |
---|
[1358] | 242 | def __getattr__(self, name) : |
---|
| 243 | """Delays data retrieval until it's really needed.""" |
---|
| 244 | if name == "ParentPrintersUserPQuota" : |
---|
| 245 | self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or [] |
---|
| 246 | return self.ParentPrintersUserPQuota |
---|
| 247 | else : |
---|
| 248 | raise AttributeError, name |
---|
| 249 | |
---|
[1041] | 250 | def setDateLimit(self, datelimit) : |
---|
| 251 | """Sets the date limit for this quota.""" |
---|
| 252 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second) |
---|
| 253 | self.parent.writeUserPQuotaDateLimit(self, date) |
---|
| 254 | self.DateLimit = date |
---|
| 255 | |
---|
| 256 | def setLimits(self, softlimit, hardlimit) : |
---|
| 257 | """Sets the soft and hard limit for this quota.""" |
---|
| 258 | self.SoftLimit = softlimit |
---|
| 259 | self.HardLimit = hardlimit |
---|
[1367] | 260 | self.DateLimit = None |
---|
[2054] | 261 | self.WarnCount = 0 |
---|
[2735] | 262 | self.isDirty = True |
---|
[1041] | 263 | |
---|
[1967] | 264 | def setUsage(self, used) : |
---|
| 265 | """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount.""" |
---|
| 266 | vused = int(used) |
---|
| 267 | if used.startswith("+") or used.startswith("-") : |
---|
[2030] | 268 | self.PageCounter += vused |
---|
| 269 | self.LifePageCounter += vused |
---|
[1967] | 270 | else : |
---|
[2030] | 271 | self.PageCounter = self.LifePageCounter = vused |
---|
| 272 | self.DateLimit = None |
---|
[2054] | 273 | self.WarnCount = 0 |
---|
[2735] | 274 | self.isDirty = 1 |
---|
[1967] | 275 | |
---|
[2066] | 276 | def incDenyBannerCounter(self) : |
---|
| 277 | """Increment the deny banner counter for this user quota.""" |
---|
[2054] | 278 | self.parent.increaseUserPQuotaWarnCount(self) |
---|
| 279 | self.WarnCount = (self.WarnCount or 0) + 1 |
---|
| 280 | |
---|
[2066] | 281 | def resetDenyBannerCounter(self) : |
---|
| 282 | """Resets the deny banner counter for this user quota.""" |
---|
| 283 | self.parent.writeUserPQuotaWarnCount(self, 0) |
---|
| 284 | self.WarnCount = 0 |
---|
| 285 | |
---|
[1041] | 286 | def reset(self) : |
---|
| 287 | """Resets page counter to 0.""" |
---|
| 288 | self.PageCounter = 0 |
---|
[2030] | 289 | self.DateLimit = None |
---|
[2735] | 290 | self.isDirty = True |
---|
[1041] | 291 | |
---|
[1755] | 292 | def hardreset(self) : |
---|
| 293 | """Resets actual and life time page counters to 0.""" |
---|
| 294 | self.PageCounter = self.LifePageCounter = 0 |
---|
[2030] | 295 | self.DateLimit = None |
---|
[2735] | 296 | self.isDirty = True |
---|
[1755] | 297 | |
---|
[1285] | 298 | def computeJobPrice(self, jobsize) : |
---|
| 299 | """Computes the job price as the sum of all parent printers' prices + current printer's ones.""" |
---|
| 300 | totalprice = 0.0 |
---|
| 301 | if jobsize : |
---|
[2054] | 302 | if self.User.OverCharge != 0.0 : # optimization, but TODO : beware of rounding errors |
---|
| 303 | for upq in [ self ] + self.ParentPrintersUserPQuota : |
---|
| 304 | price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0) |
---|
| 305 | totalprice += price |
---|
| 306 | if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors |
---|
| 307 | overcharged = totalprice * self.User.OverCharge |
---|
[2513] | 308 | self.parent.tool.logdebug("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged)) |
---|
[2054] | 309 | return overcharged |
---|
| 310 | else : |
---|
| 311 | return totalprice |
---|
[1285] | 312 | |
---|
| 313 | def increasePagesUsage(self, jobsize) : |
---|
[1041] | 314 | """Increase the value of used pages and money.""" |
---|
[1285] | 315 | jobprice = self.computeJobPrice(jobsize) |
---|
| 316 | if jobsize : |
---|
[2409] | 317 | if jobprice : |
---|
| 318 | self.User.consumeAccountBalance(jobprice) |
---|
| 319 | for upq in [ self ] + self.ParentPrintersUserPQuota : |
---|
| 320 | self.parent.increaseUserPQuotaPagesCounters(upq, jobsize) |
---|
| 321 | upq.PageCounter = int(upq.PageCounter or 0) + jobsize |
---|
| 322 | upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize |
---|
[1285] | 323 | return jobprice |
---|
[1041] | 324 | |
---|
[2717] | 325 | def delete(self) : |
---|
| 326 | """Deletes an user print quota entry from the database.""" |
---|
[2801] | 327 | self.parent.deleteUserPQuota(self) |
---|
| 328 | if self.parent.usecache : |
---|
| 329 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (self.User.Name, self.Printer.Name)) |
---|
| 330 | self.Exists = False |
---|
| 331 | self.isDirty = False |
---|
[2717] | 332 | |
---|
[1041] | 333 | class StorageGroupPQuota(StorageObject) : |
---|
| 334 | """Group Print Quota class.""" |
---|
| 335 | def __init__(self, parent, group, printer) : |
---|
| 336 | StorageObject.__init__(self, parent) |
---|
| 337 | self.Group = group |
---|
| 338 | self.Printer = printer |
---|
| 339 | self.PageCounter = None |
---|
| 340 | self.LifePageCounter = None |
---|
| 341 | self.SoftLimit = None |
---|
| 342 | self.HardLimit = None |
---|
| 343 | self.DateLimit = None |
---|
[2455] | 344 | self.MaxJobSize = None |
---|
[1041] | 345 | |
---|
[1365] | 346 | def __getattr__(self, name) : |
---|
| 347 | """Delays data retrieval until it's really needed.""" |
---|
| 348 | if name == "ParentPrintersGroupPQuota" : |
---|
| 349 | self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or [] |
---|
| 350 | return self.ParentPrintersGroupPQuota |
---|
| 351 | else : |
---|
| 352 | raise AttributeError, name |
---|
| 353 | |
---|
[2030] | 354 | def reset(self) : |
---|
| 355 | """Resets page counter to 0.""" |
---|
[2801] | 356 | for user in self.parent.getGroupMembers(self.Group) : |
---|
| 357 | uq = self.parent.getUserPQuota(user, self.Printer) |
---|
| 358 | uq.reset() |
---|
| 359 | uq.save() |
---|
[2030] | 360 | self.PageCounter = 0 |
---|
| 361 | self.DateLimit = None |
---|
[2735] | 362 | self.isDirty = True |
---|
[2030] | 363 | |
---|
| 364 | def hardreset(self) : |
---|
| 365 | """Resets actual and life time page counters to 0.""" |
---|
[2801] | 366 | for user in self.parent.getGroupMembers(self.Group) : |
---|
| 367 | uq = self.parent.getUserPQuota(user, self.Printer) |
---|
| 368 | uq.hardreset() |
---|
| 369 | uq.save() |
---|
[2030] | 370 | self.PageCounter = self.LifePageCounter = 0 |
---|
| 371 | self.DateLimit = None |
---|
[2735] | 372 | self.isDirty = True |
---|
[2030] | 373 | |
---|
[1041] | 374 | def setDateLimit(self, datelimit) : |
---|
| 375 | """Sets the date limit for this quota.""" |
---|
[2450] | 376 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, \ |
---|
| 377 | datelimit.month, \ |
---|
| 378 | datelimit.day, \ |
---|
| 379 | datelimit.hour, \ |
---|
| 380 | datelimit.minute, \ |
---|
| 381 | datelimit.second) |
---|
[1041] | 382 | self.parent.writeGroupPQuotaDateLimit(self, date) |
---|
| 383 | self.DateLimit = date |
---|
| 384 | |
---|
| 385 | def setLimits(self, softlimit, hardlimit) : |
---|
| 386 | """Sets the soft and hard limit for this quota.""" |
---|
| 387 | self.SoftLimit = softlimit |
---|
| 388 | self.HardLimit = hardlimit |
---|
[1367] | 389 | self.DateLimit = None |
---|
[2735] | 390 | self.isDirty = True |
---|
[1041] | 391 | |
---|
[2717] | 392 | def delete(self) : |
---|
| 393 | """Deletes a group print quota entry from the database.""" |
---|
[2801] | 394 | self.parent.deleteGroupPQuota(self) |
---|
| 395 | if self.parent.usecache : |
---|
| 396 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (self.Group.Name, self.Printer.Name)) |
---|
| 397 | self.Exists = False |
---|
| 398 | self.isDirty = False |
---|
[2717] | 399 | |
---|
[1274] | 400 | class StorageJob(StorageObject) : |
---|
[1692] | 401 | """Printer's Job class.""" |
---|
[1274] | 402 | def __init__(self, parent) : |
---|
[1041] | 403 | StorageObject.__init__(self, parent) |
---|
[1358] | 404 | self.UserName = None |
---|
| 405 | self.PrinterName = None |
---|
[1041] | 406 | self.JobId = None |
---|
| 407 | self.PrinterPageCounter = None |
---|
[1520] | 408 | self.JobSizeBytes = None |
---|
[1041] | 409 | self.JobSize = None |
---|
| 410 | self.JobAction = None |
---|
| 411 | self.JobDate = None |
---|
[1203] | 412 | self.JobPrice = None |
---|
| 413 | self.JobFileName = None |
---|
| 414 | self.JobTitle = None |
---|
| 415 | self.JobCopies = None |
---|
| 416 | self.JobOptions = None |
---|
[1502] | 417 | self.JobHostName = None |
---|
[2054] | 418 | self.JobMD5Sum = None |
---|
| 419 | self.JobPages = None |
---|
| 420 | self.JobBillingCode = None |
---|
[2455] | 421 | self.PrecomputedJobSize = None |
---|
| 422 | self.PrecomputedJobPrice = None |
---|
[1041] | 423 | |
---|
[1358] | 424 | def __getattr__(self, name) : |
---|
| 425 | """Delays data retrieval until it's really needed.""" |
---|
| 426 | if name == "User" : |
---|
| 427 | self.User = self.parent.getUser(self.UserName) |
---|
| 428 | return self.User |
---|
| 429 | elif name == "Printer" : |
---|
| 430 | self.Printer = self.parent.getPrinter(self.PrinterName) |
---|
| 431 | return self.Printer |
---|
| 432 | else : |
---|
| 433 | raise AttributeError, name |
---|
| 434 | |
---|
[1274] | 435 | class StorageLastJob(StorageJob) : |
---|
| 436 | """Printer's Last Job class.""" |
---|
| 437 | def __init__(self, parent, printer) : |
---|
| 438 | StorageJob.__init__(self, parent) |
---|
[1359] | 439 | self.PrinterName = printer.Name # not needed |
---|
[1274] | 440 | self.Printer = printer |
---|
| 441 | |
---|
[2340] | 442 | class StorageBillingCode(StorageObject) : |
---|
| 443 | """Billing code class.""" |
---|
| 444 | def __init__(self, parent, name) : |
---|
| 445 | StorageObject.__init__(self, parent) |
---|
| 446 | self.BillingCode = name |
---|
| 447 | self.PageCounter = None |
---|
| 448 | self.Balance = None |
---|
| 449 | |
---|
| 450 | def delete(self) : |
---|
| 451 | """Deletes the billing code from the database.""" |
---|
| 452 | self.parent.deleteBillingCode(self) |
---|
[2450] | 453 | self.parent.flushEntry("BILLINGCODES", self.BillingCode) |
---|
[2686] | 454 | self.isDirty = False |
---|
[2676] | 455 | self.Exists = False |
---|
[2340] | 456 | |
---|
[2342] | 457 | def reset(self, balance=0.0, pagecounter=0) : |
---|
[2340] | 458 | """Resets the pagecounter and balance for this billing code.""" |
---|
[2686] | 459 | self.Balance = balance |
---|
| 460 | self.PageCounter = pagecounter |
---|
| 461 | self.isDirty = True |
---|
[2340] | 462 | |
---|
| 463 | def consume(self, pages, price) : |
---|
| 464 | """Consumes some pages and credits for this billing code.""" |
---|
| 465 | if pages : |
---|
| 466 | self.parent.consumeBillingCode(self, pages, price) |
---|
| 467 | self.PageCounter += pages |
---|
| 468 | self.Balance -= price |
---|
| 469 | |
---|
[1130] | 470 | class BaseStorage : |
---|
| 471 | def __init__(self, pykotatool) : |
---|
[1523] | 472 | """Opens the storage connection.""" |
---|
[1130] | 473 | self.closed = 1 |
---|
| 474 | self.tool = pykotatool |
---|
| 475 | self.usecache = pykotatool.config.getCaching() |
---|
[1148] | 476 | self.disablehistory = pykotatool.config.getDisableHistory() |
---|
[1875] | 477 | self.privacy = pykotatool.config.getPrivacy() |
---|
| 478 | if self.privacy : |
---|
| 479 | pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.") |
---|
[1130] | 480 | if self.usecache : |
---|
| 481 | self.tool.logdebug("Caching enabled.") |
---|
[2450] | 482 | self.caches = { "USERS" : {}, \ |
---|
| 483 | "GROUPS" : {}, \ |
---|
| 484 | "PRINTERS" : {}, \ |
---|
| 485 | "USERPQUOTAS" : {}, \ |
---|
| 486 | "GROUPPQUOTAS" : {}, \ |
---|
| 487 | "JOBS" : {}, \ |
---|
| 488 | "LASTJOBS" : {}, \ |
---|
| 489 | "BILLINGCODES" : {} } |
---|
[1130] | 490 | |
---|
[1240] | 491 | def close(self) : |
---|
| 492 | """Must be overriden in children classes.""" |
---|
| 493 | raise RuntimeError, "BaseStorage.close() must be overriden !" |
---|
| 494 | |
---|
[1130] | 495 | def __del__(self) : |
---|
| 496 | """Ensures that the database connection is closed.""" |
---|
| 497 | self.close() |
---|
| 498 | |
---|
| 499 | def getFromCache(self, cachetype, key) : |
---|
| 500 | """Tries to extract something from the cache.""" |
---|
| 501 | if self.usecache : |
---|
| 502 | entry = self.caches[cachetype].get(key) |
---|
| 503 | if entry is not None : |
---|
| 504 | self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key)) |
---|
| 505 | else : |
---|
| 506 | self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key)) |
---|
[1743] | 507 | return entry |
---|
[1130] | 508 | |
---|
| 509 | def cacheEntry(self, cachetype, key, value) : |
---|
| 510 | """Puts an entry in the cache.""" |
---|
[1151] | 511 | if self.usecache and getattr(value, "Exists", 0) : |
---|
[1130] | 512 | self.caches[cachetype][key] = value |
---|
[1132] | 513 | self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key)) |
---|
[1130] | 514 | |
---|
[2450] | 515 | def flushEntry(self, cachetype, key) : |
---|
| 516 | """Removes an entry from the cache.""" |
---|
| 517 | if self.usecache : |
---|
| 518 | try : |
---|
| 519 | del self.caches[cachetype][key] |
---|
| 520 | except KeyError : |
---|
| 521 | pass |
---|
| 522 | else : |
---|
| 523 | self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key)) |
---|
| 524 | |
---|
[1130] | 525 | def getUser(self, username) : |
---|
| 526 | """Returns the user from cache.""" |
---|
| 527 | user = self.getFromCache("USERS", username) |
---|
| 528 | if user is None : |
---|
| 529 | user = self.getUserFromBackend(username) |
---|
| 530 | self.cacheEntry("USERS", username, user) |
---|
| 531 | return user |
---|
| 532 | |
---|
| 533 | def getGroup(self, groupname) : |
---|
| 534 | """Returns the group from cache.""" |
---|
| 535 | group = self.getFromCache("GROUPS", groupname) |
---|
| 536 | if group is None : |
---|
| 537 | group = self.getGroupFromBackend(groupname) |
---|
| 538 | self.cacheEntry("GROUPS", groupname, group) |
---|
| 539 | return group |
---|
| 540 | |
---|
| 541 | def getPrinter(self, printername) : |
---|
| 542 | """Returns the printer from cache.""" |
---|
| 543 | printer = self.getFromCache("PRINTERS", printername) |
---|
| 544 | if printer is None : |
---|
| 545 | printer = self.getPrinterFromBackend(printername) |
---|
| 546 | self.cacheEntry("PRINTERS", printername, printer) |
---|
| 547 | return printer |
---|
| 548 | |
---|
| 549 | def getUserPQuota(self, user, printer) : |
---|
| 550 | """Returns the user quota information from cache.""" |
---|
| 551 | useratprinter = "%s@%s" % (user.Name, printer.Name) |
---|
| 552 | upquota = self.getFromCache("USERPQUOTAS", useratprinter) |
---|
| 553 | if upquota is None : |
---|
| 554 | upquota = self.getUserPQuotaFromBackend(user, printer) |
---|
| 555 | self.cacheEntry("USERPQUOTAS", useratprinter, upquota) |
---|
| 556 | return upquota |
---|
| 557 | |
---|
| 558 | def getGroupPQuota(self, group, printer) : |
---|
| 559 | """Returns the group quota information from cache.""" |
---|
| 560 | groupatprinter = "%s@%s" % (group.Name, printer.Name) |
---|
| 561 | gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter) |
---|
| 562 | if gpquota is None : |
---|
| 563 | gpquota = self.getGroupPQuotaFromBackend(group, printer) |
---|
| 564 | self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota) |
---|
| 565 | return gpquota |
---|
| 566 | |
---|
| 567 | def getPrinterLastJob(self, printer) : |
---|
| 568 | """Extracts last job information for a given printer from cache.""" |
---|
| 569 | lastjob = self.getFromCache("LASTJOBS", printer.Name) |
---|
| 570 | if lastjob is None : |
---|
| 571 | lastjob = self.getPrinterLastJobFromBackend(printer) |
---|
| 572 | self.cacheEntry("LASTJOBS", printer.Name, lastjob) |
---|
| 573 | return lastjob |
---|
| 574 | |
---|
[2342] | 575 | def getBillingCode(self, label) : |
---|
| 576 | """Returns the user from cache.""" |
---|
| 577 | code = self.getFromCache("BILLINGCODES", label) |
---|
| 578 | if code is None : |
---|
| 579 | code = self.getBillingCodeFromBackend(label) |
---|
| 580 | self.cacheEntry("BILLINGCODES", label, code) |
---|
| 581 | return code |
---|
| 582 | |
---|
[1249] | 583 | def getParentPrinters(self, printer) : |
---|
| 584 | """Extracts parent printers information for a given printer from cache.""" |
---|
[1252] | 585 | if self.usecache : |
---|
| 586 | if not hasattr(printer, "Parents") : |
---|
| 587 | self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name) |
---|
| 588 | printer.Parents = self.getParentPrintersFromBackend(printer) |
---|
| 589 | self.tool.logdebug("Cache store (%s->Parents)" % printer.Name) |
---|
| 590 | else : |
---|
| 591 | self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name) |
---|
| 592 | else : |
---|
| 593 | printer.Parents = self.getParentPrintersFromBackend(printer) |
---|
[1364] | 594 | for parent in printer.Parents[:] : |
---|
| 595 | printer.Parents.extend(self.getParentPrinters(parent)) |
---|
[1368] | 596 | uniquedic = {} |
---|
| 597 | for parent in printer.Parents : |
---|
| 598 | uniquedic[parent.Name] = parent |
---|
| 599 | printer.Parents = uniquedic.values() |
---|
[1252] | 600 | return printer.Parents |
---|
[1249] | 601 | |
---|
[1137] | 602 | def getGroupMembers(self, group) : |
---|
| 603 | """Returns the group's members list from in-group cache.""" |
---|
| 604 | if self.usecache : |
---|
| 605 | if not hasattr(group, "Members") : |
---|
| 606 | self.tool.logdebug("Cache miss (%s->Members)" % group.Name) |
---|
| 607 | group.Members = self.getGroupMembersFromBackend(group) |
---|
| 608 | self.tool.logdebug("Cache store (%s->Members)" % group.Name) |
---|
| 609 | else : |
---|
| 610 | self.tool.logdebug("Cache hit (%s->Members)" % group.Name) |
---|
| 611 | else : |
---|
| 612 | group.Members = self.getGroupMembersFromBackend(group) |
---|
| 613 | return group.Members |
---|
| 614 | |
---|
| 615 | def getUserGroups(self, user) : |
---|
| 616 | """Returns the user's groups list from in-user cache.""" |
---|
| 617 | if self.usecache : |
---|
| 618 | if not hasattr(user, "Groups") : |
---|
| 619 | self.tool.logdebug("Cache miss (%s->Groups)" % user.Name) |
---|
| 620 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
| 621 | self.tool.logdebug("Cache store (%s->Groups)" % user.Name) |
---|
| 622 | else : |
---|
| 623 | self.tool.logdebug("Cache hit (%s->Groups)" % user.Name) |
---|
| 624 | else : |
---|
| 625 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
| 626 | return user.Groups |
---|
| 627 | |
---|
[1240] | 628 | def getParentPrintersUserPQuota(self, userpquota) : |
---|
[1364] | 629 | """Returns all user print quota on the printer and all its parents recursively.""" |
---|
[1365] | 630 | upquotas = [ ] |
---|
[1240] | 631 | for printer in self.getParentPrinters(userpquota.Printer) : |
---|
[1395] | 632 | upq = self.getUserPQuota(userpquota.User, printer) |
---|
| 633 | if upq.Exists : |
---|
| 634 | upquotas.append(upq) |
---|
[1240] | 635 | return upquotas |
---|
| 636 | |
---|
[1365] | 637 | def getParentPrintersGroupPQuota(self, grouppquota) : |
---|
| 638 | """Returns all group print quota on the printer and all its parents recursively.""" |
---|
| 639 | gpquotas = [ ] |
---|
| 640 | for printer in self.getParentPrinters(grouppquota.Printer) : |
---|
[1395] | 641 | gpq = self.getGroupPQuota(grouppquota.Group, printer) |
---|
| 642 | if gpq.Exists : |
---|
| 643 | gpquotas.append(gpq) |
---|
[1365] | 644 | return gpquotas |
---|
| 645 | |
---|
[1790] | 646 | def databaseToUserCharset(self, text) : |
---|
| 647 | """Converts from database format (UTF-8) to user's charset.""" |
---|
| 648 | if text is not None : |
---|
| 649 | try : |
---|
| 650 | return unicode(text, "UTF-8").encode(self.tool.getCharset()) |
---|
| 651 | except UnicodeError : |
---|
[1791] | 652 | try : |
---|
| 653 | # Incorrect locale settings ? |
---|
| 654 | return unicode(text, "UTF-8").encode("ISO-8859-15") |
---|
| 655 | except UnicodeError : |
---|
| 656 | pass |
---|
[1790] | 657 | return text |
---|
| 658 | |
---|
| 659 | def userCharsetToDatabase(self, text) : |
---|
| 660 | """Converts from user's charset to database format (UTF-8).""" |
---|
| 661 | if text is not None : |
---|
| 662 | try : |
---|
| 663 | return unicode(text, self.tool.getCharset()).encode("UTF-8") |
---|
| 664 | except UnicodeError : |
---|
[1791] | 665 | try : |
---|
| 666 | # Incorrect locale settings ? |
---|
| 667 | return unicode(text, "ISO-8859-15").encode("UTF-8") |
---|
| 668 | except UnicodeError : |
---|
| 669 | pass |
---|
[1790] | 670 | return text |
---|
| 671 | |
---|
[2266] | 672 | def cleanDates(self, startdate, enddate) : |
---|
| 673 | """Clean the dates to create a correct filter.""" |
---|
[2665] | 674 | if startdate : |
---|
| 675 | startdate = startdate.strip().lower() |
---|
| 676 | if enddate : |
---|
| 677 | enddate = enddate.strip().lower() |
---|
| 678 | if (not startdate) and (not enddate) : |
---|
[2266] | 679 | return (None, None) |
---|
[2268] | 680 | |
---|
| 681 | now = DateTime.now() |
---|
| 682 | nameddates = ('yesterday', 'today', 'now', 'tomorrow') |
---|
[2665] | 683 | datedict = { "start" : startdate, "end" : enddate } |
---|
[2276] | 684 | for limit in datedict.keys() : |
---|
| 685 | dateval = datedict[limit] |
---|
[2665] | 686 | if dateval : |
---|
| 687 | for name in nameddates : |
---|
| 688 | if dateval.startswith(name) : |
---|
| 689 | try : |
---|
| 690 | offset = int(dateval[len(name):]) |
---|
| 691 | except : |
---|
| 692 | offset = 0 |
---|
| 693 | dateval = dateval[:len(name)] |
---|
| 694 | if limit == "start" : |
---|
| 695 | if dateval == "yesterday" : |
---|
| 696 | dateval = (now - 1 + offset).Format("%Y%m%d000000") |
---|
| 697 | elif dateval == "today" : |
---|
| 698 | dateval = (now + offset).Format("%Y%m%d000000") |
---|
| 699 | elif dateval == "now" : |
---|
| 700 | dateval = (now + offset).Format("%Y%m%d%H%M%S") |
---|
| 701 | else : # tomorrow |
---|
| 702 | dateval = (now + 1 + offset).Format("%Y%m%d000000") |
---|
| 703 | else : |
---|
| 704 | if dateval == "yesterday" : |
---|
| 705 | dateval = (now - 1 + offset).Format("%Y%m%d235959") |
---|
| 706 | elif dateval == "today" : |
---|
| 707 | dateval = (now + offset).Format("%Y%m%d235959") |
---|
| 708 | elif dateval == "now" : |
---|
| 709 | dateval = (now + offset).Format("%Y%m%d%H%M%S") |
---|
| 710 | else : # tomorrow |
---|
| 711 | dateval = (now + 1 + offset).Format("%Y%m%d235959") |
---|
| 712 | break |
---|
| 713 | |
---|
| 714 | if not dateval.isdigit() : |
---|
| 715 | dateval = None |
---|
| 716 | else : |
---|
| 717 | lgdateval = len(dateval) |
---|
| 718 | if lgdateval == 4 : |
---|
| 719 | if limit == "start" : |
---|
| 720 | dateval = "%s0101 00:00:00" % dateval |
---|
| 721 | else : |
---|
| 722 | dateval = "%s1231 23:59:59" % dateval |
---|
| 723 | elif lgdateval == 6 : |
---|
| 724 | if limit == "start" : |
---|
| 725 | dateval = "%s01 00:00:00" % dateval |
---|
| 726 | else : |
---|
| 727 | mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval) |
---|
| 728 | dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month) |
---|
| 729 | elif lgdateval == 8 : |
---|
| 730 | if limit == "start" : |
---|
| 731 | dateval = "%s 00:00:00" % dateval |
---|
| 732 | else : |
---|
| 733 | dateval = "%s 23:59:59" % dateval |
---|
| 734 | elif lgdateval == 10 : |
---|
| 735 | if limit == "start" : |
---|
| 736 | dateval = "%s %s:00:00" % (dateval[:8], dateval[8:]) |
---|
| 737 | else : |
---|
| 738 | dateval = "%s %s:59:59" % (dateval[:8], dateval[8:]) |
---|
| 739 | elif lgdateval == 12 : |
---|
| 740 | if limit == "start" : |
---|
| 741 | dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:]) |
---|
| 742 | else : |
---|
| 743 | dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:]) |
---|
| 744 | elif lgdateval == 14 : |
---|
| 745 | dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:]) |
---|
| 746 | else : |
---|
| 747 | dateval = None |
---|
| 748 | try : |
---|
| 749 | DateTime.ISO.ParseDateTime(dateval) |
---|
[2276] | 750 | except : |
---|
[2665] | 751 | dateval = None |
---|
| 752 | datedict[limit] = dateval |
---|
[2276] | 753 | (start, end) = (datedict["start"], datedict["end"]) |
---|
[2665] | 754 | if start and end and (start > end) : |
---|
[2276] | 755 | (start, end) = (end, start) |
---|
| 756 | return (start, end) |
---|
[2266] | 757 | |
---|
[1021] | 758 | def openConnection(pykotatool) : |
---|
[2717] | 759 | """Returns a connection handle to the appropriate database.""" |
---|
[1021] | 760 | backendinfo = pykotatool.config.getStorageBackend() |
---|
[800] | 761 | backend = backendinfo["storagebackend"] |
---|
[695] | 762 | try : |
---|
[1219] | 763 | exec "from pykota.storages import %s as storagebackend" % backend.lower() |
---|
[695] | 764 | except ImportError : |
---|
[773] | 765 | raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend |
---|
[695] | 766 | else : |
---|
[800] | 767 | host = backendinfo["storageserver"] |
---|
| 768 | database = backendinfo["storagename"] |
---|
[1087] | 769 | admin = backendinfo["storageadmin"] or backendinfo["storageuser"] |
---|
| 770 | adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"] |
---|
[1240] | 771 | return storagebackend.Storage(pykotatool, host, database, admin, adminpw) |
---|