hansho 0.1.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 +7 -0
- data/LICENSE +21 -0
- data/README.md +202 -0
- data/lib/hansho/client.rb +420 -0
- data/lib/hansho/errors.rb +65 -0
- data/lib/hansho/retry.rb +56 -0
- data/lib/hansho/transport.rb +32 -0
- data/lib/hansho/types.rb +45 -0
- data/lib/hansho/version.rb +8 -0
- data/lib/hansho/webhook.rb +171 -0
- data/lib/hansho.rb +18 -0
- metadata +56 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: b3623fd7d4b8e19d6223ec3d9d9f2e487c0ce509d150a95b7dd296f5c8952ab4
|
|
4
|
+
data.tar.gz: e1fac42de4990e258aa7c810438349524ac39fbd4ecdd828612e8796b323b52f
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: eb7e610018d8411a718b2c55a9401e9b0438c796cbd05703b3f5cb056ce43209f036e5966f1c7d80f7cf42d040567c66618d33515c167d9da7927b1a3e78c0f9
|
|
7
|
+
data.tar.gz: 46333af31dbd2f7b87f8a678d168156eecf8c1405060e923bdc8dd5e8a516b2595a5d9a4541077a3649165963da296f2b5d8538ed951cd1e7df7bfd2312aaa69
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Recodive
|
|
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,202 @@
|
|
|
1
|
+
# hansho (Ruby)
|
|
2
|
+
|
|
3
|
+
Ruby client for a Hansho hub. Ruby 3.1 or newer, no runtime dependencies (`net/http`,
|
|
4
|
+
`json`, `openssl` from the standard library).
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
gem install hansho # or: gem "hansho" in your Gemfile
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
See [../README.md](../README.md) for the model shared with the Go and Node SDKs.
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
```ruby
|
|
15
|
+
require "hansho"
|
|
16
|
+
|
|
17
|
+
hansho = Hansho::Client.new(base_url: "https://hub.example.com", api_key: ENV.fetch("HANSHO_API_KEY"))
|
|
18
|
+
|
|
19
|
+
hansho.put_channel("ops", name: "Operations", default_level: :active, max_level: :critical)
|
|
20
|
+
|
|
21
|
+
res = hansho.send_message(
|
|
22
|
+
external_user_id: "user-42",
|
|
23
|
+
channel: "ops",
|
|
24
|
+
title: "Disk full",
|
|
25
|
+
body: "db-1 is at 97%"
|
|
26
|
+
)
|
|
27
|
+
puts "#{res.message_id} #{res.status}" # msg_... queued
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Options: `max_retries:` (default 3, 0 disables), `timeout:` (seconds per attempt, default 30,
|
|
31
|
+
0 or nil disables), `user_agent:`, `transport:` (any object answering
|
|
32
|
+
`call(method:, url:, target:, headers:, body:, timeout:)` with a `Hansho::Response`, for proxies
|
|
33
|
+
and tests) and `sleeper:` (replaces the retry wait; meant for tests).
|
|
34
|
+
|
|
35
|
+
Arguments are keywords in `snake_case`; results are `Struct`s with the same names
|
|
36
|
+
(`res.message_id`, `ticket.expires_at` as a `Time`). `level` is a String or Symbol
|
|
37
|
+
(`:passive`, `:active`, `:time_sensitive` or `"time-sensitive"`, `:critical`, `:page`); a level the hub
|
|
38
|
+
does not know comes back as its 400. Nested hashes (`actions`, `page`, `alert`) take Symbol or String keys.
|
|
39
|
+
|
|
40
|
+
## Pairing
|
|
41
|
+
|
|
42
|
+
```ruby
|
|
43
|
+
ticket = hansho.create_pairing_ticket("user-42")
|
|
44
|
+
# Render ticket.qr as a QR code; the user scans it in the Hansho app.
|
|
45
|
+
# ticket.expires_at is 10 minutes out; the ticket works once.
|
|
46
|
+
# The hub then sends a pairing.created webhook.
|
|
47
|
+
|
|
48
|
+
hansho.unpair("user-42") # revokes every pairing of the user
|
|
49
|
+
hansho.kick("user-42") # the same call; the app tells the person that you ended it
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Audiences and groups
|
|
53
|
+
|
|
54
|
+
A channel or feed is open to everyone unless it has an `audience:`: `mode: :only` the listed users and groups, or
|
|
55
|
+
`mode: :except` them. Users are your external user ids (they may not have paired yet); groups are named lists you keep
|
|
56
|
+
on the hub, and every group an audience names must exist (a channel or feed naming a missing one is refused with a
|
|
57
|
+
400, `e.field == "audience.groups"`). The hub decides who has access and checks it on every request, so a change
|
|
58
|
+
applies at once.
|
|
59
|
+
|
|
60
|
+
```ruby
|
|
61
|
+
hansho.put_group("oncall", %w[alice bob]) # replaces the whole member list; get_group, delete_group
|
|
62
|
+
hansho.put_channel("pager", name: "Pager", default_level: :page, max_level: :page,
|
|
63
|
+
audience: { mode: :only, groups: ["oncall"] })
|
|
64
|
+
# Leaving audience: out keeps the one stored on the hub, so a republish never widens access.
|
|
65
|
+
# Send audience: { mode: :everyone } to open a channel up again.
|
|
66
|
+
|
|
67
|
+
# A feed uses its channel's audience unless it sets its own. Leaving both out keeps the stored ones.
|
|
68
|
+
hansho.put_feed("queue", template_id: "status", channel: "pager", data: { value: 3 })
|
|
69
|
+
settings = hansho.get_feed("queue") # the settings without the data; pass external_user_id: for a per-user feed
|
|
70
|
+
|
|
71
|
+
# Send to several users, or to everyone in the channel's audience. People outside it are not delivered to.
|
|
72
|
+
res = hansho.send_message(to_audience: true, channel: "pager", title: "DB down", body: "...")
|
|
73
|
+
res.recipients.each do |r|
|
|
74
|
+
next unless r.status == Hansho::RECIPIENT_NO_ACCESS # only with external_user_id(s): not in the audience, no message
|
|
75
|
+
end
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`send_message` takes exactly one of `external_user_id:`, `external_user_ids:` (at most 1000) and `to_audience: true`.
|
|
79
|
+
The answer has one `Recipient` per user in `res.recipients` (`message_id` is `nil` for `"no_access"`). For
|
|
80
|
+
`external_user_id:` the top-level fields describe that one recipient (`message_id` is `""`, `status` is
|
|
81
|
+
`"no_access"` and `devices` is 0 without access); for several users or an audience the top-level `message_id`,
|
|
82
|
+
`devices` and `status` are `nil`, `deliveries` is empty and each message is under `recipients`. `audience` comes
|
|
83
|
+
back from `get_channel` and `get_feed` as a Hash with Symbol keys.
|
|
84
|
+
|
|
85
|
+
Error codes: `Hansho::APIError::NO_ACCESS` (403, `start_activity` for a user outside the channel's audience) and
|
|
86
|
+
`Hansho::APIError::UNKNOWN_GROUP` (404), compared against `e.code`.
|
|
87
|
+
|
|
88
|
+
## Sending
|
|
89
|
+
|
|
90
|
+
```ruby
|
|
91
|
+
# A notification. The level defaults to the channel's default and is capped at its max.
|
|
92
|
+
hansho.send_message(
|
|
93
|
+
external_user_id: "user-42", channel: "ops", level: :time_sensitive,
|
|
94
|
+
title: "Deploy failed", body: "web-3 rolled back",
|
|
95
|
+
actions: [{ id: "retry", title: "Retry" }],
|
|
96
|
+
collapse_id: "deploy-web" # a later message with the same id replaces this one
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# A page repeats every interval_seconds until someone acknowledges it on any
|
|
100
|
+
# device, then the hub sends message.acked. Defaults: 120 s, 5 resends.
|
|
101
|
+
page = hansho.send_message(
|
|
102
|
+
external_user_id: "user-42", channel: "ops", level: :page,
|
|
103
|
+
title: "Primary DB down", body: "Failover did not complete",
|
|
104
|
+
page: { interval_seconds: 60, max_retries: 10 }
|
|
105
|
+
)
|
|
106
|
+
status = hansho.get_message(page.message_id) # status.status: queued, delivered, undeliverable, paging, acked, expired
|
|
107
|
+
|
|
108
|
+
# A templated message; data is sent exactly as given (its keys are never renamed).
|
|
109
|
+
hansho.put_template("status", 1, { type: "vstack", children: [{ type: "text", style: "headline", text: "{{title}}" }] })
|
|
110
|
+
hansho.send_message(external_user_id: "user-42", channel: "ops", template_id: "status", title: "Uptime", body: "99.98%", data: { title: "Uptime" })
|
|
111
|
+
|
|
112
|
+
# A Live Activity.
|
|
113
|
+
act = hansho.start_activity(external_user_id: "user-42", channel: "ops", template_id: "deploy", data: { progress: 0.1 })
|
|
114
|
+
hansho.update_activity(act.activity_id, data: { progress: 0.6 }, priority: 10)
|
|
115
|
+
hansho.end_activity(act.activity_id)
|
|
116
|
+
|
|
117
|
+
# A widget feed; omit external_user_id for one shared by all paired users. The title is the name the app's feed
|
|
118
|
+
# picker shows (it lists the feeds published for that person plus the shared ones).
|
|
119
|
+
hansho.put_feed("uptime", external_user_id: "user-42", template_id: "status", title: "Uptime", data: { title: "up" })
|
|
120
|
+
|
|
121
|
+
# A sound (audio/x-caf, audio/wav or audio/aiff, at most 1 MB).
|
|
122
|
+
hansho.put_sound("ding", "audio/wav", File.binread("ding.wav"))
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Ids may contain any characters except `.` and `..`: they are path-escaped. Empty, non-String and
|
|
126
|
+
dot ids raise `ArgumentError` before anything is sent.
|
|
127
|
+
|
|
128
|
+
## Webhooks
|
|
129
|
+
|
|
130
|
+
Set `HUB_WEBHOOK_URL` and `HUB_WEBHOOK_SECRET` on the hub. Verify the **raw** request body: a body a
|
|
131
|
+
framework parsed and you re-serialised will not match its signature, and `Hansho::Webhook.verify`
|
|
132
|
+
refuses anything that is not a String (`invalid_body`).
|
|
133
|
+
|
|
134
|
+
Rack / Sinatra (`request.body.read` is the raw body; the header is `HTTP_X_HANSHO_WEBHOOK_SIGNATURE`):
|
|
135
|
+
|
|
136
|
+
```ruby
|
|
137
|
+
post "/hansho-hook" do
|
|
138
|
+
event = Hansho::Webhook.verify(
|
|
139
|
+
secret: ENV.fetch("HANSHO_WEBHOOK_SECRET"),
|
|
140
|
+
header: request.env["HTTP_X_HANSHO_WEBHOOK_SIGNATURE"],
|
|
141
|
+
body: request.body.read
|
|
142
|
+
)
|
|
143
|
+
case event.type
|
|
144
|
+
when "message.acked" then puts "acknowledged: #{event.data.message_id}"
|
|
145
|
+
when "action" then puts "button #{event.data.action_id} on #{event.data.message_id}"
|
|
146
|
+
when "unknown" then puts "newer hub event: #{event.name}"
|
|
147
|
+
end
|
|
148
|
+
status 200
|
|
149
|
+
rescue Hansho::WebhookError
|
|
150
|
+
status 400 # non-2xx: the hub retries
|
|
151
|
+
end
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Rails: `request.raw_post` is the raw body, `request.headers["X-Hansho-Webhook-Signature"]` the header; skip
|
|
155
|
+
CSRF for the route.
|
|
156
|
+
|
|
157
|
+
`verify` accepts several `v1=` signatures (secret rotation), compares in constant time and rejects
|
|
158
|
+
timestamps more than 300 s from now (`tolerance:` in seconds changes it; `now:`, a `Time` or epoch
|
|
159
|
+
seconds, is injectable). `WebhookError#code` is one of `malformed_header`, `bad_signature`, `stale` (a valid
|
|
160
|
+
signature, replayed too late), `malformed_body`, `invalid_body`, `invalid_secret`. The returned
|
|
161
|
+
`Hansho::Webhook::Event` has `type`, `id`, `created_at` (a `Time`), `data` and the verified `raw` body.
|
|
162
|
+
Events: `pairing.created`, `pairing.revoked`, `message.delivered`, `message.undeliverable`,
|
|
163
|
+
`message.acked`, `message.dismissed`, `message.expired`, `action`, `activity.ended`, each with a `Struct` as
|
|
164
|
+
`data` (`snake_case` fields); anything else is `type: "unknown"` with the event name in `name` and the
|
|
165
|
+
parsed payload in `data`.
|
|
166
|
+
|
|
167
|
+
## Errors
|
|
168
|
+
|
|
169
|
+
```ruby
|
|
170
|
+
begin
|
|
171
|
+
hansho.send_message(**msg)
|
|
172
|
+
rescue Hansho::APIError => e
|
|
173
|
+
# e.status, e.code ("unknown_channel", "invalid_request", ...), e.field ("title"), e.retry_after (seconds) / e.retry_after_ms
|
|
174
|
+
rescue Hansho::NetworkError => e
|
|
175
|
+
# no answer at all: connection, timeout, unreadable response; see e.cause
|
|
176
|
+
end
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Both inherit from `Hansho::Error`. API keys, ticket values and message bodies are never put into error
|
|
180
|
+
messages, and the client's `inspect` does not show the key.
|
|
181
|
+
|
|
182
|
+
## Retries
|
|
183
|
+
|
|
184
|
+
`GET`, `PUT` and `DELETE` are retried on 429 and 503, up to `max_retries` times, waiting for
|
|
185
|
+
`Retry-After` (a wait over 60 s is raised to you as the error) or an exponential backoff with jitter.
|
|
186
|
+
`send_message` is never retried unless you pass an `idempotency_key:`; the hub does not deduplicate on it
|
|
187
|
+
yet, so a retried send is at-least-once. Activity updates (`PATCH`) are not retried. Connection errors and
|
|
188
|
+
timeouts are not retried.
|
|
189
|
+
|
|
190
|
+
## Development
|
|
191
|
+
|
|
192
|
+
```sh
|
|
193
|
+
bundle install
|
|
194
|
+
bundle exec rake test
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The unit tests load `../spec/api.json` and `../spec/webhook-vectors.json`. `test/integration_test.rb` runs
|
|
198
|
+
against a real hub and is skipped unless `HANSHO_HUB_URL` is set; `../scripts/run-integration.sh` sets that up.
|
|
199
|
+
|
|
200
|
+
## Licence
|
|
201
|
+
|
|
202
|
+
MIT, see [LICENSE](LICENSE). The hub itself is AGPL-3.0.
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "time"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module Hansho
|
|
8
|
+
# Client for a Hansho hub's sender API.
|
|
9
|
+
#
|
|
10
|
+
# hansho = Hansho::Client.new(base_url: "https://hub.example.com", api_key: ENV.fetch("HANSHO_API_KEY"))
|
|
11
|
+
# hansho.send_message(external_user_id: "user-42", channel: "ops", title: "Disk full", body: "db-1 is at 97%")
|
|
12
|
+
#
|
|
13
|
+
# Failures raise APIError (the hub answered with a non-2xx status) or NetworkError
|
|
14
|
+
# (no answer). Mistakes in the arguments raise ArgumentError before anything is sent.
|
|
15
|
+
class Client
|
|
16
|
+
MAX_SOUND_BYTES = 1 << 20
|
|
17
|
+
|
|
18
|
+
Call = Struct.new(:verb, :path, :body, :content_type, :retryable, :headers, keyword_init: true)
|
|
19
|
+
private_constant :Call
|
|
20
|
+
|
|
21
|
+
# +base_url+:: the hub's public URL.
|
|
22
|
+
# +api_key+:: a sender API key from `hub apikey create`.
|
|
23
|
+
# +max_retries+:: retries of GET/PUT/DELETE on 429 and 503. Default 3; 0 disables.
|
|
24
|
+
# +timeout+:: per-attempt connect/read/write timeout in seconds. Default 30; nil or 0 disables.
|
|
25
|
+
# +user_agent+:: replaces the default `hansho-ruby/VERSION`.
|
|
26
|
+
# +transport+:: see NetHTTPTransport; for proxies and tests.
|
|
27
|
+
# +sleeper+:: called with the number of seconds to wait between retries; for tests.
|
|
28
|
+
def initialize(base_url:, api_key:, max_retries: Retry::DEFAULT_MAX_RETRIES, timeout: 30, user_agent: nil, transport: nil, sleeper: nil)
|
|
29
|
+
raise ArgumentError, "hansho: base_url is required" unless base_url.is_a?(String) && !base_url.empty?
|
|
30
|
+
raise ArgumentError, "hansho: api_key is required" unless api_key.is_a?(String) && !api_key.empty?
|
|
31
|
+
raise ArgumentError, "hansho: api_key must not contain control characters" if control?(api_key)
|
|
32
|
+
|
|
33
|
+
uri = URI.parse(base_url)
|
|
34
|
+
raise ArgumentError, "hansho: base_url must be an http or https URL" unless %w[http https].include?(uri.scheme) && uri.host
|
|
35
|
+
|
|
36
|
+
@base_url = base_url.sub(%r{/+\z}, "")
|
|
37
|
+
@uri = uri
|
|
38
|
+
@prefix = uri.path.sub(%r{/+\z}, "")
|
|
39
|
+
@api_key = api_key
|
|
40
|
+
@max_retries = [max_retries.to_i, 0].max
|
|
41
|
+
@timeout = timeout
|
|
42
|
+
@user_agent = user_agent || "#{NAME}-ruby/#{VERSION}"
|
|
43
|
+
@transport = transport || NetHTTPTransport.new
|
|
44
|
+
@sleeper = sleeper || ->(seconds) { sleep(seconds) }
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Keeps the API key out of logs.
|
|
48
|
+
def inspect
|
|
49
|
+
"#<#{self.class.name} base_url=#{@base_url.inspect}>"
|
|
50
|
+
end
|
|
51
|
+
alias to_s inspect
|
|
52
|
+
|
|
53
|
+
def to_json(*args)
|
|
54
|
+
{ base_url: @base_url }.to_json(*args)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# --- pairing -----------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
# Creates a single-use pairing ticket (valid 10 minutes). Render +qr+ as a QR
|
|
60
|
+
# code for the user to scan in the Hansho app. Returns a PairingTicket.
|
|
61
|
+
def create_pairing_ticket(external_user_id)
|
|
62
|
+
raise ArgumentError, "hansho: id must not be empty" if external_user_id.to_s.empty?
|
|
63
|
+
|
|
64
|
+
w = json(:post, "/api/v1/pairing-tickets", { external_user_id: external_user_id })
|
|
65
|
+
PairingTicket.new(ticket: w["ticket"], qr: w["qr"], expires_at: time(w["expires_at"]))
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Revokes every pairing of the user.
|
|
69
|
+
def unpair(external_user_id)
|
|
70
|
+
json(:delete, "/api/v1/users/#{seg(external_user_id)}/pairings")
|
|
71
|
+
nil
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Ends the user's whole pairing, on every device: +unpair+ under its sender-side name. The app tells the person
|
|
75
|
+
# that the sender ended it (a 401 pairing_revoked with reason "kicked"), where an unpair they did themselves
|
|
76
|
+
# carries no reason. There is no block list; a new ticket pairs them again.
|
|
77
|
+
def kick(external_user_id)
|
|
78
|
+
unpair(external_user_id)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# --- catalog -----------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
# Creates or replaces a channel. +actions+ is an Array of Hashes
|
|
84
|
+
# (`{ id: "ack", title: "Acknowledge", ack: true }`). +audience+ says who may use the channel:
|
|
85
|
+
# `{ mode: :only, users: ["alice"], groups: ["oncall"] }` (+mode+ is :everyone, :only or :except; users are your
|
|
86
|
+
# external user ids, groups must exist). Leaving it out keeps the audience stored on the hub (a new channel is
|
|
87
|
+
# open to everyone); pass `{ mode: :everyone }` to open a channel up again.
|
|
88
|
+
def put_channel(id, name:, default_level:, max_level:, sound: nil, template_id: nil, thread: nil, actions: nil, audience: nil)
|
|
89
|
+
wire = {
|
|
90
|
+
name: name, default_level: level_to_wire(default_level), max_level: level_to_wire(max_level),
|
|
91
|
+
sound: sound, template_id: template_id, thread: thread, actions: actions_to_wire(actions),
|
|
92
|
+
audience: audience_to_wire(audience)
|
|
93
|
+
}.compact
|
|
94
|
+
json(:put, "/api/v1/channels/#{seg(id)}", wire)
|
|
95
|
+
nil
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Returns a Channel.
|
|
99
|
+
def get_channel(id)
|
|
100
|
+
w = json(:get, "/api/v1/channels/#{seg(id)}")
|
|
101
|
+
Channel.new(
|
|
102
|
+
name: w["name"], default_level: w["default_level"], max_level: w["max_level"], sound: w["sound"],
|
|
103
|
+
template_id: w["template_id"], thread: w["thread"], actions: actions_from_wire(w["actions"]),
|
|
104
|
+
audience: audience_from_wire(w["audience"])
|
|
105
|
+
)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# --- groups ------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
# Creates a group or replaces its whole member list (external user ids, who may not have paired yet).
|
|
111
|
+
# Audiences that name the group follow at once. Ids match `[A-Za-z0-9][A-Za-z0-9_-]{0,63}`. Returns a Group.
|
|
112
|
+
def put_group(id, members)
|
|
113
|
+
raise ArgumentError, "hansho: members must be an Array" unless members.is_a?(Array)
|
|
114
|
+
|
|
115
|
+
group_from_wire(json(:put, "/api/v1/groups/#{seg(id)}", { members: members }), id)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# Returns a Group; a missing one is an APIError with code APIError::UNKNOWN_GROUP.
|
|
119
|
+
def get_group(id)
|
|
120
|
+
group_from_wire(json(:get, "/api/v1/groups/#{seg(id)}"), id)
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# An audience that still names the group matches nobody through it.
|
|
124
|
+
def delete_group(id)
|
|
125
|
+
json(:delete, "/api/v1/groups/#{seg(id)}")
|
|
126
|
+
nil
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def delete_channel(id)
|
|
130
|
+
json(:delete, "/api/v1/channels/#{seg(id)}")
|
|
131
|
+
nil
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Stores a template version; the version must increase. +body+ is the template
|
|
135
|
+
# as Hash/Array (anything JSON can express).
|
|
136
|
+
def put_template(id, version, body)
|
|
137
|
+
json(:put, "/api/v1/templates/#{seg(id)}", { version: version, body: body })
|
|
138
|
+
nil
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# Uploads a sound (+audio/x-caf+, +audio/wav+ or +audio/aiff+, at most 1 MB). Returns a SoundResult.
|
|
142
|
+
def put_sound(id, content_type, bytes)
|
|
143
|
+
path = "/api/v1/sounds/#{seg(id)}"
|
|
144
|
+
raise ArgumentError, "hansho: bytes must be a String" unless bytes.is_a?(String)
|
|
145
|
+
raise ArgumentError, "hansho: sound exceeds 1 MB" if bytes.bytesize > MAX_SOUND_BYTES
|
|
146
|
+
raise ArgumentError, "hansho: content_type is required" unless content_type.is_a?(String) && !content_type.empty? && !control?(content_type)
|
|
147
|
+
|
|
148
|
+
w = send_call(Call.new(verb: "PUT", path: path, body: bytes.b, content_type: content_type, retryable: true))
|
|
149
|
+
SoundResult.new(id: w["id"], filename: w["filename"], sha256: w["sha256"], size: w["size"])
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# --- messages ----------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
# Sends a notification, or a page when +level+ is +:page+. +level+ is a String or
|
|
155
|
+
# Symbol (+:time_sensitive+ is read as "time-sensitive"); it defaults to the
|
|
156
|
+
# channel's default and is capped at its max. +data+ is sent as given (its keys
|
|
157
|
+
# are never renamed). +page+ is `{ interval_seconds: 60, max_retries: 3 }`.
|
|
158
|
+
#
|
|
159
|
+
# It is never retried automatically (a repeat would notify twice) unless you pass
|
|
160
|
+
# an +idempotency_key+, which is sent as the Idempotency-Key header, never in the
|
|
161
|
+
# body. The hub does not deduplicate on it yet, so a retried send is at-least-once.
|
|
162
|
+
#
|
|
163
|
+
# Give exactly one target: +external_user_id+, +external_user_ids+ (an Array, at most 1000) or +to_audience: true+
|
|
164
|
+
# (every paired user in the channel's audience, resolved when you send). Users outside the audience are not
|
|
165
|
+
# delivered to: their MessageResult#recipients entry has status RECIPIENT_NO_ACCESS.
|
|
166
|
+
# Returns a MessageResult.
|
|
167
|
+
def send_message(channel:, title:, body:, external_user_id: nil, external_user_ids: nil, to_audience: nil, level: nil,
|
|
168
|
+
subtitle: nil, image_url: nil, template_id: nil, data: nil, sound: nil, actions: nil, collapse_id: nil,
|
|
169
|
+
page: nil, idempotency_key: nil)
|
|
170
|
+
unless external_user_ids.nil? || external_user_ids.is_a?(Array)
|
|
171
|
+
raise ArgumentError, "hansho: external_user_ids must be an Array"
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
wire = {
|
|
175
|
+
external_user_id: external_user_id, external_user_ids: external_user_ids, to_audience: to_audience ? true : nil,
|
|
176
|
+
channel: channel, level: level_to_wire(level), title: title, subtitle: subtitle,
|
|
177
|
+
body: body, image_url: image_url, template_id: template_id, data: data, sound: sound,
|
|
178
|
+
actions: actions_to_wire(actions), collapse_id: collapse_id, page: page_to_wire(page)
|
|
179
|
+
}.compact
|
|
180
|
+
call = Call.new(verb: "POST", path: "/api/v1/messages", body: JSON.generate(wire), content_type: "application/json", retryable: false)
|
|
181
|
+
unless idempotency_key.nil? || idempotency_key == ""
|
|
182
|
+
raise ArgumentError, "hansho: idempotency_key must not contain control characters" if control?(idempotency_key.to_s)
|
|
183
|
+
|
|
184
|
+
call.retryable = true
|
|
185
|
+
call.headers = { "Idempotency-Key" => idempotency_key.to_s }
|
|
186
|
+
end
|
|
187
|
+
w = send_call(call)
|
|
188
|
+
MessageResult.new(message_id: w["message_id"], level: w["level"], devices: w["devices"], status: w["status"],
|
|
189
|
+
deliveries: deliveries_from_wire(w["deliveries"]), recipients: recipients_from_wire(w["recipients"]))
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Returns a MessageStatus.
|
|
193
|
+
def get_message(id)
|
|
194
|
+
w = json(:get, "/api/v1/messages/#{seg(id)}")
|
|
195
|
+
MessageStatus.new(message_id: w["message_id"], status: w["status"], level: w["level"], attempts: w["attempts"],
|
|
196
|
+
deliveries: deliveries_from_wire(w["deliveries"]), acked_at: time(w["acked_at"]))
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# --- live activities and feeds -----------------------------------------
|
|
200
|
+
|
|
201
|
+
# Starts a Live Activity. +alert+ is `{ title:, body: }`. Returns an ActivityStarted.
|
|
202
|
+
def start_activity(external_user_id:, channel:, template_id:, data:, alert: nil)
|
|
203
|
+
wire = { external_user_id: external_user_id, channel: channel, template_id: template_id, data: data,
|
|
204
|
+
alert: alert_to_wire(alert) }.compact
|
|
205
|
+
w = json(:post, "/api/v1/activities", wire)
|
|
206
|
+
ActivityStarted.new(activity_id: w["activity_id"], devices: w["devices"])
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# Not retried automatically. +priority+ is 5 (default) or 10. Returns an ActivityUpdated.
|
|
210
|
+
def update_activity(id, data:, priority: nil, alert: nil)
|
|
211
|
+
wire = { data: data, priority: priority, alert: alert_to_wire(alert) }.compact
|
|
212
|
+
w = json(:patch, "/api/v1/activities/#{seg(id)}", wire)
|
|
213
|
+
ActivityUpdated.new(activity_id: w["activity_id"], update: w["update"])
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def end_activity(id)
|
|
217
|
+
json(:delete, "/api/v1/activities/#{seg(id)}")
|
|
218
|
+
nil
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Publishes a widget feed; omit +external_user_id+ for one shared by all paired
|
|
222
|
+
# users. +title+ is the name the app's feed picker shows. The feed uses the audience of +channel+ unless it sets its
|
|
223
|
+
# own +audience+ (see #put_channel); leaving both out keeps the values stored on the hub. Returns a FeedResult.
|
|
224
|
+
def put_feed(id, template_id:, data:, external_user_id: nil, title: nil, channel: nil, audience: nil)
|
|
225
|
+
wire = { external_user_id: external_user_id, template_id: template_id, title: title, channel: channel,
|
|
226
|
+
audience: audience_to_wire(audience), data: data }.compact
|
|
227
|
+
w = json(:put, "/api/v1/feeds/#{seg(id)}", wire)
|
|
228
|
+
FeedResult.new(feed_id: w["feed_id"], devices: w["devices"])
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
# A feed's settings without its data; omit +external_user_id+ for the feed shared by all users. Returns a FeedSettings.
|
|
232
|
+
def get_feed(id, external_user_id: nil)
|
|
233
|
+
query = external_user_id.nil? || external_user_id == "" ? "" : "?external_user_id=#{URI.encode_www_form_component(external_user_id.to_s)}"
|
|
234
|
+
w = json(:get, "/api/v1/feeds/#{seg(id)}#{query}")
|
|
235
|
+
FeedSettings.new(feed_id: w["feed_id"], external_user_id: w["external_user_id"], template_id: w["template_id"],
|
|
236
|
+
title: w["title"], channel: w["channel"], audience: audience_from_wire(w["audience"]),
|
|
237
|
+
updated_at: w["updated_at"])
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
private
|
|
241
|
+
|
|
242
|
+
# Escapes one path segment; rejects ids that would not stay in their collection.
|
|
243
|
+
def seg(id)
|
|
244
|
+
raise ArgumentError, "hansho: id must be a String" unless id.is_a?(String)
|
|
245
|
+
raise ArgumentError, "hansho: id must not be empty" if id.empty?
|
|
246
|
+
raise ArgumentError, %(hansho: id must not be "#{id}") if [".", ".."].include?(id)
|
|
247
|
+
|
|
248
|
+
id.b.gsub(/[^A-Za-z0-9\-_.~]/n) { |c| format("%%%02X", c.ord) }
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
def control?(string)
|
|
252
|
+
string.match?(/[\x00-\x1f\x7f]/)
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
def symbolize(hash, what)
|
|
256
|
+
raise ArgumentError, "hansho: #{what} must be a Hash" unless hash.is_a?(Hash)
|
|
257
|
+
|
|
258
|
+
hash.transform_keys(&:to_sym)
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
def level_to_wire(level)
|
|
262
|
+
level&.to_s&.tr("_", "-")
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
def actions_to_wire(actions)
|
|
266
|
+
return nil if actions.nil?
|
|
267
|
+
raise ArgumentError, "hansho: actions must be an Array" unless actions.is_a?(Array)
|
|
268
|
+
|
|
269
|
+
actions.map do |a|
|
|
270
|
+
a = symbolize(a, "action")
|
|
271
|
+
{ id: a[:id], title: a[:title], ack: a[:ack], kind: a[:kind] }.compact
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
def actions_from_wire(raw)
|
|
276
|
+
return nil unless raw.is_a?(Array)
|
|
277
|
+
|
|
278
|
+
raw.map { |a| { id: a["id"], title: a["title"], ack: a["ack"], kind: a["kind"] }.compact }
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
def page_to_wire(page)
|
|
282
|
+
return nil if page.nil?
|
|
283
|
+
|
|
284
|
+
p = symbolize(page, "page")
|
|
285
|
+
{ interval_s: p[:interval_seconds], max_retries: p[:max_retries] }.compact
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
def alert_to_wire(alert)
|
|
289
|
+
return nil if alert.nil?
|
|
290
|
+
|
|
291
|
+
a = symbolize(alert, "alert")
|
|
292
|
+
{ title: a[:title], body: a[:body] }.compact
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
def audience_to_wire(audience)
|
|
296
|
+
return nil if audience.nil?
|
|
297
|
+
|
|
298
|
+
a = symbolize(audience, "audience")
|
|
299
|
+
%i[users groups].each do |key|
|
|
300
|
+
raise ArgumentError, "hansho: audience #{key} must be an Array" unless a[key].nil? || a[key].is_a?(Array)
|
|
301
|
+
end
|
|
302
|
+
{ mode: a[:mode]&.to_s, users: non_empty(a[:users]), groups: non_empty(a[:groups]) }.compact
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def non_empty(list)
|
|
306
|
+
list.nil? || list.empty? ? nil : list
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def audience_from_wire(raw)
|
|
310
|
+
return nil unless raw.is_a?(Hash)
|
|
311
|
+
|
|
312
|
+
{ mode: raw["mode"], users: raw["users"].is_a?(Array) ? raw["users"] : [], groups: raw["groups"].is_a?(Array) ? raw["groups"] : [] }
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
def group_from_wire(w, id)
|
|
316
|
+
Group.new(id: w["id"] || id, members: w["members"].is_a?(Array) ? w["members"] : [])
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
def recipients_from_wire(raw)
|
|
320
|
+
return [] unless raw.is_a?(Array)
|
|
321
|
+
|
|
322
|
+
raw.select { |r| r.is_a?(Hash) }.map do |r|
|
|
323
|
+
Recipient.new(external_user_id: r["external_user_id"], message_id: r["message_id"], status: r["status"],
|
|
324
|
+
devices: r["devices"] || 0, deliveries: deliveries_from_wire(r["deliveries"]))
|
|
325
|
+
end
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
def deliveries_from_wire(raw)
|
|
329
|
+
return [] unless raw.is_a?(Array)
|
|
330
|
+
|
|
331
|
+
raw.map do |d|
|
|
332
|
+
err = d["error"]
|
|
333
|
+
Delivery.new(device_id: d["device_id"], status: d["status"], error: err.nil? || err == "" ? nil : err)
|
|
334
|
+
end
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
def time(value)
|
|
338
|
+
value.is_a?(String) ? Time.iso8601(value) : nil
|
|
339
|
+
rescue ArgumentError
|
|
340
|
+
nil
|
|
341
|
+
end
|
|
342
|
+
|
|
343
|
+
def json(method, path, body = nil)
|
|
344
|
+
verb = method.to_s.upcase
|
|
345
|
+
call = Call.new(verb: verb, path: path, retryable: Retry.idempotent?(verb))
|
|
346
|
+
unless body.nil?
|
|
347
|
+
call.body = JSON.generate(body)
|
|
348
|
+
call.content_type = "application/json"
|
|
349
|
+
end
|
|
350
|
+
send_call(call)
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
def send_call(call)
|
|
354
|
+
attempt = 0
|
|
355
|
+
loop do
|
|
356
|
+
res = round_trip(call)
|
|
357
|
+
return parse_success(call, res) if res.status.between?(200, 299)
|
|
358
|
+
|
|
359
|
+
err = api_error(call, res)
|
|
360
|
+
raise err if !call.retryable || !Retry.retryable_status?(res.status) || attempt >= @max_retries
|
|
361
|
+
|
|
362
|
+
wait_ms = err.retry_after_ms&.positive? ? err.retry_after_ms : Retry.backoff_ms(attempt)
|
|
363
|
+
raise err if wait_ms > Retry::MAX_WAIT_MS
|
|
364
|
+
|
|
365
|
+
@sleeper.call(wait_ms / 1000.0)
|
|
366
|
+
attempt += 1
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
def round_trip(call)
|
|
371
|
+
headers = { "Authorization" => "Bearer #{@api_key}", "Accept" => "application/json", "User-Agent" => @user_agent }
|
|
372
|
+
headers.merge!(call.headers) if call.headers
|
|
373
|
+
headers["Content-Type"] = call.content_type if call.content_type
|
|
374
|
+
begin
|
|
375
|
+
@transport.call(method: call.verb, url: @uri, target: @prefix + call.path, headers: headers, body: call.body, timeout: @timeout)
|
|
376
|
+
rescue StandardError => e
|
|
377
|
+
safe = redact(e)
|
|
378
|
+
raise NetworkError.new(call.verb, call.path, safe), cause: safe
|
|
379
|
+
end
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
def redact(error)
|
|
383
|
+
return error unless error.message.include?(@api_key)
|
|
384
|
+
|
|
385
|
+
RuntimeError.new(error.message.gsub(@api_key, "[redacted]"))
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
# The body as valid UTF-8 text; bytes that are not UTF-8 become U+FFFD instead of raising.
|
|
389
|
+
def text_of(res)
|
|
390
|
+
res.body.to_s.dup.force_encoding(Encoding::UTF_8).scrub
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
def parse_success(call, res)
|
|
394
|
+
text = text_of(res)
|
|
395
|
+
return {} if text.strip.empty?
|
|
396
|
+
|
|
397
|
+
parsed = JSON.parse(text)
|
|
398
|
+
parsed.is_a?(Hash) ? parsed : {}
|
|
399
|
+
rescue JSON::ParserError
|
|
400
|
+
raise NetworkError.new(call.verb, call.path, "invalid JSON in response")
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
def api_error(call, res)
|
|
404
|
+
code = field = detail = nil
|
|
405
|
+
begin
|
|
406
|
+
p = JSON.parse(text_of(res))
|
|
407
|
+
if p.is_a?(Hash)
|
|
408
|
+
code = p["error"] if p["error"].is_a?(String)
|
|
409
|
+
field = p["field"] if p["field"].is_a?(String) && !p["field"].empty?
|
|
410
|
+
detail = p["message"].gsub(@api_key, "[redacted]") if p["message"].is_a?(String)
|
|
411
|
+
end
|
|
412
|
+
rescue JSON::ParserError
|
|
413
|
+
nil # not JSON (proxy error page): status only
|
|
414
|
+
end
|
|
415
|
+
retry_after = Retry.parse_retry_after(res.headers["retry-after"])
|
|
416
|
+
APIError.new(method: call.verb, path: call.path, status: res.status, code: code, field: field,
|
|
417
|
+
retry_after_ms: retry_after&.positive? ? retry_after : nil, detail: detail)
|
|
418
|
+
end
|
|
419
|
+
end
|
|
420
|
+
end
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Hansho
|
|
4
|
+
# Base class of everything this gem raises on purpose (argument mistakes raise ArgumentError).
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# A non-2xx answer from the hub. The API key never appears in it.
|
|
8
|
+
class APIError < Error
|
|
9
|
+
# 403: the user is outside the channel's audience (+start_activity+ for such a user).
|
|
10
|
+
NO_ACCESS = "no_access"
|
|
11
|
+
# 404: the group does not exist (+get_group+, +delete_group+).
|
|
12
|
+
UNKNOWN_GROUP = "unknown_group"
|
|
13
|
+
|
|
14
|
+
# HTTP status code.
|
|
15
|
+
attr_reader :status
|
|
16
|
+
# The hub's error code, e.g. "invalid_request"; "" when the body was not JSON.
|
|
17
|
+
attr_reader :code
|
|
18
|
+
# The offending request field for validation failures, else nil.
|
|
19
|
+
attr_reader :field
|
|
20
|
+
# Parsed Retry-After in milliseconds, else nil.
|
|
21
|
+
attr_reader :retry_after_ms
|
|
22
|
+
# The hub's validation message, when present.
|
|
23
|
+
attr_reader :detail
|
|
24
|
+
|
|
25
|
+
def initialize(method:, path:, status:, code: nil, field: nil, retry_after_ms: nil, detail: nil)
|
|
26
|
+
text = "hansho: #{method} #{path}: #{status}"
|
|
27
|
+
text += " #{code}" if code && !code.empty?
|
|
28
|
+
text += " (field #{field})" if field && !field.empty?
|
|
29
|
+
text += " (retry after #{retry_after_ms} ms)" if retry_after_ms
|
|
30
|
+
super(text)
|
|
31
|
+
@status = status
|
|
32
|
+
@code = code || ""
|
|
33
|
+
@field = field && !field.empty? ? field : nil
|
|
34
|
+
@retry_after_ms = retry_after_ms
|
|
35
|
+
@detail = detail
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Retry-After in seconds, else nil.
|
|
39
|
+
def retry_after
|
|
40
|
+
retry_after_ms && retry_after_ms / 1000.0
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# No HTTP answer arrived: connection failure, timeout or an unreadable response.
|
|
45
|
+
# The original exception is in #cause.
|
|
46
|
+
class NetworkError < Error
|
|
47
|
+
def initialize(method, path, cause)
|
|
48
|
+
message = cause.respond_to?(:message) ? cause.message : cause.to_s
|
|
49
|
+
super("hansho: #{method} #{path}: #{message}")
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Raised by Webhook.verify; check #code.
|
|
54
|
+
class WebhookError < Error
|
|
55
|
+
CODES = %w[malformed_header bad_signature stale malformed_body invalid_body invalid_secret].freeze
|
|
56
|
+
|
|
57
|
+
# One of CODES.
|
|
58
|
+
attr_reader :code
|
|
59
|
+
|
|
60
|
+
def initialize(code, message)
|
|
61
|
+
super(message)
|
|
62
|
+
@code = code
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
data/lib/hansho/retry.rb
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
module Hansho
|
|
6
|
+
# Retry policy shared by the client: only 429 and 503, at most 3 times.
|
|
7
|
+
module Retry
|
|
8
|
+
DEFAULT_MAX_RETRIES = 3
|
|
9
|
+
BASE_BACKOFF_MS = 250
|
|
10
|
+
MAX_BACKOFF_MS = 8000
|
|
11
|
+
# A longer Retry-After is raised to the caller instead of waited out.
|
|
12
|
+
MAX_WAIT_MS = 60_000
|
|
13
|
+
|
|
14
|
+
module_function
|
|
15
|
+
|
|
16
|
+
# Only GET, PUT and DELETE may be repeated without side effects.
|
|
17
|
+
def idempotent?(method)
|
|
18
|
+
%w[GET PUT DELETE].include?(method)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def retryable_status?(status)
|
|
22
|
+
status == 429 || status == 503
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Exponential backoff with jitter in [d/2, d], in milliseconds.
|
|
26
|
+
def backoff_ms(attempt, random: Kernel)
|
|
27
|
+
d = [BASE_BACKOFF_MS * (2**[attempt, 10].min), MAX_BACKOFF_MS].min
|
|
28
|
+
(d / 2.0) + (random.rand * (d / 2.0))
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Reads delay-seconds or an HTTP date; returns nil when absent or unusable.
|
|
32
|
+
# The result is in milliseconds.
|
|
33
|
+
def parse_retry_after(value, now: Time.now)
|
|
34
|
+
return nil if value.nil?
|
|
35
|
+
|
|
36
|
+
v = value.strip
|
|
37
|
+
return nil if v.empty?
|
|
38
|
+
return (Float(v) * 1000).round if v.match?(/\A\d+(\.\d+)?\z/)
|
|
39
|
+
|
|
40
|
+
at = parse_date(v)
|
|
41
|
+
return nil unless at
|
|
42
|
+
|
|
43
|
+
[((at - now) * 1000).round, 0].max
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def parse_date(text)
|
|
47
|
+
Time.httpdate(text)
|
|
48
|
+
rescue ArgumentError
|
|
49
|
+
begin
|
|
50
|
+
Time.rfc2822(text)
|
|
51
|
+
rescue ArgumentError
|
|
52
|
+
nil
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
|
|
6
|
+
module Hansho
|
|
7
|
+
# What a transport returns. #headers has lower-case names.
|
|
8
|
+
Response = Struct.new(:status, :headers, :body, keyword_init: true)
|
|
9
|
+
|
|
10
|
+
# The default transport, on Net::HTTP. A transport is any object that answers
|
|
11
|
+
# `call(method:, url:, target:, headers:, body:, timeout:)` with a Response and
|
|
12
|
+
# raises on connection failure; pass your own to Client.new(transport: ...) for
|
|
13
|
+
# proxies or tests. +url+ is the base URI (scheme, host, port), +target+ the request path.
|
|
14
|
+
class NetHTTPTransport
|
|
15
|
+
def call(method:, url:, target:, headers:, body:, timeout:)
|
|
16
|
+
http = Net::HTTP.new(url.hostname, url.port)
|
|
17
|
+
http.use_ssl = url.scheme == "https"
|
|
18
|
+
# Net::HTTP would silently repeat idempotent requests after a reset or timeout; retries are the client's call.
|
|
19
|
+
http.max_retries = 0
|
|
20
|
+
limit = timeout&.positive? ? timeout : nil
|
|
21
|
+
http.open_timeout = limit
|
|
22
|
+
http.read_timeout = limit
|
|
23
|
+
http.write_timeout = limit
|
|
24
|
+
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, target, headers)
|
|
25
|
+
req.body = body unless body.nil?
|
|
26
|
+
res = http.start { |h| h.request(req) }
|
|
27
|
+
out = {}
|
|
28
|
+
res.each_header { |k, v| out[k.downcase] = v }
|
|
29
|
+
Response.new(status: res.code.to_i, headers: out, body: res.body.to_s.dup.force_encoding(Encoding::UTF_8))
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
data/lib/hansho/types.rb
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Hansho
|
|
4
|
+
# How loudly a message is presented, lowest to highest.
|
|
5
|
+
LEVELS = %w[passive active time-sensitive critical page].freeze
|
|
6
|
+
|
|
7
|
+
# A pairing ticket. Render #qr as a QR code for the user to scan in the Hansho app.
|
|
8
|
+
PairingTicket = Struct.new(:ticket, :qr, :expires_at, keyword_init: true)
|
|
9
|
+
|
|
10
|
+
# A channel as stored on the hub. #actions is an Array of Hashes with the keys :id, :title and optionally :ack, :kind.
|
|
11
|
+
# #audience is a Hash `{ mode:, users:, groups: }` (see Client#put_channel); the hub always returns one.
|
|
12
|
+
Channel = Struct.new(:name, :default_level, :max_level, :sound, :template_id, :thread, :actions, :audience, keyword_init: true)
|
|
13
|
+
|
|
14
|
+
# A named list of users, used in audiences. #members are external user ids.
|
|
15
|
+
Group = Struct.new(:id, :members, keyword_init: true)
|
|
16
|
+
|
|
17
|
+
# The #status of a Recipient outside the channel's audience: it got no message.
|
|
18
|
+
RECIPIENT_NO_ACCESS = "no_access"
|
|
19
|
+
|
|
20
|
+
# The outcome of a send for one user. #status is the message status (queued, undeliverable) or RECIPIENT_NO_ACCESS,
|
|
21
|
+
# in which case #message_id is nil. #devices is 0 and #deliveries empty when there is no message.
|
|
22
|
+
Recipient = Struct.new(:external_user_id, :message_id, :status, :devices, :deliveries, keyword_init: true)
|
|
23
|
+
|
|
24
|
+
# One device a message was handed to. #error is nil unless the delivery failed.
|
|
25
|
+
Delivery = Struct.new(:device_id, :status, :error, keyword_init: true)
|
|
26
|
+
|
|
27
|
+
# The answer to #send_message. #recipients has one Recipient per user (empty when the hub predates audiences).
|
|
28
|
+
# For a send to +external_user_id+ the other fields describe that one recipient (#message_id is "", #status is
|
|
29
|
+
# "no_access" and #devices is 0 when the user is outside the audience); for +external_user_ids+ or +to_audience+
|
|
30
|
+
# #message_id, #devices and #status are nil and #deliveries is empty: each message is under #recipients.
|
|
31
|
+
MessageResult = Struct.new(:message_id, :level, :devices, :status, :deliveries, :recipients, keyword_init: true)
|
|
32
|
+
|
|
33
|
+
# The answer to #get_message. #status is one of queued, delivered, undeliverable, paging, acked, expired.
|
|
34
|
+
# #acked_at is a Time or nil.
|
|
35
|
+
MessageStatus = Struct.new(:message_id, :status, :level, :attempts, :deliveries, :acked_at, keyword_init: true)
|
|
36
|
+
|
|
37
|
+
ActivityStarted = Struct.new(:activity_id, :devices, keyword_init: true)
|
|
38
|
+
ActivityUpdated = Struct.new(:activity_id, :update, keyword_init: true)
|
|
39
|
+
FeedResult = Struct.new(:feed_id, :devices, keyword_init: true)
|
|
40
|
+
|
|
41
|
+
# A feed without its data, from Client#get_feed. #audience is nil while the feed inherits its channel's.
|
|
42
|
+
FeedSettings = Struct.new(:feed_id, :external_user_id, :template_id, :title, :channel, :audience, :updated_at,
|
|
43
|
+
keyword_init: true)
|
|
44
|
+
SoundResult = Struct.new(:id, :filename, :sha256, :size, keyword_init: true)
|
|
45
|
+
end
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "openssl"
|
|
5
|
+
|
|
6
|
+
module Hansho
|
|
7
|
+
# Verifies and parses the hub's webhooks.
|
|
8
|
+
#
|
|
9
|
+
# event = Hansho::Webhook.verify(secret: ENV.fetch("HANSHO_WEBHOOK_SECRET"), header: signature_header, body: raw_body)
|
|
10
|
+
# event.type # => "message.acked"
|
|
11
|
+
# event.data.message_id
|
|
12
|
+
module Webhook
|
|
13
|
+
# `X-Hansho-Webhook-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, t + "." + body)>`
|
|
14
|
+
SIGNATURE_HEADER = "X-Hansho-Webhook-Signature"
|
|
15
|
+
# Default allowed distance between the signed timestamp and now, in seconds.
|
|
16
|
+
DEFAULT_TOLERANCE = 300
|
|
17
|
+
|
|
18
|
+
PairingCreated = Struct.new(:pairing_id, :external_user_id, :device_name, keyword_init: true)
|
|
19
|
+
# +by+ is who revoked: "sender", "device" or "relay".
|
|
20
|
+
PairingRevoked = Struct.new(:pairing_id, :external_user_id, :by, keyword_init: true)
|
|
21
|
+
MessageDelivered = Struct.new(:message_id, :external_user_id, :channel, :level, :devices, keyword_init: true)
|
|
22
|
+
# +reason+ is "no_devices" or "all_deliveries_failed".
|
|
23
|
+
MessageUndeliverable = Struct.new(:message_id, :external_user_id, :channel, :reason, keyword_init: true)
|
|
24
|
+
MessageAcked = Struct.new(:message_id, :external_user_id, :device_id, keyword_init: true)
|
|
25
|
+
# The person swiped away a message that asked to be acknowledged, without acknowledging it.
|
|
26
|
+
MessageDismissed = Struct.new(:message_id, :external_user_id, :device_id, keyword_init: true)
|
|
27
|
+
MessageExpired = Struct.new(:message_id, :external_user_id, :channel, :attempts, keyword_init: true)
|
|
28
|
+
# A button press. +text+ is the reply of a text action, else nil.
|
|
29
|
+
ActionTaken = Struct.new(:message_id, :action_id, :device_id, :external_user_id, :text, keyword_init: true)
|
|
30
|
+
ActivityEnded = Struct.new(:activity_id, :external_user_id, :channel, :reason, keyword_init: true)
|
|
31
|
+
|
|
32
|
+
# A verified webhook. +type+ is the event name ("message.acked", ...) or "unknown"
|
|
33
|
+
# for an event this SDK does not know; then +name+ is the name as sent and +data+
|
|
34
|
+
# the parsed JSON payload, untouched. +raw+ is the verified request body.
|
|
35
|
+
Event = Struct.new(:type, :id, :created_at, :data, :raw, :name, keyword_init: true) do
|
|
36
|
+
def unknown?
|
|
37
|
+
type == "unknown"
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
SCHEMAS = {
|
|
42
|
+
"pairing.created" => [PairingCreated, { pairing_id: :s, external_user_id: :s, device_name: :s }],
|
|
43
|
+
"pairing.revoked" => [PairingRevoked, { pairing_id: :s, external_user_id: :s, by: :s }],
|
|
44
|
+
"message.delivered" => [MessageDelivered, { message_id: :s, external_user_id: :s, channel: :s, level: :s, devices: :n }],
|
|
45
|
+
"message.undeliverable" => [MessageUndeliverable, { message_id: :s, external_user_id: :s, channel: :s, reason: :s }],
|
|
46
|
+
"message.acked" => [MessageAcked, { message_id: :s, external_user_id: :s, device_id: :s }],
|
|
47
|
+
"message.dismissed" => [MessageDismissed, { message_id: :s, external_user_id: :s, device_id: :s }],
|
|
48
|
+
"message.expired" => [MessageExpired, { message_id: :s, external_user_id: :s, channel: :s, attempts: :n }],
|
|
49
|
+
"action" => [ActionTaken, { message_id: :s, action_id: :s, device_id: :s, external_user_id: :s, text: :opt }],
|
|
50
|
+
"activity.ended" => [ActivityEnded, { activity_id: :s, external_user_id: :s, channel: :s, reason: :s }]
|
|
51
|
+
}.freeze
|
|
52
|
+
private_constant :SCHEMAS
|
|
53
|
+
|
|
54
|
+
HEX_SIGNATURE = /\A[0-9a-fA-F]{64}\z/
|
|
55
|
+
private_constant :HEX_SIGNATURE
|
|
56
|
+
|
|
57
|
+
module_function
|
|
58
|
+
|
|
59
|
+
# Verifies a webhook against its raw body and returns the Event. Raises WebhookError
|
|
60
|
+
# (+code+: malformed_header, bad_signature, stale, malformed_body, invalid_body,
|
|
61
|
+
# invalid_secret). With several v1 values in the header (secret rotation) any match
|
|
62
|
+
# is accepted.
|
|
63
|
+
#
|
|
64
|
+
# +secret+:: the shared secret (HUB_WEBHOOK_SECRET).
|
|
65
|
+
# +header+:: the X-Hansho-Webhook-Signature request header.
|
|
66
|
+
# +body+:: the request body exactly as received (a String). A body that a framework
|
|
67
|
+
# parsed and you re-serialised will not verify, and a Hash is rejected.
|
|
68
|
+
# +now+:: a Time or epoch seconds; default the current time.
|
|
69
|
+
# +tolerance+:: allowed distance between the signed timestamp and +now+ in seconds;
|
|
70
|
+
# default 300, a value <= 0 means the default.
|
|
71
|
+
def verify(secret:, header:, body:, now: nil, tolerance: nil)
|
|
72
|
+
raise WebhookError.new("invalid_secret", "webhook secret is empty") unless secret.is_a?(String) && !secret.empty?
|
|
73
|
+
unless body.is_a?(String)
|
|
74
|
+
raise WebhookError.new("invalid_body", "body must be the raw request body (a String), not a parsed object")
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
t, sigs = parse_header(header)
|
|
78
|
+
raw = body.b
|
|
79
|
+
mac = OpenSSL::HMAC.new(secret.b, "SHA256")
|
|
80
|
+
mac.update("#{t}.")
|
|
81
|
+
mac.update(raw)
|
|
82
|
+
want = mac.digest
|
|
83
|
+
match = false
|
|
84
|
+
sigs.each do |sig|
|
|
85
|
+
next unless HEX_SIGNATURE.match?(sig)
|
|
86
|
+
|
|
87
|
+
match = true if OpenSSL.fixed_length_secure_compare([sig].pack("H*"), want)
|
|
88
|
+
end
|
|
89
|
+
raise WebhookError.new("bad_signature", "signature does not match") unless match
|
|
90
|
+
|
|
91
|
+
now_s = now.nil? ? Time.now.to_f : now.to_f
|
|
92
|
+
tol = tolerance && tolerance > 0 ? tolerance : DEFAULT_TOLERANCE
|
|
93
|
+
raise WebhookError.new("stale", "timestamp outside tolerance") if (now_s - t.to_i).abs > tol
|
|
94
|
+
|
|
95
|
+
build_event(raw)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def parse_header(header)
|
|
99
|
+
raise WebhookError.new("malformed_header", "missing signature header") unless header.is_a?(String) && !header.strip.empty?
|
|
100
|
+
|
|
101
|
+
t = nil
|
|
102
|
+
sigs = []
|
|
103
|
+
header.split(",", -1).each do |part|
|
|
104
|
+
part = part.strip
|
|
105
|
+
eq = part.index("=")
|
|
106
|
+
raise WebhookError.new("malformed_header", "signature header part is not key=value") unless eq
|
|
107
|
+
|
|
108
|
+
k = part[0...eq]
|
|
109
|
+
v = part[(eq + 1)..]
|
|
110
|
+
if k == "t"
|
|
111
|
+
raise WebhookError.new("malformed_header", "duplicate timestamp") unless t.nil?
|
|
112
|
+
|
|
113
|
+
t = v
|
|
114
|
+
elsif k == "v1" && !v.empty?
|
|
115
|
+
sigs << v
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
if t.nil? || !t.match?(/\A-?\d+\z/) || sigs.empty?
|
|
119
|
+
raise WebhookError.new("malformed_header", "signature header needs t=<unix> and v1=<hex>")
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
[t, sigs]
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def build_event(raw)
|
|
126
|
+
text = raw.dup.force_encoding(Encoding::UTF_8)
|
|
127
|
+
env = begin
|
|
128
|
+
parsed = text.valid_encoding? ? JSON.parse(text) : nil
|
|
129
|
+
parsed.is_a?(Hash) ? parsed : nil
|
|
130
|
+
rescue JSON::ParserError
|
|
131
|
+
nil
|
|
132
|
+
end
|
|
133
|
+
raise WebhookError.new("malformed_body", "body is not a webhook envelope") unless env
|
|
134
|
+
|
|
135
|
+
name = env["event"]
|
|
136
|
+
raise WebhookError.new("malformed_body", "body has no event") unless name.is_a?(String) && !name.empty?
|
|
137
|
+
|
|
138
|
+
created_at = Time.at(num(env["created_at"]))
|
|
139
|
+
id = str(env["id"])
|
|
140
|
+
payload = env["data"].is_a?(Hash) ? env["data"] : {}
|
|
141
|
+
schema = SCHEMAS[name]
|
|
142
|
+
return Event.new(type: "unknown", id: id, created_at: created_at, data: env["data"], raw: raw, name: name) unless schema
|
|
143
|
+
|
|
144
|
+
klass, fields = schema
|
|
145
|
+
data = klass.new(**fields.to_h { |field, cast| [field, cast_value(payload[field.to_s], cast)] })
|
|
146
|
+
Event.new(type: name, id: id, created_at: created_at, data: data, raw: raw)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def cast_value(value, cast)
|
|
150
|
+
case cast
|
|
151
|
+
when :n then num(value)
|
|
152
|
+
when :opt then value.is_a?(String) ? value : nil
|
|
153
|
+
else str(value)
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def str(value)
|
|
158
|
+
value.nil? ? "" : value.to_s
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def num(value)
|
|
162
|
+
case value
|
|
163
|
+
when Integer then value
|
|
164
|
+
when Float then value == value.to_i ? value.to_i : value
|
|
165
|
+
when String then Integer(value, exception: false) || 0
|
|
166
|
+
else 0
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
private_class_method :parse_header, :build_event, :cast_value, :str, :num
|
|
170
|
+
end
|
|
171
|
+
end
|
data/lib/hansho.rb
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "hansho/version"
|
|
4
|
+
require_relative "hansho/errors"
|
|
5
|
+
require_relative "hansho/retry"
|
|
6
|
+
require_relative "hansho/types"
|
|
7
|
+
require_relative "hansho/transport"
|
|
8
|
+
require_relative "hansho/client"
|
|
9
|
+
require_relative "hansho/webhook"
|
|
10
|
+
|
|
11
|
+
# Official Ruby client for a Hansho hub's sender API: pair users, send notifications,
|
|
12
|
+
# pages, Live Activities and widget feeds, and verify the hub's webhooks.
|
|
13
|
+
module Hansho
|
|
14
|
+
# Shorthand for Webhook.verify.
|
|
15
|
+
def self.verify_webhook(**opts)
|
|
16
|
+
Webhook.verify(**opts)
|
|
17
|
+
end
|
|
18
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: hansho
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Recodive
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: 'A small, dependency-free client (net/http, json, openssl) for the Hansho
|
|
13
|
+
hub''s sender API: pairing tickets, channels, templates, sounds, notifications,
|
|
14
|
+
pages, Live Activities, widget feeds, typed errors, safe retries and signed-webhook
|
|
15
|
+
verification.'
|
|
16
|
+
executables: []
|
|
17
|
+
extensions: []
|
|
18
|
+
extra_rdoc_files: []
|
|
19
|
+
files:
|
|
20
|
+
- LICENSE
|
|
21
|
+
- README.md
|
|
22
|
+
- lib/hansho.rb
|
|
23
|
+
- lib/hansho/client.rb
|
|
24
|
+
- lib/hansho/errors.rb
|
|
25
|
+
- lib/hansho/retry.rb
|
|
26
|
+
- lib/hansho/transport.rb
|
|
27
|
+
- lib/hansho/types.rb
|
|
28
|
+
- lib/hansho/version.rb
|
|
29
|
+
- lib/hansho/webhook.rb
|
|
30
|
+
homepage: https://github.com/Recodive/hansho/tree/main/sdk/ruby#readme
|
|
31
|
+
licenses:
|
|
32
|
+
- MIT
|
|
33
|
+
metadata:
|
|
34
|
+
homepage_uri: https://github.com/Recodive/hansho/tree/main/sdk/ruby#readme
|
|
35
|
+
source_code_uri: https://github.com/Recodive/hansho/tree/main/sdk/ruby
|
|
36
|
+
bug_tracker_uri: https://github.com/Recodive/hansho/issues
|
|
37
|
+
rubygems_mfa_required: 'true'
|
|
38
|
+
rdoc_options: []
|
|
39
|
+
require_paths:
|
|
40
|
+
- lib
|
|
41
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
42
|
+
requirements:
|
|
43
|
+
- - ">="
|
|
44
|
+
- !ruby/object:Gem::Version
|
|
45
|
+
version: '3.1'
|
|
46
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
- - ">="
|
|
49
|
+
- !ruby/object:Gem::Version
|
|
50
|
+
version: '0'
|
|
51
|
+
requirements: []
|
|
52
|
+
rubygems_version: 3.6.9
|
|
53
|
+
specification_version: 4
|
|
54
|
+
summary: 'Official Ruby client for a Hansho hub: pair users, send notifications, pages,
|
|
55
|
+
Live Activities and widget feeds, verify webhooks.'
|
|
56
|
+
test_files: []
|