onlinesim 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6e0b71a52a66215988199f175be20382ccfa1f0dbb18632f5720fa159d0fcf4a
4
- data.tar.gz: 9512addf2dcc16873bac27043fc08a8e5e7e31ae690c424c988c6c8b0624332e
3
+ metadata.gz: 9a0be2702e2e1a4ac0fb798e3212e556307eee9692a4376f88cee77a2507d6f7
4
+ data.tar.gz: c7c21cdfafab641627d061531215cc7565a3e673527aba9b13bfa314f3ecba5f
5
5
  SHA512:
6
- metadata.gz: ae411b2fd9db2ee029bf376fa707f0f2605fb7fe1102b424d2a8d7de9db9d71d11ddd24d6d83ed3bcdff0ff1c9f6e3ae78e9545538519b6bf68666757495696d
7
- data.tar.gz: d97360f0ba0940dad8322235ea558a92e3ef639ec8610f72cf155b52a0b3bfd35423f552fc6dfffefc0897bc9dcc6bdaea05269715a291aacac948e7438b9d2e
6
+ metadata.gz: d7595f15f4b2b0571c02c6c4419158f334adc3a4e70e0a50d3aefa639d2fb53bb4eb55935dce87bd877febde652cce74c9b116a2359a69c9ca94e329fdf6e792
7
+ data.tar.gz: 80161ab8d592ddf69f221245f4e14c05752f7ecaa95a3c9bef31a4e620b0a433db5cbb10b794dea3975b657629cc0e68eb352b92f04a8504a3f1df984687d953
data/CHANGELOG.md CHANGED
@@ -4,6 +4,18 @@ All notable changes to this project will be documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [2.1.1] - 2026-11-20
8
+
9
+ Aligned with the regenerated backend API spec.
10
+
11
+ ### Fixed
12
+
13
+ - `user.payment_history` no longer drops `paylist` when the server sends it as a JSON array (ids 0, 1, 2…); it is returned as sent.
14
+ - `numbers.wait_code` retries `ApiError` `TRY_AGAIN_LATER` (HTTP 429 rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR` until its timeout instead of raising at once.
15
+ - Error messages: `"0"` (ban not applied, the operation already has an SMS), `ACCOUNT_CLEANED`, `USER_NOT_ACTIVATED`, `ERROR_UNDEFINED`, `FORWARD_NOT_SUPPORTED` added; `ERROR_NO_KEY`, `NO_NUMBER_FOR_FORWARD`, `ACCOUNT_IDENTIFICATION_REQUIRED`, `API_DISABLED` (no longer sent) removed; `ERROR_WRONG_KEY` reads "Wrong or missing API key". `NoNumberError` is raised for `NO_NUMBER` only.
16
+ - `MockOnlineSim` follows the backend: `setOperationRevise` answers `{"tzid":"N","response":"1"}` and `ERROR_WRONG_TZID` / `ERROR_NO_TZID`; `setOperationOk` tzid `0` → `ERROR_NO_TZID`; a missing key is HTTP 200 `ERROR_WRONG_KEY` (456 only for a wrong key, also on public endpoints); `getNum` with `number` adds `title`, `response_text`, `guard_interval_remaining_seconds`. Rent: `getRentNum` reserves the price (`status` 0) and the first non-`notify` SMS confirms and charges it (a `notify` SMS has the integer `code` `0`), unknown country → `UNDEFINED_COUNTRY`, `sum` a number in getRentNum/extendRentState and a string in getRentState, `guard_interval_remaining_seconds` with `number`; `extendRentState` refusals are all `TRY_AGAIN_LATER`; `closeRentNum` unknown tzid → `ERROR_NO_OPERATIONS`, releases the reservation of an unconfirmed rent. Webhook-log params: `code` `""` without a code, rent `number` in full digits, rent `time_left` in minutes, `time_start` per type. `profile.php` accepts any `scheme://…` URL. `getPaymentHistory` adds `forms`/`buttons`; `getFreeList` clamps `count` to 10..500, sends ISO-8601 `created_at` and `ignore`/`content`.
17
+ - Docs: rent reservation and `sum`, available = balance − max(zbalance, 0), `ban` answer `"0"`, webhook `number`/`time_left`/`time_start`, the `wait_code` retry policy, rent message `code` `0`, nullable profile/payment/free fields, the mock's behaviour.
18
+
7
19
  ## [2.1.0] - 2026-11-19
8
20
 
9
21
  ### Added
data/README.md CHANGED
@@ -16,7 +16,7 @@ require "onlinesim"
16
16
  client = OnlineSim::Client.new(api_key: ENV["ONLINESIM_KEY"])
17
17
 
18
18
  b = client.user.balance
19
- puts "available: #{b['balance'] - b['zbalance']} USD"
19
+ puts "available: #{b['balance'] - [b['zbalance'], 0].max} USD"
20
20
 
21
21
  order = client.numbers.get_with_number("google", 44)
22
22
  puts "enter #{order['number']} in the app"
@@ -66,7 +66,8 @@ module OnlineSim
66
66
  rescue JSON::ParserError
67
67
  raise TransportError.new("HTTP #{status}: response is not JSON", status: status, body: text[0, BODY_EXCERPT])
68
68
  end
69
- # The body is checked before the status: a wrong key is HTTP 456 with {"response":"ERROR_WRONG_KEY"}.
69
+ # The body is checked before the status: a wrong key is HTTP 456 with {"response":"ERROR_WRONG_KEY"},
70
+ # the rate limit HTTP 429 with {"response":"TRY_AGAIN_LATER"}.
70
71
  return unwrap(data) if data.is_a?(Hash) && data.key?("response")
71
72
  raise TransportError.new("HTTP #{status}", status: status, body: text[0, BODY_EXCERPT]) unless (200..299).cover?(status)
72
73
 
@@ -95,7 +96,7 @@ module OnlineSim
95
96
  code = response.to_s
96
97
  # Debug backends echo the code as `message`; prefer the readable fallback then.
97
98
  message = rest["message"].is_a?(String) && rest["message"] != code ? rest["message"] : nil
98
- raise NoNumberError.new(code, message) if %w[NO_NUMBER NO_NUMBER_FOR_FORWARD].include?(code)
99
+ raise NoNumberError.new(code, message) if code == "NO_NUMBER"
99
100
 
100
101
  raise ApiError.new(code, message)
101
102
  end
@@ -15,7 +15,7 @@ module OnlineSim
15
15
  end
16
16
  end
17
17
 
18
- # No number is available right now (NO_NUMBER, NO_NUMBER_FOR_FORWARD). Retry later or pick another country.
18
+ # No number is available right now (NO_NUMBER). Retry later or pick another country.
19
19
  class NoNumberError < ApiError; end
20
20
 
21
21
  # Network failure, request timeout, or a response that is not JSON.
@@ -38,29 +38,30 @@ module OnlineSim
38
38
  # Fallback messages for error codes the server sends without a `message`.
39
39
  ERROR_MESSAGES = {
40
40
  "ACCOUNT_BLOCKED" => "Account is blocked",
41
- "ERROR_WRONG_KEY" => "Wrong API key",
42
- "ERROR_NO_KEY" => "API key is missing",
41
+ "ACCOUNT_CLEANED" => "Account was deleted",
42
+ "USER_NOT_ACTIVATED" => "Account email is not confirmed",
43
+ "ERROR_WRONG_KEY" => "Wrong or missing API key",
43
44
  "ERROR_NO_SERVICE" => "Service is not specified",
44
45
  "API_ACCESS_DISABLED" => "API access is disabled in the profile",
45
46
  "API_ACCESS_IP" => "API access from this IP is not allowed in the profile",
46
47
  "ERROR_NO_TZID" => "tzid is not specified",
47
48
  "ERROR_WRONG_TZID" => "Wrong tzid",
48
49
  "ERROR_NO_OPERATIONS" => "No operations",
50
+ "ERROR_UNDEFINED" => "Unexpected server error, try again",
49
51
  "NO_NUMBER" => "No numbers available for this service right now",
50
- "NO_NUMBER_FOR_FORWARD" => "No numbers available for forwarding",
51
52
  "NO_COUNTRY" => "Country not found",
52
53
  "UNDEFINED_COUNTRY" => "Unknown country",
53
54
  "WARNING_LOW_BALANCE" => "Not enough balance",
54
55
  "EXCEEDED_CONCURRENT_OPERATIONS" => "Too many concurrent operations for this account",
55
56
  "INTERVAL_CONCURRENT_REQUESTS_ERROR" => "Too many concurrent requests, try again in a few seconds",
56
- "TRY_AGAIN_LATER" => "Temporarily unable to perform the request, try again later",
57
- "ACCOUNT_IDENTIFICATION_REQUIRED" => "Account identification is required",
57
+ "TRY_AGAIN_LATER" => "Rate limit exceeded or temporary error, try again later",
58
+ "FORWARD_NOT_SUPPORTED" => "Number forwarding is no longer available",
58
59
  "ERROR_PARAMS" => "Wrong parameters",
59
- "API_DISABLED" => "API is disabled",
60
60
  "NO_COMPLETE_TZID" => "The operation cannot be closed yet",
61
61
  "NO_CLOSE_RENT_US" => "US rent numbers cannot be closed early",
62
62
  "UNDEFINED_DAYS" => "Unknown rent period",
63
63
  "VALIDATION_ERROR" => "Validation failed",
64
+ "0" => "Ban not applied: the operation already has an SMS",
64
65
  "TZ_OVER_OK" => "Operation finished without a new code",
65
66
  "ERROR_NO_ITEMS" => "Operation failed"
66
67
  }.freeze
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "uri"
4
-
5
3
  module OnlineSim
6
4
  class MockOnlineSim
7
5
  # The mock's routes: endpoint path (relative to `/api/`) → handler. A handler gets the state and the request
@@ -25,6 +23,10 @@ module OnlineSim
25
23
  "first_login" => false, "sub" => 0, "disable" => false, "is_project_subscription" => false
26
24
  }.freeze
27
25
 
26
+ # `ignore` of getFreeList: a note about prohibited services and their ids.
27
+ FREE_IGNORE = "<p>Messages from these services are not shown:</p><p>1,2,3</p>"
28
+
29
+ # Country 44 first, like the backend's list.
28
30
  FREE = {
29
31
  44 => {
30
32
  name: "united_kingdom", text: "United Kingdom",
@@ -46,6 +48,9 @@ module OnlineSim
46
48
  value.nil? ? fallback : Integer(value, 10, exception: false) || fallback
47
49
  end
48
50
 
51
+ # `YYYY-MM-DDTHH:MM:SS.000000Z`, the ISO-8601 form getFreeList sends.
52
+ def iso(seconds) = "#{State.stamp(seconds).sub(" ", "T")}.000000Z"
53
+
49
54
  # USD with `digits` decimals, as the backend sends `balance` and rent `sum`.
50
55
  def decimal(mills, digits = 3) = format("%.#{digits}f", State.from_mills(mills))
51
56
 
@@ -119,7 +124,8 @@ module OnlineSim
119
124
  return { "response" => 1, "tzid" => tzid } if req[:query]["number"].nil?
120
125
 
121
126
  { "response" => 1, "tzid" => tzid, "number" => number, "country" => country, "time" => State::OPERATION_TIME,
122
- "service" => service }
127
+ "service" => service, "title" => service, "response_text" => "Waiting for SMS",
128
+ "guard_interval_remaining_seconds" => state.guard_interval }
123
129
  end
124
130
 
125
131
  def get_state(state, req)
@@ -138,17 +144,20 @@ module OnlineSim
138
144
 
139
145
  def set_operation_revise(state, req)
140
146
  tzid = int(req, "tzid", 0)
141
- op = state.operations[tzid]
142
- # Always succeeds, even for unknown tzids, like the backend.
143
- if op && op.status != "TZ_OVER_OK"
147
+ return error("ERROR_NO_TZID") if tzid.zero?
148
+
149
+ op = state.operations[tzid] or return error("ERROR_WRONG_TZID")
150
+ if op.status != "TZ_OVER_OK"
144
151
  op.cursor = op.messages.size
145
152
  op.status = "TZ_NUM_WAIT"
146
153
  end
147
- { "response" => 1, "tzid" => tzid }
154
+ { "tzid" => tzid.to_s, "response" => "1" }
148
155
  end
149
156
 
150
157
  def set_operation_ok(state, req)
151
158
  tzid = int(req, "tzid", 0)
159
+ return error("ERROR_NO_TZID") if tzid.zero?
160
+
152
161
  op = state.operations[tzid]
153
162
  return error("ERROR_WRONG_TZID") if op.nil? || op.status == "TZ_OVER_OK"
154
163
 
@@ -185,38 +194,49 @@ module OnlineSim
185
194
 
186
195
  # ----- rent -----
187
196
 
188
- def rent_item(state, rent, req) # rubocop:disable Metrics/AbcSize
197
+ # A rent as the backend sends it. `sum` is a number in getRentNum/extendRentState and a 2-decimal string in
198
+ # getRentState (`string_sum`). An unconfirmed rent (`status` 0) waits 20 minutes for its first SMS.
199
+ def rent_item(state, rent, req, string_sum: false) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
189
200
  tariff = state.rent_tariffs[rent.country]
190
201
  extendable = rent.extension && tariff && tariff[:extend] == 1
202
+ confirmed = rent.status == 1
191
203
  start = rent.tzid
204
+ minutes = confirmed ? rent.days * 24 * 60 : State::RENT_FIRST_SMS_MINUTES
192
205
  item = {
193
- "status" => 1, "extension" => rent.extension ? 1 : 0,
206
+ "status" => rent.status, "extension" => rent.extension ? 1 : 0,
194
207
  "messages" => rent.messages.reverse.map do |m|
195
- { "id" => m.id, "service" => m.service, "text" => m.text, "code" => m.code || "", "created_at" => m.created_at }
208
+ # A notice about a prohibited sender carries the Integer 0, other SMS a String ("" without a code).
209
+ code = m.service == State::NOTIFY ? 0 : m.code || ""
210
+ { "id" => m.id, "service" => m.service, "text" => m.text, "code" => code, "created_at" => m.created_at }
196
211
  end,
197
- "webhook_url" => state.webhook_url, "sum" => decimal(State.to_mills(rent.sum), 2), "country" => rent.country,
198
- "start_time" => State.stamp(start), "stop_time" => State.stamp(start + (rent.days * 86_400)),
199
- "checked_time" => State.stamp(start), "number" => rent.number, "days_autoextend" => 0, "rent" => 1,
200
- "tzid" => rent.tzid, "time" => rent.days * 24 * 60, "days" => rent.days, "hours" => rent.days * 24,
201
- "extend" => extendable ? tariff[:days].dup : [], "checked" => true, "reload" => nil,
212
+ "webhook_url" => state.webhook_url, "sum" => string_sum ? decimal(State.to_mills(rent.sum), 2) : rent.sum,
213
+ "country" => rent.country, "start_time" => State.stamp(start), "stop_time" => State.stamp(start + (minutes * 60)),
214
+ "checked_time" => State.stamp(start), "number" => rent.number, "days_autoextend" => rent.initial_days,
215
+ "rent" => rent.days, "tzid" => rent.tzid, "time" => minutes, "days" => confirmed ? rent.days : 0,
216
+ "hours" => confirmed ? rent.days * 24 : 0, "extend" => extendable ? tariff[:days].dup : [],
217
+ "checked" => confirmed, "reload" => rent.country == 7 ? 0 : nil,
202
218
  "day_extend" => extendable ? tariff[:days].fetch(1, 0) : 0, "m_ext" => false, "freeze" => false
203
219
  }
204
- item["time_seconds"] = rent.days * 86_400 unless req[:query]["number"].nil?
220
+ unless req[:query]["number"].nil?
221
+ item["time_seconds"] = minutes * 60
222
+ item["guard_interval_remaining_seconds"] = !confirmed && rent.messages.empty? ? state.guard_interval : 0
223
+ end
205
224
  item
206
225
  end
207
226
 
208
227
  def get_rent_num(state, req)
209
228
  country = int(req, "country", 7)
210
- tariff = state.rent_tariffs[country] or return error("NO_COUNTRY")
229
+ tariff = state.rent_tariffs[country] or return error("UNDEFINED_COUNTRY")
211
230
  days = int(req, "days", 1)
212
231
  price = tariff[:days][days] or return error("UNDEFINED_DAYS")
213
232
  return error("WARNING_LOW_BALANCE") if state.available < State.to_mills(price)
214
233
 
215
234
  tzid = state.next_id
216
- state.balance -= State.to_mills(price)
235
+ # Reserved, not charged: the first SMS that is not `notify` confirms the rent and charges it.
236
+ state.frozen += State.to_mills(price)
217
237
  # `extension` defaults to 1 on the server; `0` makes the rent non-extendable for good.
218
- rent = Rent.new(tzid: tzid, country: country, number: State.short_number(tzid), days: days, sum: price,
219
- extension: req[:query]["extension"] != "0", messages: [])
238
+ rent = Rent.new(tzid: tzid, country: country, number: State.short_number(tzid), days: days, initial_days: days,
239
+ status: 0, sum: price, extension: req[:query]["extension"] != "0", messages: [])
220
240
  state.rents[tzid] = rent
221
241
  { "response" => 1, "item" => rent_item(state, rent, req) }
222
242
  end
@@ -228,16 +248,17 @@ module OnlineSim
228
248
  [state.rents[int(req, "tzid", -1)]].compact
229
249
  end
230
250
  rents.each { |rent| state.poll(rent.tzid) }
231
- { "response" => 1, "list" => rents.map { |r| rent_item(state, r, req) } }
251
+ { "response" => 1, "list" => rents.map { |r| rent_item(state, r, req, string_sum: true) } }
232
252
  end
233
253
 
234
254
  def extend_rent_state(state, req)
235
- rent = state.rents[int(req, "tzid", 0)] or return error("ERROR_WRONG_TZID")
236
- tariff = state.rent_tariffs[rent.country]
237
- return error("TRY_AGAIN_LATER") unless rent.extension && tariff && tariff[:extend] == 1
255
+ # Every refusal is TRY_AGAIN_LATER, like the backend: unknown tzid, unconfirmed rent, not extendable, unknown days.
256
+ rent = state.rents[int(req, "tzid", 0)]
257
+ tariff = rent && state.rent_tariffs[rent.country]
258
+ return error("TRY_AGAIN_LATER") unless tariff && rent.status == 1 && rent.extension && tariff[:extend] == 1
238
259
 
239
260
  days = int(req, "days", 1)
240
- price = tariff[:days][days] or return error("UNDEFINED_DAYS")
261
+ price = tariff[:days][days] or return error("TRY_AGAIN_LATER")
241
262
  return error("WARNING_LOW_BALANCE") if state.available < State.to_mills(price)
242
263
 
243
264
  state.balance -= State.to_mills(price)
@@ -248,8 +269,16 @@ module OnlineSim
248
269
 
249
270
  def close_rent_num(state, req)
250
271
  tzid = int(req, "tzid", 0)
251
- return error("ERROR_WRONG_TZID") unless state.rents.delete(tzid)
272
+ rent = state.rents[tzid] or return error("ERROR_NO_OPERATIONS")
273
+ if rent.status.zero?
274
+ # `guard_interval` stands in for the backend's first 120 s, during which a rent without any SMS stays open.
275
+ return error("NO_COMPLETE_TZID") if rent.messages.empty? && state.guard_interval.positive?
252
276
 
277
+ # Unconfirmed (no SMS or only `notify`): the reservation is released.
278
+ state.frozen -= State.to_mills(rent.sum)
279
+ end
280
+ # A confirmed rent closes without a refund.
281
+ state.rents.delete(tzid)
253
282
  state.scheduled.delete(tzid)
254
283
  { "response" => "1" }
255
284
  end
@@ -281,12 +310,8 @@ module OnlineSim
281
310
  { "response" => "1", "profile" => PROFILE.merge("apikey" => state.api_key, "webhook_url" => state.webhook_url) }
282
311
  end
283
312
 
284
- def http_url?(value)
285
- uri = URI.parse(value)
286
- %w[http https].include?(uri.scheme) && !uri.host.to_s.empty?
287
- rescue URI::InvalidURIError
288
- false
289
- end
313
+ # The backend accepts any `scheme://…` URL.
314
+ def url?(value) = value.match?(%r{\A[a-z][a-z0-9+.-]*://\S+\z}i)
290
315
 
291
316
  def profile(state, req)
292
317
  body = req[:body]
@@ -294,7 +319,7 @@ module OnlineSim
294
319
 
295
320
  fields = body["profile"]
296
321
  url = fields["webhook_url"]
297
- unless url.nil? || (url.is_a?(String) && http_url?(url))
322
+ unless url.nil? || (url.is_a?(String) && url?(url))
298
323
  return { "response" => { "webhook_url" => ["The webhook url must be a valid URL."] } }
299
324
  end
300
325
 
@@ -308,7 +333,8 @@ module OnlineSim
308
333
 
309
334
  def get_payment_history(_state, req)
310
335
  { "response" => "1", "orders" => paginate([], int(req, "page", 1), 10, "getPaymentHistory.php"),
311
- "paylist" => [], "domains" => [], "currency" => { "USD" => 1 } }
336
+ "paylist" => [], "domains" => ["onlinesim.io"], "forms" => { "1" => "Card" }, "currency" => { "USD" => 1 },
337
+ "buttons" => { "USD" => [5, 10, 20] } }
312
338
  end
313
339
 
314
340
  # ----- free -----
@@ -323,15 +349,18 @@ module OnlineSim
323
349
  end
324
350
  number = data[:numbers].key?(req[:query]["number"]) ? req[:query]["number"] : data[:numbers].keys.first
325
351
  messages = data[:numbers][number].each_with_index.map do |(sender, text), i|
326
- { "id" => i + 1, "text" => text, "in_number" => sender, "my_number" => number, "created_at" => State.stamp(i),
352
+ { "id" => i + 1, "text" => text, "in_number" => sender, "my_number" => number, "created_at" => iso(i),
327
353
  "data_humans" => "1 day ago", "code" => State.extract_code(text) || "-" }
328
354
  end
329
- page = paginate(messages, int(req, "page", 1), int(req, "count", 10), "getFreeList")
355
+ count = int(req, "count", 10).clamp(10, 500)
356
+ page = paginate(messages, [1, int(req, "page", 1)].max, count, "getFreeList")
330
357
  {
331
358
  "response" => 1,
332
359
  "countries" => FREE.map { |c, d| { "country" => c, "country_text" => d[:text], "country_original" => d[:name] } },
333
360
  "numbers" => numbers,
334
- "messages" => page.merge("number" => number, "country" => country)
361
+ "messages" => page.merge("number" => number, "country" => country),
362
+ "ignore" => FREE_IGNORE,
363
+ "content" => nil
335
364
  }
336
365
  end
337
366
 
@@ -3,8 +3,8 @@
3
3
  module OnlineSim
4
4
  class MockOnlineSim
5
5
  # One SMS received by an operation or a rent. `code` is extracted from `text` (nil when there is none);
6
- # `id` and `created_at` are set for rent messages only.
7
- Sms = Struct.new(:service, :text, :code, :id, :created_at, keyword_init: true)
6
+ # `at` is the seconds after the mock epoch when it arrived; `id` and `created_at` are set for rent messages only.
7
+ Sms = Struct.new(:service, :text, :code, :at, :id, :created_at, keyword_init: true)
8
8
 
9
9
  # A number operation. `number` has the `+`; `sum` (USD) is frozen while open, spent on close after an SMS,
10
10
  # refunded on close without one. `cursor` is the index of the SMS shown in `msg`; `next` moves it past the last.
@@ -12,9 +12,12 @@ module OnlineSim
12
12
  Operation = Struct.new(:tzid, :service, :country, :number, :sum, :status, :messages, :cursor, # rubocop:disable Lint/StructNewOverride
13
13
  keyword_init: true)
14
14
 
15
- # A rent. `number` has no country code, as the backend sends it for rents; `sum` is the total paid, USD.
16
- # `messages` are oldest first. Closed rents are removed.
17
- Rent = Struct.new(:tzid, :country, :number, :days, :sum, :extension, :messages, keyword_init: true) # rubocop:disable Lint/StructNewOverride
15
+ # A rent. `number` has no country code, as the backend sends it for rents. `days` is the total period incl.
16
+ # extensions, `initial_days` the period of getRentNum. `status` 0: reserved, waiting for the first SMS; 1: confirmed
17
+ # by an SMS that is not `notify`, price charged. `sum` is the total cost incl. extensions, USD, frozen while
18
+ # `status` is 0. `messages` are oldest first. Closed rents are removed.
19
+ Rent = Struct.new(:tzid, :country, :number, :days, :initial_days, :status, :sum, :extension, :messages, # rubocop:disable Lint/StructNewOverride
20
+ keyword_init: true)
18
21
 
19
22
  # State of the mock backend: the single owner of everything the fake API remembers — balance, operations,
20
23
  # rents, the profile's webhook URL and its delivery log, scheduled SMS, the failure queue and the request
@@ -22,7 +25,7 @@ module OnlineSim
22
25
  #
23
26
  # Deterministic: ids and numbers come from a counter, timestamps from a fixed epoch plus that counter.
24
27
  # Money is kept in integer thousandths of a USD ("mills") so sums never drift.
25
- class State
28
+ class State # rubocop:disable Metrics/ClassLength -- the single owner of the mock's state; splitting it would spread that state
26
29
  DEFAULT_PRICES = {
27
30
  7 => { "vkcom" => 0.5, "telegram" => 1.2, "google" => 0.3 },
28
31
  44 => { "google" => 0.2, "vkcom" => 0.36 }
@@ -32,6 +35,10 @@ module OnlineSim
32
35
  USER_ID = 1
33
36
  # Seconds an operation stays open, as reported in `time`. The mock has no clock, so it never runs down.
34
37
  OPERATION_TIME = 1200
38
+ # Minutes an unconfirmed rent waits for its first SMS (`stop_time` = start + this).
39
+ RENT_FIRST_SMS_MINUTES = 20
40
+ # Sender of a rent SMS from a prohibited sender: it gets the Integer `code` 0 and does not confirm the rent.
41
+ NOTIFY = "notify"
35
42
  # 2026-01-01 00:00:00 UTC.
36
43
  EPOCH = 1_767_225_600
37
44
 
@@ -54,7 +61,7 @@ module OnlineSim
54
61
 
55
62
  attr_reader :api_key, :guard_interval, :prices, :rent_tariffs,
56
63
  :operations, :rents, :webhook_logs, :requests, :failures, :scheduled
57
- # Total balance incl. the frozen part, and the part frozen by open operations, mills.
64
+ # Total balance incl. the frozen part, and the part frozen by open operations and unconfirmed rents, mills.
58
65
  attr_accessor :balance, :frozen, :webhook_url
59
66
 
60
67
  def initialize(api_key: "mock-key", balance: 100, prices: nil, rent_tariffs: nil, guard_interval: 0)
@@ -95,23 +102,18 @@ module OnlineSim
95
102
 
96
103
  # An SMS arrives at operation or rent `tzid` now. Returns false when there is no open one.
97
104
  def deliver(tzid, text, service = nil)
98
- sms = Sms.new(text: text, code: State.extract_code(text))
99
105
  op = @operations[tzid]
100
106
  if op && op.status != "TZ_OVER_OK"
101
- sms.service = service || op.service
107
+ sms = Sms.new(service: service || op.service, text: text, code: State.extract_code(text), at: @seq)
102
108
  op.messages << sms
103
109
  op.status = "TZ_NUM_ANSWER"
104
- record_webhook("receiving_sms", tzid, op.country, op.number, sms)
110
+ # Activation: `+<digits>`, seconds left, the order time.
111
+ record_webhook("receiving_sms", tzid, op.country, op.number, sms, OPERATION_TIME, State.stamp(op.tzid))
105
112
  return true
106
113
  end
107
- rent = @rents[tzid]
108
- return false unless rent
114
+ rent = @rents[tzid] or return false
109
115
 
110
- sms.service = service || "other"
111
- sms.id = next_id
112
- sms.created_at = State.stamp(sms.id)
113
- rent.messages << sms
114
- record_webhook("rent_sms", tzid, rent.country, rent.number, sms)
116
+ deliver_to_rent(rent, text, service || "other")
115
117
  true
116
118
  end
117
119
 
@@ -131,17 +133,33 @@ module OnlineSim
131
133
 
132
134
  private
133
135
 
136
+ # The first SMS that is not `notify` confirms the rent: the reservation is charged.
137
+ def deliver_to_rent(rent, text, service)
138
+ id = next_id
139
+ sms = Sms.new(service: service, text: text, code: State.extract_code(text), at: id, id: id, created_at: State.stamp(id))
140
+ rent.messages << sms
141
+ if rent.status.zero? && service != NOTIFY
142
+ cost = State.to_mills(rent.sum)
143
+ @frozen -= cost
144
+ @balance -= cost
145
+ rent.status = 1
146
+ end
147
+ # Rent: full number in digits without `+`, minutes left, the SMS time.
148
+ minutes_left = rent.status == 1 ? rent.days * 24 * 60 : RENT_FIRST_SMS_MINUTES
149
+ record_webhook("rent_sms", rent.tzid, rent.country, "#{rent.country}#{rent.number}", sms, minutes_left, sms.created_at)
150
+ end
151
+
134
152
  # No HTTP call: the mock only records what the backend would have sent.
135
- def record_webhook(type, tzid, country, number, sms)
153
+ def record_webhook(type, tzid, country, number, sms, time_left, time_start) # rubocop:disable Metrics/ParameterLists
136
154
  return unless @webhook_url
137
155
 
138
- time = State.stamp(@seq)
156
+ time = State.stamp(sms.at)
139
157
  @webhook_logs << {
140
158
  "id" => @webhook_logs.size + 1, "user_id" => USER_ID, "webhook_url" => @webhook_url, "type" => type,
141
159
  "params" => {
142
160
  "webhook_type" => type, "operation_id" => tzid, "user_id" => USER_ID, "country_code" => country,
143
- "number" => number, "sender" => sms.service, "message" => sms.text, "code" => sms.code,
144
- "time_start" => time, "time_left" => OPERATION_TIME
161
+ "number" => number, "sender" => sms.service, "message" => sms.text, "code" => sms.code || "",
162
+ "time_start" => time_start, "time_left" => time_left
145
163
  },
146
164
  "status" => "success", "error" => nil, "created_at" => time, "updated_at" => time
147
165
  }
@@ -25,7 +25,8 @@ module OnlineSim
25
25
  # balance - starting balance, USD.
26
26
  # prices - number prices, country code => { service slug => USD }; replaces the defaults.
27
27
  # rent_tariffs - rent tariffs, country code => { days: { days => USD }, extend: 1 | 0 }; replaces the defaults.
28
- # guard_interval - seconds; > 0: an operation without SMS cannot be closed (NO_COMPLETE_TZID).
28
+ # guard_interval - seconds; > 0: an operation without SMS, or an unconfirmed rent without any SMS, cannot be
29
+ # closed (NO_COMPLETE_TZID).
29
30
  def initialize(api_key: "mock-key", balance: 100, prices: nil, rent_tariffs: nil, guard_interval: 0)
30
31
  @state = State.new(api_key: api_key, balance: balance, prices: prices, rent_tariffs: rent_tariffs,
31
32
  guard_interval: guard_interval)
@@ -70,7 +71,7 @@ module OnlineSim
70
71
  @state.balance = State.to_mills(usd)
71
72
  end
72
73
 
73
- # Total balance, USD, including the part frozen by open operations (as `user.balance` reports it).
74
+ # Total balance, USD, including the part frozen by open operations and unconfirmed rents (as `user.balance` reports it).
74
75
  def balance = State.from_mills(@state.balance)
75
76
 
76
77
  # Number operations, oldest first (deep copies).
@@ -117,9 +118,11 @@ module OnlineSim
117
118
 
118
119
  handler = Handlers::ROUTES[req[:path]]
119
120
  return html(404, "Not Found") unless handler
120
- if !Handlers::PUBLIC_PATHS.include?(req[:path]) && authorization(headers) != "Bearer #{@state.api_key}"
121
- return json({ "response" => "ERROR_WRONG_KEY" }, 456)
122
- end
121
+
122
+ # A wrong key is HTTP 456 (public endpoints check a sent key too); no key at all is HTTP 200.
123
+ auth = authorization(headers)
124
+ return json({ "response" => "ERROR_WRONG_KEY" }, 456) if !auth.nil? && auth != "Bearer #{@state.api_key}"
125
+ return json({ "response" => "ERROR_WRONG_KEY" }) if auth.nil? && !Handlers::PUBLIC_PATHS.include?(req[:path])
123
126
 
124
127
  json(Handlers.public_send(handler, @state, req))
125
128
  end
@@ -10,7 +10,8 @@ module OnlineSim
10
10
  @request = request
11
11
  end
12
12
 
13
- # Rent a number for `days` days. `extension: false` makes the rent non-extendable for good.
13
+ # Rent a number for `days` days. The price is reserved (`status` 0); the first SMS that is not `notify`
14
+ # confirms the rent and charges it. `extension: false` makes the rent non-extendable for good.
14
15
  def get(country = 7, days = 1, extension: true)
15
16
  res = @request.call("rent/getRentNum.php", query: { country: country, days: days, extension: extension, **DETAIL })
16
17
  item(res["item"])
@@ -29,7 +30,7 @@ module OnlineSim
29
30
  item(raw)
30
31
  end
31
32
 
32
- # Extend a rent by `days` days (only rents created with `extension: true`).
33
+ # Extend a rent by `days` days and charge at once (only confirmed rents created with `extension: true`).
33
34
  # Overrides Object#extend on this section object on purpose: the name is the API's.
34
35
  def extend(tzid, days = 1)
35
36
  item(@request.call("rent/extendRentState.php", query: { tzid: tzid, days: days, **DETAIL })["item"])
@@ -57,7 +58,8 @@ module OnlineSim
57
58
 
58
59
  private
59
60
 
60
- # `sum` is a decimal string, `extend` may be `[]`.
61
+ # `sum` is a number (getRentNum, extendRentState) or a decimal string (getRentState), `extend` may be `[]`.
62
+ # Message `code` stays as sent: a String, or the Integer 0 for a `notify` SMS.
61
63
  def item(raw)
62
64
  raw.merge(
63
65
  "sum" => (Normalize.num(raw["sum"]) || 0).to_f,
@@ -8,7 +8,7 @@ module OnlineSim
8
8
  end
9
9
 
10
10
  # Balance in USD: {"balance" => Float, "zbalance" => Float, "income" => Float (when sent)}.
11
- # `balance` includes the frozen `zbalance`: available = balance - zbalance.
11
+ # `balance` includes the frozen `zbalance` (may be negative): available = balance - max(zbalance, 0).
12
12
  def balance
13
13
  res = @request.call("getBalance.php", query: { income: 1 })
14
14
  out = { "balance" => (Normalize.num(res["balance"]) || 0).to_f, "zbalance" => (Normalize.num(res["zbalance"]) || 0).to_f }
@@ -24,8 +24,8 @@ module OnlineSim
24
24
 
25
25
  # Top-up orders (paginated, newest first) and the available payment methods.
26
26
  def payment_history(page = 1)
27
- res = @request.call("getPaymentHistory.php", query: { page: page })
28
- res.merge("paylist" => Normalize.map(res["paylist"]))
27
+ # `paylist` stays as sent: a non-empty JSON array is real data (group ids 0..n), not PHP's empty map.
28
+ @request.call("getPaymentHistory.php", query: { page: page })
29
29
  end
30
30
 
31
31
  # Set the URL that receives SMS webhooks. Raises ApiError VALIDATION_ERROR for an invalid URL.
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module OnlineSim
4
- VERSION = "2.1.0"
4
+ VERSION = "2.1.1"
5
5
  end
@@ -5,10 +5,15 @@ module OnlineSim
5
5
  MONOTONIC = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
6
6
  private_constant :MONOTONIC
7
7
 
8
+ # ApiError codes that mean "try again": rate limit (HTTP 429), a transient server error, too many requests.
9
+ RETRYABLE_CODES = %w[TRY_AGAIN_LATER ERROR_UNDEFINED INTERVAL_CONCURRENT_REQUESTS_ERROR].freeze
10
+ private_constant :RETRYABLE_CODES
11
+
8
12
  # Poll `numbers.state_one(tzid)` every `interval` seconds until a code different from `since` arrives, then
9
13
  # `close` (or `next` with `keep_open`) and return it. A finished operation (TZ_OVER_OK, ERROR_NO_ITEMS) without a
10
14
  # new code raises ApiError with that state as the code; running out of `timeout` seconds raises TimeoutError.
11
- # TransportError is retried until the timeout; any ApiError is raised at once.
15
+ # TransportError and the transient ApiError codes TRY_AGAIN_LATER, ERROR_UNDEFINED and
16
+ # INTERVAL_CONCURRENT_REQUESTS_ERROR are retried until the timeout; any other ApiError is raised at once.
12
17
  # `sleep` (seconds -> any) and `now` (-> seconds) are injectable for tests.
13
18
  def self.wait_code(numbers, tzid, interval: 5, timeout: 600, keep_open: false, full_message: false, since: nil,
14
19
  sleep: Kernel.method(:sleep), now: MONOTONIC)
@@ -17,6 +22,10 @@ module OnlineSim
17
22
  op = begin
18
23
  numbers.state_one(tzid, message_to_code: !full_message)
19
24
  rescue TransportError
25
+ nil
26
+ rescue ApiError => e
27
+ raise unless RETRYABLE_CODES.include?(e.code)
28
+
20
29
  nil
21
30
  end
22
31
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: onlinesim
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.0
4
+ version: 2.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - s00d
@@ -39,7 +39,7 @@ homepage: https://github.com/s00d/onlinesim-ruby-api
39
39
  licenses:
40
40
  - Apache-2.0
41
41
  metadata:
42
- source_code_uri: https://github.com/s00d/onlinesim-ruby-api/tree/2.1.0
42
+ source_code_uri: https://github.com/s00d/onlinesim-ruby-api/tree/2.1.1
43
43
  documentation_uri: https://s00d.github.io/onlinesim-ruby-api/
44
44
  changelog_uri: https://github.com/s00d/onlinesim-ruby-api/blob/master/CHANGELOG.md
45
45
  bug_tracker_uri: https://github.com/s00d/onlinesim-ruby-api/issues