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