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