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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use super::TransformEntry;
use crate::{
action::transform::{
error::RawContentsNotSetError,
field::Replace,
result::{TransformResult as TrRes, TransformedEntry, TransformedMessage},
},
entry::Entry,
error::InvalidUrlError,
sink::message::Media,
utils::OptionExt,
};
use async_trait::async_trait;
use either::Either;
use serde_json::Value;
use std::{borrow::Cow, ops::ControlFlow};
use url::Url;
#[derive(Debug)]
pub struct Json {
pub item: Option<Query>,
pub title: Option<StringQuery>,
pub text: Option<Vec<StringQuery>>, pub id: Option<StringQuery>,
pub link: Option<StringQuery>,
pub img: Option<Vec<StringQuery>>, }
#[derive(Clone, Debug)]
pub enum Key {
String(String),
Usize(usize),
}
pub type Keys = Vec<Key>;
#[derive(Debug)]
pub struct StringQuery {
pub query: Query,
pub regex: Option<Replace>,
}
#[derive(Debug)]
pub struct Query {
pub keys: Keys,
pub optional: bool,
}
#[allow(missing_docs)] #[derive(thiserror::Error, Debug)]
pub enum JsonError {
#[error(transparent)]
RawContentsNotSet(#[from] RawContentsNotSetError),
#[error("Invalid JSON")]
Invalid(#[from] serde_json::error::Error),
#[error("JSON key #{num} not found. From query list: {key_list:?}")]
KeyNotFound { num: usize, key_list: Keys },
#[error("JSON key {key:?} wrong type: expected {expected_type}, found {found_type}")]
KeyWrongType {
key: Keys,
expected_type: &'static str,
found_type: String,
},
#[error(transparent)]
InvalidUrl(#[from] InvalidUrlError),
}
#[async_trait]
impl TransformEntry for Json {
type Err = JsonError;
async fn transform_entry(&self, entry: Entry) -> Result<Vec<TransformedEntry>, Self::Err> {
let json: Value =
serde_json::from_str(entry.raw_contents.as_ref().ok_or(RawContentsNotSetError)?)?;
let items = match self.item.as_ref() {
Some(query) => match extract_data(&json, query)? {
Some(items) => items,
None => return Ok(Vec::new()),
},
None => &json,
};
let items = if let Some(items) = items.as_array() {
Either::Left(items.iter())
} else if let Some(items) = items.as_object() {
Either::Right(items.iter().map(|(_, v)| v))
} else {
return Err(JsonError::KeyWrongType {
key: self.item.as_ref().map_or_else(Vec::new, |v| v.keys.clone()),
expected_type: "iterator (array, map)",
found_type: format!("{items:?}"),
});
};
items
.into_iter()
.map(|item| self.extract_entry(item))
.collect::<Result<Vec<_>, _>>()
}
}
impl Json {
fn extract_entry(&self, item: &Value) -> Result<TransformedEntry, JsonError> {
let title = self
.title
.as_ref()
.try_and_then(|q| extract_string(item, q))?;
let body = self.text.as_ref().try_and_then(|v| extract_body(item, v))?;
let id = self.id.as_ref().try_and_then(|q| extract_id(item, q))?;
let link = self.link.as_ref().try_and_then(|q| extract_url(item, q))?;
let img = self.img.as_ref().try_map(|v| {
v.iter()
.filter_map(|q| extract_url(item, q).transpose())
.collect::<Result<Vec<_>, _>>()
})?;
Ok(TransformedEntry {
id: TrRes::Old(id.map(Into::into)),
raw_contents: TrRes::Old(body.clone()),
msg: TransformedMessage {
title: TrRes::Old(title),
body: TrRes::Old(body),
link: TrRes::Old(link),
media: TrRes::Old(img.map(|v| v.into_iter().map(Media::Photo).collect())),
},
..Default::default()
})
}
}
fn extract_data<'a>(json: &'a Value, query: &Query) -> Result<Option<&'a Value>, JsonError> {
let data = query.keys.iter().enumerate().try_fold(json, |val, (i, q)| {
let res_val = match q {
Key::String(s) => val.get(s),
Key::Usize(u) => val.get(u),
};
match res_val {
Some(v) => ControlFlow::Continue(v),
None => ControlFlow::Break(i),
}
});
let data = match data {
ControlFlow::Continue(v) => v,
ControlFlow::Break(_) if query.optional => return Ok(None),
ControlFlow::Break(key) => {
return Err(JsonError::KeyNotFound {
num: key,
key_list: query.keys.clone(),
})
}
};
Ok(Some(data))
}
fn extract_string(item: &Value, str_query: &StringQuery) -> Result<Option<String>, JsonError> {
let data = match extract_data(item, &str_query.query) {
Ok(Some(v)) => v,
Ok(None) => return Ok(None),
Err(e) => return Err(e),
};
let s = data.as_str().ok_or_else(|| JsonError::KeyWrongType {
key: str_query.query.keys.clone(),
expected_type: "string",
found_type: format!("{data:?}"),
})?;
let s = match str_query.regex.as_ref() {
Some(r) => r.replace(s),
None => Cow::Borrowed(s),
};
Ok(Some(s.trim().to_owned()))
}
fn extract_body(item: &Value, bodyq: &[StringQuery]) -> Result<Option<String>, JsonError> {
let body = bodyq
.iter()
.filter_map(|query| extract_string(item, query).transpose())
.collect::<Result<Vec<String>, JsonError>>()?
.join("\n\n");
if body.is_empty() {
Ok(None)
} else {
Ok(Some(body))
}
}
fn extract_id(item: &Value, query: &StringQuery) -> Result<Option<String>, JsonError> {
let id_val = match extract_data(item, &query.query) {
Ok(Some(v)) => v,
Ok(None) => return Ok(None),
Err(e) => return Err(e),
};
let id = if let Some(id) = id_val.as_str() {
id.to_owned()
} else if let Some(id) = id_val.as_i64() {
id.to_string()
} else if let Some(id) = id_val.as_u64() {
id.to_string()
} else {
return Err(JsonError::KeyWrongType {
key: query.query.keys.clone(),
expected_type: "string/i64/u64",
found_type: format!("{id_val:?}"),
});
};
let id = match query.regex.as_ref() {
Some(r) => r.replace(&id).into_owned(),
None => id,
};
Ok(Some(id))
}
fn extract_url(item: &Value, query: &StringQuery) -> Result<Option<Url>, JsonError> {
let url_str = match extract_string(item, query) {
Ok(Some(v)) => v,
Ok(None) => return Ok(None),
Err(e) => return Err(e),
};
let url = Url::try_from(url_str.as_str()).map_err(|e| InvalidUrlError(e, url_str))?;
Ok(Some(url))
}