mundosms 1.2.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 +59 -0
- data/lib/mundosms.rb +477 -0
- metadata +50 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: b576064fac420cc608d8251b480d54c8e67605103d41bce0d701760dace5708d
|
|
4
|
+
data.tar.gz: c9f8e34947d6572ef61dad8711f419feee5697ed1fa50c24265c060287616ada
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 4889bc8b39afc679ee7d3e7cb383baed7c725182259a4f14c76dc7930c90dd1ff5f86a17bac059aa6669bc3b9c4ea64e3dd8640aefcea83bae3d2d9a9ab9c61c
|
|
7
|
+
data.tar.gz: 9e60a195c98e374da925fbe7c1371f2d0badd5334fdd49aa46228a68810e58f882b8cfe12935a94b39bad2e2e513dedd24b4e2bc461d23d979aaa3a6abb86ea3
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MundoSMS
|
|
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,59 @@
|
|
|
1
|
+
# mundosms
|
|
2
|
+
|
|
3
|
+
Cliente Ruby de la [API REST v3 de MundoSMS](https://www.mundosms.es/api-v3): centralita, llamadas, SMS, VozPush, NumCheck y
|
|
4
|
+
WhatsApp. Firma cada petición por ti (`X-Timestamp` en milisegundos y la firma HMAC de tu API Key), pone una
|
|
5
|
+
`Idempotency-Key` en cada `POST` para que un reintento no envíe nada dos veces, y reintenta solo lo que es seguro repetir.
|
|
6
|
+
Comprueba también la firma de los avisos que te mandamos. Un solo fichero, sin dependencias: solo la biblioteca estándar.
|
|
7
|
+
|
|
8
|
+
Requiere Ruby 3.1 o superior.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
gem install mundosms
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
(o `gem "mundosms"` en tu `Gemfile`). Las API Keys (token y clave privada) se crean en el panel de MundoSMS, en **API y
|
|
15
|
+
Soporte → Claves de API**.
|
|
16
|
+
|
|
17
|
+
## Uso
|
|
18
|
+
|
|
19
|
+
```ruby
|
|
20
|
+
require "mundosms"
|
|
21
|
+
|
|
22
|
+
api = MundoSMS::Client.new("TU_TOKEN", "TU_CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
|
|
23
|
+
r = api.post("/sms", { "to" => "34600123456", "text" => "Tu cita es mañana a las 10:00", "from" => "MiClinica" })
|
|
24
|
+
puts r["data"]["id"]
|
|
25
|
+
|
|
26
|
+
api.all("/calls", { "from_datetime" => "2026-11-01" }).each do |call|
|
|
27
|
+
puts "#{call['type']} #{call['id']} #{call['state']}"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
begin
|
|
31
|
+
api.patch("/extensions/recepcion", { "record_calls" => true })
|
|
32
|
+
rescue MundoSMS::Error => e
|
|
33
|
+
puts [e.http, e.status_code, e.message, e.detail, e.request_id].join(" ")
|
|
34
|
+
end
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
- `get(path, query)`, `post(path, data)`, `patch(path, data)` y `delete(path, query)` devuelven la respuesta entera, un
|
|
38
|
+
`Hash` con claves de texto. La ruta va sin `/v3`. `request(method, path, data)` hace una petición cualquiera.
|
|
39
|
+
- `all(path, query)` recorre todas las páginas de un listado (un `Enumerator::Lazy`: pide cada página al llegar a ella).
|
|
40
|
+
Al acabar, el último `next_cursor` queda en `last_cursor`; `last_rate_limit` es el cupo (`X-RateLimit-*`) de la última
|
|
41
|
+
respuesta.
|
|
42
|
+
- Cualquier error es un `MundoSMS::Error` con `http`, `status_code`, `message`, `detail`, `data`, `request_id` y `response`.
|
|
43
|
+
Un WhatsApp sin confirmar (`202`, `data["state"]` `"unknown"`: puede haber salido) no es un error: vuelve la respuesta.
|
|
44
|
+
- Cada `POST` lleva una `Idempotency-Key`, la misma en todos sus intentos; la tuya, con
|
|
45
|
+
`api.post(path, data, idempotency_key: "pedido-881")`.
|
|
46
|
+
- Una redirección no se sigue nunca (llevaría tu firma a otro servidor): es un `MundoSMS::Error`.
|
|
47
|
+
- `MundoSMS.verify_webhook(secret, header, body)` comprueba la cabecera `X-MundoSMS-Signature` de un aviso que te llega, con
|
|
48
|
+
el cuerpo tal cual llegó (en Rails, `request.raw_post`, nunca `params`): `true` o `false`.
|
|
49
|
+
- Opciones, con nombre: `MundoSMS::Client.new(token, private_key, base_url: …, retries: 3, timeout: 60)`.
|
|
50
|
+
|
|
51
|
+
## Documentación
|
|
52
|
+
|
|
53
|
+
La referencia completa de cada ruta, sus parámetros y sus respuestas: **[www.mundosms.es/api-v3](https://www.mundosms.es/api-v3)**.
|
|
54
|
+
El código, los clientes en PHP, Python, Node.js, Java, C# y Go, y los cambios de cada versión:
|
|
55
|
+
[github.com/mundosms/mundosms-sdk](https://github.com/mundosms/mundosms-sdk).
|
|
56
|
+
|
|
57
|
+
## Licencia
|
|
58
|
+
|
|
59
|
+
[MIT](https://github.com/mundosms/mundosms-sdk/blob/main/LICENSE).
|
data/lib/mundosms.rb
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# MundoSMS API v3 — cliente Ruby en un solo fichero (Ruby 3.1 o superior). Sin dependencias: solo la biblioteca estándar.
|
|
4
|
+
# Documentación: https://www.mundosms.es/api-v3
|
|
5
|
+
# Código y versiones: https://github.com/mundosms/mundosms-sdk (licencia MIT)
|
|
6
|
+
#
|
|
7
|
+
# require "mundosms"
|
|
8
|
+
# api = MundoSMS::Client.new("TOKEN", "CLAVE_PRIVADA") # la clave privada, "" si tu API Key no exige firma
|
|
9
|
+
# r = api.post("/sms", { "to" => "34600123456", "text" => "Hola", "from" => "MiEmpresa" })
|
|
10
|
+
# puts r["data"]["id"]
|
|
11
|
+
# api.all("/calls", { "from_datetime" => "2026-11-01", "stop_at_ongoing" => true }).each { |call| ... }
|
|
12
|
+
#
|
|
13
|
+
# Errores: excepción MundoSMS::Error con #http (código HTTP), #status_code ("3", "4"…), #message, #detail, #data, #response
|
|
14
|
+
# (la respuesta entera) y #request_id (la cabecera X-Request-Id). También cuando la API contesta con "status": "error",
|
|
15
|
+
# venga con el código HTTP que venga. Un WhatsApp sin confirmar (202) no es un error: vuelve la respuesta, con
|
|
16
|
+
# data["state"] "unknown". Lo que no se puede mandar (una Idempotency-Key mal formada, un cuerpo que no es UTF-8) es un
|
|
17
|
+
# ArgumentError, y no se manda nada.
|
|
18
|
+
# Cada POST lleva una Idempotency-Key (un UUID nuevo en cada llamada, la misma en todos sus intentos; la tuya, con
|
|
19
|
+
# api.post(path, data, idempotency_key: "pedido-881")). Por eso un POST que falla por la red, o con 409 «Request in
|
|
20
|
+
# progress», se repite sin miedo: la API no lo hace dos veces. Si la respuesta es la guardada de la primera vez, trae
|
|
21
|
+
# "idempotent_replayed" => true.
|
|
22
|
+
# Reintenta: un 429, en cualquier método (no se hizo nada); un fallo de red, en cualquier método; un 5xx, solo en GET (un
|
|
23
|
+
# POST con 5xx no se repite: la API no guarda los 5xx, y repetirlo lo haría otra vez). Espera lo que diga Retry-After (como
|
|
24
|
+
# mucho 60 s) o, si no lo trae, 1, 2, 4… s. Un DELETE que se repite tras quedarse sin respuesta y da 404 ya estaba hecho:
|
|
25
|
+
# vuelve como éxito, con data["changed"] false.
|
|
26
|
+
# Una redirección (3xx) no se sigue nunca: es un MundoSMS::Error (la API no redirige). Un 2xx que no es JSON (el HTML de un
|
|
27
|
+
# proxy o de un portal cautivo) también es un error; los ficheros que da la API (audio, imagen, PDF) vuelven por su
|
|
28
|
+
# Content-Type.
|
|
29
|
+
# Los avisos que te mandamos (callback_url y webhooks de WhatsApp) se comprueban con MundoSMS.verify_webhook.
|
|
30
|
+
|
|
31
|
+
require "json"
|
|
32
|
+
require "net/http"
|
|
33
|
+
require "openssl"
|
|
34
|
+
require "securerandom"
|
|
35
|
+
require "time"
|
|
36
|
+
require "timeout"
|
|
37
|
+
require "uri"
|
|
38
|
+
|
|
39
|
+
module MundoSMS
|
|
40
|
+
VERSION = "1.2.0"
|
|
41
|
+
DEFAULT_BASE_URL = "https://api.mundosms.es/v3"
|
|
42
|
+
MAX_RETRY_WAIT = 60 # segundos: lo más que se espera antes de un reintento, aunque Retry-After pida más
|
|
43
|
+
WEBHOOK_TOLERANCE = 300 # segundos: lo más que puede alejarse de tu hora la «t» de la firma de un aviso
|
|
44
|
+
IDEMPOTENCY_KEY = /\A[A-Za-z0-9_.:-]{1,64}\z/.freeze # la forma que exige la API para la Idempotency-Key
|
|
45
|
+
FILE_TYPES = %r{\A(audio/|image/|application/pdf\z|application/octet-stream\z)}.freeze # lo que la API da como fichero
|
|
46
|
+
|
|
47
|
+
# El error de cualquier petición: un 4xx o un 5xx, una respuesta 2xx con "status": "error" o, sin respuesta (la red o el
|
|
48
|
+
# plazo agotado), http 0 y un mensaje que empieza por «No response from the API:».
|
|
49
|
+
class Error < StandardError
|
|
50
|
+
attr_reader :http, # el código HTTP; 0 si no hubo respuesta
|
|
51
|
+
:status_code, # el status_code de la API, como texto ("3", "4", "12"…)
|
|
52
|
+
:detail, # el detail de la respuesta, si lo trae
|
|
53
|
+
:data, # el data de la respuesta (en WhatsApp, el id del mensaje que puede haber salido)
|
|
54
|
+
:response, # la respuesta entera, decodificada; nil si no era JSON
|
|
55
|
+
:request_id # la cabecera X-Request-Id: con ella encuentras la petición en Logs API
|
|
56
|
+
|
|
57
|
+
def initialize(message, http: 0, status_code: nil, detail: nil, data: nil, response: nil, request_id: nil)
|
|
58
|
+
super(message)
|
|
59
|
+
@http = http
|
|
60
|
+
@status_code = status_code
|
|
61
|
+
@detail = detail
|
|
62
|
+
@data = data
|
|
63
|
+
@response = response
|
|
64
|
+
@request_id = request_id
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
@timestamp_lock = Mutex.new
|
|
69
|
+
@last_timestamp = 0
|
|
70
|
+
|
|
71
|
+
# El X-Timestamp de una petición: milisegundos, y siempre mayor que el de la anterior de este proceso (también desde
|
|
72
|
+
# varios hilos). Dos peticiones iguales en el mismo milisegundo (un reintento tras un 429 con Retry-After: 0, o dos a la
|
|
73
|
+
# vez) firmarían igual, y la API rechazaría la segunda por repetida («409 Duplicated request»).
|
|
74
|
+
def self.timestamp
|
|
75
|
+
@timestamp_lock.synchronize do
|
|
76
|
+
@last_timestamp = [Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond), @last_timestamp + 1].max
|
|
77
|
+
@last_timestamp.to_s
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# true si un aviso que te llega (callback_url o webhook de WhatsApp) es nuestro y nadie lo ha tocado.
|
|
82
|
+
# secret: el de «API y Soporte → Webhooks» (whsec_…); header: X-MundoSMS-Signature; body: el cuerpo TAL CUAL llegó (en
|
|
83
|
+
# Rails, request.raw_post; en Rack, request.body.read), sin volver a serializar el JSON; tolerance: los segundos que puede
|
|
84
|
+
# alejarse «t» de tu hora. Una cabecera que falta o está mal formada da false, sin excepción.
|
|
85
|
+
def self.verify_webhook(secret, header, body, tolerance: WEBHOOK_TOLERANCE)
|
|
86
|
+
raise ArgumentError, "MundoSMS.verify_webhook: pass the raw body as received (a String), not a decoded value" unless body.is_a?(String)
|
|
87
|
+
|
|
88
|
+
secret = secret.is_a?(String) ? secret.strip : ""
|
|
89
|
+
return false if secret.empty? || !header.is_a?(String)
|
|
90
|
+
|
|
91
|
+
t = nil
|
|
92
|
+
signatures = []
|
|
93
|
+
header.split(",").each do |part|
|
|
94
|
+
k, equals, v = part.partition("=")
|
|
95
|
+
next if equals.empty?
|
|
96
|
+
|
|
97
|
+
k = k.strip
|
|
98
|
+
v = v.strip
|
|
99
|
+
if k == "t"
|
|
100
|
+
return false unless t.nil? # dos «t»: no se sabe cuál vale
|
|
101
|
+
|
|
102
|
+
t = v
|
|
103
|
+
elsif k == "v1"
|
|
104
|
+
signatures << v.downcase
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
return false if t.nil? || !t.match?(/\A[0-9]{1,15}\z/) || signatures.empty?
|
|
108
|
+
return false if (Time.now.to_i - Integer(t, 10)).abs > tolerance
|
|
109
|
+
|
|
110
|
+
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.".b + body.b)
|
|
111
|
+
valid = false
|
|
112
|
+
signatures.each do |sig| # todas, sin cortar en la primera: fixed_length_secure_compare es de tiempo constante
|
|
113
|
+
valid = true if sig.match?(/\A[0-9a-f]{64}\z/) && OpenSSL.fixed_length_secure_compare(expected, sig)
|
|
114
|
+
end
|
|
115
|
+
valid
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# El cliente de la API. Créalo una vez y reutilízalo: se puede usar desde varios hilos a la vez.
|
|
119
|
+
class Client
|
|
120
|
+
# El cursor del último listado recorrido con #all: guárdalo para la siguiente sincronización. Al empezar el recorrido, el
|
|
121
|
+
# cursor que le pasas (o nil); después, el último next_cursor que llegó (una página sin cursor no lo borra).
|
|
122
|
+
attr_reader :last_cursor
|
|
123
|
+
# El cupo que dijo la última respuesta (sus cabeceras X-RateLimit-*): { "limit" => 10, "remaining" => 7, "reset" => 1 }, o
|
|
124
|
+
# nil si no lo traía (o no hubo respuesta).
|
|
125
|
+
attr_reader :last_rate_limit
|
|
126
|
+
attr_reader :base_url, :retries, :timeout
|
|
127
|
+
|
|
128
|
+
# token: el Token de tu API Key (empieza por eyJ); private_key: su clave privada si exige firma (lo normal), o "".
|
|
129
|
+
# base_url: la dirección de la API; retries: cuántas veces se reintenta lo que es seguro repetir (0, ninguna); timeout:
|
|
130
|
+
# los segundos que puede durar cada petición entera (conectar, mandar y recibir la respuesta), con decimales si quieres.
|
|
131
|
+
# Una opción que no existe es un ArgumentError (unknown keyword).
|
|
132
|
+
def initialize(token, private_key = "", base_url: DEFAULT_BASE_URL, retries: 3, timeout: 60)
|
|
133
|
+
uri = URI.parse(base_url.to_s.sub(%r{/+\z}, ""))
|
|
134
|
+
unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty? && uri.query.nil? && uri.fragment.nil?
|
|
135
|
+
raise ArgumentError, "MundoSMS: base_url must be an http(s) address without query, like #{DEFAULT_BASE_URL}"
|
|
136
|
+
end
|
|
137
|
+
raise ArgumentError, "MundoSMS: retries must be an integer, 0 or more" unless retries.is_a?(Integer) && retries >= 0
|
|
138
|
+
raise ArgumentError, "MundoSMS: timeout must be a number of seconds greater than 0" unless timeout.is_a?(Numeric) && timeout.positive?
|
|
139
|
+
|
|
140
|
+
@token = token.to_s.strip
|
|
141
|
+
@private_key = private_key.to_s.strip
|
|
142
|
+
@base_url = base_url.to_s.sub(%r{/+\z}, "")
|
|
143
|
+
@uri = uri
|
|
144
|
+
@base_path = uri.path.to_s
|
|
145
|
+
@retries = retries
|
|
146
|
+
@timeout = timeout
|
|
147
|
+
@last_cursor = nil
|
|
148
|
+
@last_rate_limit = nil
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# Lo que enseñan p, inspect, to_s y pp (que usa este inspect): sin el token ni la clave privada, para que no acaben en un log.
|
|
152
|
+
def inspect
|
|
153
|
+
"#<MundoSMS::Client base_url=#{@base_url.inspect}>"
|
|
154
|
+
end
|
|
155
|
+
alias to_s inspect
|
|
156
|
+
|
|
157
|
+
# GET: query va en la query.
|
|
158
|
+
def get(path, query = {})
|
|
159
|
+
request("GET", path, query)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# POST: data va en un cuerpo JSON. idempotency_key: tu clave para que repetir este POST no lo vuelva a hacer (por ejemplo,
|
|
163
|
+
# el id de tu pedido); sin ella, un UUID nuevo en cada llamada.
|
|
164
|
+
def post(path, data = {}, idempotency_key: nil)
|
|
165
|
+
request("POST", path, data, idempotency_key: idempotency_key)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# PATCH: data va en un cuerpo JSON.
|
|
169
|
+
def patch(path, data)
|
|
170
|
+
request("PATCH", path, data)
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# DELETE: query va en la query.
|
|
174
|
+
def delete(path, query = {})
|
|
175
|
+
request("DELETE", path, query)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# Recorre un listado entero, página a página, siguiendo su cursor (next_cursor), elemento a elemento. Cada página lleva
|
|
179
|
+
# los mismos filtros (y el mismo order) más el cursor, y se pide al llegar a ella. Con un bloque, lo llama con cada
|
|
180
|
+
# elemento; sin él, devuelve un Enumerator::Lazy (api.all("/calls").first(10) pide solo las páginas que hacen falta). Al
|
|
181
|
+
# acabar, el último next_cursor queda en #last_cursor: guárdalo para la siguiente sincronización. Es uno por cliente: para
|
|
182
|
+
# dos recorridos a la vez, un cliente para cada uno. #last_cursor avanza cuando ya te ha dado todos los elementos de una
|
|
183
|
+
# página: si tu código falla a mitad de una, sigue en la anterior.
|
|
184
|
+
# Termina con has_more false (con stop_at_ongoing, también cuando la página se para en una llamada en curso), o si el
|
|
185
|
+
# cursor no avanza. Una página vacía con has_more true (con stop_at_ongoing y un filtro, cuando ha mirado muchas que no
|
|
186
|
+
# casan) no es el final: sigue.
|
|
187
|
+
# Una lista que no va por páginas (GET /calls/missed y /calls/live: has_more sin next_cursor) no se puede recorrer entera:
|
|
188
|
+
# es un MundoSMS::Error, antes de dar nada. Sube limit, o filtra, y pídela con #get.
|
|
189
|
+
def all(path, query = {}, &block)
|
|
190
|
+
enum = Enumerator.new do |y|
|
|
191
|
+
q = (query || {}).to_h { |k, v| [k.to_s, v] }
|
|
192
|
+
@last_cursor = truthy(q["cursor"]) ? q["cursor"] : nil # el de este recorrido: al empezar, el que le pasas
|
|
193
|
+
list_key = nil
|
|
194
|
+
loop do
|
|
195
|
+
r = get(path, q)
|
|
196
|
+
data = r["data"]
|
|
197
|
+
data = {} unless data.is_a?(Hash)
|
|
198
|
+
cursor = data["next_cursor"]
|
|
199
|
+
if truthy(data["has_more"]) && truthy(data["results"]) && !truthy(cursor)
|
|
200
|
+
message = "MundoSMS: all() cannot go through #{path}: it has more (has_more) but no next_cursor, so the list is not " \
|
|
201
|
+
"paginated: raise limit or narrow the filters, and read it with get"
|
|
202
|
+
raise Error.new(message, http: 200, status_code: text(r["status_code"]), data: data, response: r)
|
|
203
|
+
end
|
|
204
|
+
list_key ||= data.keys.find { |k| data[k].is_a?(Array) } # la lista es el primer campo que es una lista
|
|
205
|
+
(list_key && data[list_key].is_a?(Array) ? data[list_key] : []).each { |item| y << item }
|
|
206
|
+
@last_cursor = cursor if truthy(cursor)
|
|
207
|
+
break if !truthy(data["has_more"]) || !truthy(cursor) || cursor == q["cursor"] || truthy(data["ongoing_call"])
|
|
208
|
+
|
|
209
|
+
q["cursor"] = cursor
|
|
210
|
+
end
|
|
211
|
+
end.lazy
|
|
212
|
+
return enum unless block
|
|
213
|
+
|
|
214
|
+
enum.each(&block)
|
|
215
|
+
nil
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# Una petición cualquiera. path: "/calls", "/numbers/34910123456"… (sin /v3: si lo lleva, se quita); cada trozo se
|
|
219
|
+
# codifica solo y un %XX que ya escribas se respeta. Si la ruta trae "?…", esos parámetros se juntan con data (gana
|
|
220
|
+
# data). En GET y DELETE, data (un Hash) va en la query; en POST y PATCH, en el cuerpo JSON. Devuelve la respuesta
|
|
221
|
+
# decodificada (un Hash con claves de texto). idempotency_key: la Idempotency-Key (en un POST, sin ella, un UUID nuevo).
|
|
222
|
+
def request(method, path, data = nil, idempotency_key: nil)
|
|
223
|
+
method = method.to_s.upcase
|
|
224
|
+
idem_key = idempotency_key_for(idempotency_key, method) # antes de nada: con una clave mala no se manda nada
|
|
225
|
+
encoded_path, path_query = split_path(path, @base_path.end_with?("/v3"))
|
|
226
|
+
body = ""
|
|
227
|
+
if %w[GET DELETE].include?(method)
|
|
228
|
+
raise ArgumentError, "MundoSMS: in GET and DELETE the query must be a Hash (nothing was sent)" unless data.nil? || data.is_a?(Hash)
|
|
229
|
+
|
|
230
|
+
(data || {}).each { |k, v| path_query[k.to_s] = v }
|
|
231
|
+
elsif !blank?(data)
|
|
232
|
+
body = json_body(data)
|
|
233
|
+
end
|
|
234
|
+
query = path_query.filter_map { |k, v| (t = query_value(v)).nil? ? nil : "#{rfc3986(k)}=#{rfc3986(t)}" }.join("&")
|
|
235
|
+
rest = encoded_path + (query.empty? ? "" : "?#{query}")
|
|
236
|
+
signed_path = @base_path + rest # lo que se firma es justo lo que se manda
|
|
237
|
+
attempt = 0
|
|
238
|
+
after_network = false # un intento de antes se quedó sin respuesta (o llegó dos veces): puede que se hiciera
|
|
239
|
+
loop do
|
|
240
|
+
attempt += 1
|
|
241
|
+
status, headers, resp, network_error = send_once(method, rest, signed_path, body, idem_key)
|
|
242
|
+
redirect = network_error.nil? && status.between?(300, 399) # de una redirección no se lee nada
|
|
243
|
+
j = nil
|
|
244
|
+
unless network_error || redirect
|
|
245
|
+
begin
|
|
246
|
+
j = JSON.parse(resp)
|
|
247
|
+
rescue JSON::ParserError, EncodingError
|
|
248
|
+
j = nil
|
|
249
|
+
end
|
|
250
|
+
j = nil unless j.is_a?(Hash)
|
|
251
|
+
end
|
|
252
|
+
if retryable?(method, !network_error.nil?, status, j, idem_key) && attempt <= @retries
|
|
253
|
+
after_network ||= !network_error.nil? || duplicated?(status, j)
|
|
254
|
+
sleep(retry_wait(headers["retry-after"], attempt))
|
|
255
|
+
next
|
|
256
|
+
end
|
|
257
|
+
if network_error
|
|
258
|
+
@last_rate_limit = nil
|
|
259
|
+
raise Error.new("No response from the API: #{network_error}")
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
@last_rate_limit = rate_limit(headers)
|
|
263
|
+
rid = headers["x-request-id"]
|
|
264
|
+
if redirect # no se sigue: llevaría el token y la firma a otro servidor
|
|
265
|
+
where = headers["location"].to_s.strip.empty? ? "" : " to #{headers['location'].strip[0, 300]}"
|
|
266
|
+
message = "HTTP #{status}: redirect#{where} not followed (the API does not redirect: check base_url)"
|
|
267
|
+
raise Error.new(message, http: status, request_id: rid)
|
|
268
|
+
end
|
|
269
|
+
replayed = headers["idempotent-replayed"].to_s.strip.downcase == "true"
|
|
270
|
+
j["idempotent_replayed"] = true if replayed && j.is_a?(Hash) # la respuesta guardada de la primera vez
|
|
271
|
+
if status.between?(200, 299)
|
|
272
|
+
unless j.is_a?(Hash) # un fichero, o algo que no es de la API
|
|
273
|
+
type = headers["content-type"].to_s.split(";").first.to_s.strip
|
|
274
|
+
unless resp.empty? || type.downcase.match?(FILE_TYPES)
|
|
275
|
+
message = "HTTP #{status}: the response is not JSON (#{type.empty? ? 'no Content-Type' : type})"
|
|
276
|
+
raise Error.new(message, http: status, request_id: rid)
|
|
277
|
+
end
|
|
278
|
+
file = { "status" => "success", "content_type" => headers["content-type"].to_s, "body" => resp }
|
|
279
|
+
file["idempotent_replayed"] = true if replayed
|
|
280
|
+
return file
|
|
281
|
+
end
|
|
282
|
+
return j unless j["status"] == "error"
|
|
283
|
+
end
|
|
284
|
+
if method == "DELETE" && after_network && status == 404 && j.is_a?(Hash) && !j["message"].to_s.start_with?("Route not found")
|
|
285
|
+
# lo borró el intento que se quedó sin respuesta
|
|
286
|
+
return { "status" => "success", "status_code" => "0", "message" => "Already deleted",
|
|
287
|
+
"data" => { "state" => "deleted", "changed" => false } }
|
|
288
|
+
end
|
|
289
|
+
if j.is_a?(Hash)
|
|
290
|
+
message = j["message"].is_a?(String) ? j["message"] : "Error"
|
|
291
|
+
raise Error.new(message, http: status, status_code: text(j["status_code"]), detail: text(j["detail"]), data: j["data"],
|
|
292
|
+
response: j, request_id: rid)
|
|
293
|
+
end
|
|
294
|
+
raise Error.new("HTTP #{status}", http: status, request_id: rid)
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
private
|
|
299
|
+
|
|
300
|
+
# Un intento: [código HTTP, cabeceras (en minúsculas), cuerpo, nil] o, sin respuesta entera (la red, el plazo), [0, {}, "",
|
|
301
|
+
# el motivo]. Las redirecciones no se siguen: la API no las usa, y la firma no valdría.
|
|
302
|
+
def send_once(method, rest, signed_path, body, idem_key)
|
|
303
|
+
ts = MundoSMS.timestamp # un reintento inmediato, o dos peticiones iguales a la vez, no firman igual
|
|
304
|
+
req = Net::HTTPGenericRequest.new(method, !body.empty?, true, @uri.path.to_s + rest)
|
|
305
|
+
req["Authorization"] = "Bearer #{@token}"
|
|
306
|
+
req["X-Timestamp"] = ts
|
|
307
|
+
req["Accept"] = "application/json"
|
|
308
|
+
req["User-Agent"] = "MundoSMS-Ruby/#{VERSION}"
|
|
309
|
+
req["Idempotency-Key"] = idem_key if idem_key # la misma en todos los intentos de esta llamada
|
|
310
|
+
unless body.empty?
|
|
311
|
+
req["Content-Type"] = "application/json"
|
|
312
|
+
req.body = body
|
|
313
|
+
end
|
|
314
|
+
unless @private_key.empty?
|
|
315
|
+
signed = "#{@token}.#{ts}.#{method} #{signed_path}.".b + body.b
|
|
316
|
+
req["X-Signature"] = [OpenSSL::HMAC.digest("SHA256", @private_key, signed)].pack("m0").tr("+/", "-_").delete("=")
|
|
317
|
+
end
|
|
318
|
+
res = nil
|
|
319
|
+
Timeout.timeout(@timeout, TimeoutReached) do # el plazo de la petición ENTERA: también una respuesta que llega poco a poco
|
|
320
|
+
http = Net::HTTP.new(@uri.host, @uri.port)
|
|
321
|
+
http.use_ssl = @uri.scheme == "https"
|
|
322
|
+
http.open_timeout = http.read_timeout = http.write_timeout = @timeout
|
|
323
|
+
http.max_retries = 0 # que no repita la petición por su cuenta, con la misma firma: si se corta, la repite el SDK
|
|
324
|
+
http.start { |h| res = h.request(req) }
|
|
325
|
+
end
|
|
326
|
+
headers = {}
|
|
327
|
+
res.each_header { |k, v| headers[k.downcase] = v }
|
|
328
|
+
[res.code.to_i, headers, res.body.to_s, nil]
|
|
329
|
+
rescue TimeoutReached, Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout
|
|
330
|
+
[0, {}, "", "timed out after #{format_seconds(@timeout)} s"]
|
|
331
|
+
rescue StandardError => e
|
|
332
|
+
raise if e.is_a?(ArgumentError) || e.is_a?(Error)
|
|
333
|
+
|
|
334
|
+
[0, {}, "", e.message.to_s.empty? ? e.class.name : e.message]
|
|
335
|
+
end
|
|
336
|
+
|
|
337
|
+
# El plazo agotado (lo lanza Timeout dentro de la petición, sin que lo vea nadie de fuera).
|
|
338
|
+
class TimeoutReached < StandardError; end
|
|
339
|
+
|
|
340
|
+
def format_seconds(s)
|
|
341
|
+
s == s.to_i ? s.to_i.to_s : s.to_s
|
|
342
|
+
end
|
|
343
|
+
|
|
344
|
+
# La Idempotency-Key de la llamada: la tuya, si tiene la forma que exige la API; en un POST sin ella, un UUID v4 nuevo.
|
|
345
|
+
def idempotency_key_for(key, method)
|
|
346
|
+
return (method == "POST" ? SecureRandom.uuid : nil) if key.nil?
|
|
347
|
+
unless key.is_a?(String) && key.match?(IDEMPOTENCY_KEY)
|
|
348
|
+
raise ArgumentError, "MundoSMS: idempotency_key must be 1 to 64 characters: A-Z, a-z, 0-9 and _ . : - (nothing was sent)"
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
key
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
# Si se puede repetir: un 429 en cualquier método; un GET, ante un fallo de red o un 5xx; un PATCH o un DELETE, ante un
|
|
355
|
+
# fallo de red; un POST (con su Idempotency-Key), ante un fallo de red o un 409 «Request in progress». Un 5xx de un POST
|
|
356
|
+
# no: la API no guarda los 5xx y repetirlo lo haría otra vez. Un 409 «Duplicated request» (la MISMA petición firmada llegó
|
|
357
|
+
# dos veces: la repitió algo entre medias) es un fallo de red más.
|
|
358
|
+
def retryable?(method, network, status, j, idem_key)
|
|
359
|
+
return true if status == 429
|
|
360
|
+
|
|
361
|
+
message = j.is_a?(Hash) && j["message"].is_a?(String) ? j["message"] : nil
|
|
362
|
+
network ||= duplicated?(status, j)
|
|
363
|
+
return network || status >= 500 if method == "GET"
|
|
364
|
+
return network if %w[PATCH DELETE].include?(method)
|
|
365
|
+
return network || (status == 409 && message == "Request in progress") if idem_key
|
|
366
|
+
|
|
367
|
+
false
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
# 409 «Duplicated request»: la MISMA petición firmada llegó dos veces (la repitió algo entre medias).
|
|
371
|
+
def duplicated?(status, j)
|
|
372
|
+
status == 409 && j.is_a?(Hash) && j["message"].is_a?(String) && j["message"].start_with?("Duplicated request")
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
# El cupo de la respuesta (X-RateLimit-Limit, -Remaining y -Reset, en enteros), o nil si no lo trae.
|
|
376
|
+
def rate_limit(headers)
|
|
377
|
+
out = %w[limit remaining reset].to_h do |k|
|
|
378
|
+
v = headers["x-ratelimit-#{k}"].to_s.strip
|
|
379
|
+
[k, v.match?(/\A-?[0-9]{1,18}\z/) ? Integer(v, 10) : nil]
|
|
380
|
+
end
|
|
381
|
+
out.values.any? ? out : nil
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
# Segundos antes del siguiente intento: lo que pida Retry-After (segundos o fecha HTTP), o 1, 2, 4… Como mucho 60.
|
|
385
|
+
def retry_wait(retry_after, attempt)
|
|
386
|
+
s = nil
|
|
387
|
+
v = retry_after.to_s.strip
|
|
388
|
+
unless v.empty?
|
|
389
|
+
s = begin
|
|
390
|
+
Float(v)
|
|
391
|
+
rescue ArgumentError
|
|
392
|
+
begin
|
|
393
|
+
Time.httpdate(v) - Time.now
|
|
394
|
+
rescue ArgumentError
|
|
395
|
+
nil
|
|
396
|
+
end
|
|
397
|
+
end
|
|
398
|
+
end
|
|
399
|
+
s = 2**(attempt - 1) if s.nil? || s.nan?
|
|
400
|
+
s.clamp(0, MAX_RETRY_WAIT)
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
# El cuerpo JSON de un POST o un PATCH, tal cual se firma y se manda.
|
|
404
|
+
def json_body(data)
|
|
405
|
+
JSON.generate(data)
|
|
406
|
+
rescue JSON::GeneratorError, EncodingError => e
|
|
407
|
+
raise ArgumentError, "MundoSMS: the body cannot be encoded as JSON, nothing was sent (is every text UTF-8?): #{e.message}"
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
def blank?(data)
|
|
411
|
+
data.nil? || data == false || (data.respond_to?(:empty?) && data.empty?)
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
# RFC 3986: todo codificado menos A-Z a-z 0-9 - . _ ~, byte a byte en UTF-8.
|
|
415
|
+
def rfc3986(s)
|
|
416
|
+
s.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |c| format("%%%02X", c.ord) }
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
# Un valor de la query: true/false, una lista separada por comas; nil o una lista vacía (o solo de nil), nada. Una
|
|
420
|
+
# fecha (Time), en ISO 8601 con milisegundos y su zona.
|
|
421
|
+
def query_value(v)
|
|
422
|
+
case v
|
|
423
|
+
when nil then nil
|
|
424
|
+
when true, false then v.to_s
|
|
425
|
+
when Array
|
|
426
|
+
items = v.map { |x| query_value(x) }.compact
|
|
427
|
+
items.empty? ? nil : items.join(",")
|
|
428
|
+
when Time then v.iso8601(3)
|
|
429
|
+
when Hash then raise ArgumentError, "MundoSMS: a Hash cannot go in the query (nothing was sent)"
|
|
430
|
+
else v.to_s
|
|
431
|
+
end
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
# La ruta codificada trozo a trozo (un %XX ya escrito se respeta), sin el /v3 del principio si la base ya lo lleva, y
|
|
435
|
+
# los parámetros que traiga tras «?».
|
|
436
|
+
def split_path(path, strip_v3)
|
|
437
|
+
path, _, query = path.to_s.partition("?")
|
|
438
|
+
path_query = {}
|
|
439
|
+
query.split("&").each do |pair|
|
|
440
|
+
next if pair.empty?
|
|
441
|
+
|
|
442
|
+
k, _, v = pair.partition("=")
|
|
443
|
+
path_query[unescape(k)] = unescape(v)
|
|
444
|
+
end
|
|
445
|
+
path = "/#{path.sub(%r{\A/+}, '')}"
|
|
446
|
+
path = "/#{path[3..].sub(%r{\A/+}, '')}" if strip_v3 && (path == "/v3" || path.start_with?("/v3/"))
|
|
447
|
+
encoded = path.split("/", -1).map do |seg|
|
|
448
|
+
seg.split(/(%[0-9A-Fa-f]{2})/).each_with_index.map { |x, i| i.odd? ? x : rfc3986(x) }.join
|
|
449
|
+
end
|
|
450
|
+
[encoded.join("/"), path_query]
|
|
451
|
+
end
|
|
452
|
+
|
|
453
|
+
# Un trozo de la query de la ruta: cada %XX, su byte; lo demás, también el «+», tal cual (RFC 3986: no es un formulario),
|
|
454
|
+
# para que una fecha con zona escrita en la ruta (from_datetime=…+01:00) llegue tal cual. Un % que no es %XX se deja.
|
|
455
|
+
def unescape(s)
|
|
456
|
+
s.b.gsub(/%[0-9A-Fa-f]{2}/n) { |m| m[1, 2].to_i(16).chr }.force_encoding(Encoding::UTF_8)
|
|
457
|
+
end
|
|
458
|
+
|
|
459
|
+
# Un valor de la respuesta como texto: un String tal cual, un número con sus cifras; una lista o un objeto, en JSON.
|
|
460
|
+
def text(v)
|
|
461
|
+
case v
|
|
462
|
+
when nil, String then v
|
|
463
|
+
when Numeric, true, false then v.to_s
|
|
464
|
+
else JSON.generate(v)
|
|
465
|
+
end
|
|
466
|
+
end
|
|
467
|
+
|
|
468
|
+
# Lo que en la respuesta cuenta como «sí» (true, un número que no es 0, un texto, una lista o un objeto con algo).
|
|
469
|
+
def truthy(v)
|
|
470
|
+
return false if v.nil? || v == false
|
|
471
|
+
return v != 0 if v.is_a?(Numeric)
|
|
472
|
+
return !v.empty? if v.respond_to?(:empty?)
|
|
473
|
+
|
|
474
|
+
true
|
|
475
|
+
end
|
|
476
|
+
end
|
|
477
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: mundosms
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.2.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- MundoSMS
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: Firma cada petición, pone una Idempotency-Key en cada POST, reintenta
|
|
13
|
+
solo lo que es seguro repetir, recorre los listados por su cursor y comprueba la
|
|
14
|
+
firma de los avisos. Un solo fichero, sin dependencias.
|
|
15
|
+
email:
|
|
16
|
+
- contacto@mundosms.es
|
|
17
|
+
executables: []
|
|
18
|
+
extensions: []
|
|
19
|
+
extra_rdoc_files: []
|
|
20
|
+
files:
|
|
21
|
+
- LICENSE
|
|
22
|
+
- README.md
|
|
23
|
+
- lib/mundosms.rb
|
|
24
|
+
homepage: https://www.mundosms.es/api-v3
|
|
25
|
+
licenses:
|
|
26
|
+
- MIT
|
|
27
|
+
metadata:
|
|
28
|
+
documentation_uri: https://www.mundosms.es/api-v3
|
|
29
|
+
source_code_uri: https://github.com/mundosms/mundosms-sdk
|
|
30
|
+
changelog_uri: https://github.com/mundosms/mundosms-sdk/blob/main/CHANGELOG.md
|
|
31
|
+
bug_tracker_uri: https://github.com/mundosms/mundosms-sdk/issues
|
|
32
|
+
rdoc_options: []
|
|
33
|
+
require_paths:
|
|
34
|
+
- lib
|
|
35
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
36
|
+
requirements:
|
|
37
|
+
- - ">="
|
|
38
|
+
- !ruby/object:Gem::Version
|
|
39
|
+
version: '3.1'
|
|
40
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
41
|
+
requirements:
|
|
42
|
+
- - ">="
|
|
43
|
+
- !ruby/object:Gem::Version
|
|
44
|
+
version: '0'
|
|
45
|
+
requirements: []
|
|
46
|
+
rubygems_version: 4.0.20
|
|
47
|
+
specification_version: 4
|
|
48
|
+
summary: 'Cliente de la API REST v3 de MundoSMS: SMS, WhatsApp, centralita, VozPush
|
|
49
|
+
y NumCheck.'
|
|
50
|
+
test_files: []
|