calmlens 0.27.5 → 0.28.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c66ffbf6002c2f2f834daa2bf8c1793b4f871f957343cbeb7856cff99ce2a925
4
- data.tar.gz: b0acc8427937664d03957cde562ccc07f68070a97e8681a5f2dfe6d84b078803
3
+ metadata.gz: 0f85c3f503981a9430e9032ae390a3f6a93fc3ea3cd25e6dc55b431778f655a5
4
+ data.tar.gz: 4bbafa1e0d09344f9617f79f4bb4617717c569d3aa8d9dbec72261b10bab727c
5
5
  SHA512:
6
- metadata.gz: e0b25c0469d47ec97d783cad2529f83ef8a601c6617e4d9e8efa6e9630bf14759a209eabacc81fd6555d5c57e5cd4dbf7267aba0df87bbb45eef9e0d014d090f
7
- data.tar.gz: b969adfee29aea29aa2cc800d25c3b7f16df42a6077fc3d75d0c8d6af235db7f02e3862f1dffcd00124c457e631af26e8960bc45dc204206747b2375eebbd23f
6
+ metadata.gz: 7ee8f7cbc21318a692173523cbce471fccd27927cf504871f8b7fc00747c4bafd99d64e8e4c189af0739bc65f9f564855c09e10d135bb7af101abfcb1fb6dd75
7
+ data.tar.gz: bc87dccf6bc1e39428cc8b8dd1363e6a773a8f58428db114846ad54fc3d0431c7c9ac6005576437b1e08bec3c5e95baa4cf1c86218822413014f33c6b03d954d
data/lib/calmlens/cdn.rb CHANGED
@@ -76,16 +76,15 @@ module CalmLens
76
76
  end
77
77
 
78
78
  # Signs a private asset's URL on your server, so browsers and apps can load it without an API key
79
- # until it expires. Every resource is a path beneath it, as beneath a public asset URL; `original`
80
- # only when signed with `original: true`. With `resource`, returns that resource's URL beneath the
81
- # grant; lenses, transforms and viewer claims are appended as {#get_asset_url} appends them and
79
+ # until it expires. With `resource`, it is signed for that resource and ends in it; only a URL
80
+ # signed for `original` serves the exact upload, and any other serves every other resource beneath
81
+ # its grant. Lenses, transforms and viewer claims are appended as {#get_asset_url} appends them and
82
82
  # aren't part of the signature.
83
83
  # @option options [String] :asset_id give it or `external_id`, not both
84
84
  # @option options [String] :external_id
85
85
  # @option options [String] :project_id the client's by default
86
86
  # @option options [Integer] :expires_in whole seconds from 1 to 86400; 900 by default
87
- # @option options [Boolean] :original whether the URL also serves the exact upload (`original`); false by default
88
- # @option options [String] :resource see {#get_asset_url}
87
+ # @option options [String] :resource the resource the URL is signed for and ends in; see {#get_asset_url}
89
88
  # @option options [String] :lens
90
89
  # @option options [String, Hash] :transform
91
90
  # @option options [Hash] :viewer_claims
@@ -96,13 +95,13 @@ module CalmLens
96
95
  project = Internal.segment(api.fetch('projectId', @session.project_id))
97
96
  body = api.slice('assetId', 'externalId')
98
97
  body['expiresIn'] = api.fetch('expiresIn', DEFAULT_SIGNED_URL_EXPIRES_IN)
99
- body['original'] = api.fetch('original', false)
98
+ body['resource'] = api['resource'] if api.key?('resource')
100
99
  signed = request('POST', "/projects/#{project}/signed-asset-urls", body: body, request_options: request)
101
100
  unless signed.is_a?(Hash) && signed['url'].is_a?(String) && !signed['url'].empty? && signed['expiresAt'].is_a?(Integer)
102
101
  raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE, 'The API returned no signed asset URL')
103
102
  end
104
103
 
105
- build(SignedAssetUrl, signed.merge('url' => append_location(signed['url'], api)))
104
+ build(SignedAssetUrl, signed.merge('url' => append_signed_location(signed['url'], api)))
106
105
  end
107
106
  end
108
107
 
@@ -110,7 +109,7 @@ module CalmLens
110
109
  # size, rendered file, preview and stream, and whether the viewer its claims describe can see it
111
110
  # now (`availability`: `available`, `age-restricted` or `unavailable`). It sends no API key, as a
112
111
  # browser would, so a private asset's info needs a signed URL.
113
- # @param url [String] an asset URL from {#get_asset_url} or {#sign_asset_url}, without a resource
112
+ # @param url [String] an asset URL from {#get_asset_url} or {#sign_asset_url}, or a resource URL beneath one
114
113
  # @param viewer_claims [Hash, nil] the viewer's claims, as for {#get_asset_url}; the URL's own
115
114
  # `viewerClaims` when omitted
116
115
  # @return [AssetInfo]
@@ -203,13 +202,24 @@ module CalmLens
203
202
  "#{url}#{viewer_claims_query(api['viewerClaims'])}"
204
203
  end
205
204
 
205
+ # The lens, transform and viewer claims added to a URL the API signed for `api['resource']`,
206
+ # which already ends in that resource.
207
+ def append_signed_location(url, api)
208
+ resource_path = api['resource'] ? "/#{RESOURCE_PATHS.fetch(api['resource'])}" : ''
209
+ unless url.end_with?(resource_path)
210
+ raise InvalidResponseError.new(SdkErrorCodes::INVALID_RESPONSE,
211
+ "The signed asset URL doesn't end in the resource it was signed for")
212
+ end
213
+
214
+ url + append_location('', api)[resource_path.length..]
215
+ end
216
+
206
217
  # Checks sign_asset_url's own options as the API does, then the location, before anything is sent.
207
218
  def check_signing(api)
208
219
  expires = api.fetch('expiresIn', DEFAULT_SIGNED_URL_EXPIRES_IN)
209
220
  unless expires.is_a?(Integer) && expires.between?(1, MAX_SIGNED_URL_EXPIRES_IN)
210
221
  raise Internal.invalid("expires_in must be a whole number of seconds from 1 to #{MAX_SIGNED_URL_EXPIRES_IN}")
211
222
  end
212
- raise Internal.invalid('original must be true or false') unless [true, false].include?(api.fetch('original', false))
213
223
 
214
224
  asset_segment(api)
215
225
  append_location('', api)
@@ -243,7 +253,17 @@ module CalmLens
243
253
  rescue JSON::ParserError
244
254
  raise Internal.invalid("The asset URL's viewerClaims are not JSON")
245
255
  end
246
- [path.sub(%r{/+\z}, ''), claims]
256
+ [asset_url_of(path), claims]
257
+ end
258
+
259
+ # The asset URL of a path: an asset URL (`…/assets/{projectId}/{asset}`) as it is, and a resource
260
+ # URL beneath one, such as a URL signed for `original`, cut back to the asset URL its resources
261
+ # are paths beneath.
262
+ def asset_url_of(path)
263
+ path = path.sub(%r{/+\z}, '')
264
+ parts = path.split('/', -1)
265
+ assets = parts.rindex('assets')
266
+ assets && assets >= 3 && parts.length > assets + 3 ? parts[0, assets + 3].join('/') : path
247
267
  end
248
268
 
249
269
  def asset_info?(info)
@@ -44,6 +44,7 @@ module CalmLens
44
44
  INVALID_IMAGE = 'image/invalid'
45
45
  IMAGE_TOO_LARGE = 'image/too-large'
46
46
  FREE_UPLOADS_EXHAUSTED = 'usage/free-uploads-exhausted'
47
+ WEBSITE_BILLING_REQUIRED = 'payment/billing-required'
47
48
  UPLOADS_PAUSED = 'usage/uploads-paused'
48
49
  UNSUPPORTED_UPLOAD_TYPE = 'upload/unsupported-type'
49
50
  INVALID_UPLOAD_PAYLOAD = 'upload-payload/invalid'
@@ -83,6 +84,7 @@ module CalmLens
83
84
  HASH_LIST_ENTRY_NOT_FOUND = 'hash-list-entry/not-found'
84
85
  HASH_LIST_LIMIT_REACHED = 'hash-list/limit-reached'
85
86
  HASH_LIST_ENTRY_LIMIT_REACHED = 'hash-list-entry/limit-reached'
87
+ HASH_LIST_ENTRY_QUALITY_TOO_LOW = 'hash-list-entry/quality-too-low'
86
88
  HASH_LIST_ASSET_NOT_HASHED = 'hash-list/asset-not-hashed'
87
89
  POLICY_NOT_FOUND = 'policy/not-found'
88
90
  POLICY_REVISION_CONFLICT = 'policy/revision-conflict'
@@ -164,6 +166,7 @@ module CalmLens
164
166
  'image/invalid' => 422,
165
167
  'image/too-large' => 422,
166
168
  'usage/free-uploads-exhausted' => 403,
169
+ 'payment/billing-required' => 409,
167
170
  'usage/uploads-paused' => 402,
168
171
  'upload/unsupported-type' => 415,
169
172
  'upload-payload/invalid' => 400,
@@ -203,6 +206,7 @@ module CalmLens
203
206
  'hash-list-entry/not-found' => 404,
204
207
  'hash-list/limit-reached' => 409,
205
208
  'hash-list-entry/limit-reached' => 409,
209
+ 'hash-list-entry/quality-too-low' => 422,
206
210
  'hash-list/asset-not-hashed' => 409,
207
211
  'policy/not-found' => 404,
208
212
  'policy/revision-conflict' => 409,
@@ -110,6 +110,20 @@ module CalmLens
110
110
  rest.empty? || value.nil? ? value : value.dig(*rest)
111
111
  end
112
112
 
113
+ # The value of a field, as Hash#fetch reads one: a field the API didn't send returns the block's
114
+ # value or `default`, or raises KeyError. A field sent as null returns nil.
115
+ # asset.fetch(:description, '') # => '' when the API sent no description
116
+ def fetch(key, *default)
117
+ raise ArgumentError, "wrong number of arguments (given #{default.size + 1}, expected 1..2)" if default.size > 1
118
+
119
+ name = name_of(key)
120
+ return @values[name] if @values.key?(name)
121
+ return yield(key) if block_given?
122
+ return default.first unless default.empty?
123
+
124
+ raise KeyError.new("key not found: #{key.inspect}", receiver: self, key: key)
125
+ end
126
+
113
127
  # The values of several fields, by reader name or API key.
114
128
  def values_at(*keys) = keys.map { |key| self[key] }
115
129
 
@@ -31,7 +31,7 @@ module CalmLens
31
31
  'assets.update' => %w[assetId description externalId externalUrl metadata name tags visibility].freeze,
32
32
  'assets.uploadPart' => %w[assetId part wait].freeze,
33
33
  'cdn.signAssetUrl' => %w[
34
- assetId expiresIn externalId lens original projectId resource transform viewerClaims
34
+ assetId expiresIn externalId lens projectId resource resource transform viewerClaims
35
35
  ].freeze,
36
36
  'ensureLens' => %w[active description identifier name transform type].freeze,
37
37
  'ensureLenses' => %w[lenses].freeze,
@@ -56,6 +56,11 @@ module CalmLens
56
56
  DEFAULT_PAGE_SIZE = 50
57
57
  MAX_PAGE_SIZE = 100
58
58
  REVIEW_DECISIONS = %w[allowed limited age-restricted blocked purged].freeze
59
+ # Where the API's signed URL for each resource ends.
60
+ SIGNED_RESOURCE_PATHS = {
61
+ 'original' => 'original', 'rendered' => 'rendered', 'preview' => 'preview',
62
+ 'hls' => 'hls/index.m3u8', 'embed' => 'embed', 'placeholder' => 'placeholder', 'info' => 'info'
63
+ }.freeze
59
64
  # The moderation status each `asset.<status>` event announces.
60
65
  ANNOUNCED_STATUSES = REVIEW_DECISIONS.to_h { |status| ["asset.#{status}", status] }.freeze
61
66
  MAX_DECISION_NOTE_LENGTH = 1499
@@ -1075,8 +1080,9 @@ module CalmLens
1075
1080
  # Without `moderate`, queued work stays pending until completed, which allows it.
1076
1081
  def default_moderation(trigger, queued) = queued && trigger != 'complete' ? 'pending' : 'allowed'
1077
1082
 
1078
- # Applies `decision` to `asset` with its report. The mock reads no text, QR codes, people or
1079
- # faces in an image, so a decided image reports that the features its upload ran found nothing:
1083
+ # Applies `decision` to `asset` with its report. The mock reads nothing in an image, so a
1084
+ # decided image reports what the decision supplies ({MockDecision#with_ocr},
1085
+ # {MockDecision#with_link_detection}) and no people or faces, for the features its upload ran:
1080
1086
  # OCR and person and face detection when turned on, link detection unless turned off.
1081
1087
  def decided(asset, decision)
1082
1088
  apply_outcome(asset, decision.status, 'policy', decision.report(@now.call))
@@ -1086,9 +1092,15 @@ module CalmLens
1086
1092
  processing = @processing_options[asset['id']]
1087
1093
  features = processing.is_a?(Hash) && processing['features'].is_a?(Hash) ? processing['features'] : {}
1088
1094
  setting = ->(name) { features[name].is_a?(Hash) ? features[name]['enabled'] : nil }
1089
- classification['ocr'] = { 'status' => 'evaluated', 'textRegions' => [] } if setting.call('ocr') == true
1095
+ if setting.call('ocr') == true
1096
+ ocr = decision.ocr_findings || { 'text' => nil, 'textRegions' => [] }
1097
+ classification['ocr'] = { 'status' => 'evaluated', 'textRegions' => ocr['textRegions'] }
1098
+ if !ocr['text'].nil? && asset['content']['status'] == 'stored'
1099
+ asset['content']['extractedText'] = { 'type' => 'string', 'content' => ocr['text'] }
1100
+ end
1101
+ end
1090
1102
  unless setting.call('linkDetection') == false
1091
- classification['linkDetection'] = { 'status' => 'evaluated', 'qrCodes' => [], 'links' => [] }
1103
+ classification['linkDetection'] = { 'status' => 'evaluated' }.merge(decision.link_findings || { 'qrCodes' => [], 'links' => [] })
1092
1104
  end
1093
1105
  { 'personDetection' => 'people', 'faceDetection' => 'faces' }.each do |feature, list|
1094
1106
  classification[feature] = { 'status' => 'evaluated', list => [] } if setting.call(feature) == true
@@ -1292,11 +1304,14 @@ module CalmLens
1292
1304
  end
1293
1305
 
1294
1306
  # Signs an asset URL like the API (`POST /projects/:projectId/signed-asset-urls`): a grant to one
1295
- # asset, by ID or external ID, until it expires, serving the original only when asked. Only the
1296
- # mock's CDN accepts the grant.
1307
+ # asset, by ID or external ID, until it expires, ending in the resource it was signed for and
1308
+ # serving the original only when signed for it. Only the mock's CDN accepts the grant.
1297
1309
  def sign_asset_url(json)
1298
- # Like the API's schema, none of these fields takes null.
1299
- %w[assetId externalId expiresIn original].each do |key|
1310
+ # Like the API's schema, it takes only these fields, and none of them takes null.
1311
+ fields = %w[assetId externalId expiresIn resource]
1312
+ unknown = json.keys.find { |key| !fields.include?(key) }
1313
+ invalid!('validation/unknown-field', unknown) if unknown
1314
+ fields.each do |key|
1300
1315
  invalid!('validation/invalid-type', key) if json.key?(key) && json[key].nil?
1301
1316
  end
1302
1317
  if json.key?('assetId') == json.key?('externalId')
@@ -1308,8 +1323,8 @@ module CalmLens
1308
1323
  invalid!('validation/invalid-type', 'expiresIn') unless expires.is_a?(Integer) || (expires.is_a?(Float) && expires == expires.floor)
1309
1324
  invalid!('validation/too-small', 'expiresIn') if expires < 1
1310
1325
  invalid!('validation/too-big', 'expiresIn') if expires > CDN::MAX_SIGNED_URL_EXPIRES_IN
1311
- original = json.fetch('original', false)
1312
- invalid!('validation/invalid-type', 'original') unless [true, false].include?(original)
1326
+ resource = json['resource']
1327
+ invalid!('validation/invalid-value', 'resource') unless resource.nil? || SIGNED_RESOURCE_PATHS.key?(resource)
1313
1328
 
1314
1329
  item = if json.key?('externalId')
1315
1330
  project_assets.find { |asset| asset['externalId'] == json['externalId'] }
@@ -1320,7 +1335,9 @@ module CalmLens
1320
1335
  fail!(ErrorCodes::ASSET_HELD) if item['content']['safetyHold']
1321
1336
 
1322
1337
  expires_at = @now.call + (expires.to_i * 1000)
1323
- { 'url' => "#{@cdn_base_url}/assets/#{Internal.component(@project_id)}/#{MockGrant.encode(item['id'], original, expires_at)}",
1338
+ path = resource ? "/#{SIGNED_RESOURCE_PATHS.fetch(resource)}" : ''
1339
+ grant = MockGrant.encode(item['id'], resource == 'original', expires_at)
1340
+ { 'url' => "#{@cdn_base_url}/assets/#{Internal.component(@project_id)}/#{grant}#{path}",
1324
1341
  'expiresAt' => expires_at }
1325
1342
  end
1326
1343
 
@@ -1775,7 +1792,7 @@ module CalmLens
1775
1792
  return not_available if item['content']['safetyHold']
1776
1793
  return placeholder(method, item, authorised) if resource == 'placeholder'
1777
1794
 
1778
- deliver(method, item, resource, params, selected ? options || {} : nil, authorised)
1795
+ deliver(method, item, resource, params, selected ? options || {} : nil, authorised, grant)
1779
1796
  end
1780
1797
 
1781
1798
  # What a grant doesn't cover, or, like the CDN, removed content for anyone (isAssetContentNotKept)
@@ -1862,13 +1879,13 @@ module CalmLens
1862
1879
  # Serves a found asset's resource after the delivery, age and access checks, then whether it
1863
1880
  # has the resource and takes the selector, then the transform options' schema check.
1864
1881
  # `selector` is the selector's options (empty for a lens alone), or nil without one.
1865
- def deliver(method, item, resource, params, selector, authorised)
1882
+ def deliver(method, item, resource, params, selector, authorised, grant)
1866
1883
  stored = @state.content[item['id']]
1867
1884
  refused = refuse_delivery(item, resource, stored, params, authorised)
1868
1885
  return refused if refused
1869
1886
 
1870
1887
  restricted = item['visibility'] != 'public'
1871
- return embed(method, item, restricted, params) if resource == 'embed'
1888
+ return embed(method, item) if resource == 'embed'
1872
1889
 
1873
1890
  # Then whether the asset has the resource, and whether it is a still image that takes a lens
1874
1891
  # or transform: the preview always is, the rendered file only when it is an image.
@@ -1886,8 +1903,9 @@ module CalmLens
1886
1903
  bytes, type = resource_body(item, resource, stored)
1887
1904
  return not_available unless bytes
1888
1905
 
1889
- immutable = still || (resource == 'original' && item['type'] == 'image')
1890
- cdn_response(method, bytes, viewer_delivery_headers(item, type, restricted, immutable, params))
1906
+ image_response = still || (resource == 'original' && item['type'] == 'image')
1907
+ cache = delivery_cache_control(restricted, grant, params)
1908
+ cdn_response(method, bytes, delivery_headers(item, type, image_response, cache))
1891
1909
  end
1892
1910
 
1893
1911
  # The delivery checks, which refuse everyone, then age and access, as an error response, or nil.
@@ -1926,19 +1944,17 @@ module CalmLens
1926
1944
  JSON.parse(params.fetch('viewerClaims', '{}'))['ageConfirmed'] == true
1927
1945
  end
1928
1946
 
1929
- def viewer_delivery_headers(item, type, restricted, immutable, params)
1930
- headers = delivery_headers(item, type, restricted, immutable)
1931
- headers['Cache-Control'] = 'private, no-store' if params.key?('viewerClaims')
1932
- headers
1947
+ def delivery_cache_control(restricted, grant, params)
1948
+ return 'private, no-store' if params.key?('viewerClaims')
1949
+ return 'private, no-cache' if restricted && !grant
1950
+
1951
+ max_age = grant ? ((grant[:expires_at] - @now.call) / 1000).clamp(0, 86_400) : 86_400
1952
+ "#{restricted ? 'private' : 'public'}, max-age=#{max_age}, must-revalidate"
1933
1953
  end
1934
1954
 
1935
- # The embed page, which shows any asset that may be delivered, as its viewer for the asset's
1936
- # type or a notice that the type has none; cached like other non-image content.
1937
- def embed(method, item, restricted, params)
1938
- cache = if params.key?('viewerClaims') then 'private, no-store'
1939
- else "#{restricted ? 'private' : 'public'}, max-age=3600"
1940
- end
1941
- cdn_response(method, EMBED_HTML, { 'content-type' => 'text/html; charset=utf-8', 'cache-control' => cache,
1955
+ def embed(method, item)
1956
+ cdn_response(method, EMBED_HTML, { 'content-type' => 'text/html; charset=utf-8',
1957
+ 'cache-control' => 'private, no-store',
1942
1958
  'cache-tag' => "asset-#{item['id']}", 'x-content-type-options' => 'nosniff' })
1943
1959
  end
1944
1960
 
@@ -1963,13 +1979,10 @@ module CalmLens
1963
1979
  'cache-tag' => "asset-#{item['id']}", 'etag' => "\"#{thumbhash}\"")
1964
1980
  end
1965
1981
 
1966
- # Like the CDN: a still image's bytes are immutable for a year, other content is kept for an
1967
- # hour, by shared caches only when delivery is public. Active content is served as a download.
1968
- def delivery_headers(item, type, restricted, immutable)
1969
- lifetime = immutable ? 'max-age=31536000, immutable' : 'max-age=3600'
1970
- headers = { 'content-type' => type, 'cache-control' => "#{restricted ? 'private' : 'public'}, #{lifetime}",
1971
- 'cache-tag' => "asset-#{item['id']}" }
1972
- headers.merge!('etag' => "\"#{item['id']}\"", 'expires' => Time.at((@now.call / 1000) + 31_536_000).utc.httpdate) if immutable
1982
+ # Active content is served as a download.
1983
+ def delivery_headers(item, type, image_response, cache)
1984
+ headers = { 'content-type' => type, 'cache-control' => cache, 'cache-tag' => "asset-#{item['id']}" }
1985
+ headers['etag'] = "\"#{item['id']}\"" if image_response
1973
1986
  headers.merge!('x-content-type-options' => 'nosniff', 'content-security-policy' => "sandbox; default-src 'none'")
1974
1987
  mime = type.downcase.split(';', 2).first.to_s.strip
1975
1988
  headers['content-disposition'] = 'attachment' if ACTIVE_TYPES.include?(mime) || mime.end_with?('+xml')
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'json'
3
4
  require_relative 'classification'
4
5
 
5
6
  module CalmLens
@@ -106,6 +107,45 @@ module CalmLens
106
107
  self
107
108
  end
108
109
 
110
+ # The text OCR finds in an image, for an upload that turns OCR on: `classification.ocr` reports
111
+ # `text_regions` (each `{ 'box' => { 'left', 'top', 'width', 'height' }, 'personalInformation' }`),
112
+ # and `content.extractedText` holds `text` when the upload keeps its content.
113
+ # @param text [String, nil]
114
+ # @param text_regions [Array<Hash>]
115
+ # @return [self]
116
+ def with_ocr(text, text_regions = [])
117
+ raise Internal.invalid('text must be a String or nil') unless text.nil? || text.is_a?(String)
118
+ raise Internal.invalid('text_regions must be an Array') unless text_regions.is_a?(Array)
119
+
120
+ @ocr = { 'text' => text, 'textRegions' => MockDecision.json_copy(text_regions) }
121
+ self
122
+ end
123
+
124
+ # The QR codes (`{ 'value', 'box' }`) and links (`{ 'url', 'source' }`, `source` being `text`
125
+ # or `qr-code`) link detection finds in an image, reported as `classification.linkDetection`
126
+ # unless the upload turns link detection off.
127
+ # @param qr_codes [Array<Hash>]
128
+ # @param links [Array<Hash>]
129
+ # @return [self]
130
+ def with_link_detection(qr_codes = [], links = [])
131
+ raise Internal.invalid('qr_codes and links must be Arrays') unless qr_codes.is_a?(Array) && links.is_a?(Array)
132
+
133
+ @link_detection = { 'qrCodes' => MockDecision.json_copy(qr_codes), 'links' => MockDecision.json_copy(links) }
134
+ self
135
+ end
136
+
137
+ # What {#with_ocr} set, or nil.
138
+ # @api private
139
+ def ocr_findings = @ocr && MockDecision.json_copy(@ocr)
140
+
141
+ # What {#with_link_detection} set, or nil.
142
+ # @api private
143
+ def link_findings = @link_detection && MockDecision.json_copy(@link_detection)
144
+
145
+ # A deep copy with String keys, as the API's JSON has.
146
+ # @api private
147
+ def self.json_copy(value) = JSON.parse(JSON.generate(value))
148
+
109
149
  # The report a decided asset gets, as the API sends it: every category (unflagged ones
110
150
  # evaluated with score 0), the policy's actions, the automated status and `flaggedCategories`.
111
151
  # @param requested_at [Integer] when a pending review joined the queue, in epoch milliseconds
@@ -9,7 +9,7 @@ module CalmLens
9
9
  # Checks test input scenarios and writes them as the backend's canonical JSON.
10
10
  # @api private
11
11
  module Scenario
12
- ACTIONS = %w[allow limit age-restrict block].freeze
12
+ ACTIONS = %w[limit age-restrict block].freeze
13
13
  REGIONAL_ACTIONS = %w[limit age-restrict block].freeze
14
14
  # The qualifiers a scenario may list for each category: all but those the input type sets.
15
15
  ALLOWED_QUALIFIERS = MockClassification::QUALIFIERS.transform_values do |list|
@@ -17,7 +17,7 @@ module CalmLens
17
17
  # 'instances' => [{ 'category' => 'harassment', 'score' => 0.9, 'action' => 'block', 'qualifiers' => ['harassment-abuse'] }] }`.
18
18
  # `instances` (at most 128) and each instance's `qualifiers` (unique qualifiers of its category, at
19
19
  # most 64; input-type qualifiers such as `sexual-text` are automatic) are required; `score` (0 to
20
- # 1) and `action` (`allow`, `limit`, `age-restrict` or `block`, on every instance or none) are
20
+ # 1) and `action` (`limit`, `age-restrict` or `block`, on every instance or none) are
21
21
  # optional. `unassessedCategories` lists categories reported as not assessed, none with instances;
22
22
  # `regionalActions` gives up to one `limit`, `age-restrict` or `block` action for each of
23
23
  # {REGIONS}. `detections` (optional, `people` and `faces` each optional) sets the person and face
@@ -27,7 +27,7 @@ module CalmLens
27
27
  # for a private asset unless `api_key` comes from {.create_api_key} with an `assets:download`
28
28
  # grant (the default key has no grants), or the URL is signed: {CDN#sign_asset_url} returns
29
29
  # `{cdn_base_url}/assets/{project_id}/sig_…`, a readable grant that only the mock's CDN accepts,
30
- # which serves `original` only when signed with `original: true`. {#fetch_cdn} loads such a URL
30
+ # which serves `original` only when signed for it. {#fetch_cdn} loads such a URL
31
31
  # without the API key, as a browser would; without the key or a grant, a private asset answers
32
32
  # as an unknown one does, `asset/not-found` (404) whatever its state, including its placeholder
33
33
  # and display info. {#decide} applies a reviewer's decision, and {Assets#wait_for_decision} takes no real
@@ -160,7 +160,7 @@ module CalmLens
160
160
  # increasing `createdAt` and order predictably. A clock you pass is used as is.
161
161
  # @param create_id [#call] receives the prefix of the kind of object (`asset`, `fldr`, `hl`, `hle`, `lens`,
162
162
  # `evt` or `rev`) and returns a new ID. The default is like the API's: the prefix, `_` and 20 random base62
163
- # characters, such as `asset_5Gm2Rk8XqT3wLp9VbN4c`.
163
+ # characters, such as `asset_e5Gm2Rk8XqT3wLp9VbN4`.
164
164
  # @param moderate [#call, nil] decides each asset the mock moderates. It receives a
165
165
  # {MockModerationInput} (the stored asset, its content, the trigger and whether the API would
166
166
  # queue the work) and returns a status from {MockDecision::STATUSES} or a {MockDecision}. It is
@@ -2,5 +2,5 @@
2
2
 
3
3
  module CalmLens
4
4
  # The gem version. The gemspec and the User-Agent header read it from here.
5
- VERSION = '0.27.5'
5
+ VERSION = '0.28.0'
6
6
  end
data/sig/calmlens.rbs CHANGED
@@ -81,6 +81,9 @@ module CalmLens
81
81
  def []: (Symbol | String key) -> untyped
82
82
  def key?: (Symbol | String key) -> bool
83
83
  def dig: (Symbol | String key, *untyped rest) -> untyped
84
+ def fetch: (Symbol | String key) -> untyped
85
+ | [T] (Symbol | String key, T default) -> untyped
86
+ | [T] (Symbol | String key) { (Symbol | String key) -> T } -> untyped
84
87
  def values_at: (*(Symbol | String) keys) -> Array[untyped]
85
88
  def keys: () -> Array[Symbol]
86
89
  def to_h: () -> Hash[String, json_value]
@@ -357,7 +360,7 @@ module CalmLens
357
360
  # The ISO 3166-1 alpha-2 countries a viewer's `region` can be.
358
361
  VIEWER_COUNTRIES: Array[String]
359
362
  def get_asset_url: (?asset_id: String, ?external_id: String, ?project_id: String, ?resource: cdn_resource, ?lens: String, ?transform: transform_input, ?viewer_claims: viewer_claims, ?request_options: request_options) -> String
360
- def sign_asset_url: (?asset_id: String, ?external_id: String, ?project_id: String, ?expires_in: Integer, ?original: bool, ?resource: cdn_resource, ?lens: String, ?transform: transform_input, ?viewer_claims: viewer_claims, ?request_options: request_options) -> SignedAssetUrl
363
+ def sign_asset_url: (?asset_id: String, ?external_id: String, ?project_id: String, ?expires_in: Integer, ?resource: cdn_resource, ?lens: String, ?transform: transform_input, ?viewer_claims: viewer_claims, ?request_options: request_options) -> SignedAssetUrl
361
364
  def get_asset_info: (String url, ?viewer_claims: viewer_claims?) -> AssetInfo
362
365
  def serve: (?asset_id: String, ?external_id: String, ?project_id: String, ?viewer_claims: viewer_claims, ?resource: cdn_resource, ?lens: String, ?transform: transform_input, ?init: { ?method: "GET" | "HEAD", ?headers: Hash[String, String] }, ?request_options: request_options) -> Response
363
366
  | [T] (?asset_id: String, ?external_id: String, ?project_id: String, ?viewer_claims: viewer_claims, ?resource: cdn_resource, ?lens: String, ?transform: transform_input, ?init: { ?method: "GET" | "HEAD", ?headers: Hash[String, String] }, ?request_options: request_options) { (Response) -> T } -> T
@@ -543,6 +546,14 @@ module CalmLens
543
546
  def not_evaluated: (String | Symbol category) -> self
544
547
  # Leaves the decision waiting for human review: `sampled`, or `uncertain` with the categories that made it so.
545
548
  def pending_review: ("sampled" | "uncertain" | :sampled | :uncertain reason, ?Array[String | Symbol] uncertain_categories) -> self
549
+ # The text OCR finds in an image: `classification.ocr` reports `text_regions`, and
550
+ # `content.extractedText` holds `text` when the upload keeps its content.
551
+ def with_ocr: (String? text, ?Array[Hash[String | Symbol, untyped]] text_regions) -> self
552
+ # The QR codes and links link detection finds in an image (`classification.linkDetection`).
553
+ def with_link_detection: (?Array[Hash[String | Symbol, untyped]] qr_codes, ?Array[Hash[String | Symbol, untyped]] links) -> self
554
+ def ocr_findings: () -> Hash[String, untyped]?
555
+ def link_findings: () -> Hash[String, untyped]?
556
+ def self.json_copy: (untyped value) -> untyped
546
557
  # The `categories`, `score` and `policy` a decided asset gets; nil for `pending` and `failed`.
547
558
  # `requested_at` is when a pending review joined the queue, in epoch milliseconds.
548
559
  def report: (?Integer requested_at) -> Hash[String, json_value]?
@@ -583,7 +594,7 @@ module CalmLens
583
594
  # Signed test inputs: text codes, test images and media phrases signed with a project's secret
584
595
  # test input key from the portal.
585
596
  module TestInputs
586
- type action = "allow" | "limit" | "age-restrict" | "block"
597
+ type action = "limit" | "age-restrict" | "block"
587
598
  type region = moderation_region
588
599
  type regional_action = { "region" => region, "action" => "limit" | "age-restrict" | "block" }
589
600
  # One qualifying instance; set an action on every instance or on none.
data/sig/error_codes.rbs CHANGED
@@ -41,6 +41,7 @@ module CalmLens
41
41
  INVALID_IMAGE: String
42
42
  IMAGE_TOO_LARGE: String
43
43
  FREE_UPLOADS_EXHAUSTED: String
44
+ WEBSITE_BILLING_REQUIRED: String
44
45
  UPLOADS_PAUSED: String
45
46
  UNSUPPORTED_UPLOAD_TYPE: String
46
47
  INVALID_UPLOAD_PAYLOAD: String
@@ -80,6 +81,7 @@ module CalmLens
80
81
  HASH_LIST_ENTRY_NOT_FOUND: String
81
82
  HASH_LIST_LIMIT_REACHED: String
82
83
  HASH_LIST_ENTRY_LIMIT_REACHED: String
84
+ HASH_LIST_ENTRY_QUALITY_TOO_LOW: String
83
85
  HASH_LIST_ASSET_NOT_HASHED: String
84
86
  POLICY_NOT_FOUND: String
85
87
  POLICY_REVISION_CONFLICT: String
data/sig/models.rbs CHANGED
@@ -1,7 +1,7 @@
1
1
  # Generated by script/generate_models.rb from testdata/types.json; do not edit.
2
2
  module CalmLens
3
3
  type moderation_qualifier = "sexual-pornographic-media" | "hate-nazi-symbols-public-display" | "hate-nazi-insignia-public-display" | "hate-nazi-genocide-public-peace" | "hate-nazi-genocide-denial-or-approval" | "hate-adjudicated-nazi-crimes-denial" | "violence-high-impact" | "self-harm-age-restricted" | "personal-information-contact" | "personal-information-email" | "personal-information-phone" | "personal-information-government-id" | "personal-information-financial" | "personal-information-location" | "personal-information-identifiers" | "personal-information-credentials" | "personal-information-request" | "personal-information-self-disclosure" | "personal-information-third-party" | "personal-information-historical" | "personal-information-documentary" | "personal-information-educational" | "personal-information-fictional" | "personal-information-support-prevention" | "profanity-mild" | "profanity-strong" | "profanity-slurs" | "profanity-obfuscated" | "profanity-historical" | "profanity-documentary" | "profanity-educational" | "profanity-fictional" | "profanity-support-prevention" | "sexual-nudity" | "sexual-activity" | "sexual-explicit-language" | "sexual-assault-media" | "sexual-non-consensual" | "sexual-intimate-image-abuse" | "sexual-extreme" | "sexual-strangulation" | "sexual-incest" | "sexual-minors" | "sexual-solicitation" | "sexual-paid" | "sexual-adult-promotion" | "sexual-revealing-clothing" | "sexual-suggestive" | "sexual-non-erotic-nudity" | "sexual-text" | "sexual-historical" | "sexual-documentary" | "sexual-educational" | "sexual-discussion" | "sexual-fictional" | "sexual-artistic" | "sexual-support-prevention" | "violence-attack" | "violence-threat" | "violence-preparation" | "violence-encouragement" | "violence-wish" | "violence-coded-incitement" | "violence-extremism" | "violence-injury" | "violence-violent-death" | "violence-natural-death" | "violence-graphic" | "violence-decapitation-act" | "violence-gore" | "violence-weapon" | "violence-sport" | "violence-text" | "violence-historical" | "violence-documentary" | "violence-educational" | "violence-discussion" | "violence-fictional" | "violence-fantasy" | "violence-support-prevention" | "self-harm-thoughts" | "self-harm-preparation" | "self-harm-act" | "self-harm-methods" | "self-harm-encouragement" | "self-harm-historical" | "self-harm-documentary" | "self-harm-educational" | "self-harm-fictional" | "self-harm-support-prevention" | "harassment-abuse" | "harassment-mild" | "harassment-bullying" | "harassment-public-target" | "harassment-threat" | "harassment-sexual" | "harassment-encouragement" | "harassment-historical" | "harassment-documentary" | "harassment-educational" | "harassment-fictional" | "harassment-support-prevention" | "hate-abuse" | "hate-slurs" | "hate-dehumanization" | "hate-inferiority" | "hate-exclusion" | "hate-symbol" | "hate-hostility" | "hate-threat" | "hate-personal" | "hate-historical" | "hate-documentary" | "hate-educational" | "hate-fictional" | "hate-counterspeech" | "hate-support-prevention" | "criminal-activity-demonstration" | "criminal-activity-preparation" | "criminal-activity-request" | "criminal-activity-instructions" | "criminal-activity-promotion" | "criminal-activity-coded-incitement" | "criminal-activity-substances" | "criminal-activity-grooming" | "criminal-activity-csam" | "criminal-activity-alcohol" | "criminal-activity-tobacco" | "criminal-activity-gambling" | "criminal-activity-fraud" | "criminal-activity-sexual-solicitation" | "criminal-activity-graffiti" | "criminal-activity-historical" | "criminal-activity-documentary" | "criminal-activity-educational" | "criminal-activity-discussion" | "criminal-activity-fictional" | "criminal-activity-support-prevention"
4
- type event_type = "asset.uploaded" | "asset.classified" | "asset.region-restricted" | "asset.allowed" | "asset.limited" | "asset.age-restricted" | "asset.blocked" | "asset.purged" | "asset.failed" | "asset.progress-updated" | "asset.deleted" | "asset.content-removed" | "asset.retried" | "asset.review-requested" | "asset.review-completed" | "asset.hash-matched" | "usage.free-uploads-exhausted" | "usage.uploads-paused" | "upload-preset.daily-limit-reached" | "project.member-joined" | "project.member-removed" | "project.member-left" | "project.member-role-changed" | "project.invitation-sent" | "project.transferred" | "api-key.created" | "api-key.revoked" | "api-key.deleted" | "connector.disabled"
4
+ type event_type = "asset.uploaded" | "asset.classified" | "asset.region-restricted" | "asset.allowed" | "asset.limited" | "asset.age-restricted" | "asset.blocked" | "asset.purged" | "asset.failed" | "asset.progress-updated" | "asset.media-ready" | "asset.deleted" | "asset.content-removed" | "asset.retried" | "asset.review-requested" | "asset.review-completed" | "asset.hash-matched" | "usage.free-uploads-exhausted" | "usage.uploads-paused" | "upload-preset.daily-limit-reached" | "project.member-joined" | "project.member-removed" | "project.member-left" | "project.member-role-changed" | "project.invitation-sent" | "project.transferred" | "api-key.created" | "api-key.revoked" | "api-key.deleted" | "connector.disabled"
5
5
  type event_fact_key = "asset-name" | "asset-type" | "file-format" | "test" | "parent-asset" | "flagged-categories" | "moderation-status" | "automated-status" | "region" | "rule" | "status" | "reviewer-name" | "note" | "child-asset" | "child-status" | "previous-status" | "failure-reason" | "completed-sections" | "total-sections" | "batch-id" | "review-reason" | "uncertain-categories" | "review-id" | "decision" | "applied-to-asset" | "hash-list-id" | "hash-list-name" | "distance" | "match-action" | "limit" | "used" | "organisation-id" | "reason" | "resumes-at" | "preset-id" | "preset-name" | "daily-limit" | "member-user-id" | "member-name" | "role" | "previous-role" | "invitee-email" | "previous-organisation-id" | "previous-organisation-name" | "organisation-name" | "method" | "api-keys-revoked" | "connectors-paused" | "key-id" | "key-name" | "created-by-name" | "revoked-by-name" | "deleted-by-name" | "connector-id" | "connector-name" | "connector-type" | "consecutive-failures" | "last-error"
6
6
  class Asset < Model
7
7
  def id: () -> String
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: calmlens
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.27.5
4
+ version: 0.28.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - CalmLens
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-22 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: 'Server-side client for the CalmLens API: moderation, uploads, events,
14
14
  webhooks and CDN delivery.'