Add object detection, tracking, mobile notifications, and search to any security camera.
remove segments dict
roryclear1dc42aa03314
diff --git a/clearcam/FileServer.h b/clearcam/FileServer.hindex b4d2eb5..157191d 100644--- a/clearcam/FileServer.h+++ b/clearcam/FileServer.h@@ -5,8 +5,7 @@@interface FileServer : NSObject- (void)start;-- (void)fetchAndProcessSegmentsFromCoreDataForDateParam:(NSString *)dateParam context:(NSManagedObjectContext *)context;-@property (nonatomic, strong) NSMutableDictionary *segmentsDict;+- (NSArray *)fetchAndProcessSegmentsFromCoreDataForDateParam:(NSString *)dateParam context:(NSManagedObjectContext *)context;@property (nonatomic, assign) NSInteger segment_length;@property (nonatomic, strong) NSDate *last_req_time;@property (nonatomic, strong) PortScanner *scanner;diff --git a/clearcam/FileServer.m b/clearcam/FileServer.mindex aef69e7..cfb67de 100644--- a/clearcam/FileServer.m+++ b/clearcam/FileServer.m@@ -64,7 +64,6 @@self.segment_length = 60;self.scanner = [[PortScanner alloc] init];self.last_req_time = [NSDate now];- self.segmentsDict = [[NSMutableDictionary alloc] init];self.basePath = [self getDocumentsDirectory];self.durationCache = [[NSMutableDictionary alloc] init];[self startHTTPServerWithBasePath:self.basePath];@@ -76,9 +75,10 @@return [paths firstObject];}-- (void)fetchAndProcessSegmentsFromCoreDataForDateParam:(NSString *)dateParam context:(NSManagedObjectContext *)context {+- (NSArray *)fetchAndProcessSegmentsFromCoreDataForDateParam:(NSString *)dateParam context:(NSManagedObjectContext *)context {+ // Create a temporary array for the segment dictionaries+ NSMutableArray *tempSegmentDicts = [NSMutableArray array];NSError *error = nil;-// Fetch the DayEntity for the given dateNSFetchRequest *dayFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"DayEntity"];dayFetchRequest.predicate = [NSPredicate predicateWithFormat:@"date == %@", dateParam];@@ -87,20 +87,17 @@if (error) {NSLog(@"Failed to fetch DayEntity: %@", error.localizedDescription);- return;+ return tempSegmentDicts;}if (fetchedDays.count == 0) {NSLog(@"No DayEntity found for date %@",dateParam);- return;+ return tempSegmentDicts;}NSManagedObject *dayEntity = fetchedDays.firstObject;NSOrderedSet *segments = [dayEntity valueForKey:@"segments"];- // Create a temporary array for the segment dictionaries- NSMutableArray *tempSegmentDicts = [NSMutableArray array];-for (NSManagedObject *segment in segments) {NSString *url = [segment valueForKey:@"url"];double timeStamp = [[segment valueForKey:@"timeStamp"] doubleValue];@@ -159,12 +156,10 @@[tempSegmentDicts addObject:segmentDict];}- // Assign tempSegmentDicts to the final array- self.segmentsDict[dateParam] = tempSegmentDicts;-// Log the resultsNSLog(@"rory length of init segments = %lu", (unsigned long)tempSegmentDicts.count);NSLog(@"Fetched and processed %lu segments for date %@", (unsigned long)tempSegmentDicts.count,dateParam);+ return tempSegmentDicts;}- (void)startHTTPServerWithBasePath:(NSString *)basePath {@@ -345,11 +340,7 @@}NSInteger start = startParam ? [startParam integerValue] : 0;- if (!self.segmentsDict[dateParam] || start == 0) {- [self fetchAndProcessSegmentsFromCoreDataForDateParam:dateParam context:self.context]; //todo, only works for one date! and is a mess- }-- NSArray *segmentsForDate = self.segmentsDict[dateParam];+ NSArray *segmentsForDate = [self fetchAndProcessSegmentsFromCoreDataForDateParam:dateParam context:self.context];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\"}";diff --git a/clearcam/ViewController.m b/clearcam/ViewController.mindex 121d748..ec7fcec 100644--- a/clearcam/ViewController.m+++ b/clearcam/ViewController.m@@ -339,36 +339,31 @@ NSMutableDictionary *classColorMap;NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour fromDate:self.current_file_timestamp];NSString *dateKey = [NSString stringWithFormat:@"%04ld-%02ld-%02ld", (long)components.year, (long)components.month, (long)components.day];- if (!self.fileServer.segmentsDict[dateKey]) {- [self.fileServer fetchAndProcessSegmentsFromCoreDataForDateParam:dateKey context:self.fileServer.context]; //todo only works on today's segments!- }-- // Create a copy of self.current_segment_squares to avoid mutation during enumerationNSArray *currentSegmentSquaresCopy = [self.current_segment_squares copy];- NSMutableDictionary *segmentEntry = [NSMutableDictionary dictionaryWithDictionary:@{ //does this fix last segment in hour/day?- @"url": [NSString stringWithFormat:@"%@/%@", [[self.assetWriter.outputURL URLByDeletingLastPathComponent] lastPathComponent], self.assetWriter.outputURL.lastPathComponent],+ NSString *segmentURL = [NSString stringWithFormat:@"%@/%@", [[self.assetWriter.outputURL URLByDeletingLastPathComponent] lastPathComponent], self.assetWriter.outputURL.lastPathComponent];++ NSMutableDictionary *segmentEntry = [NSMutableDictionary dictionaryWithDictionary:@{+ @"url": segmentURL,@"duration": @(CMTimeGetSeconds(time)),@"frames": currentSegmentSquaresCopy}];-- //timestamp of every segment now++ // Get timestampcalendar = [NSCalendar currentCalendar];components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.current_file_timestamp];NSDate *midnight = [calendar dateFromComponents:components];NSTimeInterval timeStamp = [self.current_file_timestamp timeIntervalSinceDate:midnight];segmentEntry[@"timeStamp"] = @(timeStamp);--- //core data below- // Create a private context for background processing++ // Core Data - Background ProcessingNSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];- backgroundContext.parentContext = self.fileServer.context; // Link to main context+ backgroundContext.parentContext = self.fileServer.context;[backgroundContext performBlock:^{NSError *error = nil;- // Fetch or create DayEntity+ // Fetch DayEntityNSDateFormatter *formatter = [NSDateFormatter new];formatter.dateFormat = @"yyyy-MM-dd";NSString *dateParam = [formatter stringFromDate:[NSDate date]];@@ -384,72 +379,66 @@ NSMutableDictionary *classColorMap;[dayEntity setValue:dateParam forKey:@"date"];}- // Create new SegmentEntity- NSManagedObject *newSegment = [NSEntityDescription insertNewObjectForEntityForName:@"SegmentEntity" inManagedObjectContext:backgroundContext];-- // Set segment properties- [newSegment setValue:[NSString stringWithFormat:@"%@/%@", [[self.assetWriter.outputURL URLByDeletingLastPathComponent] lastPathComponent], self.assetWriter.outputURL.lastPathComponent] forKey:@"url"];- [newSegment setValue:@(timeStamp) forKey:@"timeStamp"];- [newSegment setValue:@(CMTimeGetSeconds(time)) forKey:@"duration"];-- // Create an array for the frames- NSMutableArray<NSManagedObject *> *segmentFrames = [[NSMutableArray alloc] init];-- for (NSDictionary *frameData in currentSegmentSquaresCopy) {- // Create new FrameEntity- NSManagedObject *newFrame = [NSEntityDescription insertNewObjectForEntityForName:@"FrameEntity" inManagedObjectContext:backgroundContext];- [newFrame setValue:frameData[@"frame_timeStamp"] forKey:@"frame_timeStamp"];- [newFrame setValue:frameData[@"aspect_ratio"] forKey:@"aspect_ratio"];- [newFrame setValue:frameData[@"res"] forKey:@"res"];-- // Create an array for the squares in this frame- NSMutableArray<NSManagedObject *> *frameSquares = [[NSMutableArray alloc] init];-- for (NSDictionary *squareData in frameData[@"squares"]) {- // Create new SquareEntity- NSManagedObject *newSquare = [NSEntityDescription insertNewObjectForEntityForName:@"SquareEntity" inManagedObjectContext:backgroundContext];- [newSquare setValue:squareData[@"originX"] forKey:@"originX"];- [newSquare setValue:squareData[@"originY"] forKey:@"originY"];- [newSquare setValue:squareData[@"bottomRightX"] forKey:@"bottomRightX"];- [newSquare setValue:squareData[@"bottomRightY"] forKey:@"bottomRightY"];- [newSquare setValue:squareData[@"classIndex"] forKey:@"classIndex"];-- [frameSquares addObject:newSquare];- }+ // Check for existing segment+ NSFetchRequest *segmentFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"SegmentEntity"];+ segmentFetchRequest.predicate = [NSPredicate predicateWithFormat:@"url == %@", segmentURL];+ NSArray *existingSegments = [backgroundContext executeFetchRequest:segmentFetchRequest error:&error];- // Convert squares array to NSOrderedSet and set to the frame- NSOrderedSet *orderedSquares = [NSOrderedSet orderedSetWithArray:frameSquares];- [newFrame setValue:orderedSquares forKey:@"squares"];+ if (existingSegments.count == 0) { // Only insert if no duplicate exists+ NSManagedObject *newSegment = [NSEntityDescription insertNewObjectForEntityForName:@"SegmentEntity" inManagedObjectContext:backgroundContext];- [segmentFrames addObject:newFrame];- }+ [newSegment setValue:segmentURL forKey:@"url"];+ [newSegment setValue:@(timeStamp) forKey:@"timeStamp"];+ [newSegment setValue:@(CMTimeGetSeconds(time)) forKey:@"duration"];- // Convert NSMutableArray to NSOrderedSet and set to the segment- NSOrderedSet *orderedFrames = [NSOrderedSet orderedSetWithArray:segmentFrames];- [newSegment setValue:orderedFrames forKey:@"frames"];+ NSMutableArray<NSManagedObject *> *segmentFrames = [[NSMutableArray alloc] init];- // Add new segment to DayEntity- NSMutableOrderedSet *daySegments = [dayEntity mutableOrderedSetValueForKey:@"segments"];- [daySegments addObject:newSegment];+ for (NSDictionary *frameData in currentSegmentSquaresCopy) {+ NSManagedObject *newFrame = [NSEntityDescription insertNewObjectForEntityForName:@"FrameEntity" inManagedObjectContext:backgroundContext];+ [newFrame setValue:frameData[@"frame_timeStamp"] forKey:@"frame_timeStamp"];+ [newFrame setValue:frameData[@"aspect_ratio"] forKey:@"aspect_ratio"];+ [newFrame setValue:frameData[@"res"] forKey:@"res"];- // Save changes in the background context- if (![backgroundContext save:&error]) {- NSLog(@"Failed to save segment: %@", error.localizedDescription);- } else {- NSLog(@"Segment saved successfully under DayEntity with date %@",dateParam);+ NSMutableArray<NSManagedObject *> *frameSquares = [[NSMutableArray alloc] init];++ for (NSDictionary *squareData in frameData[@"squares"]) {+ NSManagedObject *newSquare = [NSEntityDescription insertNewObjectForEntityForName:@"SquareEntity" inManagedObjectContext:backgroundContext];+ [newSquare setValue:squareData[@"originX"] forKey:@"originX"];+ [newSquare setValue:squareData[@"originY"] forKey:@"originY"];+ [newSquare setValue:squareData[@"bottomRightX"] forKey:@"bottomRightX"];+ [newSquare setValue:squareData[@"bottomRightY"] forKey:@"bottomRightY"];+ [newSquare setValue:squareData[@"classIndex"] forKey:@"classIndex"];- // Merge changes back to the main context- [self.fileServer.context performBlock:^{- NSError *mainContextError = nil;- if (![self.fileServer.context save:&mainContextError]) {- NSLog(@"Failed to save main context: %@", mainContextError.localizedDescription);+ [frameSquares addObject:newSquare];}- }];++ NSOrderedSet *orderedSquares = [NSOrderedSet orderedSetWithArray:frameSquares];+ [newFrame setValue:orderedSquares forKey:@"squares"];+ [segmentFrames addObject:newFrame];+ }++ NSOrderedSet *orderedFrames = [NSOrderedSet orderedSetWithArray:segmentFrames];+ [newSegment setValue:orderedFrames forKey:@"frames"];++ NSMutableOrderedSet *daySegments = [dayEntity mutableOrderedSetValueForKey:@"segments"];+ [daySegments addObject:newSegment];++ if (![backgroundContext save:&error]) {+ NSLog(@"Failed to save segment: %@", error.localizedDescription);+ } else {+ NSLog(@"Segment saved successfully under DayEntity with date %@", dateParam);++ [self.fileServer.context performBlock:^{+ NSError *mainContextError = nil;+ if (![self.fileServer.context save:&mainContextError]) {+ NSLog(@"Failed to save main context: %@", mainContextError.localizedDescription);+ }+ }];+ }+ } else {+ NSLog(@"Segment with URL %@ already exists. Skipping insertion.", segmentURL);}}];- //core data above-- [self.fileServer.segmentsDict[dateKey] addObject:segmentEntry];[self startNewRecording];[self.segmentLock lock];[self.current_segment_squares removeAllObjects];@@ -460,6 +449,7 @@ NSMutableDictionary *classColorMap;}}+- (NSString *)jsonStringFromDictionary:(NSDictionary *)dictionary {NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];