-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfrs_api.cpp
More file actions
1646 lines (1472 loc) · 66.5 KB
/
Copy pathfrs_api.cpp
File metadata and controls
1646 lines (1472 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <filesystem>
#include <fstream>
#include <userver/components/component_context.hpp>
#include <userver/formats/serialize/common_containers.hpp>
#include "converters.hpp"
#include "frs_api.hpp"
namespace Frs
{
Api::Api(const userver::components::ComponentConfig& config,
const userver::components::ComponentContext& context)
: HttpHandlerJsonBase(config, context),
pg_cluster_(context.FindComponent<userver::components::Postgres>(Workflow::kDatabase).GetCluster()),
groups_cache_(context.FindComponent<GroupsCache>()),
config_cache_(context.FindComponent<ConfigCache>()),
vstreams_config_cache_(context.FindComponent<VStreamsConfigCache>()),
sg_config_cache_(context.FindComponent<SGConfigCache>()),
workflow_(context.FindComponent<Workflow>())
{
}
userver::formats::json::Value Api::HandleRequestJsonThrow(const userver::server::http::HttpRequest& request,
const userver::formats::json::Value& json,
userver::server::request::RequestContext&) const
{
const auto& api_method = request.GetPathArg(0);
if (request.GetMethod() == userver::server::http::HttpMethod::kGet)
{
if (api_method == METHOD_MOTION_DETECTION)
{
const auto& token = request.GetArg(P_TOKEN);
int32_t id_group = workflow_.getLocalConfig().allow_group_id_without_auth;
if (token.empty() && id_group <= 0)
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
if (!token.empty())
id_group = checkToken(token);
if (id_group <= 0)
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
userver::formats::json::ValueBuilder json_params;
json_params[P_STREAM_ID] = request.GetArg(P_STREAM_ID);
json_params[P_START] = request.GetArg(P_START);
if (!request.GetArg(P_DURATION).empty())
json_params[P_DURATION] = request.GetArg(P_DURATION);
LOG_INFO_TO(workflow_.getLogger(),
"API call from: {}; method: {}; {} = {}; {} = {}; {} = {}",
request.GetRemoteAddress(), api_method, P_STREAM_ID, request.GetArg(P_STREAM_ID), P_START, request.GetArg(P_START), P_DURATION, request.GetArg(P_DURATION));
motionDetection(id_group, json_params.ExtractValue());
userver::formats::json::ValueBuilder response;
response[P_CODE] = std::to_string(userver::server::http::HttpStatus::kOk);
response[P_MESSAGE] = MESSAGE_REQUEST_COMPLETED;
return response.ExtractValue();
}
throw userver::server::handlers::ClientError(ExternalBody{ERROR_UNKNOWN_METHOD});
}
LOG_INFO_TO(workflow_.getLogger(),
"API call from: {}; method: {}; body: {}",
request.GetRemoteAddress(), api_method, absl::ClippedSubstr(ToStableString(json), 0, 300));
const auto& auth_value = request.GetHeader("Authorization");
if (api_method.starts_with(SG_METHOD_PREFIX))
{
// check special group authorization
if (auth_value.empty())
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
const auto bearer_sep_pos = auth_value.find(' ');
if (bearer_sep_pos == std::string::npos || std::string_view{auth_value.data(), bearer_sep_pos} != "Bearer")
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
const auto token{auth_value.data() + bearer_sep_pos + 1};
const auto id_sgroup = checkSGToken(token);
if (id_sgroup <= 0)
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
HashMap<std::string_view, std::function<void(int32_t, const userver::formats::json::Value&)>> no_content_methods = {
{METHOD_SG_DELETE_FACES, [this](auto&& id_sgroup, auto&& json)
{
sgDeleteFaces(id_sgroup, json);
}},
{METHOD_SG_UPDATE_GROUP, [this](auto&& id_sgroup, auto&& json)
{
sgUpdateGroup(id_sgroup, json);
}},
};
if (no_content_methods.contains(api_method))
{
no_content_methods[api_method](id_sgroup, json);
request.SetResponseStatus(userver::server::http::HttpStatus::kNoContent);
return {};
}
HashMap<std::string_view, std::function<userver::formats::json::Value(int32_t, const userver::formats::json::Value&)>> with_content_methods = {
{METHOD_SG_REGISTER_FACE, [this](auto&& id_sgroup, auto&& json)
{
return sgRegisterFace(id_sgroup, json);
}},
{METHOD_SG_LIST_FACES, [this](auto&& id_sgroup, auto&&)
{
return sgListFaces(id_sgroup);
}},
{METHOD_SG_RENEW_TOKEN, [this](auto&& id_sgroup, auto&&)
{
return sgRenewToken(id_sgroup);
}},
{METHOD_SG_SEARCH_FACES, [this](auto&& id_sgroup, auto&& json)
{
return sgSearchFaces(id_sgroup, json);
}},
};
if (with_content_methods.contains(api_method))
{
auto data = with_content_methods[api_method](id_sgroup, json);
if (data.IsEmpty())
{
request.SetResponseStatus(userver::server::http::HttpStatus::kNoContent);
return {};
}
userver::formats::json::ValueBuilder response;
response[P_CODE] = std::to_string(userver::server::http::HttpStatus::kOk);
response[P_MESSAGE] = MESSAGE_REQUEST_COMPLETED;
response[P_DATA] = std::move(data);
return response.ExtractValue();
}
throw userver::server::handlers::ClientError(ExternalBody{ERROR_UNKNOWN_METHOD});
}
int32_t id_group = workflow_.getLocalConfig().allow_group_id_without_auth;
// check authorization
if (auth_value.empty() && id_group <= 0)
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
if (!auth_value.empty())
{
const auto bearer_sep_pos = auth_value.find(' ');
if (bearer_sep_pos == std::string::npos || std::string_view{auth_value.data(), bearer_sep_pos} != "Bearer")
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
const auto token{auth_value.data() + bearer_sep_pos + 1};
id_group = checkToken(token);
}
if (id_group <= 0)
throw userver::server::handlers::ClientError(HandlerErrorCode::kUnauthorized);
HashMap<std::string_view, std::function<void(int32_t, const userver::formats::json::Value&)>> no_content_methods = {
{METHOD_ADD_STREAM, [this](auto&& id_group, auto&& json)
{
addStream(id_group, json);
}},
{METHOD_MOTION_DETECTION, [this](auto&& id_group, auto&& json)
{
motionDetection(id_group, json);
}},
{METHOD_DOOR_IS_OPEN, [this](auto&& id_group, auto&& json)
{
doorIsOpen(id_group, json);
}},
{METHOD_ADD_FACES, [this](auto&& id_group, auto&& json)
{
addFaces(id_group, json);
}},
{METHOD_REMOVE_FACES, [this](auto&& id_group, auto&& json)
{
removeFaces(id_group, json);
}},
{METHOD_REMOVE_STREAM, [this](auto&& id_group, auto&& json)
{
removeVStream(id_group, json);
}},
{METHOD_DELETE_FACES, [this](auto&& id_group, auto&& json)
{
deleteFaces(id_group, json);
}},
{METHOD_TEST_IMAGE, [this](auto&& id_group, auto&& json)
{
testImage(id_group, json);
}},
{METHOD_UPDATE_SPECIAL_GROUP, [this](auto&& id_group, auto&& json)
{
updateSpecialGroup(id_group, json);
}},
{METHOD_DELETE_SPECIAL_GROUP, [this](auto&& id_group, auto&& json)
{
deleteSpecialGroup(id_group, json);
}},
{METHOD_SAVE_DNN_STATS_DATA, [this](auto&&, auto&&)
{
saveDNNStatsData();
}},
{METHOD_SET_COMMON_CONFIG, [this](auto&& id_group, auto&& json)
{
setCommonConfigParams(id_group, json);
}},
{METHOD_SET_STREAM_DEFAULT_CONFIG, [this](auto&& id_group, auto&& json)
{
setStreamDefaultConfigParams(id_group, json);
}},
};
if (no_content_methods.contains(api_method))
{
no_content_methods[api_method](id_group, json);
request.SetResponseStatus(userver::server::http::HttpStatus::kNoContent);
return {};
}
HashMap<std::string_view, std::function<userver::formats::json::Value(int32_t, const userver::formats::json::Value&)>> with_content_methods = {
{METHOD_LIST_STREAMS, [this](auto&& id_group, auto&&)
{
return listStreams(id_group);
}},
{METHOD_BEST_QUALITY, [this](auto&& id_group, auto&& json)
{
return bestQuality(id_group, json);
}},
{METHOD_LIST_ALL_FACES, [this](auto&& id_group, auto&&)
{
return listAllFaces(id_group);
}},
{METHOD_CLUSTER_FACES_BY_SIMILARITY, [this](auto&& id_group, auto&& json)
{
return clusterFacesBySimilarity(id_group, json);
}},
{METHOD_GET_EVENTS, [this](auto&& id_group, auto&& json)
{
return getEvents(id_group, json);
}},
{METHOD_REGISTER_FACE, [this](auto&& id_group, auto&& json)
{
return registerFace(id_group, json);
}},
{METHOD_PROCESS_FRAME, [this](auto&& id_group, auto&& json)
{
return processFrame(id_group, json);
}},
{METHOD_ADD_SPECIAL_GROUP, [this](auto&& id_group, auto&& json)
{
return addSpecialGroup(id_group, json);
}},
{METHOD_LIST_SPECIAL_GROUPS, [this](auto&& id_group, auto&&)
{
return listSpecialGroups(id_group);
}},
{METHOD_GET_COMMON_CONFIG, [this](auto&& id_group, auto&&)
{
return getCommonConfigParams(id_group);
}},
{METHOD_GET_STREAM_DEFAULT_CONFIG, [this](auto&& id_group, auto&&)
{
return getStreamDefaultConfigParams(id_group);
}},
{METHOD_GET_BARCODE_EVENT, [this](auto&& id_group, auto&& json)
{
return getBarcodeEvent(id_group, json);
}},
{METHOD_GET_ADDITIONAL_FEATURES, [](auto&&, auto&&)
{
return getAdditionalFeatures();
}},
};
if (with_content_methods.contains(api_method))
{
auto data = with_content_methods[api_method](id_group, json);
if (data.IsEmpty())
{
request.SetResponseStatus(userver::server::http::HttpStatus::kNoContent);
return {};
}
userver::formats::json::ValueBuilder response;
response[P_CODE] = std::to_string(userver::server::http::HttpStatus::kOk);
response[P_MESSAGE] = MESSAGE_REQUEST_COMPLETED;
response[P_DATA] = std::move(data);
return response.ExtractValue();
}
throw userver::server::handlers::ClientError(ExternalBody{ERROR_UNKNOWN_METHOD});
}
int32_t Api::checkToken(const absl::string_view token) const
{
if (const auto g_cache = groups_cache_.Get(); g_cache->contains(token))
return g_cache->at(token).id_group;
return -1;
}
int32_t Api::checkSGToken(const absl::string_view token) const
{
if (const auto sg_config_cache = sg_config_cache_.Get(); sg_config_cache->getData().contains(token))
return sg_config_cache->getData().at(token).id_special_group;
return -1;
}
int32_t Api::getVStreamId(const int32_t id_group, const absl::string_view vstream_ext) const
{
try
{
if (const auto result = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_GET_VSTREAM_ID, id_group, vstream_ext); !result.IsEmpty())
return result[0][DatabaseFields::ID_VSTREAM].As<int32_t>();
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
return -1;
}
std::string Api::getVStreamExt(const int32_t id_group, int32_t id_vstream) const
{
try
{
if (const auto result = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_GET_VSTREAM_EXT, id_group, id_vstream); !result.IsEmpty())
return result[0][DatabaseFields::VSTREAM_EXT].As<std::string>();
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
return {};
}
void Api::requireMemberThrow(const userver::formats::json::Value& json, const absl::string_view member)
{
if (!json.HasMember(member))
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Required member `$0` not found.", member)});
if (json[member].IsNull())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be null.", member)});
if (json[member].IsArray())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be an array.", member)});
if (json[member].IsObject())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be an object.", member)});
if (json[member].IsString() && json[member].As<std::string>().empty())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be empty.", member)});
}
void Api::requireArrayThrow(const userver::formats::json::Value& json, const absl::string_view member)
{
if (!json.HasMember(member))
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Required array member `$0` not found.", member)});
if (json[member].IsNull())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be null.", member)});
if (json[member].IsObject())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must not be an object.", member)});
if (!json[member].IsArray())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Member `$0` must be an array.", member)});
if (json[member].IsEmpty())
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Array member `$0` must not be empty.", member)});
}
void Api::addStream(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
const auto vstream_ext = convertToString(json[P_STREAM_ID]);
auto url = json[P_URL].As<std::optional<std::string>>(std::nullopt);
auto callback_url = json[P_CALLBACK_URL].As<std::optional<std::string>>(std::nullopt);
auto callback_url_barcodes = json[P_CALLBACK_URL_BARCODES].As<std::optional<std::string>>(std::nullopt);
std::vector<int32_t> faces;
if (json.HasMember(P_FACE_IDS))
try
{
for (const auto& item : json[P_FACE_IDS].As<std::vector<userver::formats::json::Value>>())
{
if (auto id_d = convertToNumber<int32_t>(item, 0); id_d > 0)
faces.emplace_back(id_d);
}
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
std::optional<userver::formats::json::Value> config = std::nullopt;
if (json.HasMember(P_PARAMS) && json[P_PARAMS].IsArray()) // for compatibility with old API
try
{
HashSet<std::string> int_params = {
ConfigParams::MAX_CAPTURE_ERROR_COUNT};
HashSet<std::string> float_params = {
ConfigParams::BLUR,
ConfigParams::BLUR_MAX,
ConfigParams::TOLERANCE,
ConfigParams::TITLE_HEIGHT_RATIO,
ConfigParams::FACE_CONFIDENCE_THRESHOLD,
ConfigParams::FACE_ENLARGE_SCALE,
ConfigParams::FACE_CLASS_CONFIDENCE_THRESHOLD,
ConfigParams::MARGIN};
HashSet<std::string> string_params = {
ConfigParams::CONF_OSD_DT_FORMAT,
ConfigParams::DNN_FD_INFERENCE_SERVER,
ConfigParams::DNN_FC_INFERENCE_SERVER,
ConfigParams::DNN_FR_INFERENCE_SERVER,
ConfigParams::DNN_BD_INFERENCE_SERVER,
ConfigParams::TITLE};
HashSet<std::string> time_params = {
ConfigParams::BEST_QUALITY_INTERVAL_AFTER,
ConfigParams::BEST_QUALITY_INTERVAL_BEFORE,
ConfigParams::CAPTURE_TIMEOUT,
ConfigParams::DELAY_AFTER_ERROR,
ConfigParams::DELAY_BETWEEN_FRAMES,
ConfigParams::OPEN_DOOR_DURATION,
ConfigParams::WORKFLOW_TIMEOUT,
ConfigParams::UNKNOWN_DESCRIPTOR_TTL};
HashSet<std::string> bool_params = {
ConfigParams::FLAG_SPAWNED_DESCRIPTORS,
ConfigParams::FLAG_PROCESS_FACES,
ConfigParams::FLAG_PROCESS_BARCODES};
// build video stream config
userver::formats::json::ValueBuilder config_builder;
for (const auto& param : json[P_PARAMS].As<userver::formats::json::Value>())
{
constexpr auto param_name = "paramName";
constexpr auto param_value = "paramValue";
const auto& p_name = param[param_name].As<std::string>();
if (int_params.contains(p_name))
{
config_builder[p_name] = param[param_value].As<int32_t>();
continue;
}
if (float_params.contains(p_name))
{
config_builder[p_name] = param[param_value].As<float>();
continue;
}
if (string_params.contains(p_name))
{
config_builder[p_name] = param[param_value].As<std::string>();
continue;
}
if (time_params.contains(p_name))
{
config_builder[p_name] = absl::Substitute("$0ms", static_cast<int32_t>(lround(param[param_value].As<float>() * 1000.0)));
continue;
}
if (bool_params.contains(p_name))
{
config_builder[p_name] = param[param_value].As<bool>();
continue;
}
if (p_name == ConfigParams::LOGS_LEVEL)
{
HashMap<int32_t, std::string> logs_level_map = {
{0, "error"},
{1, "info"},
{2, "trace"}};
auto p_value = param[param_value].As<int32_t>();
config_builder[p_name] = logs_level_map.contains(p_value) ? logs_level_map.at(p_value) : "info";
}
}
if (!config_builder.IsEmpty())
config = config_builder.ExtractValue();
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
if (json.HasMember(P_CONFIG) && json[P_CONFIG].IsObject())
config = json[P_CONFIG];
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
int32_t id_vstream;
if (const auto res = trx.Execute(SQL_GET_STREAM, id_group, vstream_ext); res.IsEmpty())
{
const auto r = trx.Execute(SQL_ADD_STREAM, id_group, vstream_ext, url, callback_url, callback_url_barcodes, config);
id_vstream = r.AsSingleRow<int32_t>();
} else
{
id_vstream = res[0][DatabaseFields::ID_VSTREAM].As<int32_t>();
if (!url)
url = res[0][DatabaseFields::URL].As<std::optional<std::string>>();
if (!callback_url)
callback_url = res[0][DatabaseFields::CALLBACK_URL].As<std::optional<std::string>>();
if (!callback_url_barcodes)
callback_url_barcodes = res[0][DatabaseFields::CALLBACK_URL_BARCODES].As<std::optional<std::string>>();
trx.Execute(SQL_UPDATE_STREAM, id_group, url, callback_url, callback_url_barcodes, config, id_vstream);
}
if (!faces.empty())
{
// bind faces to a video stream
for (const auto& id_descriptor : faces)
trx.Execute(SQL_ADD_LINK_DESCRIPTOR_VSTREAM, id_group, id_vstream, id_descriptor);
}
trx.Commit();
} catch (const std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
}
userver::formats::json::Value Api::listStreams(const int32_t id_group) const
{
struct VStreamData
{
std::optional<std::string> url;
std::optional<std::string> callback_url;
std::optional<std::string> callback_url_barcodes;
std::optional<userver::formats::json::Value> config;
std::vector<int32_t> faces;
};
HashMap<std::string, VStreamData> vstreams_data;
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
for (const auto result = trx.Execute(SQL_LIST_STREAMS_SIMPLE, id_group); const auto& row : result)
{
auto vstream_ext = row[DatabaseFields::VSTREAM_EXT].As<std::string>();
vstreams_data[vstream_ext] = {
row[DatabaseFields::URL].As<std::optional<std::string>>(),
row[DatabaseFields::CALLBACK_URL].As<std::optional<std::string>>(),
row[DatabaseFields::CALLBACK_URL_BARCODES].As<std::optional<std::string>>(),
row[DatabaseFields::CONFIG].As<std::optional<userver::formats::json::Value>>(),
{}};
}
for (const auto result = trx.Execute(SQL_LIST_STREAM_FACES, id_group); const auto& row : result)
{
auto vstream_ext = row[DatabaseFields::VSTREAM_EXT].As<std::string>();
auto id_descriptor = row[DatabaseFields::ID_DESCRIPTOR].As<int32_t>();
if (vstreams_data.contains(vstream_ext))
vstreams_data[vstream_ext].faces.push_back(id_descriptor);
}
trx.Commit();
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
userver::formats::json::ValueBuilder data;
for (const auto& [fst, snd] : vstreams_data)
{
userver::formats::json::ValueBuilder v;
v[P_STREAM_ID] = fst;
if (snd.url)
v[P_URL] = snd.url.value();
if (snd.callback_url)
v[P_CALLBACK_URL] = snd.callback_url.value();
if (snd.callback_url_barcodes)
v[P_CALLBACK_URL_BARCODES] = snd.callback_url_barcodes.value();
if (snd.config)
v[P_CONFIG] = snd.config.value();
if (!snd.faces.empty())
v[P_FACE_IDS] = snd.faces;
data.PushBack(std::move(v));
}
return data.ExtractValue();
}
void Api::motionDetection(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
requireMemberThrow(json, P_START);
auto vstream_key = absl::Substitute("$0_$1", id_group, convertToString(json[P_STREAM_ID]));
const auto duration = convertToDuration(json[P_DURATION], std::chrono::seconds(0));
if (json[P_START].IsBool() ? json[P_START].As<bool>() : json[P_START].As<std::string>() == "t")
workflow_.startWorkflow(std::move(vstream_key), duration);
else
workflow_.stopWorkflow(std::move(vstream_key), false);
}
void Api::doorIsOpen(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
auto vstream_key = absl::Substitute("$0_$1", id_group, convertToString(json[P_STREAM_ID]));
workflow_.stopWorkflow(std::move(vstream_key), false);
}
userver::formats::json::Value Api::bestQuality(const int32_t id_group, const userver::formats::json::Value& json) const
{
const auto id_log = convertToInt<int32_t>(json[P_LOG_EVENT_ID]);
if (!(id_log || (json.HasMember(P_STREAM_ID) && !json[P_STREAM_ID].IsNull() && json.HasMember(P_DATE) && !json[P_DATE].IsNull())))
throw userver::server::handlers::ClientError(ExternalBody{absl::Substitute("Required members `$0` or `$1` and `$2` not found or invalid.",
P_LOG_EVENT_ID, P_STREAM_ID, P_DATE)});
std::string vstream_key;
if (json.HasMember(P_STREAM_ID) && !json[P_STREAM_ID].IsNull())
vstream_key = absl::Substitute("$0_$1", id_group, convertToString(json[P_STREAM_ID]));
const auto ext_event_uuid = json[P_EVENT_UUID].As<std::string>("");
int32_t id_vstream{};
std::chrono::milliseconds interval_before{};
std::chrono::milliseconds interval_after{};
bool do_copy_event_data = false;
// scope for accessing cache
{
if (const auto cache = config_cache_.Get(); cache->getCommonConfig().contains(id_group))
do_copy_event_data = cache->getCommonConfig().at(id_group).flag_copy_event_data;
}
if (!id_log)
{
const auto cache = vstreams_config_cache_.Get();
if (!cache->getData().contains(vstream_key))
return {};
id_vstream = getVStreamId(id_group, convertToString(json[P_STREAM_ID]));
interval_before = cache->getData().at(vstream_key).best_quality_interval_before;
interval_after = cache->getData().at(vstream_key).best_quality_interval_after;
}
try
{
const auto result = id_log
? pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_GET_LOG_FACE_BY_ID, id_group, id_log.value())
: pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster,
SQL_GET_LOG_FACE_BEST_QUALITY,
id_vstream,
json[P_DATE].As<std::string>(),
interval_before.count(),
interval_after.count());
if (!result.IsEmpty())
{
userver::formats::json::ValueBuilder event_data;
event_data[Api::P_SCREENSHOT_URL] = result[0][DatabaseFields::SCREENSHOT_URL].As<std::string>();
event_data[Api::P_FACE_LEFT] = result[0][DatabaseFields::FACE_LEFT].As<int32_t>();
event_data[Api::P_FACE_TOP] = result[0][DatabaseFields::FACE_TOP].As<int32_t>();
event_data[Api::P_FACE_WIDTH] = result[0][DatabaseFields::FACE_WIDTH].As<int32_t>();
event_data[Api::P_FACE_HEIGHT] = result[0][DatabaseFields::FACE_HEIGHT].As<int32_t>();
const auto id_event_log = result[0][DatabaseFields::ID_LOG].As<int32_t>();
// schedule copy event data
if (const auto copy_event_data = result[0][DatabaseFields::COPY_EVENT_DATA].As<int16_t>(); do_copy_event_data && (copy_event_data == CopyEventData::NONE) && !ext_event_uuid.empty())
pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_SET_COPY_DATA_BY_ID,
static_cast<int16_t>(CopyEventData::SCHEDULED), ext_event_uuid, id_event_log);
return event_data.ExtractValue();
}
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
return {};
}
void Api::addFaces(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
requireArrayThrow(json, P_FACE_IDS);
std::vector<int32_t> faces;
if (json.HasMember(P_FACE_IDS))
try
{
for (const auto& item : json[P_FACE_IDS].As<std::vector<userver::formats::json::Value>>())
{
if (auto id_d = convertToNumber<int32_t>(item, 0); id_d > 0)
faces.emplace_back(id_d);
}
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
if (const auto id_vstream = getVStreamId(id_group, convertToString(json[P_STREAM_ID])); !faces.empty() && id_vstream > 0)
{
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
// bind faces to a video stream
for (const auto& id_descriptor : faces)
trx.Execute(SQL_ADD_LINK_DESCRIPTOR_VSTREAM, id_group, id_vstream, id_descriptor);
trx.Commit();
} catch (const std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
}
}
void Api::removeFaces(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
requireArrayThrow(json, P_FACE_IDS);
std::vector<int32_t> faces;
if (json.HasMember(P_FACE_IDS))
try
{
for (const auto& item : json[P_FACE_IDS].As<std::vector<userver::formats::json::Value>>())
{
if (auto id_d = convertToNumber<int32_t>(item, 0); id_d > 0)
faces.emplace_back(id_d);
}
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
if (const auto id_vstream = getVStreamId(id_group, convertToString(json[P_STREAM_ID])); !faces.empty() && id_vstream > 0)
{
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
// unbind faces from the video stream: we don't delete rows from a database right now, just mark them to delete later
for (const auto& id_descriptor : faces)
trx.Execute(SQL_REMOVE_LINK_DESCRIPTOR_VSTREAM, id_vstream, id_descriptor);
trx.Commit();
} catch (const std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
}
}
void Api::removeVStream(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
const auto id_vstream = getVStreamId(id_group, convertToString(json[P_STREAM_ID]));
if (id_vstream <= 0)
return;
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
trx.Execute(SQL_REMOVE_LINK_DESCRIPTOR_VSTREAM_BY_VSTREAM, id_vstream);
trx.Execute(SQL_DELETE_VIDEO_STREAM, id_group, id_vstream);
trx.Commit();
} catch (const std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
}
userver::formats::json::Value Api::listAllFaces(const int32_t id_group) const
{
userver::formats::json::ValueBuilder data;
try
{
for (const auto result = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_LIST_ALL_FACES, id_group); const auto& row : result)
data.PushBack(row[DatabaseFields::ID_DESCRIPTOR].As<int32_t>());
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
return data.ExtractValue();
}
userver::formats::json::Value Api::clusterFacesBySimilarity(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireArrayThrow(json, P_FACE_IDS);
requireMemberThrow(json, P_SIMILARITY);
const auto similarity_threshold = convertToNumber<float>(json[P_SIMILARITY], std::numeric_limits<float>::quiet_NaN());
if (similarity_threshold < -1.0f || similarity_threshold > 1.0f || std::isnan(similarity_threshold))
{
throw userver::server::handlers::ClientError(ExternalBody{
absl::Substitute("Member `$0` must be a number within the range [-1.0, 1.0].", P_SIMILARITY)});
}
std::vector<int32_t> faces;
if (json.HasMember(P_FACE_IDS))
try
{
HashSet<int32_t> seen;
for (const auto& item : json[P_FACE_IDS].As<std::vector<userver::formats::json::Value>>())
if (auto id_d = convertToNumber<int32_t>(item, 0); id_d > 0)
if (seen.insert(id_d).second)
faces.emplace_back(id_d);
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
if (faces.empty())
return userver::formats::json::MakeArray();
HashMap<int32_t, DescriptorData> descriptors;
try
{
for (const auto result = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster, SQL_GET_DESCRIPTORS, id_group, faces); const auto& row : result)
{
auto id_descriptor = row[DatabaseFields::ID_DESCRIPTOR].As<int32_t>();
std::string descriptor_data;
row[DatabaseFields::DESCRIPTOR_DATA].To(userver::storages::postgres::Bytea(descriptor_data));
descriptors[id_descriptor] = {};
std::memmove(descriptors[id_descriptor].data, descriptor_data.data(), descriptor_data.size());
}
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
std::vector<int32_t> available_faces;
for (auto id : faces)
{
if (descriptors.contains(id))
available_faces.emplace_back(id);
}
// cluster faces by similarity using BFS in the similarity graph connected components
const int n = static_cast<int>(available_faces.size());
std::vector<std::vector<int>> adj(n);
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
{
if (cosineSimilaritySIMD(descriptors[available_faces[i]].data, descriptors[available_faces[j]].data) >= similarity_threshold)
{
adj[i].push_back(j);
adj[j].push_back(i);
}
}
std::vector visited(n, false);
userver::formats::json::ValueBuilder data;
for (int i = 0; i < n; ++i)
{
if (!visited[i])
{
std::vector<int32_t> component;
std::vector<int> q;
q.push_back(i);
visited[i] = true;
int head = 0;
while (head < static_cast<int>(q.size()))
{
const int u = q[head++];
component.push_back(available_faces[u]);
for (int v : adj[u])
{
if (!visited[v])
{
visited[v] = true;
q.push_back(v);
}
}
}
data.PushBack(component);
}
}
return data.ExtractValue();
}
void Api::deleteFaces(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireArrayThrow(json, P_FACE_IDS);
std::vector<int32_t> faces;
if (json.HasMember(P_FACE_IDS))
try
{
for (const auto& item : json[P_FACE_IDS].As<std::vector<userver::formats::json::Value>>())
{
if (auto id_d = convertToNumber<int32_t>(item, 0); id_d > 0)
faces.emplace_back(id_d);
}
} catch (const std::exception& e)
{
throw userver::server::handlers::ClientError(ExternalBody{e.what()});
}
if (!faces.empty())
{
auto trx = pg_cluster_->Begin(userver::storages::postgres::ClusterHostType::kMaster, {});
try
{
for (const auto& id_descriptor : faces)
{
// unbind faces from all video streams: we don't delete rows from a database right now, just mark them to delete later
trx.Execute(SQL_REMOVE_LINK_DESCRIPTOR_VSTREAM_BY_DESCRIPTOR, id_group, id_descriptor);
// do not delete descriptor from a database, just mark for deletion
trx.Execute(SQL_REMOVE_DESCRIPTOR, id_group, id_descriptor);
// do not delete spawned descriptors from a database, just mark for deletion
trx.Execute(SQL_REMOVE_SPAWNED_DESCRIPTORS, id_group, id_descriptor);
}
trx.Commit();
} catch (const std::exception& e)
{
trx.Rollback();
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
}
}
userver::formats::json::Value Api::getEvents(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
requireMemberThrow(json, P_DATE_START);
requireMemberThrow(json, P_DATE_END);
const auto id_vstream = getVStreamId(id_group, convertToString(json[P_STREAM_ID]));
userver::formats::json::ValueBuilder data;
try
{
const auto result = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kMaster,
SQL_GET_LOG_FACES_FROM_INTERVAL,
id_vstream,
json[P_DATE_START].As<std::string>(),
json[P_DATE_END].As<std::string>());
for (const auto& row : result)
{
userver::formats::json::ValueBuilder v;
v[P_DATE] = row[DatabaseFields::LOG_DATE].As<userver::storages::postgres::TimePointTz>();
if (!row[DatabaseFields::ID_DESCRIPTOR].IsNull())
v[P_FACE_ID] = row[DatabaseFields::ID_DESCRIPTOR].As<int32_t>();
v[P_QUALITY] = row[DatabaseFields::QUALITY].As<double>();
v[P_SCREENSHOT_URL] = row[DatabaseFields::SCREENSHOT_URL].As<std::string>();
v[P_FACE_LEFT] = row[DatabaseFields::FACE_LEFT].As<int32_t>();
v[P_FACE_TOP] = row[DatabaseFields::FACE_TOP].As<int32_t>();
v[P_FACE_WIDTH] = row[DatabaseFields::FACE_WIDTH].As<int32_t>();
v[P_FACE_HEIGHT] = row[DatabaseFields::FACE_HEIGHT].As<int32_t>();
data.PushBack(std::move(v));
}
} catch (const std::exception& e)
{
LOG_ERROR_TO(workflow_.getLogger()) << e.what();
throw userver::server::handlers::ClientError(HandlerErrorCode::kServerSideError);
}
return data.ExtractValue();
}
userver::formats::json::Value Api::registerFace(const int32_t id_group, const userver::formats::json::Value& json) const
{
requireMemberThrow(json, P_STREAM_ID);
requireMemberThrow(json, P_URL);
auto vstream_key = absl::Substitute("$0_$1", id_group, convertToString(json[P_STREAM_ID]));
TaskData task_data{
.id_group = id_group,
.vstream_key = std::move(vstream_key),
.task_type = TaskType::TASK_REGISTER_DESCRIPTOR,
.frame_url = json[P_URL].As<std::string>()};
task_data.face_left = json[P_FACE_LEFT].As<int>(0);
task_data.face_top = json[P_FACE_TOP].As<int>(0);
task_data.face_width = json[P_FACE_WIDTH].As<int>(0);
task_data.face_height = json[P_FACE_HEIGHT].As<int>(0);
auto [id_descriptor, comments, face_image, face_left, face_top, face_width, face_height, id_descriptors] = workflow_.processPipeline(std::move(task_data));
userver::formats::json::ValueBuilder data;
if (id_descriptor > 0)
{
std::vector<uchar> buff;
imencode(".jpg", face_image, buff);
data[P_FACE_ID] = id_descriptor;
data[P_FACE_LEFT] = face_left;
data[P_FACE_TOP] = face_top;
data[P_FACE_WIDTH] = face_width;
data[P_FACE_HEIGHT] = face_height;
data[P_FACE_IMAGE] = absl::Substitute("data:$0;base64,$1", Workflow::MIME_IMAGE,
absl::Base64Escape(std::string(reinterpret_cast<const char*>(buff.data()), buff.size())));
} else
throw userver::server::handlers::ClientError(ExternalBody{comments});