meeng-sdk 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/README.md +185 -0
- data/lib/meeng/client.rb +177 -0
- data/lib/meeng/error.rb +75 -0
- data/lib/meeng/services.rb +441 -0
- data/lib/meeng/version.rb +19 -0
- data/lib/meeng/webhooks.rb +118 -0
- data/lib/meeng.rb +21 -0
- metadata +48 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: dbf77ec452366803203cd6d0e039ea8282f58f115157d693f86ac73090184180
|
|
4
|
+
data.tar.gz: fa79a6698267aa3537d3a76df8e6a963180709ba9084acef7a15b0d17b540f6a
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: cd1dd3d09d6972f815b96d7dbbacf3d3e210d42d7594984473c93fdb4c7c3f296de1439b712a238873adc8cab5912747451477cf638f1902a44c41fbcc2be9ac
|
|
7
|
+
data.tar.gz: a72ae6f6d528fdcf9ffab97c08ea2297f56caca3c56be1936b9068e739837cd181b4fbe3bab6e86c9d91a01bc00d321fdbfc8d2890e8acb6543e636e3a6c7d87
|
data/README.md
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# meeng-sdk (Ruby)
|
|
2
|
+
|
|
3
|
+
SDK do Meeng.dev para Ruby 3.1 ou mais novo: e-mails, domínios, contatos, listas de contatos, campanhas, analytics e webhooks. Não depende de nenhuma gem.
|
|
4
|
+
|
|
5
|
+
Gerado pelo `sdk/generator` a partir do contrato da API do Meeng.dev (versão 1.0.0); não edite à mão.
|
|
6
|
+
|
|
7
|
+
## Começando
|
|
8
|
+
|
|
9
|
+
```ruby
|
|
10
|
+
require "meeng"
|
|
11
|
+
|
|
12
|
+
meeng = Meeng::Client.new("mg_123")
|
|
13
|
+
|
|
14
|
+
sent = meeng.emails.send(
|
|
15
|
+
from: "contato@acme.com.br",
|
|
16
|
+
to: "ana@example.com",
|
|
17
|
+
subject: "Olá",
|
|
18
|
+
html: "<p>Olá!</p>"
|
|
19
|
+
)
|
|
20
|
+
puts sent[:emailId]
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Os corpos são hashes com as chaves da API, em camelCase (`contactBookId`, `scheduledAt`), e as respostas são hashes com essas mesmas chaves como símbolos. Uma recusa da API levanta `Meeng::Error` (`status`, `code`, como `NOT_UNIQUE` ou `FORBIDDEN`, `retry_after` e a mensagem).
|
|
24
|
+
|
|
25
|
+
Sem argumentos, `Meeng::Client.new` lê a chave de `MEENG_API_KEY` e o endereço do app de `MEENG_BASE_URL`. O segundo argumento é o endereço do app (para instalações próprias), sem `/api/v1`; ele precisa ser https, e http só vale para `localhost`, `127.0.0.0/8` e `::1`, para a chave nunca viajar em texto puro. O transporte padrão usa `Net::HTTP` e não segue redirecionamentos.
|
|
26
|
+
|
|
27
|
+
## Recursos
|
|
28
|
+
|
|
29
|
+
### `meeng.emails`
|
|
30
|
+
|
|
31
|
+
- `send`: envia um e-mail, agora ou em `scheduledAt`.
|
|
32
|
+
- `batch`: envia até 100 e-mails numa requisição.
|
|
33
|
+
- `get`: lê um e-mail com os seus eventos.
|
|
34
|
+
- `list`: lista e-mails, do mais novo ao mais velho, com período e domínio opcionais.
|
|
35
|
+
- `update`: reagenda um e-mail que ainda não saiu.
|
|
36
|
+
- `cancel`: cancela um e-mail agendado.
|
|
37
|
+
|
|
38
|
+
### `meeng.domains`
|
|
39
|
+
|
|
40
|
+
- `list`: lista os domínios de envio do time.
|
|
41
|
+
- `create`: adiciona um domínio de envio e devolve os registros DNS a publicar.
|
|
42
|
+
- `verify`: pede para conferir de novo os registros DNS do domínio.
|
|
43
|
+
- `get`: lê um domínio com os seus registros DNS.
|
|
44
|
+
- `delete`: remove um domínio.
|
|
45
|
+
|
|
46
|
+
### `meeng.contacts`
|
|
47
|
+
|
|
48
|
+
- `create`: adiciona um contato a uma lista de contatos.
|
|
49
|
+
- `list`: lista os contatos de uma lista, com filtro opcional por e-mail ou id.
|
|
50
|
+
- `get`: lê um contato.
|
|
51
|
+
- `update`: muda só os campos enviados de um contato.
|
|
52
|
+
- `upsert`: cria o contato, ou o substitui quando ele já existe.
|
|
53
|
+
- `delete`: remove um contato.
|
|
54
|
+
- `bulk_create`: adiciona vários contatos a uma lista numa requisição.
|
|
55
|
+
- `bulk_delete`: remove vários contatos de uma lista numa requisição.
|
|
56
|
+
|
|
57
|
+
### `meeng.contact_books`
|
|
58
|
+
|
|
59
|
+
- `list`: lista as listas de contatos do time.
|
|
60
|
+
- `create`: cria uma lista de contatos.
|
|
61
|
+
- `get`: lê uma lista de contatos.
|
|
62
|
+
- `update`: muda só os campos enviados de uma lista de contatos.
|
|
63
|
+
- `delete`: remove uma lista de contatos e os seus contatos.
|
|
64
|
+
|
|
65
|
+
### `meeng.campaigns`
|
|
66
|
+
|
|
67
|
+
- `create`: cria uma campanha, e a envia agora quando `sendNow` é verdadeiro.
|
|
68
|
+
- `list`: lista campanhas, com filtro opcional por status ou texto.
|
|
69
|
+
- `get`: lê uma campanha com os seus contadores.
|
|
70
|
+
- `delete`: remove uma campanha.
|
|
71
|
+
- `schedule`: agenda uma campanha, ou a envia agora quando não há horário.
|
|
72
|
+
- `pause`: pausa uma campanha em andamento ou agendada.
|
|
73
|
+
- `resume`: retoma uma campanha pausada.
|
|
74
|
+
|
|
75
|
+
### `meeng.analytics`
|
|
76
|
+
|
|
77
|
+
- `email_time_series`: conta e-mails por dia nos últimos 7 ou 30 dias.
|
|
78
|
+
- `reputation_metrics`: lê as taxas de rejeição e de reclamação da reputação de envio.
|
|
79
|
+
|
|
80
|
+
`emails.create` é outro nome de `emails.send`, e `campaigns.get_all` de `campaigns.list`.
|
|
81
|
+
|
|
82
|
+
Os filtros de listagem são argumentos nomeados em snake_case (`start_date`, `domain_id`); uma lista em `domain_id` vira um `domainId` por valor. `emails.send` e `emails.batch` aceitam `idempotency_key: "pedido-1"`: a mesma chave com o mesmo corpo devolve o primeiro resultado.
|
|
83
|
+
|
|
84
|
+
## Arquivos: use links, não anexos
|
|
85
|
+
|
|
86
|
+
O Meeng.dev não anexa, não guarda e não repassa arquivos, e por isso nenhum SDK tem o campo `attachments`. Hospede o arquivo onde preferir (seu armazenamento, um link assinado com prazo) e ponha o link no corpo do e-mail:
|
|
87
|
+
|
|
88
|
+
```html
|
|
89
|
+
<p>Sua fatura está pronta: <a href="https://exemplo.com.br/faturas/1042?token=...">baixar a fatura (PDF)</a></p>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Se um pedido chegar à API com `attachments` e itens, ela responde `400` (`ZodError`) com a mensagem `Attachments are not supported. Include links to your files in the email body.`; uma lista vazia passa. Para um documento sensível, use um link que expira.
|
|
93
|
+
|
|
94
|
+
## Configuração
|
|
95
|
+
|
|
96
|
+
A API do Meeng.dev fica em `https://meeng.dev/api`. O cliente recebe o endereço do app, `https://meeng.dev` (o padrão), e acrescenta `/api/v1` a cada chamada. Crie uma chave em [Configurações > Chaves](https://meeng.dev/configuracoes/chaves); ela tem a forma `mg_<id>_<segredo>`.
|
|
97
|
+
|
|
98
|
+
- A chave vem do argumento ou de `MEENG_API_KEY`; o endereço, do argumento ou de `MEENG_BASE_URL`.
|
|
99
|
+
- Só `https` é aceito. `http` vale para `localhost`, `127.0.0.0/8` e `::1` (um servidor local), para a chave nunca viajar em texto puro. Nenhum cliente segue redirecionamento.
|
|
100
|
+
|
|
101
|
+
```ruby
|
|
102
|
+
meeng = Meeng::Client.new("mg_...", "https://meeng.dev", timeout: 10, max_retries: 3, retry_delay: 1.0)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Exemplos
|
|
106
|
+
|
|
107
|
+
A pasta [`examples/`](examples) tem programas que rodam: enviar um e-mail, enviar em lote, agendar (remarcar e cancelar), adicionar um domínio (com os registros DNS) e verificar um webhook.
|
|
108
|
+
|
|
109
|
+
| Exemplo | Arquivo | Rode com |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| Enviar um e-mail | `examples/send_email.rb` | `ruby examples/send_email.rb` |
|
|
112
|
+
| Enviar em lote | `examples/send_batch.rb` | `ruby examples/send_batch.rb` |
|
|
113
|
+
| Agendar, remarcar e cancelar | `examples/schedule_email.rb` | `ruby examples/schedule_email.rb` |
|
|
114
|
+
| Adicionar um domínio | `examples/add_domain.rb` | `ruby examples/add_domain.rb` |
|
|
115
|
+
| Verificar um webhook | `examples/verify_webhook.rb` | `ruby examples/verify_webhook.rb` |
|
|
116
|
+
|
|
117
|
+
Todos leem `MEENG_API_KEY` e, se quiser apontar para outro app, `MEENG_BASE_URL`; o de webhook roda sem chave, com uma requisição montada no próprio programa.
|
|
118
|
+
|
|
119
|
+
## Paginação
|
|
120
|
+
|
|
121
|
+
As listagens de e-mails, contatos e campanhas são paginadas por `page` (a partir de 1) e, nas duas primeiras, `limit`. `emails.list` devolve `count`, o total de e-mails; `campaigns.list` devolve `totalPage`, o total de páginas; `contacts.list` devolve a lista sem total, e a última página é a que vem com menos de `limit` contatos.
|
|
122
|
+
|
|
123
|
+
```ruby
|
|
124
|
+
todos = []
|
|
125
|
+
page = 1
|
|
126
|
+
loop do
|
|
127
|
+
lista = meeng.emails.list(page: page, limit: 100)
|
|
128
|
+
todos += lista[:data]
|
|
129
|
+
break if todos.size >= lista[:count] || lista[:data].empty?
|
|
130
|
+
|
|
131
|
+
page += 1
|
|
132
|
+
end
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Erros
|
|
136
|
+
|
|
137
|
+
Uma recusa da API levanta `Meeng::Error`, com `status`, `code`, `message` e `retry_after`:
|
|
138
|
+
|
|
139
|
+
```ruby
|
|
140
|
+
begin
|
|
141
|
+
meeng.emails.get("em_123")
|
|
142
|
+
rescue Meeng::Error => erro
|
|
143
|
+
# o e-mail não existe, ou é de outro time
|
|
144
|
+
raise unless erro.code == "NOT_FOUND"
|
|
145
|
+
end
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Os códigos que a API devolve: `UNAUTHORIZED` (sem chave), `FORBIDDEN` (chave inválida ou sem permissão), `NOT_FOUND`, `NOT_UNIQUE` (a mesma chave de idempotência com outro corpo, ou ainda em andamento), `RATE_LIMITED`, `BAD_REQUEST`, `METHOD_NOT_ALLOWED`, `NOT_IMPLEMENTED` e `INTERNAL_SERVER_ERROR`. Uma validação recusada vira o código `ZodError`, e a mensagem é a primeira falha (`from: Required`).
|
|
149
|
+
|
|
150
|
+
## Tentativas automáticas
|
|
151
|
+
|
|
152
|
+
O cliente repete sozinho a chamada que pode ser repetida, até `max_retries` vezes depois da primeira tentativa (2 por padrão; 0 envia cada chamada uma vez só):
|
|
153
|
+
|
|
154
|
+
| Resposta | Repete? |
|
|
155
|
+
|---|---|
|
|
156
|
+
| 429 (limite de requisições por segundo) | Sempre: a chamada não foi processada, então qualquer uma pode ser repetida. |
|
|
157
|
+
| 500, 502, 503, 504 ou falha de conexão | Só quando repetir não faz o trabalho duas vezes: uma leitura (`GET`), um `PUT`, um `DELETE`, ou uma chamada com chave de idempotência. Um envio sem chave não é repetido. |
|
|
158
|
+
| 409 e qualquer outra recusa | Nunca. |
|
|
159
|
+
|
|
160
|
+
A primeira repetição espera `retry_delay` (500 ms por padrão), cada uma seguinte espera o dobro, até 30 segundos, e o `Retry-After` que a API devolve vale no lugar dessa espera. Esgotadas as tentativas, a última resposta é o erro.
|
|
161
|
+
|
|
162
|
+
## Webhooks
|
|
163
|
+
|
|
164
|
+
```ruby
|
|
165
|
+
webhooks = meeng.webhooks("whsec_xxx")
|
|
166
|
+
|
|
167
|
+
# O corpo cru, antes de interpretá-lo.
|
|
168
|
+
event = webhooks.construct_event(request.body.read, headers: request.headers)
|
|
169
|
+
|
|
170
|
+
puts event[:data][:to] if event[:type] == "email.delivered"
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`verify(body, headers:)` só confere a assinatura e devolve `true` ou `false`. `construct_event` confere e devolve o evento, ou levanta `Meeng::WebhookVerificationError` com um `code`: `MISSING_SIGNATURE`, `MISSING_TIMESTAMP`, `INVALID_SIGNATURE_FORMAT`, `INVALID_TIMESTAMP`, `TIMESTAMP_OUT_OF_RANGE`, `SIGNATURE_MISMATCH` ou `INVALID_JSON`.
|
|
174
|
+
|
|
175
|
+
A assinatura é `v1=` mais o HMAC-SHA256, em hexadecimal, de `{timestamp}.{corpo}` com o segredo do webhook; o timestamp vem em milissegundos. A tolerância padrão é de 5 minutos (`tolerance:`, em milissegundos; um número negativo desliga a checagem; `secret:` troca o segredo de uma checagem). Os cabeçalhos são `X-Meeng-Signature`, `X-Meeng-Timestamp`, `X-Meeng-Event` e `X-Meeng-Call`.
|
|
176
|
+
|
|
177
|
+
Eventos: `contact.created`, `contact.updated`, `contact.deleted`, `domain.created`, `domain.verified`, `domain.updated`, `domain.deleted`, `email.queued`, `email.sent`, `email.delivery_delayed`, `email.delivered`, `email.rejected`, `email.rendering_failure`, `email.complained`, `email.cancelled`, `email.bounced`, `email.clicked`, `email.failed`, `email.opened`, `email.suppressed`, `webhook.test`.
|
|
178
|
+
|
|
179
|
+
## Desenvolvimento
|
|
180
|
+
|
|
181
|
+
```sh
|
|
182
|
+
ruby -w -Ilib -Itest -e 'Dir["test/*_test.rb"].sort.each { |file| require "./#{file}" }'
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
O `./check.sh` da raiz do repositório sobe uma API de mentira gerada do contrato (`go run ./cmd/fakeapi`), que recusa o que o contrato não permite, e roda contra ela o teste de contrato (cada método do SDK é chamado, e nenhuma operação pode ficar de fora) e os exemplos.
|
data/lib/meeng/client.rb
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdk/generator. DO NOT EDIT.
|
|
4
|
+
|
|
5
|
+
require "ipaddr"
|
|
6
|
+
require "json"
|
|
7
|
+
require "net/http"
|
|
8
|
+
require "openssl"
|
|
9
|
+
require "socket"
|
|
10
|
+
require "timeout"
|
|
11
|
+
require "uri"
|
|
12
|
+
|
|
13
|
+
module Meeng
|
|
14
|
+
# The standard library's HTTP, so the SDK depends on nothing. A transport is
|
|
15
|
+
# anything that answers +call(method, url, headers, body, timeout)+ with
|
|
16
|
+
# +[status, headers in lower case, body]+. It does not follow redirects, so the
|
|
17
|
+
# key never goes where a redirect points.
|
|
18
|
+
class NetHTTPTransport
|
|
19
|
+
def call(method, url, headers, body, timeout)
|
|
20
|
+
uri = URI(url)
|
|
21
|
+
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
|
|
22
|
+
open_timeout: timeout, read_timeout: timeout, write_timeout: timeout) do |http|
|
|
23
|
+
response = http.send_request(method, uri.request_uri, body, headers)
|
|
24
|
+
[response.code.to_i, response.each_header.to_h, response.body.to_s]
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# meeng's API with one team's API key. Without a key it is read from
|
|
30
|
+
# MEENG_API_KEY, and the address of the app from MEENG_BASE_URL.
|
|
31
|
+
#
|
|
32
|
+
# meeng = Meeng::Client.new("mg_123")
|
|
33
|
+
# sent = meeng.emails.send(from: "hello@acme.com", to: "customer@example.com", subject: "Hello", html: "<p>Hello</p>")
|
|
34
|
+
#
|
|
35
|
+
# Answers are hashes with symbol keys, the API's own names (+:emailId+); a
|
|
36
|
+
# refusal raises Meeng::Error.
|
|
37
|
+
#
|
|
38
|
+
# A call that may be repeated is repeated up to +max_retries+ times (2 by
|
|
39
|
+
# default; 0 sends every call once) after the first attempt. It is repeated
|
|
40
|
+
# when the API answers 429, which means it was not processed, so any call may
|
|
41
|
+
# be; and when the API answers 500, 502, 503 or 504, or the connection fails,
|
|
42
|
+
# only if repeating it cannot do the work twice: a read, a PUT, a DELETE, or any
|
|
43
|
+
# call that carries an idempotency key. Any other refusal, a 409 included, is
|
|
44
|
+
# never repeated. The first repetition waits +retry_delay+ seconds, each next
|
|
45
|
+
# one twice as long, and a Retry-After from the API replaces the wait.
|
|
46
|
+
class Client
|
|
47
|
+
# The longest, in seconds, a call waits before a repetition.
|
|
48
|
+
MAX_RETRY_DELAY = 30.0
|
|
49
|
+
TRANSIENT = [500, 502, 503, 504].freeze
|
|
50
|
+
CONNECTION_FAILURES = [SystemCallError, IOError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
|
|
51
|
+
private_constant :TRANSIENT, :CONNECTION_FAILURES
|
|
52
|
+
# @return [EmailsService]
|
|
53
|
+
attr_reader :emails
|
|
54
|
+
# @return [DomainsService]
|
|
55
|
+
attr_reader :domains
|
|
56
|
+
# @return [ContactsService]
|
|
57
|
+
attr_reader :contacts
|
|
58
|
+
# @return [ContactBooksService]
|
|
59
|
+
attr_reader :contact_books
|
|
60
|
+
# @return [CampaignsService]
|
|
61
|
+
attr_reader :campaigns
|
|
62
|
+
# @return [AnalyticsService]
|
|
63
|
+
attr_reader :analytics
|
|
64
|
+
|
|
65
|
+
# The base URL is the address of the app, without +/api/v1+. It must be
|
|
66
|
+
# https; http is accepted only for localhost, 127.0.0.0/8 and ::1, and any
|
|
67
|
+
# other raises ArgumentError.
|
|
68
|
+
def initialize(api_key = nil, base_url = nil, timeout: 30, transport: NetHTTPTransport.new, max_retries: 2, retry_delay: 0.5)
|
|
69
|
+
key = api_key.nil? || api_key.empty? ? ENV.fetch("MEENG_API_KEY", nil) : api_key
|
|
70
|
+
raise ArgumentError, "Missing API key. Pass it to Meeng::Client.new(\"mg_123\") or set MEENG_API_KEY" if key.nil? || key.empty?
|
|
71
|
+
|
|
72
|
+
@key = key
|
|
73
|
+
base = base_url.nil? || base_url.empty? ? (ENV.fetch("MEENG_BASE_URL", nil) || DEFAULT_BASE_URL) : base_url
|
|
74
|
+
base = base.chomp("/")
|
|
75
|
+
check_base_url!(base)
|
|
76
|
+
@url = base + API_PREFIX
|
|
77
|
+
@timeout = timeout
|
|
78
|
+
@transport = transport
|
|
79
|
+
@max_retries = [max_retries.to_i, 0].max
|
|
80
|
+
@retry_delay = [retry_delay.to_f, 0.0].max
|
|
81
|
+
@emails = EmailsService.new(self)
|
|
82
|
+
@domains = DomainsService.new(self)
|
|
83
|
+
@contacts = ContactsService.new(self)
|
|
84
|
+
@contact_books = ContactBooksService.new(self)
|
|
85
|
+
@campaigns = CampaignsService.new(self)
|
|
86
|
+
@analytics = AnalyticsService.new(self)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# @return [String] the address every call goes to, with the API prefix
|
|
90
|
+
attr_reader :url
|
|
91
|
+
|
|
92
|
+
# Checks and reads the webhooks a team's endpoint receives.
|
|
93
|
+
#
|
|
94
|
+
# @return [Webhooks]
|
|
95
|
+
def webhooks(secret)
|
|
96
|
+
Webhooks.new(secret)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Calls the API and answers its JSON, decoded with symbol keys; a refusal
|
|
100
|
+
# raises Meeng::Error.
|
|
101
|
+
def request(method, path, query: nil, body: nil, idempotency_key: nil)
|
|
102
|
+
pairs = []
|
|
103
|
+
(query || {}).each do |name, value|
|
|
104
|
+
# A list is sent once for each value: name=a&name=b.
|
|
105
|
+
Array(value).each { |each| pairs << [name, each] unless each.nil? || each == "" }
|
|
106
|
+
end
|
|
107
|
+
full = @url + path
|
|
108
|
+
full += "?#{URI.encode_www_form(pairs)}" unless pairs.empty?
|
|
109
|
+
headers = {
|
|
110
|
+
"Authorization" => "Bearer #{@key}",
|
|
111
|
+
"Accept" => "application/json",
|
|
112
|
+
"User-Agent" => "meeng-ruby/#{VERSION}"
|
|
113
|
+
}
|
|
114
|
+
data = nil
|
|
115
|
+
unless body.nil?
|
|
116
|
+
data = JSON.generate(body)
|
|
117
|
+
headers["Content-Type"] = "application/json"
|
|
118
|
+
end
|
|
119
|
+
headers["Idempotency-Key"] = idempotency_key if idempotency_key && !idempotency_key.empty?
|
|
120
|
+
may_repeat = %w[GET HEAD PUT DELETE].include?(method.to_s.upcase) || !(idempotency_key.nil? || idempotency_key.empty?)
|
|
121
|
+
attempt = 0
|
|
122
|
+
status = response_headers = raw = nil
|
|
123
|
+
loop do
|
|
124
|
+
begin
|
|
125
|
+
status, response_headers, raw = @transport.call(method, full, headers, data, @timeout)
|
|
126
|
+
rescue *CONNECTION_FAILURES
|
|
127
|
+
# The connection failed or timed out: the call may or may not have arrived.
|
|
128
|
+
raise if !may_repeat || attempt >= @max_retries
|
|
129
|
+
|
|
130
|
+
pause(attempt, nil)
|
|
131
|
+
attempt += 1
|
|
132
|
+
next
|
|
133
|
+
end
|
|
134
|
+
if (status == 429 || (may_repeat && TRANSIENT.include?(status))) && attempt < @max_retries
|
|
135
|
+
pause(attempt, response_headers["retry-after"])
|
|
136
|
+
attempt += 1
|
|
137
|
+
next
|
|
138
|
+
end
|
|
139
|
+
break
|
|
140
|
+
end
|
|
141
|
+
raise Error.from_response(status, response_headers, raw) if status >= 300
|
|
142
|
+
|
|
143
|
+
JSON.parse(raw, symbolize_names: true)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
private
|
|
147
|
+
|
|
148
|
+
# Sleeps before repetition number attempt + 1: the API's Retry-After, or the
|
|
149
|
+
# base delay doubled each time and spread over its upper half.
|
|
150
|
+
def pause(attempt, retry_after)
|
|
151
|
+
seconds = retry_after.to_f
|
|
152
|
+
if seconds <= 0
|
|
153
|
+
delay = [@retry_delay * (2**[attempt, 10].min), MAX_RETRY_DELAY].min
|
|
154
|
+
seconds = (delay / 2) + (rand * delay / 2)
|
|
155
|
+
end
|
|
156
|
+
sleep([seconds, MAX_RETRY_DELAY].min)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def check_base_url!(base_url)
|
|
160
|
+
uri = begin
|
|
161
|
+
URI.parse(base_url)
|
|
162
|
+
rescue URI::InvalidURIError
|
|
163
|
+
nil
|
|
164
|
+
end
|
|
165
|
+
scheme = uri&.scheme.to_s.downcase
|
|
166
|
+
host = uri&.hostname.to_s.downcase
|
|
167
|
+
loopback = host == "localhost" || begin
|
|
168
|
+
IPAddr.new(host).loopback?
|
|
169
|
+
rescue IPAddr::Error
|
|
170
|
+
false
|
|
171
|
+
end
|
|
172
|
+
return if scheme == "https" || (scheme == "http" && loopback)
|
|
173
|
+
|
|
174
|
+
raise ArgumentError, "meeng: the base URL must be https (http is accepted only for localhost, 127.0.0.0/8 and ::1), so the API key is never sent in clear text"
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
data/lib/meeng/error.rb
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Meeng
|
|
6
|
+
# A request the API refused.
|
|
7
|
+
#
|
|
8
|
+
# +code+ is the API's, such as NOT_UNIQUE, FORBIDDEN or NOT_FOUND; it is
|
|
9
|
+
# INTERNAL_SERVER_ERROR when the answer carried none. +status+ is the HTTP
|
|
10
|
+
# status and +retry_after+, on a 429, how many seconds to wait.
|
|
11
|
+
class Error < StandardError
|
|
12
|
+
REASONS = {
|
|
13
|
+
400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 409 => "Conflict",
|
|
14
|
+
422 => "Unprocessable Entity", 429 => "Too Many Requests", 500 => "Internal Server Error",
|
|
15
|
+
502 => "Bad Gateway", 503 => "Service Unavailable"
|
|
16
|
+
}.freeze
|
|
17
|
+
|
|
18
|
+
attr_reader :status, :code, :retry_after
|
|
19
|
+
|
|
20
|
+
def initialize(status, code, message = "", retry_after = nil)
|
|
21
|
+
@status = status
|
|
22
|
+
@code = code
|
|
23
|
+
@retry_after = retry_after
|
|
24
|
+
super(message.empty? ? "meeng: #{status} #{code}" : "meeng: #{status} #{code}: #{message}")
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# What Ruby prints for an error nobody rescued: the status and code too.
|
|
28
|
+
def detailed_message(highlight: false, **)
|
|
29
|
+
highlight ? "\e[1m#{self} (#{self.class.name})\e[m" : "#{self} (#{self.class.name})"
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The error a response with a status of 300 or more is: the answer's
|
|
33
|
+
# +{"error": {"code", "message"}}+, +{"error": "text"}+ or the error itself.
|
|
34
|
+
def self.from_response(status, headers, body)
|
|
35
|
+
code = "INTERNAL_SERVER_ERROR"
|
|
36
|
+
message = REASONS.fetch(status, "Error")
|
|
37
|
+
data = begin
|
|
38
|
+
JSON.parse(body.to_s)
|
|
39
|
+
rescue JSON::ParserError
|
|
40
|
+
nil
|
|
41
|
+
end
|
|
42
|
+
if data.is_a?(Hash)
|
|
43
|
+
found = data.fetch("error", data)
|
|
44
|
+
found = { "message" => found } if found.is_a?(String)
|
|
45
|
+
if found.is_a?(Hash)
|
|
46
|
+
code = found["code"] if found["code"].is_a?(String) && !found["code"].empty?
|
|
47
|
+
# A refused validation answers {"success": false, "error": {"issues", "name"}}, with no code of its own.
|
|
48
|
+
code = found["name"] if !found["code"].is_a?(String) && found["name"].is_a?(String) && !found["name"].empty?
|
|
49
|
+
if found["message"].is_a?(String) && !found["message"].empty?
|
|
50
|
+
message = found["message"]
|
|
51
|
+
elsif found["issues"].is_a?(Array) && found["issues"].first.is_a?(Hash) && found["issues"].first["message"].is_a?(String)
|
|
52
|
+
first = found["issues"].first
|
|
53
|
+
where = first["path"].is_a?(Array) && !first["path"].empty? ? "#{first["path"].join(".")}: " : ""
|
|
54
|
+
message = where + first["message"]
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
retry_after = headers["retry-after"].to_s
|
|
59
|
+
new(status, code, message, retry_after.match?(/\A\d+\z/) ? retry_after.to_i : nil)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# A request meeng did not sign, signed too long ago, or that is not an event.
|
|
64
|
+
# +code+ is MISSING_SIGNATURE, MISSING_TIMESTAMP, INVALID_SIGNATURE_FORMAT,
|
|
65
|
+
# INVALID_TIMESTAMP, TIMESTAMP_OUT_OF_RANGE, SIGNATURE_MISMATCH, INVALID_BODY or
|
|
66
|
+
# INVALID_JSON.
|
|
67
|
+
class WebhookVerificationError < StandardError
|
|
68
|
+
attr_reader :code
|
|
69
|
+
|
|
70
|
+
def initialize(code, message)
|
|
71
|
+
@code = code
|
|
72
|
+
super("#{code}: #{message}")
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdk/generator. DO NOT EDIT.
|
|
4
|
+
|
|
5
|
+
module Meeng
|
|
6
|
+
# The API's emails.
|
|
7
|
+
class EmailsService
|
|
8
|
+
def initialize(client)
|
|
9
|
+
@client = client
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Sends an email, now or at scheduledAt.
|
|
13
|
+
#
|
|
14
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
15
|
+
# +to+
|
|
16
|
+
# +from+
|
|
17
|
+
# +subject+ (optional)
|
|
18
|
+
# +templateId+ (optional)
|
|
19
|
+
# +variables+ (optional)
|
|
20
|
+
# +replyTo+ (optional)
|
|
21
|
+
# +cc+ (optional)
|
|
22
|
+
# +bcc+ (optional)
|
|
23
|
+
# +text+ (optional)
|
|
24
|
+
# +html+ (optional)
|
|
25
|
+
# +headers+ (optional)
|
|
26
|
+
# +scheduledAt+ (optional)
|
|
27
|
+
# +inReplyToId+ (optional)
|
|
28
|
+
# @param idempotency_key [String, nil] makes the send safe to retry: the same key with the same body answers the first result again
|
|
29
|
+
# @return [Hash]
|
|
30
|
+
def send(payload, idempotency_key: nil)
|
|
31
|
+
@client.request("POST", "/v1/emails", body: payload, idempotency_key: idempotency_key)
|
|
32
|
+
end
|
|
33
|
+
alias_method :create, :send
|
|
34
|
+
|
|
35
|
+
# Sends up to 100 emails in one request.
|
|
36
|
+
#
|
|
37
|
+
# @param payload [Array<Hash>] the body, with the API's own names:
|
|
38
|
+
# +to+
|
|
39
|
+
# +from+
|
|
40
|
+
# +subject+ (optional)
|
|
41
|
+
# +templateId+ (optional)
|
|
42
|
+
# +variables+ (optional)
|
|
43
|
+
# +replyTo+ (optional)
|
|
44
|
+
# +cc+ (optional)
|
|
45
|
+
# +bcc+ (optional)
|
|
46
|
+
# +text+ (optional)
|
|
47
|
+
# +html+ (optional)
|
|
48
|
+
# +headers+ (optional)
|
|
49
|
+
# +scheduledAt+ (optional)
|
|
50
|
+
# +inReplyToId+ (optional)
|
|
51
|
+
# @param idempotency_key [String, nil] makes the send safe to retry: the same key with the same body answers the first result again
|
|
52
|
+
# @return [Hash]
|
|
53
|
+
def batch(payload, idempotency_key: nil)
|
|
54
|
+
@client.request("POST", "/v1/emails/batch", body: payload, idempotency_key: idempotency_key)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Reads one email with its events.
|
|
58
|
+
#
|
|
59
|
+
# @param emailId [String, Integer]
|
|
60
|
+
# @return [Hash]
|
|
61
|
+
def get(emailId)
|
|
62
|
+
@client.request("GET", "/v1/emails/#{Meeng.segment(emailId)}")
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Lists emails, newest first, with an optional date range and domain filter.
|
|
66
|
+
#
|
|
67
|
+
# @param page [Integer, nil] The page, from 1.
|
|
68
|
+
# @param limit [Integer, nil] The items a page: 1 to 100, 50 by default.
|
|
69
|
+
# @param start_date [String, nil] Only emails created at or after this time (RFC 3339).
|
|
70
|
+
# @param end_date [String, nil] Only emails created at or before this time (RFC 3339).
|
|
71
|
+
# @param domain_id [String, Array<String>, nil] Only emails of these domains; a list sends one domainId for each value.
|
|
72
|
+
# @return [Hash]
|
|
73
|
+
def list(page: nil, limit: nil, start_date: nil, end_date: nil, domain_id: nil)
|
|
74
|
+
query = {
|
|
75
|
+
"page" => page,
|
|
76
|
+
"limit" => limit,
|
|
77
|
+
"startDate" => start_date,
|
|
78
|
+
"endDate" => end_date,
|
|
79
|
+
"domainId" => domain_id,
|
|
80
|
+
}
|
|
81
|
+
@client.request("GET", "/v1/emails", query: query)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Reschedules an email that has not been sent.
|
|
85
|
+
#
|
|
86
|
+
# @param emailId [String, Integer]
|
|
87
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
88
|
+
# +scheduledAt+
|
|
89
|
+
# @return [Hash]
|
|
90
|
+
def update(emailId, payload)
|
|
91
|
+
@client.request("PATCH", "/v1/emails/#{Meeng.segment(emailId)}", body: payload)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Cancels a scheduled email.
|
|
95
|
+
#
|
|
96
|
+
# @param emailId [String, Integer]
|
|
97
|
+
# @return [Hash]
|
|
98
|
+
def cancel(emailId)
|
|
99
|
+
@client.request("POST", "/v1/emails/#{Meeng.segment(emailId)}/cancel", body: {})
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The API's domains.
|
|
104
|
+
class DomainsService
|
|
105
|
+
def initialize(client)
|
|
106
|
+
@client = client
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Lists the sending domains of the team.
|
|
110
|
+
#
|
|
111
|
+
# @return [Array<Hash>]
|
|
112
|
+
def list()
|
|
113
|
+
@client.request("GET", "/v1/domains")
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# Adds a sending domain and returns the DNS records to publish.
|
|
117
|
+
#
|
|
118
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
119
|
+
# +name+
|
|
120
|
+
# +region+
|
|
121
|
+
# @return [Hash]
|
|
122
|
+
def create(payload)
|
|
123
|
+
@client.request("POST", "/v1/domains", body: payload)
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Asks for the domain's DNS records to be checked again.
|
|
127
|
+
#
|
|
128
|
+
# @param id [String, Integer]
|
|
129
|
+
# @return [Hash]
|
|
130
|
+
def verify(id)
|
|
131
|
+
@client.request("PUT", "/v1/domains/#{Meeng.segment(id)}/verify", body: {})
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Reads one domain with its DNS records.
|
|
135
|
+
#
|
|
136
|
+
# @param id [String, Integer]
|
|
137
|
+
# @return [Hash]
|
|
138
|
+
def get(id)
|
|
139
|
+
@client.request("GET", "/v1/domains/#{Meeng.segment(id)}")
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Removes a domain.
|
|
143
|
+
#
|
|
144
|
+
# @param id [String, Integer]
|
|
145
|
+
# @return [Hash]
|
|
146
|
+
def delete(id)
|
|
147
|
+
@client.request("DELETE", "/v1/domains/#{Meeng.segment(id)}")
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# The API's contacts.
|
|
152
|
+
class ContactsService
|
|
153
|
+
def initialize(client)
|
|
154
|
+
@client = client
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Adds a contact to a contact book.
|
|
158
|
+
#
|
|
159
|
+
# @param contactBookId [String, Integer]
|
|
160
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
161
|
+
# +email+
|
|
162
|
+
# +firstName+ (optional)
|
|
163
|
+
# +lastName+ (optional)
|
|
164
|
+
# +properties+ (optional)
|
|
165
|
+
# +subscribed+ (optional)
|
|
166
|
+
# @return [Hash]
|
|
167
|
+
def create(contactBookId, payload)
|
|
168
|
+
@client.request("POST", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts", body: payload)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# Lists the contacts of a contact book, optionally by email or id.
|
|
172
|
+
#
|
|
173
|
+
# @param contactBookId [String, Integer]
|
|
174
|
+
# @param emails [String, nil] Endereços de e-mail separados por vírgula; correspondência exata.
|
|
175
|
+
# @param page [Integer, nil] A página, a partir de 1.
|
|
176
|
+
# @param limit [Integer, nil] Contatos por página; 5000 quando não é informado.
|
|
177
|
+
# @param ids [String, nil] Ids de contatos separados por vírgula.
|
|
178
|
+
# @return [Array<Hash>]
|
|
179
|
+
def list(contactBookId, emails: nil, page: nil, limit: nil, ids: nil)
|
|
180
|
+
query = {
|
|
181
|
+
"emails" => emails,
|
|
182
|
+
"page" => page,
|
|
183
|
+
"limit" => limit,
|
|
184
|
+
"ids" => ids,
|
|
185
|
+
}
|
|
186
|
+
@client.request("GET", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts", query: query)
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
# Reads one contact.
|
|
190
|
+
#
|
|
191
|
+
# @param contactBookId [String, Integer]
|
|
192
|
+
# @param contactId [String, Integer]
|
|
193
|
+
# @return [Hash]
|
|
194
|
+
def get(contactBookId, contactId)
|
|
195
|
+
@client.request("GET", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/#{Meeng.segment(contactId)}")
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
# Changes the fields of a contact that are sent.
|
|
199
|
+
#
|
|
200
|
+
# @param contactBookId [String, Integer]
|
|
201
|
+
# @param contactId [String, Integer]
|
|
202
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
203
|
+
# +firstName+ (optional)
|
|
204
|
+
# +lastName+ (optional)
|
|
205
|
+
# +properties+ (optional)
|
|
206
|
+
# +subscribed+ (optional)
|
|
207
|
+
# @return [Hash]
|
|
208
|
+
def update(contactBookId, contactId, payload)
|
|
209
|
+
@client.request("PATCH", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/#{Meeng.segment(contactId)}", body: payload)
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
# Creates the contact, or replaces it when it exists.
|
|
213
|
+
#
|
|
214
|
+
# @param contactBookId [String, Integer]
|
|
215
|
+
# @param contactId [String, Integer]
|
|
216
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
217
|
+
# +email+
|
|
218
|
+
# +firstName+ (optional)
|
|
219
|
+
# +lastName+ (optional)
|
|
220
|
+
# +properties+ (optional)
|
|
221
|
+
# +subscribed+ (optional)
|
|
222
|
+
# @return [Hash]
|
|
223
|
+
def upsert(contactBookId, contactId, payload)
|
|
224
|
+
@client.request("PUT", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/#{Meeng.segment(contactId)}", body: payload)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# Removes a contact.
|
|
228
|
+
#
|
|
229
|
+
# @param contactBookId [String, Integer]
|
|
230
|
+
# @param contactId [String, Integer]
|
|
231
|
+
# @return [Hash]
|
|
232
|
+
def delete(contactBookId, contactId)
|
|
233
|
+
@client.request("DELETE", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/#{Meeng.segment(contactId)}")
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# Adds many contacts to a contact book in one request.
|
|
237
|
+
#
|
|
238
|
+
# @param contactBookId [String, Integer]
|
|
239
|
+
# @param payload [Array<Hash>] the body, with the API's own names:
|
|
240
|
+
# +email+
|
|
241
|
+
# +firstName+ (optional)
|
|
242
|
+
# +lastName+ (optional)
|
|
243
|
+
# +properties+ (optional)
|
|
244
|
+
# +subscribed+ (optional)
|
|
245
|
+
# @return [Hash]
|
|
246
|
+
def bulk_create(contactBookId, payload)
|
|
247
|
+
@client.request("POST", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/bulk", body: payload)
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# Removes many contacts from a contact book in one request.
|
|
251
|
+
#
|
|
252
|
+
# @param contactBookId [String, Integer]
|
|
253
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
254
|
+
# +contactIds+
|
|
255
|
+
# @return [Hash]
|
|
256
|
+
def bulk_delete(contactBookId, payload)
|
|
257
|
+
@client.request("DELETE", "/v1/contactBooks/#{Meeng.segment(contactBookId)}/contacts/bulk", body: payload)
|
|
258
|
+
end
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# The API's contactBooks.
|
|
262
|
+
class ContactBooksService
|
|
263
|
+
def initialize(client)
|
|
264
|
+
@client = client
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# Lists the contact books of the team.
|
|
268
|
+
#
|
|
269
|
+
# @return [Array<Hash>]
|
|
270
|
+
def list()
|
|
271
|
+
@client.request("GET", "/v1/contactBooks")
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
# Creates a contact book.
|
|
275
|
+
#
|
|
276
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
277
|
+
# +name+
|
|
278
|
+
# +emoji+ (optional)
|
|
279
|
+
# +properties+ (optional)
|
|
280
|
+
# +doubleOptInEnabled+ (optional)
|
|
281
|
+
# +doubleOptInFrom+ (optional)
|
|
282
|
+
# +doubleOptInSubject+ (optional)
|
|
283
|
+
# +doubleOptInContent+ (optional)
|
|
284
|
+
# +variables+ (optional)
|
|
285
|
+
# @return [Hash]
|
|
286
|
+
def create(payload)
|
|
287
|
+
@client.request("POST", "/v1/contactBooks", body: payload)
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# Reads one contact book.
|
|
291
|
+
#
|
|
292
|
+
# @param contactBookId [String, Integer]
|
|
293
|
+
# @return [Hash]
|
|
294
|
+
def get(contactBookId)
|
|
295
|
+
@client.request("GET", "/v1/contactBooks/#{Meeng.segment(contactBookId)}")
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
# Changes the fields of a contact book that are sent.
|
|
299
|
+
#
|
|
300
|
+
# @param contactBookId [String, Integer]
|
|
301
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
302
|
+
# +name+ (optional)
|
|
303
|
+
# +emoji+ (optional)
|
|
304
|
+
# +properties+ (optional)
|
|
305
|
+
# +doubleOptInEnabled+ (optional)
|
|
306
|
+
# +doubleOptInFrom+ (optional)
|
|
307
|
+
# +doubleOptInSubject+ (optional)
|
|
308
|
+
# +doubleOptInContent+ (optional)
|
|
309
|
+
# +variables+ (optional)
|
|
310
|
+
# @return [Hash]
|
|
311
|
+
def update(contactBookId, payload)
|
|
312
|
+
@client.request("PATCH", "/v1/contactBooks/#{Meeng.segment(contactBookId)}", body: payload)
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# Removes a contact book and its contacts.
|
|
316
|
+
#
|
|
317
|
+
# @param contactBookId [String, Integer]
|
|
318
|
+
# @return [Hash]
|
|
319
|
+
def delete(contactBookId)
|
|
320
|
+
@client.request("DELETE", "/v1/contactBooks/#{Meeng.segment(contactBookId)}")
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
# The API's campaigns.
|
|
325
|
+
class CampaignsService
|
|
326
|
+
def initialize(client)
|
|
327
|
+
@client = client
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# Creates a campaign, and sends it now when sendNow is true.
|
|
331
|
+
#
|
|
332
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
333
|
+
# +name+
|
|
334
|
+
# +from+
|
|
335
|
+
# +subject+
|
|
336
|
+
# +previewText+ (optional)
|
|
337
|
+
# +contactBookId+
|
|
338
|
+
# +content+ (optional)
|
|
339
|
+
# +html+ (optional)
|
|
340
|
+
# +replyTo+ (optional)
|
|
341
|
+
# +cc+ (optional)
|
|
342
|
+
# +bcc+ (optional)
|
|
343
|
+
# +sendNow+ (optional)
|
|
344
|
+
# +scheduledAt+ (optional)
|
|
345
|
+
# +batchSize+ (optional)
|
|
346
|
+
# @return [Hash]
|
|
347
|
+
def create(payload)
|
|
348
|
+
@client.request("POST", "/v1/campaigns", body: payload)
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
# Lists campaigns, optionally by status or a search text.
|
|
352
|
+
#
|
|
353
|
+
# @param page [Integer, nil] A página, a partir de 1; 30 campanhas por página.
|
|
354
|
+
# @param status [String, nil] Só campanhas neste status.
|
|
355
|
+
# @param search [String, nil] Parte do nome ou do assunto.
|
|
356
|
+
# @return [Hash]
|
|
357
|
+
def list(page: nil, status: nil, search: nil)
|
|
358
|
+
query = {
|
|
359
|
+
"page" => page,
|
|
360
|
+
"status" => status,
|
|
361
|
+
"search" => search,
|
|
362
|
+
}
|
|
363
|
+
@client.request("GET", "/v1/campaigns", query: query)
|
|
364
|
+
end
|
|
365
|
+
alias_method :get_all, :list
|
|
366
|
+
|
|
367
|
+
# Reads one campaign with its counters.
|
|
368
|
+
#
|
|
369
|
+
# @param campaignId [String, Integer]
|
|
370
|
+
# @return [Hash]
|
|
371
|
+
def get(campaignId)
|
|
372
|
+
@client.request("GET", "/v1/campaigns/#{Meeng.segment(campaignId)}")
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
# Removes a campaign.
|
|
376
|
+
#
|
|
377
|
+
# @param campaignId [String, Integer]
|
|
378
|
+
# @return [Hash]
|
|
379
|
+
def delete(campaignId)
|
|
380
|
+
@client.request("DELETE", "/v1/campaigns/#{Meeng.segment(campaignId)}")
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
# Schedules a campaign, or sends it now when no time is given.
|
|
384
|
+
#
|
|
385
|
+
# @param campaignId [String, Integer]
|
|
386
|
+
# @param payload [Hash] the body, with the API's own names:
|
|
387
|
+
# +scheduledAt+ (optional)
|
|
388
|
+
# +batchSize+ (optional)
|
|
389
|
+
# @return [Hash]
|
|
390
|
+
def schedule(campaignId, payload)
|
|
391
|
+
@client.request("POST", "/v1/campaigns/#{Meeng.segment(campaignId)}/schedule", body: payload)
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
# Pauses a running or scheduled campaign.
|
|
395
|
+
#
|
|
396
|
+
# @param campaignId [String, Integer]
|
|
397
|
+
# @return [Hash]
|
|
398
|
+
def pause(campaignId)
|
|
399
|
+
@client.request("POST", "/v1/campaigns/#{Meeng.segment(campaignId)}/pause", body: {})
|
|
400
|
+
end
|
|
401
|
+
|
|
402
|
+
# Resumes a paused campaign.
|
|
403
|
+
#
|
|
404
|
+
# @param campaignId [String, Integer]
|
|
405
|
+
# @return [Hash]
|
|
406
|
+
def resume(campaignId)
|
|
407
|
+
@client.request("POST", "/v1/campaigns/#{Meeng.segment(campaignId)}/resume", body: {})
|
|
408
|
+
end
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
# The API's analytics.
|
|
412
|
+
class AnalyticsService
|
|
413
|
+
def initialize(client)
|
|
414
|
+
@client = client
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
# Counts emails by day over the last 7 or 30 days.
|
|
418
|
+
#
|
|
419
|
+
# @param days [String, nil] Quantos dias para trás contar: 7 ou 30 (padrão 30). A resposta traz uma entrada para cada um desses dias e uma para hoje.
|
|
420
|
+
# @param domain_id [String, nil] Conta só este domínio, pelo id numérico. Um valor que não seja número não filtra nada. Uma chave restrita a um domínio lê esse domínio e ignora este parâmetro.
|
|
421
|
+
# @return [Hash]
|
|
422
|
+
def email_time_series(days: nil, domain_id: nil)
|
|
423
|
+
query = {
|
|
424
|
+
"days" => days,
|
|
425
|
+
"domainId" => domain_id,
|
|
426
|
+
}
|
|
427
|
+
@client.request("GET", "/v1/analytics/email-time-series", query: query)
|
|
428
|
+
end
|
|
429
|
+
|
|
430
|
+
# Reads the bounce and complaint rates of the sending reputation.
|
|
431
|
+
#
|
|
432
|
+
# @param domain_id [String, nil] Lê só este domínio, pelo id numérico. Um valor que não seja número não filtra nada. Uma chave restrita a um domínio lê esse domínio e ignora este parâmetro.
|
|
433
|
+
# @return [Hash]
|
|
434
|
+
def reputation_metrics(domain_id: nil)
|
|
435
|
+
query = {
|
|
436
|
+
"domainId" => domain_id,
|
|
437
|
+
}
|
|
438
|
+
@client.request("GET", "/v1/analytics/reputation-metrics", query: query)
|
|
439
|
+
end
|
|
440
|
+
end
|
|
441
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdk/generator. DO NOT EDIT.
|
|
4
|
+
|
|
5
|
+
module Meeng
|
|
6
|
+
# This SDK's version.
|
|
7
|
+
VERSION = "0.1.0"
|
|
8
|
+
|
|
9
|
+
# The contract this SDK was generated from.
|
|
10
|
+
API_VERSION = "1.0.0"
|
|
11
|
+
|
|
12
|
+
# Where meeng's API lives. The client appends +/api/v1+ to it, so
|
|
13
|
+
# MEENG_BASE_URL, like the +base_url+ argument, is the address of the app and
|
|
14
|
+
# nothing more.
|
|
15
|
+
DEFAULT_BASE_URL = "https://meeng.dev"
|
|
16
|
+
|
|
17
|
+
# What every path starts with, after the base URL.
|
|
18
|
+
API_PREFIX = "/api"
|
|
19
|
+
end
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdk/generator. DO NOT EDIT.
|
|
4
|
+
|
|
5
|
+
require "json"
|
|
6
|
+
require "openssl"
|
|
7
|
+
|
|
8
|
+
module Meeng
|
|
9
|
+
# Checks and reads the webhooks a team's endpoint receives. Make one with
|
|
10
|
+
# +meeng.webhooks(secret)+.
|
|
11
|
+
#
|
|
12
|
+
# event = meeng.webhooks("whsec_xxx").construct_event(request.body.read, headers: request.headers)
|
|
13
|
+
# puts event[:data][:to] if event[:type] == "email.delivered"
|
|
14
|
+
#
|
|
15
|
+
# An event is a hash with +:id+ (the id of the delivery, the same on every attempt),
|
|
16
|
+
# +:type+, +:version+, +:createdAt+, +:teamId+, +:attempt+ (1 to 6) and +:data+. The
|
|
17
|
+
# events, by +type+ (the data of each is a hash with the API's own names):
|
|
18
|
+
#
|
|
19
|
+
# * +contact.created+, +contact.updated+, +contact.deleted+: a ContactPayload
|
|
20
|
+
#
|
|
21
|
+
# * +domain.created+, +domain.verified+, +domain.updated+, +domain.deleted+: a DomainPayload
|
|
22
|
+
#
|
|
23
|
+
# * +email.queued+, +email.sent+, +email.delivery_delayed+, +email.delivered+, +email.rejected+, +email.rendering_failure+, +email.complained+, +email.cancelled+: an EmailBasePayload
|
|
24
|
+
#
|
|
25
|
+
# * +email.bounced+: an EmailBouncedPayload
|
|
26
|
+
#
|
|
27
|
+
# * +email.clicked+: an EmailClickedPayload
|
|
28
|
+
#
|
|
29
|
+
# * +email.failed+: an EmailFailedPayload
|
|
30
|
+
#
|
|
31
|
+
# * +email.opened+: an EmailOpenedPayload
|
|
32
|
+
#
|
|
33
|
+
# * +email.suppressed+: an EmailSuppressedPayload
|
|
34
|
+
#
|
|
35
|
+
# * +webhook.test+: a WebhookTestPayload
|
|
36
|
+
class Webhooks
|
|
37
|
+
# The header that carries the signature: +v1=+ and the HMAC-SHA256 of
|
|
38
|
+
# +{timestamp}.{body}+, in hex.
|
|
39
|
+
SIGNATURE_HEADER = "X-Meeng-Signature"
|
|
40
|
+
# The header that carries the time the webhook was sent, in milliseconds
|
|
41
|
+
# since the epoch.
|
|
42
|
+
TIMESTAMP_HEADER = "X-Meeng-Timestamp"
|
|
43
|
+
# The header that carries the event's type.
|
|
44
|
+
EVENT_HEADER = "X-Meeng-Event"
|
|
45
|
+
# The header that carries the id of the delivery attempt.
|
|
46
|
+
CALL_HEADER = "X-Meeng-Call"
|
|
47
|
+
# How far from now, in milliseconds, a timestamp may be.
|
|
48
|
+
DEFAULT_TOLERANCE_MS = 5 * 60 * 1000
|
|
49
|
+
|
|
50
|
+
SIGNATURE_PREFIX = "v1="
|
|
51
|
+
private_constant :SIGNATURE_PREFIX
|
|
52
|
+
|
|
53
|
+
def initialize(secret)
|
|
54
|
+
@secret = secret
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Checks the signature without reading the event; true when it is valid.
|
|
58
|
+
# +body+ is exactly what arrived, before parsing. +tolerance+ is in
|
|
59
|
+
# milliseconds (5 minutes by default; a negative number turns the check off),
|
|
60
|
+
# +secret+ replaces the handler's, +now+ is the current time in milliseconds,
|
|
61
|
+
# for tests.
|
|
62
|
+
def verify(body, headers:, secret: nil, tolerance: nil, now: nil)
|
|
63
|
+
check(body, headers, secret, tolerance, now)
|
|
64
|
+
true
|
|
65
|
+
rescue WebhookVerificationError
|
|
66
|
+
false
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Checks the signature and reads the event, a hash with symbol keys; raises
|
|
70
|
+
# WebhookVerificationError when the request is not one meeng signed.
|
|
71
|
+
def construct_event(body, headers:, secret: nil, tolerance: nil, now: nil)
|
|
72
|
+
check(body, headers, secret, tolerance, now)
|
|
73
|
+
begin
|
|
74
|
+
JSON.parse(body.to_s, symbolize_names: true)
|
|
75
|
+
rescue JSON::ParserError
|
|
76
|
+
raise WebhookVerificationError.new("INVALID_JSON", "Webhook payload is not valid JSON")
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
private
|
|
81
|
+
|
|
82
|
+
def check(body, headers, secret, tolerance, now)
|
|
83
|
+
key = secret || @secret
|
|
84
|
+
signature = header(headers, SIGNATURE_HEADER)
|
|
85
|
+
timestamp = header(headers, TIMESTAMP_HEADER)
|
|
86
|
+
raise WebhookVerificationError.new("MISSING_SIGNATURE", "Missing #{SIGNATURE_HEADER} header") if signature.nil? || signature.empty?
|
|
87
|
+
raise WebhookVerificationError.new("MISSING_TIMESTAMP", "Missing #{TIMESTAMP_HEADER} header") if timestamp.nil? || timestamp.empty?
|
|
88
|
+
raise WebhookVerificationError.new("INVALID_SIGNATURE_FORMAT", "Signature header must start with v1=") unless signature.start_with?(SIGNATURE_PREFIX)
|
|
89
|
+
|
|
90
|
+
sent = Float(timestamp.strip, exception: false)
|
|
91
|
+
unless sent&.finite?
|
|
92
|
+
raise WebhookVerificationError.new("INVALID_TIMESTAMP", "Timestamp header must be a number (milliseconds since epoch)")
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
tolerance_ms = tolerance || DEFAULT_TOLERANCE_MS
|
|
96
|
+
current = now || (Time.now.to_f * 1000)
|
|
97
|
+
if tolerance_ms >= 0 && (current - sent).abs > tolerance_ms
|
|
98
|
+
raise WebhookVerificationError.new("TIMESTAMP_OUT_OF_RANGE", "Webhook timestamp is outside the allowed tolerance")
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
expected = SIGNATURE_PREFIX + OpenSSL::HMAC.hexdigest("SHA256", key, "#{timestamp}.#{body}")
|
|
102
|
+
return if expected.bytesize == signature.bytesize && OpenSSL.fixed_length_secure_compare(expected, signature)
|
|
103
|
+
|
|
104
|
+
raise WebhookVerificationError.new("SIGNATURE_MISMATCH", "Webhook signature does not match")
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def header(headers, name)
|
|
108
|
+
lower = name.downcase
|
|
109
|
+
headers.each do |key, value|
|
|
110
|
+
next unless key.to_s.downcase == lower
|
|
111
|
+
|
|
112
|
+
value = value.first if value.is_a?(Array)
|
|
113
|
+
return value&.to_s
|
|
114
|
+
end
|
|
115
|
+
nil
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
end
|
data/lib/meeng.rb
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdk/generator. DO NOT EDIT.
|
|
4
|
+
|
|
5
|
+
# meeng's SDK for Ruby, generated from meeng's API contract.
|
|
6
|
+
#
|
|
7
|
+
# meeng = Meeng::Client.new("mg_123")
|
|
8
|
+
# sent = meeng.emails.send(from: "hello@acme.com", to: "customer@example.com", subject: "Hello", html: "<p>Hello</p>")
|
|
9
|
+
# sent[:emailId]
|
|
10
|
+
module Meeng
|
|
11
|
+
# A path parameter, escaped.
|
|
12
|
+
def self.segment(value)
|
|
13
|
+
value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/) { |char| format("%%%02X", char.ord) }
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
require_relative "meeng/version"
|
|
18
|
+
require_relative "meeng/error"
|
|
19
|
+
require_relative "meeng/services"
|
|
20
|
+
require_relative "meeng/webhooks"
|
|
21
|
+
require_relative "meeng/client"
|
metadata
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: meeng-sdk
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Meeng.dev
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
executables: []
|
|
13
|
+
extensions: []
|
|
14
|
+
extra_rdoc_files: []
|
|
15
|
+
files:
|
|
16
|
+
- README.md
|
|
17
|
+
- lib/meeng.rb
|
|
18
|
+
- lib/meeng/client.rb
|
|
19
|
+
- lib/meeng/error.rb
|
|
20
|
+
- lib/meeng/services.rb
|
|
21
|
+
- lib/meeng/version.rb
|
|
22
|
+
- lib/meeng/webhooks.rb
|
|
23
|
+
homepage: https://meeng.dev
|
|
24
|
+
licenses:
|
|
25
|
+
- MIT
|
|
26
|
+
metadata:
|
|
27
|
+
homepage_uri: https://meeng.dev
|
|
28
|
+
source_code_uri: https://github.com/meeng-dev/sdk
|
|
29
|
+
rubygems_mfa_required: 'true'
|
|
30
|
+
rdoc_options: []
|
|
31
|
+
require_paths:
|
|
32
|
+
- lib
|
|
33
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
34
|
+
requirements:
|
|
35
|
+
- - ">="
|
|
36
|
+
- !ruby/object:Gem::Version
|
|
37
|
+
version: '3.1'
|
|
38
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
39
|
+
requirements:
|
|
40
|
+
- - ">="
|
|
41
|
+
- !ruby/object:Gem::Version
|
|
42
|
+
version: '0'
|
|
43
|
+
requirements: []
|
|
44
|
+
rubygems_version: 4.0.16
|
|
45
|
+
specification_version: 4
|
|
46
|
+
summary: 'Meeng.dev''s SDK for Ruby: emails, domains, contacts, contact books, campaigns,
|
|
47
|
+
analytics and webhooks.'
|
|
48
|
+
test_files: []
|