root / pkipplib / trunk / pkipplib / pkipplib.py @ 18

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

Renamed the correct way now.

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