Debian Codegraph @

ppdcache.py

raw
1 #!/usr/bin/python3
2
3 ## Copyright (C) 2010, 2011, 2012, 2013, 2014 Red Hat, Inc.
4 ## Authors:
5 ## Tim Waugh <[email protected]>
6
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
16
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 import asyncconn
22 import cups
23 from gi.repository import GLib
24 from gi.repository import Gdk
25 from gi.repository import Gtk
26 import os
27 from shutil import copyfileobj
28 from tempfile import NamedTemporaryFile
29 from debug import *
30
31 cups.require ("1.9.50")
32
33 class PPDCache:
34 def __init__ (self, host=None, port=None, encryption=None):
35 self._cups = None
36 self._exc = None
37 self._cache = dict()
38 self._modtimes = dict()
39 self._host = host
40 self._port = port
41 self._encryption = encryption
42 self._queued = list()
43 self._connecting = False
44 debugprint ("+%s" % self)
45
46 def __del__ (self):
47 debugprint ("-%s" % self)
48 if self._cups:
49 self._cups.destroy ()
50
51 def fetch_ppd (self, name, callback, check_uptodate=True):
52 if check_uptodate and name in self._modtimes:
53 # We have getPPD3 so we can check whether the PPD is up to
54 # date.
55 debugprint ("%s: check if %s is up to date" % (self, name))
56 self._cups.getPPD3 (name,
57 modtime=self._modtimes[name],
58 reply_handler=lambda c, r:
59 self._got_ppd3 (c, name, r, callback),
60 error_handler=lambda c, r:
61 self._got_ppd3 (c, name, r, callback))
62 return
63
64 try:
65 f = self._cache[name]
66 except RuntimeError as e:
67 self._schedule_callback (callback, name, None, e)
68 return
69 except KeyError:
70 if not self._cups:
71 self._queued.append ((name, callback))
72 if not self._connecting:
73 self._connect ()
74
75 return
76
77 debugprint ("%s: fetch PPD for %s" % (self, name))
78 self._cups.getPPD3 (name,
79 reply_handler=lambda c, r:
80 self._got_ppd3 (c, name, r, callback),
81 error_handler=lambda c, r:
82 self._got_ppd3 (c, name, r, callback))
83 return
84
85 # Copy from our file object to a new temporary file, create a
86 # PPD object from it, then remove the file. This way we don't
87 # leave temporary files around even though we are caching...
88 f.seek (0)
89 with NamedTemporaryFile () as tmpf:
90 copyfileobj (f, tmpf)
91
92 try:
93 ppd = cups.PPD (tmpf.file)
94 self._schedule_callback (callback, name, ppd, None)
95 except Exception as e:
96 self._schedule_callback (callback, name, None, e)
97
98 def _connect (self, callback=None):
99 self._connecting = True
100 asyncconn.Connection (host=self._host, port=self._port,
101 encryption=self._encryption,
102 reply_handler=self._connected,
103 error_handler=self._connected)
104
105 def _got_ppd (self, connection, name, result, callback):
106 if isinstance (result, Exception):
107 self._schedule_callback (callback, name, none, result)
108 else:
109 # Store an open file object, then remove the actual file.
110 # This way we don't leave temporary files around.
111 try:
112 self._cache[name] = open (result, "rb")
113 debugprint ("%s: caching %s (fd %d)" %
114 (self, result,
115 self._cache[name].fileno()))
116 os.unlink (result)
117 except IOError as exc:
118 self._schedule_callback (callback, name, None, exc)
119 return
120
121 self.fetch_ppd (name, callback)
122
123 def _got_ppd3 (self, connection, name, result, callback):
124 (status, modtime, filename) = result
125 if status in [cups.HTTP_OK, cups.HTTP_NOT_MODIFIED]:
126 if status == cups.HTTP_NOT_MODIFIED:
127 # The file is no newer than the one we already have.
128
129 # CUPS before 1.5.3 created a temporary file in error
130 # in this situation (STR #4018) so remove that.
131 try:
132 os.unlink (filename)
133 except OSError:
134 pass
135
136 elif status == cups.HTTP_OK:
137 # Our version of the file was older. Cache the new version.
138
139 # Store an open file object, then remove the actual
140 # file. This way we don't leave temporary files
141 # around.
142 try:
143 self._cache[name] = open (filename, "rb")
144 debugprint ("%s: caching %s (fd %d) "
145 "(%s) - %s" % (self, filename,
146 self._cache[name].fileno (),
147 modtime, status))
148 os.unlink (filename)
149 self._modtimes[name] = modtime
150 except IOError as exc:
151 # File disappeared?
152 debugprint ("%s: file %s disappeared? Unable to cache it"
153 % (self, filename))
154 self._schedule_callback (callback, name, None, exc)
155 return
156
157 # Now fetch it from our own cache.
158 self.fetch_ppd (name, callback, check_uptodate=False)
159 else:
160 self._schedule_callback (callback, name,
161 None, cups.HTTPError (status))
162
163 def _connected (self, connection, exc):
164 self._connecting = False
165 if isinstance (exc, Exception):
166 self._cups = None
167 self._exc = exc
168 else:
169 self._cups = connection
170
171 queued = self._queued
172 self._queued = list()
173 for name, callback in queued:
174 self.fetch_ppd (name, callback)
175
176 def _schedule_callback (self, callback, name, result, exc):
177 def cb_func (callback, name, result, exc):
178 Gdk.threads_enter ()
179 callback (name, result, exc)
180 Gdk.threads_leave ()
181 return False
182
183 GLib.idle_add (cb_func, callback, name, result, exc)
184
185 if __name__ == "__main__":
186 import sys
187 from debug import *
188 from gi.repository import GObject
189 set_debugging (True)
190 Gdk.threads_init ()
191 loop = GObject.MainLoop ()
192
193 def signal (name, result, exc):
194 debugprint ("**** %s" % name)
195 debugprint (repr (result))
196 debugprint (repr (exc))
197
198 c = cups.Connection ()
199 printers = c.getPrinters ()
200 del c
201
202 cache = PPDCache ()
203 p = None
204 for p in printers:
205 cache.fetch_ppd (p, signal)
206
207 if p:
208 GLib.timeout_add_seconds (1, cache.fetch_ppd, p, signal)
209 GLib.timeout_add_seconds (5, loop.quit)
210 loop.run ()