1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use log::error;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub enum Error {
ParseError(serde_json::Error),
IOError(std::io::Error),
RequestError(reqwest::Error),
TelegramError(TelegramError),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Response<A> {
Ok { ok: bool, result: A },
Error { ok: bool, error_code: u32, description: String },
}
#[derive(Serialize, Deserialize, Debug)]
pub struct TelegramError {
ok: bool,
error_code: u32,
description: String,
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Error::ParseError(e)
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Error::RequestError(e)
}
}
impl From<TelegramError> for Error {
fn from(e: TelegramError) -> Self {
Error::TelegramError(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IOError(e)
}
}
pub(crate) fn parse_api_result<A: DeserializeOwned>(text: String) -> Result<A, Error> {
#[derive(Deserialize)]
struct O<B> {
ok: bool,
result: B,
}
match serde_json::from_str::<Response<A>>(text.as_str()).map_err(|e| {
error!("Could not parse telegram response. Please report this issue on https://www.github.com/Thechi2000/telegram-api-rust\nServer response: {}", text);
Error::ParseError(e)
})? {
Response::Ok { ok: _, result } => Ok(result),
Response::Error { ok, error_code, description } => Err(Error::TelegramError(TelegramError { ok, error_code, description })),
}
}