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::network_dldata::{ListOptions, ListQueryCond, NetworkDlData, SortCond, SortKey};
23

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

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

            
37
108
    let mut query: request::GetCountQuery = (*query).clone();
38
108
    if let Some(network) = query.network {
39
6
        query.network = Some(network.to_lowercase());
40
102
    }
41
108
    if let Some(addr) = query.addr {
42
4
        query.addr = Some(addr.to_lowercase());
43
104
    }
44

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

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

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

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

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

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

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

            
262
208
    Ok(cond)
263
268
}
264

            
265
270
async fn get_unit_cond(
266
270
    fn_name: &str,
267
270
    req: &HttpRequest,
268
270
    query_unit: Option<&String>,
269
270
    state: &web::Data<State>,
270
270
) -> Result<Option<String>, HttpResponse> {
271
270
    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
270
        Some(token_info) => token_info.clone(),
279
270
    };
280
270
    let broker_base = state.broker_base.as_str();
281
270
    let client = state.client.clone();
282
270

            
283
270
    match query_unit {
284
        None => {
285
82
            if !Role::is_role(&token_info.info.roles, Role::ADMIN)
286
82
                && !Role::is_role(&token_info.info.roles, Role::MANAGER)
287
            {
288
8
                return Err(ErrResp::ErrParam(Some("missing `unit`".to_string())).error_response());
289
74
            }
290
74
            Ok(None)
291
        }
292
188
        Some(unit_id) => match unit_id.len() {
293
12
            0 => Ok(None),
294
            _ => {
295
176
                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
176
                    Ok(value) => value,
302
176
                };
303
183
                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
176
                    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
168
                        Some(_) => Ok(Some(unit_id.clone())),
318
                    },
319
                }
320
            }
321
        },
322
    }
323
270
}
324

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

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

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

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

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

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

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