1
use std::error::Error as StdError;
2

            
3
use actix_web::{
4
    http::header::{self, HeaderValue},
5
    web::{self, Bytes},
6
    HttpMessage, HttpRequest, HttpResponse, Responder, ResponseError,
7
};
8
use chrono::{TimeZone, Utc};
9
use csv::WriterBuilder;
10
use log::error;
11
use serde_json;
12

            
13
use sylvia_iot_corelib::{err::ErrResp, role::Role, strings};
14

            
15
use super::{
16
    super::{
17
        super::{middleware::FullTokenInfo, ErrReq, State},
18
        get_unit_inner,
19
    },
20
    request, response,
21
};
22
use crate::models::application_dldata::{
23
    ApplicationDlData, ListOptions, ListQueryCond, SortCond, SortKey,
24
};
25

            
26
const LIST_LIMIT_DEFAULT: u64 = 100;
27
const LIST_CURSOR_MAX: u64 = 100;
28
const CSV_FIELDS: &'static str =
29
    "dataId,proc,resp,status,unitId,deviceId,networkCode,networkAddr,profile,data,extension\n";
30

            
31
/// `GET /{base}/api/v1/application-dldata/count`
32
96
pub async fn get_count(
33
96
    req: HttpRequest,
34
96
    query: web::Query<request::GetCountQuery>,
35
96
    state: web::Data<State>,
36
96
) -> impl Responder {
37
96
    const FN_NAME: &'static str = "get_count";
38
96

            
39
96
    let mut query: request::GetCountQuery = (*query).clone();
40
96
    if let Some(network) = query.network {
41
6
        query.network = Some(network.to_lowercase());
42
90
    }
43
96
    if let Some(addr) = query.addr {
44
4
        query.addr = Some(addr.to_lowercase());
45
92
    }
46

            
47
96
    let unit_cond = match get_unit_cond(FN_NAME, &req, query.unit.as_ref(), &state).await {
48
8
        Err(e) => return e,
49
88
        Ok(cond) => cond,
50
    };
51
88
    let cond = match get_list_cond(&query, &unit_cond).await {
52
30
        Err(e) => return e.error_response(),
53
58
        Ok(cond) => cond,
54
58
    };
55
117
    match state.model.application_dldata().count(&cond).await {
56
        Err(e) => {
57
            error!("[{}] count error: {}", FN_NAME, e);
58
            ErrResp::ErrDb(Some(e.to_string())).error_response()
59
        }
60
58
        Ok(count) => HttpResponse::Ok().json(response::GetCount {
61
58
            data: response::GetCountData { count },
62
58
        }),
63
    }
64
96
}
65

            
66
/// `GET /{base}/api/v1/application-dldata/list`
67
146
pub async fn get_list(
68
146
    req: HttpRequest,
69
146
    query: web::Query<request::GetListQuery>,
70
146
    state: web::Data<State>,
71
146
) -> impl Responder {
72
    const FN_NAME: &'static str = "get_list";
73

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

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

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

            
181
14
        let mut list = list;
182
14
        let mut cursor = cursor;
183
14
        let mut is_first = true;
184
        loop {
185
30
            yield list_transform_bytes(&list, is_first, cursor.is_none(), query.format.as_ref());
186
30
            is_first = false;
187
30
            if cursor.is_none() {
188
14
                break;
189
16
            }
190
22
            let (_list, _cursor) = match state.model.application_dldata().list(&opts, cursor).await {
191
                Err(_) => break,
192
16
                Ok((list, cursor)) => (list, cursor),
193
16
            };
194
16
            list = _list;
195
16
            cursor = _cursor;
196
        }
197
    };
198
4
    match query_format {
199
2
        Some(request::ListFormat::Csv) => Ok(HttpResponse::Ok()
200
2
            .insert_header((header::CONTENT_TYPE, "text/csv"))
201
2
            .insert_header((
202
2
                header::CONTENT_DISPOSITION,
203
2
                "attachment;filename=application-dldata.csv",
204
2
            ))
205
2
            .streaming(stream)),
206
12
        _ => Ok(HttpResponse::Ok().streaming(stream)),
207
    }
208
146
}
209

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

            
262
180
    Ok(cond)
263
240
}
264

            
265
242
async fn get_unit_cond(
266
242
    fn_name: &str,
267
242
    req: &HttpRequest,
268
242
    query_unit: Option<&String>,
269
242
    state: &web::Data<State>,
270
242
) -> Result<Option<String>, HttpResponse> {
271
242
    let token_info = match req.extensions_mut().get::<FullTokenInfo>() {
272
        None => {
273
            error!("[{}] token not found", fn_name);
274
            return Err(
275
                ErrResp::ErrUnknown(Some("token info not found".to_string())).error_response(),
276
            );
277
        }
278
242
        Some(token_info) => token_info.clone(),
279
242
    };
280
242
    let broker_base = state.broker_base.as_str();
281
242
    let client = state.client.clone();
282
242

            
283
242
    match query_unit {
284
        None => {
285
78
            if !Role::is_role(&token_info.info.roles, Role::ADMIN)
286
78
                && !Role::is_role(&token_info.info.roles, Role::MANAGER)
287
            {
288
8
                return Err(ErrResp::ErrParam(Some("missing `unit`".to_string())).error_response());
289
70
            }
290
70
            Ok(None)
291
        }
292
164
        Some(unit_id) => match unit_id.len() {
293
12
            0 => Ok(None),
294
            _ => {
295
152
                let token = match HeaderValue::from_str(token_info.token.as_str()) {
296
                    Err(e) => {
297
                        error!("[{}] get token error: {}", fn_name, e);
298
                        return Err(ErrResp::ErrUnknown(Some(format!("get token error: {}", e)))
299
                            .error_response());
300
                    }
301
152
                    Ok(value) => value,
302
152
                };
303
168
                match get_unit_inner(fn_name, &client, broker_base, unit_id, &token).await {
304
                    Err(e) => {
305
                        error!("[{}] get unit error", fn_name);
306
                        return Err(e);
307
                    }
308
152
                    Ok(unit) => match unit {
309
                        None => {
310
8
                            return Err(ErrResp::Custom(
311
8
                                ErrReq::UNIT_NOT_EXIST.0,
312
8
                                ErrReq::UNIT_NOT_EXIST.1,
313
8
                                None,
314
8
                            )
315
8
                            .error_response())
316
                        }
317
144
                        Some(_) => Ok(Some(unit_id.clone())),
318
                    },
319
                }
320
            }
321
        },
322
    }
323
242
}
324

            
325
108
fn get_sort_cond(sort_args: &Option<String>) -> Result<Vec<SortCond>, ErrResp> {
326
108
    match sort_args.as_ref() {
327
60
        None => Ok(vec![SortCond {
328
60
            key: SortKey::Proc,
329
60
            asc: false,
330
60
        }]),
331
48
        Some(args) => {
332
48
            let mut args = args.split(",");
333
48
            let mut sort_cond = vec![];
334
104
            while let Some(arg) = args.next() {
335
66
                let mut cond = arg.split(":");
336
66
                let key = match cond.next() {
337
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
338
66
                    Some(field) => match field {
339
66
                        "proc" => SortKey::Proc,
340
26
                        "resp" => SortKey::Resp,
341
20
                        "network" => SortKey::NetworkCode,
342
12
                        "addr" => SortKey::NetworkAddr,
343
                        _ => {
344
4
                            return Err(ErrResp::ErrParam(Some(format!(
345
4
                                "invalid sort key {}",
346
4
                                field
347
4
                            ))))
348
                        }
349
                    },
350
                };
351
62
                let asc = match cond.next() {
352
2
                    None => return Err(ErrResp::ErrParam(Some("wrong sort argument".to_string()))),
353
60
                    Some(asc) => match asc {
354
60
                        "asc" => true,
355
14
                        "desc" => false,
356
                        _ => {
357
2
                            return Err(ErrResp::ErrParam(Some(format!(
358
2
                                "invalid sort asc {}",
359
2
                                asc
360
2
                            ))))
361
                        }
362
                    },
363
                };
364
58
                if cond.next().is_some() {
365
2
                    return Err(ErrResp::ErrParam(Some(
366
2
                        "invalid sort condition".to_string(),
367
2
                    )));
368
56
                }
369
56
                sort_cond.push(SortCond { key, asc });
370
            }
371
38
            Ok(sort_cond)
372
        }
373
    }
374
108
}
375

            
376
82
fn list_transform(list: &Vec<ApplicationDlData>) -> Vec<response::GetListData> {
377
82
    let mut ret = vec![];
378
244
    for item in list.iter() {
379
244
        ret.push(data_transform(&item));
380
244
    }
381
82
    ret
382
82
}
383

            
384
32
fn list_transform_bytes(
385
32
    list: &Vec<ApplicationDlData>,
386
32
    with_start: bool,
387
32
    with_end: bool,
388
32
    format: Option<&request::ListFormat>,
389
32
) -> Result<Bytes, Box<dyn StdError>> {
390
32
    let mut build_str = match with_start {
391
16
        false => "".to_string(),
392
6
        true => match format {
393
2
            Some(request::ListFormat::Array) => "[".to_string(),
394
            Some(request::ListFormat::Csv) => {
395
4
                let bom = String::from_utf8(vec![0xEF, 0xBB, 0xBF])?;
396
4
                format!("{}{}", bom, CSV_FIELDS)
397
            }
398
10
            _ => "{\"data\":[".to_string(),
399
        },
400
    };
401
32
    let mut is_first = with_start;
402

            
403
1870
    for item in list {
404
430
        match format {
405
            Some(request::ListFormat::Csv) => {
406
220
                let mut writer = WriterBuilder::new().has_headers(false).from_writer(vec![]);
407
220
                writer.serialize(data_transform_csv(item))?;
408
220
                build_str += String::from_utf8(writer.into_inner()?)?.as_str();
409
            }
410
            _ => {
411
1618
                if is_first {
412
12
                    is_first = false;
413
1606
                } else {
414
1606
                    build_str.push(',');
415
1606
                }
416
1618
                let json_str = match serde_json::to_string(&data_transform(item)) {
417
                    Err(e) => return Err(Box::new(e)),
418
1618
                    Ok(str) => str,
419
1618
                };
420
1618
                build_str += json_str.as_str();
421
            }
422
        }
423
    }
424

            
425
32
    if with_end {
426
16
        build_str += match format {
427
2
            Some(request::ListFormat::Array) => "]",
428
4
            Some(request::ListFormat::Csv) => "",
429
10
            _ => "]}",
430
        }
431
16
    }
432
32
    Ok(Bytes::copy_from_slice(build_str.as_str().as_bytes()))
433
32
}
434

            
435
1862
fn data_transform(data: &ApplicationDlData) -> response::GetListData {
436
1862
    response::GetListData {
437
1862
        data_id: data.data_id.clone(),
438
1862
        proc: strings::time_str(&data.proc),
439
1862
        resp: match data.resp {
440
1246
            None => None,
441
616
            Some(resp) => Some(strings::time_str(&resp)),
442
        },
443
1862
        status: data.status,
444
1862
        unit_id: data.unit_id.clone(),
445
1862
        device_id: data.device_id.clone(),
446
1862
        network_code: data.network_code.clone(),
447
1862
        network_addr: data.network_addr.clone(),
448
1862
        profile: data.profile.clone(),
449
1862
        data: data.data.clone(),
450
1862
        extension: data.extension.clone(),
451
1862
    }
452
1862
}
453

            
454
220
fn data_transform_csv(data: &ApplicationDlData) -> response::GetListCsvData {
455
220
    response::GetListCsvData {
456
220
        data_id: data.data_id.clone(),
457
220
        proc: strings::time_str(&data.proc),
458
220
        resp: match data.resp {
459
208
            None => "".to_string(),
460
12
            Some(resp) => strings::time_str(&resp),
461
        },
462
220
        status: data.status,
463
220
        unit_id: data.unit_id.clone(),
464
220
        device_id: match data.device_id.as_ref() {
465
208
            None => "".to_string(),
466
12
            Some(device_id) => device_id.clone(),
467
        },
468
220
        network_code: match data.network_code.as_ref() {
469
208
            None => "".to_string(),
470
12
            Some(network_code) => network_code.clone(),
471
        },
472
220
        network_addr: match data.network_addr.as_ref() {
473
208
            None => "".to_string(),
474
12
            Some(network_addr) => network_addr.clone(),
475
        },
476
220
        profile: data.profile.clone(),
477
220
        data: data.data.clone(),
478
220
        extension: match data.extension.as_ref() {
479
208
            None => "".to_string(),
480
12
            Some(extension) => match serde_json::to_string(extension) {
481
                Err(_) => "".to_string(),
482
12
                Ok(extension) => extension,
483
            },
484
        },
485
    }
486
220
}