| 1 |
## system-config-printer |
| 2 |
|
| 3 |
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc. |
| 4 |
## Authors: |
| 5 |
## Florian Festi <[email protected]> |
| 6 |
## Tim Waugh <[email protected]> |
| 7 |
|
| 8 |
## This program is free software; you can redistribute it and/or modify |
| 9 |
## it under the terms of the GNU General Public License as published by |
| 10 |
## the Free Software Foundation; either version 2 of the License, or |
| 11 |
## (at your option) any later version. |
| 12 |
|
| 13 |
## This program is distributed in the hope that it will be useful, |
| 14 |
## but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
## GNU General Public License for more details. |
| 17 |
|
| 18 |
## You should have received a copy of the GNU General Public License |
| 19 |
## along with this program; if not, write to the Free Software |
| 20 |
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 21 |
|
| 22 |
import cups, pprint, os, tempfile, re, string |
| 23 |
import locale |
| 24 |
from . import _debugprint |
| 25 |
from . import config |
| 26 |
from functools import reduce |
| 27 |
|
| 28 |
class Printer: |
| 29 |
_flags_blacklist = ["options", "local"] |
| 30 |
|
| 31 |
def __init__(self, name, connection, **kw): |
| 32 |
""" |
| 33 |
@param name: printer name |
| 34 |
@type name: string |
| 35 |
@param connection: CUPS connection |
| 36 |
@type connection: CUPS.Connection object |
| 37 |
@param kw: printer attributes |
| 38 |
@type kw: dict indexed by string |
| 39 |
""" |
| 40 |
self.name = name |
| 41 |
self.connection = connection |
| 42 |
self.class_members = [] |
| 43 |
have_kw = len (kw) > 0 |
| 44 |
fetch_attrs = True |
| 45 |
if have_kw: |
| 46 |
self.update (**kw) |
| 47 |
if self.is_class: |
| 48 |
fetch_attrs = True |
| 49 |
else: |
| 50 |
fetch_attrs = False |
| 51 |
|
| 52 |
if fetch_attrs: |
| 53 |
self.getAttributes () |
| 54 |
|
| 55 |
self._ppd = None # load on demand |
| 56 |
|
| 57 |
def __del__ (self): |
| 58 |
if self._ppd is not None: |
| 59 |
os.unlink(self._ppd) |
| 60 |
|
| 61 |
def __repr__ (self): |
| 62 |
return "<cupshelpers.Printer \"%s\">" % self.name |
| 63 |
|
| 64 |
def _expand_flags(self): |
| 65 |
|
| 66 |
def _ascii_lower(str): |
| 67 |
return str.lower(); |
| 68 |
|
| 69 |
prefix = "CUPS_PRINTER_" |
| 70 |
prefix_length = len(prefix) |
| 71 |
|
| 72 |
# loop over cups constants |
| 73 |
for name in cups.__dict__: |
| 74 |
if name.startswith(prefix): |
| 75 |
attr_name = \ |
| 76 |
_ascii_lower(name[prefix_length:]) |
| 77 |
if attr_name in self._flags_blacklist: continue |
| 78 |
if attr_name == "class": attr_name = "is_class" |
| 79 |
# set as attribute |
| 80 |
setattr(self, attr_name, |
| 81 |
bool(self.type & getattr(cups, name))) |
| 82 |
|
| 83 |
def update(self, **kw): |
| 84 |
""" |
| 85 |
Update object from printer attributes. |
| 86 |
|
| 87 |
@param kw: printer attributes |
| 88 |
@type kw: dict indexed by string |
| 89 |
""" |
| 90 |
self.state = kw.get('printer-state', 0) |
| 91 |
self.enabled = self.state != cups.IPP_PRINTER_STOPPED |
| 92 |
self.device_uri = kw.get('device-uri', "") |
| 93 |
self.info = kw.get('printer-info', "") |
| 94 |
self.is_shared = kw.get('printer-is-shared', None) |
| 95 |
self.location = kw.get('printer-location', "") |
| 96 |
self.make_and_model = kw.get('printer-make-and-model', "") |
| 97 |
self.type = kw.get('printer-type', 0) |
| 98 |
self.uri_supported = kw.get('printer-uri-supported', "") |
| 99 |
if type (self.uri_supported) != list: |
| 100 |
self.uri_supported = [self.uri_supported] |
| 101 |
self._expand_flags() |
| 102 |
if self.is_shared is None: |
| 103 |
self.is_shared = not self.not_shared |
| 104 |
del self.not_shared |
| 105 |
self.class_members = kw.get('member-names', []) |
| 106 |
if type (self.class_members) != list: |
| 107 |
self.class_members = [self.class_members] |
| 108 |
self.class_members.sort () |
| 109 |
self.other_attributes = kw |
| 110 |
|
| 111 |
def getAttributes(self): |
| 112 |
""" |
| 113 |
Fetch further attributes for the printer. |
| 114 |
|
| 115 |
Normally only a small set of attributes is fetched. This |
| 116 |
method is for fetching more. |
| 117 |
""" |
| 118 |
attrs = self.connection.getPrinterAttributes(self.name) |
| 119 |
self.attributes = {} |
| 120 |
self.other_attributes = {} |
| 121 |
self.possible_attributes = { |
| 122 |
'landscape' : ('False', ['True', 'False']), |
| 123 |
'page-border' : ('none', ['none', 'single', 'single-thick', |
| 124 |
'double', 'double-thick']), |
| 125 |
} |
| 126 |
|
| 127 |
for key, value in attrs.items(): |
| 128 |
if key.endswith("-default"): |
| 129 |
name = key[:-len("-default")] |
| 130 |
if name in ["job-sheets", "printer-error-policy", |
| 131 |
"printer-op-policy", # handled below |
| 132 |
"notify-events", # cannot be set |
| 133 |
"document-format", # cannot be set |
| 134 |
"notify-lease-duration"]: # cannot be set |
| 135 |
continue |
| 136 |
|
| 137 |
supported = attrs.get(name + "-supported", None) or \ |
| 138 |
self.possible_attributes.get(name, None) or \ |
| 139 |
"" |
| 140 |
|
| 141 |
# Convert a list into a comma-separated string, since |
| 142 |
# it can only really have been misinterpreted as a list |
| 143 |
# by CUPS. |
| 144 |
if isinstance (value, list): |
| 145 |
value = reduce (lambda x, y: x+','+y, value) |
| 146 |
|
| 147 |
self.attributes[name] = value |
| 148 |
|
| 149 |
if name+"-supported" in attrs: |
| 150 |
supported = attrs[name+"-supported"] |
| 151 |
self.possible_attributes[name] = (value, supported) |
| 152 |
elif (not key.endswith ("-supported") and |
| 153 |
key != 'job-sheets-default' and |
| 154 |
key != 'printer-error-policy' and |
| 155 |
key != 'printer-op-policy' and |
| 156 |
not key.startswith ('requesting-user-name-')): |
| 157 |
self.other_attributes[key] = value |
| 158 |
|
| 159 |
self.job_sheet_start, self.job_sheet_end = attrs.get( |
| 160 |
'job-sheets-default', ('none', 'none')) |
| 161 |
self.job_sheets_supported = attrs.get('job-sheets-supported', ['none']) |
| 162 |
self.error_policy = attrs.get('printer-error-policy', 'none') |
| 163 |
self.error_policy_supported = attrs.get( |
| 164 |
'printer-error-policy-supported', ['none']) |
| 165 |
self.op_policy = attrs.get('printer-op-policy', "") or "default" |
| 166 |
self.op_policy_supported = attrs.get( |
| 167 |
'printer-op-policy-supported', ["default"]) |
| 168 |
|
| 169 |
self.default_allow = True |
| 170 |
self.except_users = [] |
| 171 |
if 'requesting-user-name-allowed' in attrs: |
| 172 |
self.except_users = attrs['requesting-user-name-allowed'] |
| 173 |
self.default_allow = False |
| 174 |
elif 'requesting-user-name-denied' in attrs: |
| 175 |
self.except_users = attrs['requesting-user-name-denied'] |
| 176 |
self.except_users_string = ', '.join(self.except_users) |
| 177 |
self.update (**attrs) |
| 178 |
|
| 179 |
def getServer(self): |
| 180 |
""" |
| 181 |
Find out which server defines this printer. |
| 182 |
|
| 183 |
@returns: server URI or None |
| 184 |
""" |
| 185 |
if not self.uri_supported[0].startswith('ipp://'): |
| 186 |
return None |
| 187 |
uri = self.uri_supported[0][6:] |
| 188 |
uri = uri.split('/')[0] |
| 189 |
uri = uri.split(':')[0] |
| 190 |
if uri == "localhost.localdomain": |
| 191 |
uri = "localhost" |
| 192 |
return uri |
| 193 |
|
| 194 |
def getPPD(self): |
| 195 |
""" |
| 196 |
Obtain the printer's PPD. |
| 197 |
|
| 198 |
@returns: cups.PPD object, or False for raw queues |
| 199 |
@raise cups.IPPError: IPP error |
| 200 |
""" |
| 201 |
result = None |
| 202 |
if self._ppd is None: |
| 203 |
try: |
| 204 |
self._ppd = self.connection.getPPD(self.name) |
| 205 |
result = cups.PPD (self._ppd) |
| 206 |
except cups.IPPError as emargs: |
| 207 |
(e, m) = emargs.args |
| 208 |
if e == cups.IPP_NOT_FOUND: |
| 209 |
result = False |
| 210 |
else: |
| 211 |
raise |
| 212 |
|
| 213 |
if result is None and self._ppd is not None: |
| 214 |
result = cups.PPD (self._ppd) |
| 215 |
|
| 216 |
return result |
| 217 |
|
| 218 |
def setOption(self, name, value): |
| 219 |
""" |
| 220 |
Set a printer's option. |
| 221 |
|
| 222 |
@param name: option name |
| 223 |
@type name: string |
| 224 |
@param value: option value |
| 225 |
@type value: option-specific |
| 226 |
""" |
| 227 |
if isinstance (value, float): |
| 228 |
radixchar = locale.nl_langinfo (locale.RADIXCHAR) |
| 229 |
if radixchar != '.': |
| 230 |
# Convert floats to strings, being careful with decimal points. |
| 231 |
value = str (value).replace (radixchar, '.') |
| 232 |
self.connection.addPrinterOptionDefault(self.name, name, value) |
| 233 |
|
| 234 |
def unsetOption(self, name): |
| 235 |
""" |
| 236 |
Unset a printer's option. |
| 237 |
|
| 238 |
@param name: option name |
| 239 |
@type name: string |
| 240 |
""" |
| 241 |
self.connection.deletePrinterOptionDefault(self.name, name) |
| 242 |
|
| 243 |
def setEnabled(self, on, reason=None): |
| 244 |
""" |
| 245 |
Set the printer's enabled state. |
| 246 |
|
| 247 |
@param on: whether it will be enabled |
| 248 |
@type on: bool |
| 249 |
@param reason: reason for this state |
| 250 |
@type reason: string |
| 251 |
""" |
| 252 |
if on: |
| 253 |
self.connection.enablePrinter(self.name) |
| 254 |
else: |
| 255 |
if reason: |
| 256 |
self.connection.disablePrinter(self.name, reason=reason) |
| 257 |
else: |
| 258 |
self.connection.disablePrinter(self.name) |
| 259 |
|
| 260 |
def setAccepting(self, on, reason=None): |
| 261 |
""" |
| 262 |
Set the printer's accepting state. |
| 263 |
|
| 264 |
@param on: whether it will be accepting |
| 265 |
@type on: bool |
| 266 |
@param reason: reason for this state |
| 267 |
@type reason: string |
| 268 |
""" |
| 269 |
if on: |
| 270 |
self.connection.acceptJobs(self.name) |
| 271 |
else: |
| 272 |
if reason: |
| 273 |
self.connection.rejectJobs(self.name, reason=reason) |
| 274 |
else: |
| 275 |
self.connection.rejectJobs(self.name) |
| 276 |
|
| 277 |
def setShared(self,on): |
| 278 |
""" |
| 279 |
Set the printer's shared state. |
| 280 |
|
| 281 |
@param on: whether it will be accepting |
| 282 |
@type on: bool |
| 283 |
""" |
| 284 |
self.connection.setPrinterShared(self.name, on) |
| 285 |
|
| 286 |
def setErrorPolicy (self, policy): |
| 287 |
""" |
| 288 |
Set the printer's error policy. |
| 289 |
|
| 290 |
@param policy: error policy |
| 291 |
@type policy: string |
| 292 |
""" |
| 293 |
self.connection.setPrinterErrorPolicy(self.name, policy) |
| 294 |
|
| 295 |
def setOperationPolicy(self, policy): |
| 296 |
""" |
| 297 |
Set the printer's operation policy. |
| 298 |
|
| 299 |
@param policy: operation policy |
| 300 |
@type policy: string |
| 301 |
""" |
| 302 |
self.connection.setPrinterOpPolicy(self.name, policy) |
| 303 |
|
| 304 |
def setJobSheets(self, start, end): |
| 305 |
""" |
| 306 |
Set the printer's job sheets. |
| 307 |
|
| 308 |
@param start: start sheet |
| 309 |
@type start: string |
| 310 |
@param end: end sheet |
| 311 |
@type end: string |
| 312 |
""" |
| 313 |
self.connection.setPrinterJobSheets(self.name, start, end) |
| 314 |
|
| 315 |
def setAccess(self, allow, except_users): |
| 316 |
""" |
| 317 |
Set access control list. |
| 318 |
|
| 319 |
@param allow: whether to allow by default, otherwise deny |
| 320 |
@type allow: bool |
| 321 |
@param except_users: exception list |
| 322 |
@type except_users: string list |
| 323 |
""" |
| 324 |
if isinstance(except_users, str): |
| 325 |
users = except_users.split() |
| 326 |
users = [u.split(",") for u in users] |
| 327 |
except_users = [] |
| 328 |
for u in users: |
| 329 |
except_users.extend(u) |
| 330 |
except_users = [u.strip() for u in except_users] |
| 331 |
except_users = [_f for _f in except_users if _f] |
| 332 |
|
| 333 |
if allow: |
| 334 |
self.connection.setPrinterUsersDenied(self.name, except_users) |
| 335 |
else: |
| 336 |
self.connection.setPrinterUsersAllowed(self.name, except_users) |
| 337 |
|
| 338 |
def jobsQueued(self, only_tests=False, limit=None): |
| 339 |
""" |
| 340 |
Find out whether jobs are queued for this printer. |
| 341 |
|
| 342 |
@param only_tests: whether to restrict search to test pages |
| 343 |
@type only_tests: bool |
| 344 |
@returns: list of job IDs |
| 345 |
""" |
| 346 |
ret = [] |
| 347 |
try: |
| 348 |
try: |
| 349 |
r = ['job-id', 'job-printer-uri', 'job-name'] |
| 350 |
jobs = self.connection.getJobs (requested_attributes=r) |
| 351 |
except TypeError: |
| 352 |
# requested_attributes requires pycups 1.9.50 |
| 353 |
jobs = self.connection.getJobs () |
| 354 |
except cups.IPPError: |
| 355 |
return ret |
| 356 |
|
| 357 |
for id, attrs in jobs.items(): |
| 358 |
try: |
| 359 |
uri = attrs['job-printer-uri'] |
| 360 |
uri = uri[uri.rindex ('/') + 1:] |
| 361 |
except: |
| 362 |
continue |
| 363 |
if uri != self.name: |
| 364 |
continue |
| 365 |
|
| 366 |
if (not only_tests or |
| 367 |
('job-name' in attrs and |
| 368 |
attrs['job-name'] == 'Test Page')): |
| 369 |
ret.append (id) |
| 370 |
|
| 371 |
if limit is not None and len (ret) == limit: |
| 372 |
break |
| 373 |
return ret |
| 374 |
|
| 375 |
def jobsPreserved(self, limit=None): |
| 376 |
""" |
| 377 |
Find out whether there are preserved jobs for this printer. |
| 378 |
|
| 379 |
@return: list of job IDs |
| 380 |
""" |
| 381 |
ret = [] |
| 382 |
try: |
| 383 |
try: |
| 384 |
r = ['job-id', 'job-printer-uri', 'job-state'] |
| 385 |
jobs = self.connection.getJobs (which_jobs='completed', |
| 386 |
requested_attributes=r) |
| 387 |
except TypeError: |
| 388 |
# requested_attributes requires pycups 1.9.50 |
| 389 |
jobs = self.connection.getJobs (which_jobs='completed') |
| 390 |
except cups.IPPError: |
| 391 |
return ret |
| 392 |
|
| 393 |
for id, attrs in jobs.items(): |
| 394 |
try: |
| 395 |
uri = attrs['job-printer-uri'] |
| 396 |
uri = uri[uri.rindex ('/') + 1:] |
| 397 |
except: |
| 398 |
continue |
| 399 |
if uri != self.name: |
| 400 |
continue |
| 401 |
if (attrs.get ('job-state', |
| 402 |
cups.IPP_JOB_PENDING) < cups.IPP_JOB_COMPLETED): |
| 403 |
continue |
| 404 |
ret.append (id) |
| 405 |
if limit is not None and len (ret) == limit: |
| 406 |
break |
| 407 |
|
| 408 |
return ret |
| 409 |
|
| 410 |
def testsQueued(self, limit=None): |
| 411 |
""" |
| 412 |
Find out whether test jobs are queued for this printer. |
| 413 |
|
| 414 |
@returns: list of job IDs |
| 415 |
""" |
| 416 |
return self.jobsQueued (only_tests=True, limit=limit) |
| 417 |
|
| 418 |
def setAsDefault(self): |
| 419 |
""" |
| 420 |
Set this printer as the system default. |
| 421 |
""" |
| 422 |
self.connection.setDefault(self.name) |
| 423 |
|
| 424 |
# Also need to check system-wide lpoptions because that's how |
| 425 |
# previous Fedora versions set the default (bug #217395). |
| 426 |
with tempfile.TemporaryFile () as f: |
| 427 |
try: |
| 428 |
resource = "/admin/conf/lpoptions" |
| 429 |
self.connection.getFile(resource, fd=f.fileno ()) |
| 430 |
except cups.HTTPError as e: |
| 431 |
(s,) = e.args |
| 432 |
if s in [cups.HTTP_NOT_FOUND, cups.HTTP_AUTHORIZATION_CANCELED]: |
| 433 |
return False |
| 434 |
|
| 435 |
raise cups.HTTPError (s) |
| 436 |
|
| 437 |
f.seek (0) |
| 438 |
lines = [ line.decode('UTF-8') for line in f.readlines () ] |
| 439 |
changed = False |
| 440 |
i = 0 |
| 441 |
for line in lines: |
| 442 |
if line.startswith ("Default "): |
| 443 |
# This is the system-wide default. |
| 444 |
name = line.split (' ')[1] |
| 445 |
if name != self.name: |
| 446 |
# Stop it from over-riding the server default. |
| 447 |
lines[i] = "Dest " + line[8:] |
| 448 |
changed = True |
| 449 |
i += 1 |
| 450 |
|
| 451 |
if changed: |
| 452 |
f.seek (0) |
| 453 |
f.writelines ([ line.encode('UTF-8') for line in lines ]) |
| 454 |
f.truncate () |
| 455 |
f.flush () |
| 456 |
f.seek (0) |
| 457 |
try: |
| 458 |
self.connection.putFile (resource, fd=f.fileno ()) |
| 459 |
except cups.HTTPError: |
| 460 |
return False |
| 461 |
|
| 462 |
return changed |
| 463 |
|
| 464 |
def getPrinters(connection): |
| 465 |
""" |
| 466 |
Obtain a list of printers. |
| 467 |
|
| 468 |
@param connection: CUPS connection |
| 469 |
@type connection: CUPS.Connection object |
| 470 |
@returns: L{Printer} list |
| 471 |
""" |
| 472 |
printers = connection.getPrinters() |
| 473 |
classes = connection.getClasses() |
| 474 |
for name, printer in printers.items(): |
| 475 |
printer = Printer(name, connection, **printer) |
| 476 |
printers[name] = printer |
| 477 |
if name in classes: |
| 478 |
printer.class_members = classes[name] |
| 479 |
printer.class_members.sort() |
| 480 |
return printers |
| 481 |
|
| 482 |
def parseDeviceID (id): |
| 483 |
""" |
| 484 |
Parse an IEEE 1284 Device ID, so that it may be indexed by field name. |
| 485 |
|
| 486 |
@param id: IEEE 1284 Device ID, without the two leading length bytes |
| 487 |
@type id: string |
| 488 |
@returns: dict indexed by field name |
| 489 |
""" |
| 490 |
id_dict = {} |
| 491 |
pieces = id.split(";") |
| 492 |
for piece in pieces: |
| 493 |
if piece.find(":") == -1: |
| 494 |
continue |
| 495 |
name, value = piece.split(":",1) |
| 496 |
id_dict[name.strip ()] = value.strip() |
| 497 |
if "MANUFACTURER" in id_dict: |
| 498 |
id_dict.setdefault("MFG", id_dict["MANUFACTURER"]) |
| 499 |
if "MODEL" in id_dict: |
| 500 |
id_dict.setdefault("MDL", id_dict["MODEL"]) |
| 501 |
if "COMMAND SET" in id_dict: |
| 502 |
id_dict.setdefault("CMD", id_dict["COMMAND SET"]) |
| 503 |
for name in ["MFG", "MDL", "CMD", "CLS", "DES", "SN", "S", "P", "J"]: |
| 504 |
id_dict.setdefault(name, "") |
| 505 |
if id_dict["CMD"] == '': |
| 506 |
id_dict["CMD"] = [] |
| 507 |
else: |
| 508 |
id_dict["CMD"] = id_dict["CMD"].split(',') |
| 509 |
return id_dict |
| 510 |
|
| 511 |
class Device: |
| 512 |
""" |
| 513 |
This class represents a CUPS device. |
| 514 |
""" |
| 515 |
|
| 516 |
def __init__(self, uri, **kw): |
| 517 |
""" |
| 518 |
@param uri: device URI |
| 519 |
@type uri: string |
| 520 |
@param kw: device attributes |
| 521 |
@type kw: dict |
| 522 |
""" |
| 523 |
self.uri = uri |
| 524 |
self.device_class = kw.get('device-class', '') |
| 525 |
self.info = kw.get('device-info', '') |
| 526 |
self.make_and_model = kw.get('device-make-and-model', '') |
| 527 |
self.id = kw.get('device-id', '') |
| 528 |
self.location = kw.get('device-location', '') |
| 529 |
|
| 530 |
uri_pieces = uri.split(":") |
| 531 |
self.type = uri_pieces[0] |
| 532 |
self.is_class = len(uri_pieces)==1 |
| 533 |
|
| 534 |
#self.id = 'MFG:HEWLETT-PACKARD;MDL:DESKJET 990C;CMD:MLC,PCL,PML;CLS:PRINTER;DES:Hewlett-Packard DeskJet 990C;SN:US05N1J00XLG;S:00808880800010032C1000000C2000000;P:0800,FL,B0;J: ;' |
| 535 |
|
| 536 |
self.id_dict = parseDeviceID (self.id) |
| 537 |
|
| 538 |
s = uri.find("serial=") |
| 539 |
if s != -1 and not self.id_dict.get ('SN',''): |
| 540 |
self.id_dict['SN'] = uri[s + 7:] |
| 541 |
|
| 542 |
def __repr__ (self): |
| 543 |
return "<cupshelpers.Device \"%s\">" % self.uri |
| 544 |
|
| 545 |
def __lt__(self, other): |
| 546 |
""" |
| 547 |
Compare devices by order of preference. |
| 548 |
""" |
| 549 |
if other is None: |
| 550 |
return True |
| 551 |
|
| 552 |
if self.is_class != other.is_class: |
| 553 |
if other.is_class: |
| 554 |
return True |
| 555 |
return False |
| 556 |
|
| 557 |
stype = self.type |
| 558 |
if stype == "dnssd": |
| 559 |
if self.uri.find("._ipp") != -1: |
| 560 |
stype = "dnssdi" |
| 561 |
elif self.uri.find("._pdl-datastream") != -1: |
| 562 |
stype = "dnssds" |
| 563 |
elif self.uri.find("._printer") != -1: |
| 564 |
stype = "dnssdl" |
| 565 |
if stype == "usb": |
| 566 |
if self.uri.lower().find("fax") != -1: |
| 567 |
stype = "usbfax" |
| 568 |
otype = other.type |
| 569 |
if otype == "dnssd": |
| 570 |
if other.uri.find("._ipp") != -1: |
| 571 |
otype = "dnssdi" |
| 572 |
elif other.uri.find("._pdl-datastream") != -1: |
| 573 |
otype = "dnssds" |
| 574 |
elif other.uri.find("._printer") != -1: |
| 575 |
otype = "dnssdl" |
| 576 |
if otype == "usb": |
| 577 |
if other.uri.lower().find("fax") != -1: |
| 578 |
otype = "usbfax" |
| 579 |
|
| 580 |
if not self.is_class and (stype != otype): |
| 581 |
# "hp"/"hpfax" before "usb" before * before "parallel" before |
| 582 |
# "serial" |
| 583 |
if otype == "serial": |
| 584 |
return True |
| 585 |
if stype == "serial": |
| 586 |
return False |
| 587 |
if otype == "parallel": |
| 588 |
return True |
| 589 |
if stype == "parallel": |
| 590 |
return False |
| 591 |
if otype == "hp": |
| 592 |
return False |
| 593 |
if stype == "hp": |
| 594 |
return True |
| 595 |
if otype == "hpfax": |
| 596 |
return False |
| 597 |
if stype == "hpfax": |
| 598 |
return True |
| 599 |
if otype == "dnssdi": |
| 600 |
return False |
| 601 |
if stype == "dnssdi": |
| 602 |
return True |
| 603 |
if otype == "ipps": |
| 604 |
return False |
| 605 |
if stype == "ipps": |
| 606 |
return True |
| 607 |
if otype == "ipp": |
| 608 |
return False |
| 609 |
if stype == "ipp": |
| 610 |
return True |
| 611 |
if otype == "dnssds": |
| 612 |
return False |
| 613 |
if stype == "dnssds": |
| 614 |
return True |
| 615 |
if otype == "socket": |
| 616 |
return False |
| 617 |
if stype == "socket": |
| 618 |
return True |
| 619 |
if otype == "dnssdl": |
| 620 |
return False |
| 621 |
if stype == "dnssdl": |
| 622 |
return True |
| 623 |
if otype == "lpd": |
| 624 |
return False |
| 625 |
if stype == "lpd": |
| 626 |
return True |
| 627 |
if otype == "usb": |
| 628 |
return False |
| 629 |
if stype == "usb": |
| 630 |
return True |
| 631 |
if otype == "usbfax": |
| 632 |
return False |
| 633 |
if stype == "usbfax": |
| 634 |
return True |
| 635 |
result = bool(self.id) < bool(other.id) |
| 636 |
if not result: |
| 637 |
result = self.info < other.info |
| 638 |
|
| 639 |
return result |
| 640 |
|
| 641 |
class _GetDevicesCall(object): |
| 642 |
def call (self, connection, kwds): |
| 643 |
if "reply_handler" in kwds: |
| 644 |
self._client_reply_handler = kwds.get ("reply_handler") |
| 645 |
kwds["reply_handler"] = self._reply_handler |
| 646 |
return connection.getDevices (**kwds) |
| 647 |
|
| 648 |
self._client_reply_handler = None |
| 649 |
result = connection.getDevices (**kwds) |
| 650 |
return self._reply_handler (connection, result) |
| 651 |
|
| 652 |
def _reply_handler (self, connection, devices): |
| 653 |
for uri, data in devices.items(): |
| 654 |
device = Device(uri, **data) |
| 655 |
devices[uri] = device |
| 656 |
if device.info != '' and device.make_and_model == '': |
| 657 |
device.make_and_model = device.info |
| 658 |
|
| 659 |
if self._client_reply_handler: |
| 660 |
self._client_reply_handler (connection, devices) |
| 661 |
else: |
| 662 |
return devices |
| 663 |
|
| 664 |
def getDevices(connection, **kw): |
| 665 |
""" |
| 666 |
Obtain a list of available CUPS devices. |
| 667 |
|
| 668 |
@param connection: CUPS connection |
| 669 |
@type connection: cups.Connection object |
| 670 |
@returns: a list of L{Device} objects |
| 671 |
@raise cups.IPPError: IPP Error |
| 672 |
""" |
| 673 |
op = _GetDevicesCall () |
| 674 |
return op.call (connection, kw) |
| 675 |
|
| 676 |
def activateNewPrinter(connection, name): |
| 677 |
""" |
| 678 |
Set a new printer enabled, accepting jobs, and (if necessary) the |
| 679 |
default printer. |
| 680 |
|
| 681 |
@param connection: CUPS connection |
| 682 |
@type connection: cups.Connection object |
| 683 |
@param name: printer name |
| 684 |
@type name: string |
| 685 |
@raise cups.IPPError: IPP error |
| 686 |
""" |
| 687 |
connection.enablePrinter (name) |
| 688 |
connection.acceptJobs (name) |
| 689 |
|
| 690 |
# Set as the default if there is not already a default printer. |
| 691 |
if connection.getDefault () is None: |
| 692 |
connection.setDefault (name) |
| 693 |
|
| 694 |
def copyPPDOptions(ppd1, ppd2): |
| 695 |
""" |
| 696 |
Copy default options between PPDs. |
| 697 |
|
| 698 |
@param ppd1: source PPD |
| 699 |
@type ppd1: cups.PPD object |
| 700 |
@param ppd2: destination PPD |
| 701 |
@type ppd2: cups.PPD object |
| 702 |
""" |
| 703 |
def getPPDGroupOptions(group): |
| 704 |
options = group.options[:] |
| 705 |
for g in group.subgroups: |
| 706 |
options.extend(getPPDGroupOptions(g)) |
| 707 |
return options |
| 708 |
|
| 709 |
def iteratePPDOptions(ppd): |
| 710 |
for group in ppd.optionGroups: |
| 711 |
for option in getPPDGroupOptions(group): |
| 712 |
yield option |
| 713 |
|
| 714 |
for option in iteratePPDOptions(ppd1): |
| 715 |
if option.keyword == "PageRegion": |
| 716 |
continue |
| 717 |
new_option = ppd2.findOption(option.keyword) |
| 718 |
if new_option and option.ui==new_option.ui: |
| 719 |
value = option.defchoice |
| 720 |
for choice in new_option.choices: |
| 721 |
if choice["choice"]==value: |
| 722 |
ppd2.markOption(new_option.keyword, value) |
| 723 |
_debugprint ("set %s = %s" % (repr (new_option.keyword), |
| 724 |
repr (value))) |
| 725 |
|
| 726 |
def setPPDPageSize(ppd, language): |
| 727 |
""" |
| 728 |
Set the PPD page size according to locale. |
| 729 |
|
| 730 |
@param ppd: PPD |
| 731 |
@type ppd: cups.PPD object |
| 732 |
@param language: language, as given by the first element of |
| 733 |
locale.setlocale |
| 734 |
@type language: string |
| 735 |
""" |
| 736 |
# Just set the page size to A4 or Letter, that's all. |
| 737 |
# Use the same method CUPS uses. |
| 738 |
size = 'A4' |
| 739 |
letter = [ 'C', 'POSIX', 'en', 'en_US', 'en_CA', 'fr_CA' ] |
| 740 |
for each in letter: |
| 741 |
if language == each: |
| 742 |
size = 'Letter' |
| •743 |
|
| 744 |
# Use setting in /etc/papersize if available |
| 745 |
try: |
| 746 |
f = open ("/etc/papersize") |
| 747 |
for line in f: |
| 748 |
if line.startswith("#"): |
| 749 |
continue |
| 750 |
if line.strip().lower().startswith("a4"): |
| 751 |
size = 'A4' |
| 752 |
elif line.strip().lower().startswith("letter"): |
| 753 |
size = 'Letter' |
| 754 |
elif line.strip() != "": |
| 755 |
break |
| 756 |
f.close() |
| 757 |
except: |
| 758 |
pass |
| 759 |
|
| 760 |
try: |
| 761 |
ppd.markOption ('PageSize', size) |
| 762 |
_debugprint ("set PageSize = %s" % size) |
| 763 |
except: |
| 764 |
_debugprint ("Failed to set PageSize (%s not available?)" % size) |
| 765 |
|
| 766 |
def missingExecutables(ppd): |
| 767 |
""" |
| 768 |
Check that all relevant executables for a PPD are installed. |
| 769 |
|
| 770 |
@param ppd: PPD |
| 771 |
@type ppd: cups.PPD object |
| 772 |
@returns: string list, representing missing executables |
| 773 |
""" |
| 774 |
|
| 775 |
# First, a local function. How to check that something exists |
| 776 |
# in a path: |
| 777 |
def pathcheck (name, path="/usr/bin:/bin"): |
| 778 |
if name == "-": |
| 779 |
# A filter of "-" means that no filter is required, |
| 780 |
# i.e. the device accepts the given format as-is. |
| 781 |
return "builtin" |
| 782 |
# Strip out foomatic '%'-style place-holders. |
| 783 |
p = name.find ('%') |
| 784 |
if p != -1: |
| 785 |
name = name[:p] |
| 786 |
if len (name) == 0: |
| 787 |
return "true" |
| 788 |
if name[0] == '/': |
| 789 |
if os.access (name, os.X_OK): |
| 790 |
_debugprint ("%s: found" % name) |
| 791 |
return name |
| 792 |
else: |
| 793 |
_debugprint ("%s: NOT found" % name) |
| 794 |
return None |
| 795 |
if name.find ("=") != -1: |
| 796 |
return "builtin" |
| 797 |
if name in [ ":", ".", "[", "alias", "bind", "break", "cd", |
| 798 |
"continue", "declare", "echo", "else", "eval", |
| 799 |
"exec", "exit", "export", "fi", "if", "kill", "let", |
| 800 |
"local", "popd", "printf", "pushd", "pwd", "read", |
| 801 |
"readonly", "set", "shift", "shopt", "source", |
| 802 |
"test", "then", "trap", "type", "ulimit", "umask", |
| 803 |
"unalias", "unset", "wait" ]: |
| 804 |
return "builtin" |
| 805 |
for component in path.split (':'): |
| 806 |
file = component.rstrip (os.path.sep) + os.path.sep + name |
| 807 |
if os.access (file, os.X_OK): |
| 808 |
_debugprint ("%s: found" % file) |
| 809 |
return file |
| 810 |
_debugprint ("%s: NOT found in %s" % (name, path)) |
| 811 |
return None |
| 812 |
|
| 813 |
exes_to_install = [] |
| 814 |
|
| 815 |
def add_missing (exe): |
| 816 |
# Strip out foomatic '%'-style place-holders. |
| 817 |
p = exe.find ('%') |
| 818 |
if p != -1: |
| 819 |
exe = exe[:p] |
| 820 |
|
| 821 |
exes_to_install.append (exe) |
| 822 |
|
| 823 |
# Find a 'FoomaticRIPCommandLine' attribute. |
| 824 |
exe = exepath = None |
| 825 |
attr = ppd.findAttr ('FoomaticRIPCommandLine') |
| 826 |
if attr: |
| 827 |
# Foomatic RIP command line to check. |
| 828 |
cmdline = attr.value.replace ('&&\n', '') |
| 829 |
cmdline = cmdline.replace ('"', '"') |
| 830 |
cmdline = cmdline.replace ('<', '<') |
| 831 |
cmdline = cmdline.replace ('>', '>') |
| 832 |
if (cmdline.find ("(") != -1 or |
| 833 |
cmdline.find ("&") != -1): |
| 834 |
# Don't try to handle sub-shells or unreplaced HTML entities. |
| 835 |
cmdline = "" |
| 836 |
|
| 837 |
# Strip out foomatic '%'-style place-holders |
| 838 |
pipes = cmdline.split (';') |
| 839 |
for pipe in pipes: |
| 840 |
cmds = pipe.strip ().split ('|') |
| 841 |
for cmd in cmds: |
| 842 |
args = cmd.strip ().split (' ') |
| 843 |
exe = args[0] |
| 844 |
exepath = pathcheck (exe) |
| 845 |
if not exepath: |
| 846 |
add_missing (exe) |
| 847 |
continue |
| 848 |
|
| 849 |
# Main executable found. But if it's 'gs', |
| 850 |
# perhaps there is an IJS server we also need |
| 851 |
# to check. |
| 852 |
if os.path.basename (exepath) == 'gs': |
| 853 |
argn = len (args) |
| 854 |
argi = 1 |
| 855 |
search = "-sIjsServer=" |
| 856 |
while argi < argn: |
| 857 |
arg = args[argi] |
| 858 |
if arg.startswith (search): |
| 859 |
exe = arg[len (search):] |
| 860 |
exepath = pathcheck (exe) |
| 861 |
if not exepath: |
| 862 |
add_missing (exe) |
| 863 |
|
| 864 |
break |
| 865 |
|
| 866 |
argi += 1 |
| 867 |
|
| 868 |
if not exepath: |
| 869 |
# Next pipe. |
| 870 |
break |
| 871 |
|
| 872 |
if exepath or not exe: |
| 873 |
# Look for '*cupsFilter' lines in the PPD and check that |
| 874 |
# the filters are installed. |
| 875 |
(tmpfd, tmpfname) = tempfile.mkstemp (text=True) |
| 876 |
os.unlink (tmpfname) |
| 877 |
ppd.writeFd (tmpfd) |
| 878 |
os.lseek (tmpfd, 0, os.SEEK_SET) |
| 879 |
f = os.fdopen (tmpfd, "rt", encoding="utf-8") |
| 880 |
search = "*cupsFilter:" |
| 881 |
for line in f: |
| 882 |
if line.startswith (search): |
| 883 |
line = line[len (search):].strip ().strip ('"') |
| 884 |
try: |
| 885 |
(mimetype, cost, exe) = line.split (' ') |
| 886 |
except: |
| 887 |
continue |
| 888 |
|
| 889 |
exepath = pathcheck (exe, |
| 890 |
config.cupsserverbindir + "/filter:" |
| 891 |
"/usr/lib64/cups/filter") |
| 892 |
if not exepath: |
| 893 |
add_missing (config.cupsserverbindir + "/filter/" + exe) |
| 894 |
|
| 895 |
return exes_to_install |
| 896 |
|
| 897 |
def missingPackagesAndExecutables(ppd): |
| 898 |
""" |
| 899 |
Check that all relevant executables for a PPD are installed. |
| 900 |
|
| 901 |
@param ppd: PPD |
| 902 |
@type ppd: cups.PPD object |
| 903 |
@returns: string list pair, representing missing packages and |
| 904 |
missing executables |
| 905 |
""" |
| 906 |
executables = missingExecutables(ppd) |
| 907 |
return ([], executables) |
| 908 |
|
| 909 |
def _main(): |
| 910 |
c = cups.Connection() |
| 911 |
#printers = getPrinters(c) |
| 912 |
for device in getDevices(c).values(): |
| 913 |
print (device.uri, device.id_dict) |
| 914 |
|
| 915 |
if __name__=="__main__": |
| 916 |
_main() |