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

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

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

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

            
77
324
    let cond_query = request::GetCountQuery {
78
324
        unit: query.unit.clone(),
79
324
        device: query.device.clone(),
80
324
        network: match query.network.as_ref() {
81
312
            None => None,
82
12
            Some(network) => Some(network.to_lowercase()),
83
        },
84
324
        addr: match query.addr.as_ref() {
85
316
            None => None,
86
8
            Some(addr) => Some(addr.to_lowercase()),
87
        },
88
324
        profile: query.profile.clone(),
89
324
        tfield: query.tfield.clone(),
90
324
        tstart: query.tstart,
91
324
        tend: query.tend,
92
    };
93
324
    let unit_cond = match get_unit_cond(FN_NAME, &token_info, query.unit.as_ref(), &state).await {
94
16
        Err(e) => return Ok(e),
95
308
        Ok(cond) => cond,
96
    };
97
308
    let cond = match get_list_cond(&cond_query, &unit_cond).await {
98
60
        Err(e) => return Err(e),
99
248
        Ok(cond) => cond,
100
    };
101
248
    let sort_cond = match get_sort_cond(&query.sort) {
102
20
        Err(e) => return Err(e),
103
228
        Ok(cond) => cond,
104
    };
105
228
    let opts = ListOptions {
106
228
        cond: &cond,
107
228
        offset: query.offset,
108
228
        limit: match query.limit {
109
192
            None => Some(LIST_LIMIT_DEFAULT),
110
36
            Some(limit) => Some(limit),
111
        },
112
228
        sort: Some(sort_cond.as_slice()),
113
228
        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
228
        Ok((list, cursor)) => match cursor {
122
200
            None => match query.format.as_ref() {
123
                Some(request::ListFormat::Array) => {
124
4
                    return Ok(Json(list_transform(&list)).into_response())
125
                }
126
                Some(request::ListFormat::Csv) => {
127
4
                    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
4
                        Ok(bytes) => bytes,
134
4
                    };
135
4
                    return Ok((
136
4
                        [
137
4
                            (header::CONTENT_TYPE, ContentType::CSV),
138
4
                            (
139
4
                                header::CONTENT_DISPOSITION,
140
4
                                "attachment;filename=application-uldata.csv",
141
4
                            ),
142
4
                        ],
143
4
                        bytes,
144
4
                    )
145
4
                        .into_response());
146
                }
147
                _ => {
148
192
                    return Ok(Json(response::GetList {
149
192
                        data: list_transform(&list),
150
192
                    })
151
192
                    .into_response())
152
                }
153
            },
154
28
            Some(_) => (list, cursor),
155
28
        },
156
28
    };
157
28

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

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

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

            
272
416
    Ok(cond)
273
536
}
274

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

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

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

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

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

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

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