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::application_dldata::{
30
    ApplicationDlData, ListOptions, ListQueryCond, SortCond, SortKey,
31
};
32

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

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

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

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

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

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

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

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

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

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

            
270
180
    Ok(cond)
271
240
}
272

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

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

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

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

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

            
383
1862
fn data_transform(data: &ApplicationDlData) -> response::GetListData {
384
1862
    response::GetListData {
385
1862
        data_id: data.data_id.clone(),
386
1862
        proc: strings::time_str(&data.proc),
387
1862
        resp: match data.resp {
388
1246
            None => None,
389
616
            Some(resp) => Some(strings::time_str(&resp)),
390
        },
391
1862
        status: data.status,
392
1862
        unit_id: data.unit_id.clone(),
393
1862
        device_id: data.device_id.clone(),
394
1862
        network_code: data.network_code.clone(),
395
1862
        network_addr: data.network_addr.clone(),
396
1862
        profile: data.profile.clone(),
397
1862
        data: data.data.clone(),
398
1862
        extension: data.extension.clone(),
399
1862
    }
400
1862
}
401

            
402
220
fn data_transform_csv(data: &ApplicationDlData) -> response::GetListCsvData {
403
220
    response::GetListCsvData {
404
220
        data_id: data.data_id.clone(),
405
220
        proc: strings::time_str(&data.proc),
406
220
        resp: match data.resp {
407
208
            None => "".to_string(),
408
12
            Some(resp) => strings::time_str(&resp),
409
        },
410
220
        status: data.status,
411
220
        unit_id: data.unit_id.clone(),
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
        network_code: match data.network_code.as_ref() {
417
208
            None => "".to_string(),
418
12
            Some(network_code) => network_code.clone(),
419
        },
420
220
        network_addr: match data.network_addr.as_ref() {
421
208
            None => "".to_string(),
422
12
            Some(network_addr) => network_addr.clone(),
423
        },
424
220
        profile: data.profile.clone(),
425
220
        data: data.data.clone(),
426
220
        extension: match data.extension.as_ref() {
427
208
            None => "".to_string(),
428
12
            Some(extension) => match serde_json::to_string(extension) {
429
                Err(_) => "".to_string(),
430
12
                Ok(extension) => extension,
431
            },
432
        },
433
    }
434
220
}