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_uldata::{ListOptions, ListQueryCond, NetworkUlData, 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,unitCode,networkCode,networkAddr,unitId,deviceId,time,profile,data,extension\n";
35

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

            
44
96
    if let Some(network) = query.network {
45
6
        query.network = Some(network.to_lowercase());
46
90
    }
47
96
    if let Some(addr) = query.addr {
48
4
        query.addr = Some(addr.to_lowercase());
49
92
    }
50

            
51
96
    let unit_cond = get_unit_cond(FN_NAME, &token_info, query.unit.as_ref(), &state).await?;
52
88
    let cond = match get_list_cond(&query, &unit_cond).await {
53
30
        Err(e) => return Err(e.into_response()),
54
58
        Ok(cond) => cond,
55
58
    };
56
116
    match state.model.network_uldata().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
58
        Ok(count) => Ok(Json(response::GetCount {
62
58
            data: response::GetCountData { count },
63
58
        })),
64
    }
65
96
}
66

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

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

            
114
196
    let (list, cursor) = match state.model.network_uldata().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
98
        Ok((list, cursor)) => match cursor {
120
84
            None => match query.format.as_ref() {
121
                Some(request::ListFormat::Array) => {
122
2
                    return Ok(Json(list_transform(&list)).into_response())
123
                }
124
                Some(request::ListFormat::Csv) => {
125
2
                    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
2
                        Ok(bytes) => bytes,
132
2
                    };
133
2
                    return Ok((
134
2
                        [
135
2
                            (header::CONTENT_TYPE, ContentType::CSV),
136
2
                            (
137
2
                                header::CONTENT_DISPOSITION,
138
2
                                "attachment;filename=network-uldata.csv",
139
2
                            ),
140
2
                        ],
141
2
                        bytes,
142
2
                    )
143
2
                        .into_response());
144
                }
145
                _ => {
146
80
                    return Ok(Json(response::GetList {
147
80
                        data: list_transform(&list),
148
80
                    })
149
80
                    .into_response())
150
                }
151
            },
152
14
            Some(_) => (list, cursor),
153
14
        },
154
14
    };
155
14

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

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

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

            
269
180
    Ok(cond)
270
240
}
271

            
272
108
fn get_sort_cond(sort_args: &Option<String>) -> Result<Vec<SortCond>, ErrResp> {
273
108
    match sort_args.as_ref() {
274
60
        None => Ok(vec![SortCond {
275
60
            key: SortKey::Proc,
276
60
            asc: false,
277
60
        }]),
278
48
        Some(args) => {
279
48
            let mut args = args.split(",");
280
48
            let mut sort_cond = vec![];
281
104
            while let Some(arg) = args.next() {
282
66
                let mut cond = arg.split(":");
283
66
                let key = match cond.next() {
284
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
285
66
                    Some(field) => match field {
286
66
                        "proc" => SortKey::Proc,
287
26
                        "time" => SortKey::Time,
288
20
                        "network" => SortKey::NetworkCode,
289
12
                        "addr" => SortKey::NetworkAddr,
290
                        _ => {
291
4
                            return Err(ErrResp::ErrParam(Some(format!(
292
4
                                "invalid sort key {}",
293
4
                                field
294
4
                            ))))
295
                        }
296
                    },
297
                };
298
62
                let asc = match cond.next() {
299
2
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
300
60
                    Some(asc) => match asc {
301
60
                        "asc" => true,
302
14
                        "desc" => false,
303
                        _ => {
304
2
                            return Err(ErrResp::ErrParam(Some(format!(
305
2
                                "invalid sort asc {}",
306
2
                                asc
307
2
                            ))))
308
                        }
309
                    },
310
                };
311
58
                if cond.next().is_some() {
312
2
                    return Err(ErrResp::ErrParam(Some(
313
2
                        "invalid sort condition".to_string(),
314
2
                    )));
315
56
                }
316
56
                sort_cond.push(SortCond { key, asc });
317
            }
318
38
            Ok(sort_cond)
319
        }
320
    }
321
108
}
322

            
323
82
fn list_transform(list: &Vec<NetworkUlData>) -> Vec<response::GetListData> {
324
82
    let mut ret = vec![];
325
226
    for item in list.iter() {
326
226
        ret.push(data_transform(&item));
327
226
    }
328
82
    ret
329
82
}
330

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

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

            
372
32
    if with_end {
373
16
        build_str += match format {
374
2
            Some(request::ListFormat::Array) => "]",
375
4
            Some(request::ListFormat::Csv) => "",
376
10
            _ => "]}",
377
        }
378
16
    }
379
32
    Ok(Bytes::copy_from_slice(build_str.as_str().as_bytes()))
380
32
}
381

            
382
1844
fn data_transform(data: &NetworkUlData) -> response::GetListData {
383
1844
    response::GetListData {
384
1844
        data_id: data.data_id.clone(),
385
1844
        proc: strings::time_str(&data.proc),
386
1844
        unit_code: data.unit_code.clone(),
387
1844
        network_code: data.network_code.clone(),
388
1844
        network_addr: data.network_addr.clone(),
389
1844
        unit_id: data.unit_id.clone(),
390
1844
        device_id: data.device_id.clone(),
391
1844
        time: strings::time_str(&data.time),
392
1844
        profile: data.profile.clone(),
393
1844
        data: data.data.clone(),
394
1844
        extension: data.extension.clone(),
395
1844
    }
396
1844
}
397

            
398
220
fn data_transform_csv(data: &NetworkUlData) -> response::GetListCsvData {
399
220
    response::GetListCsvData {
400
220
        data_id: data.data_id.clone(),
401
220
        proc: strings::time_str(&data.proc),
402
220
        unit_code: match data.unit_code.as_ref() {
403
208
            None => "".to_string(),
404
12
            Some(unit_code) => unit_code.clone(),
405
        },
406
220
        network_code: data.network_code.clone(),
407
220
        network_addr: data.network_addr.clone(),
408
220
        unit_id: match data.unit_id.as_ref() {
409
208
            None => "".to_string(),
410
12
            Some(unit_id) => unit_id.clone(),
411
        },
412
220
        device_id: match data.device_id.as_ref() {
413
208
            None => "".to_string(),
414
12
            Some(device_id) => device_id.clone(),
415
        },
416
220
        time: strings::time_str(&data.time),
417
220
        profile: data.profile.clone(),
418
220
        data: data.data.clone(),
419
220
        extension: match data.extension.as_ref() {
420
208
            None => "".to_string(),
421
12
            Some(extension) => match serde_json::to_string(extension) {
422
                Err(_) => "".to_string(),
423
12
                Ok(extension) => extension,
424
            },
425
        },
426
    }
427
220
}