93 kx #!/usr/bin/env python
93 kx # -*- coding: utf-8 -*-
93 kx #
93 kx # (c) Copyright 2003-2015 HP Development Company, L.P.
93 kx #
93 kx # This program is free software; you can redistribute it and/or modify
93 kx # it under the terms of the GNU General Public License as published by
93 kx # the Free Software Foundation; either version 2 of the License, or
93 kx # (at your option) any later version.
93 kx #
93 kx # This program is distributed in the hope that it will be useful,
93 kx # but WITHOUT ANY WARRANTY; without even the implied warranty of
93 kx # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
93 kx # GNU General Public License for more details.
93 kx #
93 kx # You should have received a copy of the GNU General Public License
93 kx # along with this program; if not, write to the Free Software
93 kx # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
93 kx #
93 kx # Author: Don Welch
93 kx #
93 kx
93 kx
93 kx __version__ = '9.0'
93 kx __title__ = 'Printer/Fax Setup Utility'
93 kx __mod__ = 'hp-setup'
93 kx __doc__ = "Installs HPLIP printers and faxes in the CUPS spooler. Tries to automatically determine the correct PPD file to use. Allows the printing of a testpage. Performs basic fax parameter setup."
93 kx
93 kx # Std Lib
93 kx import sys
93 kx import getopt
93 kx import time
93 kx import os.path
93 kx import re
93 kx import os
93 kx import gzip
93 kx
93 kx
93 kx try:
93 kx import readline
93 kx except ImportError:
93 kx pass
93 kx
93 kx
93 kx # Set LC_ALL=C so that we can properly parse info from CUPS:
93 kx os.environ["LC_ALL"] = "C"
93 kx
93 kx # Local
93 kx from base.g import *
93 kx from base import device, utils, tui, models, module, services, os_utils
93 kx from prnt import cups
93 kx from base.sixext.moves import input
93 kx from base.sixext import to_unicode, from_unicode_to_str
93 kx
93 kx
93 kx try:
93 kx from importlib import import_module
93 kx except ImportError as e:
93 kx log.debug(e)
93 kx from base.utils import dyn_import_mod as import_module
93 kx
93 kx pm = None
93 kx
93 kx def plugin_download_callback(c, s, t):
93 kx pm.update(int(100*c*s/t),
93 kx utils.format_bytes(c*s))
93 kx
93 kx
93 kx def clean_exit(code = 0):
93 kx cups.releaseCupsInstance()
93 kx sys.exit(code)
93 kx
93 kx
93 kx nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
93 kx
93 kx USAGE = [ (__doc__, "", "name", True),
93 kx ("Usage: %s [MODE] [OPTIONS] [SERIAL NO.|USB bus:device|IP|DEVNODE]" % __mod__, "", "summary", True),
93 kx utils.USAGE_MODE,
93 kx utils.USAGE_GUI_MODE,
93 kx utils.USAGE_INTERACTIVE_MODE,
93 kx utils.USAGE_SPACE,
93 kx utils.USAGE_OPTIONS,
93 kx ("Automatic mode:", "-a or --auto (-i mode only)", "option", False),
93 kx ("To specify the port on a multi-port JetDirect:", "--port=<port> (Valid values are 1\*, 2, and 3. \*default)", "option", False),
93 kx ("No testpage in automatic mode:", "-x (-i mode only)", "option", False),
93 kx ("To specify a CUPS printer queue name:", "-p<printer> or --printer=<printer> (-i mode only)", "option", False),
93 kx ("To specify a CUPS fax queue name:", "-f<fax> or --fax=<fax> (-i mode only)", "option", False),
93 kx ("Type of queue(s) to install:", "-t<typelist> or --type=<typelist>. <typelist>: print*, fax\* (\*default) (-i mode only)", "option", False),
93 kx ("To specify the device URI to install:", "-d<device> or --device=<device> (--qt4 mode only)", "option", False),
93 kx ("Remove printers or faxes instead of setting-up:", "-r or --rm or --remove", "option", False),
93 kx utils.USAGE_LANGUAGE,
93 kx utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
93 kx utils.USAGE_HELP,
93 kx ("[SERIAL NO.|USB ID|IP|DEVNODE]", "", "heading", False),
93 kx ("USB bus:device (usb only):", """"xxx:yyy" where 'xxx' is the USB bus and 'yyy' is the USB device. (Note: The ':' and all leading zeros must be present.)""", 'option', False),
93 kx ("", "Use the 'lsusb' command to obtain this information.", "option", False),
93 kx ("IPs (network only):", 'IPv4 address "a.b.c.d" or "hostname"', "option", False),
93 kx ("DEVNODE (parallel only):", '"/dev/parportX", X=0,1,2,...', "option", False),
93 kx ("SERIAL NO. (usb and parallel only):", '"serial no."', "option", True),
93 kx utils.USAGE_EXAMPLES,
93 kx ("Setup using GUI mode:", "$ hp-setup", "example", False),
93 kx ("Setup using GUI mode, specifying usb:", "$ hp-setup -b usb", "example", False),
93 kx ("Setup using GUI mode, specifying an IP:", "$ hp-setup 192.168.0.101", "example", False),
93 kx ("One USB printer attached, automatic:", "$ hp-setup -i -a", "example", False),
93 kx ("USB, IDs specified:", "$ hp-setup -i 001:002", "example", False),
93 kx ("Network:", "$ hp-setup -i 66.35.250.209", "example", False),
93 kx ("Network, Jetdirect port 2:", "$ hp-setup -i --port=2 66.35.250.209", "example", False),
93 kx ("Parallel:", "$ hp-setup -i /dev/parport0", "example", False),
93 kx ("USB or parallel, using serial number:", "$ hp-setup -i US12345678A", "example", False),
93 kx ("USB, automatic:", "$ hp-setup -i --auto 001:002", "example", False),
93 kx ("Parallel, automatic, no testpage:", "$ hp-setup -i -a -x /dev/parport0", "example", False),
93 kx ("Parallel, choose device:", "$ hp-setup -i -b par", "example", False),
93 kx utils.USAGE_SPACE,
93 kx utils.USAGE_NOTES,
93 kx ("1. If no serial number, USB ID, IP, or device node is specified, the USB and parallel busses will be probed for devices.", "", 'note', False),
93 kx ("2. Using 'lsusb' to obtain USB IDs: (example)", "", 'note', False),
93 kx (" $ lsusb", "", 'note', False),
93 kx (" Bus 003 Device 011: ID 03f0:c202 Hewlett-Packard", "", 'note', False),
93 kx (" $ hp-setup --auto 003:011", "", 'note', False),
93 kx (" (Note: You may have to run 'lsusb' from /sbin or another location. Use '$ locate lsusb' to determine this.)", "", 'note', True),
93 kx ("3. Parameters -a, -f, -p, or -t are not valid in GUI (-u) mode.", "", 'note', True),
93 kx utils.USAGE_SPACE,
93 kx utils.USAGE_SEEALSO,
93 kx ("hp-makeuri", "", "seealso", False),
93 kx ("hp-probe", "", "seealso", False),
93 kx ]
93 kx
93 kx
93 kx mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
93 kx (INTERACTIVE_MODE, GUI_MODE),
93 kx (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4, UI_TOOLKIT_QT5),
93 kx run_as_root_ok=True)
93 kx
93 kx opts, device_uri, printer_name, mode, ui_toolkit, loc = \
93 kx mod.parseStdOpts('axp:P:f:t:b:d:rq',
93 kx ['ttl=', 'filter=', 'search=', 'find=',
93 kx 'method=', 'time-out=', 'timeout=',
93 kx 'printer=', 'fax=', 'type=', 'port=',
93 kx 'auto', 'device=', 'rm', 'remove'],
93 kx handle_device_printer=False)
93 kx
93 kx selected_device_name = None
93 kx printer_name = None
93 kx fax_name = None
93 kx bus = None
93 kx setup_print = True
93 kx setup_fax = True
93 kx makeuri = None
93 kx auto = False
93 kx testpage_in_auto_mode = True
93 kx jd_port = 1
93 kx remove = False
93 kx ignore_plugin_check = False
93 kx
93 kx for o, a in opts:
93 kx if o == '-x':
93 kx testpage_in_auto_mode = False
93 kx
93 kx elif o in ('-P', '-p', '--printer'):
93 kx printer_name = a
93 kx
93 kx elif o in ('-f', '--fax'):
93 kx fax_name = a
93 kx
93 kx elif o in ('-d', '--device'):
93 kx device_uri = a
93 kx
93 kx elif o in ('-b', '--bus'):
93 kx bus = [x.lower().strip() for x in a.split(',')]
93 kx if not device.validateBusList(bus, False):
93 kx mod.usage(error_msg=['Invalid bus name'])
93 kx
93 kx elif o in ('-t', '--type'):
93 kx setup_fax, setup_print = False, False
93 kx a = a.strip().lower()
93 kx for aa in a.split(','):
93 kx if aa.strip() not in ('print', 'fax'):
93 kx mod.usage(error_msg=['Invalid type.'])
93 kx
93 kx if aa.strip() == 'print':
93 kx setup_print = True
93 kx
93 kx elif aa.strip() == 'fax':
93 kx if not prop.fax_build:
93 kx log.error("Cannot enable fax setup - HPLIP not built with fax enabled.")
93 kx else:
93 kx setup_fax = True
93 kx
93 kx elif o == '--port':
93 kx try:
93 kx jd_port = int(a)
93 kx except ValueError:
93 kx #log.error("Invalid port number. Must be between 1 and 3 inclusive.")
93 kx mod.usage(error_msg=['Invalid port number. Must be between 1 and 3 inclusive.'])
93 kx
93 kx elif o in ('-a', '--auto'):
93 kx auto = True
93 kx
93 kx elif o in ('-r', '--rm', '--remove'):
93 kx remove = True
93 kx elif o in ('-q'):
93 kx ignore_plugin_check = True
93 kx
93 kx
93 kx try:
93 kx param = mod.args[0]
93 kx except IndexError:
93 kx param = ''
93 kx
93 kx log.debug("param=%s" % param)
93 kx if printer_name is not None:
93 kx selected_device_name = printer_name
93 kx else:
93 kx if fax_name is not None:
93 kx selected_device_name = fax_name
93 kx log.debug("selected_device_name=%s" % selected_device_name)
93 kx
93 kx if mode == GUI_MODE:
93 kx if selected_device_name is not None:
93 kx log.warning("-p or -f option is not supported")
93 kx if ui_toolkit == 'qt3':
93 kx if not utils.canEnterGUIMode():
93 kx log.error("%s requires GUI support (try running with --qt4). Also, try using interactive (-i) mode." % __mod__)
93 kx clean_exit(1)
93 kx else:
93 kx if not utils.canEnterGUIMode4():
93 kx log.error("%s requires GUI support (try running with --qt3). Also, try using interactive (-i) mode." % __mod__)
93 kx clean_exit(1)
93 kx
93 kx if mode == GUI_MODE:
93 kx if ui_toolkit == 'qt3':
93 kx try:
93 kx from qt import *
93 kx from ui import setupform
93 kx except ImportError:
93 kx log.error("Unable to load Qt3 support. Is it installed?")
93 kx clean_exit(1)
93 kx
93 kx if remove:
93 kx log.warn("-r/--rm/--remove not supported in qt3 mode.")
93 kx
93 kx app = QApplication(sys.argv)
93 kx QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
93 kx
93 kx if loc is None:
93 kx loc = user_conf.get('ui', 'loc', 'system')
93 kx if loc.lower() == 'system':
93 kx loc = str(QTextCodec.locale())
93 kx log.debug("Using system locale: %s" % loc)
93 kx
93 kx if loc.lower() != 'c':
93 kx e = 'utf8'
93 kx try:
93 kx l, x = loc.split('.')
93 kx loc = '.'.join([l, e])
93 kx except ValueError:
93 kx l = loc
93 kx loc = '.'.join([loc, e])
93 kx
93 kx log.debug("Trying to load .qm file for %s locale." % loc)
93 kx trans = QTranslator(None)
93 kx
93 kx qm_file = 'hplip_%s.qm' % l
93 kx log.debug("Name of .qm file: %s" % qm_file)
93 kx loaded = trans.load(qm_file, prop.localization_dir)
93 kx
93 kx if loaded:
93 kx app.installTranslator(trans)
93 kx else:
93 kx loc = 'c'
93 kx
93 kx if loc == 'c':
93 kx log.debug("Using default 'C' locale")
93 kx else:
93 kx log.debug("Using locale: %s" % loc)
93 kx QLocale.setDefault(QLocale(loc))
93 kx prop.locale = loc
93 kx try:
93 kx locale.setlocale(locale.LC_ALL, locale.normalize(loc))
93 kx except locale.Error:
93 kx pass
93 kx
93 kx try:
93 kx w = setupform.SetupForm(bus, param, jd_port)
93 kx except Error:
93 kx log.error("Unable to connect to HPLIP I/O. Please (re)start HPLIP and try again.")
93 kx clean_exit(1)
93 kx
93 kx app.setMainWidget(w)
93 kx w.show()
93 kx
93 kx app.exec_loop()
93 kx cups.releaseCupsInstance()
93 kx
93 kx else: # qt4
93 kx # if utils.ui_status[1] == "PyQt4":
93 kx # try:
93 kx # from PyQt4.QtGui import QApplication, QMessageBox
93 kx # from ui4.setupdialog import SetupDialog
93 kx # except ImportError as e:
93 kx # log.error(e)
93 kx # clean_exit(1)
93 kx # elif utils.ui_status[1] == "PyQt5":
93 kx # try:
93 kx # from PyQt5.QtWidgets import QApplication, QMessageBox
93 kx # from ui5.setupdialog import SetupDialog
93 kx # except ImportError as e:
93 kx # log.error(e)
93 kx # clean_exit(1)
93 kx # else:
93 kx # log.error("Unable to load Qt support. Is it installed?")
93 kx # clean_exit(1)
93 kx
93 kx QApplication, ui_package = utils.import_dialog(ui_toolkit)
93 kx ui = import_module(ui_package + ".setupdialog")
93 kx
93 kx app = QApplication(sys.argv)
93 kx log.debug("Sys.argv=%s printer_name=%s param=%s jd_port=%s device_uri=%s remove=%s" % (sys.argv, printer_name, param, jd_port, device_uri, remove))
93 kx dlg = ui.SetupDialog(None, param, jd_port, device_uri, remove)
93 kx dlg.show()
93 kx try:
93 kx log.debug("Starting GUI Event Loop...")
93 kx app.exec_()
93 kx except KeyboardInterrupt:
93 kx clean_exit(0)
93 kx
93 kx
93 kx else: # INTERACTIVE_MODE
93 kx try:
93 kx try:
93 kx from base import password
93 kx except ImportError:
93 kx log.warn("Failed to import Password Object")
93 kx else:
93 kx cups.setPasswordCallback(password.showPasswordPrompt)
93 kx
93 kx #Removing Queue
93 kx if remove:
93 kx tui.header("REMOVING PRINT/FAX QUEUE")
93 kx sts, printer_name, device_uri = mod.getPrinterName(selected_device_name,None,['hp','hpfax'])
93 kx selected_device_name = printer_name
93 kx log.info (log.bold("Removing '%s : %s' Queue"%(printer_name, device_uri)))
93 kx
93 kx status, status_str = cups.cups_operation(cups.delPrinter, INTERACTIVE_MODE, '', None, selected_device_name)
93 kx
93 kx if cups.IPP_OK == status:
93 kx log.info("Successfully deleted %s Print/Fax queue"%selected_device_name)
93 kx utils.sendEvent(EVENT_CUPS_QUEUES_REMOVED,device_uri, printer_name)
93 kx clean_exit(0)
93 kx else:
93 kx log.error("Failed to delete %s Print/Fax queue. Error : %s"%(selected_device_name,status_str))
93 kx clean_exit(1)
93 kx
93 kx if not auto:
93 kx log.info("(Note: Defaults for each question are maked with a '*'. Press <enter> to accept the default.)")
93 kx log.info("")
93 kx
93 kx # ******************************* MAKEURI
93 kx if param:
93 kx device_uri, sane_uri, fax_uri = device.makeURI(param, jd_port)
93 kx
93 kx # ******************************* CONNECTION TYPE CHOOSER
93 kx if not device_uri and bus is None:
93 kx bus = tui.connection_table()
93 kx
93 kx if bus is None:
93 kx clean_exit(0)
93 kx
93 kx log.info("\nUsing connection type: %s" % bus[0])
93 kx
93 kx log.info("")
93 kx
93 kx # ******************************* DEVICE CHOOSER
93 kx
93 kx if not device_uri:
93 kx log.debug("\nDEVICE CHOOSER setup_fax=%s, setup_print=%s" % (setup_fax, setup_print))
93 kx device_uri = mod.getDeviceUri(devices = device.probeDevices(bus))
93 kx
93 kx if not device_uri:
93 kx clean_exit(0)
93 kx
93 kx # ******************************* QUERY MODEL AND COLLECT PPDS
93 kx log.info(log.bold("\nSetting up device: %s\n" % device_uri))
93 kx
93 kx log.info("")
93 kx print_uri = device_uri.replace("hpfax:", "hp:")
93 kx fax_uri = device_uri.replace("hp:", "hpfax:")
93 kx
93 kx back_end, is_hp, bus, model, \
93 kx serial, dev_file, host, zc, port = \
93 kx device.parseDeviceURI(device_uri)
93 kx
93 kx log.debug("Model=%s" % model)
93 kx mq = device.queryModelByURI(device_uri)
93 kx
93 kx if not mq or mq.get('support-type', SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
93 kx log.error("Unsupported printer model.")
93 kx clean_exit(1)
93 kx
93 kx if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED) and setup_fax:
93 kx #log.warning("Cannot setup fax - device does not have fax feature.")
93 kx setup_fax = False
93 kx
93 kx # ******************************* PLUGIN
93 kx
93 kx norm_model = models.normalizeModelName(model).lower()
93 kx plugin = mq.get('plugin', PLUGIN_NONE)
93 kx
93 kx if ignore_plugin_check is False and plugin > PLUGIN_NONE:
93 kx from installer import pluginhandler
93 kx pluginObj = pluginhandler.PluginHandle()
93 kx plugin_sts = pluginObj.getStatus()
93 kx if plugin_sts != pluginhandler.PLUGIN_INSTALLED:
93 kx if plugin_sts == pluginhandler.PLUGIN_VERSION_MISMATCH:
93 kx tui.header("UPDATING PLUGIN")
93 kx else:
93 kx tui.header("PLUG-IN INSTALLATION")
93 kx
93 kx hp_plugin = utils.which('hp-plugin')
93 kx if hp_plugin:
93 kx cmd = "hp-plugin -i"
93 kx
93 kx if os_utils.execute(cmd) != 0:
93 kx log.error("Failed to install Plugin.")
93 kx log.error("The device you are trying to setup requires a binary plug-in. Some functionalities may not work as expected without plug-ins. Please run 'hp-plugin' as normal user to install plug-ins.Visit http://hplipopensource.com for more infomation.")
93 kx clean_exit(1)
93 kx
93 kx ppds = cups.getSystemPPDs()
93 kx
93 kx default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
93 kx
93 kx installed_print_devices = device.getSupportedCUPSDevices(['hp'])
93 kx for d in list(installed_print_devices.keys()):
93 kx for p in installed_print_devices[d]:
93 kx log.debug("found print queue '%s'" % p)
93 kx
93 kx installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
93 kx for d in list(installed_fax_devices.keys()):
93 kx for f in installed_fax_devices[d]:
93 kx log.debug("found fax queue '%s'" % f)
93 kx
93 kx # ******************************* PRINT QUEUE SETUP
93 kx if setup_print:
93 kx
93 kx tui.header("PRINT QUEUE SETUP")
93 kx
93 kx if not auto and print_uri in installed_print_devices:
93 kx log.warning("One or more print queues already exist for this device: %s." %
93 kx ', '.join(installed_print_devices[print_uri]))
93 kx
93 kx ok, setup_print = tui.enter_yes_no("\nWould you like to install another print queue for this device", 'n')
93 kx if not ok: clean_exit(0)
93 kx
93 kx if setup_print:
93 kx if auto:
93 kx printer_name = default_model
93 kx
93 kx printer_default_model = default_model
93 kx
93 kx installed_printer_names = device.getSupportedCUPSPrinterNames(['hp'])
93 kx # Check for duplicate names
93 kx if (device_uri in installed_print_devices and printer_default_model in installed_print_devices[device_uri]) \
93 kx or (printer_default_model in installed_printer_names):
93 kx i = 2
93 kx while True:
93 kx t = printer_default_model + "_%d" % i
93 kx if (t not in installed_printer_names) and(device_uri not in installed_print_devices or t not in installed_print_devices[device_uri]):
93 kx printer_default_model += "_%d" % i
93 kx break
93 kx i += 1
93 kx
93 kx if not auto:
93 kx if printer_name is None:
93 kx while True:
93 kx printer_name = input(log.bold("\nPlease enter a name for this print queue (m=use model name:'%s'*, q=quit) ?" % printer_default_model))
93 kx
93 kx if printer_name.lower().strip() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx if not printer_name or printer_name.lower().strip() == 'm':
93 kx printer_name = printer_default_model
93 kx
93 kx name_ok = True
93 kx
93 kx for d in list(installed_print_devices.keys()):
93 kx for p in installed_print_devices[d]:
93 kx if printer_name == p:
93 kx log.error("A print queue with that name already exists. Please enter a different name.")
93 kx name_ok = False
93 kx break
93 kx
93 kx for d in list(installed_fax_devices.keys()):
93 kx for f in installed_fax_devices[d]:
93 kx if printer_name == f:
93 kx log.error("A fax queue with that name already exists. Please enter a different name.")
93 kx name_ok = False
93 kx break
93 kx
93 kx for c in printer_name:
93 kx if c in cups.INVALID_PRINTER_NAME_CHARS:
93 kx log.error("Invalid character '%s' in printer name. Please enter a name that does not contain this character." % c)
93 kx name_ok = False
93 kx
93 kx if name_ok:
93 kx break
93 kx else:
93 kx printer_name = printer_default_model
93 kx
93 kx log.info("Using queue name: %s" % printer_name)
93 kx
93 kx default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
93 kx
93 kx
93 kx log.info("Locating PPD file... Please wait.")
93 kx print_ppd = cups.getPPDFile2(mq, default_model, ppds)
93 kx
93 kx enter_ppd = False
93 kx if print_ppd is None:
93 kx enter_ppd = True
93 kx log.error("Unable to find an appropriate PPD file.")
93 kx
93 kx else:
93 kx print_ppd, desc = print_ppd
93 kx log.info("\nFound PPD file: %s" % print_ppd)
93 kx
93 kx log.info("Description: %s" % desc)
93 kx #
93 kx if not auto:
93 kx log.info("\nNote: The model number may vary slightly from the actual model number on the device.")
93 kx ok, ans = tui.enter_yes_no("\nDoes this PPD file appear to be the correct one")
93 kx if not ok: clean_exit(0)
93 kx if not ans: enter_ppd = True
93 kx
93 kx
93 kx if enter_ppd:
93 kx enter_ppd = False
93 kx
93 kx ok, enter_ppd = tui.enter_yes_no("\nWould you like to specify the path to the correct PPD file to use", 'n')
93 kx if not ok: clean_exit(0)
93 kx
93 kx if enter_ppd:
93 kx ok = False
93 kx
93 kx while True:
93 kx user_input = input(log.bold("\nPlease enter the full filesystem path to the PPD file to use (q=quit) :"))
93 kx
93 kx if user_input.lower().strip() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx file_path = user_input
93 kx
93 kx if os.path.exists(file_path) and os.path.isfile(file_path):
93 kx
93 kx if file_path.endswith('.gz'):
93 kx nickname = gzip.GzipFile(file_path, 'r').read(4096)
93 kx else:
93 kx nickname = open(file_path, 'r').read(4096)
93 kx
93 kx try:
93 kx desc = nickname_pat.search(nickname).group(1)
93 kx except AttributeError:
93 kx desc = ''
93 kx
93 kx if desc:
93 kx log.info("Description for the file: %s" % desc)
93 kx else:
93 kx log.error("No PPD 'NickName' found. This file may not be a valid PPD file.")
93 kx
93 kx ok, ans = tui.enter_yes_no("\nUse this file")
93 kx if not ok: clean_exit(0)
93 kx if ans: print_ppd = file_path
93 kx
93 kx else:
93 kx log.error("File not found or not an appropriate (PPD) file.")
93 kx
93 kx if ok:
93 kx break
93 kx else:
93 kx log.error("PPD file required. Setup cannot continue. Exiting.")
93 kx clean_exit(1)
93 kx
93 kx if auto:
93 kx location, info = '', '%s Device (Automatically setup by HPLIP)'%(default_model.replace('_',' '))
93 kx else:
93 kx while True:
93 kx location = input(log.bold("Enter a location description for this printer (q=quit) ?"))
93 kx
93 kx if location.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx # TODO: Validate chars
93 kx break
93 kx
93 kx while True:
93 kx info = input(log.bold("Enter additonal information or notes for this printer (q=quit) ?"))
93 kx
93 kx if info.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx # TODO: Validate chars
93 kx break
93 kx
93 kx log.info(log.bold("\nAdding print queue to CUPS:"))
93 kx log.info("Device URI: %s" % print_uri)
93 kx log.info("Queue name: %s" % printer_name)
93 kx log.info("PPD file: %s" % print_ppd)
93 kx log.info("Location: %s" % location)
93 kx log.info("Information: %s" % info)
93 kx
93 kx if not os.path.exists(print_ppd): # assume foomatic: or some such
93 kx add_prnt_args = (printer_name, print_uri, location, '', print_ppd, info)
93 kx else:
93 kx add_prnt_args = (printer_name, print_uri, location, print_ppd, '', info)
93 kx
93 kx status, status_str = cups.cups_operation(cups.addPrinter, INTERACTIVE_MODE, '', None, *add_prnt_args)
93 kx
93 kx log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
93 kx log.debug(device.getSupportedCUPSDevices(['hp']))
93 kx
93 kx if status != cups.IPP_OK:
93 kx log.error("Printer queue setup failed. Error : %s "%status_str)
93 kx clean_exit(1)
93 kx else:
93 kx # sending Event to add this device in hp-systray
93 kx utils.sendEvent(EVENT_CUPS_QUEUES_ADDED,print_uri, printer_name)
93 kx
93 kx # Updating firmware download for supported devices.
93 kx if ignore_plugin_check is False and mq.get('fw-download', False):
93 kx try:
93 kx d = device.Device(print_uri)
93 kx except Error:
93 kx log.error("Error opening device. Firmware download is Failed.")
93 kx else:
93 kx if d.downloadFirmware():
93 kx log.info("Firmware download successful.\n")
93 kx else:
93 kx log.error("Firmware download is Failed.")
93 kx d.close()
93 kx
93 kx # ******************************* FAX QUEUE SETUP
93 kx if setup_fax and not prop.fax_build:
93 kx log.error("Cannot setup fax - HPLIP not built with fax enabled.")
93 kx setup_fax = False
93 kx
93 kx if setup_fax:
93 kx
93 kx try:
93 kx from fax import fax
93 kx except ImportError:
93 kx # This can fail on Python < 2.3 due to the datetime module
93 kx setup_fax = False
93 kx log.warning("Fax setup disabled - Python 2.3+ required.")
93 kx
93 kx log.info("")
93 kx
93 kx if setup_fax:
93 kx
93 kx tui.header("FAX QUEUE SETUP")
93 kx
93 kx if not auto and fax_uri in installed_fax_devices:
93 kx log.warning("One or more fax queues already exist for this device: %s." % ', '.join(installed_fax_devices[fax_uri]))
93 kx ok, setup_fax = tui.enter_yes_no("\nWould you like to install another fax queue for this device", 'n')
93 kx if not ok: clean_exit(0)
93 kx
93 kx if setup_fax:
93 kx if auto: # or fax_name is None:
93 kx fax_name = default_model + '_fax'
93 kx
93 kx fax_default_model = default_model + '_fax'
93 kx
93 kx installed_fax_names = device.getSupportedCUPSPrinterNames(['hpfax'])
93 kx # Check for duplicate names
93 kx if (fax_uri in installed_fax_devices and fax_default_model in installed_fax_devices[fax_uri]) \
93 kx or (fax_default_model in installed_fax_names):
93 kx i = 2
93 kx while True:
93 kx t = fax_default_model + "_%d" % i
93 kx if (t not in installed_fax_names) and (fax_uri not in installed_fax_devices or t not in installed_fax_devices[fax_uri]):
93 kx fax_default_model += "_%d" % i
93 kx break
93 kx i += 1
93 kx
93 kx if not auto:
93 kx if fax_name is None:
93 kx while True:
93 kx fax_name = input(log.bold("\nPlease enter a name for this fax queue (m=use model name:'%s'*, q=quit) ?" % fax_default_model))
93 kx
93 kx if fax_name.lower().strip() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx if not fax_name or fax_name.lower().strip() == 'm':
93 kx fax_name = fax_default_model
93 kx
93 kx name_ok = True
93 kx
93 kx for d in list(installed_print_devices.keys()):
93 kx for p in installed_print_devices[d]:
93 kx if fax_name == p:
93 kx log.error("A print queue with that name already exists. Please enter a different name.")
93 kx name_ok = False
93 kx break
93 kx
93 kx for d in list(installed_fax_devices.keys()):
93 kx for f in installed_fax_devices[d]:
93 kx if fax_name == f:
93 kx log.error("A fax queue with that name already exists. Please enter a different name.")
93 kx name_ok = False
93 kx break
93 kx
93 kx for c in fax_name:
93 kx if c in (' ', '#', '/', '%'):
93 kx log.error("Invalid character '%s' in fax name. Please enter a name that does not contain this character." % c)
93 kx name_ok = False
93 kx
93 kx if name_ok:
93 kx break
93 kx
93 kx else:
93 kx fax_name = fax_default_model
93 kx
93 kx log.info("Using queue name: %s" % fax_name)
93 kx fax_ppd,fax_ppd_type,nick = cups.getFaxPPDFile(mq, fax_name)
93 kx
93 kx if not fax_ppd:
93 kx log.error("Unable to find HP fax PPD file! Please check you HPLIP installation and try again.")
93 kx clean_exit(1)
93 kx
93 kx if auto:
93 kx location, info = '', '%s Fax Device (Automatically setup by HPLIP)'%(default_model.replace('_',' '))
93 kx else:
93 kx while True:
93 kx location = input(log.bold("Enter a location description for this printer (q=quit) ?"))
93 kx
93 kx if location.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx # TODO: Validate chars
93 kx break
93 kx
93 kx while True:
93 kx info = input(log.bold("Enter additonal information or notes for this printer (q=quit) ?"))
93 kx
93 kx if info.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx # TODO: Validate chars
93 kx break
93 kx
93 kx log.info(log.bold("\nAdding fax queue to CUPS:"))
93 kx log.info("Device URI: %s" % fax_uri)
93 kx log.info("Queue name: %s" % fax_name)
93 kx log.info("PPD file: %s" % fax_ppd)
93 kx log.info("Location: %s" % location)
93 kx log.info("Information: %s" % info)
93 kx
93 kx cups.setPasswordPrompt("You do not have permission to add a fax device.")
93 kx if not os.path.exists(fax_ppd): # assume foomatic: or some such
93 kx status, status_str = cups.addPrinter(fax_name, fax_uri,
93 kx location, '', fax_ppd, info)
93 kx else:
93 kx status, status_str = cups.addPrinter(fax_name, fax_uri,
93 kx location, fax_ppd, '', info)
93 kx
93 kx log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
93 kx log.debug(device.getSupportedCUPSDevices(['hpfax']))
93 kx
93 kx if status != cups.IPP_OK:
93 kx log.error("Fax queue setup failed. Error : %s"%status_str)
93 kx clean_exit(1)
93 kx else:
93 kx # sending Event to add this device in hp-systray
93 kx utils.sendEvent(EVENT_CUPS_QUEUES_ADDED,fax_uri, fax_name)
93 kx
93 kx
93 kx
93 kx # ******************************* FAX HEADER SETUP
93 kx tui.header("FAX HEADER SETUP")
93 kx
93 kx if auto:
93 kx setup_fax = False
93 kx else:
93 kx while True:
93 kx user_input = input(log.bold("\nWould you like to perform fax header setup (y=yes*, n=no, q=quit) ?")).strip().lower()
93 kx
93 kx if user_input == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx if not user_input:
93 kx user_input = 'y'
93 kx
93 kx setup_fax = (user_input == 'y')
93 kx
93 kx if user_input in ('y', 'n', 'q'):
93 kx break
93 kx
93 kx log.error("Please enter 'y' or 'n'")
93 kx
93 kx if setup_fax:
93 kx d = fax.getFaxDevice(fax_uri, disable_dbus=True)
93 kx
93 kx try:
93 kx d.open()
93 kx except Error:
93 kx log.error("Unable to communicate with the device. Please check the device and try again.")
93 kx else:
93 kx try:
93 kx tries = 0
93 kx ok = True
93 kx
93 kx while True:
93 kx tries += 1
93 kx
93 kx try:
93 kx current_phone_num = str(d.getPhoneNum())
93 kx current_station_name = to_unicode(d.getStationName())
93 kx except Error:
93 kx log.error("Could not communicate with device. Device may be busy. Please wait for retry...")
93 kx time.sleep(5)
93 kx ok = False
93 kx
93 kx if tries > 12:
93 kx break
93 kx
93 kx else:
93 kx ok = True
93 kx break
93 kx
93 kx if ok:
93 kx while True:
93 kx if current_phone_num:
93 kx phone_num = input(log.bold("\nEnter the fax phone number for this device (c=use current:'%s'*, q=quit) ?" % current_phone_num))
93 kx else:
93 kx phone_num = input(log.bold("\nEnter the fax phone number for this device (q=quit) ?"))
93 kx if phone_num.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx if current_phone_num and (not phone_num or phone_num.strip().lower() == 'c'):
93 kx phone_num = current_phone_num
93 kx
93 kx if len(phone_num) > 50:
93 kx log.error("Phone number length is too long (>50 characters). Please enter a shorter number.")
93 kx continue
93 kx
93 kx ok = True
93 kx for x in phone_num:
93 kx if x not in '0123456789-(+) ':
93 kx log.error("Invalid characters in phone number. Please only use 0-9, -, (, +, and )")
93 kx ok = False
93 kx break
93 kx
93 kx if not ok:
93 kx continue
93 kx
93 kx break
93 kx
93 kx while True:
93 kx if current_station_name:
93 kx station_name = input(log.bold("\nEnter the name and/or company for this device (c=use current:'%s'*, q=quit) ?"%from_unicode_to_str(current_station_name)))
93 kx else:
93 kx station_name = input(log.bold("\nEnter the name and/or company for this device (q=quit) ?"))
93 kx if station_name.strip().lower() == 'q':
93 kx log.info("OK, done.")
93 kx clean_exit(0)
93 kx
93 kx if current_station_name and (not station_name or station_name.strip().lower() == 'c'):
93 kx station_name = current_station_name
93 kx
93 kx ### Here station_name can be unicode or utf-8 sequence.
93 kx ### making sure to convert data to unicode for all the cases.
93 kx try:
93 kx station_name.encode('utf-8')
93 kx except (UnicodeEncodeError,UnicodeDecodeError):
93 kx station_name = station_name.decode('utf-8')
93 kx
93 kx if len(station_name) > 50:
93 kx log.error("Name/company length is too long (>50 characters). Please enter a shorter name/company.")
93 kx continue
93 kx break
93 kx
93 kx try:
93 kx d.setStationName(station_name)
93 kx d.setPhoneNum(phone_num)
93 kx except Error:
93 kx log.error("Could not communicate with device. Device may be busy.")
93 kx else:
93 kx log.info("\nParameters sent to device.")
93 kx
93 kx finally:
93 kx d.close()
93 kx
93 kx # ******************************* TEST PAGE
93 kx if setup_print:
93 kx print_test_page = False
93 kx
93 kx tui.header("PRINTER TEST PAGE")
93 kx
93 kx if auto:
93 kx if testpage_in_auto_mode:
93 kx print_test_page = True
93 kx else:
93 kx ok, print_test_page = tui.enter_yes_no("\nWould you like to print a test page")
93 kx if not ok: clean_exit(0)
93 kx
93 kx if print_test_page:
93 kx path = utils.which('hp-testpage')
93 kx
93 kx if printer_name:
93 kx param = "-p%s" % printer_name
93 kx else:
93 kx param = "-d%s" % print_uri
93 kx
93 kx if len(path) > 0:
93 kx cmd = 'hp-testpage -i %s' % param
93 kx else:
93 kx cmd = 'python ./testpage.py -i %s' % param
93 kx
93 kx os_utils.execute(cmd)
93 kx
93 kx except KeyboardInterrupt:
93 kx log.error("User exit")
93 kx
93 kx cups.releaseCupsInstance()
93 kx log.info("")
93 kx log.info("Done.")
93 kx