1
use std::error::Error as StdError;
2

            
3
use axum::{
4
    body::{Body, Bytes},
5
    extract::State,
6
    http::header,
7
    response::IntoResponse,
8
    Extension,
9
};
10
use chrono::{TimeZone, Utc};
11
use csv::WriterBuilder;
12
use log::error;
13
use serde_json;
14

            
15
use sylvia_iot_corelib::{
16
    constants::ContentType,
17
    err::ErrResp,
18
    http::{Json, Query},
19
    strings,
20
};
21

            
22
use super::{
23
    super::{
24
        super::{middleware::GetTokenInfoData, State as AppState},
25
        get_unit_cond,
26
    },
27
    request, response,
28
};
29
use crate::models::network_dldata::{ListOptions, ListQueryCond, NetworkDlData, SortCond, SortKey};
30

            
31
const LIST_LIMIT_DEFAULT: u64 = 100;
32
const LIST_CURSOR_MAX: u64 = 100;
33
const CSV_FIELDS: &'static str =
34
    "dataId,proc,pub,resp,status,unitId,deviceId,networkCode,networkAddr,profile,data,extension\n";
35

            
36
/// `GET /{base}/api/v1/network-dldata/count`
37
216
pub async fn get_count(
38
216
    State(state): State<AppState>,
39
216
    Extension(token_info): Extension<GetTokenInfoData>,
40
216
    Query(mut query): Query<request::GetCountQuery>,
41
216
) -> impl IntoResponse {
42
    const FN_NAME: &'static str = "get_count";
43

            
44
216
    if let Some(network) = query.network {
45
12
        query.network = Some(network.to_lowercase());
46
204
    }
47
216
    if let Some(addr) = query.addr {
48
8
        query.addr = Some(addr.to_lowercase());
49
208
    }
50

            
51
216
    let unit_cond = get_unit_cond(FN_NAME, &token_info, query.unit.as_ref(), &state).await?;
52
200
    let cond = match get_list_cond(&query, &unit_cond).await {
53
60
        Err(e) => return Err(e.into_response()),
54
140
        Ok(cond) => cond,
55
140
    };
56
140
    match state.model.network_dldata().count(&cond).await {
57
        Err(e) => {
58
            error!("[{}] count error: {}", FN_NAME, e);
59
            Err(ErrResp::ErrDb(Some(e.to_string())).into_response())
60
        }
61
140
        Ok(count) => Ok(Json(response::GetCount {
62
140
            data: response::GetCountData { count },
63
140
        })),
64
    }
65
216
}
66

            
67
/// `GET /{base}/api/v1/network-dldata/list`
68
324
pub async fn get_list(
69
324
    State(state): State<AppState>,
70
324
    Extension(token_info): Extension<GetTokenInfoData>,
71
324
    Query(query): Query<request::GetListQuery>,
72
324
) -> impl IntoResponse {
73
    const FN_NAME: &'static str = "get_list";
74

            
75
324
    let cond_query = request::GetCountQuery {
76
324
        unit: query.unit.clone(),
77
324
        device: query.device.clone(),
78
324
        network: match query.network.as_ref() {
79
312
            None => None,
80
12
            Some(network) => Some(network.to_lowercase()),
81
        },
82
324
        addr: match query.addr.as_ref() {
83
316
            None => None,
84
8
            Some(addr) => Some(addr.to_lowercase()),
85
        },
86
324
        profile: query.profile.clone(),
87
324
        tfield: query.tfield.clone(),
88
324
        tstart: query.tstart,
89
324
        tend: query.tend,
90
    };
91
324
    let unit_cond = match get_unit_cond(FN_NAME, &token_info, query.unit.as_ref(), &state).await {
92
16
        Err(e) => return Ok(e),
93
308
        Ok(cond) => cond,
94
    };
95
308
    let cond = match get_list_cond(&cond_query, &unit_cond).await {
96
60
        Err(e) => return Err(e),
97
248
        Ok(cond) => cond,
98
    };
99
248
    let sort_cond = match get_sort_cond(&query.sort) {
100
20
        Err(e) => return Err(e),
101
228
        Ok(cond) => cond,
102
    };
103
228
    let opts = ListOptions {
104
228
        cond: &cond,
105
228
        offset: query.offset,
106
228
        limit: match query.limit {
107
192
            None => Some(LIST_LIMIT_DEFAULT),
108
36
            Some(limit) => Some(limit),
109
        },
110
228
        sort: Some(sort_cond.as_slice()),
111
228
        cursor_max: Some(LIST_CURSOR_MAX),
112
    };
113

            
114
228
    let (list, cursor) = match state.model.network_dldata().list(&opts, None).await {
115
        Err(e) => {
116
            error!("[{}] list error: {}", FN_NAME, e);
117
            return Err(ErrResp::ErrDb(Some(e.to_string())));
118
        }
119
228
        Ok((list, cursor)) => match cursor {
120
200
            None => match query.format.as_ref() {
121
                Some(request::ListFormat::Array) => {
122
4
                    return Ok(Json(list_transform(&list)).into_response())
123
                }
124
                Some(request::ListFormat::Csv) => {
125
4
                    let bytes = match list_transform_bytes(&list, true, true, query.format.as_ref())
126
                    {
127
                        Err(e) => {
128
                            let e = format!("transform CSV error: {}", e);
129
                            return Err(ErrResp::ErrUnknown(Some(e)));
130
                        }
131
4
                        Ok(bytes) => bytes,
132
4
                    };
133
4
                    return Ok((
134
4
                        [
135
4
                            (header::CONTENT_TYPE, ContentType::CSV),
136
4
                            (
137
4
                                header::CONTENT_DISPOSITION,
138
4
                                "attachment;filename=network-dldata.csv",
139
4
                            ),
140
4
                        ],
141
4
                        bytes,
142
4
                    )
143
4
                        .into_response());
144
                }
145
                _ => {
146
192
                    return Ok(Json(response::GetList {
147
192
                        data: list_transform(&list),
148
192
                    })
149
192
                    .into_response())
150
                }
151
            },
152
28
            Some(_) => (list, cursor),
153
28
        },
154
28
    };
155
28

            
156
28
    let query_format = query.format.clone();
157
28
    let body = Body::from_stream(async_stream::stream! {
158
28
        let query = query.clone();
159
28
        let cond_query = request::GetCountQuery {
160
28
            unit: query.unit.clone(),
161
28
            device: query.device.clone(),
162
28
            network: query.network.clone(),
163
28
            addr: query.addr.clone(),
164
28
            profile: query.profile.clone(),
165
28
            tfield: query.tfield.clone(),
166
28
            tstart: query.tstart,
167
28
            tend: query.tend,
168
28
        };
169
28
        let cond = match get_list_cond(&cond_query, &unit_cond).await {
170
28
            Err(_) => return,
171
28
            Ok(cond) => cond,
172
28
        };
173
28
        let opts = ListOptions {
174
28
            cond: &cond,
175
28
            offset: query.offset,
176
28
            limit: match query.limit {
177
28
                None => Some(LIST_LIMIT_DEFAULT),
178
28
                Some(limit) => Some(limit),
179
28
            },
180
28
            sort: Some(sort_cond.as_slice()),
181
28
            cursor_max: Some(LIST_CURSOR_MAX),
182
28
        };
183
28

            
184
28
        let mut list = list;
185
28
        let mut cursor = cursor;
186
28
        let mut is_first = true;
187
28
        loop {
188
28
            yield list_transform_bytes(&list, is_first, cursor.is_none(), query.format.as_ref());
189
28
            is_first = false;
190
28
            if cursor.is_none() {
191
28
                break;
192
28
            }
193
28
            let (_list, _cursor) = match state.model.network_dldata().list(&opts, cursor).await {
194
28
                Err(_) => break,
195
28
                Ok((list, cursor)) => (list, cursor),
196
28
            };
197
28
            list = _list;
198
28
            cursor = _cursor;
199
28
        }
200
28
    });
201
8
    match query_format {
202
4
        Some(request::ListFormat::Csv) => Ok((
203
4
            [
204
4
                (header::CONTENT_TYPE, ContentType::CSV),
205
4
                (
206
4
                    header::CONTENT_DISPOSITION,
207
4
                    "attachment;filename=network-dldata.csv",
208
4
                ),
209
4
            ],
210
4
            body,
211
4
        )
212
4
            .into_response()),
213
24
        _ => Ok(([(header::CONTENT_TYPE, ContentType::JSON)], body).into_response()),
214
    }
215
324
}
216

            
217
536
async fn get_list_cond<'a>(
218
536
    query: &'a request::GetCountQuery,
219
536
    unit_cond: &'a Option<String>,
220
536
) -> Result<ListQueryCond<'a>, ErrResp> {
221
536
    let mut cond = ListQueryCond {
222
536
        unit_id: match unit_cond.as_ref() {
223
200
            None => None,
224
336
            Some(unit_id) => Some(unit_id.as_str()),
225
        },
226
536
        ..Default::default()
227
    };
228
536
    if let Some(device_id) = query.device.as_ref() {
229
40
        if device_id.len() > 0 {
230
40
            cond.device_id = Some(device_id.as_str());
231
40
        }
232
496
    }
233
536
    if let Some(network_code) = query.network.as_ref() {
234
24
        if network_code.len() > 0 {
235
24
            cond.network_code = Some(network_code.as_str());
236
24
        }
237
512
    }
238
536
    if let Some(network_addr) = query.addr.as_ref() {
239
16
        if network_addr.len() > 0 {
240
16
            cond.network_addr = Some(network_addr.as_str());
241
16
        }
242
520
    }
243
536
    if let Some(profile) = query.profile.as_ref() {
244
16
        if profile.len() > 0 {
245
16
            cond.profile = Some(profile.as_str());
246
16
        }
247
520
    }
248
536
    if let Some(start) = query.tstart.as_ref() {
249
288
        match query.tfield.as_ref() {
250
48
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
251
240
            Some(tfield) => match tfield.as_str() {
252
240
                "proc" => cond.proc_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
253
120
                "pub" => cond.pub_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
254
72
                "resp" => cond.resp_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
255
24
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
256
            },
257
        }
258
248
    }
259
464
    if let Some(end) = query.tend.as_ref() {
260
120
        match query.tfield.as_ref() {
261
24
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
262
96
            Some(tfield) => match tfield.as_str() {
263
96
                "proc" => cond.proc_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
264
72
                "pub" => cond.pub_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
265
48
                "resp" => cond.resp_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
266
24
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
267
            },
268
        }
269
344
    }
270

            
271
416
    Ok(cond)
272
536
}
273

            
274
248
fn get_sort_cond(sort_args: &Option<String>) -> Result<Vec<SortCond>, ErrResp> {
275
248
    match sort_args.as_ref() {
276
144
        None => Ok(vec![SortCond {
277
144
            key: SortKey::Proc,
278
144
            asc: false,
279
144
        }]),
280
104
        Some(args) => {
281
104
            let mut args = args.split(",");
282
104
            let mut sort_cond = vec![];
283
224
            while let Some(arg) = args.next() {
284
140
                let mut cond = arg.split(":");
285
140
                let key = match cond.next() {
286
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
287
140
                    Some(field) => match field {
288
140
                        "proc" => SortKey::Proc,
289
60
                        "pub" => SortKey::Pub,
290
52
                        "resp" => SortKey::Resp,
291
40
                        "network" => SortKey::NetworkCode,
292
24
                        "addr" => SortKey::NetworkAddr,
293
                        _ => {
294
8
                            return Err(ErrResp::ErrParam(Some(format!(
295
8
                                "invalid sort key {}",
296
8
                                field
297
8
                            ))))
298
                        }
299
                    },
300
                };
301
132
                let asc = match cond.next() {
302
4
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
303
128
                    Some(asc) => match asc {
304
128
                        "asc" => true,
305
32
                        "desc" => false,
306
                        _ => {
307
4
                            return Err(ErrResp::ErrParam(Some(format!(
308
4
                                "invalid sort asc {}",
309
4
                                asc
310
4
                            ))))
311
                        }
312
                    },
313
                };
314
124
                if cond.next().is_some() {
315
4
                    return Err(ErrResp::ErrParam(Some(
316
4
                        "invalid sort condition".to_string(),
317
4
                    )));
318
120
                }
319
120
                sort_cond.push(SortCond { key, asc });
320
            }
321
84
            Ok(sort_cond)
322
        }
323
    }
324
248
}
325

            
326
196
fn list_transform(list: &Vec<NetworkDlData>) -> Vec<response::GetListData> {
327
196
    let mut ret = vec![];
328
612
    for item in list.iter() {
329
612
        ret.push(data_transform(&item));
330
612
    }
331
196
    ret
332
196
}
333

            
334
64
fn list_transform_bytes(
335
64
    list: &Vec<NetworkDlData>,
336
64
    with_start: bool,
337
64
    with_end: bool,
338
64
    format: Option<&request::ListFormat>,
339
64
) -> Result<Bytes, Box<dyn StdError + Send + Sync>> {
340
64
    let mut build_str = match with_start {
341
32
        false => "".to_string(),
342
12
        true => match format {
343
4
            Some(request::ListFormat::Array) => "[".to_string(),
344
            Some(request::ListFormat::Csv) => {
345
8
                let bom = String::from_utf8(vec![0xEF, 0xBB, 0xBF])?;
346
8
                format!("{}{}", bom, CSV_FIELDS)
347
            }
348
20
            _ => "{\"data\":[".to_string(),
349
        },
350
    };
351
64
    let mut is_first = with_start;
352

            
353
3740
    for item in list {
354
860
        match format {
355
            Some(request::ListFormat::Csv) => {
356
440
                let mut writer = WriterBuilder::new().has_headers(false).from_writer(vec![]);
357
440
                writer.serialize(data_transform_csv(item))?;
358
440
                build_str += String::from_utf8(writer.into_inner()?)?.as_str();
359
            }
360
            _ => {
361
3236
                if is_first {
362
24
                    is_first = false;
363
3212
                } else {
364
3212
                    build_str.push(',');
365
3212
                }
366
3236
                let json_str = match serde_json::to_string(&data_transform(item)) {
367
                    Err(e) => return Err(Box::new(e)),
368
3236
                    Ok(str) => str,
369
3236
                };
370
3236
                build_str += json_str.as_str();
371
            }
372
        }
373
    }
374

            
375
64
    if with_end {
376
32
        build_str += match format {
377
4
            Some(request::ListFormat::Array) => "]",
378
8
            Some(request::ListFormat::Csv) => "",
379
20
            _ => "]}",
380
        }
381
32
    }
382
64
    Ok(Bytes::copy_from_slice(build_str.as_str().as_bytes()))
383
64
}
384

            
385
3848
fn data_transform(data: &NetworkDlData) -> response::GetListData {
386
3848
    response::GetListData {
387
3848
        data_id: data.data_id.clone(),
388
3848
        proc: strings::time_str(&data.proc),
389
3848
        publish: strings::time_str(&data.publish),
390
3848
        resp: match data.resp {
391
2524
            None => None,
392
1324
            Some(resp) => Some(strings::time_str(&resp)),
393
        },
394
3848
        status: data.status,
395
3848
        unit_id: data.unit_id.clone(),
396
3848
        device_id: data.device_id.clone(),
397
3848
        network_code: data.network_code.clone(),
398
3848
        network_addr: data.network_addr.clone(),
399
3848
        profile: data.profile.clone(),
400
3848
        data: data.data.clone(),
401
3848
        extension: data.extension.clone(),
402
3848
    }
403
3848
}
404

            
405
440
fn data_transform_csv(data: &NetworkDlData) -> response::GetListCsvData {
406
440
    response::GetListCsvData {
407
440
        data_id: data.data_id.clone(),
408
440
        proc: strings::time_str(&data.proc),
409
440
        publish: strings::time_str(&data.publish),
410
440
        resp: match data.resp {
411
416
            None => "".to_string(),
412
24
            Some(resp) => strings::time_str(&resp),
413
        },
414
440
        status: data.status,
415
440
        unit_id: data.unit_id.clone(),
416
440
        device_id: data.device_id.clone(),
417
440
        network_code: data.network_code.clone(),
418
440
        network_addr: data.network_addr.clone(),
419
440
        profile: data.profile.clone(),
420
440
        data: data.data.clone(),
421
440
        extension: match data.extension.as_ref() {
422
416
            None => "".to_string(),
423
24
            Some(extension) => match serde_json::to_string(extension) {
424
                Err(_) => "".to_string(),
425
24
                Ok(extension) => extension,
426
            },
427
        },
428
    }
429
440
}