def refresh(self, which_jobs=None, refresh_all=True): debugprint ("refresh") self.emit ('refresh') if which_jobs != None: self.which_jobs = which_jobs user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: self.emit ('cups-connection-error') cups.setUser (user) return if self.sub_id != -1: try: c.cancelSubscription (self.sub_id) except cups.IPPError, (e, m): self.emit ('cups-ipp-error', e, m) if self.update_timer: gobject.source_remove (self.update_timer) debugprint ("Canceled subscription %d" % self.sub_id)
def _connect (self, allow_pk=True): cups.setUser (self._use_user) self._use_pk = (allow_pk and (self._server[0] == '/' or self._server == 'localhost') and os.getuid () != 0) if self._use_pk: create_object = cupspk.Connection else: create_object = cups.Connection self._connection = create_object (host=self._server, port=self._port, encryption=self._encryption) if self._use_pk: self._connection.set_parent(self._parent) self._user = self._use_user debugprint ("Connected as user %s" % self._user) methodtype_lambda = type (self._connection.getPrinters) methodtype_real = type (self._connection.addPrinter) for fname in dir (self._connection): if fname[0] == '_': continue fn = getattr (self._connection, fname) if not type (fn) in [methodtype_lambda, methodtype_real]: continue setattr (self, fname, self._make_binding (fname, fn))
def collect(self): """Collects the metrics from cups """ start = time.time() self._setup_empty_prometheus_metrics() cups.setServer(self.host) cups.setPort(self.port) cups.setUser(self.user) try: conn = cups.Connection() printers = conn.getPrinters() self._prometheus_metrics['printersNum'].add_metric([], len(printers)) self._getPrinterStatus(printers) self._getJobData(conn) self._prometheus_metrics['cupsUp'].add_metric([], 1) except Exception as e: self._prometheus_metrics['cupsUp'].add_metric([], 0) print(e) duration = time.time() - start self._prometheus_metrics['scrape_duration_seconds'].add_metric( [], duration) for metric in self._prometheus_metrics.values(): yield metric
def serve(self): try: server = self.env.config.get("cups.server") port = self.env.config.get("cups.port") user = self.env.config.get("cups.user") password = self.env.config.get("cups.password") encryption_policy = getattr(cups, "HTTP_ENCRYPT_%s" % self.env.config.get("cups.encryption-policy", default="IF_REQUESTED").upper()) if server is not None: cups.setServer(server) if port is not None: cups.setPort(int(port)) if user is not None: cups.setUser(user) if encryption_policy is not None: cups.setEncryption(encryption_policy) if password is not None: def pw_callback(prompt): return password cups.setPasswordCB(pw_callback) self.client = cups.Connection() sched = PluginRegistry.getInstance("SchedulerService").getScheduler() sched.add_interval_job(self.__gc, minutes=60, tag='_internal', jobstore="ram") sched.add_interval_job(self.__update_printer_list, minutes=30, tag='_internal', jobstore="ram") except RuntimeError as e: self.log.error(str(e)) self.client = None
def cleanup(self): if self.sub_id != -1: user = cups.getUser() try: cups.setUser(self.user) c = cups.Connection(host=self.host, port=self.port, encryption=self.encryption) c.cancelSubscription(self.sub_id) debugprint("Canceled subscription %d" % self.sub_id) except: pass cups.setUser(user) if self.bus is not None: self.bus.remove_signal_receiver(self.handle_dbus_signal, path=self.DBUS_PATH, dbus_interface=self.DBUS_IFACE) timers = list(self.connecting_timers.values()) for timer in [self.update_timer, self.fetch_jobs_timer]: if timer: timers.append(timer) for timer in timers: GLib.source_remove(timer) self.emit('monitor-exited')
def cleanup (self): if self.sub_id != -1: user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) c.cancelSubscription (self.sub_id) debugprint ("Canceled subscription %d" % self.sub_id) except: pass cups.setUser (user) if self.bus is not None: self.bus.remove_signal_receiver (self.handle_dbus_signal, path=self.DBUS_PATH, dbus_interface=self.DBUS_IFACE) timers = list(self.connecting_timers.values ()) for timer in [self.update_timer, self.fetch_jobs_timer]: if timer: timers.append (timer) for timer in timers: GLib.source_remove (timer) self.emit ('monitor-exited')
def print_photos(jpg_group, img_size): conn = cups.Connection() printers = conn.getPrinters() print('Printers: ' + str(list(printers))) cups.setUser('pi') if config.print_to_pdf or len(printers) == 1: print('Printing to PDF') if 'PDF' in printers.keys(): printer_name = 'PDF' else: print('No PDF driver.') return else: try: printer_name = config.printer_name if not printer_name in printers.keys(): print('Cannot find printer (' + printer_name + ')') return except AttributeError: printer_name = None for key in printers.keys(): if key != 'PDF': printer_name = key break if printer_name is None: print('no valid printer found') return img = create_collage(jpg_group, img_size) filename = config.file_path + jpg_group + '-collage.jpg' pygame.image.save(img, filename) print('Printing to ' + printer_name) conn.printFile(printer_name, filename, 'Photobooth-' + jpg_group, {'fit-to-page':'true'})
def run (self): if self.host == None: self.host = cups.getServer () if self.port == None: self.port = cups.getPort () if self._encryption == None: self._encryption = cups.getEncryption () if self.user: cups.setUser (self.user) else: self.user = cups.getUser () try: cups.setPasswordCB2 (self._auth) except AttributeError: # Requires pycups >= 1.9.47. Fall back to rubbish API. cups.setPasswordCB (self._auth) try: conn = cups.Connection (host=self.host, port=self.port, encryption=self._encryption) self._reply (None) except RuntimeError, e: conn = None self._error (e)
def cups_print(username, printer_name): conn = cups.Connection() filename = eg.fileopenbox("Select the file to be printed", "File Selector") title = "Filename : " + filename msg = "empty - print all pages, '-' for range, ',' separate ranges)" field_names = ["Pages to be printed"] field_values = [] # we start with blanks for the values field_values = eg.multenterbox(msg, title, field_names, field_values) job_id = 0 if filename: cups.setUser(username) options = {'sides': 'two-sided-long-edge'} val = str(field_values[0]).replace(" ", "").strip(',') if bool(val): options['page-ranges'] = val try: conn.setPrinterUsersAllowed(printer_name, [username]) job_id = conn.printFile(printer_name, filename, filename, options) conn.setPrinterUsersAllowed(printer_name, ['']) except cups.IPPError as (status, description): eg.msgbox(title='IPP status is %d' % status, msg='Meaning: %s' % description)
def _authloop (self, fname, fn, *args, **kwds): self._passes = 0 c = self._connection retry = False while True: try: if self._perform_authentication () == 0: break if c != self._connection: # We have reconnected. fn = getattr (self._connection, fname) c = self._connection cups.setUser (self._use_user) result = fn.__call__ (*args, **kwds) if fname == 'adminGetServerSettings': # Special case for a rubbish bit of API. if result == {}: # Authentication failed, but we aren't told that. raise cups.IPPError (cups.IPP_NOT_AUTHORIZED, '') break except cups.IPPError, (e, m): if self._use_pk and m == 'pkcancel': raise cups.IPPError (0, _("Operation canceled")) if not self._cancel and (e == cups.IPP_NOT_AUTHORIZED or e == cups.IPP_FORBIDDEN or e == cups.IPP_AUTHENTICATION_CANCELED): self._failed (e == cups.IPP_FORBIDDEN) elif not self._cancel and e == cups.IPP_SERVICE_UNAVAILABLE: if self._lock: self._gui_event.clear () gobject.timeout_add (1, self._ask_retry_server_error, m) self._gui_event.wait () else: self._ask_retry_server_error (m) if self._retry_response == gtk.RESPONSE_OK: debugprint ("retrying operation...") retry = True self._passes -= 1 self._has_failed = True else: self._cancel = True raise else: if self._cancel and not self._cannot_auth: raise cups.IPPError (0, _("Operation canceled")) debugprint ("%s: %s" % (e, m)) raise except cups.HTTPError, (s,): if not self._cancel: self._failed (s == cups.HTTP_FORBIDDEN) else: raise
def printPic(*args): conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[0] cups.setUser('pi') output = custom.PROC_FILENAME print_id = conn.printFile(printer_name, output, "Photobooth", {}) start_img()
def __init__(self, host=None, user=None, port=None, adminurl=False): self.host = host self.user = user self.port = port self.adminurl = adminurl if self.user: cups.setUser(self.user)
def printPic(fileName): addPreviewOverlay(100,200,55,"printing...") conn = cups.Connection() printers = conn.getPrinters() default_printer = printers.keys()[0] cups.setUser('pi') conn.printFile (default_printer, fileName, "boothy", {'fit-to-page':'True'}) logging.info("Print job successfully created.");
def printPic(fileName): conn = cups.Connection() printers = conn.getPrinters() default_printer = printers.keys()[0] cups.setUser('pi') conn.printFile(default_printer, fileName, "boothy", {'fit-to-page': 'True'}) logging.info("Print job successfully created.")
def __init__(self, butterfly): cups.setPasswordCB(self.password_response) cups.setUser("cups_ctrl") self.bad_password = False self.IPP_STATUS_CODES = { cups.IPP_PRINTER_IDLE: "IDLE", cups.IPP_PRINTER_PROCESSING: "PROCESSING", cups.IPP_PRINTER_STOPPED: "STOPPED" }
def printPic2Cut(fileName): #addPreviewOverlay(100,200,55,"printing...") conn = cups.Connection() printers = conn.getPrinters() default_printer = list(printers.keys())[0] cups.setUser('pi') conn.printFile(default_printer, fileName, "boothy", {'fit-to-page': 'True'}) print("Print job successfully created.")
def __init__(self): try: self.conn = cups.Connection() self.printers = self.conn.getPrinters() cups.setUser(getpass.getuser()) except: print("Drucker konnte nicht intitialisiert werden.") self.printers = {} CfgService.set(CfgKey.PRINTER_IS_ACTIVE, False)
def printCups(photo_number, filename_prefix): filename = filename_prefix + '_' + str(photo_number) + 'of' + str( total_pics) + '.jpg' conn = cups.Connection() printers = conn.getPrinters() printer_name = list(printers)[0] cups.setUser('pi') #Photo printed one time conn.enablePrinter(printer_name) conn.printFile(printer_name, filename, filename, {"copies": "1"})
def send_print(self, filename): try: conn = cups.Connection() printers = conn.getPrinters() # default_printer = printers.keys()[self.selected_printer]#defaults to the first printer installed default_printer = conn.getDefault() cups.setUser("pi") conn.printFile(default_printer, filename, '', {'fit-to-page': 'True'}) except: pass
def print_image(path): connection = cups.Connection() printers = connection.getPrinters() printer = printers.keys()[0] cups.setUser('pi') img_to_print = os.path.join(IMAGES_PATH, IMAGE_NAME_TEMPLATE.format(format(get_next_image_number(IMAGES_PATH)-1, '04d'))) print "Sending "+img_to_print+" to printer ..." connection.printFile(printer, img_to_print, "PhotoboxImage", {})
def print_image(path): connection = cups.Connection() printers = connection.getPrinters() printer = printers.keys()[0] cups.setUser('pi') img_to_print = os.path.join(PRINT_PATH, IMAGE_NAME_TEMPLATE.format(format(get_next_image_number(IMAGES_PATH)-1, '04d'))) print "Sending "+img_to_print+" to printer ..." connection.printFile(printer, img_to_print, "PhotoboxImage", {})
def print_picture(environment, filepath): """Print the filepath picture""" lg.info("Seems like printing has been asked") #Todo handle here if ENABLE_PRINTING and environment["printer_enabled"]: if os.path.isfile(filepath): # Open a connection to cups conn = cups.Connection() # get a list of printers printers = conn.getPrinters() # select printer 0 printer_name = environment["printer_selected"] my_printer = printers.get(environment["printer_selected"], None) if my_printer is None: lg.critical("The printer " + str(printer_name) + " does not exists in list:" + str(printers.keys())) update_display(environment, "", "!! Merci pour vos photos !!", "", "", False) time.sleep(1) update_display(environment, "", "Nous vous enverrons vos photos...", "", "", False) time.sleep(1) cups.setUser('pi') # print the buffer file printqueuelength = len(conn.getJobs()) if printqueuelength > 1: play_a_sound(environment["buzz_sound"]) #show_image(environment, filepath) #time.sleep(3) conn.enablePrinter(printer_name) update_display(environment, "", "!! Merci pour vos photos !!", "", "", False) time.sleep(1) update_display(environment, "", "Nous vous enverrons vos photos...", "", "", False) time.sleep(1) else: update_display(environment, "", "Impression en cours...", "", "", False) tmp_filepath = creation_montage_to_print_a_format( filepath, environment["printer_tmp_filepath"]) conn.printFile(printer_name, tmp_filepath, "PhotoBoothBouin", environment["printer_options"]) time.sleep(20) else: play_a_sound(environment["buzz_sound"]) update_display(environment, "", "!! Merci pour vos photos !!", "", "", False) time.sleep(1) update_display(environment, "", "Nous vous enverrons vos photos...", "", "", False) time.sleep(1)
def __init__(self, host=None, user=None, port=None, verbose=False, directory=None, prefix='AirPrint-', adminurl=False): self.host = host self.user = user self.port = port self.verbose = verbose self.directory = directory self.prefix = prefix self.adminurl = adminurl if self.user: cups.setUser(self.user)
def config_printer(self, config): try: conn = cups.Connection() printers = conn.getPrinters() logger.debug('printers: %s' % printers) default_printer = printers.keys()[config['printer_key']] cups.setUser(config['user']) except (IPPError, HTTPError) as e: raise PimatonPrintExceptions('Couldnt connect to cups') self.printer = default_printer self.conn = conn
def send(self, file, user, **kwargs): try: cups.setUser(user) conn = cups.Connection() job_name = str(uuid.uuid4()) content = file.file.read() with tempfile.NamedTemporaryFile(prefix="tmp_print") as f: f.write(content) f.flush() id = conn.printFile('MFP', f.name, job_name, {}) msg = "success, job id: {}, job name: {}".format(id, job_name) except cups.IPPError as (status, description): msg = "IPP status is {}, meaning: {}".format(status, description)
def printFile(selected_frame_num, num_times): conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[0] cups.setUser('pi') if selected_frame_num < 8: selected_frame_pic = "tmp/frame_%i.jpg" % (selected_frame_num) else: selected_frame_pic = "nice_image.jpg" for i in xrange(0, num_times): conn.printFile(printer_name, os.path.abspath(selected_frame_pic), "Photo_Booth_Print", { "media": "Custom.4x6in" })
def printFile(selected_frame_num, num_times): conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[0] cups.setUser('pi') if selected_frame_num < 8: selected_frame_pic = "tmp/frame_%i.jpg" % (selected_frame_num) else: selected_frame_pic = "nice_image.jpg" for i in xrange(0, num_times): conn.printFile(printer_name, os.path.abspath(selected_frame_pic), "Photo_Booth_Print", {"media": "Custom.4x6in"})
def printit(self, username, printjob, printer): """Print a given document on the given printer requests.options = {} 'username' -- owner of the print job 'printjob' -- relative filename of the print job 'printer' -- the printer to use (<hostname>://<printer>) return: <PDF document> """ path = self._get_path(username, printjob) try: spoolhost, printer = printer.split('://', 1) except ValueError: raise UMC_Error(_('Invalid printer URI')) if not os.path.exists(path): raise UMC_Error( _('File %r could not be printed as it does not exists (anymore).' ) % (printjob, )) MODULE.process('Printing: %s' % path) self.pw_callback_bad_password = False try: cups.setUser(self.username) cups.setEncryption(cups.HTTP_ENCRYPT_ALWAYS) cups.setPasswordCB(self.pw_callback) conn = cups.Connection(spoolhost) conn.printFile(printer, path, Printjob.filename2label(printjob), {}) except RuntimeError: raise UMC_Error( _('Failed to connect to print server %(printserver)s.') % {'printserver': spoolhost}) except cups.IPPError as (errno, description): IPP_AUTHENTICATION_CANCELED = 4096 description = { cups.IPP_NOT_AUTHORIZED: _('No permission to print'), IPP_AUTHENTICATION_CANCELED: _('Wrong password'), }.get(errno, description) raise UMC_Error( _('Failed to print on %(printer)s: %(stderr)s (error %(errno)d).' ) % { 'printer': printer, 'stderr': description, 'errno': errno })
def print_file(filename, tmp_file, printer, uni, options): cups.setUser(uni) conn = cups.Connection() try: conv_file = convert_file(tmp_file) if conv_file: conn.printFile(printer, conv_file, filename, options) sys.stderr.write('File '+conv_file+' printed successfully\n') sys.stderr.flush() else: sys.stderr.write("Could not convert "+tmp_file+" successfully\n") sys.stderr.flush() except cups.IPPError: sys.stderr.write('Printing '+tmp_file+' unsuccessful\n') sys.stderr.flush()
def _connect (self): cups.setUser (self._use_user) cups.setServer (self._server) cups.setPort (self._port) self._connection = cups.Connection () self._user = self._use_user debugprint ("Connected as user %s" % self._user) methodtype = type (self._connection.getPrinters) for fname in dir (self._connection): if fname[0] == '_': continue fn = getattr (self._connection, fname) if type (fn) != methodtype: continue setattr (self, fname, self._make_binding (fname, fn))
def printFrame(): cam = Camera() json = request.get_json() print(json) if json is None: return "invalid", 400 else: firstname = json["firstname"] lastname = json["lastname"] if firstname is None or lastname is None: # TODO error page return "invalid", 400 # save file to ms since epoch now = datetime.datetime.now() msSinceEpoch = str(now.timestamp() * 1000000) filename = msSinceEpoch + '.jpg' path = BASE_PATH + filename #capture current frame #maybe better if frame comes from web whatever with open(path, 'wb') as f: f.write(cam.get_frame()) #write into db db.insert({ 'firstname': firstname, 'lastname': lastname, 'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'filename': filename }) # Set up CUPS conn = cups.Connection() # code only for testing without really printing to not waste # return 'success' cups.setUser('pi') # Send the picture to the printer # give custom media size in pin size with into it # CHANGE CM VALUES HERE IF BIGGER OR SMALLER PRINT SIZE print_id = conn.printFile(PRINTER_NAME, path, "Projekt Webcam Print", {"media": "Custom.8.5x8.5cm"}) return "success"
def __init__(self, host=None, user=None, port=None, verbose=False, directory=None, prefix='AirPrint-', adminurl=False, usecups=True, useavahi=False, dnsdomain=None): self.host = host self.user = user self.port = port self.verbose = verbose self.directory = directory self.prefix = prefix self.adminurl = adminurl self.usecups = usecups and cups self.useavahi = useavahi and avahisearch self.dnsdomain = dnsdomain if self.user: cups.setUser(self.user)
def create(cls, printer=None, server="", port=0, user=""): """Return a handle to print using a connection to the (local) CUPS server, if available.""" try: import cups except ImportError: return cups.setServer(server or "") cups.setPort(port or 0) cups.setUser(user or "") try: c = cups.Connection() except RuntimeError: return h = cls(c, printer) if h.printer().printerName() in c.getPrinters(): return h
def printPhotos(obj): logging.info('Function printPhotos was called.') global printerBusy if printerBusy == False: conn = cups.Connection() cups.setUser(cupsUser) conn.printFile(printerName, photoOne, "RasPi_Booth", {'fit-to-page':'True'}) conn.printFile(printerName, photoTwo, "RasPi_Booth", {'fit-to-page':'True'}) conn.printFile(printerName, photoThree, "RasPi_Booth", {'fit-to-page':'True'}) global printerTime global printerTimeout printerTime = 0 printerTimeout = 180 printerBusy = True logging.info('Function printPhotos completed.')
def print_file(filename, tmp_file, printer, uni, options): cups.setUser(uni) conn = cups.Connection() try: conv_file = convert_file(tmp_file) if conv_file: conn.printFile(printer, conv_file, filename, options) sys.stderr.write('File ' + conv_file + ' printed successfully\n') sys.stderr.flush() else: sys.stderr.write("Could not convert " + tmp_file + " successfully\n") sys.stderr.flush() except cups.IPPError: sys.stderr.write('Printing ' + tmp_file + ' unsuccessful\n') sys.stderr.flush()
def print_picture(): global names global person global lastPick global first_pick conn = cups.Connection() printers = conn.getPrinters() printer_name = list(printers.keys())[0] cups.setUser('pi') latest_print = Image.new('RGBA', (683, 384)) latest_print.paste(Image.open("/home/pi/SSanta/"+str(person)+".jpg").resize((683, 384)), ( 0, 0, 683, 384)) output = "/home/pi/SSanta/"+str(person)+".jpg" print_id = conn.printFile(printer_name, output, "Photo Booth", {}) while conn.getJobs().get(print_id, None): sleep(1)
def print_label(label_file, name): printerName = PRINTER_NAME if os.environ.get('WEB_USER') in REMOTES: settings = REMOTES[os.environ['WEB_USER']] if 'host' not in settings: settings['host'] = os.environ.get('WEB_REMOTE_IP') if settings['host'] == '::1': settings['host'] = '127.0.0.1' if 'username' in settings: cups.setUser(settings['username']) debug('connecting to remote cups %s' % settings['host']) cups.setServer(settings['host']) conn = cups.Connection(settings['host']) if 'printer' in settings: printerName = settings['printer'] else: conn = cups.Connection() printer = printerName or conn.getDefault() debug('print_label connection done') conn.printFile(printer, label_file.name, name, {}) debug('print_label print job sent')
def cleanup (self): if self.sub_id != -1: user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) c.cancelSubscription (self.sub_id) debugprint ("Canceled subscription %d" % self.sub_id) except: pass cups.setUser (user) if self.bus != None: self.bus.remove_signal_receiver (self.handle_dbus_signal, path=self.DBUS_PATH, dbus_interface=self.DBUS_IFACE) self.watcher.monitor_exited (self)
def print_pic(self): self.logger.info("PRINT") self.current_img = ImageTk.PhotoImage(self.imgs["print"]) self.canvas.itemconfig(self.imagesprite, image=self.current_img) self.root.update() self.logger.info("show print in progress") # to be sure that the montage is over :D self.to_print_p.wait() # send print conn = cups.Connection() printers = conn.getPrinters() default_printer = "Canon_SELPHY_CP1300" if (default_printer in printers.keys()): cups.setUser('pi') conn.printFile(default_printer, self.toprint_path, "boothy", {'fit-to-page':'True'}) else: self.logger.info("Printer not found ! ") time.sleep(5)
def printFile(selected_frame_num, num_times): print(" ** Printing!") try: conn = cups.Connection() printers = conn.getPrinters() printer_name = list(printers.keys())[0] cups.setUser('pi') if selected_frame_num < 8: selected_frame_pic = "tmp/frame_%i.jpg" % (selected_frame_num) else: selected_frame_pic = "nice_image.jpg" print(" ** Image is %s | fnum is %i | num_times is %i" % (selected_frame_pic, selected_frame_num, num_times)) for i in range(0, num_times): print(" ** Printing iteration!") conn.printFile(printer_name, os.path.abspath(selected_frame_pic), "Photo_Booth_Print", { "media": "Custom.4x6in" }) except: print(" ** Printing FAILED!") traceback.print_exc()
def printPic(fileName): #fileName = "bl.jpg" #return addPreviewOverlay(100,200,55,"Printing...") conn = cups.Connection() printers = conn.getPrinters() print "PRINT!" print printers default_printer = printers.keys()[0] print "Default P:" print default_printer cups.setUser('pi') conn.printFile (default_printer, "photos//" + fileName, "boothy", {}) #, {'fit-to-page':'True'}) logging.info("Print job successfully created."); counter=50 pstatus="-" while True: time.sleep(1) if counter > 0: counter=counter-1 else: return if len(conn.getJobs()) != 0: sta=conn.getJobAttributes(next(iter(conn.getJobs())))["job-state"] if sta == 5: #IPP_JOB_PROCESSING pstatus="Processing... (5)" if counter == 0: counter=counter+5 elif sta == 9: #IPP_JOB_COMPLETED pstatus="Completed... (9)" elif sta == 4: #IPP_JOB_HELD no paper pstatus="No paper!" counter=counter+1 addPreviewOverlayP("Printing... [" + str(counter) + "]", pstatus)
def serve(self): try: server = self.env.config.get("cups.server") port = self.env.config.get("cups.port") user = self.env.config.get("cups.user") password = self.env.config.get("cups.password") encryption_policy = getattr( cups, "HTTP_ENCRYPT_%s" % self.env.config.get( "cups.encryption-policy", default="IF_REQUESTED").upper()) if server is not None: cups.setServer(server) if port is not None: cups.setPort(int(port)) if user is not None: cups.setUser(user) if encryption_policy is not None: cups.setEncryption(encryption_policy) if password is not None: def pw_callback(prompt): return password cups.setPasswordCB(pw_callback) self.client = cups.Connection() sched = PluginRegistry.getInstance( "SchedulerService").getScheduler() sched.add_interval_job(self.__gc, minutes=60, tag='_internal', jobstore="ram") sched.add_interval_job(self.__update_printer_list, minutes=30, tag='_internal', jobstore="ram") except RuntimeError as e: self.log.error(str(e))
def fetch_jobs (self, refresh_all): if not self.process_pending_events: # Skip this call. We'll get called again soon. return True user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: self.watcher.cups_connection_error (self) self.fetch_jobs_timer = None cups.setUser (user) return False limit = 1 try: fetched = c.getJobs (which_jobs=self.which_jobs, my_jobs=self.my_jobs, first_job_id=self.fetch_first_job_id, limit=limit) except cups.IPPError, (e, m): self.watcher.cups_ipp_error (self, e, m) self.fetch_jobs_timer = None cups.setUser (user) return False
def test_cups_module (): cups.setUser ("root") cups.setPasswordCB (callback) conn = cups.Connection () printers = list(conn.getPrinters ().keys ()) if 0: print ("Getting cupsd.conf") file ("cupsd.conf", "w") conn.getFile ("/admin/conf/cupsd.conf", "cupsd.conf") print ("Putting cupsd.conf") conn.putFile ("/admin/conf/cupsd.conf", "cupsd.conf") print ("Getting PPD for %s" % printers[len (printers) - 1]) f = conn.getPPD (printers[len (printers) - 1]) ppd = cups.PPD (f) ppd.markDefaults () print (ppd.conflicts ()) groups = ppd.optionGroups for group in groups: for opt in group.options: print (list (map (lambda x: x["text"], opt.choices)))
def print_pic(self, image_name): # Dateinahmen bestimmen: print 'printing:',self.__library.get_image_path(image_name) try: conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[1] # Drucker auswaehlen cups.setUser('pi') #Benutzer einstellen # Drucker Queue lesen PrinterQueue = conn.getJobs(which_jobs='not-completed') # Drucken (Drucker, Datei, PrintJob Name, Optionen) if len(PrinterQueue)==0: #länge der Queue über 0 kein drucken conn.printFile(printer_name, self.__library.get_image_path(image_name), "Photobooth",{}) self.printing_image.emit(image_name) elif len(PrinterQueue)>0: print 'Printer busy' # Fehler abfangen und ausgeben (z.B. Papierstau oder kein Papier except cups.IPPError as (status, description): print 'IPP statis is %d' % status print 'Meaning:', description
def test_cups_module(): cups.setUser("root") cups.setPasswordCB(callback) conn = cups.Connection() printers = list(conn.getPrinters().keys()) if 0: print("Getting cupsd.conf") file("cupsd.conf", "w") conn.getFile("/admin/conf/cupsd.conf", "cupsd.conf") print("Putting cupsd.conf") conn.putFile("/admin/conf/cupsd.conf", "cupsd.conf") print("Getting PPD for %s" % printers[len(printers) - 1]) f = conn.getPPD(printers[len(printers) - 1]) ppd = cups.PPD(f) ppd.markDefaults() print(ppd.conflicts()) groups = ppd.optionGroups for group in groups: for opt in group.options: print(list(map(lambda x: x["text"], opt.choices)))
def run (self): if self.host == None: self.host = cups.getServer () if self.port == None: self.port = cups.getPort () if self._encryption == None: self._encryption = cups.getEncryption () if self.user: cups.setUser (self.user) else: self.user = cups.getUser () cups.setPasswordCB2 (self._auth) try: conn = cups.Connection (host=self.host, port=self.port, encryption=self._encryption) self._reply (None) except RuntimeError, e: conn = None self._error (e)
def refresh(self, which_jobs=None, refresh_all=True): debugprint ("refresh") if which_jobs != None: self.which_jobs = which_jobs user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: self.watcher.cups_connection_error (self) cups.setUser (user) return if self.sub_id != -1: try: c.cancelSubscription (self.sub_id) except cups.IPPError, (e, m): self.watcher.cups_ipp_error (self, e, m) debugprint ("Canceled subscription %d" % self.sub_id)
def fetch_jobs (self, refresh_all): if not self.process_pending_events: # Skip this call. We'll get called again soon. return True user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: self.emit ('cups-connection-error') self.fetch_jobs_timer = None cups.setUser (user) return False limit = 1 r = ["job-id", "job-printer-uri", "job-state", "job-originating-user-name", "job-k-octets", "job-name", "time-at-creation"] try: try: fetched = c.getJobs (which_jobs=self.which_jobs, my_jobs=self.my_jobs, first_job_id=self.fetch_first_job_id, limit=limit, requested_attributes=r) except TypeError: # requested_attributes requires pycups 1.9.50 fetched = c.getJobs (which_jobs=self.which_jobs, my_jobs=self.my_jobs, first_job_id=self.fetch_first_job_id, limit=limit) except cups.IPPError, (e, m): self.emit ('cups-ipp-error', e, m) self.fetch_jobs_timer = None cups.setUser (user) return False
def run(self): if self.host == None: self.host = cups.getServer() if self.port == None: self.port = cups.getPort() if self._encryption == None: self._encryption = cups.getEncryption() if self.user: cups.setUser(self.user) else: self.user = cups.getUser() cups.setPasswordCB2(self._auth) try: conn = cups.Connection(host=self.host, port=self.port, encryption=self._encryption) self._reply(None) except RuntimeError as e: conn = None self._error(e) while True: # Wait to find out what operation to try. debugprint("Awaiting further instructions") self.idle = self._queue.empty() item = self._queue.get() debugprint("Next task: %s" % repr(item)) if item == None: # Our signal to quit. self._queue.task_done() break elif self._destroyed: # Just mark all tasks done self._queue.task_done() continue self.idle = False (fn, args, kwds, rh, eh, ah) = item if rh != False: self._reply_handler = rh if eh != False: self._error_handler = eh if ah != False: self._auth_handler = ah if fn == True: # Our signal to change user and reconnect. self.user = args[0] cups.setUser(self.user) debugprint("Set user=%s; reconnecting..." % self.user) cups.setPasswordCB2(self._auth) try: conn = cups.Connection(host=self.host, port=self.port, encryption=self._encryption) debugprint("...reconnected") self._queue.task_done() self._reply(None) except RuntimeError as e: debugprint("...failed") self._queue.task_done() self._error(e) continue # Normal IPP operation. Try to perform it. try: debugprint("Call %s" % fn) result = fn(conn, *args, **kwds) if fn == cups.Connection.adminGetServerSettings.__call__: # Special case for a rubbish bit of API. if result == {}: # Authentication failed, but we aren't told that. raise cups.IPPError(cups.IPP_NOT_AUTHORIZED, "") debugprint("...success") self._reply(result) except Exception as e: debugprint("...failure (%s)" % repr(e)) self._error(e) self._queue.task_done() debugprint("Thread exiting") del self._conn # already destroyed del self._reply_handler del self._error_handler del self._auth_handler del self._queue del self._auth_queue del conn cups.setPasswordCB2(None)
def fetch_jobs (self, refresh_all): if not self.process_pending_events: # Skip this call. We'll get called again soon. return True user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: self.emit ('cups-connection-error') self.fetch_jobs_timer = None cups.setUser (user) return False limit = 1 r = ["job-id", "job-printer-uri", "job-state", "job-originating-user-name", "job-k-octets", "job-name", "time-at-creation"] try: fetched = c.getJobs (which_jobs=self.which_jobs, my_jobs=self.my_jobs, first_job_id=self.fetch_first_job_id, limit=limit, requested_attributes=r) except cups.IPPError as e: (e, m) = e.args self.emit ('cups-ipp-error', e, m) self.fetch_jobs_timer = None cups.setUser (user) return False cups.setUser (user) got = len (fetched) debugprint ("Got %s jobs, asked for %s" % (got, limit)) jobs = self.jobs.copy () jobids = list(fetched.keys ()) jobids.sort () if got > 0: last_jobid = jobids[got - 1] if last_jobid < self.fetch_first_job_id: last_jobid = self.fetch_first_job_id + limit - 1 debugprint ("Unexpected job IDs returned: %s" % repr (jobids)) debugprint ("That's not what we asked for!") else: last_jobid = self.fetch_first_job_id + limit - 1 for jobid in range (self.fetch_first_job_id, last_jobid + 1): try: job = fetched[jobid] if self.specific_dests is not None: uri = job.get('job-printer-uri', '/') i = uri.rfind ('/') printer = uri[i + 1:] if printer not in self.specific_dests: raise KeyError if jobid in jobs: n = 'job-event' else: n = 'job-added' jobs[jobid] = job self.emit (n, jobid, '', {}, job.copy ()) except KeyError: # No job by that ID. if jobid in jobs: del jobs[jobid] self.emit ('job-removed', jobid, '', {}) jobids = list(jobs.keys ()) jobids.sort () if got < limit: trim = False for i in range (len (jobids)): jobid = jobids[i] if not trim and jobid > last_jobid: trim = True if trim: del jobs[jobid] self.emit ('job-removed', jobid, '', {}) self.update_jobs (jobs) self.jobs = jobs if got < limit: # That's all. Don't run this timer again. self.fetch_jobs_timer = None return False # Remember where we got up to and run this timer again. next = jobid + 1 while not refresh_all and next in self.jobs: next += 1 self.fetch_first_job_id = next return True
def refresh(self, which_jobs=None, refresh_all=True): debugprint ("refresh") self.emit ('refresh') if which_jobs is not None: self.which_jobs = which_jobs user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) except RuntimeError: GLib.idle_add (self.emit, 'cups-connection-error') cups.setUser (user) return if self.sub_id != -1: try: c.cancelSubscription (self.sub_id) except cups.IPPError as e: (e, m) = e.args GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m), e, m) if self.update_timer: GLib.source_remove (self.update_timer) self.update_timer = None debugprint ("Canceled subscription %d" % self.sub_id) try: del self.sub_seq except AttributeError: pass events = ["printer-added", "printer-modified", "printer-deleted", "printer-state-changed"] if self.monitor_jobs: events.extend (["job-created", "job-completed", "job-stopped", "job-state-changed", "job-progress"]) try: self.sub_id = c.createSubscription ("/", events=events) debugprint ("Created subscription %d, events=%s" % (self.sub_id, repr (events))) except cups.IPPError as e: (e, m) = e.args GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m), e, m) cups.setUser (user) if self.sub_id != -1: if self.update_timer: GLib.source_remove (self.update_timer) self.update_timer = GLib.timeout_add_seconds ( MIN_REFRESH_INTERVAL, self.get_notifications) debugprint ("Next notifications fetch in %ds" % MIN_REFRESH_INTERVAL) if self.monitor_jobs: jobs = self.jobs.copy () if self.which_jobs not in ['all', 'completed']: # Filter out completed jobs. filtered = {} for jobid, job in jobs.items (): if job.get ('job-state', cups.IPP_JOB_CANCELED) < cups.IPP_JOB_CANCELED: filtered[jobid] = job jobs = filtered self.fetch_first_job_id = 1 if self.fetch_jobs_timer: GLib.source_remove (self.fetch_jobs_timer) self.fetch_jobs_timer = GLib.timeout_add (5, self.fetch_jobs, refresh_all) else: jobs = {} try: r = collect_printer_state_reasons (c, self.ppdcache) self.printer_state_reasons = r dests = c.getPrinters () self.printers = set(dests.keys ()) except cups.IPPError as e: (e, m) = e.args GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m), e, m) return except RuntimeError: GLib.idle_add (self.emit, 'cups-connection-error') return if self.specific_dests is not None: for jobid in jobs.keys (): uri = jobs[jobid].get('job-printer-uri', '/') i = uri.rfind ('/') printer = uri[i + 1:] if printer not in self.specific_dests: del jobs[jobid] self.set_process_pending (False) for printer in self.printers: GLib.idle_add (lambda x: self.emit ('printer-added', x), printer) for jobid, job in jobs.items (): GLib.idle_add (lambda jobid, job: self.emit ('job-added', jobid, '', {}, job), jobid, job) self.update_jobs (jobs) self.jobs = jobs self.set_process_pending (True) return False
def get_notifications(self): if self.update_timer: GLib.source_remove (self.update_timer) self.update_timer = None if not self.process_pending_events: # Defer the timer callback. self.update_timer = GLib.timeout_add (200, self.get_notifications) debugprint ("Deferred get_notifications by 200ms") return False debugprint ("get_notifications") user = cups.getUser () try: cups.setUser (self.user) c = cups.Connection (host=self.host, port=self.port, encryption=self.encryption) try: try: notifications = c.getNotifications ([self.sub_id], [self.sub_seq + 1]) except AttributeError: notifications = c.getNotifications ([self.sub_id]) except cups.IPPError as e: (e, m) = e.args cups.setUser (user) if e == cups.IPP_NOT_FOUND: # Subscription lease has expired. self.sub_id = -1 debugprint ("Subscription not found, will refresh") self.refresh () return False self.emit ('cups-ipp-error', e, m) if e == cups.IPP_FORBIDDEN: return False debugprint ("getNotifications failed with %d (%s)" % (e, m)) return True except RuntimeError: cups.setUser (user) debugprint ("cups-connection-error, will retry") self.cups_connection_in_error = True self.emit ('cups-connection-error') return True if self.cups_connection_in_error: self.cups_connection_in_error = False debugprint ("cups-connection-recovered") self.emit ('cups-connection-recovered') cups.setUser (user) jobs = self.jobs.copy () for event in notifications['events']: seq = event['notify-sequence-number'] self.sub_seq = seq nse = event['notify-subscribed-event'] debugprint ("%d %s %s" % (seq, nse, event['notify-text'])) if get_debugging (): debugprint (pprint.pformat (event)) if nse.startswith ('printer-'): # Printer events name = event['printer-name'] if nse == 'printer-added' and name not in self.printers: self.printers.add (name) self.emit ('printer-added', name) elif nse == 'printer-deleted' and name in self.printers: self.printers.remove (name) items = list(self.reasons_seen.keys ()) for tuple in items: if tuple[1] == name: reason = self.reasons_seen[tuple] del self.reasons_seen[tuple] self.emit ('state-reason-removed', reason) if name in self.printer_state_reasons: del self.printer_state_reasons[name] self.emit ('printer-removed', name) elif name in self.printers: printer_state_reasons = event['printer-state-reasons'] reasons = [] for reason in printer_state_reasons: if reason == "none": break if state_reason_is_harmless (reason): continue reasons.append (StateReason (name, reason, self.ppdcache)) self.printer_state_reasons[name] = reasons self.emit ('printer-event', name, nse, event) continue # Job events if not nse.startswith ("job-"): # Some versions of CUPS give empty # notify-subscribed-event attributes (STR #3608). debugprint ("Unhandled nse %s" % repr (nse)) continue jobid = event['notify-job-id'] if (nse == 'job-created' or (nse == 'job-state-changed' and jobid not in jobs and event['job-state'] == cups.IPP_JOB_PROCESSING)): if (self.specific_dests is not None and event['printer-name'] not in self.specific_dests): continue try: attrs = c.getJobAttributes (jobid) if (self.my_jobs and attrs['job-originating-user-name'] != cups.getUser ()): continue jobs[jobid] = attrs except KeyError: jobs[jobid] = {'job-k-octets': 0} except cups.IPPError as e: (e, m) = e.args self.emit ('cups-ipp-error', e, m) jobs[jobid] = {'job-k-octets': 0} self.emit ('job-added', jobid, nse, event, jobs[jobid].copy ()) elif (nse == 'job-completed' or (nse == 'job-state-changed' and event['job-state'] == cups.IPP_JOB_COMPLETED)): if not (self.which_jobs in ['completed', 'all']): try: del jobs[jobid] self.emit ('job-removed', jobid, nse, event) except KeyError: pass continue try: job = jobs[jobid] except KeyError: continue if (self.specific_dests is not None and event['printer-name'] not in self.specific_dests): del jobs[jobid] self.emit ('job-removed', jobid, nse, event) continue for attribute in ['job-state', 'job-name']: job[attribute] = event[attribute] if 'notify-printer-uri' in event: job['job-printer-uri'] = event['notify-printer-uri'] self.emit ('job-event', jobid, nse, event, job.copy ()) self.set_process_pending (False) self.update_jobs (jobs) self.jobs = jobs self.set_process_pending (True) # Update again when we're told to. If we're getting CUPS # D-Bus signals, however, rely on those instead. if not self.received_any_dbus_signals: interval = notifications['notify-get-interval'] t = GLib.timeout_add_seconds (interval, self.get_notifications) debugprint ("Next notifications fetch in %ds" % interval) self.update_timer = t return False
def _perform_authentication (self): self._passes += 1 creds = global_authinfocache.lookup_auth_info (host=self._server, port=self._port) if creds != None: if (creds[0] != 'root' or self._try_as_root): (self._use_user, self._use_password) = creds del creds debugprint ("Authentication pass: %d" % self._passes) if self._passes == 1: # Haven't yet tried the operation. Set the password # callback and return > 0 so we try it for the first time. self._has_failed = False self._forbidden = False self._auth_called = False self._cancel = False self._cannot_auth = False self._dialog_shown = False cups.setPasswordCB (self._password_callback) debugprint ("Authentication: password callback set") return 1 debugprint ("Forbidden: %s" % self._forbidden) if not self._has_failed: # Tried the operation and it worked. Return 0 to signal to # break out of the loop. debugprint ("Authentication: Operation successful") return 0 # Reset failure flag. self._has_failed = False if self._passes >= 2: # Tried the operation without a password and it failed. if (self._try_as_root and self._user != 'root' and (self._server[0] == '/' or self._forbidden)): # This is a UNIX domain socket connection so we should # not have needed a password (or it is not a UDS but # we got an HTTP_FORBIDDEN response), and so the # operation must not be something that the current # user is authorised to do. They need to try as root, # and supply the password. However, to get the right # prompt, we need to try as root but with no password # first. debugprint ("Authentication: Try as root") self._use_user = '******' self._auth_called = False try: self._connect (allow_pk=False) except RuntimeError: raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE, 'server-error-service-unavailable') return 1 if not self._prompt_allowed: debugprint ("Authentication: prompting not allowed") self._cancel = True return 1 if not self._auth_called: # We aren't even getting a chance to supply credentials. debugprint ("Authentication: giving up") self._cancel = True self._cannot_auth = True return 1 # Reset the flag indicating whether we were given an auth callback. self._auth_called = False # If we're previously prompted, explain why we're prompting again. if self._dialog_shown: if self._lock: self._gui_event.clear () GLib.timeout_add (1, self._show_not_authorized_dialog) self._gui_event.wait () else: self._show_not_authorized_dialog () if self._lock: self._gui_event.clear () GLib.timeout_add (1, self._perform_authentication_with_dialog) self._gui_event.wait () else: self._perform_authentication_with_dialog () if self._cancel: debugprint ("cancelled") return -1 cups.setUser (self._use_user) debugprint ("Authentication: Reconnect") try: self._connect (allow_pk=False) except RuntimeError: raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE, 'server-error-service-unavailable') return 1
(e, m) = e.args print("Error getting printer attibutes: %s" % m) sys.exit (1) SPECIFIC_URI = attrs['device-uri'] print("URI for queue %s is %s" % (sys.argv[1], SPECIFIC_URI)) else: print ("\nIf you have not already done so, you may get more results\n" "by temporarily disabling your firewall (or by allowing\n" "incoming UDP packets on port 161).\n") if devices == None: if not SPECIFIC_URI: print("Examining connected devices") cups.setUser ('root') c = cups.Connection () try: if SPECIFIC_URI: scheme = str (SPECIFIC_URI.split (":", 1)[0]) devices = c.getDevices (include_schemes=[scheme]) else: devices = c.getDevices (exclude_schemes=["dnssd", "hal", "hpfax"]) except cups.IPPError as e: (e, m) = e.args if e == cups.IPP_FORBIDDEN: print("Run this as root to examine IDs from attached devices.") sys.exit (1) if e in (cups.IPP_NOT_AUTHORIZED, cups.IPP_AUTHENTICATION_CANCELED): print("Not authorized.")
def test (xml_path=None, attached=False, deviceid=None, debug=False): import cups import locale from . import ppds from pprint import pprint from time import time import os.path if debug: def debugprint (x): print (x) ppds.set_debugprint_fn (debugprint) locale.setlocale (locale.LC_ALL, "") encoding = locale.getlocale (locale.LC_CTYPE)[1] if xml_path == None: xml_path = os.path.join (os.path.join (os.path.dirname (__file__), ".."), "xml") os.environ["CUPSHELPERS_XMLDIR"] = xml_path xml_path = os.path.join (xml_path, "preferreddrivers.xml") loadstart = time () (xmldrivertypes, xmlpreferenceorder) = PreferredDrivers (xml_path) drivertypes = DriverTypes () drivertypes.load (xmldrivertypes) preforder = PreferenceOrder () preforder.load (xmlpreferenceorder) loadtime = time () - loadstart if debug: print("Time to load %s: %.3fs" % (xml_path, loadtime)) c = cups.Connection () try: cupsppds = c.getPPDs2 () except AttributeError: # getPPDs2 requires pycups >= 1.9.52 cupsppds = c.getPPDs () ppdfinder = ppds.PPDs (cupsppds) if attached or deviceid: if attached: cups.setUser ("root") devices = c.getDevices () else: devid = parseDeviceID (deviceid) devices = { "xxx://yyy": { "device-id": deviceid, "device-make-and-model": "%s %s" % (devid["MFG"], devid["MDL"]) } } for uri, device in devices.items (): if uri.find (":") == -1: continue devid = device.get ("device-id", "") if isinstance (devid, list): devid = devid[0] if not devid: continue if not uri.startswith ("xxx:"): print (uri) id_dict = parseDeviceID (devid) fit = ppdfinder.getPPDNamesFromDeviceID (id_dict["MFG"], id_dict["MDL"], id_dict["DES"], id_dict["CMD"], uri) mm = device.get ("device-make-and-model", "") orderedtypes = preforder.get_ordered_types (drivertypes, mm, id_dict) ppds = {} for ppdname in fit.keys (): ppds[ppdname] = ppdfinder.getInfoFromPPDName (ppdname) orderedppds = drivertypes.get_ordered_ppdnames (orderedtypes, ppds, fit) i = 1 for t, ppd in orderedppds: print("%d %s\n (%s, %s)" % (i, ppd, t, fit[ppd])) i += 1 else: for make in ppdfinder.getMakes (): for model in ppdfinder.getModels (make): ppdsdict = ppdfinder.getInfoFromModel (make, model) mm = make + " " + model orderedtypes = preforder.get_ordered_types (drivertypes, mm, None) fit = {} for ppdname in ppdsdict.keys (): fit[ppdname] = DriverType.FIT_CLOSE orderedppds = drivertypes.get_ordered_ppdnames (orderedtypes, ppdsdict, fit) print((mm.encode (encoding) + ":")) i = 1 for t, ppd in orderedppds: print("%d %s\n (%s)" % (i, ppd, t)) i += 1 print()