Skip to main content

timeweb_rs/apis/
account_api.rs

1/*
2 * Документация публичного API
3 *
4 * # Введение API Timeweb Cloud позволяет вам управлять ресурсами в облаке программным способом с использованием обычных HTTP-запросов.  Множество функций, которые доступны в панели управления Timeweb Cloud, также доступны через API, что позволяет вам автоматизировать ваши собственные сценарии.  В этой документации сперва будет описан общий дизайн и принципы работы API, а после этого конкретные конечные точки. Также будут приведены примеры запросов к ним.   ## Запросы Запросы должны выполняться по протоколу `HTTPS`, чтобы гарантировать шифрование транзакций. Поддерживаются следующие методы запроса: |Метод|Применение| |--- |--- | |GET|Извлекает данные о коллекциях и отдельных ресурсах.| |POST|Для коллекций создает новый ресурс этого типа. Также используется для выполнения действий с конкретным ресурсом.| |PUT|Обновляет существующий ресурс.| |PATCH|Некоторые ресурсы поддерживают частичное обновление, то есть обновление только части атрибутов ресурса, в этом случае вместо метода PUT будет использован PATCH.| |DELETE|Удаляет ресурс.|  Методы `POST`, `PUT` и `PATCH` могут включать объект в тело запроса с типом содержимого `application/json`.  ### Параметры в запросах Некоторые коллекции поддерживают пагинацию, поиск или сортировку в запросах. В параметрах запроса требуется передать: - `limit` — обозначает количество записей, которое необходимо вернуть  - `offset` — указывает на смещение, относительно начала списка  - `search` — позволяет указать набор символов для поиска  - `sort` — можно задать правило сортировки коллекции  ## Ответы Запросы вернут один из следующих кодов состояния ответа HTTP:  |Статус|Описание| |--- |--- | |200 OK|Действие с ресурсом было выполнено успешно.| |201 Created|Ресурс был успешно создан. При этом ресурс может быть как уже готовым к использованию, так и находиться в процессе запуска.| |204 No Content|Действие с ресурсом было выполнено успешно, и ответ не содержит дополнительной информации в теле.| |400 Bad Request|Был отправлен неверный запрос, например, в нем отсутствуют обязательные параметры и т. д. Тело ответа будет содержать дополнительную информацию об ошибке.| |401 Unauthorized|Ошибка аутентификации.| |403 Forbidden|Аутентификация прошла успешно, но недостаточно прав для выполнения действия.| |404 Not Found|Запрашиваемый ресурс не найден.| |409 Conflict|Запрос конфликтует с текущим состоянием.| |423 Locked|Ресурс из запроса заблокирован от применения к нему указанного метода.| |429 Too Many Requests|Был достигнут лимит по количеству запросов в единицу времени.| |500 Internal Server Error|При выполнении запроса произошла какая-то внутренняя ошибка. Чтобы решить эту проблему, лучше всего создать тикет в панели управления.|  ### Структура успешного ответа Все конечные точки будут возвращать данные в формате `JSON`. Ответы на `GET`-запросы будут иметь на верхнем уровне следующую структуру атрибутов:  |Название поля|Тип|Описание| |--- |--- |--- | |[entity_name]|object, object[], string[], number[], boolean|Динамическое поле, которое будет меняться в зависимости от запрашиваемого ресурса и будет содержать все атрибуты, необходимые для описания этого ресурса. Например, при запросе списка баз данных будет возвращаться поле `dbs`, а при запросе конкретного облачного сервера `server`. Для некоторых конечных точек в ответе может возвращаться сразу несколько ресурсов.| |meta|object|Опционально. Объект, который содержит вспомогательную информацию о ресурсе. Чаще всего будет встречаться при запросе коллекций и содержать поле `total`, которое будет указывать на количество элементов в коллекции.| |response_id|string|Опционально. В большинстве случаев в ответе будет содержаться ID ответа в формате UUIDv4, который однозначно указывает на ваш запрос внутри нашей системы. Если вам потребуется задать вопрос нашей поддержке, приложите к вопросу этот ID— так мы сможем найти ответ на него намного быстрее. Также вы можете использовать этот ID, чтобы убедиться, что это новый ответ на запрос и результат не был получен из кэша.|  Пример запроса на получение списка SSH-ключей: ```     HTTP/2.0 200 OK     {       \"ssh_keys\":[           {             \"body\":\"ssh-rsa AAAAB3NzaC1sdfghjkOAsBwWhs= example@device.local\",             \"created_at\":\"2021-09-15T19:52:27Z\",             \"expired_at\":null,             \"id\":5297,             \"is_default\":false,             \"name\":\"example@device.local\",             \"used_at\":null,             \"used_by\":[]           }       ],       \"meta\":{           \"total\":1       },       \"response_id\":\"94608d15-8672-4eed-8ab6-28bd6fa3cdf7\"     } ```  ### Структура ответа с ошибкой |Название поля|Тип|Описание| |--- |--- |--- | |status_code|number|Короткий числовой идентификатор ошибки.| |error_code|string|Короткий текстовый идентификатор ошибки, который уточняет числовой идентификатор и удобен для программной обработки. Самый простой пример — это код `not_found` для ошибки 404.| |message|string, string[]|Опционально. В большинстве случаев в ответе будет содержаться человекочитаемое подробное описание ошибки или ошибок, которые помогут понять, что нужно исправить.| |response_id|string|Опционально. В большинстве случае в ответе будет содержаться ID ответа в формате UUIDv4, который однозначно указывает на ваш запрос внутри нашей системы. Если вам потребуется задать вопрос нашей поддержке, приложите к вопросу этот ID — так мы сможем найти ответ на него намного быстрее.|  Пример: ```     HTTP/2.0 403 Forbidden     {       \"status_code\": 403,       \"error_code\":  \"forbidden\",       \"message\":     \"You do not have access for the attempted action\",       \"response_id\": \"94608d15-8672-4eed-8ab6-28bd6fa3cdf7\"     } ```  ## Статусы ресурсов Важно учесть, что при создании большинства ресурсов внутри платформы вам будет сразу возвращен ответ от сервера со статусом `200 OK` или `201 Created` и ID созданного ресурса в теле ответа, но при этом этот ресурс может быть ещё в *состоянии запуска*.  Для того чтобы понять, в каком состоянии сейчас находится ваш ресурс, мы добавили поле `status` в ответ на получение информации о ресурсе.  Список статусов будет отличаться в зависимости от типа ресурса. Увидеть поддерживаемый список статусов вы сможете в описании каждого конкретного ресурса.     ## Ограничение скорости запросов (Rate Limiting) Чтобы обеспечить стабильность для всех пользователей, Timeweb Cloud защищает API от всплесков входящего трафика, анализируя количество запросов c каждого аккаунта к каждой конечной точке.  Если ваше приложение отправляет более 20 запросов в секунду на одну конечную точку, то для этого запроса API может вернуть код состояния HTTP `429 Too Many Requests`.   ## Аутентификация Доступ к API осуществляется с помощью JWT-токена. Токенами можно управлять внутри панели управления Timeweb Cloud в разделе *API и Terraform*.  Токен необходимо передавать в заголовке каждого запроса в формате: ```   Authorization: Bearer $TIMEWEB_CLOUD_TOKEN ```  ## Формат примеров API Примеры в этой документации описаны с помощью `curl`, HTTP-клиента командной строки. На компьютерах `Linux` и `macOS` обычно по умолчанию установлен `curl`, и он доступен для загрузки на всех популярных платформах, включая `Windows`.  Каждый пример разделен на несколько строк символом `\\`, который совместим с `bash`. Типичный пример выглядит так: ```   curl -X PATCH      -H \"Content-Type: application/json\"      -H \"Authorization: Bearer $TIMEWEB_CLOUD_TOKEN\"      -d '{\"name\":\"Cute Corvus\",\"comment\":\"Development Server\"}'      \"https://api.timeweb.cloud/api/v1/dedicated/1051\" ``` - Параметр `-X` задает метод запроса. Для согласованности метод будет указан во всех примерах, даже если он явно не требуется для методов `GET`. - Строки `-H` задают требуемые HTTP-заголовки. - Примеры, для которых требуется объект JSON в теле запроса, передают требуемые данные через параметр `-d`.  Чтобы использовать приведенные примеры, не подставляя каждый раз в них свой токен, вы можете добавить токен один раз в переменные окружения в вашей консоли. Например, на `Linux` это можно сделать с помощью команды:  ``` TIMEWEB_CLOUD_TOKEN=\"token\" ```  После этого токен будет автоматически подставляться в ваши запросы.  Обратите внимание, что все значения в этой документации являются примерами. Не полагайтесь на IDы операционных систем, тарифов и т.д., используемые в примерах. Используйте соответствующую конечную точку для получения значений перед созданием ресурсов.   ## Версионирование API построено согласно принципам [семантического версионирования](https://semver.org/lang/ru). Это значит, что мы гарантируем обратную совместимость всех изменений в пределах одной мажорной версии.  Мажорная версия каждой конечной точки обозначается в пути запроса, например, запрос `/api/v1/servers` указывает, что этот метод имеет версию 1.
5 *
6 * The version of the OpenAPI document: 1.0.0
7 * Contact: info@timeweb.cloud
8 * Generated by: https://openapi-generator.tech
9 */
10
11use reqwest;
12use serde::{Deserialize, Serialize, de::Error as _};
13
14use super::{ContentType, Error, configuration};
15use crate::{apis::ResponseContent, models};
16
17/// struct for typed errors of method [`add_countries_to_allowed_list`]
18#[derive(Debug, Clone, Serialize, Deserialize)]
19#[serde(untagged)]
20pub enum AddCountriesToAllowedListError {
21    Status400(models::GetFinances400Response),
22    Status401(models::GetFinances401Response),
23    Status429(models::GetFinances429Response),
24    Status500(models::GetFinances500Response),
25    UnknownValue(serde_json::Value)
26}
27
28/// struct for typed errors of method [`add_ips_to_allowed_list`]
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(untagged)]
31pub enum AddIpsToAllowedListError {
32    Status400(models::GetFinances400Response),
33    Status401(models::GetFinances401Response),
34    Status429(models::GetFinances429Response),
35    Status500(models::GetFinances500Response),
36    UnknownValue(serde_json::Value)
37}
38
39/// struct for typed errors of method [`delete_countries_from_allowed_list`]
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(untagged)]
42pub enum DeleteCountriesFromAllowedListError {
43    Status400(models::GetFinances400Response),
44    Status401(models::GetFinances401Response),
45    Status429(models::GetFinances429Response),
46    Status500(models::GetFinances500Response),
47    UnknownValue(serde_json::Value)
48}
49
50/// struct for typed errors of method [`delete_ips_from_allowed_list`]
51#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(untagged)]
53pub enum DeleteIpsFromAllowedListError {
54    Status400(models::GetFinances400Response),
55    Status401(models::GetFinances401Response),
56    Status429(models::GetFinances429Response),
57    Status500(models::GetFinances500Response),
58    UnknownValue(serde_json::Value)
59}
60
61/// struct for typed errors of method [`get_account_status`]
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(untagged)]
64pub enum GetAccountStatusError {
65    Status400(models::GetFinances400Response),
66    Status401(models::GetFinances401Response),
67    Status403(models::GetAccountStatus403Response),
68    Status429(models::GetFinances429Response),
69    Status500(models::GetFinances500Response),
70    UnknownValue(serde_json::Value)
71}
72
73/// struct for typed errors of method [`get_auth_access_settings`]
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[serde(untagged)]
76pub enum GetAuthAccessSettingsError {
77    Status400(models::GetFinances400Response),
78    Status401(models::GetFinances401Response),
79    Status429(models::GetFinances429Response),
80    Status500(models::GetFinances500Response),
81    UnknownValue(serde_json::Value)
82}
83
84/// struct for typed errors of method [`get_countries`]
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(untagged)]
87pub enum GetCountriesError {
88    Status400(models::GetFinances400Response),
89    Status401(models::GetFinances401Response),
90    Status429(models::GetFinances429Response),
91    Status500(models::GetFinances500Response),
92    UnknownValue(serde_json::Value)
93}
94
95/// struct for typed errors of method [`get_notification_settings`]
96#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(untagged)]
98pub enum GetNotificationSettingsError {
99    Status400(models::GetFinances400Response),
100    Status401(models::GetFinances401Response),
101    Status403(models::GetAccountStatus403Response),
102    Status429(models::GetFinances429Response),
103    Status500(models::GetFinances500Response),
104    UnknownValue(serde_json::Value)
105}
106
107/// struct for typed errors of method [`update_auth_restrictions_by_countries`]
108#[derive(Debug, Clone, Serialize, Deserialize)]
109#[serde(untagged)]
110pub enum UpdateAuthRestrictionsByCountriesError {
111    Status400(models::GetFinances400Response),
112    Status401(models::GetFinances401Response),
113    Status429(models::GetFinances429Response),
114    Status500(models::GetFinances500Response),
115    UnknownValue(serde_json::Value)
116}
117
118/// struct for typed errors of method [`update_auth_restrictions_by_ip`]
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(untagged)]
121pub enum UpdateAuthRestrictionsByIpError {
122    Status400(models::GetFinances400Response),
123    Status401(models::GetFinances401Response),
124    Status429(models::GetFinances429Response),
125    Status500(models::GetFinances500Response),
126    UnknownValue(serde_json::Value)
127}
128
129/// struct for typed errors of method [`update_notification_settings`]
130#[derive(Debug, Clone, Serialize, Deserialize)]
131#[serde(untagged)]
132pub enum UpdateNotificationSettingsError {
133    Status400(models::GetFinances400Response),
134    Status401(models::GetFinances401Response),
135    Status403(models::GetAccountStatus403Response),
136    Status429(models::GetFinances429Response),
137    Status500(models::GetFinances500Response),
138    UnknownValue(serde_json::Value)
139}
140
141/// Чтобы добавить страны в список разрешенных, отправьте POST-запрос в
142/// `api/v1/access/countries`, передав в теле запроса параметр `countries` со
143/// списком стран.
144pub async fn add_countries_to_allowed_list(
145    configuration: &configuration::Configuration,
146    add_countries_to_allowed_list_request: models::AddCountriesToAllowedListRequest
147) -> Result<models::AddCountriesToAllowedList201Response, Error<AddCountriesToAllowedListError>> {
148    // add a prefix to parameters to efficiently prevent name collisions
149    let p_body_add_countries_to_allowed_list_request = add_countries_to_allowed_list_request;
150
151    let uri_str = format!("{}/api/v1/auth/access/countries", configuration.base_path);
152    let mut req_builder = configuration
153        .client
154        .request(reqwest::Method::POST, &uri_str);
155
156    if let Some(ref user_agent) = configuration.user_agent {
157        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
158    }
159    if let Some(ref token) = configuration.bearer_access_token {
160        req_builder = req_builder.bearer_auth(token.to_owned());
161    };
162    req_builder = req_builder.json(&p_body_add_countries_to_allowed_list_request);
163
164    let req = req_builder.build()?;
165    let resp = configuration.client.execute(req).await?;
166
167    let status = resp.status();
168    let content_type = resp
169        .headers()
170        .get("content-type")
171        .and_then(|v| v.to_str().ok())
172        .unwrap_or("application/octet-stream");
173    let content_type = super::ContentType::from(content_type);
174
175    if !status.is_client_error() && !status.is_server_error() {
176        let content = resp.text().await?;
177        match content_type {
178            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
179            ContentType::Text => {
180                return Err(Error::from(serde_json::Error::custom(
181                    "Received `text/plain` content type response that cannot be converted to `models::AddCountriesToAllowedList201Response`"
182                )));
183            }
184            ContentType::Unsupported(unknown_type) => {
185                return Err(Error::from(serde_json::Error::custom(format!(
186                    "Received `{unknown_type}` content type response that cannot be converted to `models::AddCountriesToAllowedList201Response`"
187                ))));
188            }
189        }
190    } else {
191        let content = resp.text().await?;
192        let entity: Option<AddCountriesToAllowedListError> = serde_json::from_str(&content).ok();
193        Err(Error::ResponseError(ResponseContent {
194            status,
195            content,
196            entity
197        }))
198    }
199}
200
201/// Чтобы добавить IP-адреса в список разрешенных, отправьте POST-запрос в
202/// `api/v1/access/ips`, передав в теле запроса параметр `ips` со списком
203/// IP-адресов.
204pub async fn add_ips_to_allowed_list(
205    configuration: &configuration::Configuration,
206    add_ips_to_allowed_list_request: models::AddIpsToAllowedListRequest
207) -> Result<models::AddIpsToAllowedList201Response, Error<AddIpsToAllowedListError>> {
208    // add a prefix to parameters to efficiently prevent name collisions
209    let p_body_add_ips_to_allowed_list_request = add_ips_to_allowed_list_request;
210
211    let uri_str = format!("{}/api/v1/auth/access/ips", configuration.base_path);
212    let mut req_builder = configuration
213        .client
214        .request(reqwest::Method::POST, &uri_str);
215
216    if let Some(ref user_agent) = configuration.user_agent {
217        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
218    }
219    if let Some(ref token) = configuration.bearer_access_token {
220        req_builder = req_builder.bearer_auth(token.to_owned());
221    };
222    req_builder = req_builder.json(&p_body_add_ips_to_allowed_list_request);
223
224    let req = req_builder.build()?;
225    let resp = configuration.client.execute(req).await?;
226
227    let status = resp.status();
228    let content_type = resp
229        .headers()
230        .get("content-type")
231        .and_then(|v| v.to_str().ok())
232        .unwrap_or("application/octet-stream");
233    let content_type = super::ContentType::from(content_type);
234
235    if !status.is_client_error() && !status.is_server_error() {
236        let content = resp.text().await?;
237        match content_type {
238            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
239            ContentType::Text => {
240                return Err(Error::from(serde_json::Error::custom(
241                    "Received `text/plain` content type response that cannot be converted to `models::AddIpsToAllowedList201Response`"
242                )));
243            }
244            ContentType::Unsupported(unknown_type) => {
245                return Err(Error::from(serde_json::Error::custom(format!(
246                    "Received `{unknown_type}` content type response that cannot be converted to `models::AddIpsToAllowedList201Response`"
247                ))));
248            }
249        }
250    } else {
251        let content = resp.text().await?;
252        let entity: Option<AddIpsToAllowedListError> = serde_json::from_str(&content).ok();
253        Err(Error::ResponseError(ResponseContent {
254            status,
255            content,
256            entity
257        }))
258    }
259}
260
261/// Чтобы удалить страны из списка разрешенных, отправьте DELETE-запрос в
262/// `api/v1/access/countries`, передав в теле запроса параметр `countries` со
263/// списком стран.
264pub async fn delete_countries_from_allowed_list(
265    configuration: &configuration::Configuration,
266    delete_countries_from_allowed_list_request: models::DeleteCountriesFromAllowedListRequest
267) -> Result<
268    models::DeleteCountriesFromAllowedList200Response,
269    Error<DeleteCountriesFromAllowedListError>
270> {
271    // add a prefix to parameters to efficiently prevent name collisions
272    let p_body_delete_countries_from_allowed_list_request =
273        delete_countries_from_allowed_list_request;
274
275    let uri_str = format!("{}/api/v1/auth/access/countries", configuration.base_path);
276    let mut req_builder = configuration
277        .client
278        .request(reqwest::Method::DELETE, &uri_str);
279
280    if let Some(ref user_agent) = configuration.user_agent {
281        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
282    }
283    if let Some(ref token) = configuration.bearer_access_token {
284        req_builder = req_builder.bearer_auth(token.to_owned());
285    };
286    req_builder = req_builder.json(&p_body_delete_countries_from_allowed_list_request);
287
288    let req = req_builder.build()?;
289    let resp = configuration.client.execute(req).await?;
290
291    let status = resp.status();
292    let content_type = resp
293        .headers()
294        .get("content-type")
295        .and_then(|v| v.to_str().ok())
296        .unwrap_or("application/octet-stream");
297    let content_type = super::ContentType::from(content_type);
298
299    if !status.is_client_error() && !status.is_server_error() {
300        let content = resp.text().await?;
301        match content_type {
302            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
303            ContentType::Text => {
304                return Err(Error::from(serde_json::Error::custom(
305                    "Received `text/plain` content type response that cannot be converted to `models::DeleteCountriesFromAllowedList200Response`"
306                )));
307            }
308            ContentType::Unsupported(unknown_type) => {
309                return Err(Error::from(serde_json::Error::custom(format!(
310                    "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteCountriesFromAllowedList200Response`"
311                ))));
312            }
313        }
314    } else {
315        let content = resp.text().await?;
316        let entity: Option<DeleteCountriesFromAllowedListError> =
317            serde_json::from_str(&content).ok();
318        Err(Error::ResponseError(ResponseContent {
319            status,
320            content,
321            entity
322        }))
323    }
324}
325
326/// Чтобы удалить IP-адреса из списка разрешенных, отправьте DELETE-запрос в
327/// `api/v1/access/ips`, передав в теле запроса параметр `ips` со списком
328/// IP-адресов.
329pub async fn delete_ips_from_allowed_list(
330    configuration: &configuration::Configuration,
331    delete_ips_from_allowed_list_request: models::DeleteIpsFromAllowedListRequest
332) -> Result<models::DeleteIpsFromAllowedList200Response, Error<DeleteIpsFromAllowedListError>> {
333    // add a prefix to parameters to efficiently prevent name collisions
334    let p_body_delete_ips_from_allowed_list_request = delete_ips_from_allowed_list_request;
335
336    let uri_str = format!("{}/api/v1/auth/access/ips", configuration.base_path);
337    let mut req_builder = configuration
338        .client
339        .request(reqwest::Method::DELETE, &uri_str);
340
341    if let Some(ref user_agent) = configuration.user_agent {
342        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
343    }
344    if let Some(ref token) = configuration.bearer_access_token {
345        req_builder = req_builder.bearer_auth(token.to_owned());
346    };
347    req_builder = req_builder.json(&p_body_delete_ips_from_allowed_list_request);
348
349    let req = req_builder.build()?;
350    let resp = configuration.client.execute(req).await?;
351
352    let status = resp.status();
353    let content_type = resp
354        .headers()
355        .get("content-type")
356        .and_then(|v| v.to_str().ok())
357        .unwrap_or("application/octet-stream");
358    let content_type = super::ContentType::from(content_type);
359
360    if !status.is_client_error() && !status.is_server_error() {
361        let content = resp.text().await?;
362        match content_type {
363            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
364            ContentType::Text => {
365                return Err(Error::from(serde_json::Error::custom(
366                    "Received `text/plain` content type response that cannot be converted to `models::DeleteIpsFromAllowedList200Response`"
367                )));
368            }
369            ContentType::Unsupported(unknown_type) => {
370                return Err(Error::from(serde_json::Error::custom(format!(
371                    "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteIpsFromAllowedList200Response`"
372                ))));
373            }
374        }
375    } else {
376        let content = resp.text().await?;
377        let entity: Option<DeleteIpsFromAllowedListError> = serde_json::from_str(&content).ok();
378        Err(Error::ResponseError(ResponseContent {
379            status,
380            content,
381            entity
382        }))
383    }
384}
385
386/// Чтобы получить статус аккаунта, отправьте GET-запрос на
387/// `/api/v1/account/status`.
388pub async fn get_account_status(
389    configuration: &configuration::Configuration
390) -> Result<models::GetAccountStatus200Response, Error<GetAccountStatusError>> {
391    let uri_str = format!("{}/api/v1/account/status", configuration.base_path);
392    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
393
394    if let Some(ref user_agent) = configuration.user_agent {
395        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
396    }
397    if let Some(ref token) = configuration.bearer_access_token {
398        req_builder = req_builder.bearer_auth(token.to_owned());
399    };
400
401    let req = req_builder.build()?;
402    let resp = configuration.client.execute(req).await?;
403
404    let status = resp.status();
405    let content_type = resp
406        .headers()
407        .get("content-type")
408        .and_then(|v| v.to_str().ok())
409        .unwrap_or("application/octet-stream");
410    let content_type = super::ContentType::from(content_type);
411
412    if !status.is_client_error() && !status.is_server_error() {
413        let content = resp.text().await?;
414        match content_type {
415            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
416            ContentType::Text => {
417                return Err(Error::from(serde_json::Error::custom(
418                    "Received `text/plain` content type response that cannot be converted to `models::GetAccountStatus200Response`"
419                )));
420            }
421            ContentType::Unsupported(unknown_type) => {
422                return Err(Error::from(serde_json::Error::custom(format!(
423                    "Received `{unknown_type}` content type response that cannot be converted to `models::GetAccountStatus200Response`"
424                ))));
425            }
426        }
427    } else {
428        let content = resp.text().await?;
429        let entity: Option<GetAccountStatusError> = serde_json::from_str(&content).ok();
430        Err(Error::ResponseError(ResponseContent {
431            status,
432            content,
433            entity
434        }))
435    }
436}
437
438/// Чтобы получить информацию о ограничениях авторизации пользователя, отправьте
439/// GET-запрос на `/api/v1/auth/access`.   Тело ответа будет представлять собой
440/// объект JSON с ключами `is_ip_restrictions_enabled`,
441/// `is_country_restrictions_enabled` и `white_list`.
442pub async fn get_auth_access_settings(
443    configuration: &configuration::Configuration
444) -> Result<models::GetAuthAccessSettings200Response, Error<GetAuthAccessSettingsError>> {
445    let uri_str = format!("{}/api/v1/auth/access", configuration.base_path);
446    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
447
448    if let Some(ref user_agent) = configuration.user_agent {
449        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
450    }
451    if let Some(ref token) = configuration.bearer_access_token {
452        req_builder = req_builder.bearer_auth(token.to_owned());
453    };
454
455    let req = req_builder.build()?;
456    let resp = configuration.client.execute(req).await?;
457
458    let status = resp.status();
459    let content_type = resp
460        .headers()
461        .get("content-type")
462        .and_then(|v| v.to_str().ok())
463        .unwrap_or("application/octet-stream");
464    let content_type = super::ContentType::from(content_type);
465
466    if !status.is_client_error() && !status.is_server_error() {
467        let content = resp.text().await?;
468        match content_type {
469            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
470            ContentType::Text => {
471                return Err(Error::from(serde_json::Error::custom(
472                    "Received `text/plain` content type response that cannot be converted to `models::GetAuthAccessSettings200Response`"
473                )));
474            }
475            ContentType::Unsupported(unknown_type) => {
476                return Err(Error::from(serde_json::Error::custom(format!(
477                    "Received `{unknown_type}` content type response that cannot be converted to `models::GetAuthAccessSettings200Response`"
478                ))));
479            }
480        }
481    } else {
482        let content = resp.text().await?;
483        let entity: Option<GetAuthAccessSettingsError> = serde_json::from_str(&content).ok();
484        Err(Error::ResponseError(ResponseContent {
485            status,
486            content,
487            entity
488        }))
489    }
490}
491
492/// Чтобы получить список стран, отправьте GET-запрос на
493/// `/api/v1/auth/access/countries`.   Тело ответа будет представлять собой
494/// объект JSON с ключом `countries`.
495pub async fn get_countries(
496    configuration: &configuration::Configuration
497) -> Result<models::GetCountries200Response, Error<GetCountriesError>> {
498    let uri_str = format!("{}/api/v1/auth/access/countries", configuration.base_path);
499    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
500
501    if let Some(ref user_agent) = configuration.user_agent {
502        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
503    }
504    if let Some(ref token) = configuration.bearer_access_token {
505        req_builder = req_builder.bearer_auth(token.to_owned());
506    };
507
508    let req = req_builder.build()?;
509    let resp = configuration.client.execute(req).await?;
510
511    let status = resp.status();
512    let content_type = resp
513        .headers()
514        .get("content-type")
515        .and_then(|v| v.to_str().ok())
516        .unwrap_or("application/octet-stream");
517    let content_type = super::ContentType::from(content_type);
518
519    if !status.is_client_error() && !status.is_server_error() {
520        let content = resp.text().await?;
521        match content_type {
522            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
523            ContentType::Text => {
524                return Err(Error::from(serde_json::Error::custom(
525                    "Received `text/plain` content type response that cannot be converted to `models::GetCountries200Response`"
526                )));
527            }
528            ContentType::Unsupported(unknown_type) => {
529                return Err(Error::from(serde_json::Error::custom(format!(
530                    "Received `{unknown_type}` content type response that cannot be converted to `models::GetCountries200Response`"
531                ))));
532            }
533        }
534    } else {
535        let content = resp.text().await?;
536        let entity: Option<GetCountriesError> = serde_json::from_str(&content).ok();
537        Err(Error::ResponseError(ResponseContent {
538            status,
539            content,
540            entity
541        }))
542    }
543}
544
545/// Чтобы получить статус аккаунта, отправьте GET запрос на
546/// `/api/v1/account/notification-settings`.
547pub async fn get_notification_settings(
548    configuration: &configuration::Configuration
549) -> Result<models::GetNotificationSettings200Response, Error<GetNotificationSettingsError>> {
550    let uri_str = format!(
551        "{}/api/v1/account/notification-settings",
552        configuration.base_path
553    );
554    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
555
556    if let Some(ref user_agent) = configuration.user_agent {
557        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
558    }
559    if let Some(ref token) = configuration.bearer_access_token {
560        req_builder = req_builder.bearer_auth(token.to_owned());
561    };
562
563    let req = req_builder.build()?;
564    let resp = configuration.client.execute(req).await?;
565
566    let status = resp.status();
567    let content_type = resp
568        .headers()
569        .get("content-type")
570        .and_then(|v| v.to_str().ok())
571        .unwrap_or("application/octet-stream");
572    let content_type = super::ContentType::from(content_type);
573
574    if !status.is_client_error() && !status.is_server_error() {
575        let content = resp.text().await?;
576        match content_type {
577            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
578            ContentType::Text => {
579                return Err(Error::from(serde_json::Error::custom(
580                    "Received `text/plain` content type response that cannot be converted to `models::GetNotificationSettings200Response`"
581                )));
582            }
583            ContentType::Unsupported(unknown_type) => {
584                return Err(Error::from(serde_json::Error::custom(format!(
585                    "Received `{unknown_type}` content type response that cannot be converted to `models::GetNotificationSettings200Response`"
586                ))));
587            }
588        }
589    } else {
590        let content = resp.text().await?;
591        let entity: Option<GetNotificationSettingsError> = serde_json::from_str(&content).ok();
592        Err(Error::ResponseError(ResponseContent {
593            status,
594            content,
595            entity
596        }))
597    }
598}
599
600/// Чтобы включить/отключить ограничения по стране, отправьте POST-запрос в
601/// `api/v1/access/countries/enabled`, передав в теле запроса параметр
602/// `is_enabled`
603pub async fn update_auth_restrictions_by_countries(
604    configuration: &configuration::Configuration,
605    update_auth_restrictions_by_countries_request: models::UpdateAuthRestrictionsByCountriesRequest
606) -> Result<(), Error<UpdateAuthRestrictionsByCountriesError>> {
607    // add a prefix to parameters to efficiently prevent name collisions
608    let p_body_update_auth_restrictions_by_countries_request =
609        update_auth_restrictions_by_countries_request;
610
611    let uri_str = format!(
612        "{}/api/v1/auth/access/countries/enabled",
613        configuration.base_path
614    );
615    let mut req_builder = configuration
616        .client
617        .request(reqwest::Method::POST, &uri_str);
618
619    if let Some(ref user_agent) = configuration.user_agent {
620        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
621    }
622    if let Some(ref token) = configuration.bearer_access_token {
623        req_builder = req_builder.bearer_auth(token.to_owned());
624    };
625    req_builder = req_builder.json(&p_body_update_auth_restrictions_by_countries_request);
626
627    let req = req_builder.build()?;
628    let resp = configuration.client.execute(req).await?;
629
630    let status = resp.status();
631
632    if !status.is_client_error() && !status.is_server_error() {
633        Ok(())
634    } else {
635        let content = resp.text().await?;
636        let entity: Option<UpdateAuthRestrictionsByCountriesError> =
637            serde_json::from_str(&content).ok();
638        Err(Error::ResponseError(ResponseContent {
639            status,
640            content,
641            entity
642        }))
643    }
644}
645
646/// Чтобы включить/отключить ограничения по IP-адресу, отправьте POST-запрос в
647/// `api/v1/access/ips/enabled`, передав в теле запроса параметр `is_enabled`
648pub async fn update_auth_restrictions_by_ip(
649    configuration: &configuration::Configuration,
650    update_auth_restrictions_by_countries_request: models::UpdateAuthRestrictionsByCountriesRequest
651) -> Result<(), Error<UpdateAuthRestrictionsByIpError>> {
652    // add a prefix to parameters to efficiently prevent name collisions
653    let p_body_update_auth_restrictions_by_countries_request =
654        update_auth_restrictions_by_countries_request;
655
656    let uri_str = format!("{}/api/v1/auth/access/ips/enabled", configuration.base_path);
657    let mut req_builder = configuration
658        .client
659        .request(reqwest::Method::POST, &uri_str);
660
661    if let Some(ref user_agent) = configuration.user_agent {
662        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
663    }
664    if let Some(ref token) = configuration.bearer_access_token {
665        req_builder = req_builder.bearer_auth(token.to_owned());
666    };
667    req_builder = req_builder.json(&p_body_update_auth_restrictions_by_countries_request);
668
669    let req = req_builder.build()?;
670    let resp = configuration.client.execute(req).await?;
671
672    let status = resp.status();
673
674    if !status.is_client_error() && !status.is_server_error() {
675        Ok(())
676    } else {
677        let content = resp.text().await?;
678        let entity: Option<UpdateAuthRestrictionsByIpError> = serde_json::from_str(&content).ok();
679        Err(Error::ResponseError(ResponseContent {
680            status,
681            content,
682            entity
683        }))
684    }
685}
686
687/// Чтобы изменить настройки уведомлений аккаунта, отправьте PATCH запрос на
688/// `/api/v1/account/notification-settings`.
689pub async fn update_notification_settings(
690    configuration: &configuration::Configuration,
691    update_notification_settings_request: models::UpdateNotificationSettingsRequest
692) -> Result<models::GetNotificationSettings200Response, Error<UpdateNotificationSettingsError>> {
693    // add a prefix to parameters to efficiently prevent name collisions
694    let p_body_update_notification_settings_request = update_notification_settings_request;
695
696    let uri_str = format!(
697        "{}/api/v1/account/notification-settings",
698        configuration.base_path
699    );
700    let mut req_builder = configuration
701        .client
702        .request(reqwest::Method::PATCH, &uri_str);
703
704    if let Some(ref user_agent) = configuration.user_agent {
705        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
706    }
707    if let Some(ref token) = configuration.bearer_access_token {
708        req_builder = req_builder.bearer_auth(token.to_owned());
709    };
710    req_builder = req_builder.json(&p_body_update_notification_settings_request);
711
712    let req = req_builder.build()?;
713    let resp = configuration.client.execute(req).await?;
714
715    let status = resp.status();
716    let content_type = resp
717        .headers()
718        .get("content-type")
719        .and_then(|v| v.to_str().ok())
720        .unwrap_or("application/octet-stream");
721    let content_type = super::ContentType::from(content_type);
722
723    if !status.is_client_error() && !status.is_server_error() {
724        let content = resp.text().await?;
725        match content_type {
726            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
727            ContentType::Text => {
728                return Err(Error::from(serde_json::Error::custom(
729                    "Received `text/plain` content type response that cannot be converted to `models::GetNotificationSettings200Response`"
730                )));
731            }
732            ContentType::Unsupported(unknown_type) => {
733                return Err(Error::from(serde_json::Error::custom(format!(
734                    "Received `{unknown_type}` content type response that cannot be converted to `models::GetNotificationSettings200Response`"
735                ))));
736            }
737        }
738    } else {
739        let content = resp.text().await?;
740        let entity: Option<UpdateNotificationSettingsError> = serde_json::from_str(&content).ok();
741        Err(Error::ResponseError(ResponseContent {
742            status,
743            content,
744            entity
745        }))
746    }
747}