Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [3.1.1]

Aligned with the regenerated backend API spec.

### Fixed
- `numbers.wait_code` no longer crashes with `KeyError` on a getState operation without `response` (absent while no number is issued); it keeps polling.
- Types: `Profile["number"]` is `int | None` and `Profile["country"]` is `str | None` (they were swapped); `Operation["response"]` is optional; `RentSms["code"]` is `str | int` (the integer `0` for a `notify` SMS, returned as sent); `FreeCountry` `country_text`/`country_original`, `FreeNumber["country_original"]`, `PaymentOrder` `currency`/`form_text` accept `None`.
- `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.
- `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.
- 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; `NoNumberError` only for `NO_NUMBER`; `ERROR_WRONG_KEY` reads "Wrong or missing API key".
- `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, 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` lists 44 first, clamps `count` to 10..500, sends ISO-8601 `created_at` and `ignore`/`content`. `MockRent` gained `initial_days` and `status`, `MockSms` gained `at`.
- Docs: rent reservation and `sum`, available = balance − max(zbalance, 0), `ban` answer `"0"`, webhook `number`/`time_left`/`time_start`, the `wait_code` retry policy, the mock's behaviour.

## [3.1.0]

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ from onlinesimru import OnlineSim
client = OnlineSim(os.environ["ONLINESIM_KEY"])

b = client.user.balance()
print(f"available: {b['balance'] - b['zbalance']} USD")
print(f"available: {b['balance'] - max(b['zbalance'], 0)} USD")

order = client.numbers.get_with_number("google", 44)
print(f"enter {order['number']} in the app")
Expand Down
6 changes: 6 additions & 0 deletions docs/content/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ navigation:

The full history is in [CHANGELOG.md](https://github.com/s00d/onlinesim-python-api/blob/master/CHANGELOG.md).

## 3.1.1

- Fixed: `wait_code` no longer crashes on an operation without `response`; types against the current API (`Profile` `number`/`country`, optional `Operation["response"]`, `RentSms["code"]` `0` for `notify` SMS, nullable free-list and payment fields); `payment_history()["paylist"]` is kept when it arrives as a list.
- `wait_code` retries `TRY_AGAIN_LATER` (rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR`.
- `MockOnlineSim` follows the backend more closely: rent reservation and confirmation, `setOperationRevise` and `closeRentNum` answers, missing vs wrong key — see [Testing](/testing).

## 3.1.0

- New: `MockOnlineSim`, an offline fake of the API for your tests — see [Testing](/testing).
Expand Down
8 changes: 4 additions & 4 deletions docs/content/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ from onlinesimru import OnlineSim
client = OnlineSim(os.environ["ONLINESIM_KEY"])

b = client.user.balance()
print(f"available: {b['balance'] - b['zbalance']} USD")
print(f"available: {b['balance'] - max(b['zbalance'], 0)} USD")

order = client.numbers.get_with_number("google", 44)
print(f"enter {order['number']} in the app")
Expand Down Expand Up @@ -60,7 +60,7 @@ client = OnlineSim("your-api-key", lang="en", timeout=15)

Sections: [`client.numbers`](/numbers), [`client.rent`](/rent), [`client.user`](/user), [`client.free`](/free). Webhook bodies are parsed by the standalone [`parse_webhook`](/webhooks).

Returned dicts keep the server's snake_case field names. Two things are normalised: money that the server sends as a decimal string (`balance`, rent `sum`) becomes a number, and maps that arrive as an empty PHP array `[]` become `{}`.
Returned dicts keep the server's snake_case field names. Two things are normalised: money that the server sends as a decimal string (`balance`, rent `sum` in `rent.state`) becomes a number, and maps that arrive as an empty PHP array `[]` become `{}`. `payment_history()["paylist"]` is left as sent: a JSON array when its ids are 0, 1, 2…

### Transport

Expand All @@ -82,8 +82,8 @@ Every error extends `OnlineSimError`.

| Class | When | Attributes |
|---|---|---|
| `ApiError` | The API answered with an error code (also a wrong key, HTTP 456). | `code`, `message` |
| `NoNumberError` | `NO_NUMBER` / `NO_NUMBER_FOR_FORWARD`: no number right now. Subclass of `ApiError`. | `code`, `message` |
| `ApiError` | The API answered with an error code (also a wrong key, HTTP 456, and the rate limit, HTTP 429 `TRY_AGAIN_LATER`). | `code`, `message` |
| `NoNumberError` | `NO_NUMBER`: no number right now. Subclass of `ApiError`. | `code`, `message` |
| `TransportError` | Network error, request timeout, or a body that is not JSON. | `status` (`None` without a response), `body` (first 500 chars) |
| `TimeoutError` | `wait_code` got no code within its `timeout`. Also a built-in `TimeoutError`. | — |

Expand Down
14 changes: 8 additions & 6 deletions docs/content/numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ def state(*, message_to_code: bool = True, order_by: Literal["asc", "desc"] = "a
| `order_by` | `"asc" \| "desc"` | `"asc"` | Order of operations. |
| `msg_list` | `bool` | `False` | `msg` is a list of all SMS (`list[OperationSms]`). |

`Operation`: `{tzid, response, number?, service?, country?, sum?, time?, msg?, guard_interval_remaining_seconds?, …}`.
`response` is the state: `TZ_INPOOL` (number being assigned), `TZ_NUM_WAIT` (waiting for SMS), `TZ_NUM_ANSWER` (SMS arrived), `TZ_OVER_OK` (finished), `ERROR_NO_ITEMS` (failed). `msg` is absent until the first SMS. The server caches answers for a few seconds.
`Operation`: `{tzid, response?, number?, service?, country?, sum?, time?, msg?, guard_interval_remaining_seconds?, …}`.
`response` is the state (absent when no number could be issued): `TZ_INPOOL` (number being assigned), `TZ_NUM_WAIT` (waiting for SMS), `TZ_NUM_ANSWER` (SMS arrived), `TZ_OVER_OK` (finished), `ERROR_NO_ITEMS` (failed). `msg` is absent until the first SMS. The server caches answers for a few seconds.

```python
for op in client.numbers.state(order_by="desc"):
print(op["tzid"], op["response"], op.get("msg"))
print(op["tzid"], op.get("response"), op.get("msg"))
```

## state_one
Expand All @@ -95,7 +95,7 @@ def state_one(tzid: int, *, message_to_code: bool = True, msg_list: bool = False

```python
op = client.numbers.state_one(tzid)
if op["response"] == "TZ_NUM_ANSWER":
if op.get("response") == "TZ_NUM_ANSWER":
print(op.get("msg"))
```

Expand All @@ -120,7 +120,7 @@ def wait_code(tzid: int, *, interval: float = 5.0, timeout: float = 600.0, keep_
| `since` | `str \| None` | `None` | Ignore this value (the previous code). |
| `sleep`, `clock` | callables | `time.sleep`, `time.monotonic` | Injectable for tests. |

A transient `TransportError` is retried until the timeout; any `ApiError` is raised at once. The same function is available standalone as `onlinesimru.wait_code(numbers, tzid, ...)`.
Transient errors are retried until the timeout: `TransportError`, and `ApiError` `TRY_AGAIN_LATER` (the HTTP 429 rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR`. Any other `ApiError` is raised at once. The same function is available standalone as `onlinesimru.wait_code(numbers, tzid, ...)`.

```python
first = client.numbers.wait_code(tzid, keep_open=True)
Expand All @@ -141,6 +141,8 @@ def next(tzid: int) -> bool
client.numbers.next(tzid)
```

Errors: `ApiError` `ERROR_WRONG_TZID` (not an operation of your account), `ERROR_NO_TZID`.

## close

Finish the operation. An operation without SMS can be closed only after its guard interval (`guard_interval_remaining_seconds`); every attempt locks the tzid for 5 s.
Expand All @@ -167,7 +169,7 @@ def ban(tzid: int) -> bool
client.numbers.ban(tzid)
```

Errors: as `close`.
Errors: as `close`; `ApiError` with code `"0"` when the operation already has an SMS — nothing is changed then.

## tariffs

Expand Down
14 changes: 8 additions & 6 deletions docs/content/rent.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ navigation:

A rent keeps a number for `days` days. Its SMS come in `RentItem["messages"]`, newest first.

`get` reserves the price (it shows in `zbalance`): the rent starts with `status` `0` and `checked` `False` and waits up to 20 minutes for its first SMS. The first SMS that is not a `notify` notice confirms it (`status` `1`) and charges the price; without one the rent closes and the reservation is released. Some countries (`confirm` in `tariffs`, e.g. US numbers) are confirmed and charged at once.

`RentItem`: `{tzid, status, number, country, sum, days, hours, time, time_seconds?, extension, extend, messages, start_time, stop_time, day_extend?, …}` —
`sum` is the price paid in USD (a number; the server sends a decimal string), `time` minutes left, `time_seconds` seconds left,
`sum` is the cost in USD incl. extensions (a number; `rent.state` gets it from the server as a decimal string), `time` minutes left, `time_seconds` seconds left,
`extension` `0` not extendable / `1` extendable / `2` auto-extension, `extend` maps days to the extension price (`{}` when not extendable),
`messages` is `list[RentSms]`: `{id, service, text, code, created_at}`.
`messages` is `list[RentSms]`: `{id, service, text, code, created_at}` — `code` is `""` when no code was found and the integer `0` for a `notify` SMS (a prohibited sender).

## get

Rent a number and charge the balance.
Rent a number. The price is reserved; the first SMS charges it.

```python
def get(country: int = 7, days: int = 1, extension: bool = True) -> RentItem
Expand Down Expand Up @@ -62,7 +64,7 @@ Errors: `ApiError` `ERROR_NO_OPERATIONS` for an unknown tzid.

## extend

Extend a rent by `days` days and charge the balance. Only rents created with `extension=True`.
Extend a rent by `days` days and charge the balance at once. Only confirmed rents (`status` `1` or `4`) created with `extension=True`.

```python
def extend(tzid: int, days: int = 1) -> RentItem
Expand All @@ -73,11 +75,11 @@ rent = client.rent.extend(tzid, 3)
print(rent["stop_time"])
```

Errors: `ApiError` `TRY_AGAIN_LATER` (not extendable, unknown tzid or period, a repeat within 10 s), `WARNING_LOW_BALANCE`.
Errors: `ApiError` `TRY_AGAIN_LATER` (unknown tzid, not confirmed yet or closed, not extendable, unknown period, a repeat within 10 s), `WARNING_LOW_BALANCE`.

## close

Return the number before the period ends. A rent that is not confirmed yet and has no SMS can be closed only after 120 s; US numbers cannot be closed early.
Return the number before the period ends. A rent that is not confirmed yet (`status` `0`) and has no SMS can be closed only after 120 s; then, or with only `notify` SMS, the reservation is released. With a real SMS the rent is confirmed (charged) and closed. A confirmed rent closes without a refund. US numbers cannot be closed early.

```python
def close(tzid: int) -> bool
Expand Down
14 changes: 7 additions & 7 deletions docs/content/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ navigation:
order: 6
---

`MockOnlineSim` is an in-process fake of the OnlineSim API that ships with the package. It is a [transport](/#transport) that answers like the real backend — same shapes, same error codes, HTTP 456 for a wrong key — and keeps a balance, operations and rents. Your code talks to a normal `OnlineSim` client, so nothing in it changes for tests. It is deterministic: no randomness, no clock, numbers and ids come from a counter.
`MockOnlineSim` is an in-process fake of the OnlineSim API that ships with the package. It is a [transport](/#transport) that answers like the real backend — same shapes, same error codes, HTTP 456 for a wrong key and HTTP 200 `ERROR_WRONG_KEY` for a missing one — and keeps a balance, operations and rents. Your code talks to a normal `OnlineSim` client, so nothing in it changes for tests. It is deterministic: no randomness, no clock, numbers and ids come from a counter.

## Setup

Expand Down Expand Up @@ -33,7 +33,7 @@ MockOnlineSim(
| `balance` | `100` | Starting balance, USD. |
| `prices` | `{7: {"vkcom": 0.5, "telegram": 1.2, "google": 0.3}, 44: {"google": 0.2, "vkcom": 0.36}}` | Number prices; replaces the defaults. Also feeds `numbers.tariffs()`. |
| `rent_tariffs` | `{7: {"days": {1: 1.0, 3: 2.5, 7: 5.0}, "extend": 1}}` | Rent prices; `"extend": 0` makes rents of that country non-extendable. |
| `guard_interval` | `0` | `> 0`: an operation without SMS cannot be closed (`NO_COMPLETE_TZID`). |
| `guard_interval` | `0` | `> 0`: an operation without SMS, or an unconfirmed rent without any SMS, cannot be closed (`NO_COMPLETE_TZID`). |

`mock.client(*, api_key, base_url, lang, dev_id, timeout)` takes the usual [client options](/#client-options) except `transport`. To build the client yourself, pass `mock.transport` as `transport`; any `base_url` works:

Expand Down Expand Up @@ -94,7 +94,7 @@ def test_handles_a_missing_number_and_a_network_hiccup() -> None:
assert client.user.balance()["balance"] == 100 # one-shot
```

The state itself produces the real error codes too: `WARNING_LOW_BALANCE` when the balance is short, `NO_NUMBER` when `reject` matches the next number, `UNDEFINED_COUNTRY` / `ERROR_NO_SERVICE` for unknown prices, `ERROR_WRONG_TZID` for an unknown or closed operation, `TRY_AGAIN_LATER` when extending a non-extendable rent, `ERROR_WRONG_KEY` (HTTP 456) for a wrong key.
The state itself produces the real error codes too: `WARNING_LOW_BALANCE` when the balance is short, `NO_NUMBER` when `reject` matches the next number, `UNDEFINED_COUNTRY` / `ERROR_NO_SERVICE` for unknown prices, `ERROR_WRONG_TZID` for an unknown or closed operation (`next` too; `ERROR_NO_TZID` for tzid `0`), `UNDEFINED_COUNTRY` / `UNDEFINED_DAYS` for an unknown rent country or period, `TRY_AGAIN_LATER` for every refused `rent.extend`, `ERROR_NO_OPERATIONS` for an unknown rent in `rent.close`, `ERROR_WRONG_KEY` for a wrong key (HTTP 456) or no key (HTTP 200).

## Inspecting requests

Expand Down Expand Up @@ -131,7 +131,7 @@ def test_sends_reject_as_a_comma_list() -> None:
## What the mock does

- **Numbers**: `get` freezes the price; `close` after an SMS spends it, `close` without one refunds it; `ban` after an SMS answers `"0"`, like the server. Numbers are `+<country>9000000NN`, ids count from 1. `next` switches to the following SMS. The operation's `time` stays at 1200 s — there is no clock.
- **Rent**: `get` charges at once and keeps the `extension` flag; `extend` charges again; `close` removes the rent. SMS appear in `messages`, newest first.
- **User**: `balance` (frozen part included), a fixed profile, `set_webhook_url` validates `http(s)` URLs (`VALIDATION_ERROR` otherwise), `webhook_logs` lists the deliveries the mock *recorded* when an SMS arrived while a webhook URL was set — it makes no HTTP call. `payment_history` is empty.
- **Free**: `free.list` returns two fixed countries with one number and a few SMS each.
- Not imitated: the server's 5 s lock after `setOperationOk` (`INTERVAL_CONCURRENT_REQUESTS_ERROR`) and anything else that needs real time.
- **Rent**: `get` reserves the price (`status` `0`, `checked` `False`) and keeps the `extension` flag; the first SMS that is not `notify` confirms the rent (`status` `1`) and charges it — `add_sms(tzid, text, service="notify")` adds a notice with `code` `0` that confirms nothing. `extend` works on a confirmed rent and charges at once. `close` releases the reservation of an unconfirmed rent and gives no refund for a confirmed one. `sum` is a number in `get`/`extend` and a decimal string on the wire of `state`, like the server. SMS appear in `messages`, newest first.
- **User**: `balance` (frozen part included), a fixed profile, `set_webhook_url` accepts any `scheme://…` URL (`VALIDATION_ERROR` otherwise), `webhook_logs` lists the deliveries the mock *recorded* when an SMS arrived while a webhook URL was set — it makes no HTTP call; their `params` follow the real payload (`code` `""` without a code, rent `number` in digits without `+`, rent `time_left` in minutes). `payment_history` has no orders.
- **Free**: `free.list` returns two fixed countries (44 first) with one number and a few SMS each.
- Not imitated: anything that needs real time — the 5 s lock after `setOperationOk` (`INTERVAL_CONCURRENT_REQUESTS_ERROR`), the 10 s lock of `rent.extend`, the 120 s before an unconfirmed rent may be closed and its 20-minute wait for the first SMS. `guard_interval > 0` stands in for "too early to close".
6 changes: 3 additions & 3 deletions docs/content/user.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ Balance in USD.
def balance() -> Balance # {"balance": float, "zbalance": float, "income"?: float}
```

`balance` includes the sum frozen by numbers in progress (`zbalance`): available = `balance − zbalance`. `income` is the partner income. The server caches the answer for 60 s.
`balance` includes the sum frozen by numbers and unconfirmed rents in progress (`zbalance`, which may be negative): available = `balance − max(zbalance, 0)`. `income` is the partner income. The server caches the answer for 60 s.

```python
b = client.user.balance()
available = b["balance"] - b["zbalance"]
available = b["balance"] - max(b["zbalance"], 0)
```

Errors: `ApiError` `ERROR_WRONG_KEY`, `ACCOUNT_BLOCKED`, `API_ACCESS_DISABLED`, `API_ACCESS_IP`.
Expand Down Expand Up @@ -45,7 +45,7 @@ Top-up orders (paginated, newest first) and the available payment methods.
def payment_history(page: int = 1) -> PaymentHistory
```

`PaymentHistory`: `{orders, paylist, domains?, forms?, currency?, buttons?}` — `orders` is a paginator of `PaymentOrder`. `PaymentOrder["sum"]` stays a decimal string (`"89.00"`).
`PaymentHistory`: `{orders, paylist, domains?, forms?, currency?, buttons?}` — `orders` is a paginator of `PaymentOrder`. `PaymentOrder["sum"]` stays a decimal string (`"89.00"`); `currency` and `form_text` may be `None`. `paylist` maps a group id to its payment methods, or is a list when the ids are 0, 1, 2… (the server sends a JSON array then).

```python
orders = client.user.payment_history()["orders"]
Expand Down
8 changes: 4 additions & 4 deletions docs/content/webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ HTTPServer(("", 8080), Hook).serve_forever()
| `operation_id` | `int \| None` | `tzid` of the operation or rent. |
| `user_id` | `int \| None` | Account id. |
| `country_code` | `int \| None` | Country code of the number. |
| `number` | `str \| None` | The number, e.g. `+79001234567`. |
| `number` | `str \| None` | Numbers: `+` and the full number (`+79001234567`), or `hidden`. Rent: the full number in digits without `+` (`79001234567`). |
| `sender` | `str \| None` | Sender of the SMS, e.g. `VK`. |
| `message` | `str \| None` | Full SMS text. |
| `code` | `str \| None` | Code extracted from the SMS. |
| `time_start` | `str \| None` | Start of the operation. |
| `time_left` | `int \| None` | Time left. |
| `code` | `str \| None` | Code extracted from the SMS; `""` when none was found. |
| `time_start` | `str \| None` | Numbers: when the operation was ordered. Rent: when the SMS arrived. `YYYY-MM-DD HH:MM:SS`. |
| `time_left` | `int \| None` | Time left: seconds for numbers, minutes for rent. |
Loading
Loading