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
192
pub async fn get_count(
38
192
    State(state): State<AppState>,
39
192
    Extension(token_info): Extension<GetTokenInfoData>,
40
192
    Query(mut query): Query<request::GetCountQuery>,
41
192
) -> impl IntoResponse {
42
    const FN_NAME: &'static str = "get_count";
43

            
44
192
    if let Some(network) = query.network {
45
12
        query.network = Some(network.to_lowercase());
46
180
    }
47
192
    if let Some(addr) = query.addr {
48
8
        query.addr = Some(addr.to_lowercase());
49
184
    }
50

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

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

            
75
292
    let cond_query = request::GetCountQuery {
76
292
        unit: query.unit.clone(),
77
292
        device: query.device.clone(),
78
292
        network: match query.network.as_ref() {
79
280
            None => None,
80
12
            Some(network) => Some(network.to_lowercase()),
81
        },
82
292
        addr: match query.addr.as_ref() {
83
284
            None => None,
84
8
            Some(addr) => Some(addr.to_lowercase()),
85
        },
86
292
        profile: query.profile.clone(),
87
292
        tfield: query.tfield.clone(),
88
292
        tstart: query.tstart,
89
292
        tend: query.tend,
90
    };
91
292
    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
276
        Ok(cond) => cond,
94
    };
95
276
    let cond = match get_list_cond(&cond_query, &unit_cond).await {
96
60
        Err(e) => return Err(e),
97
216
        Ok(cond) => cond,
98
    };
99
216
    let sort_cond = match get_sort_cond(&query.sort) {
100
20
        Err(e) => return Err(e),
101
196
        Ok(cond) => cond,
102
    };
103
196
    let opts = ListOptions {
104
196
        cond: &cond,
105
196
        offset: query.offset,
106
196
        limit: match query.limit {
107
160
            None => Some(LIST_LIMIT_DEFAULT),
108
36
            Some(limit) => Some(limit),
109
        },
110
196
        sort: Some(sort_cond.as_slice()),
111
196
        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
196
        Ok((list, cursor)) => match cursor {
120
168
            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-uldata.csv",
139
4
                            ),
140
4
                        ],
141
4
                        bytes,
142
4
                    )
143
4
                        .into_response());
144
                }
145
                _ => {
146
160
                    return Ok(Json(response::GetList {
147
160
                        data: list_transform(&list),
148
160
                    })
149
160
                    .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_uldata().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-uldata.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
292
}
216

            
217
480
async fn get_list_cond<'a>(
218
480
    query: &'a request::GetCountQuery,
219
480
    unit_cond: &'a Option<String>,
220
480
) -> Result<ListQueryCond<'a>, ErrResp> {
221
480
    let mut cond = ListQueryCond {
222
480
        unit_id: match unit_cond.as_ref() {
223
192
            None => None,
224
288
            Some(unit_id) => Some(unit_id.as_str()),
225
        },
226
480
        ..Default::default()
227
    };
228
480
    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
440
    }
233
480
    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
456
    }
238
480
    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
464
    }
243
480
    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
464
    }
248
480
    if let Some(start) = query.tstart.as_ref() {
249
240
        match query.tfield.as_ref() {
250
48
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
251
192
            Some(tfield) => match tfield.as_str() {
252
192
                "proc" => cond.proc_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
253
72
                "time" => cond.time_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
254
24
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
255
            },
256
        }
257
240
    }
258
408
    if let Some(end) = query.tend.as_ref() {
259
96
        match query.tfield.as_ref() {
260
24
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
261
72
            Some(tfield) => match tfield.as_str() {
262
72
                "proc" => cond.proc_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
263
48
                "time" => cond.time_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
264
24
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
265
            },
266
        }
267
312
    }
268

            
269
360
    Ok(cond)
270
480
}
271

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

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

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

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

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

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

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