onlinesim 1.0.11 → 2.0.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: 37701937f0a81313f8e3dbdfc2985b32024b8deb402da85c4e87b214beccfa03
4
- data.tar.gz: 4975f861b1334a050c6bfa3fea245f7f5a15b066f95756c3c8bd11dc26332159
3
+ metadata.gz: 4af26c6c66c785ca9c4519a122daad48d105d05d249c600e3f7a2345f3c11006
4
+ data.tar.gz: c22124c94febefbe5328eeda630c37bccc6da62eecfdd62deab38034aed282c8
5
5
  SHA512:
6
- metadata.gz: 777d1d56926782d0e859457adbc62bca8b2addff38a205289203dfd29917d4287318a504c41e6fd8bd4cc2ac8f8807aad69eb512a9c6d44cbd59483ef56dbc98
7
- data.tar.gz: 33fad1c9a5a0752ef1a3fbe49d60e70b9af0482a90cb5646ca9cbc130da8ae6df245fa519e2655c47fcba6d81ae565e284d24f82998964a10a94962af730b11e
6
+ metadata.gz: 2528b67b4dc6fe472f4a3e17d543bb9365a9a4532b3bb9a4118712a6d422e7cc09b74d25fa9247fa3ed0a7f1bae47ab7fbb3d2f1bae90b9a7601c5f055f17151
7
+ data.tar.gz: 9decd39dd76c1812f4718b78b440c96214fcbd0f0af0dd36d4545f222c9766af3f29fc3fb60d8f6212571857476e9e6231c966bf40824d26cbe74c95b1139c9c
data/CHANGELOG.md CHANGED
@@ -4,6 +4,54 @@ 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
8
+
9
+ A rewrite. The public API changed; see the [docs](https://s00d.github.io/onlinesim-ruby-api/).
10
+
11
+ ### Removed
12
+
13
+ - Runtime dependencies `faraday`, `oj`, `thor`; the `onlinesim` CLI (`cli.rb`).
14
+ - The global `Faraday::Connection` monkeypatch that disabled TLS verification for every Faraday client in the process, and `Faraday.ignore_env_proxy`.
15
+ - The proxy API (`driver.proxy`) and the forward API (`driver.forward`, `getForward`).
16
+ - `numbers.service` (getService), `numbers.servicenumber` (getServiceNumber), `forward.repeat` (getNumRepeat): no backend route.
17
+ - `free.countries`, `free.numbers`, `free.messages`: the backend returns empty data for them; use `free.list`.
18
+ - `OnlineSim::Driver`, `Onlinesim::VERSION` (now `OnlineSim::VERSION`), `ServerError`, `BaseError`.
19
+ - `tester.rb`, `.travis.yml`, `bin/`, the committed `Gemfile.lock` and the `bundler ~> 2.2.27` dev pin.
20
+
21
+ ### Changed
22
+
23
+ - One client: `OnlineSim::Client.new(api_key:, base_url:, lang:, dev_id:, timeout:, transport:)`; sections are readers (`client.numbers`, `client.rent`, `client.user`, `client.free`).
24
+ - The API key is sent as `Authorization: Bearer <key>`, never in the query string.
25
+ - Errors: `OnlineSim::Error` → `ApiError` (`code`, `message`), `NoNumberError` (subclass of `ApiError`), `TransportError` (`status`, `body`), `TimeoutError`.
26
+ - Method names are snake_case: `get_with_number`, `state_one`, `tariffs_one`, `payment_history`, `wait_code`.
27
+ - `numbers.get(service, country = 7, reject: [...])`; `state(message_to_code:, order_by:, msg_list:)` / `state_one(tzid, ...)` take booleans; `order_by` is lowercase.
28
+ - `numbers.wait_code(tzid, interval: 5, timeout: 600, keep_open: false, full_message: false, since: nil)`, seconds, injectable `sleep:` / `now:`.
29
+ - `rent.get(country = 7, days = 1, extension: true)`: `extension` defaults to `true` (the server default; `false` makes the rent non-extendable for good).
30
+ - Results keep the server's string keys; money parsed to `Float`: `user.balance["balance"]`, rent `sum`.
31
+ - Ruby >= 3.0; gemspec license matches LICENSE (Apache-2.0); `Gemfile.lock` is not committed (library).
32
+
33
+ ### Fixed
34
+
35
+ - TLS certificates are verified (v1 disabled verification globally); the environment proxy is honoured.
36
+ - The host was hardcoded; `base_url` is configurable. No more double slashes (`/api//rent/...`).
37
+ - `dev_id` was always sent (empty); now only when set. Booleans are sent as `1`/`0`; unset parameters are omitted.
38
+ - `reject: {}` default and the stray `&&` in its encoding; `reject` is now a comma list.
39
+ - Error mapping was dead code (the check was a method defined inside the request but never called), so error codes came back as data. They now raise `ApiError`; an HTTP 456 wrong-key answer is an `ApiError`, non-JSON answers raise `TransportError`.
40
+ - `wait_code` closed the operation on the first poll, before any SMS (`nil != ""`), and gave up after 10 polls; it now returns only a real code, then closes.
41
+ - `rent.extend` sent no `days`; it now takes `days` (default 1).
42
+ - `state` sent `orderby=ASC`; the server accepts only lowercase. `state` returns `[]` instead of raising when there are no operations.
43
+ - Empty maps sent by PHP as `[]` (rent `extend`, `paylist`, free `numbers`, country `services`) are returned as `{}`.
44
+ - Rent requests always send `pagination=0`, so `messages` is a flat list.
45
+
46
+ ### Added
47
+
48
+ - `user.set_webhook_url(url)`, `user.clear_webhook_url`, `user.webhook_logs(page)`, `user.payment_history(page)`.
49
+ - `free.list(country:, number:, page:, count:)`.
50
+ - `OnlineSim.parse_webhook(payload)` for inbound `receiving_sms` / `rent_sms` webhooks.
51
+ - Injectable transport (`OnlineSim::NetHttpTransport` by default) and per-request `timeout`.
52
+ - Offline test suite (minitest, fake transport), opt-in integration test, RuboCop, CI on Ruby 3.0 and latest.
53
+ - Documentation site (Nuxt Content).
54
+
7
55
  ## [1.0.6] - 2019-08-12
8
56
  ### Changed
9
57
  - fix proxy
data/README.md CHANGED
@@ -1,31 +1,26 @@
1
- # Onlinesim Ruby API
1
+ # onlinesim
2
2
 
3
+ [![Gem Version](https://badge.fury.io/rb/onlinesim.svg)](https://rubygems.org/gems/onlinesim)
4
+ [![CI](https://github.com/s00d/onlinesim-ruby-api/actions/workflows/ci.yml/badge.svg)](https://github.com/s00d/onlinesim-ruby-api/actions/workflows/ci.yml)
3
5
 
4
- Wrapper for automatic reception of SMS-messages by onlinesim.ru
6
+ Ruby client for the [OnlineSim](https://onlinesim.io) API: SMS numbers, rent, account and free numbers.
7
+ Zero runtime dependencies (`Net::HTTP` + `JSON` from the standard library), Ruby 3.0+.
5
8
 
6
- [![Gem Version](https://badge.fury.io/rb/onlinesim.svg)](https://badge.fury.io/rb/onlinesim)
7
-
8
- ### Installation
9
- You can install or upgrade package with:
10
9
  ```bash
11
- $ gem install onlinesim
10
+ bundle add onlinesim
12
11
  ```
13
- ### Example
14
- ```ruby
15
- require 'onlinesim'
16
-
17
- # ...
18
12
 
19
- driver = OnlineSim::Driver.new(:apikey => 'TOKEN').numbers
20
- tzid = driver.get('vkcom')
21
- puts driver.stateone(tzid)['number']
22
- puts driver.close(tzid)
23
- ```
13
+ ```ruby
14
+ require "onlinesim"
24
15
 
25
- ## Documentation
16
+ client = OnlineSim::Client.new(api_key: ENV["ONLINESIM_KEY"])
26
17
 
27
- All documentation is in the wiki of this project - **[Documentation](https://github.com/s00d/onlinesim-ruby-api/wiki)**
18
+ b = client.user.balance
19
+ puts "available: #{b['balance'] - b['zbalance']} USD"
28
20
 
29
- ## Bugs
21
+ order = client.numbers.get_with_number("google", 44)
22
+ puts "enter #{order['number']} in the app"
23
+ puts "code: #{client.numbers.wait_code(order['tzid'])}"
24
+ ```
30
25
 
31
- If you have any problems, please create Issues [here](https://github.com/s00d/onlinesim-ruby-api/issues)
26
+ Documentation: **https://s00d.github.io/onlinesim-ruby-api/** · Changes: [CHANGELOG.md](CHANGELOG.md) · License: Apache-2.0
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+ require "timeout"
6
+
7
+ module OnlineSim
8
+ DEFAULT_BASE_URL = "https://onlinesim.host/api/"
9
+
10
+ # OnlineSim API client.
11
+ #
12
+ # client = OnlineSim::Client.new(api_key: ENV["ONLINESIM_KEY"])
13
+ # client.user.balance["balance"]
14
+ class Client
15
+ DEFAULT_TIMEOUT = 30
16
+ BODY_EXCERPT = 500
17
+
18
+ attr_reader :numbers, :rent, :user, :free
19
+
20
+ # api_key - sent as "Authorization: Bearer <api_key>"; not needed for tariffs and free numbers.
21
+ # base_url - full API base, trailing slash optional.
22
+ # lang - `lang` query parameter.
23
+ # dev_id - `dev_id` query parameter, sent only when set.
24
+ # timeout - per-request timeout, seconds (Numeric).
25
+ # transport - object with `call(method, url, headers, body, timeout)`; see NetHttpTransport.
26
+ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, lang: "en", dev_id: nil, timeout: DEFAULT_TIMEOUT,
27
+ transport: NetHttpTransport.new)
28
+ @api_key = blank?(api_key) ? nil : api_key.to_s
29
+ @base_url = base_url.end_with?("/") ? base_url : "#{base_url}/"
30
+ @lang = lang
31
+ @dev_id = blank?(dev_id) ? nil : dev_id.to_s
32
+ @timeout = timeout
33
+ @transport = transport
34
+
35
+ request = method(:request)
36
+ @numbers = Numbers.new(request)
37
+ @rent = Rent.new(request)
38
+ @user = User.new(request)
39
+ @free = Free.new(request)
40
+ end
41
+
42
+ def inspect
43
+ "#<#{self.class.name} base_url=#{@base_url.inspect} lang=#{@lang.inspect}>"
44
+ end
45
+
46
+ private
47
+
48
+ # The one request function the sections call. `endpoint` is relative to `base_url`, suffix included
49
+ # ("getNum.php"). Query values: nil/""/[] omitted, booleans 1/0, arrays a comma list. `body` switches to POST.
50
+ def request(endpoint, query: {}, body: nil)
51
+ url = "#{@base_url}#{endpoint}"
52
+ params = encode_query(query.merge(lang: @lang, dev_id: @dev_id))
53
+ url = "#{url}?#{params}" unless params.empty?
54
+ headers = { "Accept" => "application/json" }
55
+ headers["Authorization"] = "Bearer #{@api_key}" if @api_key
56
+ method = "GET"
57
+ unless body.nil?
58
+ method = "POST"
59
+ headers["Content-Type"] = "application/json"
60
+ body = JSON.generate(body)
61
+ end
62
+
63
+ status, text = send_request(method, url, headers, body)
64
+ begin
65
+ data = JSON.parse(text)
66
+ rescue JSON::ParserError
67
+ raise TransportError.new("HTTP #{status}: response is not JSON", status: status, body: text[0, BODY_EXCERPT])
68
+ end
69
+ # The body is checked before the status: a wrong key is HTTP 456 with {"response":"ERROR_WRONG_KEY"}.
70
+ return unwrap(data) if data.is_a?(Hash) && data.key?("response")
71
+ raise TransportError.new("HTTP #{status}", status: status, body: text[0, BODY_EXCERPT]) unless (200..299).cover?(status)
72
+
73
+ data
74
+ end
75
+
76
+ def send_request(method, url, headers, body)
77
+ @transport.call(method, url, headers, body, @timeout)
78
+ rescue ::Timeout::Error
79
+ raise TransportError, "Request timed out after #{@timeout} s"
80
+ rescue StandardError => e
81
+ raise TransportError, "Network error: #{e.message}"
82
+ end
83
+
84
+ # Success: strip `response`, return the rest. Error code: raise.
85
+ def unwrap(data)
86
+ response = data["response"]
87
+ rest = data.except("response")
88
+ return rest if [1, "1"].include?(response)
89
+
90
+ if response.is_a?(Hash)
91
+ # profile.php validation errors: {"response":{"webhook_url":["The webhook url must be a valid URL."]}}
92
+ raise ApiError.new("VALIDATION_ERROR", response.values.flatten.join("; "))
93
+ end
94
+
95
+ code = response.to_s
96
+ # Debug backends echo the code as `message`; prefer the readable fallback then.
97
+ 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
+
100
+ raise ApiError.new(code, message)
101
+ end
102
+
103
+ def encode_query(query)
104
+ pairs = query.filter_map do |key, value|
105
+ value = value.join(",") if value.is_a?(Array)
106
+ next if blank?(value)
107
+
108
+ value = 1 if value == true
109
+ value = 0 if value == false
110
+ [key.to_s, value.to_s]
111
+ end
112
+ URI.encode_www_form(pairs)
113
+ end
114
+
115
+ def blank?(value)
116
+ value.nil? || value == ""
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Base class of every error raised by the SDK.
5
+ class Error < StandardError; end
6
+
7
+ # The API answered with an error code in `response`.
8
+ class ApiError < Error
9
+ # Raw error code, e.g. "ERROR_WRONG_KEY".
10
+ attr_reader :code
11
+
12
+ def initialize(code, message = nil)
13
+ @code = code
14
+ super(message.nil? || message.empty? ? ERROR_MESSAGES.fetch(code, code) : message)
15
+ end
16
+ end
17
+
18
+ # No number is available right now (NO_NUMBER, NO_NUMBER_FOR_FORWARD). Retry later or pick another country.
19
+ class NoNumberError < ApiError; end
20
+
21
+ # Network failure, request timeout, or a response that is not JSON.
22
+ class TransportError < Error
23
+ # HTTP status, or nil when no response arrived (network error, timeout).
24
+ attr_reader :status
25
+ # Start of the response body (up to 500 chars), empty when none.
26
+ attr_reader :body
27
+
28
+ def initialize(message, status: nil, body: "")
29
+ super(message)
30
+ @status = status
31
+ @body = body
32
+ end
33
+ end
34
+
35
+ # `wait_code` gave up: no code arrived within its `timeout`.
36
+ class TimeoutError < Error; end
37
+
38
+ # Fallback messages for error codes the server sends without a `message`.
39
+ ERROR_MESSAGES = {
40
+ "ACCOUNT_BLOCKED" => "Account is blocked",
41
+ "ERROR_WRONG_KEY" => "Wrong API key",
42
+ "ERROR_NO_KEY" => "API key is missing",
43
+ "ERROR_NO_SERVICE" => "Service is not specified",
44
+ "API_ACCESS_DISABLED" => "API access is disabled in the profile",
45
+ "API_ACCESS_IP" => "API access from this IP is not allowed in the profile",
46
+ "ERROR_NO_TZID" => "tzid is not specified",
47
+ "ERROR_WRONG_TZID" => "Wrong tzid",
48
+ "ERROR_NO_OPERATIONS" => "No operations",
49
+ "NO_NUMBER" => "No numbers available for this service right now",
50
+ "NO_NUMBER_FOR_FORWARD" => "No numbers available for forwarding",
51
+ "NO_COUNTRY" => "Country not found",
52
+ "UNDEFINED_COUNTRY" => "Unknown country",
53
+ "WARNING_LOW_BALANCE" => "Not enough balance",
54
+ "EXCEEDED_CONCURRENT_OPERATIONS" => "Too many concurrent operations for this account",
55
+ "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",
58
+ "ERROR_PARAMS" => "Wrong parameters",
59
+ "API_DISABLED" => "API is disabled",
60
+ "NO_COMPLETE_TZID" => "The operation cannot be closed yet",
61
+ "NO_CLOSE_RENT_US" => "US rent numbers cannot be closed early",
62
+ "UNDEFINED_DAYS" => "Unknown rent period",
63
+ "VALIDATION_ERROR" => "Validation failed",
64
+ "TZ_OVER_OK" => "Operation finished without a new code",
65
+ "ERROR_NO_ITEMS" => "Operation failed"
66
+ }.freeze
67
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Public free numbers: `client.free`. No key needed.
5
+ class Free
6
+ def initialize(request)
7
+ @request = request
8
+ end
9
+
10
+ # Countries, the numbers of the selected country and the SMS of the selected number.
11
+ # `number` is the number without its country code, as the keys of "numbers".
12
+ def list(country: nil, number: nil, page: nil, count: nil)
13
+ res = @request.call("getFreeList", query: { country: country, number: number, page: page, count: count })
14
+ { "countries" => res["countries"], "numbers" => Normalize.map(res["numbers"]), "messages" => res["messages"] }
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Client-side normalisation of server quirks, shared by the sections and `parse_webhook`.
5
+ module Normalize
6
+ module_function
7
+
8
+ # PHP sends an empty map as `[]`: return `{}` for it (and for anything that is not a Hash).
9
+ def map(value)
10
+ value.is_a?(Hash) ? value : {}
11
+ end
12
+
13
+ # Number from a number or a numeric string ("1442.330"); nil when missing or not numeric.
14
+ def num(value)
15
+ case value
16
+ when Integer then value
17
+ when Float then value.finite? ? value : nil
18
+ when String
19
+ text = value.strip
20
+ return nil if text.empty?
21
+
22
+ Integer(text, exception: false) || Float(text, exception: false)&.then { |f| f.finite? ? f : nil }
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Numbers for receiving SMS: `client.numbers`. Results are Hashes with the server's (string) keys.
5
+ class Numbers
6
+ def initialize(request)
7
+ @request = request
8
+ end
9
+
10
+ # Price (USD) of one number of `service` in `country`; nil when the country has no price for it.
11
+ def price(service, country = 7)
12
+ @request.call("getPrice.php", query: { service: service, country: country })["price"]
13
+ end
14
+
15
+ # Order a number. Returns the operation id (tzid).
16
+ def get(service, country = 7, reject: nil)
17
+ @request.call("getNum.php", query: { service: service, country: country, reject: reject })["tzid"]
18
+ end
19
+
20
+ # Order a number and get it right away: {"tzid", "number", "country", "time", "service", ...}.
21
+ def get_with_number(service, country = 7, reject: nil)
22
+ # `number` is a presence flag on getNum: sent here only.
23
+ @request.call("getNum.php", query: { service: service, country: country, reject: reject, number: 1 })
24
+ end
25
+
26
+ # All operations of the account; [] when there are none.
27
+ def state(message_to_code: true, order_by: "asc", msg_list: false)
28
+ @request.call("getState.php", query: {
29
+ message_to_code: message_to_code, orderby: order_by, msg_list: msg_list, number: 1
30
+ })
31
+ rescue ApiError => e
32
+ raise unless e.code == "ERROR_NO_OPERATIONS"
33
+
34
+ []
35
+ end
36
+
37
+ # One operation. Raises ApiError ERROR_NO_OPERATIONS when it does not exist (any more).
38
+ def state_one(tzid, message_to_code: true, msg_list: false)
39
+ list = @request.call("getState.php", query: {
40
+ tzid: tzid, message_to_code: message_to_code, msg_list: msg_list, number: 1
41
+ })
42
+ list.first || raise(ApiError, "ERROR_NO_OPERATIONS")
43
+ end
44
+
45
+ # Switch the operation to its next SMS and keep it open.
46
+ def next(tzid)
47
+ @request.call("setOperationRevise.php", query: { tzid: tzid })
48
+ true
49
+ end
50
+
51
+ # Finish the operation.
52
+ def close(tzid)
53
+ @request.call("setOperationOk.php", query: { tzid: tzid })
54
+ true
55
+ end
56
+
57
+ # Finish the operation and report the number as bad (only before any SMS arrived).
58
+ def ban(tzid)
59
+ @request.call("setOperationOk.php", query: { tzid: tzid, ban: true })
60
+ true
61
+ end
62
+
63
+ # Services, prices and stock of every country, keyed by country code. No key needed.
64
+ def tariffs
65
+ Normalize.map(@request.call("getNumbersStats.php", query: { country: "all" }))
66
+ .transform_values { |c| country(c) }
67
+ end
68
+
69
+ # Services, prices and stock of one country. No key needed.
70
+ def tariffs_one(code = 7)
71
+ country(@request.call("getNumbersStats.php", query: { country: code }))
72
+ end
73
+
74
+ # Poll the operation until an SMS code arrives, then close it (or `next` with keep_open). See OnlineSim.wait_code.
75
+ def wait_code(tzid, **options)
76
+ OnlineSim.wait_code(self, tzid, **options)
77
+ end
78
+
79
+ private
80
+
81
+ def country(stat)
82
+ stat.merge("services" => Normalize.map(stat["services"]))
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Rented numbers: `client.rent`.
5
+ class Rent
6
+ # Always sent: flat `messages` list and `time_seconds`.
7
+ DETAIL = { pagination: 0, number: 1 }.freeze
8
+
9
+ def initialize(request)
10
+ @request = request
11
+ end
12
+
13
+ # Rent a number for `days` days. `extension: false` makes the rent non-extendable for good.
14
+ def get(country = 7, days = 1, extension: true)
15
+ res = @request.call("rent/getRentNum.php", query: { country: country, days: days, extension: extension, **DETAIL })
16
+ item(res["item"])
17
+ end
18
+
19
+ # All rents of the account.
20
+ def state
21
+ @request.call("rent/getRentState.php", query: DETAIL)["list"].map { |raw| item(raw) }
22
+ end
23
+
24
+ # One rent. Raises ApiError ERROR_NO_OPERATIONS when it does not exist.
25
+ def state_one(tzid)
26
+ raw = @request.call("rent/getRentState.php", query: { tzid: tzid, **DETAIL })["list"].first
27
+ raise ApiError, "ERROR_NO_OPERATIONS" unless raw
28
+
29
+ item(raw)
30
+ end
31
+
32
+ # Extend a rent by `days` days (only rents created with `extension: true`).
33
+ # Overrides Object#extend on this section object on purpose: the name is the API's.
34
+ def extend(tzid, days = 1)
35
+ item(@request.call("rent/extendRentState.php", query: { tzid: tzid, days: days, **DETAIL })["item"])
36
+ end
37
+
38
+ # Rent prices of every country, keyed by country code. No key needed.
39
+ def tariffs
40
+ Normalize.map(@request.call("rent/tariffsRent.php"))
41
+ end
42
+
43
+ # Rent prices of one country. Raises ApiError NO_COUNTRY for a country without rent. No key needed.
44
+ def tariffs_one(country = 7)
45
+ res = @request.call("rent/tariffsRent.php", query: { country: country })
46
+ # An unknown country answers `[]`.
47
+ raise ApiError, "NO_COUNTRY" unless res.is_a?(Hash) && res.key?("code")
48
+
49
+ res
50
+ end
51
+
52
+ # Return the number before the rent period ends.
53
+ def close(tzid)
54
+ @request.call("rent/closeRentNum.php", query: { tzid: tzid })
55
+ true
56
+ end
57
+
58
+ private
59
+
60
+ # `sum` is a decimal string, `extend` may be `[]`.
61
+ def item(raw)
62
+ raw.merge(
63
+ "sum" => (Normalize.num(raw["sum"]) || 0).to_f,
64
+ "extend" => Normalize.map(raw["extend"]),
65
+ "messages" => raw["messages"].is_a?(Array) ? raw["messages"] : []
66
+ )
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+
6
+ module OnlineSim
7
+ # Default transport on stdlib Net::HTTP. Any object with the same `call` works (a fake in tests, a proxy setup).
8
+ #
9
+ # `call(method, url, headers, body, timeout)` returns `[status, body_string]` and raises on network errors
10
+ # (`Timeout::Error` for a timeout). `timeout` (seconds) applies to connect, read and write separately.
11
+ class NetHttpTransport
12
+ # `start_options` go to `Net::HTTP.start`, e.g. `ca_file:`, `cert:`, `key:`. TLS is verified by default.
13
+ def initialize(**start_options)
14
+ @start_options = start_options
15
+ end
16
+
17
+ def call(method, url, headers, body, timeout)
18
+ uri = URI(url)
19
+ options = {
20
+ use_ssl: uri.scheme == "https",
21
+ open_timeout: timeout, read_timeout: timeout, write_timeout: timeout
22
+ }.merge(@start_options)
23
+ # Proxy from the environment (http_proxy / https_proxy / no_proxy), as Net::HTTP does by default.
24
+ Net::HTTP.start(uri.host, uri.port, options) do |http|
25
+ request = (method == "POST" ? Net::HTTP::Post : Net::HTTP::Get).new(uri, headers)
26
+ request.body = body if body
27
+ response = http.request(request)
28
+ [response.code.to_i, String.new(response.body.to_s, encoding: Encoding::UTF_8)]
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ # Account: `client.user`.
5
+ class User
6
+ def initialize(request)
7
+ @request = request
8
+ end
9
+
10
+ # Balance in USD: {"balance" => Float, "zbalance" => Float, "income" => Float (when sent)}.
11
+ # `balance` includes the frozen `zbalance`: available = balance - zbalance.
12
+ def balance
13
+ res = @request.call("getBalance.php", query: { income: 1 })
14
+ out = { "balance" => (Normalize.num(res["balance"]) || 0).to_f, "zbalance" => (Normalize.num(res["zbalance"]) || 0).to_f }
15
+ income = Normalize.num(res["income"])
16
+ out["income"] = income.to_f unless income.nil?
17
+ out
18
+ end
19
+
20
+ # Account profile.
21
+ def profile
22
+ @request.call("getProfile.php")["profile"]
23
+ end
24
+
25
+ # Top-up orders (paginated, newest first) and the available payment methods.
26
+ def payment_history(page = 1)
27
+ res = @request.call("getPaymentHistory.php", query: { page: page })
28
+ res.merge("paylist" => Normalize.map(res["paylist"]))
29
+ end
30
+
31
+ # Set the URL that receives SMS webhooks. Raises ApiError VALIDATION_ERROR for an invalid URL.
32
+ def set_webhook_url(url) # rubocop:disable Naming/AccessorMethodName -- API method name
33
+ @request.call("profile.php", body: { profile: { webhook_url: url } })
34
+ true
35
+ end
36
+
37
+ # Remove the webhook URL (also from operations in progress).
38
+ def clear_webhook_url
39
+ @request.call("profile.php", body: { profile: { webhook_url: nil } })
40
+ true
41
+ end
42
+
43
+ # Webhook delivery log, newest first, 10 per page (a Laravel paginator Hash).
44
+ def webhook_logs(page = 1)
45
+ @request.call("webhook-logs", query: { page: page })["data"]
46
+ end
47
+ end
48
+ end
@@ -1,3 +1,5 @@
1
- module Onlinesim
2
- VERSION = "1.0.11"
1
+ # frozen_string_literal: true
2
+
3
+ module OnlineSim
4
+ VERSION = "2.0.0"
3
5
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ruby client for the OnlineSim API. Entry point: OnlineSim::Client.
4
+ module OnlineSim
5
+ MONOTONIC = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
6
+ private_constant :MONOTONIC
7
+
8
+ # Poll `numbers.state_one(tzid)` every `interval` seconds until a code different from `since` arrives, then
9
+ # `close` (or `next` with `keep_open`) and return it. A finished operation (TZ_OVER_OK, ERROR_NO_ITEMS) without a
10
+ # 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.
12
+ # `sleep` (seconds -> any) and `now` (-> seconds) are injectable for tests.
13
+ def self.wait_code(numbers, tzid, interval: 5, timeout: 600, keep_open: false, full_message: false, since: nil,
14
+ sleep: Kernel.method(:sleep), now: MONOTONIC)
15
+ deadline = now.call + timeout
16
+ loop do
17
+ op = begin
18
+ numbers.state_one(tzid, message_to_code: !full_message)
19
+ rescue TransportError
20
+ nil
21
+ end
22
+
23
+ if op
24
+ msg = op["msg"]
25
+ if msg.is_a?(String) && !msg.empty? && msg != since
26
+ keep_open ? numbers.next(tzid) : numbers.close(tzid)
27
+ return msg
28
+ end
29
+ raise ApiError, op["response"] if %w[TZ_OVER_OK ERROR_NO_ITEMS].include?(op["response"])
30
+ end
31
+
32
+ left = deadline - now.call
33
+ raise TimeoutError, "No code for operation #{tzid} within #{timeout} s" if left <= 0
34
+
35
+ sleep.call([interval, left].min)
36
+ end
37
+ end
38
+ end