Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

start folders for days

roryclear41e09d7cf327
diff --git a/clearcam/FileServer.h b/clearcam/FileServer.h
index 384b177..e5b3765 100644
--- a/clearcam/FileServer.h
+++ b/clearcam/FileServer.h
@@ -3,6 +3,6 @@
@interface FileServer : NSObject
- (void)start;
-@property (nonatomic, strong) NSMutableArray *segmentsArray;
+@property (nonatomic, strong) NSMutableDictionary *segmentsDict;
@end
diff --git a/clearcam/FileServer.m b/clearcam/FileServer.m
index 6057793..0814e7d 100644
--- a/clearcam/FileServer.m
+++ b/clearcam/FileServer.m
@@ -18,6 +18,7 @@
- (void)start {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+ self.segmentsDict = [[NSMutableDictionary alloc] init];
self.basePath = [self getDocumentsDirectory];
self.durationCache = [[NSMutableDictionary alloc] init];
[self startHTTPServerWithBasePath:self.basePath];
@@ -85,40 +86,51 @@
if ([filePath isEqualToString:@"/"]) filePath = @"";
if ([filePath hasPrefix:@"get-segments"]) {
- // Extract the query string if present
NSString *startParam = nil;
+ NSString *dateParam = nil;
+
NSRange queryRange = [filePath rangeOfString:@"?"];
if (queryRange.location != NSNotFound) {
NSString *queryString = [filePath substringFromIndex:queryRange.location + 1];
NSArray *queryItems = [queryString componentsSeparatedByString:@"&"];
for (NSString *item in queryItems) {
NSArray *keyValue = [item componentsSeparatedByString:@"="];
- if (keyValue.count == 2 && [keyValue[0] isEqualToString:@"start"]) {
- startParam = keyValue[1];
- break;
+ if (keyValue.count == 2) {
+ if ([keyValue[0] isEqualToString:@"start"]) {
+ startParam = keyValue[1];
+ } else if ([keyValue[0] isEqualToString:@"date"]) {
+ dateParam = keyValue[1];
+ }
}
}
}
- // Default to 0 if "start" is not provided
+ // Default start to 0 if not provided
NSInteger start = startParam ? [startParam integerValue] : 0;
-
+
NSLog(@"START PARAM = %ld", (long)start);
+ NSLog(@"DATE PARAM = %@", dateParam);
+
+ // Validate the date parameter
+ if (!dateParam || !self.segmentsDict[dateParam]) {
+ NSString *httpHeader = @"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n";
+ NSString *errorMessage = @"{\"error\": \"Missing or invalid date parameter\"}";
+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);
+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);
+ return;
+ }
- // Use self.segmentsArray instead of reading from a file
- if (start >= self.segmentsArray.count) {
+ NSArray *segmentsForDate = self.segmentsDict[dateParam];
+ if (start >= segmentsForDate.count) {
NSString *httpHeader = @"HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\n\r\n";
NSString *errorMessage = @"{\"error\": \"Start index is out of range\"}";
send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);
send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);
return;
}
-
- NSArray *slicedSegments = [self.segmentsArray subarrayWithRange:NSMakeRange(start, self.segmentsArray.count - start)];
-
- // Convert the sliced array back to JSON
+ NSArray *slicedSegments = [segmentsForDate subarrayWithRange:NSMakeRange(start, segmentsForDate.count - start)];
NSData *slicedJsonData = [NSJSONSerialization dataWithJSONObject:slicedSegments options:0 error:nil];
-
+
NSString *httpHeader = @"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n";
send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);
send(clientSocket, slicedJsonData.bytes, slicedJsonData.length, 0);
diff --git a/clearcam/ViewController.m b/clearcam/ViewController.m
index f3f8765..37eaa4f 100644
--- a/clearcam/ViewController.m
+++ b/clearcam/ViewController.m
@@ -28,7 +28,6 @@
@property (nonatomic, assign) NSDate *last_file_timestamp;
@property (nonatomic, assign) NSDate *current_file_timestamp;
-
@end
@implementation ViewController
@@ -43,7 +42,6 @@ NSMutableDictionary *classColorMap;
self.seg_number = 0;
self.fileServer = [[FileServer alloc] init];
[self.fileServer start];
- self.fileServer.segmentsArray = [[NSMutableArray alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleDeviceOrientationChange)
@@ -293,44 +291,54 @@ NSMutableDictionary *classColorMap;
[self.videoWriterInput markAsFinished];
[self.assetWriter finishWritingWithCompletionHandler:^{
NSLog(@"Finished recording and saving file");
-
+
NSString *fileName = [self.assetWriter.outputURL lastPathComponent];
NSLog(@"File saved is %@", fileName);
-
+
AVAsset *asset = [AVAsset assetWithURL:self.assetWriter.outputURL];
CMTime time = asset.duration;
-
+
NSString *segmentsFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
stringByAppendingPathComponent:@"segments.txt"];
-
+
+ NSCalendar *calendar = [NSCalendar currentCalendar];
+ NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.current_file_timestamp];
+ NSDate *midnight = [calendar dateFromComponents:components];
+ NSString *dateKey = [NSString stringWithFormat:@"%04ld-%02ld-%02ld", (long)components.year, (long)components.month, (long)components.day];
+
+ if (!self.fileServer.segmentsDict[dateKey]) {
+ self.fileServer.segmentsDict[dateKey] = [NSMutableArray array];
+ }
+
+ NSMutableArray *segmentsForDate = self.fileServer.segmentsDict[dateKey];
+
if (CMTIME_IS_INVALID(self.last_file_duration)) {
self.last_file_duration = time;
self.last_file_url = [self.assetWriter.outputURL copy];
self.last_file_timestamp = self.current_file_timestamp;
} else {
CMTime timeDifference = CMTimeMakeWithSeconds([self.current_file_timestamp timeIntervalSinceDate:self.last_file_timestamp], NSEC_PER_SEC);
-
+
NSMutableDictionary *segmentEntry = [NSMutableDictionary dictionaryWithDictionary:@{
@"url": [NSString stringWithFormat:@"%@/%@", [[self.assetWriter.outputURL URLByDeletingLastPathComponent] lastPathComponent], self.last_file_url.lastPathComponent],
@"duration": @(CMTimeGetSeconds(self.last_file_duration)),
@"timeDifference": @(CMTimeGetSeconds(timeDifference))
}];
-
- if (self.fileServer.segmentsArray.count == 0) {
- NSCalendar *calendar = [NSCalendar currentCalendar];
- NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.current_file_timestamp];
- NSDate *midnight = [calendar dateFromComponents:components];
+
+ // If this is the first entry of the day, store a timestamp relative to midnight
+ if (segmentsForDate.count == 0) {
NSTimeInterval timeStamp = [self.last_file_timestamp timeIntervalSinceDate:midnight];
segmentEntry[@"timeStamp"] = @(timeStamp);
}
-
- [self saveSegmentEntry:segmentEntry toFile:segmentsFilePath]; //not used yet
- [self.fileServer.segmentsArray addObject:segmentEntry];
+
+ [self saveSegmentEntry:segmentEntry toFile:segmentsFilePath]; // Not used yet
+ [segmentsForDate addObject:segmentEntry];
+
self.last_file_duration = time;
self.last_file_url = [self.assetWriter.outputURL copy];
self.last_file_timestamp = self.current_file_timestamp;
}
-
+
NSLog(@"Duration is %f seconds", CMTimeGetSeconds(time));
[self startNewRecording];
}];
diff --git a/clearcam/player.html b/clearcam/player.html
index 1a79013..905f918 100644
--- a/clearcam/player.html
+++ b/clearcam/player.html
@@ -151,7 +151,11 @@
async function fetchSegments() {
try {
const startParam = segments.length;
- const response = await fetch(`/get-segments?start=${startParam}`);
+
+ // Get the current date in YYYY-MM-DD format
+ const currentDate = new Date().toISOString().split('T')[0];
+
+ const response = await fetch(`/get-segments?date=${currentDate}&start=${startParam}`);
if (response.ok) {
const newSegments = await response.json();
if (Array.isArray(newSegments)) {
@@ -177,8 +181,10 @@
if (totalDuration !== oldTotalDuration) {
updateTimeline();
preloadNextSegments();
- //todo, bad autoplay at the start logic
- if (currentVideo.currentTime + segments[currentSegment].cumulativeStart == 0 || (isPlaying && isWaitingForNextSegment && segments.length < currentSegment + 1)) {
+
+ // TODO: Improve autoplay logic
+ if (currentVideo.currentTime + segments[currentSegment].cumulativeStart == 0 ||
+ (isPlaying && isWaitingForNextSegment && segments.length < currentSegment + 1)) {
playSegment();
}
if (isWaitingForNextSegment && segments.length > currentSegment + 1) {