onlinesim 2.0.0 → 2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4af26c6c66c785ca9c4519a122daad48d105d05d249c600e3f7a2345f3c11006
4
- data.tar.gz: c22124c94febefbe5328eeda630c37bccc6da62eecfdd62deab38034aed282c8
3
+ metadata.gz: 6e0b71a52a66215988199f175be20382ccfa1f0dbb18632f5720fa159d0fcf4a
4
+ data.tar.gz: 9512addf2dcc16873bac27043fc08a8e5e7e31ae690c424c988c6c8b0624332e
5
5
  SHA512:
6
- metadata.gz: 2528b67b4dc6fe472f4a3e17d543bb9365a9a4532b3bb9a4118712a6d422e7cc09b74d25fa9247fa3ed0a7f1bae47ab7fbb3d2f1bae90b9a7601c5f055f17151
7
- data.tar.gz: 9decd39dd76c1812f4718b78b440c96214fcbd0f0af0dd36d4545f222c9766af3f29fc3fb60d8f6212571857476e9e6231c966bf40824d26cbe74c95b1139c9c
6
+ metadata.gz: ae411b2fd9db2ee029bf376fa707f0f2605fb7fe1102b424d2a8d7de9db9d71d11ddd24d6d83ed3bcdff0ff1c9f6e3ae78e9545538519b6bf68666757495696d
7
+ data.tar.gz: d97360f0ba0940dad8322235ea558a92e3ef639ec8610f72cf155b52a0b3bfd35423f552fc6dfffefc0897bc9dcc6bdaea05269715a291aacac948e7438b9d2e
data/CHANGELOG.md CHANGED
@@ -4,7 +4,19 @@ 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.0.0] - unreleased
7
+ ## [2.1.0] - 2026-11-19
8
+
9
+ ### Added
10
+
11
+ - `OnlineSim::MockOnlineSim`: a built-in, in-process fake of the OnlineSim API for testing integrations offline — no network, key, money or clock. `mock.client` returns a normal `OnlineSim::Client` wired to it (`mock.transport` is the mock itself, a transport with `call(method, url, headers, body, timeout)`). It answers every endpoint the SDK calls like the real backend (HTTP 456 for a wrong key, string/int `response`, decimal-string money, `[]` for empty maps) and keeps balance, operations and rents. Test helpers: `add_sms`, `add_sms_after` (lets `wait_code` run with `interval: 0`), `fail_next`, `fail_next_transport`, `set_balance`, `balance`, `operations`, `rents`, `requests`, `reset`. Autoloaded by `require "onlinesim"` (nothing is loaded until first use); `require "onlinesim/mock"` works too. See the [testing guide](https://s00d.github.io/onlinesim-ruby-api/testing).
12
+ - Packaging checks in CI: `gem build --strict` (warnings fail the build) and a smoke test that builds the gem, installs it with `--install-dir` into an empty directory and runs the README "Testing" example on Ruby 3.0 and the latest Ruby.
13
+ - `.github/workflows/release.yml`: a version tag runs CI, checks the tag against `OnlineSim::VERSION`, publishes to RubyGems with trusted publishing (OIDC, no API key) and creates the GitHub release from this file.
14
+
15
+ ### Changed
16
+
17
+ - Gemspec `source_code_uri` points to the release tag's tree, so it no longer repeats `homepage` (RubyGems warned about the duplicate).
18
+
19
+ ## [2.0.0] - 2026-11-19
8
20
 
9
21
  A rewrite. The public API changed; see the [docs](https://s00d.github.io/onlinesim-ruby-api/).
10
22
 
data/README.md CHANGED
@@ -23,4 +23,21 @@ puts "enter #{order['number']} in the app"
23
23
  puts "code: #{client.numbers.wait_code(order['tzid'])}"
24
24
  ```
25
25
 
26
+ ## Testing
27
+
28
+ `OnlineSim::MockOnlineSim` is a built-in offline fake of the API: test your integration without network, key or money.
29
+ More in the [testing guide](https://s00d.github.io/onlinesim-ruby-api/testing).
30
+
31
+ ```ruby
32
+ require "onlinesim"
33
+
34
+ mock = OnlineSim::MockOnlineSim.new(balance: 10)
35
+ client = mock.client
36
+
37
+ tzid = client.numbers.get("google", 44)
38
+ mock.add_sms_after(tzid, "Your code: 123-456", 2) # arrives on the third poll
39
+ raise "wrong code" unless client.numbers.wait_code(tzid, interval: 0) == "123456"
40
+ raise "wrong balance" unless mock.balance == 9.8
41
+ ```
42
+
26
43
  Documentation: **https://s00d.github.io/onlinesim-ruby-api/** · Changes: [CHANGELOG.md](CHANGELOG.md) · License: Apache-2.0
@@ -0,0 +1,359 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module OnlineSim
6
+ class MockOnlineSim
7
+ # The mock's routes: endpoint path (relative to `/api/`) → handler. A handler gets the state and the request
8
+ # and returns the JSON value the real backend would send (HTTP 200). Shapes follow the OpenAPI spec and the
9
+ # live captures: `response` as int or string per endpoint, decimal-string money, `[]` for empty maps.
10
+ # Auth, queued failures, 456 and 404 are the transport's job (MockOnlineSim#call), not the handlers'.
11
+ module Handlers # rubocop:disable Metrics/ModuleLength -- one small function per endpoint; size follows the API
12
+ module_function
13
+
14
+ # Endpoints that answer without a key.
15
+ PUBLIC_PATHS = ["getNumbersStats.php", "rent/tariffsRent.php", "getFreeList"].freeze
16
+
17
+ COUNTRY_NAMES = { 7 => %w[russia Russia], 44 => ["united_kingdom", "United Kingdom"] }.freeze
18
+
19
+ PROFILE = {
20
+ "id" => State::USER_ID, "hash_id" => "mock", "name" => "mock@example.com", "username" => "mock@example.com",
21
+ "email" => "mock@example.com", "email_verified_at" => State.stamp, "active" => "true", "api_access" => true,
22
+ "is_api" => true, "number" => nil, "country" => nil, "locale" => "en", "currency" => "USD",
23
+ "number_region" => nil, "number_country" => nil, "number_reject" => [], "ugroup" => 1, "verify" => 0,
24
+ "block" => 0, "resetCount" => nil, "created_at" => State.stamp, "notification_at" => nil,
25
+ "first_login" => false, "sub" => 0, "disable" => false, "is_project_subscription" => false
26
+ }.freeze
27
+
28
+ FREE = {
29
+ 44 => {
30
+ name: "united_kingdom", text: "United Kingdom",
31
+ numbers: { "7459608320" => [["Amazon", "Amazon: Use 195895 to reset your password."],
32
+ ["Microsoft", "Microsoft access code: 2991"]] }
33
+ },
34
+ 7 => { name: "russia", text: "Russia", numbers: { "9001234567" => [["Telegram", "Telegram code: 51423"]] } }
35
+ }.freeze
36
+
37
+ def error(code) = { "response" => code }
38
+
39
+ def flag?(req, key)
40
+ value = req[:query][key]
41
+ !value.nil? && value != "0"
42
+ end
43
+
44
+ def int(req, key, fallback)
45
+ value = req[:query][key]
46
+ value.nil? ? fallback : Integer(value, 10, exception: false) || fallback
47
+ end
48
+
49
+ # USD with `digits` decimals, as the backend sends `balance` and rent `sum`.
50
+ def decimal(mills, digits = 3) = format("%.#{digits}f", State.from_mills(mills))
51
+
52
+ def country_name(code) = COUNTRY_NAMES.fetch(code) { ["country_#{code}", "Country #{code}"] }
53
+
54
+ # Laravel paginator over `items`.
55
+ def paginate(items, page, per_page, path)
56
+ total = items.size
57
+ last_page = [1, (total.to_f / per_page).ceil].max
58
+ data = items[((page - 1) * per_page), per_page] || []
59
+ url = ->(p) { "https://onlinesim.host/api/#{path}?page=#{p}" }
60
+ {
61
+ "current_page" => page, "data" => data, "first_page_url" => url.call(1),
62
+ "from" => data.empty? ? nil : ((page - 1) * per_page) + 1, "last_page" => last_page,
63
+ "last_page_url" => url.call(last_page), "links" => [],
64
+ "next_page_url" => page < last_page ? url.call(page + 1) : nil,
65
+ "path" => "https://onlinesim.host/api/#{path}", "per_page" => per_page,
66
+ "prev_page_url" => page > 1 ? url.call(page - 1) : nil,
67
+ "to" => data.empty? ? nil : ((page - 1) * per_page) + data.size, "total" => total
68
+ }
69
+ end
70
+
71
+ # ----- numbers -----
72
+
73
+ def msg_of(sms, to_code) = to_code ? sms.code || sms.text : sms.text
74
+
75
+ def operation_view(state, operation, req)
76
+ to_code = flag?(req, "message_to_code")
77
+ open = operation.status != "TZ_OVER_OK"
78
+ view = {
79
+ "country" => operation.country, "sum" => operation.sum, "service" => operation.service, "number" => operation.number,
80
+ "subscription_package_id" => nil, "webhook_url" => state.webhook_url, "response" => operation.status,
81
+ "tzid" => operation.tzid, "time" => open ? State::OPERATION_TIME : 0, "form" => "index"
82
+ }
83
+ if flag?(req, "msg_list")
84
+ unless operation.messages.empty?
85
+ view["msg"] = operation.messages.map do |s|
86
+ { "service" => s.service, "msg" => msg_of(s, to_code) }
87
+ end
88
+ end
89
+ elsif (current = operation.messages[operation.cursor])
90
+ view["msg"] = msg_of(current, to_code)
91
+ end
92
+ unless req[:query]["number"].nil?
93
+ view["guard_interval_remaining_seconds"] = open && operation.messages.empty? ? state.guard_interval : 0
94
+ end
95
+ view
96
+ end
97
+
98
+ def get_price(state, req)
99
+ prices = state.prices[int(req, "country", 7)] or return error("UNDEFINED_COUNTRY")
100
+ { "response" => "1", "price" => prices[req[:query]["service"].to_s] }
101
+ end
102
+
103
+ def get_num(state, req)
104
+ country = int(req, "country", 7)
105
+ service = req[:query]["service"].to_s
106
+ prices = state.prices[country] or return error("UNDEFINED_COUNTRY")
107
+ price = prices[service] or return error("ERROR_NO_SERVICE")
108
+ cost = State.to_mills(price)
109
+ return error("WARNING_LOW_BALANCE") if state.available < cost
110
+
111
+ number = "+#{country}#{State.short_number(state.peek_id)}"
112
+ reject = req[:query]["reject"].to_s.split(",").reject(&:empty?)
113
+ return error("NO_NUMBER") if reject.any? { |prefix| number[1..].start_with?(prefix) }
114
+
115
+ tzid = state.next_id
116
+ state.frozen += cost
117
+ state.operations[tzid] = Operation.new(tzid: tzid, service: service, country: country, number: number, sum: price,
118
+ status: "TZ_NUM_WAIT", messages: [], cursor: 0)
119
+ return { "response" => 1, "tzid" => tzid } if req[:query]["number"].nil?
120
+
121
+ { "response" => 1, "tzid" => tzid, "number" => number, "country" => country, "time" => State::OPERATION_TIME,
122
+ "service" => service }
123
+ end
124
+
125
+ def get_state(state, req)
126
+ ops = if req[:query]["tzid"].nil?
127
+ state.operations.values
128
+ else
129
+ [state.operations[int(req, "tzid", -1)]].compact
130
+ end
131
+ ops.each { |op| state.poll(op.tzid) }
132
+ return error("ERROR_NO_OPERATIONS") if ops.empty?
133
+
134
+ ops = ops.sort_by(&:tzid)
135
+ ops.reverse! if req[:query]["orderby"] == "desc"
136
+ ops.map { |operation| operation_view(state, operation, req) }
137
+ end
138
+
139
+ def set_operation_revise(state, req)
140
+ 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"
144
+ op.cursor = op.messages.size
145
+ op.status = "TZ_NUM_WAIT"
146
+ end
147
+ { "response" => 1, "tzid" => tzid }
148
+ end
149
+
150
+ def set_operation_ok(state, req)
151
+ tzid = int(req, "tzid", 0)
152
+ op = state.operations[tzid]
153
+ return error("ERROR_WRONG_TZID") if op.nil? || op.status == "TZ_OVER_OK"
154
+
155
+ received = !op.messages.empty?
156
+ return { "response" => "0" } if flag?(req, "ban") && received
157
+ return error("NO_COMPLETE_TZID") if !received && state.guard_interval.positive?
158
+
159
+ cost = State.to_mills(op.sum)
160
+ state.frozen -= cost
161
+ state.balance -= cost if received
162
+ op.status = "TZ_OVER_OK"
163
+ { "response" => 1, "tzid" => tzid }
164
+ end
165
+
166
+ def country_stat(state, code)
167
+ name, locale = country_name(code)
168
+ services = {}
169
+ (state.prices[code] || {}).each_with_index do |(slug, price), i|
170
+ services["service_#{slug}"] = { "count" => 100, "popular" => false, "code" => code, "price" => price,
171
+ "id" => i + 1, "service" => slug, "slug" => slug }
172
+ end
173
+ { "name" => name, "position" => code, "code" => code, "other" => false, "new" => false, "enabled" => true,
174
+ "services" => services.empty? ? [] : services, "locale_name" => locale }
175
+ end
176
+
177
+ def get_numbers_stats(state, req)
178
+ if req[:query]["country"] == "all"
179
+ all = state.prices.keys.to_h { |code| [code, country_stat(state, code)] }
180
+ return all.empty? ? [] : all
181
+ end
182
+ code = int(req, "country", 7)
183
+ state.prices.key?(code) ? country_stat(state, code) : error("NO_COUNTRY")
184
+ end
185
+
186
+ # ----- rent -----
187
+
188
+ def rent_item(state, rent, req) # rubocop:disable Metrics/AbcSize
189
+ tariff = state.rent_tariffs[rent.country]
190
+ extendable = rent.extension && tariff && tariff[:extend] == 1
191
+ start = rent.tzid
192
+ item = {
193
+ "status" => 1, "extension" => rent.extension ? 1 : 0,
194
+ "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 }
196
+ 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,
202
+ "day_extend" => extendable ? tariff[:days].fetch(1, 0) : 0, "m_ext" => false, "freeze" => false
203
+ }
204
+ item["time_seconds"] = rent.days * 86_400 unless req[:query]["number"].nil?
205
+ item
206
+ end
207
+
208
+ def get_rent_num(state, req)
209
+ country = int(req, "country", 7)
210
+ tariff = state.rent_tariffs[country] or return error("NO_COUNTRY")
211
+ days = int(req, "days", 1)
212
+ price = tariff[:days][days] or return error("UNDEFINED_DAYS")
213
+ return error("WARNING_LOW_BALANCE") if state.available < State.to_mills(price)
214
+
215
+ tzid = state.next_id
216
+ state.balance -= State.to_mills(price)
217
+ # `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: [])
220
+ state.rents[tzid] = rent
221
+ { "response" => 1, "item" => rent_item(state, rent, req) }
222
+ end
223
+
224
+ def get_rent_state(state, req)
225
+ rents = if req[:query]["tzid"].nil?
226
+ state.rents.values
227
+ else
228
+ [state.rents[int(req, "tzid", -1)]].compact
229
+ end
230
+ rents.each { |rent| state.poll(rent.tzid) }
231
+ { "response" => 1, "list" => rents.map { |r| rent_item(state, r, req) } }
232
+ end
233
+
234
+ 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
238
+
239
+ days = int(req, "days", 1)
240
+ price = tariff[:days][days] or return error("UNDEFINED_DAYS")
241
+ return error("WARNING_LOW_BALANCE") if state.available < State.to_mills(price)
242
+
243
+ state.balance -= State.to_mills(price)
244
+ rent.days += days
245
+ rent.sum = State.from_mills(State.to_mills(rent.sum) + State.to_mills(price))
246
+ { "response" => 1, "item" => rent_item(state, rent, req) }
247
+ end
248
+
249
+ def close_rent_num(state, req)
250
+ tzid = int(req, "tzid", 0)
251
+ return error("ERROR_WRONG_TZID") unless state.rents.delete(tzid)
252
+
253
+ state.scheduled.delete(tzid)
254
+ { "response" => "1" }
255
+ end
256
+
257
+ def rent_tariff(state, code)
258
+ tariff = state.rent_tariffs[code] or return []
259
+ count = tariff[:days].keys.to_h { |d| [d, 100] }
260
+ { "code" => code, "enabled" => true, "name" => country_name(code).first, "new" => false, "position" => code,
261
+ "count" => count, "days" => tariff[:days].dup, "extend" => tariff[:extend], "confirm" => false,
262
+ "ext_counts" => count }
263
+ end
264
+
265
+ def tariffs_rent(state, req)
266
+ return rent_tariff(state, int(req, "country", 0)) unless req[:query]["country"].nil?
267
+
268
+ all = state.rent_tariffs.keys.to_h { |code| [code, rent_tariff(state, code)] }
269
+ all.empty? ? [] : all
270
+ end
271
+
272
+ # ----- user -----
273
+
274
+ def get_balance(state, req)
275
+ res = { "response" => "1", "balance" => decimal(state.balance), "zbalance" => State.from_mills(state.frozen) }
276
+ res.merge!("income" => 0, "income_usd" => "0.000") unless req[:query]["income"].nil?
277
+ res
278
+ end
279
+
280
+ def get_profile(state, _req)
281
+ { "response" => "1", "profile" => PROFILE.merge("apikey" => state.api_key, "webhook_url" => state.webhook_url) }
282
+ end
283
+
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
290
+
291
+ def profile(state, req)
292
+ body = req[:body]
293
+ return error("ERROR_PARAMS") unless req[:method] == "POST" && body.is_a?(Hash) && body["profile"].is_a?(Hash)
294
+
295
+ fields = body["profile"]
296
+ url = fields["webhook_url"]
297
+ unless url.nil? || (url.is_a?(String) && http_url?(url))
298
+ return { "response" => { "webhook_url" => ["The webhook url must be a valid URL."] } }
299
+ end
300
+
301
+ state.webhook_url = url if fields.key?("webhook_url")
302
+ { "response" => "1", "user" => { "id" => State::USER_ID, "webhook_url" => state.webhook_url } }
303
+ end
304
+
305
+ def webhook_logs(state, req)
306
+ { "response" => "1", "data" => paginate(state.webhook_logs.reverse, int(req, "page", 1), 10, "webhook-logs") }
307
+ end
308
+
309
+ def get_payment_history(_state, req)
310
+ { "response" => "1", "orders" => paginate([], int(req, "page", 1), 10, "getPaymentHistory.php"),
311
+ "paylist" => [], "domains" => [], "currency" => { "USD" => 1 } }
312
+ end
313
+
314
+ # ----- free -----
315
+
316
+ def get_free_list(_state, req) # rubocop:disable Metrics/AbcSize
317
+ wanted = int(req, "country", 44)
318
+ country = FREE.key?(wanted) ? wanted : FREE.keys.first
319
+ data = FREE[country]
320
+ numbers = data[:numbers].keys.to_h do |n|
321
+ [n, { "country" => country, "country_original" => data[:name], "data_humans" => "1 day ago",
322
+ "full_number" => "#{country}#{n}", "is_archive" => false }]
323
+ end
324
+ number = data[:numbers].key?(req[:query]["number"]) ? req[:query]["number"] : data[:numbers].keys.first
325
+ 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),
327
+ "data_humans" => "1 day ago", "code" => State.extract_code(text) || "-" }
328
+ end
329
+ page = paginate(messages, int(req, "page", 1), int(req, "count", 10), "getFreeList")
330
+ {
331
+ "response" => 1,
332
+ "countries" => FREE.map { |c, d| { "country" => c, "country_text" => d[:text], "country_original" => d[:name] } },
333
+ "numbers" => numbers,
334
+ "messages" => page.merge("number" => number, "country" => country)
335
+ }
336
+ end
337
+
338
+ ROUTES = {
339
+ "getPrice.php" => :get_price,
340
+ "getNum.php" => :get_num,
341
+ "getState.php" => :get_state,
342
+ "setOperationRevise.php" => :set_operation_revise,
343
+ "setOperationOk.php" => :set_operation_ok,
344
+ "getNumbersStats.php" => :get_numbers_stats,
345
+ "rent/getRentNum.php" => :get_rent_num,
346
+ "rent/getRentState.php" => :get_rent_state,
347
+ "rent/extendRentState.php" => :extend_rent_state,
348
+ "rent/closeRentNum.php" => :close_rent_num,
349
+ "rent/tariffsRent.php" => :tariffs_rent,
350
+ "getBalance.php" => :get_balance,
351
+ "getProfile.php" => :get_profile,
352
+ "profile.php" => :profile,
353
+ "webhook-logs" => :webhook_logs,
354
+ "getPaymentHistory.php" => :get_payment_history,
355
+ "getFreeList" => :get_free_list
356
+ }.freeze
357
+ end
358
+ end
359
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ class MockOnlineSim
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)
8
+
9
+ # A number operation. `number` has the `+`; `sum` (USD) is frozen while open, spent on close after an SMS,
10
+ # refunded on close without one. `cursor` is the index of the SMS shown in `msg`; `next` moves it past the last.
11
+ # `sum` is the API's field name; Enumerable#sum is not used on these records.
12
+ Operation = Struct.new(:tzid, :service, :country, :number, :sum, :status, :messages, :cursor, # rubocop:disable Lint/StructNewOverride
13
+ keyword_init: true)
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
18
+
19
+ # State of the mock backend: the single owner of everything the fake API remembers — balance, operations,
20
+ # rents, the profile's webhook URL and its delivery log, scheduled SMS, the failure queue and the request
21
+ # log. Handlers read and change it only through this object.
22
+ #
23
+ # Deterministic: ids and numbers come from a counter, timestamps from a fixed epoch plus that counter.
24
+ # Money is kept in integer thousandths of a USD ("mills") so sums never drift.
25
+ class State
26
+ DEFAULT_PRICES = {
27
+ 7 => { "vkcom" => 0.5, "telegram" => 1.2, "google" => 0.3 },
28
+ 44 => { "google" => 0.2, "vkcom" => 0.36 }
29
+ }.freeze
30
+ DEFAULT_RENT_TARIFFS = { 7 => { days: { 1 => 1.0, 3 => 2.5, 7 => 5.0 }, extend: 1 } }.freeze
31
+
32
+ USER_ID = 1
33
+ # Seconds an operation stays open, as reported in `time`. The mock has no clock, so it never runs down.
34
+ OPERATION_TIME = 1200
35
+ # 2026-01-01 00:00:00 UTC.
36
+ EPOCH = 1_767_225_600
37
+
38
+ # `YYYY-MM-DD HH:MM:SS` at `seconds` after the fixed mock epoch.
39
+ def self.stamp(seconds = 0)
40
+ Time.at(EPOCH + seconds).utc.strftime("%Y-%m-%d %H:%M:%S")
41
+ end
42
+
43
+ # The code rule shared by every SDK mock: dashes/spaces between digits are removed, then the first run of
44
+ # 4–8 digits (not part of a longer run) is the code; nil when there is none.
45
+ def self.extract_code(text)
46
+ text.gsub(/(\d)[\s-]+(?=\d)/, '\1')[/(?<!\d)\d{4,8}(?!\d)/]
47
+ end
48
+
49
+ def self.to_mills(usd) = (usd * 1000).round
50
+ def self.from_mills(mills) = mills / 1000.0
51
+
52
+ # Short (country-less) number for an id: deterministic, 9 digits.
53
+ def self.short_number(id) = (900_000_000 + id).to_s
54
+
55
+ attr_reader :api_key, :guard_interval, :prices, :rent_tariffs,
56
+ :operations, :rents, :webhook_logs, :requests, :failures, :scheduled
57
+ # Total balance incl. the frozen part, and the part frozen by open operations, mills.
58
+ attr_accessor :balance, :frozen, :webhook_url
59
+
60
+ def initialize(api_key: "mock-key", balance: 100, prices: nil, rent_tariffs: nil, guard_interval: 0)
61
+ @api_key = api_key
62
+ @guard_interval = guard_interval
63
+ @prices = normalize_prices(prices || DEFAULT_PRICES)
64
+ @rent_tariffs = normalize_tariffs(rent_tariffs || DEFAULT_RENT_TARIFFS)
65
+ @start_balance = State.to_mills(balance)
66
+ reset
67
+ end
68
+
69
+ def reset
70
+ @balance = @start_balance
71
+ @frozen = 0
72
+ @operations = {}
73
+ @rents = {}
74
+ @webhook_url = nil
75
+ @webhook_logs = []
76
+ @requests = []
77
+ @failures = []
78
+ @scheduled = {}
79
+ @seq = 0
80
+ end
81
+
82
+ # Available balance (total minus frozen), mills.
83
+ def available = @balance - @frozen
84
+
85
+ # The id the next operation/rent will get.
86
+ def peek_id = @seq + 1
87
+
88
+ def next_id = @seq += 1
89
+
90
+ # Remove and return the first queued failure that applies to `path`.
91
+ def take_failure(path)
92
+ index = @failures.index { |f| f[:endpoint].nil? || f[:endpoint] == path }
93
+ index && @failures.delete_at(index)
94
+ end
95
+
96
+ # An SMS arrives at operation or rent `tzid` now. Returns false when there is no open one.
97
+ def deliver(tzid, text, service = nil)
98
+ sms = Sms.new(text: text, code: State.extract_code(text))
99
+ op = @operations[tzid]
100
+ if op && op.status != "TZ_OVER_OK"
101
+ sms.service = service || op.service
102
+ op.messages << sms
103
+ op.status = "TZ_NUM_ANSWER"
104
+ record_webhook("receiving_sms", tzid, op.country, op.number, sms)
105
+ return true
106
+ end
107
+ rent = @rents[tzid]
108
+ return false unless rent
109
+
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)
115
+ true
116
+ end
117
+
118
+ def schedule(tzid, text, polls, service = nil)
119
+ (@scheduled[tzid] ||= []) << { text: text, service: service, polls: polls }
120
+ end
121
+
122
+ # One state poll of `tzid`: delivers the scheduled SMS whose polls ran out, counts down the rest.
123
+ def poll(tzid)
124
+ list = @scheduled[tzid] or return
125
+ due, rest = list.partition { |s| s[:polls] <= 0 }
126
+ rest.each { |s| s[:polls] -= 1 }
127
+ rest.empty? ? @scheduled.delete(tzid) : @scheduled[tzid] = rest
128
+ # Dropped silently when the operation was closed meanwhile: a real SMS would not arrive either.
129
+ due.each { |s| deliver(tzid, s[:text], s[:service]) }
130
+ end
131
+
132
+ private
133
+
134
+ # No HTTP call: the mock only records what the backend would have sent.
135
+ def record_webhook(type, tzid, country, number, sms)
136
+ return unless @webhook_url
137
+
138
+ time = State.stamp(@seq)
139
+ @webhook_logs << {
140
+ "id" => @webhook_logs.size + 1, "user_id" => USER_ID, "webhook_url" => @webhook_url, "type" => type,
141
+ "params" => {
142
+ "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
145
+ },
146
+ "status" => "success", "error" => nil, "created_at" => time, "updated_at" => time
147
+ }
148
+ end
149
+
150
+ # Country codes as Integers, service slugs as Strings, whatever the caller passed.
151
+ def normalize_prices(prices)
152
+ prices.to_h { |code, services| [Integer(code), services.to_h { |slug, usd| [slug.to_s, usd] }] }
153
+ end
154
+
155
+ def normalize_tariffs(tariffs)
156
+ tariffs.to_h do |code, tariff|
157
+ days = tariff.fetch(:days) { tariff.fetch("days") }
158
+ [Integer(code), { days: days.to_h { |d, usd| [Integer(d), usd] }, extend: tariff.fetch(:extend) { tariff["extend"] } }]
159
+ end
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+ require_relative "../onlinesim"
6
+ require_relative "mock/state"
7
+ require_relative "mock/handlers"
8
+
9
+ module OnlineSim
10
+ # In-process fake OnlineSim API for tests: no network, no key, no money, no clock.
11
+ # It is a transport (`call(method, url, headers, body, timeout)`, see NetHttpTransport) that answers like the
12
+ # real backend; `mock.client` returns a normal OnlineSim::Client wired to it. Test helpers add SMS, queue
13
+ # failures and expose the state.
14
+ #
15
+ # mock = OnlineSim::MockOnlineSim.new(balance: 10)
16
+ # client = mock.client
17
+ # tzid = client.numbers.get("google", 44)
18
+ # mock.add_sms_after(tzid, "Your code: 123-456", 2)
19
+ # client.numbers.wait_code(tzid, interval: 0) # => "123456"
20
+ class MockOnlineSim
21
+ # Base URL of clients made by `client`. Never contacted: the mock answers in-process.
22
+ BASE_URL = "https://mock.onlinesim.invalid/api/"
23
+
24
+ # api_key - key the mock accepts as "Authorization: Bearer <api_key>".
25
+ # balance - starting balance, USD.
26
+ # prices - number prices, country code => { service slug => USD }; replaces the defaults.
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).
29
+ def initialize(api_key: "mock-key", balance: 100, prices: nil, rent_tariffs: nil, guard_interval: 0)
30
+ @state = State.new(api_key: api_key, balance: balance, prices: prices, rent_tariffs: rent_tariffs,
31
+ guard_interval: guard_interval)
32
+ end
33
+
34
+ # The mock itself is the transport: pass it as `transport:` when you build the client yourself. Any base URL works.
35
+ def transport = self
36
+
37
+ # A normal client wired to the mock. `api_key` defaults to the mock's key; override it to test a wrong key.
38
+ # Takes the other Client options (`lang:`, `dev_id:`, ...) except `transport:`.
39
+ def client(**options)
40
+ Client.new(api_key: @state.api_key, base_url: BASE_URL, **options, transport: self)
41
+ end
42
+
43
+ # An SMS arrives now at number operation or rent `tzid`. Raises ArgumentError when there is no open one.
44
+ def add_sms(tzid, text, service: nil)
45
+ raise ArgumentError, "MockOnlineSim: no open operation or rent #{tzid}" unless @state.deliver(tzid, text, service)
46
+ end
47
+
48
+ # The SMS arrives after `polls` state requests for `tzid` (getState / rent getRentState, listing it alone or
49
+ # with others): with `polls = 2` the third poll sees it. Lets `wait_code` run with `interval: 0`.
50
+ def add_sms_after(tzid, text, polls, service: nil)
51
+ unless @state.operations.key?(tzid) || @state.rents.key?(tzid)
52
+ raise ArgumentError, "MockOnlineSim: no operation or rent #{tzid}"
53
+ end
54
+
55
+ @state.schedule(tzid, text, polls, service)
56
+ end
57
+
58
+ # The next request (to `endpoint` only, e.g. "getNum.php", when given) answers {"response": code}.
59
+ def fail_next(code, endpoint: nil)
60
+ @state.failures << { code: code, endpoint: endpoint }
61
+ end
62
+
63
+ # The next request (to `endpoint` only, when given) fails at transport level: a non-JSON body with HTTP `status`.
64
+ def fail_next_transport(status: 502, endpoint: nil)
65
+ @state.failures << { status: status, endpoint: endpoint }
66
+ end
67
+
68
+ # Set the total balance, USD.
69
+ def set_balance(usd) # rubocop:disable Naming/AccessorMethodName -- control API name shared by every SDK
70
+ @state.balance = State.to_mills(usd)
71
+ end
72
+
73
+ # Total balance, USD, including the part frozen by open operations (as `user.balance` reports it).
74
+ def balance = State.from_mills(@state.balance)
75
+
76
+ # Number operations, oldest first (deep copies).
77
+ def operations = copy(@state.operations.values)
78
+
79
+ # Open rents, oldest first (deep copies).
80
+ def rents = copy(@state.rents.values)
81
+
82
+ # Every request received, in order: { method:, path:, query:, body: }, `path` relative to `/api/`,
83
+ # `query` with String keys and values, `body` the parsed JSON of a POST (nil for GET). A copy.
84
+ def requests = copy(@state.requests)
85
+
86
+ # Back to the constructor's state: balance, no operations, rents, logs, schedules or failures.
87
+ def reset
88
+ @state.reset
89
+ end
90
+
91
+ # The transport interface of OnlineSim::Client: returns [status, body].
92
+ def call(method, url, headers, body, _timeout)
93
+ uri = URI(url)
94
+ path = uri.path
95
+ at = path.index("/api/")
96
+ req = {
97
+ method: method.to_s.upcase,
98
+ path: at ? path[(at + 5)..] : path.delete_prefix("/"),
99
+ query: URI.decode_www_form(uri.query.to_s).to_h,
100
+ body: body.is_a?(String) ? JSON.parse(body) : nil
101
+ }
102
+ @state.requests << req
103
+ respond(req, headers)
104
+ end
105
+
106
+ def inspect
107
+ "#<#{self.class.name} balance=#{balance} operations=#{@state.operations.size} rents=#{@state.rents.size}>"
108
+ end
109
+
110
+ private
111
+
112
+ def respond(req, headers)
113
+ failure = @state.take_failure(req[:path])
114
+ if failure
115
+ return failure.key?(:code) ? json({ "response" => failure[:code] }) : html(failure[:status], "Mock transport failure")
116
+ end
117
+
118
+ handler = Handlers::ROUTES[req[:path]]
119
+ 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
123
+
124
+ json(Handlers.public_send(handler, @state, req))
125
+ end
126
+
127
+ def authorization(headers)
128
+ headers.find { |name, _| name.to_s.casecmp?("authorization") }&.last
129
+ end
130
+
131
+ def json(value, status = 200) = [status, JSON.generate(value)]
132
+
133
+ def html(status, text) = [status, "<html><body>#{status} #{text}</body></html>"]
134
+
135
+ def copy(value) = Marshal.load(Marshal.dump(value))
136
+ end
137
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module OnlineSim
4
- VERSION = "2.0.0"
4
+ VERSION = "2.1.0"
5
5
  end
data/lib/onlinesim.rb CHANGED
@@ -11,3 +11,9 @@ require_relative "onlinesim/free"
11
11
  require_relative "onlinesim/wait"
12
12
  require_relative "onlinesim/webhook"
13
13
  require_relative "onlinesim/client"
14
+
15
+ # Ruby client for the OnlineSim API. Entry point: OnlineSim::Client.
16
+ module OnlineSim
17
+ # Offline fake of the API for tests (lib/onlinesim/mock.rb). Loaded on first use, so it costs nothing otherwise.
18
+ autoload :MockOnlineSim, File.expand_path("onlinesim/mock", __dir__)
19
+ end
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.0.0
4
+ version: 2.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - s00d
@@ -24,6 +24,9 @@ files:
24
24
  - lib/onlinesim/client.rb
25
25
  - lib/onlinesim/errors.rb
26
26
  - lib/onlinesim/free.rb
27
+ - lib/onlinesim/mock.rb
28
+ - lib/onlinesim/mock/handlers.rb
29
+ - lib/onlinesim/mock/state.rb
27
30
  - lib/onlinesim/normalize.rb
28
31
  - lib/onlinesim/numbers.rb
29
32
  - lib/onlinesim/rent.rb
@@ -36,7 +39,7 @@ homepage: https://github.com/s00d/onlinesim-ruby-api
36
39
  licenses:
37
40
  - Apache-2.0
38
41
  metadata:
39
- source_code_uri: https://github.com/s00d/onlinesim-ruby-api
42
+ source_code_uri: https://github.com/s00d/onlinesim-ruby-api/tree/2.1.0
40
43
  documentation_uri: https://s00d.github.io/onlinesim-ruby-api/
41
44
  changelog_uri: https://github.com/s00d/onlinesim-ruby-api/blob/master/CHANGELOG.md
42
45
  bug_tracker_uri: https://github.com/s00d/onlinesim-ruby-api/issues
@@ -55,7 +58,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
55
58
  - !ruby/object:Gem::Version
56
59
  version: '0'
57
60
  requirements: []
58
- rubygems_version: 4.0.24
61
+ rubygems_version: 4.0.20
59
62
  specification_version: 4
60
63
  summary: 'Ruby client for the OnlineSim API: SMS numbers, rent, account and free numbers.'
61
64
  test_files: []