labelzoom 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +312 -96
- data/lib/labelzoom/client.rb +195 -30
- data/lib/labelzoom/conversion_result.rb +1 -1
- data/lib/labelzoom/errors.rb +23 -3
- data/lib/labelzoom/formats.rb +40 -4
- data/lib/labelzoom/options.rb +122 -3
- data/lib/labelzoom/printing.rb +205 -0
- data/lib/labelzoom/version.rb +1 -1
- data/lib/labelzoom.rb +7 -1
- metadata +5 -3
data/lib/labelzoom/client.rb
CHANGED
|
@@ -7,7 +7,7 @@ require "time"
|
|
|
7
7
|
require "uri"
|
|
8
8
|
|
|
9
9
|
module LabelZoom
|
|
10
|
-
# Converts labels through the LabelZoom API.
|
|
10
|
+
# Converts labels through the LabelZoom API, and prints them through Cloud Print.
|
|
11
11
|
#
|
|
12
12
|
# Authentication is optional. Without a credential the API serves a free tier:
|
|
13
13
|
# watermarked output, the first label only, a 1 MB request cap, and no multi-page,
|
|
@@ -28,6 +28,13 @@ module LabelZoom
|
|
|
28
28
|
# E2 caps the derived message here. APIError#raw_body keeps the whole body.
|
|
29
29
|
MAX_MESSAGE_LENGTH = 512
|
|
30
30
|
|
|
31
|
+
# Every print call's Accept, and a template print's Content-Type: every print success
|
|
32
|
+
# response is JSON, so convert's */* (rule B2) does not apply.
|
|
33
|
+
JSON_MEDIA_TYPE = "application/json"
|
|
34
|
+
|
|
35
|
+
# The 429 code that makes a {PrintQuotaExceededError} (rule E4), which is never retried.
|
|
36
|
+
DAILY_JOB_LIMIT_CODE = "daily_job_limit_reached"
|
|
37
|
+
|
|
31
38
|
# Statuses worth retrying. Rule F1: nothing else, ever.
|
|
32
39
|
RETRYABLE_STATUSES = ->(status) { status == 429 || status >= 500 }
|
|
33
40
|
|
|
@@ -35,7 +42,8 @@ module LabelZoom
|
|
|
35
42
|
# not always surface a phrase, so this is derived from a table rather than the wire.
|
|
36
43
|
REASON_PHRASES = {
|
|
37
44
|
400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found",
|
|
38
|
-
406 => "Not Acceptable", 413 => "Payload Too Large",
|
|
45
|
+
406 => "Not Acceptable", 413 => "Payload Too Large", 422 => "Unprocessable Content",
|
|
46
|
+
429 => "Too Many Requests",
|
|
39
47
|
500 => "Internal Server Error", 502 => "Bad Gateway", 503 => "Service Unavailable",
|
|
40
48
|
504 => "Gateway Timeout"
|
|
41
49
|
}.freeze
|
|
@@ -117,25 +125,158 @@ module LabelZoom
|
|
|
117
125
|
|
|
118
126
|
params = Options.serialize(**options)
|
|
119
127
|
uri = build_uri(source, target, params)
|
|
120
|
-
|
|
128
|
+
# Accept must be */*. The server's `produces` list omits image/gif, image/bmp and
|
|
129
|
+
# image/jpeg, so naming the target's exact media type yields a 406 from content
|
|
130
|
+
# negotiation before the handler ever runs.
|
|
131
|
+
headers = request_headers(
|
|
132
|
+
"*/*", "Content-Type" => base64_text ? "text/plain" : Formats.media_type(source)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
execute(:post, uri, headers, body) { |response, status| build_result(response, status) }
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Prints a document on a Cloud Print printer. Printing needs an API key with the +print+
|
|
139
|
+
# scope.
|
|
140
|
+
#
|
|
141
|
+
# A printer is a target: the call mirrors {#convert} with the printer in the target's
|
|
142
|
+
# place. The printer's configuration picks the output language, and LabelZoom converts the
|
|
143
|
+
# document to it, so a PDF prints on a ZPL printer.
|
|
144
|
+
#
|
|
145
|
+
# @param source [Symbol] the format of +body+: any source format except +:url+, because
|
|
146
|
+
# print does not fetch. Design files such as +:btw+ and +:nlbl+ print as their own bytes.
|
|
147
|
+
# @param printer_id [String] the printer to print on.
|
|
148
|
+
# @param body [String] the document, as the format's own bytes. Base64 text is not
|
|
149
|
+
# accepted: +base64_text: true+ raises.
|
|
150
|
+
# @param copies [Integer, nil] sends the whole job this many times, 1 to 9999. It
|
|
151
|
+
# multiplies any quantity in the document: +^PQ3+ with 3 copies prints 9 labels.
|
|
152
|
+
# @param idempotency_key [String, nil] makes the print safe to repeat: the same key
|
|
153
|
+
# returns the original job instead of printing again. Use something unique to the
|
|
154
|
+
# label, such as an order number. Omitted, the SDK generates one per call, so its own
|
|
155
|
+
# retries cannot print twice.
|
|
156
|
+
# @param options [Hash] the source options {#convert} takes, in the same nested form
|
|
157
|
+
# (+label:+, +pdf:+, +split:+, +source_dpi:+, ...), plus +rotation:+, the one target
|
|
158
|
+
# option a printer takes. Any other target option, such as +target_dpi:+, raises,
|
|
159
|
+
# because it depends on the output language the printer picks.
|
|
160
|
+
#
|
|
161
|
+
# @return [PrintJob]
|
|
162
|
+
# @raise [ValidationError] if the request is rejected locally, before any network call.
|
|
163
|
+
# @raise [APIError] on any non-2xx response.
|
|
164
|
+
def print(source, printer_id, body, copies: nil, idempotency_key: nil, **options)
|
|
165
|
+
source = Formats.print_source!(source)
|
|
166
|
+
printer_id = Printing.require_id!(printer_id, "printerId")
|
|
167
|
+
body = body.to_s
|
|
168
|
+
if body.empty?
|
|
169
|
+
raise ValidationError.new("body",
|
|
170
|
+
"The document cannot be empty; the API rejects an empty print " \
|
|
171
|
+
"request.")
|
|
172
|
+
end
|
|
173
|
+
copies = Printing.copies!(copies)
|
|
174
|
+
key = Printing.key_for_call(idempotency_key)
|
|
175
|
+
# An empty params would make the server convert a document that is already in the
|
|
176
|
+
# printer's language, so it is sent only when an option is set (rule P2).
|
|
177
|
+
params = Options.serialize_print(**options)
|
|
178
|
+
|
|
179
|
+
# sourceFormat on every request: the server cannot tell ZPL from EPL by Content-Type.
|
|
180
|
+
query = [["sourceFormat", Formats.source_token(source)]]
|
|
181
|
+
query << ["copies", copies] unless copies.nil?
|
|
182
|
+
query << ["params", params] unless params.nil?
|
|
183
|
+
uri = api_uri("/api/v3/printers/#{encode_segment(printer_id)}/print", query)
|
|
184
|
+
headers = request_headers(JSON_MEDIA_TYPE, "Content-Type" => Formats.media_type(source),
|
|
185
|
+
"Idempotency-Key" => key)
|
|
186
|
+
|
|
187
|
+
execute(:post, uri, headers, body) { |response, _| Printing.read_job(read_json(response)) }
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# Prints a published template, one label per record. A template is a source of its own:
|
|
191
|
+
# it takes merge data instead of source options, and the printer is its target.
|
|
192
|
+
#
|
|
193
|
+
# @param template_id [String] a template published from LabelZoom Studio or the web
|
|
194
|
+
# designer.
|
|
195
|
+
# @param printer_id [String] the printer to print on.
|
|
196
|
+
# @param data [Hash, Array<Hash>, nil] one Hash of merge-field values per label. A single
|
|
197
|
+
# Hash is one label. Omit it for a template with no merge fields.
|
|
198
|
+
# @param validate [Boolean] checks every record for missing merge fields before anything
|
|
199
|
+
# prints.
|
|
200
|
+
# @param copies [Integer, nil] sends each label this many times, 1 to 9999.
|
|
201
|
+
# @param idempotency_key [String, nil] one key for the whole batch; the server derives
|
|
202
|
+
# each record's key from it.
|
|
203
|
+
#
|
|
204
|
+
# @return [PrintBatch] a batch whatever the number of records. If +remaining+ is not 0,
|
|
205
|
+
# send the same request with the same key to submit the rest.
|
|
206
|
+
# @raise [ValidationError] if the request is rejected locally, before any network call.
|
|
207
|
+
# @raise [APIError] on any non-2xx response.
|
|
208
|
+
def print_template(template_id, printer_id, data: nil, validate: false, copies: nil,
|
|
209
|
+
idempotency_key: nil)
|
|
210
|
+
template_id = Printing.require_id!(template_id, "templateId")
|
|
211
|
+
printer_id = Printing.require_id!(printer_id, "printerId")
|
|
212
|
+
records = data.nil? ? [] : Options.normalize_data(data)
|
|
213
|
+
copies = Printing.copies!(copies)
|
|
214
|
+
key = Printing.key_for_call(idempotency_key)
|
|
215
|
+
|
|
216
|
+
query = []
|
|
217
|
+
query << ["copies", copies] unless copies.nil?
|
|
218
|
+
query << %w[validate true] if validate
|
|
219
|
+
uri = api_uri("/api/v3/printers/#{encode_segment(printer_id)}/templates/" \
|
|
220
|
+
"#{encode_segment(template_id)}/print", query)
|
|
221
|
+
headers = request_headers(JSON_MEDIA_TYPE, "Content-Type" => JSON_MEDIA_TYPE,
|
|
222
|
+
"Idempotency-Key" => key)
|
|
223
|
+
|
|
224
|
+
execute(:post, uri, headers, Printing.template_body(records)) do |response, _|
|
|
225
|
+
Printing.read_batch(read_json(response))
|
|
226
|
+
end
|
|
227
|
+
end
|
|
121
228
|
|
|
122
|
-
|
|
229
|
+
# Print jobs: +client.jobs.get(job_id)+ follows one to completion.
|
|
230
|
+
#
|
|
231
|
+
# @return [PrintJobs]
|
|
232
|
+
def jobs
|
|
233
|
+
@jobs ||= PrintJobs.new(->(job_id) { fetch_job(job_id) })
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# The account's Cloud Print limits and today's usage. Check it to stop before the daily
|
|
237
|
+
# job limit's {PrintQuotaExceededError}.
|
|
238
|
+
#
|
|
239
|
+
# @return [PrintQuota]
|
|
240
|
+
# @raise [APIError] on any non-2xx response.
|
|
241
|
+
def print_quota
|
|
242
|
+
execute(:get, api_uri("/api/v3/print/quota"), request_headers(JSON_MEDIA_TYPE), nil) do |r, _|
|
|
243
|
+
Printing.read_quota(read_json(r))
|
|
244
|
+
end
|
|
123
245
|
end
|
|
124
246
|
|
|
125
247
|
# The URL a given conversion would be posted to. Exposed because it is the first thing
|
|
126
248
|
# anyone debugging a proxy or a base-URL override wants to see.
|
|
127
249
|
def build_uri(source, target, params = nil)
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
"#{Formats.target_token(target)}"
|
|
132
|
-
# Rule C7: no options means a bare URL, not an empty query string.
|
|
133
|
-
url += "?#{URI.encode_www_form("params" => params)}" unless params.nil?
|
|
134
|
-
URI.parse(url)
|
|
250
|
+
api_uri("/api/v2/convert/#{Formats.source_token(source)}/to/" \
|
|
251
|
+
"#{Formats.target_token(target)}",
|
|
252
|
+
params.nil? ? [] : [["params", params]])
|
|
135
253
|
end
|
|
136
254
|
|
|
137
255
|
private
|
|
138
256
|
|
|
257
|
+
# Concatenated, not resolved: a base URL carrying a path prefix
|
|
258
|
+
# (https://proxy.example.com/labelzoom) must keep it, which URI.join would discard.
|
|
259
|
+
# Rule C7: no query parameters means a bare URL, not an empty query string.
|
|
260
|
+
def api_uri(path, query = [])
|
|
261
|
+
url = "#{@base_url}#{path}"
|
|
262
|
+
url += "?#{URI.encode_www_form(query)}" unless query.empty?
|
|
263
|
+
URI.parse(url)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# Percent-encodes an id as one path segment (rule P1): everything but RFC 3986's
|
|
267
|
+
# unreserved characters, byte by byte.
|
|
268
|
+
def encode_segment(value)
|
|
269
|
+
value.b.gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format("%%%02X", byte.ord) }
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
def fetch_job(job_id)
|
|
273
|
+
job_id = Printing.require_id!(job_id, "jobId")
|
|
274
|
+
uri = api_uri("/api/v3/jobs/#{encode_segment(job_id)}")
|
|
275
|
+
execute(:get, uri, request_headers(JSON_MEDIA_TYPE), nil) do |response, _|
|
|
276
|
+
Printing.read_job_details(read_json(response))
|
|
277
|
+
end
|
|
278
|
+
end
|
|
279
|
+
|
|
139
280
|
def resolve_credential(api_key, env)
|
|
140
281
|
if UNSET.equal?(api_key)
|
|
141
282
|
value = env[API_KEY_ENVIRONMENT_VARIABLE]
|
|
@@ -146,25 +287,22 @@ module LabelZoom
|
|
|
146
287
|
api_key.nil? || api_key.empty? ? nil : api_key
|
|
147
288
|
end
|
|
148
289
|
|
|
149
|
-
def
|
|
150
|
-
headers =
|
|
151
|
-
"Content-Type" => base64_text ? "text/plain" : Formats.media_type(source),
|
|
152
|
-
# Accept must be */*. The server's `produces` list omits image/gif, image/bmp and
|
|
153
|
-
# image/jpeg, so naming the target's exact media type yields a 406 from content
|
|
154
|
-
# negotiation before the handler ever runs.
|
|
155
|
-
"Accept" => "*/*",
|
|
156
|
-
"User-Agent" => @user_agent
|
|
157
|
-
}
|
|
290
|
+
def request_headers(accept, extra = {})
|
|
291
|
+
headers = extra.merge("Accept" => accept, "User-Agent" => @user_agent)
|
|
158
292
|
headers["Authorization"] = "Bearer #{@credential}" unless @credential.nil?
|
|
159
293
|
headers
|
|
160
294
|
end
|
|
161
295
|
|
|
162
|
-
|
|
296
|
+
# Sends one request under the retry policy (rule F) and yields the 2xx response to the
|
|
297
|
+
# block, whose value is returned. Every call goes through here, convert and print alike.
|
|
298
|
+
# The headers, Idempotency-Key included, are fixed before the first attempt, so every
|
|
299
|
+
# retry sends the same ones.
|
|
300
|
+
def execute(method, uri, headers, body)
|
|
163
301
|
attempts = @max_retries + 1
|
|
164
302
|
|
|
165
303
|
(1..).each do |attempt|
|
|
166
304
|
begin
|
|
167
|
-
response = perform(uri, headers, body)
|
|
305
|
+
response = perform(method, uri, headers, body)
|
|
168
306
|
rescue *transport_exceptions => e
|
|
169
307
|
if attempt >= attempts
|
|
170
308
|
raise TransportError, "labelzoom: request to #{uri} failed: #{e.message}"
|
|
@@ -175,26 +313,31 @@ module LabelZoom
|
|
|
175
313
|
end
|
|
176
314
|
|
|
177
315
|
status = response.code.to_i
|
|
178
|
-
return
|
|
316
|
+
return yield(response, status) if status.between?(200, 299)
|
|
179
317
|
|
|
180
318
|
retry_after = retry_after_seconds(response)
|
|
181
|
-
|
|
182
|
-
|
|
319
|
+
error = error_for(response, status, retry_after)
|
|
320
|
+
# Rule F5: the daily print limit's Retry-After is the 00:00 UTC reset, hours away, and
|
|
321
|
+
# honoring it would hang the call.
|
|
322
|
+
if attempt >= attempts || !RETRYABLE_STATUSES.call(status) ||
|
|
323
|
+
error.is_a?(PrintQuotaExceededError)
|
|
324
|
+
raise error
|
|
183
325
|
end
|
|
184
326
|
|
|
185
327
|
delay(attempt, retry_after)
|
|
186
328
|
end
|
|
187
329
|
end
|
|
188
330
|
|
|
189
|
-
def perform(uri, headers, body)
|
|
331
|
+
def perform(method, uri, headers, body)
|
|
190
332
|
http = @http_builder&.call(uri) || Net::HTTP.new(uri.host, uri.port)
|
|
191
333
|
http.use_ssl = uri.scheme == "https"
|
|
192
334
|
http.open_timeout = @timeout
|
|
193
335
|
http.read_timeout = @timeout
|
|
194
336
|
|
|
195
|
-
request = Net::HTTP::Post.new(uri)
|
|
337
|
+
request = (method == :get ? Net::HTTP::Get : Net::HTTP::Post).new(uri)
|
|
196
338
|
headers.each { |name, value| request[name] = value }
|
|
197
|
-
|
|
339
|
+
# The GETs send no body, and so no Content-Type (rule P1).
|
|
340
|
+
request.body = body unless body.nil?
|
|
198
341
|
|
|
199
342
|
http.start { |session| session.request(request) }
|
|
200
343
|
end
|
|
@@ -213,10 +356,20 @@ module LabelZoom
|
|
|
213
356
|
)
|
|
214
357
|
end
|
|
215
358
|
|
|
359
|
+
# Every print success response is a JSON object.
|
|
360
|
+
def read_json(response)
|
|
361
|
+
parsed = JSON.parse((response.body || "").dup.force_encoding(Encoding::UTF_8))
|
|
362
|
+
parsed.is_a?(Hash) ? parsed : {}
|
|
363
|
+
rescue JSON::ParserError => e
|
|
364
|
+
raise Error, "labelzoom: the API returned a success response that is not JSON: #{e.message}"
|
|
365
|
+
end
|
|
366
|
+
|
|
216
367
|
def error_for(response, status, retry_after)
|
|
217
368
|
raw_body = (response.body || "").dup.force_encoding(Encoding::BINARY)
|
|
218
369
|
message = extract_message(raw_body, REASON_PHRASES[status])
|
|
219
|
-
|
|
370
|
+
code = extract_code(raw_body)
|
|
371
|
+
common = { status: status, request_id: response[REQUEST_ID_HEADER], raw_body: raw_body,
|
|
372
|
+
code: code }
|
|
220
373
|
|
|
221
374
|
case status
|
|
222
375
|
when 400 then BadRequestError.new(message, **common)
|
|
@@ -225,7 +378,10 @@ module LabelZoom
|
|
|
225
378
|
ForbiddenError.new(message, paid_feature: message.match?(/paid feature/i), **common)
|
|
226
379
|
when 404 then NotFoundError.new(message, **common)
|
|
227
380
|
when 413 then PayloadTooLargeError.new(message, **common)
|
|
228
|
-
when
|
|
381
|
+
when 422 then UnprocessableError.new(message, **common)
|
|
382
|
+
when 429
|
|
383
|
+
type = code == DAILY_JOB_LIMIT_CODE ? PrintQuotaExceededError : RateLimitedError
|
|
384
|
+
type.new(message, retry_after_seconds: retry_after, **common)
|
|
229
385
|
when 500.. then ServerError.new(message, **common)
|
|
230
386
|
else
|
|
231
387
|
# Anything else non-2xx still becomes a typed error rather than being swallowed --
|
|
@@ -257,6 +413,15 @@ module LabelZoom
|
|
|
257
413
|
"The LabelZoom API returned an error with no response body."
|
|
258
414
|
end
|
|
259
415
|
|
|
416
|
+
# Rule E3: the body's top-level "code" string, else nil. Never a reason to fail.
|
|
417
|
+
def extract_code(raw_body)
|
|
418
|
+
parsed = JSON.parse(raw_body.dup.force_encoding(Encoding::UTF_8).scrub)
|
|
419
|
+
code = parsed["code"] if parsed.is_a?(Hash)
|
|
420
|
+
code.is_a?(String) ? code : nil
|
|
421
|
+
rescue JSON::ParserError
|
|
422
|
+
nil
|
|
423
|
+
end
|
|
424
|
+
|
|
260
425
|
def truncate(value)
|
|
261
426
|
value.length <= MAX_MESSAGE_LENGTH ? value : value[0, MAX_MESSAGE_LENGTH]
|
|
262
427
|
end
|
|
@@ -4,7 +4,7 @@ module LabelZoom
|
|
|
4
4
|
# The outcome of a successful conversion.
|
|
5
5
|
#
|
|
6
6
|
# {#bytes} is authoritative. PDF, PNG, BMP, GIF and JPEG targets are binary, so treating
|
|
7
|
-
# the response as text would silently corrupt five of the
|
|
7
|
+
# the response as text would silently corrupt five of the fourteen targets -- and every
|
|
8
8
|
# printer language reaches the same hazard through a +text/plain+ response: EPL's +GW+ and
|
|
9
9
|
# TSPL's +BITMAP+ inline a raw 1-bpp payload, IPL frames commands in +STX+/+ETX+ around
|
|
10
10
|
# packed bitmap columns, and SBPL embeds inline graphics between +ESC+ commands.
|
data/lib/labelzoom/errors.rb
CHANGED
|
@@ -20,11 +20,17 @@ module LabelZoom
|
|
|
20
20
|
# and capped at 512 characters; this is not.
|
|
21
21
|
attr_reader :raw_body
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
# @return [String, nil] the error body's top-level +code+, such as
|
|
24
|
+
# +"agent_update_required"+, or nil when the body has none. Codes are stable, so branch
|
|
25
|
+
# on this rather than on {#message}.
|
|
26
|
+
attr_reader :code
|
|
27
|
+
|
|
28
|
+
def initialize(message, status:, request_id: nil, raw_body: "", code: nil)
|
|
24
29
|
super(message)
|
|
25
30
|
@status = status
|
|
26
31
|
@request_id = request_id
|
|
27
32
|
@raw_body = raw_body
|
|
33
|
+
@code = code
|
|
28
34
|
end
|
|
29
35
|
end
|
|
30
36
|
|
|
@@ -53,10 +59,16 @@ module LabelZoom
|
|
|
53
59
|
# HTTP 413. The body exceeded the tier's limit -- 1 MB on the anonymous free tier.
|
|
54
60
|
class PayloadTooLargeError < APIError; end
|
|
55
61
|
|
|
62
|
+
# HTTP 422. The request is well formed but cannot be carried out. Print returns it with a
|
|
63
|
+
# {#code}: +agent_update_required+ when the print agent serving the printer is too old for
|
|
64
|
+
# the request, +idempotency_key_reused+ when the key was already used for a different
|
|
65
|
+
# request, and for a template print whose records are missing fields.
|
|
66
|
+
class UnprocessableError < APIError; end
|
|
67
|
+
|
|
56
68
|
# HTTP 429. Too many requests.
|
|
57
69
|
class RateLimitedError < APIError
|
|
58
70
|
# @return [Float, nil] Retry-After in seconds, when the server sent one. The client
|
|
59
|
-
# already
|
|
71
|
+
# already honors this during its own retries; this exposes it for callers doing
|
|
60
72
|
# their own.
|
|
61
73
|
attr_reader :retry_after_seconds
|
|
62
74
|
|
|
@@ -66,6 +78,14 @@ module LabelZoom
|
|
|
66
78
|
end
|
|
67
79
|
end
|
|
68
80
|
|
|
81
|
+
# HTTP 429 with code +daily_job_limit_reached+: the account's daily print job limit is used
|
|
82
|
+
# up. A kind of {RateLimitedError}, so a handler for that still catches it.
|
|
83
|
+
#
|
|
84
|
+
# Never retried automatically, whatever +Retry-After+ says: the limit resets at 00:00 UTC,
|
|
85
|
+
# so {#retry_after_seconds} is hours away. Call +client.print_quota+ to check what remains
|
|
86
|
+
# before printing.
|
|
87
|
+
class PrintQuotaExceededError < RateLimitedError; end
|
|
88
|
+
|
|
69
89
|
# HTTP 5xx. Retried automatically before surfacing.
|
|
70
90
|
class ServerError < APIError; end
|
|
71
91
|
|
|
@@ -76,7 +96,7 @@ module LabelZoom
|
|
|
76
96
|
#
|
|
77
97
|
# Deliberately an ArgumentError and *not* an {APIError}: this is a bug in the calling
|
|
78
98
|
# code, not a server response. It carries no status, it is never retried, and a caller
|
|
79
|
-
# rescuing {APIError} to implement fallback
|
|
99
|
+
# rescuing {APIError} to implement fallback behavior should not swallow it.
|
|
80
100
|
#
|
|
81
101
|
# This is also what makes conformance/skips/ruby.json's stated reason literally true:
|
|
82
102
|
# Ruby has no compile step, so a source-only format passed as a target is caught here.
|
data/lib/labelzoom/formats.rb
CHANGED
|
@@ -10,15 +10,29 @@ module LabelZoom
|
|
|
10
10
|
# Every accepted source, in the contract's order. +:jpg+ is an input spelling that
|
|
11
11
|
# normalizes to +:jpeg+ on the wire; +:url+ tells the server to go fetch a document
|
|
12
12
|
# rather than naming a format.
|
|
13
|
-
|
|
13
|
+
#
|
|
14
|
+
# +:esclabel+ is Epson ColorWorks ESC/Label, a dialect of ZPL; +:fingerprint+ is
|
|
15
|
+
# Honeywell/Intermec Fingerprint and Direct Protocol; +:ezpl+ is GoDEX EZPL; +:cpcl+ is
|
|
16
|
+
# Zebra CPCL; +:tpcl+ is Toshiba TEC TPCL. +:nlbl+ and +:lbl+ are NiceLabel design files and
|
|
17
|
+
# +:btw+ is a BarTender one: send their bytes. +:dymo+ is a DYMO Label design file (XML).
|
|
18
|
+
SOURCE_FORMATS = %i[
|
|
19
|
+
zpl epl ipl tspl dpl sbpl
|
|
20
|
+
esclabel fingerprint ezpl cpcl tpcl nlbl lbl btw dymo
|
|
21
|
+
xml json pdf png bmp gif jpeg jpg url
|
|
22
|
+
].freeze
|
|
14
23
|
|
|
15
24
|
# Every accepted target. There is no +:url+ -- it is a fetch instruction, not an output
|
|
16
25
|
# format -- and no +:jpg+, which is a source-side spelling only.
|
|
17
26
|
#
|
|
18
27
|
# The printer languages round-trip: +:epl+, +:tspl+ and +:dpl+ became targets in
|
|
19
28
|
# contract 1.1.0, when the printer-language writers shipped, and +:ipl+ and +:sbpl+
|
|
20
|
-
# joined them in 1.2.0 with the Intermec and SATO adapters.
|
|
21
|
-
|
|
29
|
+
# joined them in 1.2.0 with the Intermec and SATO adapters. +:cpcl+ joined in 2.1.0; it
|
|
30
|
+
# writes graphics as hex, so its output is plain text.
|
|
31
|
+
TARGET_FORMATS = %i[zpl epl ipl tspl dpl sbpl cpcl xml json pdf png bmp gif jpeg].freeze
|
|
32
|
+
|
|
33
|
+
# The sources print takes (contract P2): every source but +:url+, because print does not
|
|
34
|
+
# fetch. LabelZoom converts each one to the printer's language, design files included.
|
|
35
|
+
PRINT_SOURCE_FORMATS = (SOURCE_FORMATS - %i[url]).freeze
|
|
22
36
|
|
|
23
37
|
MEDIA_TYPES = {
|
|
24
38
|
zpl: "text/plain",
|
|
@@ -27,6 +41,15 @@ module LabelZoom
|
|
|
27
41
|
tspl: "text/plain",
|
|
28
42
|
dpl: "text/plain",
|
|
29
43
|
sbpl: "text/plain",
|
|
44
|
+
esclabel: "text/plain",
|
|
45
|
+
fingerprint: "text/plain",
|
|
46
|
+
ezpl: "text/plain",
|
|
47
|
+
cpcl: "text/plain",
|
|
48
|
+
tpcl: "text/plain",
|
|
49
|
+
nlbl: "application/octet-stream",
|
|
50
|
+
lbl: "application/octet-stream",
|
|
51
|
+
btw: "application/octet-stream",
|
|
52
|
+
dymo: "application/xml",
|
|
30
53
|
xml: "application/xml",
|
|
31
54
|
json: "application/json",
|
|
32
55
|
pdf: "application/pdf",
|
|
@@ -39,7 +62,7 @@ module LabelZoom
|
|
|
39
62
|
url: "text/plain"
|
|
40
63
|
}.freeze
|
|
41
64
|
|
|
42
|
-
#
|
|
65
|
+
# Color reduction. Server default GRAYSCALE.
|
|
43
66
|
COLOR_MODES = %w[BW GRAYSCALE COLOR].freeze
|
|
44
67
|
|
|
45
68
|
# How a PDF source is interpreted. Server default IMAGE.
|
|
@@ -74,6 +97,18 @@ module LabelZoom
|
|
|
74
97
|
"produces. Expected one of: #{TARGET_FORMATS.join(", ")}.")
|
|
75
98
|
end
|
|
76
99
|
|
|
100
|
+
# @return [Symbol] the validated print source.
|
|
101
|
+
# @raise [ValidationError] named +source+, if it is not a source format at all, or if it is
|
|
102
|
+
# +:url+, which print cannot take.
|
|
103
|
+
def print_source!(format)
|
|
104
|
+
symbol = source!(format)
|
|
105
|
+
return symbol if PRINT_SOURCE_FORMATS.include?(symbol)
|
|
106
|
+
|
|
107
|
+
raise ValidationError.new("source",
|
|
108
|
+
"A URL can't be printed: print doesn't fetch. Download the " \
|
|
109
|
+
"document and print its bytes.")
|
|
110
|
+
end
|
|
111
|
+
|
|
77
112
|
# The path segment for a source. +:jpg+ normalizes to "jpeg" (rule A2).
|
|
78
113
|
def source_token(format) = format == :jpg ? "jpeg" : format.to_s
|
|
79
114
|
|
|
@@ -86,4 +121,5 @@ module LabelZoom
|
|
|
86
121
|
|
|
87
122
|
SOURCE_FORMATS = Formats::SOURCE_FORMATS
|
|
88
123
|
TARGET_FORMATS = Formats::TARGET_FORMATS
|
|
124
|
+
PRINT_SOURCE_FORMATS = Formats::PRINT_SOURCE_FORMATS
|
|
89
125
|
end
|
data/lib/labelzoom/options.rb
CHANGED
|
@@ -29,24 +29,64 @@ module LabelZoom
|
|
|
29
29
|
position: { x: "x", y: "y" },
|
|
30
30
|
label: { width: "width", height: "height" },
|
|
31
31
|
pdf: { conversion_mode: "conversionMode", page_number: "pageNumber" },
|
|
32
|
-
zpl: {
|
|
32
|
+
zpl: {
|
|
33
|
+
commands_to_ignore: "commandsToIgnore",
|
|
34
|
+
image_compression: "imageCompression",
|
|
35
|
+
collapse_copies: "collapseCopies"
|
|
36
|
+
},
|
|
37
|
+
# Image or PDF to ZPL, IMAGE mode: labels side by side in each printed row. gap is in INCHES.
|
|
38
|
+
layout: { across: "across", gap: "gap", fill: "fill" },
|
|
39
|
+
# Image or PDF to ZPL, IMAGE mode: cuts each page into a grid of labels. Every length is in
|
|
40
|
+
# INCHES on the page as displayed; omit width and height to divide the page equally.
|
|
41
|
+
split: {
|
|
42
|
+
rows: "rows",
|
|
43
|
+
columns: "columns",
|
|
44
|
+
width: "width",
|
|
45
|
+
height: "height",
|
|
46
|
+
left: "left",
|
|
47
|
+
top: "top",
|
|
48
|
+
column_gap: "columnGap",
|
|
49
|
+
row_gap: "rowGap",
|
|
50
|
+
skip_blank: "skipBlank"
|
|
51
|
+
}
|
|
33
52
|
}.freeze
|
|
34
53
|
|
|
35
54
|
SCALAR_KEYS = {
|
|
36
|
-
|
|
55
|
+
source_dpi: "sourceDpi",
|
|
56
|
+
target_dpi: "targetDpi",
|
|
37
57
|
rotation: "rotation",
|
|
38
58
|
scaling: "scaling",
|
|
39
59
|
color_mode: "colorMode",
|
|
40
60
|
darkness: "darkness",
|
|
41
61
|
watermark: "watermark",
|
|
42
|
-
dialect: "dialect"
|
|
62
|
+
dialect: "dialect",
|
|
63
|
+
# 0-BASED. For image or PDF to ZPL it counts the labels after split, page by page.
|
|
64
|
+
label_index: "labelIndex"
|
|
43
65
|
}.freeze
|
|
44
66
|
|
|
67
|
+
# The options that change how the source document is read (contract section 1).
|
|
68
|
+
# +color_mode+ and +darkness+ are here because they also reduce an image or PDF source to
|
|
69
|
+
# black and white. +extra+ stays available as the forward-compatibility hatch.
|
|
70
|
+
SOURCE_KEYS = %i[
|
|
71
|
+
source_dpi label label_index data pdf split scaling position darkness color_mode zpl extra
|
|
72
|
+
].freeze
|
|
73
|
+
|
|
74
|
+
# What a print takes: every source option, plus +rotation+, the one target option a printer
|
|
75
|
+
# target offers. Rotation turns the finished label whatever the output language; every other
|
|
76
|
+
# target option depends on a language the request doesn't name, because the printer's
|
|
77
|
+
# configuration picks it.
|
|
78
|
+
PRINT_KEYS = (SOURCE_KEYS + %i[rotation]).freeze
|
|
79
|
+
|
|
80
|
+
# +zpl+ mixes the two stages: +commands_to_ignore+ acts on the ZPL being read, and the rest
|
|
81
|
+
# on ZPL being written.
|
|
82
|
+
SOURCE_ZPL_KEYS = %i[commands_to_ignore].freeze
|
|
83
|
+
|
|
45
84
|
module_function
|
|
46
85
|
|
|
47
86
|
# @return [String, nil] the params JSON, or nil when nothing was set -- in which case
|
|
48
87
|
# no query parameter is emitted at all (rule C7).
|
|
49
88
|
def serialize(**options)
|
|
89
|
+
reject_unknown_keys(options)
|
|
50
90
|
params = {}
|
|
51
91
|
|
|
52
92
|
SCALAR_KEYS.each do |key, wire_key|
|
|
@@ -72,6 +112,78 @@ module LabelZoom
|
|
|
72
112
|
params.empty? ? nil : JSON.generate(params)
|
|
73
113
|
end
|
|
74
114
|
|
|
115
|
+
# {serialize}, restricted to what a print takes ({PRINT_KEYS}). One serialization path:
|
|
116
|
+
# this only rejects what print cannot take, then defers, so +rotation+ is validated and
|
|
117
|
+
# written exactly as for convert.
|
|
118
|
+
#
|
|
119
|
+
# @return [String, nil] the params JSON, or nil when no option was set -- in which case
|
|
120
|
+
# print sends no +params+ at all, so the server sends the document as is.
|
|
121
|
+
def serialize_print(**options)
|
|
122
|
+
base64_text = options.delete(:base64_text)
|
|
123
|
+
if base64_text
|
|
124
|
+
# Print reads the body as the format's own bytes (contract P2).
|
|
125
|
+
raise ValidationError.new("source",
|
|
126
|
+
"Print does not accept base64 text; send the document's bytes.")
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
options.each do |key, value|
|
|
130
|
+
next if PRINT_KEYS.include?(key) || UNSET.equal?(value)
|
|
131
|
+
|
|
132
|
+
raise_not_a_print_option(key)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
zpl = options.fetch(:zpl, UNSET)
|
|
136
|
+
if zpl.is_a?(Hash)
|
|
137
|
+
rejected = zpl.keys.map(&:to_sym) - SOURCE_ZPL_KEYS
|
|
138
|
+
unless rejected.empty?
|
|
139
|
+
raise ValidationError.new("zpl",
|
|
140
|
+
"zpl[#{rejected.first.inspect}] is not an option print " \
|
|
141
|
+
"takes; only #{SOURCE_ZPL_KEYS.join(", ")} acts on the " \
|
|
142
|
+
"document being read.")
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
serialize(**options)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Every keyword {serialize} reads. +extra+ is the hatch for a parameter the SDK doesn't
|
|
150
|
+
# model yet.
|
|
151
|
+
KNOWN_KEYS = (SCALAR_KEYS.keys + NESTED_KEYS.keys + %i[data extra]).freeze
|
|
152
|
+
|
|
153
|
+
# A misspelled top-level keyword raises, as a misspelled nested key does. The server
|
|
154
|
+
# ignores unknown parameters, so a silent drop would turn `taget_dpi: 300` into a label at
|
|
155
|
+
# the default resolution with no error.
|
|
156
|
+
def reject_unknown_keys(options)
|
|
157
|
+
options.each_key do |key|
|
|
158
|
+
next if KNOWN_KEYS.include?(key)
|
|
159
|
+
|
|
160
|
+
if key == :dpi
|
|
161
|
+
# 1.x took dpi:. 2.0 names the side it applies to (contract C8).
|
|
162
|
+
raise ValidationError.new("dpi",
|
|
163
|
+
"dpi: was split in 2.0: use source_dpi: for the resolution " \
|
|
164
|
+
"the source was made for, or target_dpi: for the output's.")
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
raise ValidationError.new(key.to_s,
|
|
168
|
+
"#{key} is not a recognized option. Expected one of: " \
|
|
169
|
+
"#{KNOWN_KEYS.join(", ")}. To send a parameter the SDK " \
|
|
170
|
+
"doesn't model, use extra:.")
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def raise_not_a_print_option(key)
|
|
175
|
+
if SCALAR_KEYS.key?(key) || NESTED_KEYS.key?(key)
|
|
176
|
+
raise ValidationError.new(SCALAR_KEYS.fetch(key, key.to_s),
|
|
177
|
+
"#{key} is a target option a printer doesn't take: the " \
|
|
178
|
+
"printer's configuration picks the output language. Of the " \
|
|
179
|
+
"target options, print takes only rotation.")
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
raise ValidationError.new(key.to_s,
|
|
183
|
+
"#{key} is not a recognized option. Expected one of: " \
|
|
184
|
+
"#{PRINT_KEYS.join(", ")}.")
|
|
185
|
+
end
|
|
186
|
+
|
|
75
187
|
def validate_scalar(key, value)
|
|
76
188
|
case key
|
|
77
189
|
when :rotation
|
|
@@ -80,6 +192,13 @@ module LabelZoom
|
|
|
80
192
|
raise ValidationError.new("rotation",
|
|
81
193
|
"Rotation must be a multiple of 90 degrees, but was #{value}.")
|
|
82
194
|
end
|
|
195
|
+
when :source_dpi, :target_dpi
|
|
196
|
+
# Contract C8: only a positive resolution is checked locally.
|
|
197
|
+
unless value.is_a?(Integer) && value.positive?
|
|
198
|
+
raise ValidationError.new(key.to_s,
|
|
199
|
+
"#{key} must be a positive whole number, " \
|
|
200
|
+
"but was #{value.inspect}.")
|
|
201
|
+
end
|
|
83
202
|
when :darkness
|
|
84
203
|
unless value.is_a?(Numeric) && value.between?(0, 100)
|
|
85
204
|
raise ValidationError.new("darkness",
|