forked from opensensor/lightNVR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_recordings.c
More file actions
2215 lines (1818 loc) · 82.8 KB
/
db_recordings.c
File metadata and controls
2215 lines (1818 loc) · 82.8 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
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include <sqlite3.h>
#include <stdbool.h>
#include "database/db_recordings.h"
#include "database/db_core.h"
#include "core/logger.h"
#define MAX_MULTI_FILTER_VALUES 32
#define MAX_MULTI_FILTER_VALUE_LEN 128
static void trim_whitespace(char *value) {
if (!value) {
return;
}
char *start = value;
while (*start && isspace((unsigned char)*start)) {
start++;
}
if (start != value) {
memmove(value, start, strlen(start) + 1);
}
size_t len = strlen(value);
while (len > 0 && isspace((unsigned char)value[len - 1])) {
value[--len] = '\0';
}
}
static int parse_csv_filter_values(const char *csv,
char values[][MAX_MULTI_FILTER_VALUE_LEN],
int max_values) {
if (!csv || !*csv || max_values <= 0) {
return 0;
}
char buffer[MAX_MULTI_FILTER_VALUES * MAX_MULTI_FILTER_VALUE_LEN];
strncpy(buffer, csv, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0';
int count = 0;
char *saveptr = NULL;
char *token = strtok_r(buffer, ",", &saveptr);
while (token && count < max_values) {
trim_whitespace(token);
if (*token) {
bool duplicate = false;
for (int i = 0; i < count; i++) {
if (strcmp(values[i], token) == 0) {
duplicate = true;
break;
}
}
if (!duplicate) {
strncpy(values[count], token, MAX_MULTI_FILTER_VALUE_LEN - 1);
values[count][MAX_MULTI_FILTER_VALUE_LEN - 1] = '\0';
count++;
}
}
token = strtok_r(NULL, ",", &saveptr);
}
return count;
}
// Add recording metadata to the database
uint64_t add_recording_metadata(const recording_metadata_t *metadata) {
int rc;
sqlite3_stmt *stmt;
uint64_t recording_id = 0;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return 0;
}
if (!metadata) {
log_error("Recording metadata is required");
return 0;
}
pthread_mutex_lock(db_mutex);
const char *sql = "INSERT INTO recordings (stream_name, file_path, start_time, end_time, "
"size_bytes, width, height, fps, codec, is_complete, trigger_type, "
"retention_tier, disk_pressure_eligible) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return 0;
}
// No longer tracking statements - each function is responsible for finalizing its own statements
// Bind parameters
sqlite3_bind_text(stmt, 1, metadata->stream_name, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, metadata->file_path, -1, SQLITE_STATIC);
sqlite3_bind_int64(stmt, 3, (sqlite3_int64)metadata->start_time);
if (metadata->end_time > 0) {
sqlite3_bind_int64(stmt, 4, (sqlite3_int64)metadata->end_time);
} else {
sqlite3_bind_null(stmt, 4);
}
sqlite3_bind_int64(stmt, 5, (sqlite3_int64)metadata->size_bytes);
sqlite3_bind_int(stmt, 6, metadata->width);
sqlite3_bind_int(stmt, 7, metadata->height);
sqlite3_bind_int(stmt, 8, metadata->fps);
sqlite3_bind_text(stmt, 9, metadata->codec, -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 10, metadata->is_complete ? 1 : 0);
// Bind trigger_type, default to 'scheduled' if not set
const char *trigger_type = (metadata->trigger_type[0] != '\0') ? metadata->trigger_type : "scheduled";
sqlite3_bind_text(stmt, 11, trigger_type, -1, SQLITE_STATIC);
// Bind retention tier and disk pressure eligibility
sqlite3_bind_int(stmt, 12, metadata->retention_tier);
sqlite3_bind_int(stmt, 13, metadata->disk_pressure_eligible ? 1 : 0);
// Execute statement
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
log_error("Failed to add recording metadata: %s", sqlite3_errmsg(db));
} else {
recording_id = (uint64_t)sqlite3_last_insert_rowid(db);
log_debug("Added recording metadata with ID %llu", (unsigned long long)recording_id);
}
// Finalize the prepared statement
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return recording_id;
}
// Update recording metadata in the database
int update_recording_metadata(uint64_t id, time_t end_time,
uint64_t size_bytes, bool is_complete) {
int rc;
sqlite3_stmt *stmt;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
pthread_mutex_lock(db_mutex);
const char *sql = "UPDATE recordings SET end_time = ?, size_bytes = ?, is_complete = ? "
"WHERE id = ?;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
// No longer tracking statements - each function is responsible for finalizing its own statements
// Bind parameters
sqlite3_bind_int64(stmt, 1, (sqlite3_int64)end_time);
sqlite3_bind_int64(stmt, 2, (sqlite3_int64)size_bytes);
sqlite3_bind_int(stmt, 3, is_complete ? 1 : 0);
sqlite3_bind_int64(stmt, 4, (sqlite3_int64)id);
// Execute statement
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
log_error("Failed to update recording metadata: %s", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return -1;
}
// Finalize the prepared statement
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return 0;
}
/**
* Correct the start_time of an existing recording in the database.
*
* Used after flushing the pre-event circular buffer into a detection recording
* so that the stored start_time matches the actual first packet timestamp
* rather than the time mp4_writer_create() was called.
*/
int update_recording_start_time(uint64_t id, time_t start_time) {
int rc;
sqlite3_stmt *stmt;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
pthread_mutex_lock(db_mutex);
const char *sql = "UPDATE recordings SET start_time = ? WHERE id = ?;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare update_recording_start_time statement: %s",
sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
sqlite3_bind_int64(stmt, 1, (sqlite3_int64)start_time);
sqlite3_bind_int64(stmt, 2, (sqlite3_int64)id);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
log_error("Failed to update recording start_time (id=%llu): %s",
(unsigned long long)id, sqlite3_errmsg(db));
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return -1;
}
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
log_debug("Corrected start_time for recording ID %llu to %ld",
(unsigned long long)id, (long)start_time);
return 0;
}
// Get recording metadata by ID
int get_recording_metadata_by_id(uint64_t id, recording_metadata_t *metadata) {
int rc;
sqlite3_stmt *stmt;
int result = -1;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
if (!metadata) {
log_error("Invalid parameters for get_recording_metadata_by_id");
return -1;
}
pthread_mutex_lock(db_mutex);
const char *sql = "SELECT id, stream_name, file_path, start_time, end_time, "
"size_bytes, width, height, fps, codec, is_complete, trigger_type, "
"protected, retention_override_days, retention_tier, disk_pressure_eligible "
"FROM recordings WHERE id = ?;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
// No longer tracking statements - each function is responsible for finalizing its own statements
// Bind parameters
sqlite3_bind_int64(stmt, 1, (sqlite3_int64)id);
// Execute query and fetch result
if (sqlite3_step(stmt) == SQLITE_ROW) {
metadata->id = (uint64_t)sqlite3_column_int64(stmt, 0);
const char *stream = (const char *)sqlite3_column_text(stmt, 1);
if (stream) {
strncpy(metadata->stream_name, stream, sizeof(metadata->stream_name) - 1);
metadata->stream_name[sizeof(metadata->stream_name) - 1] = '\0';
} else {
metadata->stream_name[0] = '\0';
}
const char *path = (const char *)sqlite3_column_text(stmt, 2);
if (path) {
strncpy(metadata->file_path, path, sizeof(metadata->file_path) - 1);
metadata->file_path[sizeof(metadata->file_path) - 1] = '\0';
} else {
metadata->file_path[0] = '\0';
}
metadata->start_time = (time_t)sqlite3_column_int64(stmt, 3);
if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
metadata->end_time = (time_t)sqlite3_column_int64(stmt, 4);
} else {
metadata->end_time = 0;
}
metadata->size_bytes = (uint64_t)sqlite3_column_int64(stmt, 5);
metadata->width = sqlite3_column_int(stmt, 6);
metadata->height = sqlite3_column_int(stmt, 7);
metadata->fps = sqlite3_column_int(stmt, 8);
const char *codec = (const char *)sqlite3_column_text(stmt, 9);
if (codec) {
strncpy(metadata->codec, codec, sizeof(metadata->codec) - 1);
metadata->codec[sizeof(metadata->codec) - 1] = '\0';
} else {
metadata->codec[0] = '\0';
}
metadata->is_complete = sqlite3_column_int(stmt, 10) != 0;
const char *trigger_type = (const char *)sqlite3_column_text(stmt, 11);
if (trigger_type) {
strncpy(metadata->trigger_type, trigger_type, sizeof(metadata->trigger_type) - 1);
metadata->trigger_type[sizeof(metadata->trigger_type) - 1] = '\0';
} else {
strncpy(metadata->trigger_type, "scheduled", sizeof(metadata->trigger_type) - 1);
}
metadata->protected = sqlite3_column_int(stmt, 12) != 0;
if (sqlite3_column_type(stmt, 13) != SQLITE_NULL) {
metadata->retention_override_days = sqlite3_column_int(stmt, 13);
} else {
metadata->retention_override_days = -1;
}
metadata->retention_tier = (sqlite3_column_type(stmt, 14) != SQLITE_NULL)
? sqlite3_column_int(stmt, 14) : RETENTION_TIER_STANDARD;
metadata->disk_pressure_eligible = (sqlite3_column_type(stmt, 15) != SQLITE_NULL)
? (sqlite3_column_int(stmt, 15) != 0) : true;
result = 0; // Success
}
// Finalize the prepared statement
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return result;
}
// Get recording metadata by file path
int get_recording_metadata_by_path(const char *file_path, recording_metadata_t *metadata) {
int rc;
sqlite3_stmt *stmt;
int result = -1;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
if (!file_path || !metadata) {
log_error("Invalid parameters for get_recording_metadata_by_path");
return -1;
}
pthread_mutex_lock(db_mutex);
const char *sql = "SELECT id, stream_name, file_path, start_time, end_time, "
"size_bytes, width, height, fps, codec, is_complete, trigger_type, "
"protected, retention_override_days, retention_tier, disk_pressure_eligible "
"FROM recordings WHERE file_path = ?;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
sqlite3_bind_text(stmt, 1, file_path, -1, SQLITE_STATIC);
if (sqlite3_step(stmt) == SQLITE_ROW) {
metadata->id = (uint64_t)sqlite3_column_int64(stmt, 0);
const char *stream = (const char *)sqlite3_column_text(stmt, 1);
if (stream) {
strncpy(metadata->stream_name, stream, sizeof(metadata->stream_name) - 1);
metadata->stream_name[sizeof(metadata->stream_name) - 1] = '\0';
} else {
metadata->stream_name[0] = '\0';
}
const char *path = (const char *)sqlite3_column_text(stmt, 2);
if (path) {
strncpy(metadata->file_path, path, sizeof(metadata->file_path) - 1);
metadata->file_path[sizeof(metadata->file_path) - 1] = '\0';
} else {
metadata->file_path[0] = '\0';
}
metadata->start_time = (time_t)sqlite3_column_int64(stmt, 3);
if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
metadata->end_time = (time_t)sqlite3_column_int64(stmt, 4);
} else {
metadata->end_time = 0;
}
metadata->size_bytes = (uint64_t)sqlite3_column_int64(stmt, 5);
metadata->width = sqlite3_column_int(stmt, 6);
metadata->height = sqlite3_column_int(stmt, 7);
metadata->fps = sqlite3_column_int(stmt, 8);
const char *codec = (const char *)sqlite3_column_text(stmt, 9);
if (codec) {
strncpy(metadata->codec, codec, sizeof(metadata->codec) - 1);
metadata->codec[sizeof(metadata->codec) - 1] = '\0';
} else {
metadata->codec[0] = '\0';
}
metadata->is_complete = sqlite3_column_int(stmt, 10) != 0;
const char *trigger_type = (const char *)sqlite3_column_text(stmt, 11);
if (trigger_type) {
strncpy(metadata->trigger_type, trigger_type, sizeof(metadata->trigger_type) - 1);
metadata->trigger_type[sizeof(metadata->trigger_type) - 1] = '\0';
} else {
strncpy(metadata->trigger_type, "scheduled", sizeof(metadata->trigger_type) - 1);
}
metadata->protected = sqlite3_column_int(stmt, 12) != 0;
if (sqlite3_column_type(stmt, 13) != SQLITE_NULL) {
metadata->retention_override_days = sqlite3_column_int(stmt, 13);
} else {
metadata->retention_override_days = -1;
}
metadata->retention_tier = (sqlite3_column_type(stmt, 14) != SQLITE_NULL)
? sqlite3_column_int(stmt, 14) : RETENTION_TIER_STANDARD;
metadata->disk_pressure_eligible = (sqlite3_column_type(stmt, 15) != SQLITE_NULL)
? (sqlite3_column_int(stmt, 15) != 0) : true;
result = 0; // Success
}
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
return result;
}
// Get recording metadata from the database
int get_recording_metadata(time_t start_time, time_t end_time,
const char *stream_name, recording_metadata_t *metadata,
int max_count) {
int rc;
sqlite3_stmt *stmt;
int count = 0;
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
if (!metadata || max_count <= 0) {
log_error("Invalid parameters for get_recording_metadata");
return -1;
}
pthread_mutex_lock(db_mutex);
// Build query based on filters
char sql[1024];
snprintf(sql, sizeof(sql), "SELECT id, stream_name, file_path, start_time, end_time, "
"size_bytes, width, height, fps, codec, is_complete, trigger_type, "
"protected, retention_override_days, retention_tier, disk_pressure_eligible "
"FROM recordings WHERE is_complete = 1 AND end_time IS NOT NULL"); // Only complete recordings with end_time set
if (start_time > 0) {
strncat(sql, " AND start_time >= ?", sizeof(sql) - strlen(sql) - 1);
}
if (end_time > 0) {
strncat(sql, " AND start_time <= ?", sizeof(sql) - strlen(sql) - 1);
}
if (stream_name) {
strncat(sql, " AND stream_name = ?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, " ORDER BY start_time DESC LIMIT ?;", sizeof(sql) - strlen(sql) - 1);
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
// No longer tracking statements - each function is responsible for finalizing its own statements
// Bind parameters
int param_index = 1;
if (start_time > 0) {
sqlite3_bind_int64(stmt, param_index++, (sqlite3_int64)start_time);
}
if (end_time > 0) {
sqlite3_bind_int64(stmt, param_index++, (sqlite3_int64)end_time);
}
if (stream_name) {
sqlite3_bind_text(stmt, param_index++, stream_name, -1, SQLITE_STATIC);
}
sqlite3_bind_int(stmt, param_index, max_count);
// Execute query and fetch results
int rc_step;
while ((rc_step = sqlite3_step(stmt)) == SQLITE_ROW && count < max_count) {
// Safely copy data to metadata structure
{
metadata[count].id = (uint64_t)sqlite3_column_int64(stmt, 0);
const char *stream = (const char *)sqlite3_column_text(stmt, 1);
if (stream) {
strncpy(metadata[count].stream_name, stream, sizeof(metadata[count].stream_name) - 1);
metadata[count].stream_name[sizeof(metadata[count].stream_name) - 1] = '\0';
} else {
metadata[count].stream_name[0] = '\0';
}
const char *path = (const char *)sqlite3_column_text(stmt, 2);
if (path) {
strncpy(metadata[count].file_path, path, sizeof(metadata[count].file_path) - 1);
metadata[count].file_path[sizeof(metadata[count].file_path) - 1] = '\0';
} else {
metadata[count].file_path[0] = '\0';
}
metadata[count].start_time = (time_t)sqlite3_column_int64(stmt, 3);
if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
metadata[count].end_time = (time_t)sqlite3_column_int64(stmt, 4);
} else {
metadata[count].end_time = 0;
}
metadata[count].size_bytes = (uint64_t)sqlite3_column_int64(stmt, 5);
metadata[count].width = sqlite3_column_int(stmt, 6);
metadata[count].height = sqlite3_column_int(stmt, 7);
metadata[count].fps = sqlite3_column_int(stmt, 8);
const char *codec = (const char *)sqlite3_column_text(stmt, 9);
if (codec) {
strncpy(metadata[count].codec, codec, sizeof(metadata[count].codec) - 1);
metadata[count].codec[sizeof(metadata[count].codec) - 1] = '\0';
} else {
metadata[count].codec[0] = '\0';
}
metadata[count].is_complete = sqlite3_column_int(stmt, 10) != 0;
const char *trigger_type = (const char *)sqlite3_column_text(stmt, 11);
if (trigger_type) {
strncpy(metadata[count].trigger_type, trigger_type, sizeof(metadata[count].trigger_type) - 1);
metadata[count].trigger_type[sizeof(metadata[count].trigger_type) - 1] = '\0';
} else {
strncpy(metadata[count].trigger_type, "scheduled", sizeof(metadata[count].trigger_type) - 1);
}
metadata[count].protected = sqlite3_column_int(stmt, 12) != 0;
if (sqlite3_column_type(stmt, 13) != SQLITE_NULL) {
metadata[count].retention_override_days = sqlite3_column_int(stmt, 13);
} else {
metadata[count].retention_override_days = -1;
}
metadata[count].retention_tier = (sqlite3_column_type(stmt, 14) != SQLITE_NULL)
? sqlite3_column_int(stmt, 14) : RETENTION_TIER_STANDARD;
metadata[count].disk_pressure_eligible = (sqlite3_column_type(stmt, 15) != SQLITE_NULL)
? (sqlite3_column_int(stmt, 15) != 0) : true;
count++;
}
}
if (rc_step != SQLITE_DONE && rc_step != SQLITE_ROW) {
log_error("Error while fetching recordings: %s", sqlite3_errmsg(db));
}
// Finalize the prepared statement
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
log_info("Found %d recordings in database matching criteria", count);
return count;
}
// Get total count of recordings matching filter criteria
int get_recording_count(time_t start_time, time_t end_time,
const char *stream_name, int has_detection,
const char *detection_label, int protected_filter,
const char * const *allowed_streams, int allowed_streams_count,
const char *tag_filter, const char *capture_method_filter) {
int rc;
sqlite3_stmt *stmt;
int count = 0;
char stream_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char detection_label_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char tag_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char capture_method_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
int stream_filter_count = parse_csv_filter_values(stream_name, stream_filters, MAX_MULTI_FILTER_VALUES);
int detection_label_count = parse_csv_filter_values(detection_label, detection_label_filters, MAX_MULTI_FILTER_VALUES);
int tag_filter_count = parse_csv_filter_values(tag_filter, tag_filters, MAX_MULTI_FILTER_VALUES);
int capture_method_count = parse_csv_filter_values(capture_method_filter, capture_method_filters, MAX_MULTI_FILTER_VALUES);
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
pthread_mutex_lock(db_mutex);
// Build query based on filters
char sql[8192];
// Use trigger_type and/or detections table to filter detection-based recordings
snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM recordings r WHERE r.is_complete = 1 AND r.end_time IS NOT NULL");
if (has_detection == 1) {
// Filter by trigger_type = 'detection' OR existence of linked detections via recording_id (fast index lookup)
// Falls back to timestamp range scan for legacy detections without recording_id
strncat(sql, " AND (r.trigger_type = 'detection'"
" OR EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id)"
" OR EXISTS (SELECT 1 FROM detections d WHERE d.stream_name = r.stream_name"
" AND d.timestamp >= r.start_time AND d.timestamp <= r.end_time))",
sizeof(sql) - strlen(sql) - 1);
log_debug("Adding detection filter (trigger_type OR recording_id OR timestamp range)");
} else if (has_detection == -1) {
// Filter to recordings with NO detections
strncat(sql, " AND (r.trigger_type != 'detection' OR r.trigger_type IS NULL)"
" AND NOT EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id)"
" AND NOT EXISTS (SELECT 1 FROM detections d WHERE d.stream_name = r.stream_name"
" AND d.timestamp >= r.start_time AND d.timestamp <= r.end_time)",
sizeof(sql) - strlen(sql) - 1);
log_debug("Adding no-detection filter (no trigger_type AND no linked detections)");
}
if (detection_label_count > 0) {
// Filter by specific detection label - prefer recording_id FK lookup, fall back to timestamp range
strncat(sql, " AND (EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id AND (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < detection_label_count; i++) {
if (i > 0) strncat(sql, " OR ", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "d.label LIKE ?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")) OR EXISTS (SELECT 1 FROM detections d WHERE d.recording_id IS NULL"
" AND d.stream_name = r.stream_name AND d.timestamp >= r.start_time"
" AND d.timestamp <= r.end_time AND (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < detection_label_count; i++) {
if (i > 0) strncat(sql, " OR ", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "d.label LIKE ?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")))", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding %d detection_label filters", detection_label_count);
}
if (start_time > 0) {
strncat(sql, " AND r.start_time >= ?", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding start_time filter: %ld", (long)start_time);
}
if (end_time > 0) {
strncat(sql, " AND r.start_time <= ?", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding end_time filter: %ld", (long)end_time);
}
if (stream_filter_count > 0) {
strncat(sql, " AND r.stream_name IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < stream_filter_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
} else if (allowed_streams && allowed_streams_count > 0) {
// Tag-based RBAC: restrict to the user's whitelisted streams via IN clause
strncat(sql, " AND r.stream_name IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < allowed_streams_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding allowed_streams IN filter (%d streams)", allowed_streams_count);
}
if (protected_filter == 0) {
strncat(sql, " AND r.protected = 0", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding protected_filter=0 (unprotected only)");
} else if (protected_filter == 1) {
strncat(sql, " AND r.protected = 1", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding protected_filter=1 (protected only)");
}
if (tag_filter_count > 0) {
strncat(sql, " AND EXISTS (SELECT 1 FROM recording_tags rt WHERE rt.recording_id = r.id AND rt.tag IN (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < tag_filter_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, "))", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding %d tag filters", tag_filter_count);
}
if (capture_method_count > 0) {
strncat(sql, " AND COALESCE(r.trigger_type, 'scheduled') IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < capture_method_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding %d capture_method filters", capture_method_count);
}
log_debug("SQL query for get_recording_count: %s", sql);
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
log_error("Failed to prepare statement: %s", sqlite3_errmsg(db));
pthread_mutex_unlock(db_mutex);
return -1;
}
// No longer tracking statements - each function is responsible for finalizing its own statements
// Bind parameters
int param_index = 1;
if (detection_label_count > 0) {
for (int i = 0; i < detection_label_count; i++) {
char label_pattern[MAX_MULTI_FILTER_VALUE_LEN + 2];
snprintf(label_pattern, sizeof(label_pattern), "%%%s%%", detection_label_filters[i]);
sqlite3_bind_text(stmt, param_index++, label_pattern, -1, SQLITE_TRANSIENT);
}
for (int i = 0; i < detection_label_count; i++) {
char label_pattern[MAX_MULTI_FILTER_VALUE_LEN + 2];
snprintf(label_pattern, sizeof(label_pattern), "%%%s%%", detection_label_filters[i]);
sqlite3_bind_text(stmt, param_index++, label_pattern, -1, SQLITE_TRANSIENT);
}
}
if (start_time > 0) {
sqlite3_bind_int64(stmt, param_index++, (sqlite3_int64)start_time);
}
if (end_time > 0) {
sqlite3_bind_int64(stmt, param_index++, (sqlite3_int64)end_time);
}
if (stream_filter_count > 0) {
for (int i = 0; i < stream_filter_count; i++) {
sqlite3_bind_text(stmt, param_index++, stream_filters[i], -1, SQLITE_TRANSIENT);
}
} else if (allowed_streams && allowed_streams_count > 0) {
for (int i = 0; i < allowed_streams_count; i++) {
sqlite3_bind_text(stmt, param_index++, allowed_streams[i], -1, SQLITE_STATIC);
}
}
for (int i = 0; i < tag_filter_count; i++) {
sqlite3_bind_text(stmt, param_index++, tag_filters[i], -1, SQLITE_TRANSIENT);
}
for (int i = 0; i < capture_method_count; i++) {
sqlite3_bind_text(stmt, param_index++, capture_method_filters[i], -1, SQLITE_TRANSIENT);
}
// Execute query and get count
if (sqlite3_step(stmt) == SQLITE_ROW) {
count = sqlite3_column_int(stmt, 0);
} else {
log_error("Error while getting recording count: %s", sqlite3_errmsg(db));
count = -1;
}
// Finalize the prepared statement
sqlite3_finalize(stmt);
pthread_mutex_unlock(db_mutex);
log_debug("Total count of recordings matching criteria: %d", count);
return count;
}
// Get paginated recording metadata from the database with sorting
int get_recording_metadata_paginated(time_t start_time, time_t end_time,
const char *stream_name, int has_detection,
const char *detection_label,
int protected_filter,
const char *sort_field, const char *sort_order,
recording_metadata_t *metadata,
int limit, int offset,
const char * const *allowed_streams, int allowed_streams_count,
const char *tag_filter, const char *capture_method_filter) {
int rc;
sqlite3_stmt *stmt;
int count = 0;
char stream_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char detection_label_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char tag_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
char capture_method_filters[MAX_MULTI_FILTER_VALUES][MAX_MULTI_FILTER_VALUE_LEN] = {{0}};
int stream_filter_count = parse_csv_filter_values(stream_name, stream_filters, MAX_MULTI_FILTER_VALUES);
int detection_label_count = parse_csv_filter_values(detection_label, detection_label_filters, MAX_MULTI_FILTER_VALUES);
int tag_filter_count = parse_csv_filter_values(tag_filter, tag_filters, MAX_MULTI_FILTER_VALUES);
int capture_method_count = parse_csv_filter_values(capture_method_filter, capture_method_filters, MAX_MULTI_FILTER_VALUES);
sqlite3 *db = get_db_handle();
pthread_mutex_t *db_mutex = get_db_mutex();
if (!db) {
log_error("Database not initialized");
return -1;
}
if (!metadata || limit <= 0) {
log_error("Invalid parameters for get_recording_metadata_paginated");
return -1;
}
pthread_mutex_lock(db_mutex);
// Validate and sanitize sort field to prevent SQL injection
char safe_sort_field[32] = "start_time"; // Default sort field
if (sort_field) {
if (strcmp(sort_field, "id") == 0 ||
strcmp(sort_field, "stream_name") == 0 ||
strcmp(sort_field, "start_time") == 0 ||
strcmp(sort_field, "end_time") == 0 ||
strcmp(sort_field, "size_bytes") == 0) {
strncpy(safe_sort_field, sort_field, sizeof(safe_sort_field) - 1);
safe_sort_field[sizeof(safe_sort_field) - 1] = '\0';
} else {
log_warn("Invalid sort field: %s, using default", sort_field);
}
}
// Validate sort order
char safe_sort_order[8] = "DESC"; // Default sort order
if (sort_order) {
if (strcasecmp(sort_order, "asc") == 0) {
strcpy(safe_sort_order, "ASC");
} else if (strcasecmp(sort_order, "desc") == 0) {
strcpy(safe_sort_order, "DESC");
} else {
log_warn("Invalid sort order: %s, using default", sort_order);
}
}
// Build query based on filters
char sql[8192];
// Use trigger_type and/or detections table to filter detection-based recordings
snprintf(sql, sizeof(sql),
"SELECT r.id, r.stream_name, r.file_path, r.start_time, r.end_time, "
"r.size_bytes, r.width, r.height, r.fps, r.codec, r.is_complete, r.trigger_type, "
"r.protected, r.retention_override_days, r.retention_tier, r.disk_pressure_eligible "
"FROM recordings r WHERE r.is_complete = 1 AND r.end_time IS NOT NULL");
if (has_detection == 1) {
// Filter by trigger_type = 'detection' OR existence of linked detections via recording_id (fast index lookup)
// Falls back to timestamp range scan for legacy detections without recording_id
strncat(sql, " AND (r.trigger_type = 'detection'"
" OR EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id)"
" OR EXISTS (SELECT 1 FROM detections d WHERE d.stream_name = r.stream_name"
" AND d.timestamp >= r.start_time AND d.timestamp <= r.end_time))",
sizeof(sql) - strlen(sql) - 1);
log_info("Adding detection filter (trigger_type OR recording_id OR timestamp range)");
} else if (has_detection == -1) {
// Filter to recordings with NO detections
strncat(sql, " AND (r.trigger_type != 'detection' OR r.trigger_type IS NULL)"
" AND NOT EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id)"
" AND NOT EXISTS (SELECT 1 FROM detections d WHERE d.stream_name = r.stream_name"
" AND d.timestamp >= r.start_time AND d.timestamp <= r.end_time)",
sizeof(sql) - strlen(sql) - 1);
log_info("Adding no-detection filter (no trigger_type AND no linked detections)");
}
if (detection_label_count > 0) {
// Filter by specific detection label - prefer recording_id FK lookup, fall back to timestamp range
strncat(sql, " AND (EXISTS (SELECT 1 FROM detections d WHERE d.recording_id = r.id AND (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < detection_label_count; i++) {
if (i > 0) strncat(sql, " OR ", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "d.label LIKE ?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")) OR EXISTS (SELECT 1 FROM detections d WHERE d.recording_id IS NULL"
" AND d.stream_name = r.stream_name AND d.timestamp >= r.start_time"
" AND d.timestamp <= r.end_time AND (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < detection_label_count; i++) {
if (i > 0) strncat(sql, " OR ", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "d.label LIKE ?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")))", sizeof(sql) - strlen(sql) - 1);
log_info("Adding %d detection_label filters", detection_label_count);
}
if (start_time > 0) {
strncat(sql, " AND r.start_time >= ?", sizeof(sql) - strlen(sql) - 1);
log_info("Adding start_time filter to paginated query: %ld", (long)start_time);
}
if (end_time > 0) {
strncat(sql, " AND r.start_time <= ?", sizeof(sql) - strlen(sql) - 1);
log_info("Adding end_time filter to paginated query: %ld", (long)end_time);
}
if (stream_filter_count > 0) {
strncat(sql, " AND r.stream_name IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < stream_filter_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
} else if (allowed_streams && allowed_streams_count > 0) {
// Tag-based RBAC: restrict to the user's whitelisted streams via IN clause
strncat(sql, " AND r.stream_name IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < allowed_streams_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding allowed_streams IN filter (%d streams) to paginated query", allowed_streams_count);
}
if (protected_filter == 0) {
strncat(sql, " AND r.protected = 0", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding protected_filter=0 (unprotected only) to paginated query");
} else if (protected_filter == 1) {
strncat(sql, " AND r.protected = 1", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding protected_filter=1 (protected only) to paginated query");
}
if (tag_filter_count > 0) {
strncat(sql, " AND EXISTS (SELECT 1 FROM recording_tags rt WHERE rt.recording_id = r.id AND rt.tag IN (",
sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < tag_filter_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, "))", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding %d tag filters to paginated query", tag_filter_count);
}
if (capture_method_count > 0) {
strncat(sql, " AND COALESCE(r.trigger_type, 'scheduled') IN (", sizeof(sql) - strlen(sql) - 1);
for (int i = 0; i < capture_method_count; i++) {
if (i > 0) strncat(sql, ",", sizeof(sql) - strlen(sql) - 1);
strncat(sql, "?", sizeof(sql) - strlen(sql) - 1);
}
strncat(sql, ")", sizeof(sql) - strlen(sql) - 1);
log_debug("Adding %d capture_method filters to paginated query", capture_method_count);
}
// Add ORDER BY clause with sanitized field and order
char order_clause[64];