root / pkipplib / trunk / pkipplib / pkipplib.py @ 25

Revision 25, 24.0 kB (checked in by jerome, 18 years ago)

API cleanups.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkipplib : IPP and CUPS support for Python
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
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# $Id$
22#
23#
24
25import sys
26import os
27import urllib2
28import socket
29from struct import pack, unpack
30
31IPP_VERSION = "1.1"     # default version number
32
33IPP_PORT = 631
34
35IPP_MAX_NAME = 256
36IPP_MAX_VALUES = 8
37
38IPP_TAG_ZERO = 0x00
39IPP_TAG_OPERATION = 0x01
40IPP_TAG_JOB = 0x02
41IPP_TAG_END = 0x03
42IPP_TAG_PRINTER = 0x04
43IPP_TAG_UNSUPPORTED_GROUP = 0x05
44IPP_TAG_SUBSCRIPTION = 0x06
45IPP_TAG_EVENT_NOTIFICATION = 0x07
46IPP_TAG_UNSUPPORTED_VALUE = 0x10
47IPP_TAG_DEFAULT = 0x11
48IPP_TAG_UNKNOWN = 0x12
49IPP_TAG_NOVALUE = 0x13
50IPP_TAG_NOTSETTABLE = 0x15
51IPP_TAG_DELETEATTR = 0x16
52IPP_TAG_ADMINDEFINE = 0x17
53IPP_TAG_INTEGER = 0x21
54IPP_TAG_BOOLEAN = 0x22
55IPP_TAG_ENUM = 0x23
56IPP_TAG_STRING = 0x30
57IPP_TAG_DATE = 0x31
58IPP_TAG_RESOLUTION = 0x32
59IPP_TAG_RANGE = 0x33
60IPP_TAG_BEGIN_COLLECTION = 0x34
61IPP_TAG_TEXTLANG = 0x35
62IPP_TAG_NAMELANG = 0x36
63IPP_TAG_END_COLLECTION = 0x37
64IPP_TAG_TEXT = 0x41
65IPP_TAG_NAME = 0x42
66IPP_TAG_KEYWORD = 0x44
67IPP_TAG_URI = 0x45
68IPP_TAG_URISCHEME = 0x46
69IPP_TAG_CHARSET = 0x47
70IPP_TAG_LANGUAGE = 0x48
71IPP_TAG_MIMETYPE = 0x49
72IPP_TAG_MEMBERNAME = 0x4a
73IPP_TAG_MASK = 0x7fffffff
74IPP_TAG_COPY = -0x7fffffff-1
75
76IPP_RES_PER_INCH = 3
77IPP_RES_PER_CM = 4
78
79IPP_FINISHINGS_NONE = 3
80IPP_FINISHINGS_STAPLE = 4
81IPP_FINISHINGS_PUNCH = 5
82IPP_FINISHINGS_COVER = 6
83IPP_FINISHINGS_BIND = 7
84IPP_FINISHINGS_SADDLE_STITCH = 8
85IPP_FINISHINGS_EDGE_STITCH = 9
86IPP_FINISHINGS_FOLD = 10
87IPP_FINISHINGS_TRIM = 11
88IPP_FINISHINGS_BALE = 12
89IPP_FINISHINGS_BOOKLET_MAKER = 13
90IPP_FINISHINGS_JOB_OFFSET = 14
91IPP_FINISHINGS_STAPLE_TOP_LEFT = 20
92IPP_FINISHINGS_STAPLE_BOTTOM_LEFT = 21
93IPP_FINISHINGS_STAPLE_TOP_RIGHT = 22
94IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT = 23
95IPP_FINISHINGS_EDGE_STITCH_LEFT = 24
96IPP_FINISHINGS_EDGE_STITCH_TOP = 25
97IPP_FINISHINGS_EDGE_STITCH_RIGHT = 26
98IPP_FINISHINGS_EDGE_STITCH_BOTTOM = 27
99IPP_FINISHINGS_STAPLE_DUAL_LEFT = 28
100IPP_FINISHINGS_STAPLE_DUAL_TOP = 29
101IPP_FINISHINGS_STAPLE_DUAL_RIGHT = 30
102IPP_FINISHINGS_STAPLE_DUAL_BOTTOM = 31
103IPP_FINISHINGS_BIND_LEFT = 50
104IPP_FINISHINGS_BIND_TOP = 51
105IPP_FINISHINGS_BIND_RIGHT = 52
106IPP_FINISHINGS_BIND_BOTTO = 53
107
108IPP_PORTRAIT = 3
109IPP_LANDSCAPE = 4
110IPP_REVERSE_LANDSCAPE = 5
111IPP_REVERSE_PORTRAIT = 6
112
113IPP_QUALITY_DRAFT = 3
114IPP_QUALITY_NORMAL = 4
115IPP_QUALITY_HIGH = 5
116
117IPP_JOB_PENDING = 3
118IPP_JOB_HELD = 4
119IPP_JOB_PROCESSING = 5
120IPP_JOB_STOPPED = 6
121IPP_JOB_CANCELLED = 7
122IPP_JOB_ABORTED = 8
123IPP_JOB_COMPLETE = 9
124
125IPP_PRINTER_IDLE = 3
126IPP_PRINTER_PROCESSING = 4
127IPP_PRINTER_STOPPED = 5
128
129IPP_ERROR = -1
130IPP_IDLE = 0
131IPP_HEADER = 1
132IPP_ATTRIBUTE = 2
133IPP_DATA = 3
134
135IPP_PRINT_JOB = 0x0002
136IPP_PRINT_URI = 0x0003
137IPP_VALIDATE_JOB = 0x0004
138IPP_CREATE_JOB = 0x0005
139IPP_SEND_DOCUMENT = 0x0006
140IPP_SEND_URI = 0x0007
141IPP_CANCEL_JOB = 0x0008
142IPP_GET_JOB_ATTRIBUTES = 0x0009
143IPP_GET_JOBS = 0x000a
144IPP_GET_PRINTER_ATTRIBUTES = 0x000b
145IPP_HOLD_JOB = 0x000c
146IPP_RELEASE_JOB = 0x000d
147IPP_RESTART_JOB = 0x000e
148IPP_PAUSE_PRINTER = 0x0010
149IPP_RESUME_PRINTER = 0x0011
150IPP_PURGE_JOBS = 0x0012
151IPP_SET_PRINTER_ATTRIBUTES = 0x0013
152IPP_SET_JOB_ATTRIBUTES = 0x0014
153IPP_GET_PRINTER_SUPPORTED_VALUES = 0x0015
154IPP_CREATE_PRINTER_SUBSCRIPTION = 0x0016
155IPP_CREATE_JOB_SUBSCRIPTION = 0x0017
156IPP_GET_SUBSCRIPTION_ATTRIBUTES = 0x0018
157IPP_GET_SUBSCRIPTIONS = 0x0019
158IPP_RENEW_SUBSCRIPTION = 0x001a
159IPP_CANCEL_SUBSCRIPTION = 0x001b
160IPP_GET_NOTIFICATIONS = 0x001c
161IPP_SEND_NOTIFICATIONS = 0x001d
162IPP_GET_PRINT_SUPPORT_FILES = 0x0021
163IPP_ENABLE_PRINTER = 0x0022
164IPP_DISABLE_PRINTER = 0x0023
165IPP_PAUSE_PRINTER_AFTER_CURRENT_JOB = 0x0024
166IPP_HOLD_NEW_JOBS = 0x0025
167IPP_RELEASE_HELD_NEW_JOBS = 0x0026
168IPP_DEACTIVATE_PRINTER = 0x0027
169IPP_ACTIVATE_PRINTER = 0x0028
170IPP_RESTART_PRINTER = 0x0029
171IPP_SHUTDOWN_PRINTER = 0x002a
172IPP_STARTUP_PRINTER = 0x002b
173IPP_REPROCESS_JOB = 0x002c
174IPP_CANCEL_CURRENT_JOB = 0x002d
175IPP_SUSPEND_CURRENT_JOB = 0x002e
176IPP_RESUME_JOB = 0x002f
177IPP_PROMOTE_JOB = 0x0030
178IPP_SCHEDULE_JOB_AFTER = 0x0031
179IPP_PRIVATE = 0x4000
180CUPS_GET_DEFAULT = 0x4001
181CUPS_GET_PRINTERS = 0x4002
182CUPS_ADD_PRINTER = 0x4003
183CUPS_DELETE_PRINTER = 0x4004
184CUPS_GET_CLASSES = 0x4005
185CUPS_ADD_CLASS = 0x4006
186CUPS_DELETE_CLASS = 0x4007
187CUPS_ACCEPT_JOBS = 0x4008
188CUPS_REJECT_JOBS = 0x4009
189CUPS_SET_DEFAULT = 0x400a
190CUPS_GET_DEVICES = 0x400b
191CUPS_GET_PPDS = 0x400c
192CUPS_MOVE_JOB = 0x400d
193CUPS_AUTHENTICATE_JOB = 0x400e
194
195IPP_OK = 0x0000
196IPP_OK_SUBST = 0x0001
197IPP_OK_CONFLICT = 0x0002
198IPP_OK_IGNORED_SUBSCRIPTIONS = 0x0003
199IPP_OK_IGNORED_NOTIFICATIONS = 0x0004
200IPP_OK_TOO_MANY_EVENTS = 0x0005
201IPP_OK_BUT_CANCEL_SUBSCRIPTION = 0x0006
202IPP_REDIRECTION_OTHER_SITE = 0x0300
203IPP_BAD_REQUEST = 0x0400
204IPP_FORBIDDEN = 0x0401
205IPP_NOT_AUTHENTICATED = 0x0402
206IPP_NOT_AUTHORIZED = 0x0403
207IPP_NOT_POSSIBLE = 0x0404
208IPP_TIMEOUT = 0x0405
209IPP_NOT_FOUND = 0x0406
210IPP_GONE = 0x0407
211IPP_REQUEST_ENTITY = 0x0408
212IPP_REQUEST_VALUE = 0x0409
213IPP_DOCUMENT_FORMAT = 0x040a
214IPP_ATTRIBUTES = 0x040b
215IPP_URI_SCHEME = 0x040c
216IPP_CHARSET = 0x040d
217IPP_CONFLICT = 0x040e
218IPP_COMPRESSION_NOT_SUPPORTED = 0x040f
219IPP_COMPRESSION_ERROR = 0x0410
220IPP_DOCUMENT_FORMAT_ERROR = 0x0411
221IPP_DOCUMENT_ACCESS_ERROR = 0x0412
222IPP_ATTRIBUTES_NOT_SETTABLE = 0x0413
223IPP_IGNORED_ALL_SUBSCRIPTIONS = 0x0414
224IPP_TOO_MANY_SUBSCRIPTIONS = 0x0415
225IPP_IGNORED_ALL_NOTIFICATIONS = 0x0416
226IPP_PRINT_SUPPORT_FILE_NOT_FOUND = 0x0417
227
228IPP_INTERNAL_ERROR = 0x0500
229IPP_OPERATION_NOT_SUPPORTED = 0x0501
230IPP_SERVICE_UNAVAILABLE = 0x0502
231IPP_VERSION_NOT_SUPPORTED = 0x0503
232IPP_DEVICE_ERROR = 0x0504
233IPP_TEMPORARY_ERROR = 0x0505
234IPP_NOT_ACCEPTING = 0x0506
235IPP_PRINTER_BUSY = 0x0507
236IPP_ERROR_JOB_CANCELLED = 0x0508
237IPP_MULTIPLE_JOBS_NOT_SUPPORTED = 0x0509
238IPP_PRINTER_IS_DEACTIVATED = 0x50a
239 
240class IPPError(Exception) :
241    """An exception for IPP related stuff."""
242    def __init__(self, message = ""):
243        self.message = message
244        Exception.__init__(self, message)
245    def __repr__(self):
246        return self.message
247    __str__ = __repr__
248
249class FakeAttribute :
250    """Fakes an IPPRequest attribute to simplify usage syntax."""
251    def __init__(self, request, name) :
252        """Initializes the fake attribute."""
253        self.request = request
254        self.name = name
255       
256    def __setitem__(self, key, value) :
257        """Appends the value to the real attribute."""
258        attributeslist = getattr(self.request, "_%s_attributes" % self.name)
259        for i in range(len(attributeslist)) :
260            attribute = attributeslist[i]
261            for j in range(len(attribute)) :
262                (attrname, attrvalue) = attribute[j]
263                if attrname == key :
264                    attribute[j][1].append(value)
265                    return
266            attribute.append((key, [value]))       
267           
268    def __getitem__(self, key) :
269        """Returns an attribute's value."""
270        attributeslist = getattr(self.request, "_%s_attributes" % self.name)
271        for i in range(len(attributeslist)) :
272            attribute = attributeslist[i]
273            for j in range(len(attribute)) :
274                (attrname, attrvalue) = attribute[j]
275                if attrname == key :
276                    return attrvalue
277        raise KeyError, key           
278   
279class IPPRequest :
280    """A class for IPP requests."""
281    attributes_types = ("operation", "job", "printer", "unsupported", \
282                                     "subscription", "event_notification")
283    def __init__(self, data="", version=IPP_VERSION, 
284                                operation_id=None, \
285                                request_id=None, \
286                                debug=False) :
287        """Initializes an IPP Message object.
288       
289           Parameters :
290           
291             data : the complete IPP Message's content.
292             debug : a boolean value to output debug info on stderr.
293        """
294        self.debug = debug
295        self._data = data
296        self.parsed = False
297       
298        # Initializes message
299        self.setVersion(version)               
300        self.setOperationId(operation_id)
301        self.setRequestId(request_id)
302        self.data = ""
303       
304        for attrtype in self.attributes_types :
305            setattr(self, "_%s_attributes" % attrtype, [[]])
306       
307        # Initialize tags   
308        self.tags = [ None ] * 256 # by default all tags reserved
309       
310        # Delimiter tags
311        self.tags[0x01] = "operation-attributes-tag"
312        self.tags[0x02] = "job-attributes-tag"
313        self.tags[0x03] = "end-of-attributes-tag"
314        self.tags[0x04] = "printer-attributes-tag"
315        self.tags[0x05] = "unsupported-attributes-tag"
316        self.tags[0x06] = "subscription-attributes-tag"
317        self.tags[0x07] = "event-notification-attributes-tag"
318       
319        # out of band values
320        self.tags[0x10] = "unsupported"
321        self.tags[0x11] = "reserved-for-future-default"
322        self.tags[0x12] = "unknown"
323        self.tags[0x13] = "no-value"
324        self.tags[0x15] = "not-settable"
325        self.tags[0x16] = "delete-attribute"
326        self.tags[0x17] = "admin-define"
327 
328        # integer values
329        self.tags[0x20] = "generic-integer"
330        self.tags[0x21] = "integer"
331        self.tags[0x22] = "boolean"
332        self.tags[0x23] = "enum"
333       
334        # octetString
335        self.tags[0x30] = "octetString-with-an-unspecified-format"
336        self.tags[0x31] = "dateTime"
337        self.tags[0x32] = "resolution"
338        self.tags[0x33] = "rangeOfInteger"
339        self.tags[0x34] = "begCollection" # TODO : find sample files for testing
340        self.tags[0x35] = "textWithLanguage"
341        self.tags[0x36] = "nameWithLanguage"
342        self.tags[0x37] = "endCollection"
343       
344        # character strings
345        self.tags[0x40] = "generic-character-string"
346        self.tags[0x41] = "textWithoutLanguage"
347        self.tags[0x42] = "nameWithoutLanguage"
348        self.tags[0x44] = "keyword"
349        self.tags[0x45] = "uri"
350        self.tags[0x46] = "uriScheme"
351        self.tags[0x47] = "charset"
352        self.tags[0x48] = "naturalLanguage"
353        self.tags[0x49] = "mimeMediaType"
354        self.tags[0x4a] = "memberAttrName"
355       
356        # Reverse mapping to generate IPP messages
357        self.tagvalues = {}
358        for i in range(len(self.tags)) :
359            value = self.tags[i]
360            if value is not None :
361                self.tagvalues[value] = i
362                                     
363    def __getattr__(self, name) :                                 
364        """Fakes attribute access."""
365        if name in self.attributes_types :
366            return FakeAttribute(self, name)
367        else :
368            raise AttributeError, name
369           
370    def __str__(self) :       
371        """Returns the parsed IPP message in a readable form."""
372        if not self.parsed :
373            return ""
374        mybuffer = []
375        mybuffer.append("IPP version : %s.%s" % self.version)
376        mybuffer.append("IPP operation Id : 0x%04x" % self.operation_id)
377        mybuffer.append("IPP request Id : 0x%08x" % self.request_id)
378        for attrtype in self.attributes_types :
379            for attribute in getattr(self, "_%s_attributes" % attrtype) :
380                if attribute :
381                    mybuffer.append("%s attributes :" % attrtype.title())
382                for (name, value) in attribute :
383                    mybuffer.append("  %s : %s" % (name, value))
384        if self.data :           
385            mybuffer.append("IPP datas : %s" % repr(self.data))
386        return "\n".join(mybuffer)
387       
388    def logDebug(self, msg) :   
389        """Prints a debug message."""
390        if self.debug :
391            sys.stderr.write("%s\n" % msg)
392            sys.stderr.flush()
393           
394    def setVersion(self, version) :
395        """Sets the request's operation id."""
396        if version is not None :
397            try :
398                self.version = [int(p) for p in version.split(".")]
399            except AttributeError :
400                if len(version) == 2 : # 2-tuple
401                    self.version = version
402                else :   
403                    try :
404                        self.version = [int(p) for p in str(float(version)).split(".")]
405                    except :
406                        self.version = [int(p) for p in IPP_VERSION.split(".")]
407       
408    def setOperationId(self, opid) :       
409        """Sets the request's operation id."""
410        self.operation_id = opid
411       
412    def setRequestId(self, reqid) :       
413        """Sets the request's request id."""
414        self.request_id = reqid
415       
416    def dump(self) :   
417        """Generates an IPP Message.
418       
419           Returns the message as a string of text.
420        """   
421        mybuffer = []
422        if None not in (self.version, self.operation_id) :
423            mybuffer.append(chr(self.version[0]) + chr(self.version[1]))
424            mybuffer.append(pack(">H", self.operation_id))
425            mybuffer.append(pack(">I", self.request_id or 1))
426            for attrtype in self.attributes_types :
427                for attribute in getattr(self, "_%s_attributes" % attrtype) :
428                    if attribute :
429                        mybuffer.append(chr(self.tagvalues["%s-attributes-tag" % attrtype]))
430                    for (attrname, value) in attribute :
431                        nameprinted = 0
432                        for (vtype, val) in value :
433                            mybuffer.append(chr(self.tagvalues[vtype]))
434                            if not nameprinted :
435                                mybuffer.append(pack(">H", len(attrname)))
436                                mybuffer.append(attrname)
437                                nameprinted = 1
438                            else :     
439                                mybuffer.append(pack(">H", 0))
440                            if vtype in ("integer", "enum") :
441                                mybuffer.append(pack(">H", 4))
442                                mybuffer.append(pack(">I", val))
443                            elif vtype == "boolean" :
444                                mybuffer.append(pack(">H", 1))
445                                mybuffer.append(chr(val))
446                            else :   
447                                mybuffer.append(pack(">H", len(val)))
448                                mybuffer.append(val)
449            mybuffer.append(chr(self.tagvalues["end-of-attributes-tag"]))
450        mybuffer.append(self.data)   
451        return "".join(mybuffer)
452           
453    def parse(self) :
454        """Parses an IPP Request.
455       
456           NB : Only a subset of RFC2910 is implemented.
457        """
458        self._curname = None
459        self._curattributes = None
460       
461        self.setVersion((ord(self._data[0]), ord(self._data[1])))
462        self.setOperationId(unpack(">H", self._data[2:4])[0])
463        self.setRequestId(unpack(">I", self._data[4:8])[0])
464        self.position = 8
465        endofattributes = self.tagvalues["end-of-attributes-tag"]
466        maxdelimiter = self.tagvalues["event-notification-attributes-tag"]
467        nulloffset = lambda : 0
468        try :
469            tag = ord(self._data[self.position])
470            while tag != endofattributes :
471                self.position += 1
472                name = self.tags[tag]
473                if name is not None :
474                    func = getattr(self, name.replace("-", "_"), nulloffset)
475                    self.position += func()
476                    if ord(self._data[self.position]) > maxdelimiter :
477                        self.position -= 1
478                        continue
479                oldtag = tag       
480                tag = ord(self._data[self.position])
481                if tag == oldtag :
482                    self._curattributes.append([])
483        except IndexError :
484            raise IPPError, "Unexpected end of IPP message."
485           
486        self.data = self._data[self.position+1:]           
487        self.parsed = True
488       
489    def parseTag(self) :   
490        """Extracts information from an IPP tag."""
491        pos = self.position
492        tagtype = self.tags[ord(self._data[pos])]
493        pos += 1
494        posend = pos2 = pos + 2
495        namelength = unpack(">H", self._data[pos:pos2])[0]
496        if not namelength :
497            name = self._curname
498        else :   
499            posend += namelength
500            self._curname = name = self._data[pos2:posend]
501        pos2 = posend + 2
502        valuelength = unpack(">H", self._data[posend:pos2])[0]
503        posend = pos2 + valuelength
504        value = self._data[pos2:posend]
505        if tagtype in ("integer", "enum") :
506            value = unpack(">I", value)[0]
507        elif tagtype == "boolean" :   
508            value = ord(value)
509        try :   
510            (oldname, oldval) = self._curattributes[-1][-1]
511            if oldname == name :
512                oldval.append((tagtype, value))
513            else :   
514                raise IndexError
515        except IndexError :   
516            self._curattributes[-1].append((name, [(tagtype, value)]))
517        self.logDebug("%s(%s) : %s" % (name, tagtype, value))
518        return posend - self.position
519       
520    def operation_attributes_tag(self) : 
521        """Indicates that the parser enters into an operation-attributes-tag group."""
522        self._curattributes = self._operation_attributes
523        return self.parseTag()
524       
525    def job_attributes_tag(self) : 
526        """Indicates that the parser enters into a job-attributes-tag group."""
527        self._curattributes = self._job_attributes
528        return self.parseTag()
529       
530    def printer_attributes_tag(self) : 
531        """Indicates that the parser enters into a printer-attributes-tag group."""
532        self._curattributes = self._printer_attributes
533        return self.parseTag()
534       
535    def unsupported_attributes_tag(self) : 
536        """Indicates that the parser enters into an unsupported-attributes-tag group."""
537        self._curattributes = self._unsupported_attributes
538        return self.parseTag()
539       
540    def subscription_attributes_tag(self) : 
541        """Indicates that the parser enters into a subscription-attributes-tag group."""
542        self._curattributes = self._subscription_attributes
543        return self.parseTag()
544       
545    def event_notification_attributes_tag(self) : 
546        """Indicates that the parser enters into an event-notification-attributes-tag group."""
547        self._curattributes = self._event_notification_attributes
548        return self.parseTag()
549       
550           
551class CUPS :
552    """A class for a CUPS instance."""
553    def __init__(self, url=None, username=None, password=None, charset="utf-8", language="en-us", debug=False) :
554        """Initializes the CUPS instance."""
555        if url is not None :
556            self.url = url.replace("ipp://", "http://")
557            if self.url.endswith("/") :
558                self.url = self.url[:-1]
559        else :       
560            self.url = self.getDefaultURL()
561        self.username = username
562        self.password = password
563        self.charset = charset
564        self.language = language
565        self.debug = debug
566        self.lastError = None
567        self.lastErrorMessage = None
568        self.requestId = None
569       
570    def getDefaultURL(self) :   
571        """Builds a default URL."""
572        # TODO : encryption methods.
573        server = os.environ.get("CUPS_SERVER") or "localhost"
574        port = os.environ.get("IPP_PORT") or 631
575        if server.startswith("/") :
576            # it seems it's a unix domain socket.
577            # we can't handle this right now, so we use the default instead.
578            return "http://localhost:%s" % port
579        else :   
580            return "http://%s:%s" % (server, port)
581           
582    def identifierToURI(self, service, ident) :
583        """Transforms an identifier into a particular URI depending on requested service."""
584        return "%s/%s/%s" % (self.url.replace("http://", "ipp://"),
585                             service,
586                             ident)
587       
588    def nextRequestId(self) :       
589        """Increments the current request id and returns the new value."""
590        try :
591            self.requestId += 1
592        except TypeError :   
593            self.requestId = 1
594        return self.requestId
595           
596    def newRequest(self, operationid=None) :
597        """Generates a new empty request."""
598        if operationid is not None :
599            req = IPPRequest(operation_id=operationid, \
600                             request_id=self.nextRequestId(), \
601                             debug=self.debug)
602            req.operation["attributes-charset"] = ("charset", self.charset)
603            req.operation["attributes-natural-language"] = ("naturalLanguage", self.language)
604            return req
605   
606    def doRequest(self, req) :
607        """Sends a request to the CUPS server.
608           returns a new IPPRequest object, containing the parsed answer.
609        """   
610        connexion = urllib2.Request(url=self.url, \
611                             data=req.dump())
612        connexion.add_header("Content-Type", "application/ipp")
613        if self.username :
614            pwmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
615            pwmanager.add_password(None, \
616                                   "%s%s" % (connexion.get_host(), connexion.get_selector()), \
617                                   self.username, \
618                                   self.password or "")
619            authhandler = urllib2.HTTPBasicAuthHandler(pwmanager)                       
620            opener = urllib2.build_opener(authhandler)
621            urllib2.install_opener(opener)
622        self.lastError = None   
623        self.lastErrorMessage = None
624        try :   
625            response = urllib2.urlopen(connexion)
626        except (urllib2.URLError, urllib2.HTTPError, socket.error), error :   
627            self.lastError = error
628            self.lastErrorMessage = str(error)
629            return None
630        else :   
631            datas = response.read()
632            ippresponse = IPPRequest(datas)
633            ippresponse.parse()
634            return ippresponse
635   
636    def getDefault(self) :
637        """Retrieves CUPS' default printer."""
638        return self.doRequest(self.newRequest(CUPS_GET_DEFAULT))
639   
640    def getJobAttributes(self, jobid) :   
641        """Retrieves a print job's attributes."""
642        req = self.newRequest(IPP_GET_JOB_ATTRIBUTES)
643        req.operation["job-uri"] = ("uri", self.identifierToURI("jobs", jobid))
644        return self.doRequest(req)
645       
646    def getPPD(self, queuename) :   
647        """Retrieves the PPD for a particular queuename."""
648        req = self.newRequest(IPP_GET_PRINTER_ATTRIBUTES)
649        req.operation["printer-uri"] = ("uri", self.identifierToURI("printers", queuename))
650        for attrib in ("printer-uri-supported", "printer-type", "member-uris") :
651            req.operation["requested-attributes"] = ("nameWithoutLanguage", attrib)
652        return self.doRequest(req)  # TODO : get the PPD from the actual print server
653       
654           
655if __name__ == "__main__" :           
656    if (len(sys.argv) < 2) or (sys.argv[1] == "--debug") :
657        print "usage : python pkipplib.py /var/spool/cups/c00005 [--debug] (for example)\n"
658    else :   
659        infile = open(sys.argv[1], "rb")
660        filedata = infile.read()
661        infile.close()
662       
663        msg = IPPRequest(filedata, debug=(sys.argv[-1]=="--debug"))
664        msg.parse()
665        msg2 = IPPRequest(msg.dump())
666        msg2.parse()
667        filedata2 = msg2.dump()
668       
669        if filedata == filedata2 :
670            print "Test OK : parsing original and parsing the output of the dump produce the same dump !"
671            print str(msg)
672        else :   
673            print "Test Failed !"
674            print str(msg)
675            print
676            print str(msg2)
677       
Note: See TracBrowser for help on using the browser.