calmlens 0.25.0 → 0.27.3

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.
data/lib/calmlens/text.rb CHANGED
@@ -17,16 +17,15 @@ module CalmLens
17
17
  # @option options [String] :name defaults to `text`
18
18
  # @option options [String] :author_id who wrote the text, as for {Assets#create}
19
19
  # @option options [Hash] :context earlier posts in the conversation, as for {Assets#create}
20
- # @return [Hash] the asset; show it to everyone only when `classification.moderation.status` is
20
+ # @return [Asset] show it to everyone only when `classification.moderation.decision` is
21
21
  # `allowed` or `limited` (reduce the reach of `limited` content).
22
- def classify(options)
23
- api, request = call(options, __method__) { |*split| split }
24
- text = api['text']
22
+ def classify(**options)
23
+ call(options, __method__) { nil }
24
+ text = options[:text]
25
25
  raise Internal.invalid('Text to classify must be a non-empty string') unless text.is_a?(String) && !text.strip.empty?
26
26
 
27
- @assets.classify(without(api, 'text').merge('name' => api.fetch('name', 'text'),
28
- 'content' => { 'plainText' => text, 'type' => 'text/plain' },
29
- 'request_options' => request))
27
+ @assets.classify(**options.except(:text), name: options.fetch(:name, 'text'),
28
+ content: { plain_text: text, type: 'text/plain' })
30
29
  end
31
30
  end
32
31
  end
@@ -29,6 +29,7 @@ module CalmLens
29
29
  UPLOAD_MIME_TYPES = [
30
30
  'application/pdf',
31
31
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
32
+ 'application/vnd.ms-word.document.macroenabled.12',
32
33
  'application/msword',
33
34
  'application/rtf',
34
35
  'application/vnd.oasis.opendocument.text',
@@ -27,8 +27,8 @@ module CalmLens
27
27
  # @option options [String] :upload_preset_id the preset the token may upload through
28
28
  # @option options [String] :external_id the external ID the uploaded asset gets (not empty)
29
29
  # @option options [Integer] :expires_in lifetime in seconds, 1 to 3600 (default 600)
30
- # @return [Hash] `{'token' => String, 'expiresAt' => Integer}` (milliseconds since the Unix epoch)
31
- def sign(options)
30
+ # @return [SignedUploadToken] `token` and `expires_at` (milliseconds since the Unix epoch)
31
+ def sign(**options)
32
32
  call(options, __method__) { UploadTokens.sign_at(@api_key, options, now: (Time.now.to_f * 1000).to_i, nonce: SecureRandom.uuid) }
33
33
  end
34
34
 
@@ -57,7 +57,13 @@ module CalmLens
57
57
  body = [JSON.generate(claims, script_safe: false, ascii_only: false)].pack('m0').tr('+/', '-_').delete('=')
58
58
  secret = Digest::SHA256.hexdigest(api_key)
59
59
  signature = OpenSSL::HMAC.hexdigest('SHA256', secret, SIGNING_CONTEXT + body)
60
- { 'token' => "#{TOKEN_PREFIX}#{body}.#{signature}", 'expiresAt' => expires_at }
60
+ SignedUploadToken.new({ 'token' => "#{TOKEN_PREFIX}#{body}.#{signature}", 'expiresAt' => expires_at })
61
61
  end
62
62
  end
63
+
64
+ # A signed upload token from {UploadTokens#sign}: the `token` to hand to the browser and when it
65
+ # expires (`expires_at`, milliseconds since the Unix epoch).
66
+ class SignedUploadToken < Model
67
+ declare(token: ['token', nil], expires_at: ['expiresAt', nil])
68
+ end
63
69
  end
@@ -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.25.0'
5
+ VERSION = '0.27.3'
6
6
  end
@@ -14,37 +14,18 @@ module CalmLens
14
14
  # Deliveries whose timestamp is further than this from the receiver's clock are rejected.
15
15
  WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300
16
16
 
17
- # A verified webhook delivery. The body has the shape of an {Events#list} item:
18
- # `{id, projectId, actor, type, severity, title, description, assetId, assetSequence, asset, facts, createdAt}`.
19
- # Fields CalmLens adds later are kept in {#payload}, as are unknown asset and fact fields.
20
- #
21
- # @!attribute id [String] the event ID.
22
- # @!attribute project_id [String]
23
- # @!attribute actor [Hash, nil] who caused the event: `{'type', 'id'}`, with `type` `user`, `api-key`,
24
- # `automated` or `system`, and `id` the user's or API key's ID, or nil when it was not recorded.
25
- # @!attribute type [String] such as `asset.allowed`. New types may appear: ignore unknown ones.
26
- # @!attribute severity [String, nil] `low` or `high`.
27
- # @!attribute title [String, nil]
28
- # @!attribute description [String, nil]
29
- # @!attribute asset_id [String, nil]
30
- # @!attribute asset_sequence [Integer, nil] increases with each event about the same asset; nil for
31
- # events not about an asset. Deliveries can arrive out of order: see {#newer_than?}.
32
- # @!attribute asset [Hash, nil] the asset's status when the event was created.
33
- # @!attribute facts [Array<Hash>] `{'key', 'value', 'url'?}` entries registered for the event type.
34
- # @!attribute created_at [Integer] milliseconds since the epoch.
35
- # @!attribute payload [Hash{String => Object}] the delivery body as received, with every field.
36
- WebhookEvent = Struct.new(:id, :project_id, :actor, :type, :severity, :title, :description, :asset_id, :asset_sequence, :asset,
37
- :facts, :created_at, :payload, keyword_init: true) do
17
+ # An event from {Events#list} or a verified webhook delivery ({Webhooks.parse_event}). `type` is
18
+ # such as `asset.allowed`; new types may appear, so ignore unknown ones. `asset_sequence`
19
+ # increases with each event about the same asset and is nil for events not about an asset;
20
+ # deliveries can arrive out of order, see {#newer_than?}. {#to_h} is the body as received.
21
+ class Event
38
22
  # @return [Boolean] true for a test send from the portal or CLI.
39
23
  def test? = Webhooks.test_event?(self)
40
24
 
41
- # @param last_sequence [Integer, nil] the highest `assetSequence` applied for this event's asset
25
+ # @param last_sequence [Integer, nil] the highest `asset_sequence` applied for this event's asset
42
26
  # @return [Boolean] whether to apply this event after it.
43
27
  # @see Webhooks.newer_asset_event?
44
28
  def newer_than?(last_sequence) = Webhooks.newer_asset_event?(self, last_sequence)
45
-
46
- # @return [Hash{String => Object}] the delivery body as received, with every field.
47
- def to_payload = payload
48
29
  end
49
30
 
50
31
  # Webhook signing and verification. Always verify the exact bytes received: read the raw body
@@ -81,11 +62,11 @@ module CalmLens
81
62
 
82
63
  # Whether an event is a test send from the portal or the CLI rather than a real event: its
83
64
  # `facts` hold the registered `{ key: "test", value: true }` fact.
84
- # @param event [WebhookEvent, Hash] a parsed delivery, or a delivery body with string keys
65
+ # @param event [Event, Hash] a parsed delivery, or a delivery body with string keys
85
66
  # @return [Boolean]
86
67
  def test_event?(event)
87
- facts = event.is_a?(Hash) ? event['facts'] : event.facts
88
- facts.is_a?(Array) && facts.any? { |fact| fact.is_a?(Hash) && fact['key'] == 'test' && fact['value'] == true }
68
+ facts = event['facts']
69
+ facts.is_a?(Array) && facts.any? { |fact| (fact.is_a?(Hash) || fact.is_a?(Model)) && fact['key'] == 'test' && fact['value'] == true }
89
70
  end
90
71
 
91
72
  # Whether to apply `event` after `last_sequence`, the highest `assetSequence` you have applied
@@ -93,22 +74,23 @@ module CalmLens
93
74
  # newer only with a higher `assetSequence`, so a retried or repeated delivery of an earlier one
94
75
  # returns false. Events that aren't about an asset have no sequence and are always new. Store
95
76
  # the highest `assetSequence` applied per `assetId` and ignore lower ones.
96
- # @param event [WebhookEvent, Hash] a parsed delivery, or a delivery body with string keys
77
+ # @param event [Event, Hash] a parsed delivery, or a delivery body with string keys
97
78
  # @param last_sequence [Integer, nil]
98
79
  # @return [Boolean]
99
80
  def newer_asset_event?(event, last_sequence)
100
- sequence = event.is_a?(Hash) ? event['assetSequence'] : event.asset_sequence
81
+ sequence = event['assetSequence']
101
82
  sequence.nil? || last_sequence.nil? || sequence > last_sequence
102
83
  end
103
84
 
104
85
  # Converts an event from {Events#list} to the JSON body of its webhook delivery, which has the
105
86
  # same fields: `description`, `assetId`, `assetSequence` and `asset` are nil when absent, and
106
87
  # `actor` is left out when the event has none.
107
- # @param event [Hash] an event with string keys, as {Events#list} returns it
88
+ # @param event [Event, Hash] an {Events#list} item, or an event with string keys
108
89
  # @return [Hash] `{ 'id', 'projectId', 'actor', 'type', 'severity', 'title', 'description', 'assetId',
109
90
  # 'assetSequence', 'asset', 'facts', 'createdAt' }`
110
91
  def to_payload(event)
111
- raise Internal.invalid('event must be a Hash') unless event.is_a?(Hash)
92
+ event = event.to_h if event.is_a?(Model)
93
+ raise Internal.invalid('event must be an Event or a Hash') unless event.is_a?(Hash)
112
94
 
113
95
  payload = { 'id' => event['id'], 'projectId' => event['projectId'] }
114
96
  payload['actor'] = event['actor'] if event.key?('actor')
@@ -158,7 +140,7 @@ module CalmLens
158
140
  end
159
141
 
160
142
  # Verifies a delivery, then parses it. Takes the options of {verify}.
161
- # @return [WebhookEvent]
143
+ # @return [Event]
162
144
  # @raise [WebhookVerificationError] `sdk/invalid-webhook-signature` when verification fails, or
163
145
  # `sdk/invalid-webhook-payload` when the verified body is not an event.
164
146
  def parse_event(payload:, secret:, signature: nil, timestamp: nil, headers: nil,
@@ -176,10 +158,7 @@ module CalmLens
176
158
  body = JSON.parse(payload.dup.force_encoding(Encoding::UTF_8))
177
159
  raise WebhookVerificationError.new(SdkErrorCodes::INVALID_WEBHOOK_PAYLOAD, 'Webhook body is not a CalmLens event') unless event?(body)
178
160
 
179
- WebhookEvent.new(id: body['id'], project_id: body['projectId'], actor: body['actor'], type: body['type'], severity: body['severity'],
180
- title: body['title'], description: body['description'], asset_id: body['assetId'],
181
- asset_sequence: body['assetSequence'], asset: body['asset'], facts: body.fetch('facts', []),
182
- created_at: body['createdAt'], payload: body)
161
+ Event.new(body)
183
162
  rescue JSON::ParserError, EncodingError => e
184
163
  raise WebhookVerificationError.new(SdkErrorCodes::INVALID_WEBHOOK_PAYLOAD, 'Webhook body is not JSON'), cause: e
185
164
  end
data/lib/calmlens.rb CHANGED
@@ -8,6 +8,8 @@ end
8
8
  require_relative 'calmlens/version'
9
9
  require_relative 'calmlens/error_codes'
10
10
  require_relative 'calmlens/errors'
11
+ require_relative 'calmlens/model'
12
+ require_relative 'calmlens/models'
11
13
  require_relative 'calmlens/option_keys'
12
14
  require_relative 'calmlens/transform_schema'
13
15
  require_relative 'calmlens/upload_mime_types'