Debian Codegraph @

monitor.py

raw
1 #!/usr/bin/python3
2
3 ## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2014 Red Hat, Inc.
4 ## Author: Tim Waugh <[email protected]>
5
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
15
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 import config
21 import cups
22 cups.require("1.9.50")
23 import dbus
24 import dbus.glib
25 from gi.repository import GObject
26 from gi.repository import GLib
27 import time
28 from debug import *
29 import pprint
30 import gettext
31 gettext.install(domain=config.PACKAGE, localedir=config.localedir)
32 import ppdcache
33 import statereason
34 from statereason import StateReason
35
36 CONNECTING_TIMEOUT = 60 # seconds
37 MIN_REFRESH_INTERVAL = 1 # seconds
38
39 def state_reason_is_harmless (reason):
40 if (reason.startswith ("moving-to-paused") or
41 reason.startswith ("paused") or
42 reason.startswith ("shutdown") or
43 reason.startswith ("stopping") or
44 reason.startswith ("stopped-partly")):
45 return True
46 return False
47
48 def collect_printer_state_reasons (connection, ppdcache):
49 result = {}
50 try:
51 printers = connection.getPrinters ()
52 except cups.IPPError:
53 return result
54
55 for name, printer in printers.items ():
56 reasons = printer["printer-state-reasons"]
57 for reason in reasons:
58 if reason == "none":
59 break
60 if state_reason_is_harmless (reason):
61 continue
62 if name not in result:
63 result[name] = []
64 result[name].append (StateReason (name, reason, ppdcache))
65 return result
66
67 class Monitor(GObject.GObject):
68 __gsignals__ = {
69 'refresh': (GObject.SignalFlags.RUN_LAST, None, ()),
70 'monitor-exited' : (GObject.SignalFlags.RUN_LAST, None, ()),
71 'state-reason-added': (GObject.SignalFlags.RUN_LAST, None,
72 (GObject.TYPE_PYOBJECT,)),
73 'state-reason-removed': (GObject.SignalFlags.RUN_LAST, None,
74 (GObject.TYPE_PYOBJECT,)),
75 'still-connecting': (GObject.SignalFlags.RUN_LAST, None,
76 (GObject.TYPE_PYOBJECT,)),
77 'now-connected': (GObject.SignalFlags.RUN_LAST, None,
78 (str,)),
79 'job-added': (GObject.SignalFlags.RUN_LAST, None,
80 (int, str,
81 GObject.TYPE_PYOBJECT,
82 GObject.TYPE_PYOBJECT,)),
83 'job-event': (GObject.SignalFlags.RUN_LAST, None,
84 (int, str,
85 GObject.TYPE_PYOBJECT,
86 GObject.TYPE_PYOBJECT,)),
87 'job-removed': (GObject.SignalFlags.RUN_LAST, None,
88 (int, str,
89 GObject.TYPE_PYOBJECT,)),
90 'printer-added': (GObject.SignalFlags.RUN_LAST, None,
91 (str,)),
92 'printer-event': (GObject.SignalFlags.RUN_LAST, None,
93 (str, str,
94 GObject.TYPE_PYOBJECT,)),
95 'printer-removed': (GObject.SignalFlags.RUN_LAST, None,
96 (str,)),
97 'cups-connection-error': (GObject.SignalFlags.RUN_LAST, None, ()),
98 'cups-connection-recovered': (GObject.SignalFlags.RUN_LAST, None, ()),
99 'cups-ipp-error': (GObject.SignalFlags.RUN_LAST, None,
100 (int, str,))
101 }
102
103 # Monitor jobs and printers.
104 DBUS_PATH="/com/redhat/PrinterSpooler"
105 DBUS_IFACE="com.redhat.PrinterSpooler"
106
107 def __init__(self, bus=None, my_jobs=True,
108 specific_dests=None, monitor_jobs=True, host=None,
109 port=None, encryption=None):
110 GObject.GObject.__init__ (self)
111 self.my_jobs = my_jobs
112 self.specific_dests = specific_dests
113 self.monitor_jobs = monitor_jobs
114 self.jobs = {}
115 self.printer_state_reasons = {}
116 self.printers = set()
117 self.process_pending_events = True
118 self.fetch_jobs_timer = None
119 self.cups_connection_in_error = False
120
121 if host:
122 cups.setServer (host)
123 if port:
124 cups.setPort (port)
125 if encryption:
126 cups.setEncryption (encryption)
127 self.user = cups.getUser ()
128 self.host = cups.getServer ()
129 self.port = cups.getPort ()
130 self.encryption = cups.getEncryption ()
131 self.ppdcache = ppdcache.PPDCache (host=self.host,
132 port=self.port,
133 encryption=self.encryption)
134
135 self.which_jobs = "not-completed"
136 self.reasons_seen = {}
137 self.connecting_timers = {}
138 self.still_connecting = set()
139 self.connecting_to_device = {}
140 self.received_any_dbus_signals = False
141 self.update_timer = None
142
143 if bus is None:
144 try:
145 bus = dbus.SystemBus ()
146 except dbus.exceptions.DBusException:
147 # System bus not running.
148 pass
149
150 self.bus = bus
151 if bus is not None:
152 bus.add_signal_receiver (self.handle_dbus_signal,
153 path=self.DBUS_PATH,
154 dbus_interface=self.DBUS_IFACE)
155 self.sub_id = -1
156
157 def get_printers (self):
158 return self.printers.copy ()
159
160 def get_jobs (self):
161 return self.jobs.copy ()
162
163 def get_ppdcache (self):
164 return self.ppdcache
165
166 def cleanup (self):
167 if self.sub_id != -1:
168 user = cups.getUser ()
169 try:
170 cups.setUser (self.user)
171 c = cups.Connection (host=self.host,
172 port=self.port,
173 encryption=self.encryption)
174 c.cancelSubscription (self.sub_id)
175 debugprint ("Canceled subscription %d" % self.sub_id)
176 except:
177 pass
178 cups.setUser (user)
179
180 if self.bus is not None:
181 self.bus.remove_signal_receiver (self.handle_dbus_signal,
182 path=self.DBUS_PATH,
183 dbus_interface=self.DBUS_IFACE)
184
185 timers = list(self.connecting_timers.values ())
186 for timer in [self.update_timer, self.fetch_jobs_timer]:
187 if timer:
188 timers.append (timer)
189 for timer in timers:
190 GLib.source_remove (timer)
191
192 self.emit ('monitor-exited')
193
194 def set_process_pending (self, whether):
195 self.process_pending_events = whether
196
197 def check_still_connecting(self, printer):
198 """Timer callback to check on connecting-to-device reasons."""
199 if not self.process_pending_events:
200 # Defer the timer by setting a new one.
201 timer = GLib.timeout_add (200, self.check_still_connecting,
202 printer)
203 self.connecting_timers[printer] = timer
204 return False
205
206 if printer in self.connecting_timers:
207 del self.connecting_timers[printer]
208
209 debugprint ("Still-connecting timer fired for `%s'" % printer)
210 (printer_jobs, my_printers) = self.sort_jobs_by_printer ()
211 self.update_connecting_devices (printer_jobs)
212
213 # Don't run this callback again.
214 return False
215
216 def update_connecting_devices(self, printer_jobs={}):
217 """Updates connecting_to_device dict and still_connecting set."""
218 time_now = time.time ()
219 connecting_to_device = {}
220 trouble = False
221 for printer, reasons in self.printer_state_reasons.items ():
222 connected = True
223 for reason in reasons:
224 if reason.get_reason () == "connecting-to-device":
225 have_processing_job = False
226 for job, data in printer_jobs.get (printer, {}).items ():
227 state = data.get ('job-state',
228 cups.IPP_JOB_CANCELED)
229 if state == cups.IPP_JOB_PROCESSING:
230 have_processing_job = True
231 break
232
233 if not have_processing_job:
234 debugprint ("Ignoring stale connecting-to-device x")
235 continue
236
237 # Build a new connecting_to_device dict. If our existing
238 # dict already has an entry for this printer, use that.
239 printer = reason.get_printer ()
240 t = self.connecting_to_device.get (printer, time_now)
241 connecting_to_device[printer] = t
242 debugprint ("Connecting time: %d" % (time_now - t))
243 if time_now - t >= CONNECTING_TIMEOUT:
244 if have_processing_job:
245 if printer not in self.still_connecting:
246 self.still_connecting.add (printer)
247 self.emit ('still-connecting', reason)
248 if printer in self.connecting_timers:
249 GLib.source_remove (self.connecting_timers
250 [printer])
251 del self.connecting_timers[printer]
252 debugprint ("Stopped connecting timer "
253 "for `%s'" % printer)
254
255 connected = False
256 break
257
258 if connected and printer in self.connecting_timers:
259 GLib.source_remove (self.connecting_timers[printer])
260 del self.connecting_timers[printer]
261 debugprint ("Stopped connecting timer for `%s'" % printer)
262
263 # Clear any previously-notified errors that are now fine.
264 remove = set()
265 for printer in self.still_connecting:
266 if printer not in connecting_to_device:
267 remove.add (printer)
268 self.emit ('now-connected', printer)
269 if printer in self.connecting_timers:
270 GLib.source_remove (self.connecting_timers[printer])
271 del self.connecting_timers[printer]
272 debugprint ("Stopped connecting timer for `%s'" % printer)
273
274 self.still_connecting = self.still_connecting.difference (remove)
275 self.connecting_to_device = connecting_to_device
276
277 def check_state_reasons(self, my_printers=set(), printer_jobs={}):
278 # Look for any new reasons since we last checked.
279 old_reasons_seen_keys = list(self.reasons_seen.keys ())
280 reasons_now = set()
281 for printer, reasons in self.printer_state_reasons.items ():
282 for reason in reasons:
283 tuple = reason.get_tuple ()
284 printer = reason.get_printer ()
285 reasons_now.add (tuple)
286 if tuple not in self.reasons_seen:
287 # New reason.
288 GLib.idle_add (lambda x:
289 self.emit ('state-reason-added', x),
290 reason)
291 self.reasons_seen[tuple] = reason
292
293 if (reason.get_reason () == "connecting-to-device" and
294 printer not in self.connecting_to_device):
295 # First time we've seen this.
296
297 have_processing_job = False
298 for job, data in printer_jobs.get (printer, {}).items ():
299 state = data.get ('job-state',
300 cups.IPP_JOB_CANCELED)
301 if state == cups.IPP_JOB_PROCESSING:
302 have_processing_job = True
303 break
304
305 if have_processing_job:
306 t = GLib.timeout_add_seconds (
307 (1 + CONNECTING_TIMEOUT),
308 self.check_still_connecting,
309 printer)
310 self.connecting_timers[printer] = t
311 debugprint ("Start connecting timer for `%s'" %
312 printer)
313 else:
314 # Don't notify about this, as it must be stale.
315 debugprint ("Ignoring stale connecting-to-device")
316 if get_debugging ():
317 debugprint (pprint.pformat (printer_jobs))
318
319 self.update_connecting_devices (printer_jobs)
320 items = list(self.reasons_seen.keys ())
321 for tuple in items:
322 if not tuple in reasons_now:
323 # Reason no longer present.
324 reason = self.reasons_seen[tuple]
325 del self.reasons_seen[tuple]
326 GLib.idle_add (lambda x: self.emit ('state-reason-removed', x),
327 reason)
328
329 def get_notifications(self):
330 if self.update_timer:
331 GLib.source_remove (self.update_timer)
332
333 self.update_timer = None
334 if not self.process_pending_events:
335 # Defer the timer callback.
336 self.update_timer = GLib.timeout_add (200,
337 self.get_notifications)
338 debugprint ("Deferred get_notifications by 200ms")
339 return False
340
341 debugprint ("get_notifications")
342 user = cups.getUser ()
343 try:
344 cups.setUser (self.user)
345 c = cups.Connection (host=self.host,
346 port=self.port,
347 encryption=self.encryption)
348
349 try:
350 try:
351 notifications = c.getNotifications ([self.sub_id],
352 [self.sub_seq + 1])
353 except AttributeError:
354 notifications = c.getNotifications ([self.sub_id])
355 except cups.IPPError as e:
356 (e, m) = e.args
357 cups.setUser (user)
358 if e == cups.IPP_NOT_FOUND:
359 # Subscription lease has expired.
360 self.sub_id = -1
361 debugprint ("Subscription not found, will refresh")
362 self.refresh ()
363 return False
364
365 self.emit ('cups-ipp-error', e, m)
366 if e == cups.IPP_FORBIDDEN:
367 return False
368
369 debugprint ("getNotifications failed with %d (%s)" % (e, m))
370 return True
371 except RuntimeError:
372 cups.setUser (user)
373 debugprint ("cups-connection-error, will retry")
374 self.cups_connection_in_error = True
375 self.emit ('cups-connection-error')
376 return True
377
378 if self.cups_connection_in_error:
379 self.cups_connection_in_error = False
380 debugprint ("cups-connection-recovered")
381 self.emit ('cups-connection-recovered')
382
383 cups.setUser (user)
384 jobs = self.jobs.copy ()
385 for event in notifications['events']:
386 seq = event['notify-sequence-number']
387 self.sub_seq = seq
388 nse = event['notify-subscribed-event']
389 debugprint ("%d %s %s" % (seq, nse, event['notify-text']))
390 if get_debugging ():
391 debugprint (pprint.pformat (event))
392 if nse.startswith ('printer-'):
393 # Printer events
394 name = event['printer-name']
395 if nse == 'printer-added' and name not in self.printers:
396 self.printers.add (name)
397 self.emit ('printer-added', name)
398
399 elif nse == 'printer-deleted' and name in self.printers:
400 self.printers.remove (name)
401 items = list(self.reasons_seen.keys ())
402 for tuple in items:
403 if tuple[1] == name:
404 reason = self.reasons_seen[tuple]
405 del self.reasons_seen[tuple]
406 self.emit ('state-reason-removed', reason)
407
408 if name in self.printer_state_reasons:
409 del self.printer_state_reasons[name]
410
411 self.emit ('printer-removed', name)
412 elif name in self.printers:
413 printer_state_reasons = event['printer-state-reasons']
414 reasons = []
415 for reason in printer_state_reasons:
416 if reason == "none":
417 break
418 if state_reason_is_harmless (reason):
419 continue
420 reasons.append (StateReason (name, reason,
421 self.ppdcache))
422 self.printer_state_reasons[name] = reasons
423
424 self.emit ('printer-event', name, nse, event)
425 continue
426
427 # Job events
428 if not nse.startswith ("job-"):
429 # Some versions of CUPS give empty
430 # notify-subscribed-event attributes (STR #3608).
431 debugprint ("Unhandled nse %s" % repr (nse))
432 continue
433
434 jobid = event['notify-job-id']
435 if (nse == 'job-created' or
436 (nse == 'job-state-changed' and
437 jobid not in jobs and
438 event['job-state'] == cups.IPP_JOB_PROCESSING)):
439 if (self.specific_dests is not None and
440 event['printer-name'] not in self.specific_dests):
441 continue
442
443 try:
444 attrs = c.getJobAttributes (jobid)
445 if (self.my_jobs and
446 attrs['job-originating-user-name'] != cups.getUser ()):
447 continue
448
449 jobs[jobid] = attrs
450 except KeyError:
451 jobs[jobid] = {'job-k-octets': 0}
452 except cups.IPPError as e:
453 (e, m) = e.args
454 self.emit ('cups-ipp-error', e, m)
455 jobs[jobid] = {'job-k-octets': 0}
456
457 self.emit ('job-added', jobid, nse, event, jobs[jobid].copy ())
458 elif (nse == 'job-completed' or
459 (nse == 'job-state-changed' and
460 event['job-state'] == cups.IPP_JOB_COMPLETED)):
461 if not (self.which_jobs in ['completed', 'all']):
462 try:
463 del jobs[jobid]
464 self.emit ('job-removed', jobid, nse, event)
465 except KeyError:
466 pass
467 continue
468
469 try:
470 job = jobs[jobid]
471 except KeyError:
472 continue
473
474 if (self.specific_dests is not None and
475 event['printer-name'] not in self.specific_dests):
476 del jobs[jobid]
477 self.emit ('job-removed', jobid, nse, event)
478 continue
479
480 for attribute in ['job-state',
481 'job-name']:
482 job[attribute] = event[attribute]
483 if 'notify-printer-uri' in event:
484 job['job-printer-uri'] = event['notify-printer-uri']
485
486 self.emit ('job-event', jobid, nse, event, job.copy ())
487
488 self.set_process_pending (False)
489 self.update_jobs (jobs)
490 self.jobs = jobs
491 self.set_process_pending (True)
492
493 # Update again when we're told to. If we're getting CUPS
494 # D-Bus signals, however, rely on those instead.
495 if not self.received_any_dbus_signals:
496 interval = notifications['notify-get-interval']
497 t = GLib.timeout_add_seconds (interval,
498 self.get_notifications)
499 debugprint ("Next notifications fetch in %ds" % interval)
500 self.update_timer = t
501
502 return False
503
504 def refresh(self, which_jobs=None, refresh_all=True):
505 debugprint ("refresh")
506
507 self.emit ('refresh')
508 if which_jobs is not None:
509 self.which_jobs = which_jobs
510
511 user = cups.getUser ()
512 try:
513 cups.setUser (self.user)
514 c = cups.Connection (host=self.host,
515 port=self.port,
516 encryption=self.encryption)
517 except RuntimeError:
518 GLib.idle_add (self.emit, 'cups-connection-error')
519 cups.setUser (user)
520 return
521
522 if self.sub_id != -1:
523 try:
524 c.cancelSubscription (self.sub_id)
525 except cups.IPPError as e:
526 (e, m) = e.args
527 GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m),
528 e, m)
529
530 if self.update_timer:
531 GLib.source_remove (self.update_timer)
532
533 self.update_timer = None
534 debugprint ("Canceled subscription %d" % self.sub_id)
535
536 try:
537 del self.sub_seq
538 except AttributeError:
539 pass
540
541 events = ["printer-added",
542 "printer-modified",
543 "printer-deleted",
544 "printer-state-changed"]
545 if self.monitor_jobs:
546 events.extend (["job-created",
547 "job-completed",
548 "job-stopped",
549 "job-state-changed",
550 "job-progress"])
551
552 try:
553 self.sub_id = c.createSubscription ("/", events=events)
554 debugprint ("Created subscription %d, events=%s" % (self.sub_id,
555 repr (events)))
556 except cups.IPPError as e:
557 (e, m) = e.args
558 GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m),
559 e, m)
560
561 cups.setUser (user)
562
563 if self.sub_id != -1:
564 if self.update_timer:
565 GLib.source_remove (self.update_timer)
566
567 self.update_timer = GLib.timeout_add_seconds (
568 MIN_REFRESH_INTERVAL,
569 self.get_notifications)
570 debugprint ("Next notifications fetch in %ds" %
571 MIN_REFRESH_INTERVAL)
572
573 if self.monitor_jobs:
574 jobs = self.jobs.copy ()
575 if self.which_jobs not in ['all', 'completed']:
576 # Filter out completed jobs.
577 filtered = {}
578 for jobid, job in jobs.items ():
579 if job.get ('job-state',
580 cups.IPP_JOB_CANCELED) < cups.IPP_JOB_CANCELED:
581 filtered[jobid] = job
582 jobs = filtered
583
584 self.fetch_first_job_id = 1
585 if self.fetch_jobs_timer:
586 GLib.source_remove (self.fetch_jobs_timer)
587 self.fetch_jobs_timer = GLib.timeout_add (5, self.fetch_jobs,
588 refresh_all)
589 else:
590 jobs = {}
591
592 try:
593 r = collect_printer_state_reasons (c, self.ppdcache)
594 self.printer_state_reasons = r
595 dests = c.getPrinters ()
596 self.printers = set(dests.keys ())
597 except cups.IPPError as e:
598 (e, m) = e.args
599 GLib.idle_add (lambda e, m: self.emit ('cups-ipp-error', e, m),
600 e, m)
601 return
602 except RuntimeError:
603 GLib.idle_add (self.emit, 'cups-connection-error')
604 return
605
606 if self.specific_dests is not None:
607 for jobid in jobs.keys ():
608 uri = jobs[jobid].get('job-printer-uri', '/')
609 i = uri.rfind ('/')
610 printer = uri[i + 1:]
611 if printer not in self.specific_dests:
612 del jobs[jobid]
613
614 self.set_process_pending (False)
615 for printer in self.printers:
616 GLib.idle_add (lambda x: self.emit ('printer-added', x), printer)
617 for jobid, job in jobs.items ():
618 GLib.idle_add (lambda jobid, job:
619 self.emit ('job-added', jobid, '', {}, job),
620 jobid, job)
621 self.update_jobs (jobs)
622 self.jobs = jobs
623 self.set_process_pending (True)
624 return False
625
626 def fetch_jobs (self, refresh_all):
627 if not self.process_pending_events:
628 # Skip this call. We'll get called again soon.
629 return True
630
631 user = cups.getUser ()
632 try:
633 cups.setUser (self.user)
634 c = cups.Connection (host=self.host,
635 port=self.port,
636 encryption=self.encryption)
637 except RuntimeError:
638 self.emit ('cups-connection-error')
639 self.fetch_jobs_timer = None
640 cups.setUser (user)
641 return False
642
643 limit = 1
644 r = ["job-id",
645 "job-printer-uri",
646 "job-state",
647 "job-originating-user-name",
648 "job-k-octets",
649 "job-name",
650 "time-at-creation"]
651 try:
652 fetched = c.getJobs (which_jobs=self.which_jobs,
653 my_jobs=self.my_jobs,
654 first_job_id=self.fetch_first_job_id,
655 limit=limit,
656 requested_attributes=r)
657 except cups.IPPError as e:
658 (e, m) = e.args
659 self.emit ('cups-ipp-error', e, m)
660 self.fetch_jobs_timer = None
661 cups.setUser (user)
662 return False
663
664 cups.setUser (user)
665 got = len (fetched)
666 debugprint ("Got %s jobs, asked for %s" % (got, limit))
667
668 jobs = self.jobs.copy ()
669 jobids = list(fetched.keys ())
670 jobids.sort ()
671 if got > 0:
672 last_jobid = jobids[got - 1]
673 if last_jobid < self.fetch_first_job_id:
674 last_jobid = self.fetch_first_job_id + limit - 1
675 debugprint ("Unexpected job IDs returned: %s" % repr (jobids))
676 debugprint ("That's not what we asked for!")
677 else:
678 last_jobid = self.fetch_first_job_id + limit - 1
679 for jobid in range (self.fetch_first_job_id, last_jobid + 1):
680 try:
681 job = fetched[jobid]
682 if self.specific_dests is not None:
683 uri = job.get('job-printer-uri', '/')
684 i = uri.rfind ('/')
685 printer = uri[i + 1:]
686 if printer not in self.specific_dests:
687 raise KeyError
688
689 if jobid in jobs:
690 n = 'job-event'
691 else:
692 n = 'job-added'
693
694 jobs[jobid] = job
695 self.emit (n, jobid, '', {}, job.copy ())
696 except KeyError:
697 # No job by that ID.
698 if jobid in jobs:
699 del jobs[jobid]
700 self.emit ('job-removed', jobid, '', {})
701
702 jobids = list(jobs.keys ())
703 jobids.sort ()
704 if got < limit:
705 trim = False
706 for i in range (len (jobids)):
707 jobid = jobids[i]
708 if not trim and jobid > last_jobid:
709 trim = True
710
711 if trim:
712 del jobs[jobid]
713 self.emit ('job-removed', jobid, '', {})
714
715 self.update_jobs (jobs)
716 self.jobs = jobs
717
718 if got < limit:
719 # That's all. Don't run this timer again.
720 self.fetch_jobs_timer = None
721 return False
722
723 # Remember where we got up to and run this timer again.
724 next = jobid + 1
725
726 while not refresh_all and next in self.jobs:
727 next += 1
728
729 self.fetch_first_job_id = next
730 return True
731
732 def sort_jobs_by_printer (self, jobs=None):
733 if jobs is None:
734 jobs = self.jobs
735
736 my_printers = set()
737 printer_jobs = {}
738 for job, data in jobs.items ():
739 state = data.get ('job-state', cups.IPP_JOB_CANCELED)
740 if state >= cups.IPP_JOB_CANCELED:
741 continue
742 uri = data.get ('job-printer-uri', '')
743 i = uri.rfind ('/')
744 if i == -1:
745 continue
746 printer = uri[i + 1:]
747 my_printers.add (printer)
748 if printer not in printer_jobs:
749 printer_jobs[printer] = {}
750 printer_jobs[printer][job] = data
751
752 return (printer_jobs, my_printers)
753
754 def update_jobs(self, jobs):
755 debugprint ("update_jobs")
756 (printer_jobs, my_printers) = self.sort_jobs_by_printer (jobs)
757 self.check_state_reasons (my_printers, printer_jobs)
758
759 def update(self):
760 if self.update_timer:
761 GLib.source_remove (self.update_timer)
762
763 self.update_timer = GLib.timeout_add (200, self.get_notifications)
764 debugprint ("Next notifications fetch in 200ms (update called)")
765
766 def handle_dbus_signal(self, *args):
767 debugprint ("D-Bus signal from CUPS... calling update")
768 self.update ()
769 if not self.received_any_dbus_signals:
770 self.received_any_dbus_signals = True
771
772 if __name__ == '__main__':
773 class SignalWatcher:
774 def __init__ (self, monitor):
775 monitor.connect ('monitor-exited', self.on_monitor_exited)
776 monitor.connect ('state-reason-added', self.on_state_reason_added)
777 monitor.connect ('state-reason-removed',
778 self.on_state_reason_removed)
779 monitor.connect ('still-connecting', self.on_still_connecting)
780 monitor.connect ('now-connected', self.on_now_connected)
781 monitor.connect ('job-added', self.on_job_added)
782 monitor.connect ('job-event', self.on_job_event)
783 monitor.connect ('job-removed', self.on_job_removed)
784 monitor.connect ('printer-added', self.on_printer_added)
785 monitor.connect ('printer-event', self.on_printer_event)
786 monitor.connect ('printer-removed', self.on_printer_removed)
787 monitor.connect ('cups-connection-error',
788 self.on_cups_connection_error)
789 monitor.connect ('cups-ipp-error', self.on_cups_ipp_error)
790
791 def on_monitor_exited (self, obj):
792 print("*%s: monitor exited" % obj)
793
794 def on_state_reason_added (self, obj, reason):
795 print("*%s: +%s" % (obj, reason))
796
797 def on_state_reason_removed (self, obj, reason):
798 print("*%s: -%s" % (obj, reason))
799
800 def on_still_connecting (self, obj, reason):
801 print("*%s: still connecting: %s" % (obj, reason))
802
803 def on_now_connected (self, obj, printer):
804 print("*%s: now connected: %s" % (obj, printer))
805
806 def on_job_added (self, obj, jobid, eventname, event, jobdata):
807 print("*%s: job %d added" % (obj, jobid))
808
809 def on_job_event (self, obj, jobid, eventname, event, jobdata):
810 print("*%s: job %d event: %s" % (obj, jobid, event))
811
812 def on_job_removed (self, obj, jobid, eventname, event):
813 print("*%s: job %d removed (%s)"% (obj, jobid, eventname))
814
815 def on_printer_added (self, obj, name):
816 print("*%s: printer added: %s" % (obj, name))
817
818 def on_printer_event (self, obj, name, eventname, event):
819 print("*%s: printer event: %s: %s" % (obj, name, eventname))
820
821 def on_printer_removed (self, obj, name):
822 print("*%s: printer %s removed" % (obj, name))
823
824 def on_cups_connection_error (self, obj):
825 print("*%s: cups connection error" % obj)
826
827 def on_cups_ipp_error (self, obj, err, errstring):
828 print("*%s: IPP error (%d): %s" % (obj, err, errstring))
829
830 set_debugging (True)
831 m = Monitor ()
832 SignalWatcher (m)
833 m.refresh ()
834 loop = GObject.MainLoop ()
835 try:
836 loop.run ()
837 finally:
838 m.cleanup ()