forked from phin1x/go-ipp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipp-client.go
More file actions
405 lines (322 loc) · 11.8 KB
/
ipp-client.go
File metadata and controls
405 lines (322 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package ipp
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path"
"strconv"
)
const (
ippContentType = "application/ipp"
)
type Document struct {
Document io.Reader
Size int
Name string
MimeType string
}
type IPPClient struct {
host string
port int
username string
password string
useTLS bool
client *http.Client
}
func NewIPPClient(host string, port int, username, password string, useTLS bool) *IPPClient {
httpClient := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
return &IPPClient{host, port, username, password, useTLS, &httpClient}
}
func (c *IPPClient) getHttpUri(namespace string, object interface{}) string {
proto := "http"
if c.useTLS {
proto = "https"
}
uri := fmt.Sprintf("%s://%s:%d", proto, c.host, c.port)
if namespace != "" {
uri = fmt.Sprintf("%s/%s", uri, namespace)
}
if object != nil {
uri = fmt.Sprintf("%s/%v", uri, object)
}
return uri
}
func (c *IPPClient) getPrinterUri(printer string) string {
return fmt.Sprintf("ipp://localhost/printers/%s", printer)
}
func (c *IPPClient) getJobUri(jobID int) string {
return fmt.Sprintf("ipp://localhost/jobs/%d", jobID)
}
func (c *IPPClient) getClassUri(printer string) string {
return fmt.Sprintf("ipp://localhost/classes/%s", printer)
}
func (c *IPPClient) SendRequest(url string, req *Request) (*Response, error) {
payload, err := req.Encode()
if err != nil {
return nil, err
}
var body io.Reader
size := len(payload)
if req.File != nil && req.FileSize != -1 {
size += int(req.FileSize)
body = io.MultiReader(bytes.NewBuffer(payload), req.File)
} else {
body = bytes.NewBuffer(payload)
}
httpReq, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Length", strconv.Itoa(size))
httpReq.Header.Set("Content-Type", ippContentType)
if c.username != "" && c.password != "" {
httpReq.SetBasicAuth(c.username, c.password)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != 200 {
return nil, fmt.Errorf("ipp server returned with http status code %d", httpResp.StatusCode)
}
//read the response into a temp buffer due to some wired EOF errors
httpBody, _ := ioutil.ReadAll(httpResp.Body)
//fmt.Println(httpBody)
return NewResponseDecoder(bytes.NewBuffer(httpBody)).Decode()
//return NewResponseDecoder(httpResp.Body).Decode()
}
// Print one or more `Document`s using IPP `Create-Job` followed by `Send-Document` request(s).
func (c *IPPClient) PrintDocuments(docs []Document, printer string, jobAttributes map[string]interface{}) (int, error) {
printerURI := c.getPrinterUri(printer)
req := NewRequest(OperationCreateJob, 1)
req.OperationAttributes[OperationAttributePrinterURI] = printerURI
req.OperationAttributes[OperationAttributeRequestingUserName] = c.username
// set defaults for some attributes, may get overwritten
req.OperationAttributes[OperationAttributeJobName] = docs[0].Name
req.OperationAttributes[OperationAttributeCopies] = 1
req.OperationAttributes[OperationAttributeJobPriority] = DefaultJobPriority
for key, value := range jobAttributes {
req.JobAttributes[key] = value
}
resp, err := c.SendRequest(c.getHttpUri("printers", printer), req)
if err != nil {
return -1, err
}
if len(resp.Jobs) == 0 {
return 0, errors.New("server doesn't returned a job id")
}
jobID := resp.Jobs[0][OperationAttributeJobID][0].Value.(int)
documentCount := len(docs) - 1
for docID, doc := range docs {
req = NewRequest(OperationSendDocument, 2)
req.OperationAttributes[OperationAttributePrinterURI] = printerURI
req.OperationAttributes[OperationAttributeRequestingUserName] = c.username
req.OperationAttributes[OperationAttributeJobID] = jobID
req.OperationAttributes[OperationAttributeDocumentName] = doc.Name
req.OperationAttributes[OperationAttributeDocumentFormat] = doc.MimeType
req.OperationAttributes[OperationAttributeLastDocument] = docID == documentCount
req.File = doc.Document
req.FileSize = doc.Size
resp, err = c.SendRequest(c.getHttpUri("printers", printer), req)
if err != nil {
return -1, err
}
}
return jobID, nil
}
// Print a `Document` using an IPP `Print-Job` request.
//
// `jobAttributes` can contain arbitrary key/value pairs to control the way in which the
// document is printed. [RFC 2911 § 4.2](https://tools.ietf.org/html/rfc2911#section-4.2)
// defines some useful attributes:
//
// * [`job-priority`](https://tools.ietf.org/html/rfc2911#section-4.2.1): an integer between 1-100
// * [`copies`](https://tools.ietf.org/html/rfc2911#section-4.2.5): a positive integer
// * [`finishings`](https://tools.ietf.org/html/rfc2911#section-4.2.6): an enumeration
// * [`number-up`](https://tools.ietf.org/html/rfc2911#section-4.2.9): a positive integer
// * [`orientation-requested`](https://tools.ietf.org/html/rfc2911#section-4.2.10): an enumeration
// * [`media`](https://tools.ietf.org/html/rfc2911#section-4.2.11): a string
// * [`printer-resolution`](https://tools.ietf.org/html/rfc2911#section-4.2.12): a `Resolution`
// * [`print-quality`](https://tools.ietf.org/html/rfc2911#section-4.2.13): an enumeration
//
// Your print system may provide other attributes. Define custom attributes as needed in
// `AttributeTagMapping` and provide values here.
func (c *IPPClient) PrintJob(doc Document, printer string, jobAttributes map[string]interface{}) (int, error) {
printerURI := c.getPrinterUri(printer)
req := NewRequest(OperationPrintJob, 1)
req.OperationAttributes[OperationAttributePrinterURI] = printerURI
req.OperationAttributes[OperationAttributeRequestingUserName] = c.username
req.OperationAttributes[OperationAttributeJobName] = doc.Name
req.OperationAttributes[OperationAttributeDocumentFormat] = doc.MimeType
// set defaults for some attributes, may get overwritten
req.OperationAttributes[OperationAttributeCopies] = 1
req.OperationAttributes[OperationAttributeJobPriority] = DefaultJobPriority
for key, value := range jobAttributes {
req.JobAttributes[key] = value
}
req.File = doc.Document
req.FileSize = doc.Size
resp, err := c.SendRequest(c.getHttpUri("printers", printer), req)
if err != nil {
return -1, err
}
if len(resp.Jobs) == 0 {
return 0, errors.New("server doesn't returned a job id")
}
jobID := resp.Jobs[0][OperationAttributeJobID][0].Value.(int)
return jobID, nil
}
func (c *IPPClient) PrintFile(filePath, printer string, jobAttributes map[string]interface{}) (int, error) {
fileStats, err := os.Stat(filePath)
if os.IsNotExist(err) {
return -1, err
}
fileName := path.Base(filePath)
document, err := os.Open(filePath)
if err != nil {
return 0, err
}
defer document.Close()
jobAttributes[OperationAttributeJobName] = fileName
return c.PrintDocuments([]Document{
{
Document: document,
Name: fileName,
Size: int(fileStats.Size()),
MimeType: MimeTypeOctetStream,
},
}, printer, jobAttributes)
}
func (c *IPPClient) GetPrinterAttributes(printer string, attributes []string) (Attributes, error) {
req := NewRequest(OperationGetPrinterAttributes, 1)
req.OperationAttributes[OperationAttributePrinterURI] = c.getPrinterUri(printer)
req.OperationAttributes[OperationAttributeRequestingUserName] = c.username
if attributes == nil {
req.OperationAttributes[OperationAttributeRequestedAttributes] = DefaultPrinterAttributes
} else {
req.OperationAttributes[OperationAttributeRequestedAttributes] = attributes
}
resp, err := c.SendRequest(c.getHttpUri("printers", printer), req)
if err != nil {
return nil, err
}
if len(resp.Printers) == 0 {
return nil, errors.New("server doesn't return any printer attributes")
}
return resp.Printers[0], nil
}
func (c *IPPClient) ResumePrinter(printer string) error {
req := NewRequest(OperationResumePrinter, 1)
req.OperationAttributes[OperationAttributePrinterURI] = c.getPrinterUri(printer)
_, err := c.SendRequest(c.getHttpUri("admin", ""), req)
return err
}
func (c *IPPClient) PausePrinter(printer string) error {
req := NewRequest(OperationPausePrinter, 1)
req.OperationAttributes[OperationAttributePrinterURI] = c.getPrinterUri(printer)
_, err := c.SendRequest(c.getHttpUri("admin", ""), req)
return err
}
func (c *IPPClient) GetJobAttributes(jobID int, attributes []string) (Attributes, error) {
req := NewRequest(OperationGetJobAttributes, 1)
req.OperationAttributes[OperationAttributeJobURI] = c.getJobUri(jobID)
if attributes == nil {
req.OperationAttributes[OperationAttributeRequestedAttributes] = DefaultJobAttributes
} else {
req.OperationAttributes[OperationAttributeRequestedAttributes] = attributes
}
resp, err := c.SendRequest(c.getHttpUri("jobs", jobID), req)
if err != nil {
return nil, err
}
if len(resp.Printers) == 0 {
return nil, errors.New("server doesn't return any job attributes")
}
return resp.Printers[0], nil
}
func (c *IPPClient) GetJobs(printer string, whichJobs JobStateFilter, myJobs bool, attributes []string) (map[int]Attributes, error) {
req := NewRequest(OperationGetJobs, 1)
req.OperationAttributes[OperationAttributePrinterURI] = c.getPrinterUri(printer)
req.OperationAttributes[OperationAttributeWhichJobs] = string(whichJobs)
req.OperationAttributes[OperationAttributeMyJobs] = myJobs
if attributes == nil {
req.OperationAttributes[OperationAttributeRequestedAttributes] = DefaultJobAttributes
} else {
req.OperationAttributes[OperationAttributeRequestedAttributes] = append(attributes, OperationAttributeJobID)
}
resp, err := c.SendRequest(c.getHttpUri("", nil), req)
if err != nil {
return nil, err
}
jobIDMap := make(map[int]Attributes)
for _, jobAttributes := range resp.Jobs {
jobIDMap[jobAttributes[OperationAttributeJobID][0].Value.(int)] = jobAttributes
}
return jobIDMap, nil
}
func (c *IPPClient) CancelJob(jobID int, purge bool) error {
req := NewRequest(OperationCancelJob, 1)
req.OperationAttributes[OperationAttributeJobURI] = c.getJobUri(jobID)
req.OperationAttributes[OperationAttributePurgeJobs] = purge
_, err := c.SendRequest(c.getHttpUri("jobs", ""), req)
return err
}
func (c *IPPClient) CancelAllJob(printer string, purge bool) error {
req := NewRequest(OperationCancelJobs, 1)
req.OperationAttributes[OperationAttributePrinterURI] = c.getPrinterUri(printer)
req.OperationAttributes[OperationAttributePurgeJobs] = purge
_, err := c.SendRequest(c.getHttpUri("admin", ""), req)
return err
}
func (c *IPPClient) RestartJob(jobID int) error {
req := NewRequest(OperationRestartJob, 1)
req.OperationAttributes[OperationAttributeJobURI] = c.getJobUri(jobID)
_, err := c.SendRequest(c.getHttpUri("jobs", ""), req)
return err
}
func (c *IPPClient) HoldJobUntil(jobID int, holdUntil string) error {
req := NewRequest(OperationRestartJob, 1)
req.OperationAttributes[OperationAttributeJobURI] = c.getJobUri(jobID)
req.JobAttributes[PrinterAttributeHoldJobUntil] = holdUntil
_, err := c.SendRequest(c.getHttpUri("jobs", ""), req)
return err
}
func (c *IPPClient) PrintTestPage(printer string) (int, error) {
testPage := new(bytes.Buffer)
testPage.WriteString("#PDF-BANNER\n")
testPage.WriteString("Template default-testpage.pdf\n")
testPage.WriteString("Show printer-name printer-info printer-location printer-make-and-model printer-driver-name")
testPage.WriteString("printer-driver-version paper-size imageable-area job-id options time-at-creation")
testPage.WriteString("time-at-processing\n\n")
return c.PrintDocuments([]Document{
{
Document: testPage,
Name: "Test Page",
Size: testPage.Len(),
MimeType: MimeTypePostscript,
},
}, printer, map[string]interface{}{
OperationAttributeJobName: "Test Page",
})
}
func (c *IPPClient) TestConnection() error {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.host, c.port))
if err != nil {
return err
}
conn.Close()
return nil
}