-
Notifications
You must be signed in to change notification settings - Fork 0
/
spar.rs
314 lines (261 loc) · 9.1 KB
/
spar.rs
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use reqwest::Client;
use serde_json::Value;
use sqlx::types::Uuid;
use sqlx::PgPool;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
use super::ExecuteCrawler;
#[derive(Debug, Clone, Copy, EnumIter, PartialEq, Eq, Hash)]
pub enum Category {
Vegan,
Vegetables,
RefrigeratedGoods,
Meats,
Pantry,
Sweets,
Bread,
Drinks,
FrozenGoods,
Baby,
Pet,
Beauty,
Household,
KitchenUtensils,
}
impl Category {
fn id(&self) -> &'static str {
match self {
Category::Vegan => "F17",
Category::Vegetables => "F1",
Category::RefrigeratedGoods => "F2",
Category::Meats => "F3",
Category::Pantry => "F4",
Category::Sweets => "F5",
Category::Bread => "F6",
Category::Drinks => "F7",
Category::FrozenGoods => "F8",
Category::Baby => "F9",
Category::Pet => "F10",
Category::Beauty => "F11",
Category::Household => "F12",
Category::KitchenUtensils => "F13",
}
}
}
#[derive(Debug)]
pub struct SparUrl {
category: Category,
page: usize,
page_size: usize,
}
impl SparUrl {
pub fn new(category: Category, page: usize) -> Self {
SparUrl {
category,
page,
page_size: 80,
}
}
pub fn as_url(&self) -> String {
format!("https://search-spar.spar-ics.com/fact-finder/rest/v4/search/products_lmos_at?query=*&q=*&page={}&hitsPerPage={}&filter=category-path:{}", self.page, self.page_size, self.category.id())
}
pub fn next_page(&mut self) {
self.page += 1;
}
}
#[derive(Debug, serde::Deserialize)]
pub struct Product {
description: String,
#[serde(rename = "sales-unit")]
sales_unit: String,
pub title: String,
#[serde(rename = "code-internal")]
pub id_internal: String,
price: f32,
brand: Vec<String>,
url: String,
pub name: String,
#[serde(rename = "product-number")]
pub product_number: String,
#[serde(rename = "price-per-unit")]
price_per_unit: String,
}
#[derive(Debug, serde::Deserialize)]
struct Page {
#[serde(rename = "currentPage")]
current: usize,
#[serde(rename = "pageCount")]
count: usize,
}
#[derive(Debug)]
pub struct SparCrawl {}
impl SparCrawl {
pub async fn get_or_add_categories(pool: &PgPool) -> Result<Arc<HashMap<Category, Uuid>>> {
let mut category_map = HashMap::new();
for category in Category::iter() {
let category_string = format!("{:?}", category);
let id: Option<(Uuid,)> =
sqlx::query_as("select sc_id from sc_spar_category where sc_text = $1")
.bind(&category_string)
.fetch_optional(pool)
.await?;
let id = match id {
Some(id) => id.0,
None => {
let id: (Uuid,) = sqlx::query_as(
"insert into sc_spar_category (sc_text) values ( $1 ) returning sc_id",
)
.bind(&category_string)
.fetch_one(pool)
.await
.unwrap();
id.0
}
};
category_map.insert(category, id);
}
Ok(Arc::new(category_map))
}
pub async fn download_category(
crawl_id: Uuid,
client: Client,
pool: &PgPool,
category: Category,
) -> Result<Vec<(Product, Uuid)>> {
let mut spar_url = SparUrl::new(category.clone(), 1);
let mut products = Vec::new();
loop {
let url = spar_url.as_url();
let res = client.get(&url).send().await?;
if res.status() == 200 {
let text = res.text().await?;
let body: Value = serde_json::from_str(&text)?;
let document_id: (Uuid,) = sqlx::query_as("insert into sr_spar_raw (sr_raw, sr_url, sr_cs_crawl_session) values ( $1, $2, $3 ) returning sr_id")
.bind(text)
.bind(url)
.bind(crawl_id)
.fetch_one(pool).await?;
let hits_raw = body["hits"].clone();
let arr = hits_raw
.as_array()
.map(|items| {
items
.iter()
.map(|item| serde_json::from_value(item["masterValues"].clone()))
.map(|item| item.ok())
.filter(|item| item.is_some())
.map(|item| (item.unwrap(), document_id.0))
.collect::<Vec<_>>()
})
.unwrap_or_default();
products.extend(arr);
let paging_info: Page = serde_json::from_value(body["paging"].clone())?;
if paging_info.current >= paging_info.count {
break;
}
spar_url.next_page();
}
}
Ok(products)
}
pub async fn insert_products(
pool: &PgPool,
category_map: Arc<HashMap<Category, Uuid>>,
category: Category,
products: Vec<(Product, Uuid)>,
) -> Result<()> {
for (product, document_id) in products {
let product_id: Option<(Uuid,)> =
sqlx::query_as("select sp_id from sp_spar_product where sp_spar_id = $1")
.bind(&product.id_internal)
.fetch_optional(pool)
.await?;
let product_id = match product_id {
Some(product_id) => product_id.0,
None => {
let brand_name = product.brand.join(";");
let product_id: (Uuid,) = sqlx::query_as("insert into sp_spar_product (sp_spar_id, sp_description, sp_online_shop_url, sp_name, sp_brand, sp_sc_category) values ( $1, $2, $3, $4, $5, $6 ) returning sp_id")
.bind(product.id_internal)
.bind(product.description)
.bind(product.url)
.bind(product.name)
.bind(brand_name)
.bind(category_map.get(&category).unwrap().clone())
.fetch_one(pool)
.await?;
product_id.0
}
};
sqlx::query("insert into spr_spar_price (spr_price, spr_sales_unit, spr_price_unit, spr_sp_product, spr_sr_raw) values ( $1, $2, $3, $4, $5 )")
.bind(product.price)
.bind(product.sales_unit)
.bind(product.price_per_unit)
.bind(product_id)
.bind(document_id)
.execute(pool)
.await?;
}
Ok(())
}
}
impl ExecuteCrawler for SparCrawl {
async fn execute(pool: &PgPool, crawl_id: Uuid) -> Result<()> {
let client = Client::new();
let category_map = SparCrawl::get_or_add_categories(&pool).await?;
let semaphore = Arc::new(Semaphore::new(3));
let mut set = JoinSet::new();
for category in Category::iter() {
let semaphore = semaphore.clone();
let client = client.clone();
let pool = pool.clone();
let crawl_id = crawl_id.clone();
set.spawn(async move {
let permit = semaphore.acquire().await.unwrap();
println!("start: {:?}", category);
let products =
SparCrawl::download_category(crawl_id, client, &pool, category).await;
drop(permit);
println!("finish: {:?}", category);
(products, category)
});
}
let mut products_lists = Vec::new();
while let Some(res) = set.join_next().await {
match res {
Ok((Ok(products), category)) => products_lists.push((category, products)),
err => println!("err: {:?}", err),
}
}
println!(
"products: {}",
products_lists
.iter()
.map(|(_, item)| item.len())
.sum::<usize>()
);
println!("Start with inserting into db");
let semaphore = Arc::new(Semaphore::new(20));
let mut set = JoinSet::new();
for (category, products) in products_lists {
let semaphore = semaphore.clone();
let pool = pool.clone();
let category_map = category_map.clone();
set.spawn(async move {
let permit = semaphore.acquire().await.unwrap();
let status =
SparCrawl::insert_products(&pool, category_map, category, products).await;
drop(permit);
status
});
}
while let Some(res) = set.join_next().await {
let _ = res;
}
Ok(())
}
}