| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
## system-config-printer |
| 4 |
|
| 5 |
## Copyright (C) 2008, 2011, 2014 Red Hat, Inc. |
| 6 |
## Copyright (C) 2008 Till Kamppeter <[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 urllib.request, urllib.parse, urllib.error, platform, threading, traceback |
| 23 |
import sys |
| 24 |
from xml.etree.ElementTree import XML |
| 25 |
from . import Device |
| 26 |
from . import _debugprint |
| 27 |
|
| 28 |
__all__ = ['OpenPrinting'] |
| 29 |
|
| 30 |
HTTPS_TIMEOUT = 15.0 |
| 31 |
|
| 32 |
def _normalize_space (text): |
| 33 |
result = text.strip () |
| 34 |
result = result.replace ('\n', ' ') |
| 35 |
i = result.find (' ') |
| 36 |
while i != -1: |
| 37 |
result = result.replace (' ', ' ') |
| 38 |
i = result.find (' ') |
| 39 |
return result |
| 40 |
|
| 41 |
class _QueryThread (threading.Thread): |
| 42 |
def __init__ (self, parent, parameters, callback, user_data=None): |
| 43 |
threading.Thread.__init__ (self) |
| 44 |
self.parent = parent |
| 45 |
self.parameters = parameters |
| 46 |
self.callback = callback |
| 47 |
self.user_data = user_data |
| 48 |
self.result = b'' |
| 49 |
|
| 50 |
self.setDaemon (True) |
| 51 |
_debugprint ("+%s" % self) |
| 52 |
|
| 53 |
def __del__ (self): |
| 54 |
_debugprint ("-%s" % self) |
| 55 |
|
| 56 |
def run (self): |
| 57 |
|
| 58 |
# CGI script to be executed |
| 59 |
query_command = "/query.cgi" |
| 60 |
# Headers for the post request |
| 61 |
headers = {"Content-type": "application/x-www-form-urlencoded", |
| 62 |
"Accept": "text/plain"} |
| 63 |
params = ("%s&uilanguage=%s&locale=%s" % |
| 64 |
(urllib.parse.urlencode (self.parameters), |
| 65 |
self.parent.language[0], |
| 66 |
self.parent.language[0])) |
| 67 |
self.url = "https://%s%s?%s" % (self.parent.base_url, query_command, params) |
| 68 |
# Send request |
| 69 |
self.result = b'' |
| 70 |
status = 1 |
| 71 |
try: |
| 72 |
req = urllib.request.Request(self.url, headers=headers) |
| 73 |
with urllib.request.urlopen(req, timeout=HTTPS_TIMEOUT) as resp: |
| 74 |
self.result = resp.read() |
| 75 |
status = 0 |
| 76 |
except: |
| 77 |
self.result = sys.exc_info() |
| 78 |
|
| 79 |
_debugprint ("%s: query complete" % self) |
| 80 |
if self.callback is not None: |
| 81 |
self.callback (status, self.user_data, self.result) |
| 82 |
|
| 83 |
class OpenPrinting: |
| 84 |
def __init__(self, language=None): |
| 85 |
""" |
| 86 |
@param language: language, as given by the first element of |
| 87 |
locale.setlocale(). |
| 88 |
@type language: string |
| 89 |
""" |
| 90 |
if language is None: |
| 91 |
import locale |
| 92 |
try: |
| 93 |
language = locale.getlocale(locale.LC_MESSAGES) |
| 94 |
except locale.Error: |
| 95 |
language = 'C' |
| 96 |
self.language = language |
| 97 |
|
| 98 |
# XXX Read configuration file. |
| 99 |
self.base_url = "www.openprinting.org" |
| 100 |
|
| 101 |
# Restrictions on driver choices XXX Parameters to be taken from |
| 102 |
# config file |
| 103 |
self.onlyfree = 1 |
| 104 |
self.onlymanufacturer = 0 |
| 105 |
_debugprint ("OpenPrinting: Init %s %s %s" % (self.language, self.onlyfree, self.onlymanufacturer)) |
| 106 |
_debugprint ("+%s" % self) |
| 107 |
|
| 108 |
def __del__ (self): |
| 109 |
_debugprint ("-%s" % self) |
| 110 |
|
| 111 |
def cancelOperation(self, handle): |
| 112 |
""" |
| 113 |
Cancel an operation. |
| 114 |
|
| 115 |
@param handle: query/operation handle |
| 116 |
""" |
| 117 |
# Just prevent the callback. |
| 118 |
try: |
| 119 |
handle.callback = None |
| 120 |
except: |
| 121 |
pass |
| 122 |
|
| 123 |
def webQuery(self, parameters, callback, user_data=None): |
| 124 |
""" |
| 125 |
Run a web query for a driver. |
| 126 |
|
| 127 |
@type parameters: dict |
| 128 |
@param parameters: URL parameters |
| 129 |
@type callback: function |
| 130 |
@param callback: callback function, taking (integer, user_data, string) |
| 131 |
parameters with the first parameter being the status code, zero for |
| 132 |
success |
| 133 |
@return: query handle |
| 134 |
""" |
| 135 |
the_thread = _QueryThread (self, parameters, callback, user_data) |
| 136 |
the_thread.start() |
| 137 |
return the_thread |
| 138 |
|
| 139 |
def searchPrinters(self, searchterm, callback, user_data=None): |
| 140 |
""" |
| 141 |
Search for printers using a search term. |
| 142 |
|
| 143 |
@type searchterm: string |
| 144 |
@param searchterm: search term |
| 145 |
@type callback: function |
| 146 |
@param callback: callback function, taking (integer, user_data, string) |
| 147 |
parameters with the first parameter being the status code, zero for |
| 148 |
success |
| 149 |
@return: query handle |
| 150 |
""" |
| 151 |
|
| 152 |
def parse_result (status, data, result): |
| 153 |
(callback, user_data) = data |
| 154 |
if status != 0: |
| 155 |
callback (status, user_data, result) |
| 156 |
return |
| 157 |
|
| 158 |
status = 0 |
| 159 |
printers = {} |
| 160 |
try: |
| 161 |
root = XML (result) |
| 162 |
# We store the printers as a dict of: |
| 163 |
# foomatic_id: displayname |
| 164 |
|
| 165 |
for printer in root.findall ("printer"): |
| 166 |
id = printer.find ("id") |
| 167 |
make = printer.find ("make") |
| 168 |
model = printer.find ("model") |
| 169 |
if id is not None and make is not None and model is not None: |
| 170 |
idtxt = id.text |
| 171 |
maketxt = make.text |
| 172 |
modeltxt = model.text |
| 173 |
if idtxt and maketxt and modeltxt: |
| 174 |
printers[idtxt] = maketxt + " " + modeltxt |
| 175 |
except: |
| 176 |
status = 1 |
| 177 |
printers = sys.exc_info () |
| 178 |
|
| 179 |
_debugprint ("searchPrinters/parse_result: OpenPrinting entries: %s" % repr(printers)) |
| 180 |
try: |
| 181 |
callback (status, user_data, printers) |
| 182 |
except: |
| 183 |
(type, value, tb) = sys.exc_info () |
| 184 |
tblast = traceback.extract_tb (tb, limit=None) |
| 185 |
if len (tblast): |
| 186 |
tblast = tblast[:len (tblast) - 1] |
| 187 |
extxt = traceback.format_exception_only (type, value) |
| 188 |
for line in traceback.format_tb(tb): |
| 189 |
print (line.strip ()) |
| 190 |
print (extxt[0].strip ()) |
| 191 |
|
| 192 |
# Common parameters for the request |
| 193 |
params = { 'type': 'printers', |
| 194 |
'printer': searchterm, |
| 195 |
'format': 'xml' } |
| 196 |
_debugprint ("searchPrinters: Querying OpenPrinting: %s" % repr(params)) |
| 197 |
return self.webQuery(params, parse_result, (callback, user_data)) |
| 198 |
|
| 199 |
def listDrivers(self, model, callback, user_data=None, extra_options=None): |
| 200 |
""" |
| 201 |
Obtain a list of printer drivers. |
| 202 |
|
| 203 |
@type model: string or cupshelpers.Device |
| 204 |
@param model: foomatic printer model string or a cupshelpers.Device |
| 205 |
object |
| 206 |
@type callback: function |
| 207 |
@param callback: callback function, taking (integer, user_data, string) |
| 208 |
parameters with the first parameter being the status code, zero for |
| 209 |
success |
| 210 |
@type extra_options: string -> string dictionary |
| 211 |
@param extra_options: Additional search options, see |
| 212 |
http://www.linuxfoundation.org/en/OpenPrinting/Database/Query |
| 213 |
@return: query handle |
| 214 |
""" |
| 215 |
|
| 216 |
def parse_result (status, data, result): |
| 217 |
(callback, user_data) = data |
| 218 |
if status != 0: |
| 219 |
callback (status, user_data, result) |
| 220 |
|
| 221 |
try: |
| 222 |
# filter out invalid UTF-8 to avoid breaking the XML parser |
| 223 |
result = result.decode('UTF-8', errors='replace').encode('UTF-8') |
| 224 |
root = XML (result) |
| 225 |
drivers = {} |
| 226 |
# We store the drivers as a dict of: |
| 227 |
# foomatic_id: |
| 228 |
# { 'name': name, |
| 229 |
# 'url': url, |
| 230 |
# 'supplier': supplier, |
| 231 |
# 'license': short license string e.g. GPLv2, |
| 232 |
# 'licensetext': license text (Plain text), |
| 233 |
# 'nonfreesoftware': Boolean, |
| 234 |
# 'thirdpartysupplied': Boolean, |
| 235 |
# 'manufacturersupplied': Boolean, |
| 236 |
# 'patents': Boolean, |
| 237 |
# 'supportcontacts' (optional): |
| 238 |
# list of { 'name', |
| 239 |
# 'url', |
| 240 |
# 'level', |
| 241 |
# } |
| 242 |
# 'shortdescription': short description, |
| 243 |
# 'recommended': Boolean, |
| 244 |
# 'functionality': |
| 245 |
# { 'text': integer percentage, |
| 246 |
# 'lineart': integer percentage, |
| 247 |
# 'graphics': integer percentage, |
| 248 |
# 'photo': integer percentage, |
| 249 |
# 'speed': integer percentage, |
| 250 |
# } |
| 251 |
# 'packages' (optional): |
| 252 |
# { arch: |
| 253 |
# { file: |
| 254 |
# { 'url': url, |
| 255 |
# 'fingerprint': signature key fingerprint URL |
| 256 |
# 'realversion': upstream version string, |
| 257 |
# 'version': packaged version string, |
| 258 |
# 'release': package release string |
| 259 |
# } |
| 260 |
# } |
| 261 |
# } |
| 262 |
# 'ppds' (optional): |
| 263 |
# URL string list |
| 264 |
# } |
| 265 |
# There is more information in the raw XML, but this |
| 266 |
# can be added to the Python structure as needed. |
| 267 |
|
| 268 |
for driver in root.findall ('driver'): |
| 269 |
id = driver.attrib.get ('id') |
| 270 |
if id is None: |
| 271 |
continue |
| 272 |
|
| 273 |
dict = {} |
| 274 |
for attribute in ['name', 'url', 'supplier', 'license', |
| 275 |
'shortdescription' ]: |
| 276 |
element = driver.find (attribute) |
| 277 |
if element is not None and element.text is not None: |
| 278 |
dict[attribute] = _normalize_space (element.text) |
| 279 |
|
| 280 |
element = driver.find ('licensetext') |
| 281 |
if element is not None and element.text is not None: |
| 282 |
dict['licensetext'] = element.text |
| 283 |
if not 'licensetext' in dict or \ |
| 284 |
dict['licensetext'] is None: |
| 285 |
element = driver.find ('licenselink') |
| 286 |
if element is not None: |
| 287 |
license_url = element.text |
| 288 |
if license_url is not None: |
| 289 |
try: |
| 290 |
with urllib.request.urlopen(license_url, timeout=HTTPS_TIMEOUT) as resp: |
| 291 |
dict['licensetext'] = resp.read().decode('utf-8') |
| 292 |
except: |
| 293 |
_debugprint('Cannot retrieve %s' % |
| 294 |
license_url) |
| 295 |
|
| 296 |
for boolean in ['nonfreesoftware', 'recommended', |
| 297 |
'patents', 'thirdpartysupplied', |
| 298 |
'manufacturersupplied']: |
| 299 |
dict[boolean] = driver.find (boolean) is not None |
| 300 |
|
| 301 |
# Make a 'freesoftware' tag for compatibility with |
| 302 |
# how the OpenPrinting API used to work (see trac |
| 303 |
# #74). |
| 304 |
dict['freesoftware'] = not dict['nonfreesoftware'] |
| 305 |
|
| 306 |
supportcontacts = [] |
| 307 |
container = driver.find ('supportcontacts') |
| 308 |
if container is not None: |
| 309 |
for sc in container.findall ('supportcontact'): |
| 310 |
supportcontact = {} |
| 311 |
if sc.text is not None: |
| 312 |
supportcontact['name'] = \ |
| 313 |
_normalize_space (sc.text) |
| 314 |
else: |
| 315 |
supportcontact['name'] = "" |
| 316 |
supportcontact['url'] = sc.attrib.get ('url') |
| 317 |
supportcontact['level'] = sc.attrib.get ('level') |
| 318 |
supportcontacts.append (supportcontact) |
| 319 |
|
| 320 |
if supportcontacts: |
| 321 |
dict['supportcontacts'] = supportcontacts |
| 322 |
|
| 323 |
if 'name' not in dict or 'url' not in dict: |
| 324 |
continue |
| 325 |
|
| 326 |
container = driver.find ('functionality') |
| 327 |
if container is not None: |
| 328 |
functionality = {} |
| 329 |
for attribute in ['text', 'lineart', 'graphics', |
| 330 |
'photo', 'speed']: |
| 331 |
element = container.find (attribute) |
| 332 |
if element is not None: |
| 333 |
functionality[attribute] = element.text |
| 334 |
if functionality: |
| 335 |
dict[container.tag] = functionality |
| 336 |
|
| 337 |
packages = {} |
| 338 |
container = driver.find ('packages') |
| 339 |
if container is not None: |
| 340 |
for arch in list(container): |
| 341 |
rpms = {} |
| 342 |
for package in arch.findall ('package'): |
| 343 |
rpm = {} |
| 344 |
for attribute in ['realversion','version', |
| 345 |
'release', 'url', 'pkgsys', |
| 346 |
'fingerprint']: |
| 347 |
element = package.find (attribute) |
| 348 |
if element is not None: |
| 349 |
rpm[attribute] = element.text |
| 350 |
|
| 351 |
repositories = package.find ('repositories') |
| 352 |
if repositories is not None: |
| 353 |
for pkgsys in list(repositories): |
| 354 |
rpm.setdefault('repositories', {})[pkgsys.tag] = pkgsys.text |
| 355 |
|
| 356 |
rpms[package.attrib['file']] = rpm |
| 357 |
packages[arch.tag] = rpms |
| 358 |
|
| 359 |
if packages: |
| 360 |
dict['packages'] = packages |
| 361 |
|
| 362 |
ppds = [] |
| 363 |
container = driver.find ('ppds') |
| 364 |
if container is not None: |
| 365 |
for each in list(container): |
| 366 |
ppds.append (each.text) |
| 367 |
|
| 368 |
if ppds: |
| 369 |
dict['ppds'] = ppds |
| 370 |
|
| 371 |
drivers[id] = dict |
| 372 |
_debugprint ("listDrivers/parse_result: OpenPrinting entries: %s" % repr(drivers)) |
| 373 |
callback (0, user_data, drivers) |
| 374 |
except: |
| 375 |
callback (1, user_data, sys.exc_info ()) |
| 376 |
|
| 377 |
if isinstance(model, Device): |
| 378 |
model = model.id |
| 379 |
|
| 380 |
architecture = platform.machine() |
| 381 |
|
| 382 |
# On Intel, we could be running a 32bit user space with a 64bit kernel, in |
| 383 |
# which case platform.machine() will return x86_64, leading to downloading |
| 384 |
# the wrong printer driver, so we make sure we ask for i386 in that case. |
| 385 |
if architecture == 'x86_64' and platform.architecture()[0] == '32bit': |
| 386 |
architecture = 'i386' |
| 387 |
|
| 388 |
params = { 'type': 'drivers', |
| 389 |
'moreinfo': '1', |
| 390 |
'showprinterid': '1', |
| 391 |
'onlynewestdriverpackages': '1', |
| 392 |
'architectures': architecture, |
| 393 |
'noobsoletes': '1', |
| 394 |
'onlyfree': str (self.onlyfree), |
| 395 |
'onlymanufacturer': str (self.onlymanufacturer), |
| 396 |
'printer': model, |
| 397 |
'format': 'xml'} |
| 398 |
if extra_options: |
| 399 |
params.update(extra_options) |
| 400 |
_debugprint ("listDrivers: Querying OpenPrinting: %s" % repr(params)) |
| 401 |
return self.webQuery(params, parse_result, (callback, user_data)) |
| 402 |
|
| 403 |
def _simple_gui (): |
| 404 |
from gi.repository import Gdk |
| 405 |
from gi.repository import Gtk |
| 406 |
import pprint |
| 407 |
Gdk.threads_init () |
| 408 |
class QueryApp: |
| 409 |
def __init__(self): |
| 410 |
self.openprinting = OpenPrinting() |
| 411 |
self.main = Gtk.Dialog (title="OpenPrinting query application", |
| 412 |
transient_for=None, modal=True) |
| 413 |
self.main.add_buttons (Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE, |
| 414 |
"Search", 10, |
| 415 |
"List", 20) |
| 416 |
self.main.set_border_width (6) |
| 417 |
self.main.vbox.set_spacing (2) |
| 418 |
vbox = Gtk.VBox.new (False, 6) |
| 419 |
self.main.vbox.pack_start (vbox, True, True, 0) |
| 420 |
vbox.set_border_width (6) |
| 421 |
self.entry = Gtk.Entry () |
| 422 |
vbox.pack_start (self.entry, False, False, 6) |
| 423 |
sw = Gtk.ScrolledWindow () |
| 424 |
self.tv = Gtk.TextView () |
| 425 |
sw.add (self.tv) |
| 426 |
vbox.pack_start (sw, True, True, 6) |
| 427 |
self.main.connect ("response", self.response) |
| 428 |
self.main.show_all () |
| 429 |
|
| 430 |
def response (self, dialog, response): |
| 431 |
if (response == Gtk.ResponseType.CLOSE or |
| 432 |
response == Gtk.ResponseType.DELETE_EVENT): |
| 433 |
Gtk.main_quit () |
| 434 |
|
| 435 |
if response == 10: |
| 436 |
# Run a query. |
| 437 |
self.openprinting.searchPrinters (self.entry.get_text (), |
| 438 |
self.search_printers_callback) |
| 439 |
|
| 440 |
if response == 20: |
| 441 |
self.openprinting.listDrivers (self.entry.get_text (), |
| 442 |
self.list_drivers_callback) |
| 443 |
|
| 444 |
def search_printers_callback (self, status, user_data, printers): |
| 445 |
if status != 0: |
| 446 |
raise printers[1] |
| 447 |
|
| 448 |
text = "" |
| 449 |
for printer in printers.values (): |
| 450 |
text += printer + "\n" |
| 451 |
Gdk.threads_enter () |
| 452 |
self.tv.get_buffer ().set_text (text) |
| 453 |
Gdk.threads_leave () |
| 454 |
|
| 455 |
def list_drivers_callback (self, status, user_data, drivers): |
| 456 |
if status != 0: |
| 457 |
raise drivers[1] |
| 458 |
|
| 459 |
text = pprint.pformat (drivers) |
| 460 |
Gdk.threads_enter () |
| 461 |
self.tv.get_buffer ().set_text (text) |
| 462 |
Gdk.threads_leave () |
| 463 |
|
| 464 |
def query_callback (self, status, user_data, result): |
| 465 |
Gdk.threads_enter () |
| 466 |
self.tv.get_buffer ().set_text (str (result)) |
| 467 |
open ("result.xml", "w").write (str (result)) |
| 468 |
Gdk.threads_leave () |
| 469 |
|
| 470 |
q = QueryApp() |
| 471 |
Gtk.main () |