agilis-ads 0.1.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0e78b5817f284db616ed1b091d80bc6462eff8c26a0b0fe913a1511777d98baf
4
+ data.tar.gz: c0f5751dbd27b0fade376fe69439390ca714046ef20003e8a04320e7675c8924
5
+ SHA512:
6
+ metadata.gz: a0d2625ec17652706b4c6cba9f2f7a682fda083eeaa4835f236156f324d8779f65cc84b488aad0777546bf9132811d786247f2a0020c1f286680652325533b17
7
+ data.tar.gz: d4277a09045aa7606f44cdde9415761d05abc2f4126a3fca32a03c2ecd5e87afd74efd67be3e7f5ee6b8bf858aa742b88b13f77c68da4c5958074f0991b13060
data/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (23 November 2026)
4
+
5
+ - First release published to RubyGems. Version 0.1.0 was never published.
6
+
7
+ ## 0.1.0 (23 November 2026)
8
+
9
+ - First release: every operation of the Agilis Advertising REST API, auto-paging lists, idempotent retries, typed errors and webhook signature verification.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Agilis Dating Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,238 @@
1
+ # Agilis Advertising API for Ruby
2
+
3
+ The official Ruby library for the [Agilis Advertising REST API](https://www.agilis.dating/api-doc): create and manage Offers and Events, read their results, manage webhook endpoints, and verify the webhooks Agilis sends you.
4
+
5
+ - Ruby 3.2 or later
6
+ - No runtime dependencies: it uses Ruby's own `net/http`, `json` and `openssl`
7
+
8
+ ## Install
9
+
10
+ ```ruby
11
+ # Gemfile
12
+ gem "agilis-ads"
13
+ ```
14
+
15
+ or `gem install agilis-ads`.
16
+
17
+ ## Quick start (Test mode)
18
+
19
+ Create a Test-mode key (`pk_test_...`) in the Ad Portal and keep it in an environment variable, never in code.
20
+
21
+ ```ruby
22
+ require "agilis_ads"
23
+
24
+ client = AgilisAds::Client.new(api_key: ENV.fetch("AGILIS_API_KEY"))
25
+ client.mode # => "test"
26
+
27
+ client.categories.list.categories.each do |category|
28
+ puts "#{category.category_id}: #{category.category_name}"
29
+ end
30
+
31
+ estimate = client.offers.estimate_price(
32
+ start_datetime: "2027-07-10T08:00:00Z",
33
+ end_datetime: "2027-07-12T20:30:00Z",
34
+ location: [51.5074, -0.1278],
35
+ radius: 10
36
+ )
37
+ puts estimate.estimated_cost
38
+
39
+ offer = client.offers.create(
40
+ category_id: 1,
41
+ title: "Summer Sale",
42
+ description: "Twenty percent off everything in August.",
43
+ push_notification_title: "Summer Sale",
44
+ push_notification_message: "Twenty percent off, this week only.",
45
+ url: "https://www.example.com/summer-sale",
46
+ image: "offer.png",
47
+ location: [51.5074, -0.1278],
48
+ radius: 10,
49
+ gender: %w[Male Female],
50
+ interests: [3, 7],
51
+ start_datetime: "2027-08-01T09:00:00Z",
52
+ expiry_datetime: "2027-08-31T23:59:00Z",
53
+ payment_method: "B"
54
+ )
55
+ puts offer.offer_id
56
+ ```
57
+
58
+ A Test key works with TEST data only: members never see it and nothing is charged. With a Live key (`pk_live_...`) changes are real. `client.mode` is `"test"` or `"live"` (also `client.test_mode?` and `client.live_mode?`), so a script can refuse to run against Live.
59
+
60
+ More: [`examples/test_mode.rb`](examples/test_mode.rb) and [`examples/webhook_receiver.rb`](examples/webhook_receiver.rb).
61
+
62
+ ## Client options
63
+
64
+ ```ruby
65
+ AgilisAds::Client.new(
66
+ api_key: "pk_test_...", # default: ENV["AGILIS_API_KEY"]
67
+ base_url: "https://ads.agilis.dating", # default
68
+ timeout: 60, # seconds per attempt, default 60
69
+ max_retries: 2, # default 2
70
+ http_client: AgilisAds::NetHttpClient.new # default
71
+ )
72
+ ```
73
+
74
+ `http_client` can be any object with `call(method:, url:, headers:, body:, timeout:)` that returns `[status, headers, body]`.
75
+
76
+ The key is sent only in the `x-api-key` header. It is never logged, never put in a URL and never included in an error message.
77
+
78
+ ## Resources and methods
79
+
80
+ Each method takes path parameters as arguments and everything else as keyword arguments (or one hash), using the API's own field names. Operations that take `environment` fill it in from your key when you leave it out.
81
+
82
+ | Method | HTTP |
83
+ |---|---|
84
+ | `client.categories.list` | `GET /categories` |
85
+ | `client.interests.list` | `GET /interests` |
86
+ | `client.offers.estimate_price(**params)` | `POST /offers/price-estimate` |
87
+ | `client.offers.create(**params, dry_run: false, idempotency_key: nil)` | `POST /offers` |
88
+ | `client.offers.list(**params)` | `GET /offers` |
89
+ | `client.offers.pause(offer_id)` | `POST /offers/{offer_id}/pause` |
90
+ | `client.offers.resume(offer_id)` | `POST /offers/{offer_id}/resume` |
91
+ | `client.offers.analytics(offer_id, interval: "30d")` | `GET /offers/{offer_id}/analytics` |
92
+ | `client.offers.delete(offer_id, dry_run: false)` | `DELETE /offers/{offer_id}` |
93
+ | `client.event_categories.list` | `GET /event-categories` |
94
+ | `client.event_currencies.list` | `GET /event-currencies` |
95
+ | `client.event_config.get` | `GET /event-config` |
96
+ | `client.events.preview(**params)` | `POST /events/preview` |
97
+ | `client.events.publish(**params, dry_run: false, idempotency_key: nil)` | `POST /events` |
98
+ | `client.events.list(**params)` | `GET /events` |
99
+ | `client.events.get(event_id)` | `GET /events/{event_id}` |
100
+ | `client.events.edit(event_id, **params)` | `PATCH /events/{event_id}` |
101
+ | `client.events.delete(event_id, dry_run: false)` | `DELETE /events/{event_id}` |
102
+ | `client.events.reschedule(event_id, starts_at:, ends_at:)` | `POST /events/{event_id}/reschedule` |
103
+ | `client.events.cancel(event_id, dry_run: false)` | `POST /events/{event_id}/cancel` |
104
+ | `client.events.analytics(event_id, interval: "30d")` | `GET /events/{event_id}/analytics` |
105
+ | `client.webhook_endpoints.list` | `GET /webhook-endpoints` |
106
+ | `client.webhook_endpoints.create(url:, enabled_events:, description: nil)` | `POST /webhook-endpoints` |
107
+ | `client.webhook_endpoints.get(endpoint_id)` | `GET /webhook-endpoints/{endpoint_id}` |
108
+ | `client.webhook_endpoints.update(endpoint_id, **params)` | `PATCH /webhook-endpoints/{endpoint_id}` |
109
+ | `client.webhook_endpoints.delete(endpoint_id)` | `DELETE /webhook-endpoints/{endpoint_id}` |
110
+ | `client.webhook_endpoints.roll_secret(endpoint_id, expires_in: nil)` | `POST /webhook-endpoints/{endpoint_id}/roll-secret` |
111
+ | `client.webhook_endpoints.send_test(endpoint_id, type: nil)` | `POST /webhook-endpoints/{endpoint_id}/test` |
112
+ | `client.webhook_events.list(**params)` | `GET /webhook-events` |
113
+ | `client.webhook_events.get(webhook_event_id)` | `GET /webhook-events/{webhook_event_id}` |
114
+ | `client.webhook_events.resend(webhook_event_id, endpoint_id: nil)` | `POST /webhook-events/{webhook_event_id}/resend` |
115
+ | `AgilisAds::Webhook.construct_event(raw_body, header, secret)` | verifies a received webhook |
116
+
117
+ `dry_run: true` sends `dry_run=true`: the API checks everything and reports the price, but creates, deletes or cancels nothing.
118
+
119
+ ### Images and multipart fields
120
+
121
+ `offers.create`, `events.preview`, `events.publish` and `events.edit` are sent as `multipart/form-data`. Arrays become repeated `[]` parts (`location[]`, `gender[]`, `interests[]`), and `crop: { x: 0, y: 120, w: 1920 }` becomes `crop[x]`, `crop[y]` and `crop[w]`.
122
+
123
+ `image:` takes a file path, an open file, or an `AgilisAds::Upload`:
124
+
125
+ ```ruby
126
+ image: "offer.png"
127
+ image: File.open("offer.png", "rb")
128
+ image: AgilisAds::Upload.from_bytes(png_bytes, filename: "offer.png")
129
+ ```
130
+
131
+ The content type is detected from the file name. `events.edit` is always sent as a multipart `POST` with `X-HTTP-Method-Override: PATCH`, with or without a new image, as the API requires.
132
+
133
+ `Time` values are sent as ISO 8601 in UTC (`2027-08-01T09:00:00Z`).
134
+
135
+ ### Responses
136
+
137
+ Every method returns an `AgilisAds::AgilisObject`. Fields are methods (`offer.offer_id`) or `offer[:offer_id]`; nested objects work the same way. Fields this version does not know about are kept, and `to_h` returns them all as a plain hash.
138
+
139
+ The HTTP status and headers are on `last_response`:
140
+
141
+ ```ruby
142
+ categories = client.categories.list
143
+ categories.last_response.status # => 200
144
+ categories.last_response.rate_limit_remaining # X-RateLimit-Remaining
145
+ categories.last_response.header("X-RateLimit-Limit")
146
+ ```
147
+
148
+ ## Pagination
149
+
150
+ `offers.list`, `events.list` and `webhook_events.list` return one page (`AgilisAds::Page`): `page.data`, `page.more?`, `page.next_cursor` and `page.next_page`. To go through every item, `auto_paging_each` follows `next_cursor` until `has_more` is false, fetching pages only as they are needed:
151
+
152
+ ```ruby
153
+ client.offers.list(limit: 100, offer_status: "active").auto_paging_each do |offer|
154
+ puts offer.title
155
+ end
156
+
157
+ recent = client.events.list(limit: 50).auto_paging_each.first(10) # an Enumerator without a block
158
+ ```
159
+
160
+ ## Idempotency and retries
161
+
162
+ `offers.create` and `events.publish` always send an `Idempotency-Key`: yours if you pass `idempotency_key:`, otherwise a random UUID created once for the call and reused on every retry, so a retried request never creates a second Offer or Event or charges twice.
163
+
164
+ Up to `max_retries` (default 2) retries are made for:
165
+
166
+ - connection errors and timeouts;
167
+ - HTTP 429;
168
+ - HTTP 500, 502, 503 and 504 on `GET` and `DELETE`, and on `POST`s that carry an Idempotency-Key.
169
+
170
+ Other `POST` and `PATCH` requests are not retried on a 5xx, because the change may already have happened. The wait is the `Retry-After` header when there is one; otherwise 0.5 s × 2^attempt with ±25% jitter, at most 8 seconds.
171
+
172
+ ## Errors
173
+
174
+ Every error is an `AgilisAds::AgilisError` with `http_status`, `return_code`, `message`, `body` (the parsed response) and `headers`.
175
+
176
+ | Class | When |
177
+ |---|---|
178
+ | `AgilisAds::AuthenticationError` | 401 |
179
+ | `AgilisAds::PermissionError` | 403 |
180
+ | `AgilisAds::NotFoundError` | 404 |
181
+ | `AgilisAds::ConflictError` | 409 |
182
+ | `AgilisAds::InvalidRequestError` | 400, 422, or HTTP 200 with a `return_code` starting with `E` (for example `E3`, balance too low) |
183
+ | `AgilisAds::RateLimitError` | 429; `retry_after` holds the seconds to wait |
184
+ | `AgilisAds::ApiError` | 5xx and any other status |
185
+ | `AgilisAds::ConnectionError` | no response |
186
+ | `AgilisAds::SignatureVerificationError` | `construct_event` could not verify a webhook |
187
+
188
+ `S1` and `S2` are both success.
189
+
190
+ ```ruby
191
+ begin
192
+ client.offers.create(params)
193
+ rescue AgilisAds::InvalidRequestError => e
194
+ warn "Refused: #{e.return_code} #{e.message}"
195
+ rescue AgilisAds::RateLimitError => e
196
+ sleep e.retry_after || 1
197
+ retry
198
+ end
199
+ ```
200
+
201
+ ## Webhooks
202
+
203
+ Agilis signs every webhook with the `Agilis-Signature` header. `construct_event` checks it against your endpoint's secret, in constant time, and returns the parsed event. It accepts any matching `v1` signature (after a secret roll there are two) and refuses a timestamp more than 300 seconds from now (pass a different `tolerance` as the fourth argument).
204
+
205
+ Always pass the body exactly as received, not re-encoded JSON.
206
+
207
+ ```ruby
208
+ # Sinatra
209
+ post "/agilis/webhooks" do
210
+ event = AgilisAds::Webhook.construct_event(
211
+ request.body.read,
212
+ request.env["HTTP_AGILIS_SIGNATURE"],
213
+ ENV.fetch("AGILIS_WEBHOOK_SECRET")
214
+ )
215
+ case event.type
216
+ when "offer.started" then puts "Offer #{event.data.object.offer_id} started"
217
+ when "event.published" then puts "Event #{event.data.object.event_id} published"
218
+ end
219
+ status 200
220
+ rescue AgilisAds::SignatureVerificationError
221
+ halt 400
222
+ end
223
+ ```
224
+
225
+ In Rails, read the body with `request.raw_post` and the header with `request.headers["Agilis-Signature"]`. `SignatureVerificationError#reason` is `:header`, `:timestamp`, `:signature` or `:payload`.
226
+
227
+ Answer with a 2xx within 10 seconds and do the work afterwards. Events can arrive more than once and out of order: use `event.id` to ignore repeats and `event.created` to order them.
228
+
229
+ ## Links
230
+
231
+ - API reference: https://www.agilis.dating/api-doc
232
+ - OpenAPI: https://www.agilis.dating/openapi.json
233
+ - AsyncAPI (webhooks): https://www.agilis.dating/asyncapi.json
234
+ - API examples and MCP server: https://github.com/agilisdating/agilis-ads-api
235
+
236
+ ## Licence
237
+
238
+ MIT. See [LICENSE](LICENSE). Security issues: see [SECURITY.md](SECURITY.md).
data/SECURITY.md ADDED
@@ -0,0 +1,19 @@
1
+ # Security
2
+
3
+ ## Reporting a problem
4
+
5
+ If you find a security problem in the Agilis Advertising API, the Ad Portal or this repository, please email **help@agilis.dating** with "Security" in the subject. Include what you found, how to reproduce it, and how we can contact you.
6
+
7
+ Please don't open a public issue, and don't access, change or delete data that isn't yours while testing. Use your own Test-mode key.
8
+
9
+ We'll acknowledge your report and keep you updated while we fix it.
10
+
11
+ ## If your API key is exposed
12
+
13
+ If a key has been committed to a repository, pasted in a public place or shared by mistake:
14
+
15
+ 1. Sign in to the Ad Portal, open **Manage API Keys** in the same mode (Test or Live) and select **Roll key**. The old key stops working at once.
16
+ 2. Update your systems with the new key.
17
+ 3. Tell us at help@agilis.dating if you think it was a Live key that was used by someone else.
18
+
19
+ Keep keys in environment variables or a secrets manager, never in code. This repository's `.gitignore` excludes `.env` files.
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # A JSON object returned by the API.
5
+ #
6
+ # Every field is readable as a method (`offer.offer_id`) or with `[]`
7
+ # (`offer[:offer_id]` or `offer["offer_id"]`). Fields the SDK does not know
8
+ # about are kept, so a new API field never breaks a client. Nested objects
9
+ # are AgilisObjects too; `to_h` returns plain Ruby hashes with symbol keys.
10
+ class AgilisObject
11
+ # The HTTP response this object came from (status and headers), or nil for
12
+ # nested objects and webhook events.
13
+ attr_reader :last_response
14
+
15
+ def initialize(values = {}, last_response = nil)
16
+ @values = (values || {}).to_h { |key, value| [key.to_s, value] }
17
+ @last_response = last_response
18
+ @converted = {}
19
+ end
20
+
21
+ def [](key)
22
+ key = key.to_s
23
+ return nil unless @values.key?(key)
24
+
25
+ @converted.fetch(key) { @converted[key] = self.class.convert(@values[key]) }
26
+ end
27
+
28
+ def key?(key)
29
+ @values.key?(key.to_s)
30
+ end
31
+
32
+ def keys
33
+ @values.keys.map(&:to_sym)
34
+ end
35
+
36
+ def dig(key, *rest)
37
+ value = self[key]
38
+ return value if rest.empty? || value.nil?
39
+
40
+ value.dig(*rest)
41
+ end
42
+
43
+ def each
44
+ return to_enum(:each) unless block_given?
45
+
46
+ keys.each { |key| yield key, self[key] }
47
+ self
48
+ end
49
+
50
+ def to_h
51
+ self.class.deep_symbolize(@values)
52
+ end
53
+
54
+ def to_json(*args)
55
+ JSON.generate(@values, *args)
56
+ end
57
+
58
+ def ==(other)
59
+ other.is_a?(AgilisObject) && other.to_h == to_h
60
+ end
61
+ alias eql? ==
62
+
63
+ def hash
64
+ to_h.hash
65
+ end
66
+
67
+ def inspect
68
+ "#<#{self.class.name} #{JSON.generate(@values)}>"
69
+ end
70
+
71
+ def to_s
72
+ inspect
73
+ end
74
+
75
+ def respond_to_missing?(name, include_private = false)
76
+ @values.key?(name.to_s) || super
77
+ end
78
+
79
+ def method_missing(name, *args)
80
+ key = name.to_s
81
+ return self[key] if args.empty? && @values.key?(key)
82
+
83
+ super
84
+ end
85
+
86
+ # Wraps hashes in AgilisObject and arrays element by element.
87
+ def self.convert(value)
88
+ case value
89
+ when Hash then AgilisObject.new(value)
90
+ when Array then value.map { |item| convert(item) }
91
+ else value
92
+ end
93
+ end
94
+
95
+ def self.deep_symbolize(value)
96
+ case value
97
+ when Hash then value.to_h { |key, item| [key.to_sym, deep_symbolize(item)] }
98
+ when Array then value.map { |item| deep_symbolize(item) }
99
+ else value
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # The entry point of the SDK.
5
+ #
6
+ # client = AgilisAds::Client.new(api_key: ENV.fetch("AGILIS_API_KEY"))
7
+ # client.categories.list
8
+ # client.offers.list(limit: 50).auto_paging_each { |offer| puts offer.title }
9
+ class Client
10
+ DEFAULT_BASE_URL = "https://ads.agilis.dating"
11
+ DEFAULT_TIMEOUT = 60
12
+ DEFAULT_MAX_RETRIES = 2
13
+
14
+ attr_reader :base_url, :timeout, :max_retries, :mode,
15
+ :categories, :interests, :offers, :event_categories, :event_currencies,
16
+ :event_config, :events, :webhook_endpoints, :webhook_events, :webhooks
17
+
18
+ # api_key - your key (pk_test_... or pk_live_...); defaults to ENV["AGILIS_API_KEY"]
19
+ # base_url - defaults to https://ads.agilis.dating
20
+ # timeout - seconds per attempt, default 60
21
+ # max_retries - default 2
22
+ # http_client - an object with `call(method:, url:, headers:, body:, timeout:)`
23
+ # returning [status, headers, body]; defaults to NetHttpClient
24
+ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT,
25
+ max_retries: DEFAULT_MAX_RETRIES, http_client: nil)
26
+ api_key ||= ENV.fetch("AGILIS_API_KEY", nil)
27
+ if api_key.nil? || api_key.to_s.strip.empty?
28
+ raise ArgumentError, "No API key: pass api_key: or set the AGILIS_API_KEY environment variable"
29
+ end
30
+
31
+ @api_key = api_key.to_s.strip
32
+ @mode = self.class.mode_for(@api_key)
33
+ @base_url = base_url.to_s.chomp("/")
34
+ @timeout = timeout
35
+ @max_retries = Integer(max_retries)
36
+ @requestor = Requestor.new(api_key: @api_key, base_url: @base_url, timeout: @timeout,
37
+ max_retries: @max_retries, http_client: http_client || NetHttpClient.new)
38
+ build_resources
39
+ end
40
+
41
+ # "test" for a pk_test_ key, "live" for a pk_live_ key, otherwise nil.
42
+ def self.mode_for(api_key)
43
+ if api_key.start_with?("pk_test_")
44
+ "test"
45
+ elsif api_key.start_with?("pk_live_")
46
+ "live"
47
+ end
48
+ end
49
+
50
+ def test_mode?
51
+ @mode == "test"
52
+ end
53
+
54
+ def live_mode?
55
+ @mode == "live"
56
+ end
57
+
58
+ def inspect
59
+ "#<#{self.class.name} mode=#{@mode.inspect} base_url=#{@base_url.inspect}>"
60
+ end
61
+ alias to_s inspect
62
+
63
+ private
64
+
65
+ attr_reader :requestor
66
+
67
+ def build_resources
68
+ @categories = Resources::Categories.new(self)
69
+ @interests = Resources::Interests.new(self)
70
+ @offers = Resources::Offers.new(self)
71
+ @event_categories = Resources::EventCategories.new(self)
72
+ @event_currencies = Resources::EventCurrencies.new(self)
73
+ @event_config = Resources::EventConfig.new(self)
74
+ @events = Resources::Events.new(self)
75
+ @webhook_endpoints = Resources::WebhookEndpoints.new(self)
76
+ @webhook_events = Resources::WebhookEvents.new(self)
77
+ @webhooks = Resources::Webhooks.new(self)
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # Base class of every error the SDK raises for an API call.
5
+ class AgilisError < StandardError
6
+ attr_reader :http_status, :return_code, :body, :headers
7
+
8
+ def initialize(message = nil, http_status: nil, return_code: nil, body: nil, headers: nil)
9
+ super(message)
10
+ @http_status = http_status
11
+ @return_code = return_code
12
+ @body = body
13
+ @headers = headers || {}
14
+ end
15
+ end
16
+
17
+ # HTTP 401: the API key is missing, wrong or revoked.
18
+ class AuthenticationError < AgilisError; end
19
+
20
+ # HTTP 403: the key may not do this (for example the other mode's environment).
21
+ class PermissionError < AgilisError; end
22
+
23
+ # HTTP 404.
24
+ class NotFoundError < AgilisError; end
25
+
26
+ # HTTP 409.
27
+ class ConflictError < AgilisError; end
28
+
29
+ # HTTP 400 or 422, or HTTP 200 with a return_code starting with "E".
30
+ class InvalidRequestError < AgilisError; end
31
+
32
+ # HTTP 429.
33
+ class RateLimitError < AgilisError
34
+ # Seconds to wait, from the Retry-After header, or nil.
35
+ attr_reader :retry_after
36
+
37
+ def initialize(message = nil, retry_after: nil, **kwargs)
38
+ super(message, **kwargs)
39
+ @retry_after = retry_after
40
+ end
41
+ end
42
+
43
+ # HTTP 5xx and any other unexpected status.
44
+ class ApiError < AgilisError; end
45
+
46
+ # No response was received (connection refused, DNS failure, timeout and so on).
47
+ class ConnectionError < AgilisError; end
48
+
49
+ # A webhook message could not be verified.
50
+ class SignatureVerificationError < AgilisError
51
+ # :header, :timestamp, :signature or :payload.
52
+ attr_reader :reason
53
+
54
+ def initialize(message = nil, reason: nil)
55
+ super(message)
56
+ @reason = reason
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # Builds multipart/form-data bodies.
5
+ #
6
+ # Arrays are sent as repeated parts named with "[]" (`location[]`,
7
+ # `gender[]`, `interests[]`), a hash as bracketed names (`crop: { x: 0 }`
8
+ # becomes `crop[x]`), and uploads as file parts. nil values are left out.
9
+ module Multipart
10
+ CRLF = "\r\n"
11
+
12
+ module_function
13
+
14
+ # Returns [body, content_type].
15
+ def encode(params, boundary: "AgilisAdsBoundary#{SecureRandom.hex(16)}")
16
+ body = String.new(encoding: Encoding::BINARY)
17
+ params.each do |name, value|
18
+ each_part(name.to_s, value) { |part_name, part| body << part_bytes(boundary, part_name, part) }
19
+ end
20
+ body << "--#{boundary}--#{CRLF}".b
21
+ [body, "multipart/form-data; boundary=#{boundary}"]
22
+ end
23
+
24
+ def each_part(name, value, &block)
25
+ case value
26
+ when nil then nil
27
+ when Array
28
+ array_name = name.end_with?("[]") ? name : "#{name}[]"
29
+ value.each { |item| block.call(array_name, item) unless item.nil? }
30
+ when Hash
31
+ value.each { |key, item| each_part("#{name}[#{key}]", item, &block) }
32
+ else
33
+ block.call(name, name == "image" && value.is_a?(String) ? Upload.from_path(value) : value)
34
+ end
35
+ end
36
+
37
+ def part_bytes(boundary, name, value)
38
+ head = +"--#{boundary}#{CRLF}"
39
+ if Upload.upload?(value)
40
+ upload = Upload.coerce(value)
41
+ head << "Content-Disposition: form-data; name=\"#{escape(name)}\"; "
42
+ head << "filename=\"#{escape(upload.filename)}\"#{CRLF}"
43
+ head << "Content-Type: #{upload.content_type}#{CRLF}#{CRLF}"
44
+ head.b + upload.read + CRLF.b
45
+ else
46
+ head << "Content-Disposition: form-data; name=\"#{escape(name)}\"#{CRLF}#{CRLF}"
47
+ head.b + scalar(value).b + CRLF.b
48
+ end
49
+ end
50
+
51
+ def scalar(value)
52
+ case value
53
+ when true then "true"
54
+ when false then "false"
55
+ when Time then value.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
56
+ else value.to_s.encode(Encoding::UTF_8)
57
+ end
58
+ end
59
+
60
+ def escape(text)
61
+ text.to_s.gsub(/["\r\n\\]/) { |char| format("%%%02X", char.ord) }
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgilisAds
4
+ # The default HTTP client, built on Net::HTTP.
5
+ #
6
+ # Any object with the same `call` method can be passed to the client as
7
+ # `http_client:`. It returns `[status, headers, body]`. On a network failure
8
+ # it raises AgilisAds::ConnectionError or one of Ruby's own network errors
9
+ # (timeouts, SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError).
10
+ class NetHttpClient
11
+ REQUEST_CLASSES = {
12
+ "GET" => Net::HTTP::Get,
13
+ "POST" => Net::HTTP::Post,
14
+ "PATCH" => Net::HTTP::Patch,
15
+ "PUT" => Net::HTTP::Put,
16
+ "DELETE" => Net::HTTP::Delete
17
+ }.freeze
18
+
19
+ def call(method:, url:, headers:, body:, timeout:)
20
+ uri = URI(url)
21
+ request = REQUEST_CLASSES.fetch(method).new(uri)
22
+ headers.each { |name, value| request[name] = value }
23
+ request.body = body if body
24
+
25
+ http = Net::HTTP.new(uri.host, uri.port)
26
+ http.use_ssl = uri.scheme == "https"
27
+ http.open_timeout = timeout
28
+ http.read_timeout = timeout
29
+ http.write_timeout = timeout
30
+ response = http.start { |connection| connection.request(request) }
31
+
32
+ response_headers = {}
33
+ response.each_header { |name, value| response_headers[name] = value }
34
+ [response.code.to_i, response_headers, response.body.to_s]
35
+ end
36
+ end
37
+ end