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_uldata::{
30
    ApplicationUlData, 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,pub,unitCode,networkCode,networkAddr,unitId,deviceId,time,profile,data,extension\n";
37

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

            
46
108
    if let Some(network) = query.network {
47
6
        query.network = Some(network.to_lowercase());
48
102
    }
49
108
    if let Some(addr) = query.addr {
50
4
        query.addr = Some(addr.to_lowercase());
51
104
    }
52

            
53
108
    let unit_cond = get_unit_cond(FN_NAME, &token_info, query.unit.as_ref(), &state).await?;
54
100
    let cond = match get_list_cond(&query, &unit_cond).await {
55
30
        Err(e) => return Err(e.into_response()),
56
70
        Ok(cond) => cond,
57
70
    };
58
140
    match state.model.application_uldata().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
70
        Ok(count) => Ok(Json(response::GetCount {
64
70
            data: response::GetCountData { count },
65
70
        })),
66
    }
67
108
}
68

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

            
77
162
    let cond_query = request::GetCountQuery {
78
162
        unit: query.unit.clone(),
79
162
        device: query.device.clone(),
80
162
        network: match query.network.as_ref() {
81
156
            None => None,
82
6
            Some(network) => Some(network.to_lowercase()),
83
        },
84
162
        addr: match query.addr.as_ref() {
85
158
            None => None,
86
4
            Some(addr) => Some(addr.to_lowercase()),
87
        },
88
162
        profile: query.profile.clone(),
89
162
        tfield: query.tfield.clone(),
90
162
        tstart: query.tstart,
91
162
        tend: query.tend,
92
    };
93
162
    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
154
        Ok(cond) => cond,
96
    };
97
154
    let cond = match get_list_cond(&cond_query, &unit_cond).await {
98
30
        Err(e) => return Err(e),
99
124
        Ok(cond) => cond,
100
    };
101
124
    let sort_cond = match get_sort_cond(&query.sort) {
102
10
        Err(e) => return Err(e),
103
114
        Ok(cond) => cond,
104
    };
105
114
    let opts = ListOptions {
106
114
        cond: &cond,
107
114
        offset: query.offset,
108
114
        limit: match query.limit {
109
96
            None => Some(LIST_LIMIT_DEFAULT),
110
18
            Some(limit) => Some(limit),
111
        },
112
114
        sort: Some(sort_cond.as_slice()),
113
114
        cursor_max: Some(LIST_CURSOR_MAX),
114
    };
115

            
116
228
    let (list, cursor) = match state.model.application_uldata().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
114
        Ok((list, cursor)) => match cursor {
122
100
            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-uldata.csv",
141
2
                            ),
142
2
                        ],
143
2
                        bytes,
144
2
                    )
145
2
                        .into_response());
146
                }
147
                _ => {
148
96
                    return Ok(Json(response::GetList {
149
96
                        data: list_transform(&list),
150
96
                    })
151
96
                    .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_uldata().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-uldata.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
162
}
217

            
218
268
async fn get_list_cond<'a>(
219
268
    query: &'a request::GetCountQuery,
220
268
    unit_cond: &'a Option<String>,
221
268
) -> Result<ListQueryCond<'a>, ErrResp> {
222
268
    let mut cond = ListQueryCond {
223
268
        unit_id: match unit_cond.as_ref() {
224
100
            None => None,
225
168
            Some(unit_id) => Some(unit_id.as_str()),
226
        },
227
268
        ..Default::default()
228
    };
229
268
    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
248
    }
234
268
    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
256
    }
239
268
    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
260
    }
244
268
    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
260
    }
249
268
    if let Some(start) = query.tstart.as_ref() {
250
144
        match query.tfield.as_ref() {
251
24
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
252
120
            Some(tfield) => match tfield.as_str() {
253
120
                "proc" => cond.proc_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
254
60
                "pub" => cond.pub_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
255
36
                "time" => cond.time_gte = Some(Utc.timestamp_nanos(*start * 1000000)),
256
12
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
257
            },
258
        }
259
124
    }
260
232
    if let Some(end) = query.tend.as_ref() {
261
60
        match query.tfield.as_ref() {
262
12
            None => return Err(ErrResp::ErrParam(Some("missing `tfield`".to_string()))),
263
48
            Some(tfield) => match tfield.as_str() {
264
48
                "proc" => cond.proc_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
265
36
                "pub" => cond.pub_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
266
24
                "time" => cond.time_lte = Some(Utc.timestamp_nanos(*end * 1000000)),
267
12
                _ => return Err(ErrResp::ErrParam(Some("invalid `tfield`".to_string()))),
268
            },
269
        }
270
172
    }
271

            
272
208
    Ok(cond)
273
268
}
274

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

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

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

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

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

            
386
1906
fn data_transform(data: &ApplicationUlData) -> response::GetListData {
387
1906
    response::GetListData {
388
1906
        data_id: data.data_id.clone(),
389
1906
        proc: strings::time_str(&data.proc),
390
1906
        publish: strings::time_str(&data.publish),
391
1906
        unit_code: data.unit_code.clone(),
392
1906
        network_code: data.network_code.clone(),
393
1906
        network_addr: data.network_addr.clone(),
394
1906
        unit_id: data.unit_id.clone(),
395
1906
        device_id: data.device_id.clone(),
396
1906
        time: strings::time_str(&data.time),
397
1906
        profile: data.profile.clone(),
398
1906
        data: data.data.clone(),
399
1906
        extension: data.extension.clone(),
400
1906
    }
401
1906
}
402

            
403
220
fn data_transform_csv(data: &ApplicationUlData) -> response::GetListCsvData {
404
220
    response::GetListCsvData {
405
220
        data_id: data.data_id.clone(),
406
220
        proc: strings::time_str(&data.proc),
407
220
        publish: strings::time_str(&data.publish),
408
220
        unit_code: match data.unit_code.as_ref() {
409
208
            None => "".to_string(),
410
12
            Some(unit_code) => unit_code.clone(),
411
        },
412
220
        network_code: data.network_code.clone(),
413
220
        network_addr: data.network_addr.clone(),
414
220
        unit_id: data.unit_id.clone(),
415
220
        device_id: data.device_id.clone(),
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
}