Add object detection, tracking, mobile notifications, and search to any security camera.
move ios into folder
roryclear1091a79159cc
diff --git a/ios/SegmentsModel.xcdatamodeld/SegmentsModel.xcdatamodel/contents b/ios/SegmentsModel.xcdatamodeld/SegmentsModel.xcdatamodel/contentsnew file mode 100644index 0000000..9b7d44e--- /dev/null+++ b/ios/SegmentsModel.xcdatamodeld/SegmentsModel.xcdatamodel/contents@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="23605" systemVersion="24D81" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithSwiftData="YES" userDefinedModelVersionIdentifier="">+ <entity name="DayEntity" representedClassName="DayEntity" syncable="YES" codeGenerationType="class">+ <attribute name="date" optional="YES" attributeType="String"/>+ <relationship name="segments" optional="YES" toMany="YES" deletionRule="Nullify" ordered="YES" destinationEntity="SegmentEntity" inverseName="day" inverseEntity="SegmentEntity"/>+ </entity>+ <entity name="EventEntity" representedClassName="EventEntity" syncable="YES" codeGenerationType="class">+ <attribute name="classType" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>+ <attribute name="quantity" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>+ <attribute name="timeStamp" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ </entity>+ <entity name="FrameEntity" representedClassName="FrameEntity" syncable="YES" codeGenerationType="class">+ <attribute name="aspect_ratio" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="frame_timeStamp" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="res" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>+ <relationship name="segment" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="SegmentEntity" inverseName="frames" inverseEntity="SegmentEntity"/>+ <relationship name="squares" optional="YES" toMany="YES" deletionRule="Nullify" ordered="YES" destinationEntity="SquareEntity" inverseName="frame" inverseEntity="SquareEntity"/>+ <fetchedProperty name="fetchedProperty" optional="YES">+ <fetchRequest name="fetchedPropertyFetchRequest" entity="FrameEntity"/>+ </fetchedProperty>+ </entity>+ <entity name="SegmentEntity" representedClassName="SegmentEntity" syncable="YES" codeGenerationType="class">+ <attribute name="duration" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="orientation" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>+ <attribute name="timeStamp" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="url" optional="YES" attributeType="String"/>+ <relationship name="day" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="DayEntity" inverseName="segments" inverseEntity="DayEntity"/>+ <relationship name="frames" optional="YES" toMany="YES" deletionRule="Nullify" ordered="YES" destinationEntity="FrameEntity" inverseName="segment" inverseEntity="FrameEntity"/>+ </entity>+ <entity name="SquareEntity" representedClassName="SquareEntity" syncable="YES" codeGenerationType="class">+ <attribute name="bottomRightX" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="bottomRightY" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="classIndex" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>+ <attribute name="originX" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <attribute name="originY" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>+ <relationship name="frame" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="FrameEntity" inverseName="squares" inverseEntity="FrameEntity"/>+ </entity>+</model>\ No newline at end of filediff --git a/ios/clearcam.xcodeproj/project.pbxproj b/ios/clearcam.xcodeproj/project.pbxprojnew file mode 100644index 0000000..06db987--- /dev/null+++ b/ios/clearcam.xcodeproj/project.pbxproj@@ -0,0 +1,383 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 77;+ objects = {++/* Begin PBXBuildFile section */+ BE0FD6782D839FFE005C4A06 /* StoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BE0FD6772D839FFE005C4A06 /* StoreKit.framework */; };+ BEA6777C2D5CEFE300271B4F /* SegmentsModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = BEA6777A2D5CEFE300271B4F /* SegmentsModel.xcdatamodeld */; };+/* End PBXBuildFile section */++/* Begin PBXFileReference section */+ BE007DCA2D2BFF36005D40B3 /* clearcam.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = clearcam.app; sourceTree = BUILT_PRODUCTS_DIR; };+ BE0FD6772D839FFE005C4A06 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; };+ BEA6777B2D5CEFE300271B4F /* SegmentsModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = SegmentsModel.xcdatamodel; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */+ BE007DE12D2BFF37005D40B3 /* Exceptions for "clearcam" folder in "clearcam" target */ = {+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;+ membershipExceptions = (+ Info.plist,+ );+ target = BE007DC92D2BFF36005D40B3 /* clearcam */;+ };+/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */++/* Begin PBXFileSystemSynchronizedRootGroup section */+ BE007DCC2D2BFF36005D40B3 /* clearcam */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ exceptions = (+ BE007DE12D2BFF37005D40B3 /* Exceptions for "clearcam" folder in "clearcam" target */,+ );+ path = clearcam;+ sourceTree = "<group>";+ };+/* End PBXFileSystemSynchronizedRootGroup section */++/* Begin PBXFrameworksBuildPhase section */+ BE007DC72D2BFF36005D40B3 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ BE0FD6782D839FFE005C4A06 /* StoreKit.framework in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ BE007DC12D2BFF36005D40B3 = {+ isa = PBXGroup;+ children = (+ BEA6777A2D5CEFE300271B4F /* SegmentsModel.xcdatamodeld */,+ BE007DCC2D2BFF36005D40B3 /* clearcam */,+ BE0FD6762D839FFE005C4A06 /* Frameworks */,+ BE007DCB2D2BFF36005D40B3 /* Products */,+ );+ sourceTree = "<group>";+ };+ BE007DCB2D2BFF36005D40B3 /* Products */ = {+ isa = PBXGroup;+ children = (+ BE007DCA2D2BFF36005D40B3 /* clearcam.app */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ BE0FD6762D839FFE005C4A06 /* Frameworks */ = {+ isa = PBXGroup;+ children = (+ BE0FD6772D839FFE005C4A06 /* StoreKit.framework */,+ );+ name = Frameworks;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ BE007DC92D2BFF36005D40B3 /* clearcam */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = BE007DE22D2BFF37005D40B3 /* Build configuration list for PBXNativeTarget "clearcam" */;+ buildPhases = (+ BE007DC62D2BFF36005D40B3 /* Sources */,+ BE007DC72D2BFF36005D40B3 /* Frameworks */,+ BE007DC82D2BFF36005D40B3 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ BE007DCC2D2BFF36005D40B3 /* clearcam */,+ );+ name = clearcam;+ packageProductDependencies = (+ );+ productName = clearcam;+ productReference = BE007DCA2D2BFF36005D40B3 /* clearcam.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ BE007DC22D2BFF36005D40B3 /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = 1;+ LastUpgradeCheck = 1610;+ TargetAttributes = {+ BE007DC92D2BFF36005D40B3 = {+ CreatedOnToolsVersion = 16.1;+ };+ };+ };+ buildConfigurationList = BE007DC52D2BFF36005D40B3 /* Build configuration list for PBXProject "clearcam" */;+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ "zh-Hans",+ es,+ ja,+ ko,+ hi,+ );+ mainGroup = BE007DC12D2BFF36005D40B3;+ minimizedProjectReferenceProxies = 1;+ preferredProjectObjectVersion = 77;+ productRefGroup = BE007DCB2D2BFF36005D40B3 /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ BE007DC92D2BFF36005D40B3 /* clearcam */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ BE007DC82D2BFF36005D40B3 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ BE007DC62D2BFF36005D40B3 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ BEA6777C2D5CEFE300271B4F /* SegmentsModel.xcdatamodeld in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin XCBuildConfiguration section */+ BE007DE32D2BFF37005D40B3 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = clearcam/clearcam.entitlements;+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = VLS9B5G7MH;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = clearcam/Info.plist;+ INFOPLIST_KEY_LSSupportsOpeningDocumentsInPlace = YES;+ INFOPLIST_KEY_NSCameraUsageDescription = "Clearcam needs access to your camera to record video, stream video and detect objects.";+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;+ INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;+ INFOPLIST_KEY_UIMainStoryboardFile = Main;+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 1.2.3;+ PRODUCT_BUNDLE_IDENTIFIER = roryclear.clearcam;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";+ SUPPORTS_MACCATALYST = NO;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 4.0;+ TARGETED_DEVICE_FAMILY = 1;+ };+ name = Debug;+ };+ BE007DE42D2BFF37005D40B3 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = clearcam/clearcam.entitlements;+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = VLS9B5G7MH;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = clearcam/Info.plist;+ INFOPLIST_KEY_LSSupportsOpeningDocumentsInPlace = YES;+ INFOPLIST_KEY_NSCameraUsageDescription = "Clearcam needs access to your camera to record video, stream video and detect objects.";+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;+ INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;+ INFOPLIST_KEY_UIMainStoryboardFile = Main;+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 1.2.3;+ PRODUCT_BUNDLE_IDENTIFIER = roryclear.clearcam;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";+ SUPPORTS_MACCATALYST = NO;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 4.0;+ TARGETED_DEVICE_FAMILY = 1;+ };+ name = Release;+ };+ BE007DE52D2BFF37005D40B3 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = iphoneos;+ };+ name = Debug;+ };+ BE007DE62D2BFF37005D40B3 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 15.6;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ SDKROOT = iphoneos;+ VALIDATE_PRODUCT = YES;+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ BE007DC52D2BFF36005D40B3 /* Build configuration list for PBXProject "clearcam" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ BE007DE52D2BFF37005D40B3 /* Debug */,+ BE007DE62D2BFF37005D40B3 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ BE007DE22D2BFF37005D40B3 /* Build configuration list for PBXNativeTarget "clearcam" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ BE007DE32D2BFF37005D40B3 /* Debug */,+ BE007DE42D2BFF37005D40B3 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCVersionGroup section */+ BEA6777A2D5CEFE300271B4F /* SegmentsModel.xcdatamodeld */ = {+ isa = XCVersionGroup;+ children = (+ BEA6777B2D5CEFE300271B4F /* SegmentsModel.xcdatamodel */,+ );+ currentVersion = BEA6777B2D5CEFE300271B4F /* SegmentsModel.xcdatamodel */;+ path = SegmentsModel.xcdatamodeld;+ sourceTree = "<group>";+ versionGroupType = wrapper.xcdatamodel;+ };+/* End XCVersionGroup section */+ };+ rootObject = BE007DC22D2BFF36005D40B3 /* Project object */;+}diff --git a/ios/clearcam.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/clearcam.xcodeproj/project.xcworkspace/contents.xcworkspacedatanew file mode 100644index 0000000..919434a--- /dev/null+++ b/ios/clearcam.xcodeproj/project.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "self:">+ </FileRef>+</Workspace>diff --git a/ios/clearcam/AppDelegate.h b/ios/clearcam/AppDelegate.hnew file mode 100644index 0000000..67e2db7--- /dev/null+++ b/ios/clearcam/AppDelegate.h@@ -0,0 +1,9 @@+#import <UIKit/UIKit.h>+#import <CoreData/CoreData.h>++@interface AppDelegate : UIResponder <UIApplicationDelegate>++@property (strong, nonatomic) UIWindow *window;+@property (readonly, strong) NSPersistentContainer *persistentContainer; // Core Data container++@enddiff --git a/ios/clearcam/AppDelegate.m b/ios/clearcam/AppDelegate.mnew file mode 100644index 0000000..8ebdcfd--- /dev/null+++ b/ios/clearcam/AppDelegate.m@@ -0,0 +1,150 @@+#import "AppDelegate.h"+#import <UserNotifications/UserNotifications.h>+#import "GalleryViewController.h"+#import "StoreManager.h"+#import "FileServer.h"++@interface AppDelegate () <UNUserNotificationCenterDelegate>+@property (nonatomic, strong) NSDictionary *pendingNotification;+@end++@implementation AppDelegate++- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ center.delegate = self;++ // Handle launch from notification+ if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {+ NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];+ self.pendingNotification = userInfo;+ // Only process if notifications are enabled+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"receive_notif_enabled"] && userInfo[@"aps"][@"content-available"]) {+ [self handleNotificationReceived:userInfo];+ }+ }++ return YES;+}++- (void)applicationDidBecomeActive:(UIApplication *)application {+ if (self.pendingNotification && [[NSUserDefaults standardUserDefaults] boolForKey:@"receive_notif_enabled"]) {+ [self handleNotificationNavigation];+ self.pendingNotification = nil;+ }+}++#pragma mark - Notification Handling++- (void)handleNotificationNavigation {+ dispatch_async(dispatch_get_main_queue(), ^{+ UIWindow *window = [UIApplication sharedApplication].keyWindow;+ UIViewController *rootVC = window.rootViewController;++ UIViewController *topVC = rootVC;+ while (topVC.presentedViewController) {+ topVC = topVC.presentedViewController;+ }++ if ([topVC isKindOfClass:[UINavigationController class]]) {+ UINavigationController *nav = (UINavigationController *)topVC;+ if ([nav.topViewController isKindOfClass:[GalleryViewController class]]) return;+ }++ GalleryViewController *galleryVC = [[GalleryViewController alloc] init];++ if ([topVC isKindOfClass:[UINavigationController class]]) {+ [(UINavigationController *)topVC pushViewController:galleryVC animated:YES];+ } else if (topVC.navigationController) {+ [topVC.navigationController pushViewController:galleryVC animated:YES];+ } else {+ UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:galleryVC];+ [topVC presentViewController:navController animated:YES completion:nil];+ }+ });+}++- (void)handleNotificationReceived:(NSDictionary *)userInfo {+ return; //TODO, did this do anything before?+ /*+ GalleryViewController *gallery = [[GalleryViewController alloc] init];+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{+ sleep(15);+ [gallery getEvents];+ });+ */+}++#pragma mark - Remote Notification Methods++- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {+ const unsigned char *dataBuffer = (const unsigned char *)[deviceToken bytes];+ if (!dataBuffer) {+ return;+ }++ NSMutableString *token = [NSMutableString stringWithCapacity:(deviceToken.length * 2)];+ for (int i = 0; i < deviceToken.length; i++) {+ [token appendFormat:@"%02x", dataBuffer[i]];+ }+ [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"device_token"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ [FileServer sendDeviceTokenToServer];+}++- (void)userNotificationCenter:(UNUserNotificationCenter *)center+ willPresentNotification:(UNNotification *)notification+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {+ NSDictionary *userInfo = notification.request.content.userInfo;+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"receive_notif_enabled"]) {+ if (userInfo[@"aps"][@"content-available"]) {+ [self handleNotificationReceived:userInfo];+ }+ completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);+ } else {+ completionHandler(0); // No presentation options when disabled+ }+}++- (void)userNotificationCenter:(UNUserNotificationCenter *)center+didReceiveNotificationResponse:(UNNotificationResponse *)response+ withCompletionHandler:(void (^)(void))completionHandler {+ NSDictionary *userInfo = response.notification.request.content.userInfo;+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"receive_notif_enabled"]) {+ [self handleNotificationNavigation];+ }+ completionHandler();+}++- (void)application:(UIApplication *)application+didReceiveRemoteNotification:(NSDictionary *)userInfo+fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {+ if (![[NSUserDefaults standardUserDefaults] boolForKey:@"receive_notif_enabled"]) {+ completionHandler(UIBackgroundFetchResultNoData);+ return;+ }++ if (userInfo[@"aps"][@"content-available"]) {+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ [self handleNotificationReceived:userInfo];+ completionHandler(UIBackgroundFetchResultNewData);+ });+ } else {+ if (application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground) self.pendingNotification = userInfo;+ completionHandler(UIBackgroundFetchResultNoData);+ }+}++@synthesize persistentContainer = _persistentContainer;++- (NSPersistentContainer *)persistentContainer {+ if (_persistentContainer == nil) {+ _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"SegmentsModel"];+ [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {+ if (error) abort();+ }];+ }+ return _persistentContainer;+}++@enddiff --git a/ios/clearcam/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/clearcam/Assets.xcassets/AccentColor.colorset/Contents.jsonnew file mode 100644index 0000000..eb87897--- /dev/null+++ b/ios/clearcam/Assets.xcassets/AccentColor.colorset/Contents.json@@ -0,0 +1,11 @@+{+ "colors" : [+ {+ "idiom" : "universal"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/100.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/100.pngnew file mode 100644index 0000000..814a0ebBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/100.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/1024.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/1024.pngnew file mode 100644index 0000000..250adf0Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/1024.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/114.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/114.pngnew file mode 100644index 0000000..a763c61Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/114.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/120.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/120.pngnew file mode 100644index 0000000..538b3ffBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/120.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/144.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/144.pngnew file mode 100644index 0000000..6ee908fBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/144.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/152.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/152.pngnew file mode 100644index 0000000..8db2eaeBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/152.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/167.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/167.pngnew file mode 100644index 0000000..502e2cdBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/167.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/180.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/180.pngnew file mode 100644index 0000000..18d1956Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/180.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/20.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/20.pngnew file mode 100644index 0000000..f1aafcfBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/20.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/29.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/29.pngnew file mode 100644index 0000000..0ff2828Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/29.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/40.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/40.pngnew file mode 100644index 0000000..39b0150Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/40.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/50.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/50.pngnew file mode 100644index 0000000..74e44dcBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/50.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/57.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/57.pngnew file mode 100644index 0000000..d5e35fbBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/57.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/58.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/58.pngnew file mode 100644index 0000000..29c536eBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/58.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/60.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/60.pngnew file mode 100644index 0000000..aecf658Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/60.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/72.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/72.pngnew file mode 100644index 0000000..ecf1fb8Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/72.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/76.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/76.pngnew file mode 100644index 0000000..2e920ebBinary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/76.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/80.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/80.pngnew file mode 100644index 0000000..7171158Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/80.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/87.png b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/87.pngnew file mode 100644index 0000000..a403498Binary files /dev/null and b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/87.png differdiff --git a/ios/clearcam/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 0000000..65b74d7--- /dev/null+++ b/ios/clearcam/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1 @@+{"images":[{"size":"60x60","expected-size":"180","filename":"180.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"40x40","expected-size":"80","filename":"80.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"40x40","expected-size":"120","filename":"120.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"60x60","expected-size":"120","filename":"120.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"57x57","expected-size":"57","filename":"57.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"1x"},{"size":"29x29","expected-size":"58","filename":"58.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"29x29","expected-size":"29","filename":"29.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"1x"},{"size":"29x29","expected-size":"87","filename":"87.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"57x57","expected-size":"114","filename":"114.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"20x20","expected-size":"40","filename":"40.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"20x20","expected-size":"60","filename":"60.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"1024x1024","filename":"1024.png","expected-size":"1024","idiom":"ios-marketing","folder":"Assets.xcassets/AppIcon.appiconset/","scale":"1x"},{"size":"40x40","expected-size":"80","filename":"80.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"72x72","expected-size":"72","filename":"72.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"76x76","expected-size":"152","filename":"152.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"50x50","expected-size":"100","filename":"100.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"29x29","expected-size":"58","filename":"58.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"76x76","expected-size":"76","filename":"76.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"29x29","expected-size":"29","filename":"29.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"50x50","expected-size":"50","filename":"50.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"72x72","expected-size":"144","filename":"144.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"40x40","expected-size":"40","filename":"40.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"83.5x83.5","expected-size":"167","filename":"167.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"},{"size":"20x20","expected-size":"20","filename":"20.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"1x"},{"size":"20x20","expected-size":"40","filename":"40.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"ipad","scale":"2x"}]}\ No newline at end of filediff --git a/ios/clearcam/Assets.xcassets/Contents.json b/ios/clearcam/Assets.xcassets/Contents.jsonnew file mode 100644index 0000000..73c0059--- /dev/null+++ b/ios/clearcam/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/ios/clearcam/Base.lproj/LaunchScreen.storyboard b/ios/clearcam/Base.lproj/LaunchScreen.storyboardnew file mode 100644index 0000000..865e932--- /dev/null+++ b/ios/clearcam/Base.lproj/LaunchScreen.storyboard@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">+ <dependencies>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>+ <capability name="Safe area layout guides" minToolsVersion="9.0"/>+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>+ </dependencies>+ <scenes>+ <!--View Controller-->+ <scene sceneID="EHf-IW-A2E">+ <objects>+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">+ <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">+ <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>+ <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>+ </objects>+ <point key="canvasLocation" x="53" y="375"/>+ </scene>+ </scenes>+</document>diff --git a/ios/clearcam/Base.lproj/Main.storyboard b/ios/clearcam/Base.lproj/Main.storyboardnew file mode 100644index 0000000..808a21c--- /dev/null+++ b/ios/clearcam/Base.lproj/Main.storyboard@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">+ <dependencies>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>+ <capability name="Safe area layout guides" minToolsVersion="9.0"/>+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>+ </dependencies>+ <scenes>+ <!--View Controller-->+ <scene sceneID="tne-QT-ifu">+ <objects>+ <viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="" sceneMemberID="viewController">+ <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">+ <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>+ <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>+ </objects>+ </scene>+ </scenes>+</document>diff --git a/ios/clearcam/DeviceStreamViewController.h b/ios/clearcam/DeviceStreamViewController.hnew file mode 100644index 0000000..41d5b2a--- /dev/null+++ b/ios/clearcam/DeviceStreamViewController.h@@ -0,0 +1,5 @@+#import <UIKit/UIKit.h>++@interface DeviceStreamViewController : UIViewController+@property (nonatomic, strong) NSString *deviceName; // Property to hold the device name+@enddiff --git a/ios/clearcam/DeviceStreamViewController.m b/ios/clearcam/DeviceStreamViewController.mnew file mode 100644index 0000000..eaf938c--- /dev/null+++ b/ios/clearcam/DeviceStreamViewController.m@@ -0,0 +1,336 @@+#import "DeviceStreamViewController.h"+#import "StoreManager.h"+#import "SecretManager.h"+#import <AVFoundation/AVFoundation.h>+#import <Security/Security.h>+#import <CommonCrypto/CommonCryptor.h>++@interface DeviceStreamViewController ()+@property (nonatomic, strong) AVQueuePlayer *player;+@property (nonatomic, strong) AVPlayerLayer *playerLayer;+@property (nonatomic, strong) NSTimer *downloadTimer;+@property (nonatomic, strong) NSTimer *linkRefreshTimer;+@property (nonatomic, strong) NSData *lastSegmentData;+@property (nonatomic, assign) NSUInteger segmentIndex;+@property (nonatomic, strong) NSString *downloadLink;+@property (nonatomic, strong) NSString *decryptionKey;+@property (nonatomic, strong) NSData *lastFailedEncryptedData;+@property (nonatomic, assign) NSInteger consecutiveDecryptionFailures;+@property (nonatomic, assign) BOOL decryptionFailedOnce;+@property (nonatomic, strong) UIActivityIndicatorView *loadingSpinner;+@property (nonatomic, assign) NSInteger successfullyQueuedSegmentCount;+@property (nonatomic, strong) NSMutableSet<NSData *> *seenSegmentHashes;+@end++@implementation DeviceStreamViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.view.backgroundColor = [UIColor blackColor];++ // Setup spinner+ self.loadingSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];+ self.loadingSpinner.center = self.view.center;+ self.loadingSpinner.color = [UIColor whiteColor];+ [self.view addSubview:self.loadingSpinner];+ [self.loadingSpinner startAnimating];++ self.player = [AVQueuePlayer queuePlayerWithItems:@[]];+ self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];+ self.playerLayer.frame = self.view.bounds;+ self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;+ [self.view.layer addSublayer:self.playerLayer];++ [self.player play];+ [self fetchDownloadLinkAndStartStreaming];+ self.seenSegmentHashes = [NSMutableSet set];+}++- (void)fetchDownloadLinkAndStartStreaming {+ [self fetchDownloadLink];+ // Start timer to refresh download link every 60 seconds+ self.linkRefreshTimer = [NSTimer scheduledTimerWithTimeInterval:50.0+ target:self+ selector:@selector(fetchDownloadLink)+ userInfo:nil+ repeats:YES];+}++- (void)fetchDownloadLink {+ NSString *deviceName = self.deviceName;+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];++ if (!deviceName || !sessionToken) return;++ NSString *keyIdentifier = [NSString stringWithFormat:@"decryption_key_%@", deviceName];+ NSError *keyError;+ self.decryptionKey = [[SecretManager sharedManager] retrieveDecryptionKeyWithIdentifier:keyIdentifier error:&keyError];+ if (keyError) NSLog(@"⚠️ Keychain retrieval error: %@", keyError.localizedDescription);++ NSString *encodedDeviceName = [deviceName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];+ NSString *encodedSessionToken = [sessionToken stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];++ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/get_stream_download_link"];+ components.queryItems = @[+ [NSURLQueryItem queryItemWithName:@"name" value:encodedDeviceName],+ [NSURLQueryItem queryItemWithName:@"session_token" value:encodedSessionToken]+ ];++ NSURL *url = components.URL;++ NSURLSessionDataTask *linkTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error) return;++ NSError *jsonError;+ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];+ if (jsonError) return;++ NSString *downloadLink = json[@"download_link"];+ if (![downloadLink isKindOfClass:[NSString class]] || downloadLink.length == 0) {+ NSLog(@"🚫 Invalid downloadLink link");+ return;+ } else {+ self.downloadLink = downloadLink;+ }++ NSLog(@"✅ Got download link: %@", self.downloadLink);++ dispatch_async(dispatch_get_main_queue(), ^{+ // Start downloading segments only if this is the first fetch+ if (!self.downloadTimer) [self startDownloadTimer];+ });+ }];+ [linkTask resume];+}++- (void)startDownloadTimer {+ self.downloadTimer = [NSTimer scheduledTimerWithTimeInterval:1.0+ target:self+ selector:@selector(downloadAndQueueSegment)+ userInfo:nil+ repeats:YES];+}++- (void)downloadAndQueueSegment {+ NSString *urlString = self.downloadLink;+ if (!urlString) {+ NSLog(@"❌ No download link available");+ return;+ }+ NSURL *remoteURL = [NSURL URLWithString:urlString];++ NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:remoteURL+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error || !data) {+ NSLog(@"❌ Download error: %@", error.localizedDescription);+ return;+ }++ // Only set lastSegmentData after successful decryption+ NSLog(@"📥 New segment downloaded, attempting decryption");++ [self decryptAndQueueSegment:data withCompletion:^(NSData *decryptedData) {+ if (!decryptedData) {+ NSLog(@"❌ Decryption failed");+ return;+ }++ NSUInteger hash = data.hash;+ NSData *hashData = [NSData dataWithBytes:&hash length:sizeof(hash)];+ if ([self.seenSegmentHashes containsObject:hashData]) {+ NSLog(@"🔁 Duplicate decrypted segment, skipping queue");+ return;+ }+ [self.seenSegmentHashes addObject:hashData];+ self.lastSegmentData = data;+ self.decryptionFailedOnce = NO; // Only reset on success++ NSString *fileName = [NSString stringWithFormat:@"segment_%lu.mp4", (unsigned long)(self.segmentIndex++ % 2)];+ NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];+ NSURL *localURL = [NSURL fileURLWithPath:tempPath];++ // Delete existing file if any (from old streams)+ [[NSFileManager defaultManager] removeItemAtURL:localURL error:nil];++ if ([decryptedData writeToURL:localURL atomically:YES]) {+ NSLog(@"✅ New segment saved: %@", fileName);++ //thumbnail save+ AVAsset *videoAsset = [AVAsset assetWithURL:localURL];+ AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:videoAsset];+ imageGenerator.appliesPreferredTrackTransform = YES; // To avoid rotated images++ CMTime time = CMTimeMakeWithSeconds(0.0, 600); // Grab first frame (0s)+ [imageGenerator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:time]]+ completionHandler:^(CMTime requestedTime, CGImageRef cgImage, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {+ if (result == AVAssetImageGeneratorSucceeded && cgImage) {+ UIImage *thumbnail = [UIImage imageWithCGImage:cgImage];+ NSData *imageData = UIImageJPEGRepresentation(thumbnail, 0.7); // Compress a bit++ NSString *filename = [NSString stringWithFormat:@"thumbnail_%@.jpg", self.deviceName];+ NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;+ NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];+ if ([imageData writeToFile:filePath atomically:YES]) {+ NSLog(@"🖼️ Thumbnail saved: %@", filename);+ } else {+ NSLog(@"❌ Failed to save thumbnail");+ }+ } else {+ NSLog(@"❌ Failed to generate thumbnail: %@", error.localizedDescription);+ }+ }];+++ dispatch_async(dispatch_get_main_queue(), ^{+ AVURLAsset *asset = [AVURLAsset assetWithURL:localURL];+ AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];+ [self.player insertItem:item afterItem:nil];+ [self.loadingSpinner stopAnimating];+ self.loadingSpinner.hidden = YES;+ });+ } else {+ NSLog(@"❌ Write failed");+ }+ }];+ }];+ [task resume];+}++- (void)decryptAndQueueSegment:(NSData *)encryptedData withCompletion:(void (^)(NSData *))completion {+ if (self.decryptionKey) {+ NSData *decryptedData = [[SecretManager sharedManager] decryptData:encryptedData withKey:self.decryptionKey];+ if (decryptedData) {+ // Successful decryption, reset all failure tracking+ self.consecutiveDecryptionFailures = 0;+ self.lastFailedEncryptedData = nil;+ self.decryptionFailedOnce = NO;+ completion(decryptedData);+ return;+ } else {+ NSLog(@"⚠️ Decryption failed with stored key");+ }+ }++ // Handle failure+ BOOL isSameData = [self.lastFailedEncryptedData isEqualToData:encryptedData];+ if (!isSameData) {+ self.consecutiveDecryptionFailures += 1;+ self.lastFailedEncryptedData = encryptedData;+ NSLog(@"❌ Decryption failure count: %ld", (long)self.consecutiveDecryptionFailures);+ } else {+ NSLog(@"🔁 Same failed segment, not incrementing failure count");+ }++ // Prompt for key only after two failures and no valid key+ if (self.consecutiveDecryptionFailures >= 2 && !self.decryptionKey) {+ NSLog(@"🔑 Prompting for key after two failures");+ [self promptForKeyOnSecondFailure:encryptedData withCompletion:completion];+ self.consecutiveDecryptionFailures = 0;+ self.lastFailedEncryptedData = nil;+ } else {+ completion(nil);+ }+}++- (void)promptForKeyOnSecondFailure:(NSData *)encryptedData withCompletion:(void (^)(NSData *))completion {+ dispatch_async(dispatch_get_main_queue(), ^{+ [[SecretManager sharedManager] promptUserForKeyFromViewController:self completion:^(NSString *userProvidedKey) {+ if (userProvidedKey) {+ NSData *decryptedData = [[SecretManager sharedManager] decryptData:encryptedData withKey:userProvidedKey];+ if (decryptedData) {+ // Save the valid key to keychain+ NSString *keyIdentifier = [NSString stringWithFormat:@"decryption_key_%@", self.deviceName];+ NSError *saveError;+ [[SecretManager sharedManager] saveDecryptionKey:userProvidedKey withIdentifier:keyIdentifier error:&saveError];+ if (saveError) {+ NSLog(@"⚠️ Failed to save key to keychain: %@", saveError.localizedDescription);+ }+ self.decryptionKey = userProvidedKey;+ self.consecutiveDecryptionFailures = 0;+ self.lastFailedEncryptedData = nil;+ self.decryptionFailedOnce = NO;+ completion(decryptedData);+ } else {+ [self showErrorAlertWithMessage:@"The provided key is incorrect. Please try again or cancel." completion:^{+ // Re-prompt for the same segment+ [self promptForKeyOnSecondFailure:encryptedData withCompletion:completion];+ }];+ }+ } else {+ completion(nil); // User cancelled+ }+ }];+ });+}++- (void)showErrorAlertWithMessage:(NSString *)message completion:(void (^)(void))completion {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"+ message:message+ preferredStyle:UIAlertControllerStyleAlert];+ UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ if (completion) completion();+ }];+ [alert addAction:okAction];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ self.playerLayer.frame = self.view.bounds;+}++- (void)dealloc {+ [self.downloadTimer invalidate];+ [self.linkRefreshTimer invalidate];+}++- (void)viewWillDisappear:(BOOL)animated {+ [super viewWillDisappear:animated];++ [self.downloadTimer invalidate];+ self.downloadTimer = nil;+ [self.linkRefreshTimer invalidate];+ self.linkRefreshTimer = nil;++ [self sendDeleteStreamDownloadLink];+}++- (void)sendDeleteStreamDownloadLink {+ NSString *deviceName = self.deviceName;+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];++ if (!deviceName || !sessionToken) {+ NSLog(@"❌ Missing device name or session token for delete request");+ return;+ }++ NSString *encodedDeviceName = [deviceName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];+ NSString *encodedSessionToken = [sessionToken stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];++ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/delete_stream_download_link"];+ components.queryItems = @[+ [NSURLQueryItem queryItemWithName:@"name" value:encodedDeviceName],+ [NSURLQueryItem queryItemWithName:@"session_token" value:encodedSessionToken]+ ];++ NSURL *url = components.URL;++ NSURLSessionDataTask *deleteTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error) {+ NSLog(@"❌ Error sending delete request: %@", error.localizedDescription);+ return;+ }++ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ if (httpResponse.statusCode == 200) {+ NSLog(@"✅ Successfully deleted stream download link");+ } else {+ NSLog(@"⚠️ Delete request failed with status code: %ld", (long)httpResponse.statusCode);+ }+ }];+ [deleteTask resume];+}++@enddiff --git a/ios/clearcam/FileServer.h b/ios/clearcam/FileServer.hnew file mode 100644index 0000000..670abee--- /dev/null+++ b/ios/clearcam/FileServer.h@@ -0,0 +1,26 @@+#import <Foundation/Foundation.h>+#import "PortScanner.h"+#import <CoreData/CoreData.h>++@interface FileServer : NSObject+++ (instancetype)sharedInstance;++- (void)start;+- (NSArray *)fetchEventDataFromCoreData:(NSManagedObjectContext *)context;+- (NSString *)processVideoDownloadWithLowRes:(BOOL)low_res+ startTime:(NSTimeInterval)startTimeStamp+ endTime:(NSTimeInterval)endTimeStamp+ context:(NSManagedObjectContext *)context;++ (void)performPostRequestWithURL:(NSString *)urlString+ method:(NSString *)method+ contentType:(NSString *)contentType+ body:(id)body+ completionHandler:(void (^)(NSData *data, NSHTTPURLResponse *response, NSError *error))completion;++ (void)sendDeviceTokenToServer;+@property (nonatomic, assign) NSInteger segment_length;+@property (nonatomic, strong) NSDate *last_req_time;+@property (nonatomic, strong) PortScanner *scanner;+@property (nonatomic, strong) NSManagedObjectContext *context;++@enddiff --git a/ios/clearcam/FileServer.m b/ios/clearcam/FileServer.mnew file mode 100644index 0000000..8c5a721--- /dev/null+++ b/ios/clearcam/FileServer.m@@ -0,0 +1,1061 @@+#import "FileServer.h"+#import <sys/types.h>+#import <sys/socket.h>+#import <netinet/in.h>+#import <arpa/inet.h>+#import <unistd.h>+#import <signal.h>+#import <errno.h>+#import <AVFoundation/AVFoundation.h>+#import "SettingsManager.h"+#import "PortScanner.h"+#import "AppDelegate.h"+#import "StoreManager.h"+#import <CoreData/CoreData.h>+#import "SecretManager.h"++@interface FileServer ()+@property (nonatomic, strong) NSString *basePath;+@property (nonatomic, strong) NSMutableDictionary *durationCache;+@property (nonatomic, assign) int serverSocket;//todo+@property (nonatomic, assign) BOOL isServerRunning;+@end++@implementation FileServer+++ (instancetype)sharedInstance {+ static FileServer *sharedInstance = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedInstance = [[self alloc] init];+ });+ return sharedInstance;+}++- (instancetype)init {+ self = [super init];+ if (self) {+ _serverSocket = -1;+ _isServerRunning = NO;++ // Add KVO observer for stream_via_wifi_enabled+ [[NSUserDefaults standardUserDefaults] addObserver:self+ forKeyPath:@"stream_via_wifi_enabled"+ options:NSKeyValueObservingOptionNew+ context:nil];+ }+ return self;+}++- (void)start {+ AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];+ self.context = appDelegate.persistentContainer.viewContext;+ self.segment_length = 60;+ self.scanner = [[PortScanner alloc] init];+ self.last_req_time = [NSDate now];+ self.basePath = [self getDocumentsDirectory];+ self.durationCache = [[NSMutableDictionary alloc] init];+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"stream_via_wifi_enabled"]) [self startServer];+ if ([[NSUserDefaults standardUserDefaults] objectForKey:@"stream_via_wifi_enabled"] == nil) {+ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"stream_via_wifi_enabled"];+ }+}++- (void)dealloc {+ [self stopServer];+ [[NSUserDefaults standardUserDefaults] removeObserver:self+ forKeyPath:@"stream_via_wifi_enabled"];+}++- (void)startServer {+ if (self.isServerRunning) return;+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ @try {+ signal(SIGPIPE, SIG_IGN);+ self.serverSocket = socket(AF_INET, SOCK_STREAM, 0);+ if (self.serverSocket == -1) return;+ struct sockaddr_in serverAddr;+ memset(&serverAddr, 0, sizeof(serverAddr));+ serverAddr.sin_family = AF_INET;+ serverAddr.sin_addr.s_addr = INADDR_ANY;+ serverAddr.sin_port = htons(80);++ int opt = 1;+ setsockopt(self.serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));++ if (bind(self.serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {+ close(self.serverSocket);+ self.serverSocket = -1;+ return;+ }++ if (listen(self.serverSocket, 5) == -1) {+ close(self.serverSocket);+ self.serverSocket = -1;+ return;+ }++ self.isServerRunning = YES;+ while (self.isServerRunning) {+ int clientSocket = accept(self.serverSocket, NULL, NULL);+ if (clientSocket != -1) {+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ [self handleClientRequest:clientSocket withBasePath:self.basePath];+ close(clientSocket);+ });+ }+ }++ } @catch (NSException *exception) {+ self.isServerRunning = NO;+ if (self.serverSocket != -1) {+ close(self.serverSocket);+ self.serverSocket = -1;+ }+ }+ });+}++- (void)stopServer {+ if (!self.isServerRunning) {+ return; // Server already stopped+ }++ self.isServerRunning = NO;+ if (self.serverSocket != -1) {+ close(self.serverSocket);+ self.serverSocket = -1;+ }+}++- (void)observeValueForKeyPath:(NSString *)keyPath+ ofObject:(id)object+ change:(NSDictionary *)change+ context:(void *)context {+ if ([keyPath isEqualToString:@"stream_via_wifi_enabled"]) {+ BOOL streamViaWiFiEnabled = [change[NSKeyValueChangeNewKey] boolValue];+ if (streamViaWiFiEnabled) {+ [self startServer];+ } else {+ [self stopServer];+ }+ }+}++- (NSString *)getDocumentsDirectory {+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);+ return [paths firstObject];+}++- (NSArray *)fetchAndProcessSegmentsFromCoreDataForDateParam:(NSString *)dateParam+ start:(double)startTime+ context:(NSManagedObjectContext *)context {+ if (!context) return @[];++ __block NSArray *processedSegments = @[];++ [context performBlockAndWait:^{+ NSError *error = nil;++ // Fetch the DayEntity to get its ID+ NSFetchRequest *dayFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"DayEntity"];+ dayFetchRequest.predicate = [NSPredicate predicateWithFormat:@"date == %@", dateParam];+ dayFetchRequest.fetchLimit = 1; // We only need one DayEntity++ NSArray *fetchedDays = [context executeFetchRequest:dayFetchRequest error:&error];+ if (error || fetchedDays.count == 0) return;++ NSManagedObject *dayEntity = fetchedDays.firstObject;++ // Fetch segments with a filter based on timeStamp+ NSFetchRequest *segmentFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"SegmentEntity"];+ segmentFetchRequest.predicate = [NSPredicate predicateWithFormat:@"day == %@ AND timeStamp >= %f", dayEntity, startTime];+ segmentFetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:YES]]; // Consistent ordering+ segmentFetchRequest.propertiesToFetch = @[@"url", @"timeStamp", @"duration", @"orientation"];+ segmentFetchRequest.resultType = NSDictionaryResultType; // Return dictionaries directly++ NSArray *fetchedSegments = [context executeFetchRequest:segmentFetchRequest error:&error];+ if (error) return;++ processedSegments = fetchedSegments;+ }];++ return processedSegments;+}+- (NSArray *)fetchFramesWithURLsFromCoreDataForDateParam:(NSString *)dateParam+ start:(NSInteger)start+ context:(NSManagedObjectContext *)context {+ if (!context) return @[];++ __block NSArray *copiedSegments = @[];++ [context performBlockAndWait:^{+ NSError *error = nil;++ // Fetch the DayEntity for the given date+ NSFetchRequest *dayFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"DayEntity"];+ dayFetchRequest.predicate = [NSPredicate predicateWithFormat:@"date == %@", dateParam];++ NSArray *fetchedDays = [context executeFetchRequest:dayFetchRequest error:&error];++ if (error) return;+ if (fetchedDays.count == 0) return;++ NSManagedObject *dayEntity = fetchedDays.firstObject;+ NSOrderedSet *segments = [dayEntity valueForKey:@"segments"];++ // Slice the segments based on the 'start' parameter to avoid fetching everything+ if (start >= segments.count) return;++ copiedSegments = [[segments array] subarrayWithRange:NSMakeRange(start, segments.count - start)];+ }];++ // Process outside of performBlockAndWait to avoid blocking Core Data+ NSMutableArray *framesWithURLs = [NSMutableArray array];++ for (NSManagedObject *segment in copiedSegments) {+ NSString *url = [segment valueForKey:@"url"];+ NSArray *frames = [[segment valueForKey:@"frames"] array]; // Copy frames++ for (NSManagedObject *frame in frames) {+ double frameTimeStamp = [[frame valueForKey:@"frame_timeStamp"] doubleValue];+ double aspectRatio = [[frame valueForKey:@"aspect_ratio"] doubleValue];+ int res = [[frame valueForKey:@"res"] intValue];++ NSMutableArray *squareDicts = [NSMutableArray array];+ NSArray *squares = [[frame valueForKey:@"squares"] array]; // Copy squares++ for (NSManagedObject *square in squares) {+ double originX = [[square valueForKey:@"originX"] doubleValue];+ double originY = [[square valueForKey:@"originY"] doubleValue];+ double bottomRightX = [[square valueForKey:@"bottomRightX"] doubleValue];+ double bottomRightY = [[square valueForKey:@"bottomRightY"] doubleValue];+ int classIndex = [[square valueForKey:@"classIndex"] intValue];++ NSDictionary *squareDict = @{+ @"originX": @(originX),+ @"originY": @(originY),+ @"bottomRightX": @(bottomRightX),+ @"bottomRightY": @(bottomRightY),+ @"classIndex": @(classIndex)+ };++ [squareDicts addObject:squareDict];+ }++ NSDictionary *frameDict = @{+ @"url": url, // Include the segment's URL+ @"frame_timeStamp": @(frameTimeStamp),+ @"aspect_ratio": @(aspectRatio),+ @"res": @(res),+ @"squares": squareDicts+ };++ [framesWithURLs addObject:frameDict];+ }+ }+ return framesWithURLs;+}++- (void)sendJson200:(NSArray *)array toClient:(int)clientSocket {+ NSError *error;+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:&error];+ NSString *httpHeader = [NSString stringWithFormat:@"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %lu\r\n\r\n", (unsigned long)jsonData.length];+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, jsonData.bytes, jsonData.length, 0);+}++- (void)handleClientRequest:(int)clientSocket withBasePath:(NSString *)basePath {+ char requestBuffer[1024];+ ssize_t bytesRead = recv(clientSocket, requestBuffer, sizeof(requestBuffer) - 1, 0);+ if (bytesRead < 0) return;+ requestBuffer[bytesRead] = '\0';+ NSString *request = [NSString stringWithUTF8String:requestBuffer];+ NSRange range = [request rangeOfString:@"GET /"];+ if (range.location == NSNotFound) {+ dprintf(clientSocket, "HTTP/1.1 400 Bad Request\r\n\r\n");+ return;+ }+ NSString *filePath = [[request substringFromIndex:NSMaxRange(range)] componentsSeparatedByString:@" "][0];+ filePath = [filePath stringByRemovingPercentEncoding];+ if ([filePath isEqualToString:@"/"]) filePath = @"";++ NSMutableDictionary<NSString *, NSString *> *queryParams = [NSMutableDictionary dictionary];+ NSRange queryRange = [filePath rangeOfString:@"?"];+ if (queryRange.location != NSNotFound) {+ NSString *queryString = [filePath substringFromIndex:queryRange.location + 1];+ NSArray<NSString *> *queryItems = [queryString componentsSeparatedByString:@"&"];++ for (NSString *item in queryItems) {+ NSArray<NSString *> *keyValue = [item componentsSeparatedByString:@"="];+ if (keyValue.count == 2) {+ queryParams[keyValue[0]] = keyValue[1];+ }+ }+ }++ if ([filePath hasPrefix:@"multicamera"] || [filePath hasPrefix:@"events"]) {+ NSString *fileName = [filePath hasPrefix:@"multicamera"] ? @"multicamera.html" : @"events.html";+ NSString *playerFilePath = [[NSBundle mainBundle] pathForResource:[fileName stringByDeletingPathExtension] ofType:@"html"];++ if (playerFilePath && [[NSFileManager defaultManager] fileExistsAtPath:playerFilePath]) {+ FILE *file = fopen([playerFilePath UTF8String], "rb");+ if (file) {+ fseek(file, 0, SEEK_END);+ NSUInteger fileSize = ftell(file);+ fseek(file, 0, SEEK_SET);+ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: text/html\r\n");+ dprintf(clientSocket, "Content-Length: %lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:fileSize];+ fclose(file);+ return;+ }+ }+ dprintf(clientSocket, "HTTP/1.1 500 Internal Server Error\r\n\r\n");+ return;+ }+ if ([filePath hasPrefix:@"get-segments"]) {+ self.last_req_time = [NSDate now];+ if (self.segment_length == 60) {+ self.segment_length = 1;+ sleep(3);//todo hack, not good because clips wait too+ }++ if (!queryParams[@"date"]) {+ 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;+ }++ double startTime = queryParams[@"start"] ? [queryParams[@"start"] doubleValue] : 0;+ NSArray *segmentsForDate = [self fetchAndProcessSegmentsFromCoreDataForDateParam:queryParams[@"date"]+ start:startTime+ context:self.context];++ [self sendJson200:segmentsForDate toClient:clientSocket];+ }++ if ([filePath hasPrefix:@"download"]) {+ if (!queryParams[@"start"] || !queryParams[@"end"]) {+ NSString *errorResponse = @"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n[{\"error\": \"Missing or invalid start/end parameter\"}]";+ send(clientSocket, [errorResponse UTF8String], errorResponse.length, 0);+ return;+ }++ NSTimeInterval startTimeStamp = [queryParams[@"start"] doubleValue];+ NSTimeInterval endTimeStamp = [queryParams[@"end"] doubleValue];++ NSString *outputPath = [self processVideoDownloadWithLowRes:NO+ startTime:startTimeStamp+ endTime:endTimeStamp+ context:self.context];++ if (!outputPath) {+ NSString *errorResponse = @"HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\n\r\n[{\"error\": \"No video found for the specified time range\"}]";+ send(clientSocket, [errorResponse UTF8String], errorResponse.length, 0);+ return;+ }++ // Send the file+ FILE *mergedFile = fopen([outputPath UTF8String], "rb");+ if (!mergedFile) {+ NSString *errorResponse = @"HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\n\r\n[{\"error\": \"Failed to open video file\"}]";+ send(clientSocket, [errorResponse UTF8String], errorResponse.length, 0);+ return;+ }++ NSFileManager *fileManager = [NSFileManager defaultManager];+ NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:outputPath error:nil];+ NSUInteger fileSize = [fileAttributes[NSFileSize] unsignedIntegerValue];++ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: video/mp4\r\n");+ dprintf(clientSocket, "Content-Disposition: attachment; filename=\"%s-%s.mp4\"\r\n",+ [[^{ NSDateFormatter *f = [NSDateFormatter new]; f.dateFormat = @"yyyy-MM-dd_HH-mm-ss"; return f; }() stringFromDate:[NSDate dateWithTimeIntervalSince1970:startTimeStamp]] UTF8String],+ [[^{ NSDateFormatter *f = [NSDateFormatter new]; f.dateFormat = @"yyyy-MM-dd_HH-mm-ss"; return f; }() stringFromDate:[NSDate dateWithTimeIntervalSince1970:endTimeStamp]] UTF8String]);+ dprintf(clientSocket, "Content-Length: %lu\r\n", (unsigned long)fileSize);+ dprintf(clientSocket, "Accept-Ranges: bytes\r\n");+ dprintf(clientSocket, "\r\n");++ char buffer[64 * 1024];+ size_t bytesRead;+ while ((bytesRead = fread(buffer, 1, sizeof(buffer), mergedFile)) > 0) {+ ssize_t bytesSent = send(clientSocket, buffer, bytesRead, 0);+ if (bytesSent < 0) break;+ }+ fclose(mergedFile);++ // Clean up+ [[NSFileManager defaultManager] removeItemAtPath:outputPath error:nil];+ }++ if ([filePath hasPrefix:@"get-frames"]) {+ if (!queryParams[@"url"]) {+ NSString *httpHeader = @"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n";+ NSString *errorMessage = @"{\"error\": \"Missing or invalid url parameter\"}";+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);+ return;+ }+ [self sendJson200:[self fetchFramesForURL:queryParams[@"url"] context:self.context] toClient:clientSocket];+ }++ if ([filePath hasPrefix:@"get-events"]) [self sendJson200: [self fetchEventDataFromCoreData:self.context] toClient:clientSocket];++ if ([filePath hasPrefix:@"delete-event"]) {+ NSURLComponents *components = [NSURLComponents componentsWithString:[NSString stringWithFormat:@"http://localhost/%@", filePath]];+ NSString *eventTimeStamp = nil;+ NSString *eventTimeStamp_end = nil;++ for (NSURLQueryItem *item in components.queryItems) {+ if ([item.name isEqualToString:@"timeStamp"]) {+ eventTimeStamp = item.value;+ }+ if ([item.name isEqualToString:@"end"]) {+ eventTimeStamp_end = item.value;+ }+ }++ if(!eventTimeStamp_end) eventTimeStamp_end = eventTimeStamp;++ if (!eventTimeStamp) {+ NSString *httpHeader = @"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n";+ NSString *errorMessage = @"{\"error\": \"Missing timeStamp parameter\"}";+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);+ return;+ }+++ BOOL success = [self deleteEventsBetweenStartTimeStamp:[eventTimeStamp doubleValue] andEndTimeStamp:[eventTimeStamp_end doubleValue] ];++ if (success) {+ NSString *httpHeader = @"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n";+ NSString *successMessage = @"{\"success\": \"Event and associated image deleted\"}";+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [successMessage UTF8String], successMessage.length, 0);+ } else {+ NSString *httpHeader = @"HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\n\r\n";+ NSString *errorMessage = @"{\"error\": \"Event not found\"}";+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);+ }+ }++ NSString *fullPath = [basePath stringByAppendingPathComponent:filePath];+ queryRange = [fullPath rangeOfString:@"?"];+ if (queryRange.location != NSNotFound) {+ fullPath = [fullPath substringToIndex:queryRange.location];+ }++ BOOL isDirectory = YES;+ if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory]) {+ dprintf(clientSocket, "HTTP/1.1 404 Not Found\r\n\r\n");+ return;+ }+++ if (isDirectory) { //todo, change url maybe+ NSString *playerFilePath = [[NSBundle mainBundle] pathForResource:@"player" ofType:@"html"];+ if (playerFilePath && [[NSFileManager defaultManager] fileExistsAtPath:playerFilePath]) {+ FILE *file = fopen([playerFilePath UTF8String], "rb");+ if (file) {+ fseek(file, 0, SEEK_END);+ NSUInteger fileSize = ftell(file);+ fseek(file, 0, SEEK_SET);+ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: text/html\r\n");+ dprintf(clientSocket, "Content-Length: %lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:fileSize];+ fclose(file);+ return;+ }+ }+ dprintf(clientSocket, "HTTP/1.1 500 Internal Server Error\r\n\r\n");+ return;+ }++ FILE *file = fopen([fullPath UTF8String], "rb");+ if (!file) {+ dprintf(clientSocket, "HTTP/1.1 500 Internal Server Error\r\n\r\n");+ return;+ }+ fseek(file, 0, SEEK_END);+ NSUInteger fileSize = ftell(file);+ fseek(file, 0, SEEK_SET);++ NSString *fileExtension = [[fullPath pathExtension] lowercaseString];++ // Check if the file exists in the app bundle+ NSString *bundlePath = [[NSBundle mainBundle] pathForResource:[fullPath stringByDeletingPathExtension] ofType:fileExtension];+ if (bundlePath) {+ fullPath = bundlePath;+ }++ if ([fileExtension isEqualToString:@"mp4"]) {+ range = [request rangeOfString:@"Range: bytes="];+ if (range.location != NSNotFound) {+ range = [request rangeOfString:@"bytes="];+ NSString *byteRange = [request substringFromIndex:NSMaxRange(range)];+ byteRange = [byteRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];+ NSArray<NSString *> *rangeParts = [byteRange componentsSeparatedByString:@"-"];+ NSUInteger start = [rangeParts[0] integerValue];+ NSUInteger end = (rangeParts.count > 1 && rangeParts[1].length > 0) ? [rangeParts[1] integerValue] : fileSize - 1;++ if (start >= fileSize || end >= fileSize || start > end) {+ dprintf(clientSocket, "HTTP/1.1 416 Requested Range Not Satisfiable\r\n");+ dprintf(clientSocket, "Content-Range: bytes */%lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ } else {+ fseek(file, start, SEEK_SET);+ NSUInteger contentLength = end - start + 1;+ dprintf(clientSocket, "HTTP/1.1 206 Partial Content\r\n");+ dprintf(clientSocket, "Content-Type: video/mp4\r\n");+ dprintf(clientSocket, "Content-Range: bytes %lu-%lu/%lu\r\n", start, end, fileSize);+ dprintf(clientSocket, "Content-Length: %lu\r\n", contentLength);+ dprintf(clientSocket, "Accept-Ranges: bytes\r\n");+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:contentLength];+ }+ }+ } else if ([fileExtension isEqualToString:@"html"]) {+ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: text/html\r\n");+ dprintf(clientSocket, "Content-Length: %lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:fileSize];+ } else if ([fileExtension isEqualToString:@"txt"]) {+ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: text/plain\r\n");+ dprintf(clientSocket, "Content-Length: %lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:fileSize];+ } else if ([fileExtension isEqualToString:@"jpg"]) {+ dprintf(clientSocket, "HTTP/1.1 200 OK\r\n");+ dprintf(clientSocket, "Content-Type: image/jpg\r\n");+ dprintf(clientSocket, "Content-Length: %lu\r\n", fileSize);+ dprintf(clientSocket, "\r\n");+ [self sendFileData:file toSocket:clientSocket withContentLength:fileSize];+ }++ fclose(file);+}++- (BOOL)deleteEventsBetweenStartTimeStamp:(NSTimeInterval)startTimeStamp andEndTimeStamp:(NSTimeInterval)endTimeStamp {+ __block BOOL success = NO;+ const int maxRetries = 3;+ int attempt = 0;++ if (!self.context) return NO;++ // Verify entity exists in model+ NSEntityDescription *entity = [NSEntityDescription entityForName:@"EventEntity"+ inManagedObjectContext:self.context];+ if (!entity) return NO;++ // Validate timestamp range+ if (startTimeStamp > endTimeStamp) return NO;++ // Get the app's Documents directory and images folder+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);+ NSString *documentsDirectory = [paths firstObject];+ NSString *imagesDirectory = [documentsDirectory stringByAppendingPathComponent:@"images"];++ while (attempt < maxRetries && !success) {+ attempt++;+ [self.context performBlockAndWait:^{+ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];+ if (!fetchRequest) {+ success = NO;+ return;+ }++ [fetchRequest setEntity:entity];+ double epsilon = 1.0; // 1-second buffer on both ends+ NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %lf) AND (timeStamp <= %lf)",+ startTimeStamp - epsilon, endTimeStamp + epsilon];+ [fetchRequest setPredicate:predicate];++ // Execute fetch with error handling+ NSError *fetchError = nil;+ NSArray *events = nil;+ @try {+ events = [self.context executeFetchRequest:fetchRequest error:&fetchError];+ }+ @catch (NSException *exception) {+ success = NO;+ return;+ }++ if (fetchError) {+ success = NO;+ return;+ }++ if (!events) {+ success = YES; // Treat as success if no objects to delete+ return;+ }++ if (events.count == 0) {+ success = YES; // No events in range, still a success+ return;+ }++ // Delete events and their associated images+ NSFileManager *fileManager = [NSFileManager defaultManager];+ for (NSManagedObject *event in events) {+ NSNumber *timeStampNumber = [event valueForKey:@"timeStamp"];+ if (!timeStampNumber) {+ [self.context deleteObject:event];+ continue;+ }++ NSTimeInterval timeStamp = [timeStampNumber doubleValue];+ long long roundedTimestamp = (long long)floor(timeStamp); // Floor to integer+ NSString *imageFileName = [NSString stringWithFormat:@"%lld", roundedTimestamp];+ NSString *smallImageFilePath = [imagesDirectory stringByAppendingPathComponent:[imageFileName stringByAppendingString:@"_small.jpg"]];++ NSError *fileError = nil;+ if ([fileManager fileExistsAtPath:smallImageFilePath]) [fileManager removeItemAtPath:smallImageFilePath error:&fileError];+ [self.context deleteObject:event];+ }++ // Save changes+ if ([self.context hasChanges]) {+ NSError *saveError = nil;+ @try {+ success = [self.context save:&saveError];+ }+ @catch (NSException *exception) {+ success = NO;+ }+ } else {+ success = YES; // No changes to save, but this shouldn't happen if events were deleted+ }+ }];+ if (!success) [NSThread sleepForTimeInterval:0.1];+ }+ return success;+}++- (NSArray *)fetchFramesForURL:(NSString *)url context:(NSManagedObjectContext *)context {+ if (!context) return @[];+ __block NSArray *framesForURL = @[];++ [context performBlockAndWait:^{+ NSError *error = nil;++ // Fetch the single segment with frames and squares pre-fetched+ NSFetchRequest *segmentFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"SegmentEntity"];+ segmentFetchRequest.predicate = [NSPredicate predicateWithFormat:@"url == %@", url];+ segmentFetchRequest.fetchLimit = 1; // Only one segment exists per URL+ segmentFetchRequest.relationshipKeyPathsForPrefetching = @[@"frames", @"frames.squares"];+ segmentFetchRequest.returnsObjectsAsFaults = NO;++ NSArray *segments = [context executeFetchRequest:segmentFetchRequest error:&error];+ if (error) return;+ if (segments.count == 0) return;+ NSManagedObject *segment = segments.firstObject;+ NSArray *frames = [[segment valueForKey:@"frames"] array];+ NSMutableArray *tempFrames = [NSMutableArray arrayWithCapacity:frames.count];++ // Process frames and squares+ for (NSManagedObject *frame in frames) {+ double frameTimeStamp = [[frame valueForKey:@"frame_timeStamp"] doubleValue];+ double aspectRatio = [[frame valueForKey:@"aspect_ratio"] doubleValue];+ int res = [[frame valueForKey:@"res"] intValue];++ NSArray *squares = [[frame valueForKey:@"squares"] array];+ NSMutableArray *squareDicts = [NSMutableArray arrayWithCapacity:squares.count];++ for (NSManagedObject *square in squares) {+ NSNumber *originXNum = [square valueForKey:@"originX"];+ NSNumber *originYNum = [square valueForKey:@"originY"];+ NSNumber *bottomRightXNum = [square valueForKey:@"bottomRightX"];+ NSNumber *bottomRightYNum = [square valueForKey:@"bottomRightY"];+ NSNumber *classIndexNum = [square valueForKey:@"classIndex"];++ [squareDicts addObject:@{+ @"originX": @(originXNum ? [originXNum doubleValue] : 0.0),+ @"originY": @(originYNum ? [originYNum doubleValue] : 0.0),+ @"bottomRightX": @(bottomRightXNum ? [bottomRightXNum doubleValue] : 0.0),+ @"bottomRightY": @(bottomRightYNum ? [bottomRightYNum doubleValue] : 0.0),+ @"classIndex": @(classIndexNum ? [classIndexNum intValue] : 0)+ }];+ }++ [tempFrames addObject:@{+ @"url": url,+ @"frame_timeStamp": @(frameTimeStamp),+ @"aspect_ratio": @(aspectRatio),+ @"res": @(res),+ @"squares": squareDicts+ }];+ }++ framesForURL = [tempFrames copy];+ }];+ return framesForURL;+}+++ (void)sendDeviceTokenToServer {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSString *deviceToken = [defaults stringForKey:@"device_token"];+ if (!deviceToken || deviceToken.length == 0) return;+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (!sessionToken || sessionToken.length == 0) return;+ [FileServer performPostRequestWithURL:@"https://rors.ai/add_device"+ method:@"POST"+ contentType:@"application/json"+ body:@{@"device_token": deviceToken, @"session_token": sessionToken}+ completionHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) { if (error) return; }];+}+++ (void)performPostRequestWithURL:(NSString *)urlString+ method:(NSString *)method+ contentType:(NSString *)contentType+ body:(id)body+ completionHandler:(void (^)(NSData *data, NSHTTPURLResponse *response, NSError *error))completion {+ NSURL *url = [NSURL URLWithString:urlString];+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ request.HTTPMethod = method;+ [request setValue:contentType forHTTPHeaderField:@"Content-Type"];++ // Handle body based on content type+ if ([contentType isEqualToString:@"application/json"] && [body isKindOfClass:[NSDictionary class]]) {+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:nil];+ request.HTTPBody = jsonData;+ } else if ([contentType containsString:@"multipart/form-data"] && [body isKindOfClass:[NSData class]]) {+ [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[(NSData *)body length]] forHTTPHeaderField:@"Content-Length"];+ request.HTTPBody = body;+ } else if (body && [body isKindOfClass:[NSData class]]) {+ request.HTTPBody = body; // Raw data for other cases+ }++ NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ if (completion) {+ completion(data, httpResponse, error);+ }+ }];+ [task resume];+}++- (void)concatenateMP4Files:(NSArray<NSString *> *)filePaths completion:(void (^)(NSString *outputPath, NSError *error))completion {+ AVMutableComposition *composition = [AVMutableComposition composition];+ AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];++ CMTime currentTime = kCMTimeZero;++ for (NSString *filePath in filePaths) {+ AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:filePath]];++ if (asset.tracks.count == 0) continue;+ AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];++ NSError *error = nil;+ [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration)+ ofTrack:videoAssetTrack+ atTime:currentTime+ error:&error];+ currentTime = CMTimeAdd(currentTime, asset.duration);+ }++ NSString *outputPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject+ stringByAppendingPathComponent:@"merged_video.mp4"];+ NSURL *outputURL = [NSURL fileURLWithPath:outputPath];+ [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];//todo remove after user has downloaded too?++ AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];+ exportSession.outputURL = outputURL;+ exportSession.outputFileType = AVFileTypeMPEG4;+ exportSession.shouldOptimizeForNetworkUse = YES;++ [exportSession exportAsynchronouslyWithCompletionHandler:^{+ if (exportSession.status == AVAssetExportSessionStatusCompleted) {+ completion(outputPath, nil);+ } else {+ completion(nil, exportSession.error);+ }+ }];+}++- (NSArray *)fetchEventDataFromCoreData:(NSManagedObjectContext *)context {+ if (!context) return @[];+ __block NSArray *eventDataArray = nil;++ // Perform fetch synchronously on the context's queue+ [context performBlockAndWait:^{+ NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EventEntity"];+ NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp"+ ascending:YES];+ [fetchRequest setSortDescriptors:@[sortDescriptor]];++ NSError *error = nil;+ NSArray *fetchedEvents = nil;++ @try {+ fetchedEvents = [context executeFetchRequest:fetchRequest error:&error];+ }+ @catch (NSException *exception) {+ eventDataArray = @[];+ return;+ }++ if (error || !fetchedEvents) {+ eventDataArray = @[];+ return;+ }++ NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:fetchedEvents.count];+ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];+ [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];++ for (NSManagedObject *event in fetchedEvents) {+ // Safely access attributes with nil checks+ NSNumber *timeStampNumber = [event valueForKey:@"timeStamp"];+ if (!timeStampNumber) continue;++ NSTimeInterval timestamp = [timeStampNumber doubleValue];+ long long roundedTimestamp = (long long)timestamp;+ NSString *readableDate = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];++ NSDictionary *eventDict = @{+ @"timeStamp": readableDate ?: @"",+ @"classType": [event valueForKey:@"classType"] ?: @"unknown",+ @"quantity": [event valueForKey:@"quantity"] ?: @(0),+ @"imageURL": [NSString stringWithFormat:@"images/%lld_small.jpg", roundedTimestamp]+ };+ [tempArray addObject:eventDict];+ }++ eventDataArray = [tempArray copy];+ }];++ return eventDataArray ?: @[];+}++- (void)sendFileData:(FILE *)file toSocket:(int)socket withContentLength:(NSUInteger)contentLength {+ char buffer[64 * 1024];+ size_t bytesToSend = contentLength;+ while (bytesToSend > 0) {+ size_t chunkSize = fread(buffer, 1, sizeof(buffer), file);+ if (chunkSize == 0) break;+ ssize_t bytesSent = send(socket, buffer, chunkSize, 0);+ if (bytesSent < 0) break;+ bytesToSend -= bytesSent;+ }+}++- (void)deleteAllDayEntitiesAndEventsInContext:(NSManagedObjectContext *)context {+ NSError *fetchError = nil;++ // Fetch and delete all EventEntity objects+ NSFetchRequest *eventFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EventEntity"];+ NSArray *eventEntities = [context executeFetchRequest:eventFetchRequest error:&fetchError];++ if (fetchError) return;+ for (NSManagedObject *eventEntity in eventEntities) {+ [context deleteObject:eventEntity];+ }++ // Fetch and delete all DayEntity objects+ NSFetchRequest *dayFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DayEntity"];+ NSArray *dayEntities = [context executeFetchRequest:dayFetchRequest error:&fetchError];++ if (fetchError) return;++ for (NSManagedObject *dayEntity in dayEntities) {+ [context deleteObject:dayEntity];+ }++ // Save the context after deletion+ NSError *saveError = nil;+ [context save:&saveError];+}+++- (NSString *)processVideoDownloadWithLowRes:(BOOL)low_res+ startTime:(NSTimeInterval)startTimeStamp+ endTime:(NSTimeInterval)endTimeStamp+ context:(NSManagedObjectContext *)context {+ NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:startTimeStamp];+ NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:endTimeStamp];+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"yyyy-MM-dd"];++ NSString *formattedStartDate = [formatter stringFromDate:startDate];+ NSString *formattedEndDate = [formatter stringFromDate:endDate];++ if (![formattedStartDate isEqualToString:formattedEndDate]) {+ return nil;+ }++ NSCalendar *calendar = [NSCalendar currentCalendar];+ NSDate *midnight = [calendar startOfDayForDate:startDate];++ NSTimeInterval relativeStart = [startDate timeIntervalSinceDate:midnight];+ NSTimeInterval relativeEnd = [endDate timeIntervalSinceDate:midnight];+ NSTimeInterval requestedDuration = relativeEnd - relativeStart;++ NSArray *segments = [self fetchAndProcessSegmentsFromCoreDataForDateParam:formattedStartDate start:0 context:context];++ if (segments.count == 0) {+ return nil;+ }++ NSMutableArray<NSString *> *segmentFilePaths = [NSMutableArray array];+ NSString *tempDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"temp"];+ [[NSFileManager defaultManager] createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:nil];++ dispatch_semaphore_t trimSema = dispatch_semaphore_create(0);+ __block NSInteger trimCount = 0;++ NSInteger orientation = -1;++ for (NSInteger i = 0; i < segments.count; i++) {+ NSTimeInterval segmentStart = [segments[i][@"timeStamp"] doubleValue];+ NSTimeInterval segmentDuration = [segments[i][@"duration"] doubleValue];+ NSTimeInterval segmentEnd = segmentStart + segmentDuration;++ if (segmentEnd <= relativeStart || segmentStart >= relativeEnd) {+ continue;+ }+ if(orientation == -1) orientation = [segments[i][@"orientation"] intValue];+++ NSString *originalFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:segments[i][@"url"]];+ if (![[NSFileManager defaultManager] fileExistsAtPath:originalFilePath]) continue;++ NSTimeInterval trimStart = MAX(0, relativeStart - segmentStart);+ NSTimeInterval trimEnd = MIN(segmentDuration, relativeEnd - segmentStart);+ NSTimeInterval trimmedDuration = trimEnd - trimStart;++ NSString *trimmedFilePath = [tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"trimmed_%ld.mp4", (long)i]];+ AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:originalFilePath]];+ AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];+ exportSession.outputFileType = AVFileTypeMPEG4;+ exportSession.outputURL = [NSURL fileURLWithPath:trimmedFilePath];++ CMTime startTime = CMTimeMakeWithSeconds(trimStart, 600);+ CMTime durationTime = CMTimeMakeWithSeconds(trimmedDuration, 600);+ CMTimeRange timeRange = CMTimeRangeMake(startTime, durationTime);+ if (CMTimeCompare(CMTimeAdd(startTime, durationTime), CMTimeMakeWithSeconds(segmentDuration, 600)) > 0) {+ durationTime = CMTimeSubtract(CMTimeMakeWithSeconds(segmentDuration, 600), startTime);+ timeRange = CMTimeRangeMake(startTime, durationTime);+ }+ exportSession.timeRange = timeRange;++ AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];+ CGSize naturalSize = videoTrack.naturalSize;+ AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];+ videoComposition.frameDuration = CMTimeMake(1, 24); // 24 fps++ AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];+ instruction.timeRange = timeRange;+ AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];+ CGAffineTransform transform = CGAffineTransformIdentity;+ CGSize renderSize = naturalSize;++ if (low_res) {+ CGFloat scale = MIN(1280.0 / naturalSize.width, 720.0 / naturalSize.height);+ transform = CGAffineTransformScale(transform, scale, scale);+ renderSize = CGSizeApplyAffineTransform(naturalSize, CGAffineTransformMakeScale(scale, scale));+ }++ if (orientation == 1) {+ renderSize = CGSizeMake(naturalSize.height, naturalSize.width);+ CGAffineTransform translate = CGAffineTransformMakeTranslation(naturalSize.height, 0);+ CGAffineTransform rotate = CGAffineTransformRotate(translate, M_PI_2);+ transform = rotate;+ } else if (orientation == 4) {+ transform = CGAffineTransformTranslate(transform, naturalSize.width / 2.0, naturalSize.height / 2.0);+ transform = CGAffineTransformRotate(transform, M_PI);+ transform = CGAffineTransformTranslate(transform, -naturalSize.width / 2.0, -naturalSize.height / 2.0);+ }++ [layerInstruction setTransform:transform atTime:kCMTimeZero];+ instruction.layerInstructions = @[layerInstruction];+ videoComposition.instructions = @[instruction];+ videoComposition.renderSize = renderSize;++ if (low_res) {+ exportSession.videoComposition = videoComposition;+ exportSession.shouldOptimizeForNetworkUse = YES;+ exportSession.fileLengthLimit = 20 * 1024 * 1024 * (trimmedDuration / 60.0);+ } else if (orientation == 1 || orientation == 4) {+ exportSession.videoComposition = videoComposition;+ }++ trimCount++;+ [exportSession exportAsynchronouslyWithCompletionHandler:^{+ dispatch_semaphore_signal(trimSema);+ }];+ }++ for (NSInteger i = 0; i < trimCount; i++) {+ dispatch_semaphore_wait(trimSema, DISPATCH_TIME_FOREVER);+ }++ for (NSInteger i = 0; i < segments.count; i++) {+ NSString *trimmedFilePath = [tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"trimmed_%ld.mp4", (long)i]];+ if ([[NSFileManager defaultManager] fileExistsAtPath:trimmedFilePath]) {+ [segmentFilePaths addObject:trimmedFilePath];+ }+ }++ if (segmentFilePaths.count == 0) {+ return nil;+ }++ dispatch_semaphore_t sema = dispatch_semaphore_create(0);+ __block NSString *outputPath = nil;+ __block NSError *mergeError = nil;++ [self concatenateMP4Files:segmentFilePaths completion:^(NSString *resultPath, NSError *error) {+ outputPath = resultPath;+ mergeError = error;+ dispatch_semaphore_signal(sema);+ }];++ dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);++ for (NSString *tempFile in segmentFilePaths) {+ if ([tempFile containsString:@"trimmed"]) {+ [[NSFileManager defaultManager] removeItemAtPath:tempFile error:nil];+ }+ }++ if (mergeError || !outputPath || ![[NSFileManager defaultManager] fileExistsAtPath:outputPath]) {+ return nil;+ }++ // Rename the output file using timestamps+ NSDateFormatter *renameFormatter = [[NSDateFormatter alloc] init];+ [renameFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];+ NSString *startTimeStr = [renameFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:startTimeStamp]];+ NSString *endTimeStr = [renameFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:endTimeStamp]];+ NSString *newFileName = [NSString stringWithFormat:@"%@-%@.mp4", startTimeStr, endTimeStr];++ // Get the directory of the original outputPath and construct the new path+ NSString *directory = [outputPath stringByDeletingLastPathComponent];+ NSString *newOutputPath = [directory stringByAppendingPathComponent:newFileName];++ // Rename the file+ NSError *renameError = nil;+ [[NSFileManager defaultManager] moveItemAtPath:outputPath toPath:newOutputPath error:&renameError];+ if (renameError) {+ return outputPath;+ }++ return newOutputPath;+}++@enddiff --git a/ios/clearcam/GalleryViewController.h b/ios/clearcam/GalleryViewController.hnew file mode 100644index 0000000..1f26169--- /dev/null+++ b/ios/clearcam/GalleryViewController.h@@ -0,0 +1,6 @@+#import <UIKit/UIKit.h>++@interface GalleryViewController : UIViewController+- (void)getEvents;++@enddiff --git a/ios/clearcam/GalleryViewController.m b/ios/clearcam/GalleryViewController.mnew file mode 100644index 0000000..efd508e--- /dev/null+++ b/ios/clearcam/GalleryViewController.m@@ -0,0 +1,789 @@+#import "GalleryViewController.h"+#import "StoreManager.h"+#import "SecretManager.h"+#import <AVKit/AVKit.h>+#import <AVFoundation/AVFoundation.h>+#import "LiveViewController.h"++@interface VideoTableViewCell : UITableViewCell+@property (nonatomic, strong) UIImageView *thumbnailView;+@property (nonatomic, strong) UILabel *titleLabel;+@property (nonatomic, strong) UIButton *menuButton;+@end++@implementation VideoTableViewCell++- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {+ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];+ if (self) {+ [self setupUI];+ }+ return self;+}++- (void)setupUI {+ self.thumbnailView = [[UIImageView alloc] init];+ self.thumbnailView.contentMode = UIViewContentModeScaleAspectFill;+ self.thumbnailView.clipsToBounds = YES;+ self.thumbnailView.layer.cornerRadius = 4;+ [self.contentView addSubview:self.thumbnailView];++ self.titleLabel = [[UILabel alloc] init];+ self.titleLabel.numberOfLines = 1;+ self.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];+ [self.contentView addSubview:self.titleLabel];++ self.menuButton = [UIButton buttonWithType:UIButtonTypeSystem];+ UIImage *ellipsisImage = [UIImage systemImageNamed:@"ellipsis"];+ UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithScale:UIImageSymbolScaleLarge];+ UIImage *verticalEllipsis = [ellipsisImage imageByApplyingSymbolConfiguration:config];+ [self.menuButton setImage:verticalEllipsis forState:UIControlStateNormal];+ self.menuButton.tintColor = [UIColor systemGrayColor];+ self.menuButton.transform = CGAffineTransformMakeRotation(M_PI_2);+ [self.contentView addSubview:self.menuButton];++ self.thumbnailView.translatesAutoresizingMaskIntoConstraints = NO;+ self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;+ self.menuButton.translatesAutoresizingMaskIntoConstraints = NO;++ [NSLayoutConstraint activateConstraints:@[+ [self.thumbnailView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],+ [self.thumbnailView.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],+ [self.thumbnailView.widthAnchor constraintEqualToConstant:120],+ [self.thumbnailView.heightAnchor constraintEqualToConstant:80],++ [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.thumbnailView.trailingAnchor constant:12],+ [self.titleLabel.trailingAnchor constraintEqualToAnchor:self.menuButton.leadingAnchor constant:-12],+ [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],++ [self.menuButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],+ [self.menuButton.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],+ [self.menuButton.widthAnchor constraintEqualToConstant:44],+ [self.menuButton.heightAnchor constraintEqualToConstant:44]+ ]];+}++@end++// Modified GalleryViewController with tabs+@interface GalleryViewController () <UITableViewDelegate, UITableViewDataSource>+@property (nonatomic, strong) UITabBarController *tabController;+@property (nonatomic, strong) UIViewController *eventsViewController;+@property (nonatomic, strong) LiveViewController *liveViewController;+@property (nonatomic, strong) UITableView *tableView;+@property (nonatomic, strong) NSMutableArray<NSString *> *videoFiles;+@property (nonatomic, strong) NSString *downloadDirectory;+@property (nonatomic, strong) NSURLSession *downloadSession;+@property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *groupedVideos;+@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles;+@property (nonatomic, strong) UIRefreshControl *refreshControl;+@property (nonatomic, assign) BOOL isLoadingVideos;+@property (nonatomic, strong) NSMutableSet<NSString *> *loadedFilenames;+@property (nonatomic, strong) NSTimer *refreshTimer;+@end++@implementation GalleryViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.view.backgroundColor = [UIColor systemBackgroundColor];+ self.navigationController.navigationBarHidden = NO;++ // Initialize view controllers for tabs+ self.eventsViewController = [[UIViewController alloc] init];+ self.eventsViewController.title = NSLocalizedString(@"events", @"Title for events screen");+ self.eventsViewController.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"events", @"Title for events screen")+ image:[UIImage systemImageNamed:@"photo.on.rectangle"]+ tag:0];++ self.liveViewController = [[LiveViewController alloc] init];+ self.liveViewController.title = @"Live Cameras";+ self.liveViewController.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"live", @"Title for live screen")+ image:[UIImage systemImageNamed:@"video"]+ tag:1];++ self.tabController = [[UITabBarController alloc] init];+ self.tabController.viewControllers = @[self.eventsViewController, self.liveViewController];++ [self addChildViewController:self.tabController];+ [self.view addSubview:self.tabController.view];+ self.tabController.view.frame = self.view.bounds;+ [self.tabController didMoveToParentViewController:self];++ // Move all the existing events UI to the eventsViewController+ [self setupEventsViewController];++ self.videoFiles = [NSMutableArray array];+ self.groupedVideos = [NSMutableDictionary dictionary];+ self.sectionTitles = [NSMutableArray array];+ self.isLoadingVideos = NO;++ NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];+ config.timeoutIntervalForRequest = 60.0;+ config.timeoutIntervalForResource = 600.0;+ self.downloadSession = [NSURLSession sessionWithConfiguration:config];+ self.loadedFilenames = [NSMutableSet set];+ [self setupDownloadDirectory];+ [self loadExistingVideos];+ [[StoreManager sharedInstance] verifySubscriptionWithCompletionIfSubbed:^(BOOL isActive, NSDate *expiryDate) {+ [self getEvents];+ }];+ [self updateTableViewBackground];+ [self setupRefreshTimer];+}++- (void)dealloc {+ [self.refreshTimer invalidate];+ self.refreshTimer = nil;+}++- (void)setupRefreshTimer {+ self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:10.0+ target:self+ selector:@selector(refreshTimerFired)+ userInfo:nil+ repeats:YES];+}++- (void)refreshTimerFired {+ if (!self.isLoadingVideos) {+ [self getEvents];+ }+}+++- (void)updateTableViewBackground {+ if (self.videoFiles.count == 0) {+ UILabel *messageLabel = [[UILabel alloc] initWithFrame:self.eventsViewController.view.bounds];+ messageLabel.numberOfLines = 0;+ messageLabel.lineBreakMode = NSLineBreakByWordWrapping;++ // Create the full attributed message+ NSMutableAttributedString *message = [[NSMutableAttributedString alloc] init];++ // Centered title+ NSMutableParagraphStyle *centeredStyle = [[NSMutableParagraphStyle alloc] init];+ centeredStyle.alignment = NSTextAlignmentCenter;+ centeredStyle.paragraphSpacing = 12.0;++ NSDictionary *titleAttrs = @{+ NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline],+ NSForegroundColorAttributeName: [UIColor labelColor],+ NSParagraphStyleAttributeName: centeredStyle+ };+ [message appendAttributedString:[[NSAttributedString alloc] initWithString:NSLocalizedString(@"no_videos_available", "no videos available") attributes:titleAttrs]];++ // Left-aligned steps with hanging indent+ NSMutableParagraphStyle *stepsStyle = [[NSMutableParagraphStyle alloc] init];+ stepsStyle.alignment = NSTextAlignmentLeft;+ stepsStyle.headIndent = 20.0;+ stepsStyle.firstLineHeadIndent = 0.0;+ stepsStyle.paragraphSpacing = 8.0;+ stepsStyle.lineBreakMode = NSLineBreakByWordWrapping;++ NSDictionary *stepAttrs = @{+ NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],+ NSForegroundColorAttributeName: [UIColor secondaryLabelColor],+ NSParagraphStyleAttributeName: stepsStyle+ };++ NSString *stepsText = NSLocalizedString(@"steps_text_clips", "steps to setup clips");++ [message appendAttributedString:[[NSAttributedString alloc] initWithString:stepsText attributes:stepAttrs]];++ messageLabel.attributedText = message;+ [messageLabel sizeToFit];++ self.tableView.backgroundView = messageLabel;+ self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;+ } else {+ self.tableView.backgroundView = nil;+ self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;+ }+}+++- (void)setupEventsViewController {+ // Move all the existing table view setup to the events view controller+ self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];+ self.tableView.delegate = self;+ self.tableView.dataSource = self;+ self.tableView.backgroundColor = [UIColor systemBackgroundColor];+ [self.tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"VideoCell"];+ self.tableView.separatorInset = UIEdgeInsetsMake(0, 16, 0, 16);++ if (@available(iOS 11.0, *)) {+ self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;+ }++ [self.eventsViewController.view addSubview:self.tableView];++ self.tableView.translatesAutoresizingMaskIntoConstraints = NO;+ [NSLayoutConstraint activateConstraints:@[+ [self.tableView.topAnchor constraintEqualToAnchor:self.eventsViewController.view.safeAreaLayoutGuide.topAnchor constant:0],+ [self.tableView.leadingAnchor constraintEqualToAnchor:self.eventsViewController.view.safeAreaLayoutGuide.leadingAnchor constant:0],+ [self.tableView.trailingAnchor constraintEqualToAnchor:self.eventsViewController.view.safeAreaLayoutGuide.trailingAnchor constant:0],+ [self.tableView.bottomAnchor constraintEqualToAnchor:self.eventsViewController.view.safeAreaLayoutGuide.bottomAnchor constant:0]+ ]];++ // Setup refresh control for events+ self.refreshControl = [[UIRefreshControl alloc] init];+ [self.refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];+ if (@available(iOS 10.0, *)) {+ self.tableView.refreshControl = self.refreshControl;+ } else {+ [self.tableView addSubview:self.refreshControl];+ }+}++- (void)setupRefreshControl {+ self.refreshControl = [[UIRefreshControl alloc] init];+ [self.refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];+ if (@available(iOS 10.0, *)) {+ self.tableView.refreshControl = self.refreshControl;+ } else {+ [self.tableView addSubview:self.refreshControl];+ }+}++- (void)handleRefresh {+ if (!self.isLoadingVideos) {+ [self getEvents];+ } else {+ [self.refreshControl endRefreshing];+ }+}++- (void)setIsLoadingVideos:(BOOL)isLoadingVideos {+ _isLoadingVideos = isLoadingVideos;++ if (!isLoadingVideos && self.refreshControl.isRefreshing) {+ [self.refreshControl endRefreshing];+ }+}++- (void)setupDownloadDirectory {+ NSString *documentsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;+ self.downloadDirectory = [documentsDir stringByAppendingPathComponent:@"downloaded-events"];++ if (![[NSFileManager defaultManager] fileExistsAtPath:self.downloadDirectory]) {+ NSError *error;+ [[NSFileManager defaultManager] createDirectoryAtPath:self.downloadDirectory+ withIntermediateDirectories:YES+ attributes:nil+ error:&error];+ }+}++- (void)setupTableView {+ self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];+ self.tableView.delegate = self;+ self.tableView.dataSource = self;+ self.tableView.backgroundColor = [UIColor systemBackgroundColor];+ [self.tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"VideoCell"];+ self.tableView.separatorInset = UIEdgeInsetsMake(0, 16, 0, 16);++ if (@available(iOS 11.0, *)) {+ self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;+ }++ [self.view addSubview:self.tableView];++ self.tableView.translatesAutoresizingMaskIntoConstraints = NO;++ [NSLayoutConstraint activateConstraints:@[+ [self.tableView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:0],+ [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:0],+ [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:0],+ [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:0]+ ]];+}++- (NSDate *)latestDownloadedFileDate {+ NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.downloadDirectory error:nil];+ NSDate *latestDate = nil;++ for (NSString *file in files) {+ NSString *filePath = [self.downloadDirectory stringByAppendingPathComponent:file];+ NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];+ NSDate *creationDate = attributes[NSFileCreationDate];+ if (creationDate && (!latestDate || [creationDate compare:latestDate] == NSOrderedDescending)) {+ latestDate = creationDate;+ }+ }+ return latestDate;+}++- (void)getEvents {+ if (self.isLoadingVideos) return;++ self.isLoadingVideos = YES;++ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/events"];+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];++ NSMutableArray<NSURLQueryItem *> *queryItems = [NSMutableArray array];+ if (sessionToken) [queryItems addObject:[NSURLQueryItem queryItemWithName:@"session_token" value:sessionToken]];++ NSDate *latestDate = [self latestDownloadedFileDate];+ if (latestDate) {+ NSTimeInterval timestamp = [latestDate timeIntervalSince1970];+ NSString *timestampString = [NSString stringWithFormat:@"%.0f", timestamp];+ [queryItems addObject:[NSURLQueryItem queryItemWithName:@"newest_creation_time" value:timestampString]];+ }++ components.queryItems = queryItems;+ NSURL *url = components.URL;++ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ [request setHTTPMethod:@"GET"];++ [[self.downloadSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ self.isLoadingVideos = NO;+ });++ if (error) return;++ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ if (httpResponse.statusCode == 200) {+ NSError *jsonError;+ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];++ if (!jsonError && json[@"files"]) {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self downloadFiles:json[@"files"]];+ });+ }+ }+ }] resume];+}+++- (void)downloadFiles:(NSArray<NSString *> *)fileURLs {+ if (fileURLs.count == 0) {+ [self loadExistingVideos];+ return;+ }++ self.isLoadingVideos = YES;+ dispatch_queue_t serialQueue = dispatch_queue_create("com.yourapp.serialDownloadQueue", DISPATCH_QUEUE_SERIAL);++ dispatch_async(serialQueue, ^{+ dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);++ for (NSString *fileURL in fileURLs) {+ NSURL *url = [NSURL URLWithString:fileURL];+ NSString *saveFileName = [url lastPathComponent];+ NSString *destPath = [self.downloadDirectory stringByAppendingPathComponent:saveFileName];++ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ [request setHTTPMethod:@"GET"];++ [[self.downloadSession downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {+ if (!error && [(NSHTTPURLResponse *)response statusCode] == 200) {+ NSError *moveError;+ NSURL *destURL = [NSURL fileURLWithPath:destPath];+ [[NSFileManager defaultManager] moveItemAtURL:location toURL:destURL error:&moveError];+ }+ dispatch_semaphore_signal(semaphore);+ }] resume];++ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);+ }+ dispatch_async(dispatch_get_main_queue(), ^{+ self.isLoadingVideos = NO;+ [self loadExistingVideos];+ });+ });+}++- (void)loadExistingVideos {+ NSError *error;+ NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.downloadDirectory error:&error];+ if (!self.loadedFilenames) self.loadedFilenames = [NSMutableSet set];+ for (NSString *file in contents) {+ NSString *filePath = [self.downloadDirectory stringByAppendingPathComponent:file];+ NSString *outputFilePath = filePath;+ if ([file hasSuffix:@".aes"]) {+ NSData *encryptedData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath] options:0 error:&error];+ if (!encryptedData) {+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to read the file: %@", error.localizedDescription]];+ return;+ }+ NSArray<NSString *> *storedKeys = [[SecretManager sharedManager] getAllDecryptionKeys];+ NSData *decryptedData = nil;+ for (NSString *key in storedKeys) {+ decryptedData = [[SecretManager sharedManager] decryptData:encryptedData withKey:key];+ if (decryptedData) break;+ }+ if(decryptedData){+ NSString *outputFilename = [file stringByDeletingPathExtension];+ outputFilePath = [self.downloadDirectory stringByAppendingPathComponent:outputFilename];+ NSError *writeError = nil;+ BOOL success = [decryptedData writeToFile:outputFilePath options:NSDataWritingAtomic error:&writeError];+ if (!success) {+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to write decrypted file: %@", writeError.localizedDescription]];+ return;+ }+ NSError *deleteError = nil;+ BOOL removed = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&deleteError];+ if (!removed) {+ [self showErrorAlertWithMessage:[NSString stringWithFormat:@"Failed to delete original encrypted file: %@", deleteError.localizedDescription]];+ return;+ }+ }++ }+ [self addVideoFileAtPath:outputFilePath];+ }+}++- (void)addVideoFileAtPath:(NSString *)filePath {+ if (!filePath) return;+ NSString *filename = [filePath lastPathComponent];+ if ([self.loadedFilenames containsObject:filename]) return;+ [self.videoFiles addObject:filePath];+ [self.loadedFilenames addObject:filename];+ NSError *error = nil;+ NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{4}-\\d{2}-\\d{2})_(\\d{2}-\\d{2}-\\d{2})"+ options:0+ error:&error];+ NSTextCheckingResult *match = [regex firstMatchInString:filename options:0 range:NSMakeRange(0, filename.length)];+ if (!match) return;+ NSString *dateStr = [filename substringWithRange:[match rangeAtIndex:1]];+ NSString *timeStr = [filename substringWithRange:[match rangeAtIndex:2]];+ NSString *fullTimestamp = [NSString stringWithFormat:@"%@_%@", dateStr, timeStr];+ NSDateFormatter *fullFormatter = [[NSDateFormatter alloc] init];+ [fullFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];+ NSDate *timestampDate = [fullFormatter dateFromString:fullTimestamp];+ if (!timestampDate) return;+ NSDateFormatter *sectionFormatter = [[NSDateFormatter alloc] init];+ sectionFormatter.dateStyle = NSDateFormatterMediumStyle;+ sectionFormatter.timeStyle = NSDateFormatterNoStyle;+ NSString *sectionTitle = [sectionFormatter stringFromDate:timestampDate] ?: @"Unknown Date";+ if (!self.groupedVideos[sectionTitle]) {+ self.groupedVideos[sectionTitle] = [NSMutableArray array];+ [self.sectionTitles addObject:sectionTitle];+ }+ [self.groupedVideos[sectionTitle] addObject:filePath];+ [self.sectionTitles sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {+ NSDate *d1 = [sectionFormatter dateFromString:obj1] ?: [NSDate distantPast];+ NSDate *d2 = [sectionFormatter dateFromString:obj2] ?: [NSDate distantPast];+ return [d2 compare:d1];+ }];+ for (NSString *section in self.groupedVideos) {+ [self.groupedVideos[section] sortUsingComparator:^NSComparisonResult(NSString *path1, NSString *path2) {+ NSString *f1 = [path1 lastPathComponent];+ NSString *f2 = [path2 lastPathComponent];+ NSTextCheckingResult *m1 = [regex firstMatchInString:f1 options:0 range:NSMakeRange(0, f1.length)];+ NSTextCheckingResult *m2 = [regex firstMatchInString:f2 options:0 range:NSMakeRange(0, f2.length)];+ NSString *ts1 = (m1 ?+ [NSString stringWithFormat:@"%@_%@",+ [f1 substringWithRange:[m1 rangeAtIndex:1]],+ [f1 substringWithRange:[m1 rangeAtIndex:2]]] :+ @"1970-01-01_00-00-00");++ NSString *ts2 = (m2 ?+ [NSString stringWithFormat:@"%@_%@",+ [f2 substringWithRange:[m2 rangeAtIndex:1]],+ [f2 substringWithRange:[m2 rangeAtIndex:2]]] :+ @"1970-01-01_00-00-00");++ NSDate *d1 = [fullFormatter dateFromString:ts1] ?: [NSDate distantPast];+ NSDate *d2 = [fullFormatter dateFromString:ts2] ?: [NSDate distantPast];++ return [d2 compare:d1];+ }];+ }+ [self.tableView reloadData];+ [self updateTableViewBackground];+}+++- (UIImage *)generateThumbnailForVideoAtPath:(NSString *)videoPath {+ NSURL *videoURL = [NSURL fileURLWithPath:videoPath];+ AVAsset *asset = [AVAsset assetWithURL:videoURL];+ AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];+ generator.appliesPreferredTrackTransform = YES;+ CMTime duration = asset.duration;+ Float64 durationInSeconds = CMTimeGetSeconds(duration);+ Float64 middleTime = durationInSeconds / 1.75;+ CMTime time = CMTimeMakeWithSeconds(middleTime, 600);+ NSError *error = nil;+ CGImageRef imageRef = [generator copyCGImageAtTime:time actualTime:NULL error:&error];+ if (!imageRef) return nil;+ UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];+ CGImageRelease(imageRef);+ return thumbnail;+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {+ return self.sectionTitles.count;+}++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ NSString *sectionTitle = self.sectionTitles[indexPath.section];+ NSString *filePath = self.groupedVideos[sectionTitle][indexPath.row];+ NSString *extension = filePath.pathExtension.lowercaseString;++ if ([extension isEqualToString:@"mp4"]) {+ AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];+ playerVC.player = [AVPlayer playerWithURL:[NSURL fileURLWithPath:filePath]];+ [self presentViewController:playerVC animated:YES completion:^{+ [playerVC.player play];+ }];+ } else if ([extension isEqualToString:@"aes"]) {+ NSError *readError = nil;+ NSData *encryptedData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath] options:0 error:&readError];+ [self promptUserForKeyWithAESFileURL:[NSURL fileURLWithPath:filePath] encryptedData:encryptedData];+ }+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+}++- (void)promptUserForKeyWithAESFileURL:(NSURL *)aesFileURL encryptedData:(NSData *)encryptedData {+ [[SecretManager sharedManager] promptUserForKeyFromViewController:self completion:^(NSString *userProvidedKey) {+ if (userProvidedKey) {+ NSData *decryptedData = [[SecretManager sharedManager] decryptData:encryptedData withKey:userProvidedKey];+ if (decryptedData) {+ NSError *saveError = nil;+ NSString *fileName = [[aesFileURL lastPathComponent] stringByDeletingPathExtension];+ NSString *keyPrefix = [userProvidedKey substringToIndex:MIN(6, userProvidedKey.length)];+ NSString *keyIdentifier = [NSString stringWithFormat:@"decryption_key_%@_%@", fileName, keyPrefix];+ [[SecretManager sharedManager] saveDecryptionKey:userProvidedKey withIdentifier:keyIdentifier error:&saveError];+ NSURL *decryptedURL = [self handleDecryptedData:decryptedData fromURL:aesFileURL];+ if (decryptedURL) {+ [self.videoFiles removeAllObjects];+ [self.groupedVideos removeAllObjects];+ [self.sectionTitles removeAllObjects];+ [self.loadedFilenames removeAllObjects];+ [self loadExistingVideos];+ AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];+ playerVC.player = [AVPlayer playerWithURL:decryptedURL];+ [self presentViewController:playerVC animated:YES completion:^{+ [playerVC.player play];+ }];+ }+ } else {+ [self showErrorAlertWithMessage:@"The provided key is incorrect. Please try again or cancel." completion:^{+ [self promptUserForKeyWithAESFileURL:aesFileURL encryptedData:encryptedData];+ }];+ }+ }+ }];+}++- (void)showErrorAlertWithMessage:(NSString *)message {+ [self showErrorAlertWithMessage:message completion:nil];+}++- (void)showErrorAlertWithMessage:(NSString *)message completion:(void (^)(void))completion {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"+ message:message+ preferredStyle:UIAlertControllerStyleAlert];+ UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {+ if (completion) {+ completion();+ }+ }];+ [alert addAction:okAction];+ [self presentViewController:alert animated:YES completion:nil];+}++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ NSString *sectionTitle = self.sectionTitles[section];+ return self.groupedVideos[sectionTitle].count;+}++- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {+ return self.sectionTitles[section];+}++- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {+ UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)];+ headerView.backgroundColor = [UIColor systemGroupedBackgroundColor];++ UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, tableView.bounds.size.width - 32, 44)];+ label.text = [self tableView:tableView titleForHeaderInSection:section];+ label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];+ label.textColor = [UIColor darkGrayColor];++ [headerView addSubview:label];+ return headerView;+}++- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {+ return 44;+}++- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {+ return 100;+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoCell" forIndexPath:indexPath];++ NSString *sectionTitle = self.sectionTitles[indexPath.section];+ NSString *filePath = self.groupedVideos[sectionTitle][indexPath.row];+ NSString *filename = [filePath lastPathComponent];+ NSString *extension = filePath.pathExtension.lowercaseString;++ NSArray *components = [filename componentsSeparatedByString:@"_"];+ if (components.count >= 2) {+ NSString *timePart = components[1];+ NSArray *timeComponents = [timePart componentsSeparatedByString:@"-"];+ if (timeComponents.count >= 3) {+ NSString *hour = timeComponents[0];+ NSString *minute = timeComponents[1];+ NSString *second = timeComponents[2];+ cell.titleLabel.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];+ } else {+ cell.titleLabel.text = filename;+ }+ } else {+ cell.titleLabel.text = filename;+ }++ cell.thumbnailView.image = nil;++ if ([extension isEqualToString:@"mp4"]) {+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ UIImage *thumbnail = [self generateThumbnailForVideoAtPath:filePath];+ dispatch_async(dispatch_get_main_queue(), ^{+ VideoTableViewCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];+ if (updateCell) {+ updateCell.thumbnailView.image = thumbnail;+ }+ });+ });+ } else if ([extension isEqualToString:@"aes"]) {+ UIImage *lockImage = [UIImage systemImageNamed:@"lock.fill"];+ UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:40];+ UIImage *scaledLockImage = [lockImage imageByApplyingSymbolConfiguration:config];+ cell.thumbnailView.image = scaledLockImage;+ cell.thumbnailView.contentMode = UIViewContentModeCenter;+ cell.thumbnailView.tintColor = [UIColor systemGrayColor];+ }++ [cell.menuButton addTarget:self action:@selector(menuTapped:forEvent:) forControlEvents:UIControlEventTouchUpInside];++ return cell;+}++- (void)menuTapped:(UIButton *)sender forEvent:(UIEvent *)event {+ CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.tableView];+ NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];++ if (!indexPath) return;++ NSInteger section = indexPath.section;+ NSInteger row = indexPath.row;++ if (section >= self.sectionTitles.count) return;++ NSString *sectionTitle = self.sectionTitles[section];++ if (row >= self.groupedVideos[sectionTitle].count) return;++ NSString *videoPath = self.groupedVideos[sectionTitle][row];+ NSString *filename = [videoPath lastPathComponent];+ NSString *originalAesPath = [self.downloadDirectory stringByAppendingPathComponent:[filename stringByAppendingPathExtension:@"aes"]];++ UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil+ message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];++ [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"share", "share")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSURL *videoURL = [NSURL fileURLWithPath:videoPath];+ UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[videoURL]+ applicationActivities:nil];+ [self presentViewController:activityVC animated:YES completion:nil];+ }]];++ [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"delete", "delete")+ style:UIAlertActionStyleDestructive+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ NSError *localError;+ NSFileManager *fileManager = [NSFileManager defaultManager];++ if ([fileManager fileExistsAtPath:videoPath]) {+ [fileManager removeItemAtPath:videoPath error:&localError];+ if (localError) return;+ }++ if ([fileManager fileExistsAtPath:originalAesPath]) {+ [fileManager removeItemAtPath:originalAesPath error:&localError];+ if (localError) return;+ }++ [self.videoFiles removeObject:videoPath];+ [self.groupedVideos[sectionTitle] removeObjectAtIndex:row];++ [self.tableView beginUpdates];+ if ([self.groupedVideos[sectionTitle] count] == 0) {+ [self.groupedVideos removeObjectForKey:sectionTitle];+ [self.sectionTitles removeObjectAtIndex:section];+ [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:section]+ withRowAnimation:UITableViewRowAnimationAutomatic];+ } else {+ [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:section]]+ withRowAnimation:UITableViewRowAnimationAutomatic];+ }+ [self.tableView endUpdates];++ if (sessionToken) {+ NSString *backendFilename = [filename hasSuffix:@".aes"] ? filename : [filename stringByAppendingPathExtension:@"aes"];+ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/video"];+ components.queryItems = @[+ [NSURLQueryItem queryItemWithName:@"session_token" value:sessionToken],+ [NSURLQueryItem queryItemWithName:@"name" value:backendFilename]+ ];++ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:components.URL];+ [request setHTTPMethod:@"DELETE"];++ [[self.downloadSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ }] resume];+ }+ }]];++ [actionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", "cancel")+ style:UIAlertActionStyleCancel+ handler:nil]];++ if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {+ actionSheet.popoverPresentationController.sourceView = sender;+ actionSheet.popoverPresentationController.sourceRect = sender.bounds;+ }++ [self presentViewController:actionSheet animated:YES completion:nil];+}++- (NSURL *)handleDecryptedData:(NSData *)decryptedData fromURL:(NSURL *)aesFileURL {+ NSString *fileName = [aesFileURL lastPathComponent];+ if ([fileName hasSuffix:@".aes"]) {+ fileName = [fileName stringByReplacingOccurrencesOfString:@".aes" withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, fileName.length)];+ }+ NSURL *decFileURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0] URLByAppendingPathComponent:fileName];++ NSError *writeError = nil;+ [decryptedData writeToURL:decFileURL options:NSDataWritingAtomic error:&writeError];+ if (writeError) return nil;++ NSError *attributesError = nil;+ NSDictionary *originalAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[aesFileURL path] error:&attributesError];+ if (originalAttributes && !attributesError) {+ NSDate *originalCreationDate = originalAttributes[NSFileCreationDate];+ if (originalCreationDate) {+ NSDictionary *newAttributes = @{NSFileCreationDate: originalCreationDate};+ [[NSFileManager defaultManager] setAttributes:newAttributes ofItemAtPath:[decFileURL path] error:&attributesError];+ }+ }+ return decFileURL;+}++@enddiff --git a/ios/clearcam/Info.plist b/ios/clearcam/Info.plistnew file mode 100644index 0000000..ec98a59--- /dev/null+++ b/ios/clearcam/Info.plist@@ -0,0 +1,73 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0.1">+<dict>+ <key>NSFaceIDUsageDescription</key>+ <string>Clearcam needs to use Face ID to securely reveal your user ID in the subscription settings.</string>+ <key>NSCameraUsageDescription</key>+ <string>Clearcam needs access to your camera to record video, stream video and detect objects.</string>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeExtensions</key>+ <array>+ <string>aes</string>+ </array>+ <key>CFBundleTypeName</key>+ <string>AES File</string>+ <key>LSHandlerRank</key>+ <string>Owner</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>com.clearcam.aesfile</string>+ </array>+ </dict>+ </array>+ <key>UIApplicationSceneManifest</key>+ <dict>+ <key>UIApplicationSupportsMultipleScenes</key>+ <false/>+ <key>UISceneConfigurations</key>+ <dict>+ <key>UIWindowSceneSessionRoleApplication</key>+ <array>+ <dict>+ <key>UISceneConfigurationName</key>+ <string>Default Configuration</string>+ <key>UISceneDelegateClassName</key>+ <string>SceneDelegate</string>+ <key>UISceneStoryboardFile</key>+ <string>Main</string>+ </dict>+ </array>+ </dict>+ </dict>+ <key>UIBackgroundModes</key>+ <array>+ <string>fetch</string>+ <string>remote-notification</string>+ </array>+ <key>UIFileSharingEnabled</key>+ <true/>+ <key>UTExportedTypeDeclarations</key>+ <array>+ <dict>+ <key>UTTypeConformsTo</key>+ <array>+ <string>public.data</string>+ </array>+ <key>UTTypeDescription</key>+ <string>AES Encrypted File</string>+ <key>UTTypeIdentifier</key>+ <string>com.clearcam.aesfile</string>+ <key>UTTypeTagSpecification</key>+ <dict>+ <key>public.filename-extension</key>+ <array>+ <string>aes</string>+ </array>+ </dict>+ </dict>+ </array>+</dict>+</plist>diff --git a/ios/clearcam/LiveViewController.h b/ios/clearcam/LiveViewController.hnew file mode 100644index 0000000..253e478--- /dev/null+++ b/ios/clearcam/LiveViewController.h@@ -0,0 +1,9 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface LiveViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>+@property (nonatomic, strong) UITableView *tableView;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/ios/clearcam/LiveViewController.m b/ios/clearcam/LiveViewController.mnew file mode 100644index 0000000..5dca33d--- /dev/null+++ b/ios/clearcam/LiveViewController.m@@ -0,0 +1,236 @@+#import "LiveViewController.h"+#import "StoreManager.h"+#import "DeviceStreamViewController.h" // Import DeviceStreamViewController++@interface LiveViewController () <UITableViewDelegate, UITableViewDataSource>+@property (nonatomic, strong) NSMutableArray<NSString *> *deviceNames;+@property (nonatomic, strong) NSURLSession *session;+@property (nonatomic, strong) UIRefreshControl *refreshControl;+@end++@implementation LiveViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.title = @"Live Cameras";+ self.deviceNames = [NSMutableArray array];+++ self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];+ [self setupTableView];+ [[StoreManager sharedInstance] verifySubscriptionWithCompletionIfSubbed:^(BOOL isActive, NSDate *expiryDate) {+ [self fetchLiveDevices];+ }];+}++- (void)setupTableView {+ self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];+ self.tableView.delegate = self;+ self.tableView.dataSource = self;+ self.tableView.backgroundColor = [UIColor systemBackgroundColor];+ [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"DeviceCell"];++ [self.view addSubview:self.tableView];++ self.tableView.translatesAutoresizingMaskIntoConstraints = NO;+ [NSLayoutConstraint activateConstraints:@[+ [self.tableView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],+ [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor],+ [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor],+ [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor]+ ]];+ self.refreshControl = [[UIRefreshControl alloc] init];+ [self.refreshControl addTarget:self action:@selector(refreshDevices) forControlEvents:UIControlEventValueChanged];+ self.tableView.refreshControl = self.refreshControl;+}++- (void)updateTableViewBackground {+ if (self.deviceNames.count == 0) {+ UILabel *messageLabel = [[UILabel alloc] initWithFrame:self.tableView.bounds];+ messageLabel.numberOfLines = 0;+ messageLabel.lineBreakMode = NSLineBreakByWordWrapping;++ // Title centered+ NSMutableParagraphStyle *centeredStyle = [[NSMutableParagraphStyle alloc] init];+ centeredStyle.alignment = NSTextAlignmentCenter;+ centeredStyle.paragraphSpacing = 12.0;++ NSDictionary *titleAttrs = @{+ NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline],+ NSForegroundColorAttributeName: [UIColor labelColor],+ NSParagraphStyleAttributeName: centeredStyle+ };++ NSMutableAttributedString *message = [[NSMutableAttributedString alloc] init];+ [message appendAttributedString:[[NSAttributedString alloc] initWithString:NSLocalizedString(@"no_live_devices", "no live devices") attributes:titleAttrs]];++ // Steps with hanging indent, left-aligned+ NSMutableParagraphStyle *stepsStyle = [[NSMutableParagraphStyle alloc] init];+ stepsStyle.alignment = NSTextAlignmentLeft;+ stepsStyle.headIndent = 20.0;+ stepsStyle.firstLineHeadIndent = 0.0;+ stepsStyle.paragraphSpacing = 8.0;++ NSDictionary *stepsAttrs = @{+ NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],+ NSForegroundColorAttributeName: [UIColor secondaryLabelColor],+ NSParagraphStyleAttributeName: stepsStyle+ };++ NSString *stepsText = NSLocalizedString(@"steps_text_live","steps on how to make live work.");++ [message appendAttributedString:[[NSAttributedString alloc] initWithString:stepsText attributes:stepsAttrs]];++ messageLabel.attributedText = message;+ [messageLabel sizeToFit];++ self.tableView.backgroundView = messageLabel;+ self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;+ } else {+ self.tableView.backgroundView = nil;+ self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;+ }+}++++- (void)refreshDevices {+ [self fetchLiveDevices];+}++- (void)fetchLiveDevices {+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (!sessionToken) {+ NSLog(@"No session token available");+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.refreshControl endRefreshing];+ });+ return;+ }++ NSString *encodedSessionToken = [sessionToken stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];+ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/get_live_devices"];+ components.queryItems = @[+ [NSURLQueryItem queryItemWithName:@"session_token" value:encodedSessionToken]+ ];++ NSURL *url = components.URL;+ NSLog(@"Final URL: %@", url);++ NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.refreshControl endRefreshing];+ });+ if (error) return;+ NSError *jsonError;+ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];+ if (jsonError) return;++ NSArray<NSString *> *deviceNames = json[@"device_names"];+ if (deviceNames) {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.deviceNames removeAllObjects];+ for (NSString *deviceName in deviceNames) {+ NSString *decodedName = [deviceName stringByRemovingPercentEncoding];+ if (decodedName) {+ [self.deviceNames addObject:decodedName];+ }+ }+ [self.tableView reloadData];+ [self updateTableViewBackground];+ });+ }+ }];+ [task resume];+ //[self updateTableViewBackground];+}++#pragma mark - UITableViewDataSource++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ return self.deviceNames.count;+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceCell" forIndexPath:indexPath];++ // Clear previous content+ for (UIView *view in cell.contentView.subviews) {+ [view removeFromSuperview];+ }++ NSString *deviceName = self.deviceNames[indexPath.row];++ // Thumbnail container (4:3 ratio)+ UIView *thumbContainer = [[UIView alloc] initWithFrame:CGRectMake(15, 10, 120, 90)];+ thumbContainer.backgroundColor = [UIColor secondarySystemBackgroundColor];+ thumbContainer.layer.cornerRadius = 8;+ thumbContainer.clipsToBounds = YES;++ UIImageView *thumbnailView = [[UIImageView alloc] initWithFrame:thumbContainer.bounds];+ thumbnailView.contentMode = UIViewContentModeScaleAspectFill;+ thumbnailView.clipsToBounds = YES;++ NSString *filename = [NSString stringWithFormat:@"thumbnail_%@.jpg", deviceName];+ NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;+ NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];+ UIImage *thumbnailImage = [UIImage imageWithContentsOfFile:filePath];++ if (thumbnailImage) {+ thumbnailView.image = thumbnailImage;+ } else {+ thumbnailView.image = nil;+ // Add play icon in center+ UIImageView *playIcon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"play.circle.fill"]];+ playIcon.tintColor = [UIColor labelColor];+ playIcon.contentMode = UIViewContentModeScaleAspectFit;+ playIcon.frame = CGRectMake((thumbContainer.frame.size.width - 40)/2, (thumbContainer.frame.size.height - 40)/2, 40, 40);+ [thumbContainer addSubview:playIcon];+ }++ [thumbContainer addSubview:thumbnailView];+ [cell.contentView addSubview:thumbContainer];++ // Device Name Label+ UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 25, tableView.frame.size.width - 160, 25)];+ nameLabel.text = deviceName;+ nameLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];+ nameLabel.textColor = [UIColor labelColor];++ // Online Indicator+ UIView *greenDot = [[UIView alloc] initWithFrame:CGRectMake(150, 60, 10, 10)];+ greenDot.backgroundColor = [UIColor systemGreenColor];+ greenDot.layer.cornerRadius = 5;++ UILabel *onlineLabel = [[UILabel alloc] initWithFrame:CGRectMake(165, 57, 100, 15)];+ onlineLabel.text = NSLocalizedString(@"online", "online");+ onlineLabel.font = [UIFont systemFontOfSize:13];+ onlineLabel.textColor = [UIColor secondaryLabelColor];++ [cell.contentView addSubview:nameLabel];+ [cell.contentView addSubview:greenDot];+ [cell.contentView addSubview:onlineLabel];++ cell.backgroundColor = [UIColor systemBackgroundColor];++ return cell;+}++#pragma mark - UITableViewDelegate++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ NSString *selectedDevice = self.deviceNames[indexPath.row];+ NSLog(@"Selected device: %@", selectedDevice);++ DeviceStreamViewController *streamVC = [[DeviceStreamViewController alloc] init];+ streamVC.deviceName = selectedDevice; // Pass the device name+ [self.navigationController pushViewController:streamVC animated:YES];++ [tableView deselectRowAtIndexPath:indexPath animated:YES];+}++- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {+ return 110;+}++@enddiff --git a/ios/clearcam/MainViewController.h b/ios/clearcam/MainViewController.hnew file mode 100644index 0000000..c9bfd23--- /dev/null+++ b/ios/clearcam/MainViewController.h@@ -0,0 +1,8 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface MainViewController : UIViewController+@end++NS_ASSUME_NONNULL_ENDdiff --git a/ios/clearcam/MainViewController.m b/ios/clearcam/MainViewController.mnew file mode 100644index 0000000..bcefa06--- /dev/null+++ b/ios/clearcam/MainViewController.m@@ -0,0 +1,192 @@+// MainViewController.m+#import "MainViewController.h"+#import "ViewController.h"+#import "GalleryViewController.h"+#import "SettingsViewController.h"+#import "FileServer.h"++@interface MainViewController ()+@property (nonatomic, strong) FileServer *fileServer;+@property (nonatomic, strong) UILabel *ipLabel;+@property (nonatomic, strong) UIStackView *mainStackView;+@property (nonatomic, strong) NSLayoutConstraint *mainStackViewTopToIPLabelConstraint;+@property (nonatomic, strong) NSLayoutConstraint *mainStackViewTopToSafeAreaConstraint;+@end++@implementation MainViewController++- (void)viewDidLoad {+ [super viewDidLoad];++ self.fileServer = [FileServer sharedInstance];+ [self.fileServer start];++ self.view.backgroundColor = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark)+ ? [UIColor blackColor]+ : [UIColor whiteColor];++ self.title = @"Clearcam";+ self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"home", nil)+ style:UIBarButtonItemStylePlain+ target:nil+ action:nil];++ // Setup IP label+ self.ipLabel = [[UILabel alloc] init];+ self.ipLabel.translatesAutoresizingMaskIntoConstraints = NO;+ self.ipLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];+ self.ipLabel.textColor = [UIColor secondaryLabelColor];+ self.ipLabel.textAlignment = NSTextAlignmentCenter;+ self.ipLabel.numberOfLines = 1;+ [self.view addSubview:self.ipLabel];++ [NSLayoutConstraint activateConstraints:@[+ [self.ipLabel.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:10],+ [self.ipLabel.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:20],+ [self.ipLabel.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-20]+ ]];++ // Stack View setup+ self.mainStackView = [[UIStackView alloc] init];+ self.mainStackView.axis = UILayoutConstraintAxisVertical;+ self.mainStackView.distribution = UIStackViewDistributionFillEqually;+ self.mainStackView.alignment = UIStackViewAlignmentFill;+ self.mainStackView.spacing = 20;+ self.mainStackView.translatesAutoresizingMaskIntoConstraints = NO;+ [self.view addSubview:self.mainStackView];++ // Create the two possible top constraints for the stack view+ // The constant for mainStackViewTopToIPLabelConstraint should ensure there's enough space below the label+ self.mainStackViewTopToIPLabelConstraint = [self.mainStackView.topAnchor constraintEqualToAnchor:self.ipLabel.bottomAnchor constant:20]; // Keep original constant+ self.mainStackViewTopToSafeAreaConstraint = [self.mainStackView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:20]; // Keep original constant++ [NSLayoutConstraint activateConstraints:@[+ [self.mainStackView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:20],+ [self.mainStackView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-20],+ [self.mainStackView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-20]+ ]];++ [self addItemToStackView:self.mainStackView+ title:NSLocalizedString(@"camera_desc", nil)+ image:[UIImage systemImageNamed:@"camera.fill"]+ action:@selector(cameraTapped)];++ [self addItemToStackView:self.mainStackView+ title:NSLocalizedString(@"gallery_desc", nil)+ image:[UIImage systemImageNamed:@"photo.on.rectangle"]+ action:@selector(galleryTapped)];++ [self addItemToStackView:self.mainStackView+ title:NSLocalizedString(@"settings_desc", nil)+ image:[UIImage systemImageNamed:@"gear"]+ action:@selector(settingsTapped)];++ // Observe IP address changes+ [[NSNotificationCenter defaultCenter] addObserver:self+ selector:@selector(updateIPAddressLabel)+ name:@"DeviceIPAddressDidChangeNotification"+ object:nil];+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ [self updateIPAddressLabel]; // Ensure layout is correct when view appears/reappears+}++- (void)updateIPAddressLabel {+ BOOL streamViaWifiEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"stream_via_wifi_enabled"];+ NSString *ipAddress = [[NSUserDefaults standardUserDefaults] stringForKey:@"DeviceIPAddress"];++ if (streamViaWifiEnabled) {+ // If streaming is enabled, IP label should be visible+ self.ipLabel.hidden = NO;+ self.ipLabel.text = (ipAddress.length > 0) ? [NSString stringWithFormat:NSLocalizedString(@"streaming_over_wifi", nil), ipAddress] : NSLocalizedString(@"waiting_for_ip", nil);++ // Activate constraint to IP label, deactivate constraint to safe area+ self.mainStackViewTopToSafeAreaConstraint.active = NO;+ self.mainStackViewTopToIPLabelConstraint.active = YES;+ } else {+ // If streaming is disabled, IP label should be hidden+ self.ipLabel.hidden = YES;+ self.ipLabel.text = nil; // Clear text when hidden++ // Activate constraint to safe area, deactivate constraint to IP label+ self.mainStackViewTopToIPLabelConstraint.active = NO;+ self.mainStackViewTopToSafeAreaConstraint.active = YES;+ }++ // Force layout update after constraint changes+ [self.view layoutIfNeeded];+}++- (void)addItemToStackView:(UIStackView *)stackView title:(NSString *)title image:(UIImage *)image action:(SEL)action {+ // Create container view+ UIView *container = [[UIView alloc] init];+ container.backgroundColor = [UIColor systemGray6Color];+ container.layer.cornerRadius = 10;+ container.translatesAutoresizingMaskIntoConstraints = NO;++ // Create image view+ UIImageView *imageView = [[UIImageView alloc] initWithImage:image];+ imageView.contentMode = UIViewContentModeScaleAspectFit;+ imageView.tintColor = [UIColor systemBlueColor];+ imageView.translatesAutoresizingMaskIntoConstraints = NO;++ // Create label+ UILabel *label = [[UILabel alloc] init];+ label.text = title;+ label.numberOfLines = 0;+ label.font = [UIFont systemFontOfSize:18];+ label.translatesAutoresizingMaskIntoConstraints = NO;++ // Create horizontal stack view for image and label+ UIStackView *itemStackView = [[UIStackView alloc] init];+ itemStackView.axis = UILayoutConstraintAxisHorizontal;+ itemStackView.alignment = UIStackViewAlignmentCenter;+ itemStackView.spacing = 15;+ itemStackView.translatesAutoresizingMaskIntoConstraints = NO;+ [itemStackView addArrangedSubview:imageView];+ [itemStackView addArrangedSubview:label];++ // Add stack view to container+ [container addSubview:itemStackView];+ [NSLayoutConstraint activateConstraints:@[+ [itemStackView.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:15],+ [itemStackView.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-15],+ [itemStackView.topAnchor constraintEqualToAnchor:container.topAnchor constant:10],+ [itemStackView.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-10],+ [imageView.widthAnchor constraintEqualToConstant:50],+ [imageView.heightAnchor constraintEqualToConstant:50]+ ]];++ // Add tap gesture+ container.userInteractionEnabled = YES;+ UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:action];+ [container addGestureRecognizer:tap];++ // Add to main stack view+ [stackView addArrangedSubview:container];+}++#pragma mark - Actions++- (void)cameraTapped {+ ViewController *cameraVC = [[ViewController alloc] init];+ [self.navigationController pushViewController:cameraVC animated:YES];+}++- (void)galleryTapped {+ GalleryViewController *galleryVC = [[GalleryViewController alloc] init];+ [self.navigationController pushViewController:galleryVC animated:YES];+}++- (void)settingsTapped {+ SettingsViewController *settingsVC = [[SettingsViewController alloc] init];+ [self.navigationController pushViewController:settingsVC animated:YES];+}++- (void)dealloc {+ [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DeviceIPAddressDidChangeNotification" object:nil];+}++@enddiff --git a/ios/clearcam/Notification.h b/ios/clearcam/Notification.hnew file mode 100644index 0000000..c2f6a18--- /dev/null+++ b/ios/clearcam/Notification.h@@ -0,0 +1,9 @@+#import <Foundation/Foundation.h>++@interface notification : NSObject+++ (instancetype)sharedInstance;+- (void)uploadImageAtPath:(NSString *)imagePath;+- (void)sendNotification;++@enddiff --git a/ios/clearcam/Notification.m b/ios/clearcam/Notification.mnew file mode 100644index 0000000..23a785f--- /dev/null+++ b/ios/clearcam/Notification.m@@ -0,0 +1,150 @@+#import "notification.h"+#import "SecretManager.h"+#import "StoreManager.h"+#import "FileServer.h"+#import <UIKit/UIKit.h>++@implementation notification+++ (instancetype)sharedInstance {+ static notification *sharedInstance = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedInstance = [[self alloc] init];+ });+ return sharedInstance;+}++- (void)sendNotification {+ NSString *server = @"https://www.rors.ai";+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"use_own_server_enabled"]) {+ server = [[NSUserDefaults standardUserDefaults] valueForKey:@"own_notification_server_address"];+ if(!server) server = @"http://192.168.1.1:8080";+ if (![server hasPrefix:@"http"]) {+ server = [@"http://" stringByAppendingString:server];+ }+ }++ NSString *endpoint = @"/send";+ NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];+ NSMutableData *bodyData = [NSMutableData data];++ // Retrieve session token+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (!sessionToken) return;++ // Add "session_token" field+ [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];+ [bodyData appendData:[@"Content-Disposition: form-data; name=\"session_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];+ [bodyData appendData:[sessionToken dataUsingEncoding:NSUTF8StringEncoding]];+ [bodyData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];+ [bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];++ [FileServer performPostRequestWithURL:[server stringByAppendingString:endpoint]+ method:@"POST"+ contentType:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]+ body:bodyData+ completionHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {}];+}+++- (void)uploadImageAtPath:(NSString *)imagePath {+ NSString *server = @"https://www.rors.ai";++ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"use_own_server_enabled"]) {+ server = [[NSUserDefaults standardUserDefaults] valueForKey:@"own_notification_server_address"];+ if(!server) server = @"http://192.168.1.1:8080";+ if (![server hasPrefix:@"http"]) {+ server = [@"http://" stringByAppendingString:server];+ }+ }++ if (imagePath.length == 0) return;++ NSData *imageData = [NSData dataWithContentsOfFile:imagePath];+ if (!imageData) return;++ NSString *fileName = [imagePath lastPathComponent];+ BOOL encryptImage = ![[NSUserDefaults standardUserDefaults] boolForKey:@"use_own_server_enabled"];+ if (encryptImage) {+ NSString *encryptionKey = [[SecretManager sharedManager] getEncryptionKey];+ if (!encryptionKey) return;+ NSData *encryptedData = [[SecretManager sharedManager] encryptData:imageData withKey:encryptionKey];+ if (!encryptedData) return;+ fileName = [fileName stringByAppendingString:@".aes"];+ imageData = encryptedData;+ }++ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (!sessionToken) return;+ NSUInteger fileSize = [imageData length];+ NSURLComponents *components = [NSURLComponents componentsWithString:[server stringByAppendingString:@"/upload"]];+ NSURLQueryItem *fileItem = [NSURLQueryItem queryItemWithName:@"filename" value:fileName];+ NSURLQueryItem *sessionItem = [NSURLQueryItem queryItemWithName:@"session_token" value:sessionToken];+ NSURLQueryItem *sizeItem = [NSURLQueryItem queryItemWithName:@"size" value:[NSString stringWithFormat:@"%lu", (unsigned long)fileSize]];+ components.queryItems = @[fileItem, sessionItem, sizeItem];++ NSURL *uploadRequestURL = components.URL;+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadRequestURL];+ [request setHTTPMethod:@"GET"];++ __weak typeof(self) weakSelf = self;+ NSURLSessionDataTask *uploadTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error) {+ NSLog(@"Error getting upload URL: %@", error);+ return;+ }+ NSError *jsonError;+ NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];+ if (jsonError || !responseDict[@"url"]) {+ NSLog(@"Error parsing upload URL response: %@", jsonError ?: @"Missing 'url' key");+ return;+ }+ NSString *presignedR2URL = responseDict[@"url"];++ // Implement retry logic here+ NSInteger maxRetries = 3;+ __block NSInteger retryCount = 0;++ void (^uploadWithRetry)(void) = ^{+ if (retryCount >= maxRetries) {+ NSLog(@"Image upload failed after %ld retries.", (long)maxRetries);+ // Optionally handle the final failure, e.g., by calling a delegate method+ return;+ }++ NSMutableURLRequest *r2Request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:presignedR2URL]];+ [r2Request setHTTPMethod:@"PUT"];+ [r2Request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];+ [r2Request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)fileSize] forHTTPHeaderField:@"Content-Length"]; // Add Content-Length header++ NSURLSessionUploadTask *r2UploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:r2Request fromData:imageData completionHandler:^(NSData *r2Data, NSURLResponse *r2Response, NSError *r2Error) {+ if (!r2Error) {+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)r2Response;+ if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {+ NSLog(@"Image uploaded successfully after %ld attempts.", (long)retryCount + 1);+ // Optionally handle successful upload, e.g., by calling a delegate method+ } else {+ NSLog(@"Image upload failed with status code: %ld, attempt: %ld", (long)httpResponse.statusCode, (long)retryCount + 1);+ retryCount++;+ // Introduce a delay before retrying (e.g., exponential backoff)+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(pow(2, retryCount) * 0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), uploadWithRetry);+ }+ } else {+ NSLog(@"Image upload failed with error: %@, attempt: %ld", r2Error, (long)retryCount + 1);+ retryCount++;+ // Introduce a delay before retrying+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(pow(2, retryCount) * 0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), uploadWithRetry);+ }+ }];++ [r2UploadTask resume];+ };++ uploadWithRetry(); // Start the initial upload attempt+ }];+ [uploadTask resume];+}++@end+diff --git a/ios/clearcam/NumberSelectionViewController.h b/ios/clearcam/NumberSelectionViewController.hnew file mode 100644index 0000000..acf4333--- /dev/null+++ b/ios/clearcam/NumberSelectionViewController.h@@ -0,0 +1,9 @@+#import <UIKit/UIKit.h>++@interface NumberSelectionViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>++@property (nonatomic, strong) NSString *presetKey; // The preset being edited+@property (nonatomic, strong) NSMutableArray<NSNumber *> *selectedIndexes; // Selected numbers (0-79)+@property (nonatomic, copy) void (^completionHandler)(NSArray<NSNumber *> *selectedIndexes); // Callback to save the selected numbers++@enddiff --git a/ios/clearcam/NumberSelectionViewController.m b/ios/clearcam/NumberSelectionViewController.mnew file mode 100644index 0000000..a2e0b0f--- /dev/null+++ b/ios/clearcam/NumberSelectionViewController.m@@ -0,0 +1,151 @@+#import <UIKit/UIKit.h>++@interface NumberSelectionViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>++@property (nonatomic, strong) NSString *presetKey; // The preset being edited+@property (nonatomic, strong) NSMutableArray<NSNumber *> *selectedIndexes; // Selected numbers (0-79)+@property (nonatomic, copy) void (^completionHandler)(NSArray<NSNumber *> *selectedIndexes); // Callback to save the selected numbers+@property (nonatomic, strong) NSArray<NSString *> *classes; // Selected numbers (0-79)++@end++@implementation NumberSelectionViewController++- (void)viewDidLoad {+ [super viewDidLoad];++ self.classes = @[+ NSLocalizedString(@"person", nil),+ NSLocalizedString(@"bicycle", nil),+ NSLocalizedString(@"car", nil),+ NSLocalizedString(@"motorcycle", nil),+ NSLocalizedString(@"airplane", nil),+ NSLocalizedString(@"bus", nil),+ NSLocalizedString(@"train", nil),+ NSLocalizedString(@"truck", nil),+ NSLocalizedString(@"boat", nil),+ NSLocalizedString(@"traffic light", nil),+ NSLocalizedString(@"fire hydrant", nil),+ NSLocalizedString(@"stop sign", nil),+ NSLocalizedString(@"parking meter", nil),+ NSLocalizedString(@"bench", nil),+ NSLocalizedString(@"bird", nil),+ NSLocalizedString(@"cat", nil),+ NSLocalizedString(@"dog", nil),+ NSLocalizedString(@"horse", nil),+ NSLocalizedString(@"sheep", nil),+ NSLocalizedString(@"cow", nil),+ NSLocalizedString(@"elephant", nil),+ NSLocalizedString(@"bear", nil),+ NSLocalizedString(@"zebra", nil),+ NSLocalizedString(@"giraffe", nil),+ NSLocalizedString(@"backpack", nil),+ NSLocalizedString(@"umbrella", nil),+ NSLocalizedString(@"handbag", nil),+ NSLocalizedString(@"tie", nil),+ NSLocalizedString(@"suitcase", nil),+ NSLocalizedString(@"frisbee", nil),+ NSLocalizedString(@"skis", nil),+ NSLocalizedString(@"snowboard", nil),+ NSLocalizedString(@"sports ball", nil),+ NSLocalizedString(@"kite", nil),+ NSLocalizedString(@"baseball bat", nil),+ NSLocalizedString(@"baseball glove", nil),+ NSLocalizedString(@"skateboard", nil),+ NSLocalizedString(@"surfboard", nil),+ NSLocalizedString(@"tennis racket", nil),+ NSLocalizedString(@"bottle", nil),+ NSLocalizedString(@"wine glass", nil),+ NSLocalizedString(@"cup", nil),+ NSLocalizedString(@"fork", nil),+ NSLocalizedString(@"knife", nil),+ NSLocalizedString(@"spoon", nil),+ NSLocalizedString(@"bowl", nil),+ NSLocalizedString(@"banana", nil),+ NSLocalizedString(@"apple", nil),+ NSLocalizedString(@"sandwich", nil),+ NSLocalizedString(@"orange", nil),+ NSLocalizedString(@"broccoli", nil),+ NSLocalizedString(@"carrot", nil),+ NSLocalizedString(@"hot dog", nil),+ NSLocalizedString(@"pizza", nil),+ NSLocalizedString(@"donut", nil),+ NSLocalizedString(@"cake", nil),+ NSLocalizedString(@"chair", nil),+ NSLocalizedString(@"couch", nil),+ NSLocalizedString(@"potted plant", nil),+ NSLocalizedString(@"bed", nil),+ NSLocalizedString(@"dining table", nil),+ NSLocalizedString(@"toilet", nil),+ NSLocalizedString(@"tv", nil),+ NSLocalizedString(@"laptop", nil),+ NSLocalizedString(@"mouse", nil),+ NSLocalizedString(@"remote", nil),+ NSLocalizedString(@"keyboard", nil),+ NSLocalizedString(@"cell phone", nil),+ NSLocalizedString(@"microwave", nil),+ NSLocalizedString(@"oven", nil),+ NSLocalizedString(@"toaster", nil),+ NSLocalizedString(@"sink", nil),+ NSLocalizedString(@"refrigerator", nil),+ NSLocalizedString(@"book", nil),+ NSLocalizedString(@"clock", nil),+ NSLocalizedString(@"vase", nil),+ NSLocalizedString(@"scissors", nil),+ NSLocalizedString(@"teddy bear", nil),+ NSLocalizedString(@"hair drier", nil),+ NSLocalizedString(@"toothbrush", nil)+ ];++ self.title = self.presetKey ?: @"New Preset";+ self.view.backgroundColor = [UIColor systemBackgroundColor];++ // Create table view+ UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];+ tableView.delegate = self;+ tableView.dataSource = self;+ [self.view addSubview:tableView];++ // Add a "Save" button+ UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(savePreset)];+ self.navigationItem.rightBarButtonItem = saveButton;+}++#pragma mark - UITableView DataSource++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ return 80; // Numbers 0-79+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NumberCell"];+ if (!cell) {+ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NumberCell"];+ }+ cell.textLabel.text = [NSString stringWithFormat:@"%@", self.classes[indexPath.row]];+ cell.accessoryType = [self.selectedIndexes containsObject:@(indexPath.row)] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;+ return cell;+}++#pragma mark - UITableView Delegate++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ NSNumber *number = @(indexPath.row);+ if ([self.selectedIndexes containsObject:number]) {+ [self.selectedIndexes removeObject:number];+ } else {+ [self.selectedIndexes addObject:number];+ }+ [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];+}++#pragma mark - Save Preset++- (void)savePreset {+ if (self.completionHandler) {+ self.completionHandler(self.selectedIndexes);+ }+ [self.navigationController popViewControllerAnimated:YES];+}++@enddiff --git a/ios/clearcam/PortScanner.h b/ios/clearcam/PortScanner.hnew file mode 100644index 0000000..c80978e--- /dev/null+++ b/ios/clearcam/PortScanner.h@@ -0,0 +1,11 @@+#import <Foundation/Foundation.h>++@interface PortScanner : NSObject++- (NSString *)getDeviceIPAddress;+- (void)updateCachedOpenPortsForPort:(int)port;++@property (nonatomic, strong) NSMutableArray<NSString *> *cachedOpenPorts;+@property (nonatomic, strong) dispatch_queue_t scanQueue;+@end+diff --git a/ios/clearcam/PortScanner.m b/ios/clearcam/PortScanner.mnew file mode 100644index 0000000..b3eb713--- /dev/null+++ b/ios/clearcam/PortScanner.m@@ -0,0 +1,73 @@+#import "PortScanner.h"+#include <ifaddrs.h>+#include <arpa/inet.h>+#include <netinet/in.h>+#include <sys/socket.h>++@interface PortScanner ()+@property (nonatomic, strong) NSTimer *ipCheckTimer;+@property (nonatomic, strong) NSString *lastKnownIPAddress;+@end++@implementation PortScanner++- (instancetype)init {+ self = [super init];+ if (self) {+ [self startPeriodicIPCheck];+ }+ return self;+}++- (void)startPeriodicIPCheck {+ [self checkAndUpdateIPAddress];+ self.ipCheckTimer = [NSTimer scheduledTimerWithTimeInterval:5.0+ target:self+ selector:@selector(checkAndUpdateIPAddress)+ userInfo:nil+ repeats:YES];+}++- (void)checkAndUpdateIPAddress {+ NSString *currentIP = [self getDeviceIPAddress];++ if (currentIP && ![currentIP isEqualToString:self.lastKnownIPAddress]) {+ self.lastKnownIPAddress = currentIP;+ [[NSUserDefaults standardUserDefaults] setObject:currentIP forKey:@"DeviceIPAddress"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ [[NSNotificationCenter defaultCenter] postNotificationName:@"DeviceIPAddressDidChangeNotification"+ object:nil];+ }+}++- (NSString *)getDeviceIPAddress {+ struct ifaddrs *interfaces = NULL;+ struct ifaddrs *temp_addr = NULL;+ NSString *ipAddress = nil;++ if (getifaddrs(&interfaces) == 0) {+ temp_addr = interfaces;+ while (temp_addr != NULL) {+ if (temp_addr->ifa_addr->sa_family == AF_INET) {+ if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {+ ipAddress = [NSString stringWithUTF8String:+ inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];+ break;+ }+ }+ temp_addr = temp_addr->ifa_next;+ }+ }+ freeifaddrs(interfaces);+ if (ipAddress && ipAddress.length > 0) {+ return [NSString stringWithFormat:@"http://%@", ipAddress];+ } else {+ return @"";+ }+}++- (void)dealloc {+ [self.ipCheckTimer invalidate];+ self.ipCheckTimer = nil;+}+@enddiff --git a/ios/clearcam/Premium.storekit b/ios/clearcam/Premium.storekitnew file mode 100644index 0000000..defc750--- /dev/null+++ b/ios/clearcam/Premium.storekit@@ -0,0 +1,117 @@+{+ "appPolicies" : {+ "eula" : "",+ "policies" : [+ {+ "locale" : "en_US",+ "policyText" : "",+ "policyURL" : ""+ }+ ]+ },+ "identifier" : "7F530ACF",+ "nonRenewingSubscriptions" : [++ ],+ "products" : [++ ],+ "settings" : {+ "_applicationInternalID" : "6743237694",+ "_developerTeamID" : "VLS9B5G7MH",+ "_failTransactionsEnabled" : false,+ "_lastSynchronizedDate" : 763600409.36585605,+ "_locale" : "en_US",+ "_storefront" : "USA",+ "_storeKitErrors" : [+ {+ "current" : null,+ "enabled" : false,+ "name" : "Load Products"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Purchase"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Verification"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "App Store Sync"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Subscription Status"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "App Transaction"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Manage Subscriptions Sheet"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Refund Request Sheet"+ },+ {+ "current" : null,+ "enabled" : false,+ "name" : "Offer Code Redeem Sheet"+ }+ ]+ },+ "subscriptionGroups" : [+ {+ "id" : "21649685",+ "localizations" : [++ ],+ "name" : "Premium",+ "subscriptions" : [+ {+ "adHocOffers" : [++ ],+ "codeOffers" : [++ ],+ "displayPrice" : "0.99",+ "familyShareable" : false,+ "groupNumber" : 1,+ "internalID" : "6743237717",+ "introductoryOffer" : null,+ "localizations" : [+ {+ "description" : "Clearcam Premium",+ "displayName" : "Premium",+ "locale" : "en_GB"+ }+ ],+ "productID" : "monthly.premium",+ "recurringSubscriptionPeriod" : "P1M",+ "referenceName" : "Monthly Premium",+ "subscriptionGroupID" : "21649685",+ "type" : "RecurringSubscription",+ "winbackOffers" : [++ ]+ }+ ]+ }+ ],+ "version" : {+ "major" : 4,+ "minor" : 0+ }+}diff --git a/ios/clearcam/SceneDelegate.h b/ios/clearcam/SceneDelegate.hnew file mode 100644index 0000000..4813059--- /dev/null+++ b/ios/clearcam/SceneDelegate.h@@ -0,0 +1,9 @@+#import <UIKit/UIKit.h>++@interface SceneDelegate : UIResponder <UIWindowSceneDelegate>++@property (strong, nonatomic) UIWindow * window;++@end++diff --git a/ios/clearcam/SceneDelegate.m b/ios/clearcam/SceneDelegate.mnew file mode 100644index 0000000..89e8fc4--- /dev/null+++ b/ios/clearcam/SceneDelegate.m@@ -0,0 +1,18 @@+#import "SceneDelegate.h"+#import "MainViewController.h"++@interface SceneDelegate ()++@end++@implementation SceneDelegate++- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {+ self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];+ MainViewController *rootViewController = [[MainViewController alloc] init];+ UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];+ self.window.rootViewController = navigationController;+ [self.window makeKeyAndVisible];+}++@enddiff --git a/ios/clearcam/SceneState.h b/ios/clearcam/SceneState.hnew file mode 100644index 0000000..2d36f13--- /dev/null+++ b/ios/clearcam/SceneState.h@@ -0,0 +1,17 @@+#import <Foundation/Foundation.h>+#import <CoreData/CoreData.h>+#import <AVFoundation/AVFoundation.h>++@interface SceneState : NSObject++@property (nonatomic, strong) NSMutableArray<NSDictionary *> *lastN;+@property (nonatomic, strong) NSMutableDictionary *lastN_total;+@property (nonatomic, strong) NSArray<NSNumber *> *events;+@property (nonatomic, strong) NSDictionary *alerts;+@property (strong, nonatomic) NSManagedObjectContext *backgroundContext;+@property (strong, nonatomic) NSDate *last_notif_time;+@property (strong, nonatomic) NSDate *left_live_time;+- (void)processOutput:(NSArray *)array withImage:(CIImage *)image orientation:(AVCaptureVideoOrientation)orientation;+- (void)sendnotification; //todo, remove++@enddiff --git a/ios/clearcam/SceneState.m b/ios/clearcam/SceneState.mnew file mode 100644index 0000000..3beb868--- /dev/null+++ b/ios/clearcam/SceneState.m@@ -0,0 +1,185 @@+#import "SceneState.h"+#import "SettingsManager.h"+#import "SecretManager.h"+#import "AppDelegate.h"+#import "StoreManager.h"+#import "FileServer.h"+#import "notification.h"+#import <MobileCoreServices/MobileCoreServices.h> // Add this import+#import <CommonCrypto/CommonCryptor.h>++#define MAGIC_NUMBER 0x4D41474943ULL // "MAGIC" in ASCII as a 64-bit value+#define HEADER_SIZE (sizeof(uint64_t)) // Size of the magic number (8 bytes)++@implementation SceneState++- (instancetype)init {+ self = [super init];+ if (self) {+ self.lastN = [NSMutableArray array];+ self.lastN_total = [[NSMutableDictionary alloc] init];+ self.alerts = [SettingsManager sharedManager].alerts;+ self.last_notif_time = [NSDate dateWithTimeIntervalSince1970:0];+ self.left_live_time = [NSDate now];+ // Get Core Data context from AppDelegate+ AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];+ self.backgroundContext = appDelegate.persistentContainer.newBackgroundContext;+ }+ return self;+}++- (void)processOutput:(NSArray *)array withImage:(CIImage *)image orientation:(AVCaptureVideoOrientation)orientation{+ NSArray *events = [[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"][[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_preset_idx"]];+ if(!events) return;+ NSMutableDictionary *frame = [[NSMutableDictionary alloc] init];++ // Count occurrences in the current frame+ for (int i = 0; i < array.count; i++) {+ frame[array[i][4]] = frame[array[i][4]] ? @([frame[array[i][4]] intValue] + 1) : @1;+ }++ [self.lastN addObject:frame]; // Store this frame's data++ // Process events+ for (int i = 0; i < events.count; i++) {+ NSNumber *totalValue = self.lastN_total[events[i]] ?: @0;+ NSNumber *last_totalValue = [totalValue copy];+ NSNumber *frameValue = frame[events[i]] ?: @0;+ totalValue = @(totalValue.intValue + frameValue.intValue);++ if (self.lastN.count > 10) {+ frameValue = self.lastN[0][events[i]] ?: @0;+ totalValue = @(totalValue.intValue - frameValue.intValue);+ }++ int current_state = (int)roundf((totalValue ? [totalValue floatValue] : 0.0) / 10.0);+ int last_state = (int)roundf((last_totalValue ? [last_totalValue floatValue] : 0.0) / 10.0);+ self.lastN_total[events[i]] = totalValue;++ if (current_state != last_state && self.last_notif_time && [[NSDate date] timeIntervalSinceDate:self.last_notif_time] > 60) { //one event per min for now+ self.last_notif_time = [NSDate now];+ NSDate *date = [NSDate date];+ NSTimeInterval unixTimestamp = [date timeIntervalSince1970];+ long long roundedUnixTimestamp = (long long)unixTimestamp;++ // Convert CIImage to CGImage+ CIContext *ciContext = [CIContext context];+ CGImageRef cgImage = [ciContext createCGImage:image fromRect:image.extent];++ if (cgImage) {+ UIImage *uiImage = [UIImage imageWithCGImage:cgImage];+ CGImageRelease(cgImage);+ uiImage = [self rotatedImage:uiImage forOrientation:orientation];+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);+ NSString *documentsDirectory = [paths firstObject];+ NSString *imagesDirectory = [documentsDirectory stringByAppendingPathComponent:@"images"];+ if (![[NSFileManager defaultManager] fileExistsAtPath:imagesDirectory]) {+ [[NSFileManager defaultManager] createDirectoryAtPath:imagesDirectory+ withIntermediateDirectories:YES+ attributes:nil+ error:nil];+ }++ NSData *imageData = UIImageJPEGRepresentation(uiImage, 1.0); // 1.0 for maximum quality+ NSString *filePathSmall = [imagesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%lld_small.jpg", roundedUnixTimestamp]];++ // Write the image data to file+ if ([imageData writeToFile:filePathSmall atomically:YES]) {+ // Thumbnail generation+ UIGraphicsBeginImageContextWithOptions(CGSizeMake(uiImage.size.width / 2, uiImage.size.height / 2), YES, 1.0);+ [uiImage drawInRect:CGRectMake(0, 0, uiImage.size.width / 2, uiImage.size.height / 2)];+ UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();+ UIGraphicsEndImageContext();+ NSData *lowResImageData = UIImageJPEGRepresentation(resizedImage, 0.7);+ [lowResImageData writeToFile:filePathSmall atomically:YES];++ NSDate *expiry = [[NSUserDefaults standardUserDefaults] objectForKey:@"expiry"];+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ BOOL sessionExpiredOrNow = !expiry || [expiry compare:[NSDate date]] != NSOrderedDescending;+ if(isSubscribed) {+ if (sessionExpiredOrNow) {+ [[StoreManager sharedInstance] verifySubscriptionWithCompletion:^(BOOL isActive, NSDate *expiryDate) {+ [self sendnotification];+ }];+ } else {+ [self sendnotification];+ }+ }+ }+ }++ [self.backgroundContext performBlockAndWait:^{+ NSManagedObject *newEvent = [NSEntityDescription insertNewObjectForEntityForName:@"EventEntity"+ inManagedObjectContext:self.backgroundContext];++ [newEvent setValue:@(unixTimestamp) forKey:@"timeStamp"];+ [newEvent setValue:events[i] forKey:@"classType"];+ [newEvent setValue:@(current_state) forKey:@"quantity"];++ NSError *saveError = nil;+ [self.backgroundContext save:&saveError];+ }];+ }++ }++ // Keep lastN size within 10+ if (self.lastN.count > 10) {+ [self.lastN removeObjectAtIndex:0];+ }+}++- (UIImage *)rotatedImage:(UIImage *)image forOrientation:(AVCaptureVideoOrientation)orientation {+ UIImageOrientation uiOrientation;+ switch (orientation) {+ case AVCaptureVideoOrientationPortrait:+ uiOrientation = UIImageOrientationRight;+ break;+ case AVCaptureVideoOrientationPortraitUpsideDown:+ uiOrientation = UIImageOrientationLeft;+ break;+ case AVCaptureVideoOrientationLandscapeLeft:+ uiOrientation = UIImageOrientationDown;+ break;+ case AVCaptureVideoOrientationLandscapeRight:+ default:+ uiOrientation = UIImageOrientationUp;+ break;+ }+ return [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:uiOrientation];+}+++- (void)sendnotification {+ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"send_notif_enabled"] || !([[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"] || [[NSUserDefaults standardUserDefaults] boolForKey:@"use_own_server_enabled"])){ //todo add back other stuff+ NSDate *now = [NSDate date];+ if ([now timeIntervalSinceDate:self.left_live_time] < 5.0) return;+ [FileServer sharedInstance].last_req_time = [NSDate now]; //todo, this keep segment length 3 for a min+ NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday) fromDate:now];+ NSInteger currentTime = components.hour * 60 + components.minute;+ NSString *currentDay = @[@"Sun", @"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat"][components.weekday - 1];++ for (NSDictionary *schedule in [[NSUserDefaults standardUserDefaults] arrayForKey:@"notification_schedules"] ?: @[]) {+ if (![schedule[@"enabled"] boolValue]) continue;+ if (![schedule[@"days"] containsObject:currentDay]) continue;++ NSInteger startTime = [schedule[@"startHour"] integerValue] * 60 + [schedule[@"startMinute"] integerValue];+ NSInteger endTime = [schedule[@"endHour"] integerValue] * 60 + [schedule[@"endMinute"] integerValue];++ if (currentTime >= startTime && currentTime <= endTime) {+ [[notification sharedInstance] sendNotification];+ if([FileServer sharedInstance].segment_length > 1) [FileServer sharedInstance].segment_length = 3;+ NSTimeInterval start = [[NSDate dateWithTimeIntervalSinceNow:-7.5] timeIntervalSince1970];+ NSTimeInterval end = [[NSDate dateWithTimeIntervalSinceNow:7.5] timeIntervalSince1970];+ id context = [FileServer sharedInstance].context;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ NSString *filePath = [[FileServer sharedInstance] processVideoDownloadWithLowRes:YES startTime:start endTime:end context:context];+ [[notification sharedInstance] uploadImageAtPath:filePath];+ });+ break;+ }+ }+ }+}++@enddiff --git a/ios/clearcam/ScheduleManagementViewController.h b/ios/clearcam/ScheduleManagementViewController.hnew file mode 100644index 0000000..f7cd480--- /dev/null+++ b/ios/clearcam/ScheduleManagementViewController.h@@ -0,0 +1,12 @@+#import <UIKit/UIKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface ScheduleManagementViewController : UITableViewController++@property (nonatomic, strong) NSMutableArray<NSDictionary *> *notificationSchedules;+@property (nonatomic, copy) void (^completionHandler)(NSArray<NSDictionary *> *schedules);++@end++NS_ASSUME_NONNULL_ENDdiff --git a/ios/clearcam/ScheduleManagementViewController.m b/ios/clearcam/ScheduleManagementViewController.mnew file mode 100644index 0000000..b12f173--- /dev/null+++ b/ios/clearcam/ScheduleManagementViewController.m@@ -0,0 +1,260 @@+#import "ScheduleManagementViewController.h"++@interface ScheduleEditorViewController : UITableViewController+@property (nonatomic, strong) NSMutableDictionary *schedule;+@property (nonatomic, copy) void (^completionHandler)(NSDictionary *schedule);+@end++@implementation ScheduleManagementViewController++- (void)viewDidLoad {+ [super viewDidLoad];++ self.title = @"Notification Schedule";+ self.tableView.allowsMultipleSelection = NO;+ [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ScheduleCell"];++ // Add "Add" button+ UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addScheduleTapped:)];+ self.navigationItem.rightBarButtonItem = addButton;++ // Add "Done" button+ UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped:)];+ self.navigationItem.leftBarButtonItem = doneButton;+}++- (void)doneTapped:(id)sender {+ // Save changes and pop back+ if (self.completionHandler) {+ self.completionHandler(self.notificationSchedules);+ }+ [self.navigationController popViewControllerAnimated:YES];+}++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ return self.notificationSchedules.count;+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ScheduleCell" forIndexPath:indexPath];+ NSDictionary *schedule = self.notificationSchedules[indexPath.row];++ cell.textLabel.text = [self scheduleDescriptionFor:schedule];+ cell.detailTextLabel.text = nil;+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;++ UISwitch *toggleSwitch = [[UISwitch alloc] init];+ toggleSwitch.on = [schedule[@"enabled"] boolValue];+ toggleSwitch.tag = indexPath.row;+ [toggleSwitch addTarget:self action:@selector(toggleSwitchChanged:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = toggleSwitch;++ return cell;+}++- (NSString *)scheduleDescriptionFor:(NSDictionary *)schedule {+ NSArray *days = schedule[@"days"];+ NSNumber *startHour = schedule[@"startHour"];+ NSNumber *startMinute = schedule[@"startMinute"];+ NSNumber *endHour = schedule[@"endHour"];+ NSNumber *endMinute = schedule[@"endMinute"];++ NSString *daysString = days.count == 7 ? @"Every day" : [days componentsJoinedByString:@", "];+ NSString *timeString = [NSString stringWithFormat:@"%02ld:%02ld-%02ld:%02ld",+ [startHour longValue], [startMinute longValue],+ [endHour longValue], [endMinute longValue]];+ return [NSString stringWithFormat:@"%@ %@", daysString, timeString];+}++- (void)toggleSwitchChanged:(UISwitch *)sender {+ NSInteger index = sender.tag;+ NSMutableDictionary *schedule = [self.notificationSchedules[index] mutableCopy];+ schedule[@"enabled"] = @(sender.on);+ self.notificationSchedules[index] = schedule;+ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];+}++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ ScheduleEditorViewController *editorVC = [[ScheduleEditorViewController alloc] init];+ editorVC.schedule = [self.notificationSchedules[indexPath.row] mutableCopy];+ editorVC.completionHandler = ^(NSDictionary *updatedSchedule) {+ self.notificationSchedules[indexPath.row] = updatedSchedule;+ [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];+ };+ [self.navigationController pushViewController:editorVC animated:YES];+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+}++- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {+ NSDictionary *schedule = self.notificationSchedules[indexPath.row];+ return ([schedule[@"days"] count] == 7 && [schedule[@"startHour"] isEqual:@0] && [schedule[@"startMinute"] isEqual:@0] && [schedule[@"endHour"] isEqual:@23] && [schedule[@"endMinute"] isEqual:@59]) ? UITableViewCellEditingStyleNone : UITableViewCellEditingStyleDelete;+}++- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {+ if (editingStyle == UITableViewCellEditingStyleDelete) {+ [self.notificationSchedules removeObjectAtIndex:indexPath.row];+ [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];+ }+}++- (void)addScheduleTapped:(id)sender {+ NSMutableDictionary *newSchedule = [@{+ @"days": @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"],+ @"startHour": @0,+ @"startMinute": @0,+ @"endHour": @23,+ @"endMinute": @59,+ @"enabled": @YES+ } mutableCopy];+ [self.notificationSchedules addObject:newSchedule];+ NSInteger newIndex = self.notificationSchedules.count - 1;+ [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:newIndex inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];++ ScheduleEditorViewController *editorVC = [[ScheduleEditorViewController alloc] init];+ editorVC.schedule = newSchedule;+ editorVC.completionHandler = ^(NSDictionary *updatedSchedule) {+ self.notificationSchedules[newIndex] = updatedSchedule;+ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:newIndex inSection:0]] withRowAnimation:UITableViewRowAnimationNone];+ };+ [self.navigationController pushViewController:editorVC animated:YES];+}++@end++@implementation ScheduleEditorViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.title = @"Edit Schedule";+ [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"EditorCell"];++ UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped:)];+ self.navigationItem.rightBarButtonItem = doneButton;+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {+ return 2; // Days and Time Window+}++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ if (section == 0) {+ return 7; // One row per day+ } else {+ return 2; // Start Time and End Time+ }+}++- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {+ return section == 0 ? @"Repeat" : @"Time Window";+}++- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {+ if (indexPath.section == 1) {+ return 100; // Increased height to accommodate the UIDatePicker+ }+ return UITableViewAutomaticDimension; // Default height for days+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditorCell" forIndexPath:indexPath];++ cell.textLabel.text = nil;+ cell.detailTextLabel.text = nil;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.accessoryView = nil;++ if (indexPath.section == 0) {+ // Days section+ NSArray *allDays = @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"];+ NSString *day = allDays[indexPath.row];+ cell.textLabel.text = day;+ cell.accessoryType = [self.schedule[@"days"] containsObject:day] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;+ } else if (indexPath.section == 1) {+ // Time Window section with embedded UIDatePicker+ UIDatePicker *picker = [[UIDatePicker alloc] init];+ picker.datePickerMode = UIDatePickerModeTime;+ picker.tag = indexPath.row; // 0 for Start Time, 1 for End Time++ if (indexPath.row == 0) {+ cell.textLabel.text = @"Start Time";+ NSDateComponents *startComponents = [[NSDateComponents alloc] init];+ startComponents.hour = [self.schedule[@"startHour"] integerValue];+ startComponents.minute = [self.schedule[@"startMinute"] integerValue];+ picker.date = [[NSCalendar currentCalendar] dateFromComponents:startComponents];+ } else if (indexPath.row == 1) {+ cell.textLabel.text = @"End Time";+ NSDateComponents *endComponents = [[NSDateComponents alloc] init];+ endComponents.hour = [self.schedule[@"endHour"] integerValue];+ endComponents.minute = [self.schedule[@"endMinute"] integerValue];+ picker.date = [[NSCalendar currentCalendar] dateFromComponents:endComponents];+ }++ [picker addTarget:self action:@selector(timePickerChanged:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = picker; // Embed the picker directly in the cell+ }++ return cell;+}++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ if (indexPath.section == 0) {+ // Days section+ NSArray *allDays = @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"];+ NSString *day = allDays[indexPath.row];+ NSMutableArray *days = [self.schedule[@"days"] mutableCopy];+ if ([days containsObject:day]) {+ [days removeObject:day];+ } else {+ [days addObject:day];+ }+ self.schedule[@"days"] = days;+ [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];+ }+ // No action needed for section 1; picker is already interactive+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+}++- (void)timePickerChanged:(UIDatePicker *)picker {+ NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];+ NSInteger row = picker.tag;+ if (row == 0) {+ self.schedule[@"startHour"] = @(components.hour);+ self.schedule[@"startMinute"] = @(components.minute);+ } else {+ self.schedule[@"endHour"] = @(components.hour);+ self.schedule[@"endMinute"] = @(components.minute);+ }+ // No need to reload the table view since the picker itself shows the updated time+}++- (void)doneTapped:(id)sender {+ NSInteger startHour = [self.schedule[@"startHour"] integerValue];+ NSInteger startMinute = [self.schedule[@"startMinute"] integerValue];+ NSInteger endHour = [self.schedule[@"endHour"] integerValue];+ NSInteger endMinute = [self.schedule[@"endMinute"] integerValue];++ if ([self.schedule[@"days"] count] == 0) {+ UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:@"Error"+ message:@"Please select at least one day."+ preferredStyle:UIAlertControllerStyleAlert];+ [errorAlert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:errorAlert animated:YES completion:nil];+ return;+ }++ if (!((startHour < endHour) || (startHour == endHour && startMinute < endMinute))) {+ UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:@"Invalid Time"+ message:@"Start time must be before end time."+ preferredStyle:UIAlertControllerStyleAlert];+ [errorAlert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:errorAlert animated:YES completion:nil];+ return;+ }++ if (self.completionHandler) {+ self.completionHandler(self.schedule);+ }+ [self.navigationController popViewControllerAnimated:YES];+}++@enddiff --git a/ios/clearcam/SecretManager.h b/ios/clearcam/SecretManager.hnew file mode 100644index 0000000..9156a13--- /dev/null+++ b/ios/clearcam/SecretManager.h@@ -0,0 +1,33 @@+#ifndef SecretManager_h+#define SecretManager_h++#import <Foundation/Foundation.h>+#import <UIKit/UIKit.h>++@interface SecretManager : NSObject++// Singleton instance++ (instancetype)sharedManager;++// Encryption Key Management (Single Key)+- (BOOL)saveEncryptionKey:(NSString *)key error:(NSError **)error;+- (NSString *)getEncryptionKey;++// Decryption Key Management (Multiple Keys)+- (BOOL)saveDecryptionKey:(NSString *)key withIdentifier:(NSString *)identifier error:(NSError **)error;+- (NSArray<NSString *> *)getAllDecryptionKeys;++// Generic Key Management+- (BOOL)deleteKeyWithIdentifier:(NSString *)identifier error:(NSError **)error;+- (BOOL)deleteAllKeysWithError:(NSError **)error;+- (NSString *)retrieveDecryptionKeyWithIdentifier:(NSString *)identifier error:(NSError **)error;++- (NSData *)decryptData:(NSData *)encryptedData withKey:(NSString *)key;+- (NSData *)encryptData:(NSData *)data withKey:(NSString *)key;+- (void)promptUserForKeyFromViewController:(UIViewController *)presentingViewController+ completion:(void (^)(NSString *key))completion;++@end++#endif /* SecretManager_h */+diff --git a/ios/clearcam/SecretManager.m b/ios/clearcam/SecretManager.mnew file mode 100644index 0000000..b4c4c08--- /dev/null+++ b/ios/clearcam/SecretManager.m@@ -0,0 +1,398 @@+#import "SecretManager.h"+#import <Security/Security.h>+#import <CommonCrypto/CommonCryptor.h>+#import <UIKit/UIKit.h>++static NSString *const kServiceIdentifier = @"com.yourapp.aeskeys"; // Replace with your app's unique identifier++@implementation SecretManager++#pragma mark - Singleton+++ (instancetype)sharedManager {+ static SecretManager *sharedInstance = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedInstance = [[SecretManager alloc] init];+ });+ return sharedInstance;+}++#pragma mark - Key Retrieval++- (NSArray<NSString *> *)getAllStoredKeys {+ NSMutableArray<NSString *> *keys = [NSMutableArray array];++ // Query the Keychain for all stored keys+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecReturnAttributes: @YES,+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitAll+ };++ CFTypeRef result = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);+ if (status == errSecSuccess) {+ NSArray *items = (__bridge_transfer NSArray *)result;+ for (NSDictionary *item in items) {+ NSData *keyData = item[(__bridge id)kSecValueData];+ if (keyData) {+ NSString *key = [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding];+ if (key) {+ [keys addObject:key];+ }+ }+ }+ }+ return [keys copy];+}++- (nullable NSString *)retrieveDecryptionKeyWithIdentifier:(NSString *)identifier error:(NSError **)error {+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: identifier,+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne+ };++ CFTypeRef result = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);+ if (status == errSecSuccess) {+ NSData *keyData = (__bridge_transfer NSData *)result;+ return [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding];+ } else {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return nil;+ }+}++- (BOOL)saveEncryptionKey:(NSString *)key error:(NSError **)error {+ if (!key) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:-1+ userInfo:@{NSLocalizedDescriptionKey: @"Encryption key cannot be nil."}];+ }+ return NO;+ }++ NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];++ // Define a fixed identifier for the encryption key+ NSString *encryptionKeyIdentifier = @"encryption_key";++ // Delete any existing encryption key before saving a new one+ [self deleteKeyWithIdentifier:encryptionKeyIdentifier error:nil];++ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: encryptionKeyIdentifier,+ (__bridge id)kSecValueData: keyData,+ (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlocked+ };++ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);+ if (status != errSecSuccess) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }+ return YES;+}++- (void)promptUserForKeyFromViewController:(UIViewController *)presentingViewController completion:(void (^)(NSString *key))completion {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Decryption Key"+ message:@"Please enter the password used by your device to encrypt this data."+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = @"Decryption Key";+ textField.secureTextEntry = YES;+ }];++ UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *key = alert.textFields.firstObject.text;+ completion(key);+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"+ style:UIAlertActionStyleCancel+ handler:^(UIAlertAction * _Nonnull action) {+ completion(nil);+ }];++ [alert addAction:okAction];+ [alert addAction:cancelAction];++ [presentingViewController presentViewController:alert animated:YES completion:nil];+}+++- (NSArray<NSString *> *)getAllDecryptionKeys {+ NSMutableArray<NSString *> *keys = [NSMutableArray array];++ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecReturnAttributes: @YES,+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitAll+ };++ CFTypeRef result = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);+ if (status == errSecSuccess) {+ NSArray *items = (__bridge_transfer NSArray *)result;+ for (NSDictionary * item in items) {+ NSString *identifier = item[(__bridge id)kSecAttrAccount];+ if (![identifier isEqualToString:@"encryption_key"]) { // Ignore the encryption key+ NSData *keyData = item[(__bridge id)kSecValueData];+ NSString *key = [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding];+ if (key) {+ [keys addObject:key];+ }+ }+ }+ }++ return [keys copy];+}++- (BOOL)saveDecryptionKey:(NSString *)key withIdentifier:(NSString *)identifier error:(NSError **)error {+ if (!key || !identifier) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:-1+ userInfo:@{NSLocalizedDescriptionKey: @"Decryption key and identifier cannot be nil."}];+ }+ return NO;+ }++ NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];++ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: identifier,+ (__bridge id)kSecValueData: keyData,+ (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlocked+ };++ // Ensure we don't overwrite an existing key with the same identifier+ SecItemDelete((__bridge CFDictionaryRef)query);++ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);+ if (status != errSecSuccess) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }+ return YES;+}++- (NSString *)getEncryptionKey {+ NSString *encryptionKeyIdentifier = @"encryption_key";++ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: encryptionKeyIdentifier,+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne+ };++ CFTypeRef result = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);++ if (status == errSecSuccess) {+ NSData *keyData = (__bridge_transfer NSData *)result;+ return [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding];+ }+ return nil;+}++#pragma mark - Key Deletion++- (BOOL)deleteKeyWithIdentifier:(NSString *)identifier error:(NSError **)error {+ if (!identifier) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:-1+ userInfo:@{NSLocalizedDescriptionKey: @"Identifier cannot be nil."}];+ }+ return NO;+ }++ // Keychain query to delete the key+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier,+ (__bridge id)kSecAttrAccount: identifier+ };++ OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);+ if (status != errSecSuccess && status != errSecItemNotFound) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }+ return YES;+}++- (BOOL)deleteAllKeysWithError:(NSError **)error {+ // Keychain query to delete all keys for this service+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: kServiceIdentifier+ };++ OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);+ if (status != errSecSuccess && status != errSecItemNotFound) {+ if (error) {+ *error = [NSError errorWithDomain:@"SecretManagerErrorDomain"+ code:status+ userInfo:@{NSLocalizedDescriptionKey: [self errorMessageForStatus:status]}];+ }+ return NO;+ }+ return YES;+}++#pragma mark - Helper Methods++- (NSString *)errorMessageForStatus:(OSStatus)status {+ switch (status) {+ case errSecDuplicateItem:+ return @"A key with this identifier already exists.";+ case errSecItemNotFound:+ return @"The requested key was not found.";+ case errSecAuthFailed:+ return @"Authentication failed.";+ default:+ return [NSString stringWithFormat:@"Keychain error %d occurred.", (int)status];+ }+}++#define MAGIC_NUMBER 0x4D41474943ULL // "MAGIC" in ASCII as a 64-bit value+#define HEADER_SIZE (sizeof(uint64_t)) // Size of the magic number (8 bytes)+#define AES_BLOCK_SIZE kCCBlockSizeAES128+#define AES_KEY_SIZE kCCKeySizeAES256++- (NSData *)encryptData:(NSData *)data withKey:(NSString *)key {+ if (!data || !key) return nil;+ uint64_t magicNumber = MAGIC_NUMBER;+ NSMutableData *headerData = [NSMutableData dataWithBytes:&magicNumber length:HEADER_SIZE];+ NSMutableData *dataToEncrypt = [NSMutableData data];+ [dataToEncrypt appendData:headerData];+ [dataToEncrypt appendData:data];+ char keyPtr[AES_KEY_SIZE + 1];+ bzero(keyPtr, sizeof(keyPtr));+ BOOL keyResult = [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];+ if (!keyResult) return nil;+ uint8_t ivBytes[AES_BLOCK_SIZE];+ int status = SecRandomCopyBytes(kSecRandomDefault, AES_BLOCK_SIZE, ivBytes);+ if (status != errSecSuccess) return nil;+ NSData *ivData = [NSData dataWithBytes:ivBytes length:AES_BLOCK_SIZE];+ size_t bufferSize = dataToEncrypt.length + AES_BLOCK_SIZE;+ void *buffer = malloc(bufferSize);+ if (buffer == NULL) return nil;+ size_t numBytesEncrypted = 0;+ CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,+ kCCAlgorithmAES,+ kCCOptionPKCS7Padding,+ keyPtr,+ AES_KEY_SIZE,+ ivBytes,+ dataToEncrypt.bytes,+ dataToEncrypt.length,+ buffer,+ bufferSize,+ &numBytesEncrypted);++ if (cryptStatus == kCCSuccess) {+ NSMutableData *resultData = [NSMutableData dataWithData:ivData];+ [resultData appendBytes:buffer length:numBytesEncrypted];+ free(buffer);+ return resultData;+ } else {+ free(buffer);+ return nil;+ }+}++- (NSData *)decryptData:(NSData *)encryptedDataWithIv withKey:(NSString *)key {+ if (!encryptedDataWithIv || !key) return nil;+ if (encryptedDataWithIv.length <= AES_BLOCK_SIZE) return nil;+ NSData *ivData = [encryptedDataWithIv subdataWithRange:NSMakeRange(0, AES_BLOCK_SIZE)];+ const void *ivBytes = ivData.bytes;+ NSData *encryptedData = [encryptedDataWithIv subdataWithRange:NSMakeRange(AES_BLOCK_SIZE, encryptedDataWithIv.length - AES_BLOCK_SIZE)];+ const void *encryptedBytes = encryptedData.bytes;+ size_t encryptedLength = encryptedData.length;+ char keyPtr[AES_KEY_SIZE + 1];+ bzero(keyPtr, sizeof(keyPtr));+ BOOL keyResult = [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];+ if (!keyResult) {+ NSLog(@"Decryption Error: Failed to get key bytes.");+ return nil;+ }+ size_t bufferSize = encryptedLength;+ void *buffer = malloc(bufferSize);+ if (buffer == NULL) {+ NSLog(@"Decryption Error: Failed to allocate memory for buffer.");+ return nil;+ }++ size_t numBytesDecrypted = 0;+ CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,+ kCCAlgorithmAES,+ kCCOptionPKCS7Padding,+ keyPtr,+ AES_KEY_SIZE,+ ivBytes,+ encryptedBytes,+ encryptedLength,+ buffer,+ bufferSize,+ &numBytesDecrypted);++ if (cryptStatus != kCCSuccess) {+ free(buffer);+ return nil;+ }+ if (numBytesDecrypted < HEADER_SIZE) {+ NSLog(@"Decryption Error: Decrypted data is too short for header.");+ free(buffer);+ return nil;+ }+ uint64_t decryptedMagicNumber;+ memcpy(&decryptedMagicNumber, buffer, HEADER_SIZE);+ if (decryptedMagicNumber != MAGIC_NUMBER) {+ free(buffer);+ return nil;+ }+ size_t originalDataLength = numBytesDecrypted - HEADER_SIZE;+ NSData *result = [NSData dataWithBytes:(buffer + HEADER_SIZE) length:originalDataLength];+ free(buffer);+ return result;+}++@enddiff --git a/ios/clearcam/SettingsManager.h b/ios/clearcam/SettingsManager.hnew file mode 100644index 0000000..6c70d98--- /dev/null+++ b/ios/clearcam/SettingsManager.h@@ -0,0 +1,20 @@+#import <Foundation/Foundation.h>++@interface SettingsManager : NSObject++@property (nonatomic, strong) NSArray<NSNumber *> *events;+@property (nonatomic, strong) NSDictionary *alerts;++@property (nonatomic, strong) NSString *width;+@property (nonatomic, strong) NSString *height;+@property (nonatomic, strong) NSString *text_size;+@property (nonatomic, strong) NSString *preset; //todo, resolution++++ (instancetype)sharedManager;+- (void)updateYoloIndexesKey:(NSString *)key;+- (void)loadResolutionSettings;+- (void)saveResolutionSettings;+- (void)updateResolutionWithWidth:(NSString *)width height:(NSString *)height textSize:(NSString *)textSize preset:(NSString *)preset;++@enddiff --git a/ios/clearcam/SettingsManager.m b/ios/clearcam/SettingsManager.mnew file mode 100644index 0000000..edc40cc--- /dev/null+++ b/ios/clearcam/SettingsManager.m@@ -0,0 +1,80 @@+#import "SettingsManager.h"++@implementation SettingsManager+++ (instancetype)sharedManager {+ static SettingsManager *sharedManager = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedManager = [[self alloc] init];+ });+ return sharedManager;+}++- (instancetype)init {+ self = [super init];+ if (self) {+ NSDictionary *savedPresets = [[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"];+ if (!savedPresets) {+ [[NSUserDefaults standardUserDefaults] setObject:[[NSMutableDictionary alloc] initWithDictionary:@{+ NSLocalizedString(@"all", nil): @[@0, @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],+ NSLocalizedString(@"people+vehicles", nil): @[@0, @1, @2, @3, @5, @7]+ }] forKey:@"yolo_presets"];+ }+ if(![[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_preset_idx"]) [[NSUserDefaults standardUserDefaults] setObject:NSLocalizedString(@"people+vehicles", nil) forKey:@"yolo_preset_idx"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ [self loadResolutionSettings];+ }+ return self;+}++- (void)updateYoloIndexesKey:(NSString *)key {+ [[NSUserDefaults standardUserDefaults] setObject:key forKey:@"yolo_preset_idx"];+ [[NSUserDefaults standardUserDefaults] synchronize];+}++- (NSArray<NSNumber *> *)generateDefaultEvents {+ NSMutableArray<NSNumber *> *defaultEvents = [NSMutableArray array];+ [defaultEvents addObject:@0]; // 1 person for now+ [defaultEvents addObject:@2];+ [defaultEvents addObject:@63]; // laptop for now+ return [defaultEvents copy];+}++- (NSDictionary*)generateDefaultAlerts {+ NSMutableDictionary *defaultAlerts = [[NSMutableDictionary alloc] init];+ defaultAlerts[@2] = @0; // just min 0 for now+ return [defaultAlerts copy];+}+++//old+//self.res = [[Resolution alloc] initWithWidth:3840 height:2160 text_size:5 preset:AVCaptureSessionPreset3840x2160];+//self.res = [[Resolution alloc] initWithWidth:1920 height:1080 text_size:3 preset:AVCaptureSessionPreset1920x1080];+//self.res = [[Resolution alloc] initWithWidth:1280 height:720 text_size:2 preset:AVCaptureSessionPreset1280x720];+- (void)loadResolutionSettings {+ self.width = [[NSUserDefaults standardUserDefaults] stringForKey:@"resolution_width"] ?: @"1920";+ self.height = [[NSUserDefaults standardUserDefaults] stringForKey:@"resolution_height"] ?: @"1080";+ self.text_size = [[NSUserDefaults standardUserDefaults] stringForKey:@"resolution_text_size"] ?: @"3";+ self.preset = [[NSUserDefaults standardUserDefaults] stringForKey:@"resolution_preset"] ?: @"AVCaptureSessionPreset1920x1080";+}++// Save resolution settings to UserDefaults+- (void)saveResolutionSettings {+ [[NSUserDefaults standardUserDefaults] setObject:self.width forKey:@"resolution_width"];+ [[NSUserDefaults standardUserDefaults] setObject:self.height forKey:@"resolution_height"];+ [[NSUserDefaults standardUserDefaults] setObject:self.text_size forKey:@"resolution_text_size"];+ [[NSUserDefaults standardUserDefaults] setObject:self.preset forKey:@"resolution_preset"];+ [[NSUserDefaults standardUserDefaults] synchronize];+}++// Update resolution settings+- (void)updateResolutionWithWidth:(NSString *)width height:(NSString *)height textSize:(NSString *)textSize preset:(NSString *)preset {+ self.width = width;+ self.height = height;+ self.text_size = textSize;+ self.preset = preset;+ [self saveResolutionSettings];+}++@enddiff --git a/ios/clearcam/SettingsViewController.h b/ios/clearcam/SettingsViewController.hnew file mode 100644index 0000000..3e39cd6--- /dev/null+++ b/ios/clearcam/SettingsViewController.h@@ -0,0 +1,6 @@+// SettingsViewController.h+#import <UIKit/UIKit.h>++@interface SettingsViewController : UIViewController++@enddiff --git a/ios/clearcam/SettingsViewController.m b/ios/clearcam/SettingsViewController.mnew file mode 100644index 0000000..db95dbc--- /dev/null+++ b/ios/clearcam/SettingsViewController.m@@ -0,0 +1,1433 @@+#import "SettingsViewController.h"+#import "SettingsManager.h"+#import "SecretManager.h"+#import "StoreManager.h"+#import "NumberSelectionViewController.h"+#import "notification.h"+#import "FileServer.h"+#import "ScheduleManagementViewController.h"+#import <UserNotifications/UserNotifications.h>+#import <StoreKit/StoreKit.h>+#import <LocalAuthentication/LocalAuthentication.h>++@interface SettingsViewController () <UITableViewDelegate, UITableViewDataSource>++@property (nonatomic, strong) UITableView *tableView;+@property (nonatomic, strong) NSString *selectedResolution;+@property (nonatomic, strong) NSString *selectedPresetKey; // For YOLO indexes key+@property (nonatomic, assign) BOOL isPresetsSectionExpanded; // Track if presets section is expanded+@property (nonatomic, assign) BOOL sendNotifEnabled;+@property (nonatomic, assign) BOOL receiveNotifEnabled; // New property for receiving notifications+@property (nonatomic, assign) BOOL useOwnServerEnabled;+@property (nonatomic, strong) NSString *notificationServerAddress; // Store the notification server address+@property (nonatomic, strong) NSMutableArray<NSDictionary *> *notificationSchedules; // Array to store notification schedules+@property (nonatomic, assign) BOOL streamViaWiFiEnabled;+@property (nonatomic, strong) id ipAddressObserver;+@property (nonatomic, assign) NSInteger threshold; // New property for threshold+@property (nonatomic, assign) BOOL liveStreamInternetEnabled; // New property for live stream toggle+@property (nonatomic, strong) NSString *deviceName; // New property for device name+@property (nonatomic, assign) BOOL useOwnInferenceServerEnabled;+@property (nonatomic, strong) NSString *inferenceServerAddress;+@property (nonatomic, assign) BOOL isUserIDVisible;++@end++@implementation SettingsViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.isUserIDVisible = NO;+ self.view.backgroundColor = [UIColor systemBackgroundColor];+ self.title = NSLocalizedString(@"settings", @"Title for settings screen");+ [[StoreManager sharedInstance] verifySubscriptionWithCompletionIfSubbed:^(BOOL isActive, NSDate *expiryDate) {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.tableView reloadData];+ });+ }];++ UIBarButtonItem *helpButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"docs", nil) style:UIBarButtonItemStylePlain target:self action:@selector(helpButtonTapped)];+ [helpButton setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor systemBlueColor]}+ forState:UIControlStateNormal];+ self.navigationItem.rightBarButtonItem = helpButton;++ // Register for subscription status change notifications+ [[NSNotificationCenter defaultCenter] addObserver:self+ selector:@selector(subscriptionStatusDidChange:)+ name:StoreManagerSubscriptionStatusDidChangeNotification+ object:nil];++ // Initialize properties from NSUserDefaults+ SettingsManager *settingsManager = [SettingsManager sharedManager];+ NSString *height = settingsManager.height ?: @"720";+ self.selectedResolution = [NSString stringWithFormat:@"%@p", height];+ self.selectedPresetKey = [[NSUserDefaults standardUserDefaults] stringForKey:@"yolo_preset_idx"] ?: @"all";++ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];++ [self updateIPAddressDisplay]; // Set initial value+ [defaults addObserver:self+ forKeyPath:@"DeviceIPAddress"+ options:NSKeyValueObservingOptionNew+ context:nil];++ if ([defaults objectForKey:@"stream_via_wifi_enabled"] != nil) {+ self.streamViaWiFiEnabled = [defaults boolForKey:@"stream_via_wifi_enabled"];+ } else {+ self.streamViaWiFiEnabled = YES;+ [defaults setBool:YES forKey:@"stream_via_wifi_enabled"];+ }++ if ([defaults objectForKey:@"send_notif_enabled"] != nil) {+ self.sendNotifEnabled = [defaults boolForKey:@"send_notif_enabled"];+ } else {+ self.sendNotifEnabled = NO;+ [defaults setBool:NO forKey:@"send_notif_enabled"];+ }++ if ([defaults objectForKey:@"receive_notif_enabled"] != nil) {+ self.receiveNotifEnabled = [defaults boolForKey:@"receive_notif_enabled"];+ } else {+ self.receiveNotifEnabled = NO; // Off by default+ [defaults setBool:NO forKey:@"receive_notif_enabled"];+ }++ if ([defaults objectForKey:@"use_own_server_enabled"] != nil) {+ self.useOwnServerEnabled = [defaults boolForKey:@"use_own_server_enabled"];+ } else {+ self.useOwnServerEnabled = NO;+ [defaults setBool:NO forKey:@"use_own_server_enabled"];+ }++ if ([defaults objectForKey:@"threshold"] != nil) {+ self.threshold = [defaults integerForKey:@"threshold"];+ } else {+ self.threshold = 25; // Default value of 25%+ [defaults setInteger:25 forKey:@"threshold"];+ }++ if ([defaults objectForKey:@"live_stream_internet_enabled"] != nil) {+ self.liveStreamInternetEnabled = [defaults boolForKey:@"live_stream_internet_enabled"];+ } else {+ self.liveStreamInternetEnabled = NO;+ [defaults setBool:NO forKey:@"live_stream_internet_enabled"];+ }++ self.deviceName = [defaults stringForKey:@"device_name"] ?: NSLocalizedString(@"default_device_name", @"Default device name");+ [defaults setObject:self.deviceName forKey:@"device_name"];++ self.notificationSchedules = [[defaults arrayForKey:@"notification_schedules"] mutableCopy];+ if (!self.notificationSchedules) {+ self.notificationSchedules = [@[@{+ @"days": @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"],+ @"startHour": @0,+ @"startMinute": @0,+ @"endHour": @23,+ @"endMinute": @59,+ @"enabled": @YES+ }] mutableCopy];+ [defaults setObject:self.notificationSchedules forKey:@"notification_schedules"];+ }++ // Initialize notification server settings+ self.notificationServerAddress = [defaults stringForKey:@"own_notification_server_address"] ?: @"http://192.168.1.1:8080";++ // Initialize inference server settings+ if ([defaults objectForKey:@"useOwnInferenceServerEnabled"] != nil) {+ self.useOwnInferenceServerEnabled = [defaults boolForKey:@"useOwnInferenceServerEnabled"];+ } else {+ self.useOwnInferenceServerEnabled = NO;+ [defaults setBool:NO forKey:@"useOwnInferenceServerEnabled"];+ }+ self.inferenceServerAddress = [defaults stringForKey:@"own_inference_server_address"] ?: @"http://192.168.1.1:6667";+ [defaults synchronize];++ // Create table view+ self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];+ self.tableView.delegate = self;+ self.tableView.dataSource = self;+ self.tableView.backgroundColor = [UIColor systemBackgroundColor];+ self.tableView.translatesAutoresizingMaskIntoConstraints = NO;+ [self.view addSubview:self.tableView];++ [NSLayoutConstraint activateConstraints:@[+ [self.tableView.topAnchor constraintEqualToAnchor:self.view.topAnchor],+ [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],+ [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],+ [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]+ ]];++ // Ensure switch reflects current permission state+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {+ self.receiveNotifEnabled = [defaults boolForKey:@"receive_notif_enabled"];+ } else {+ self.receiveNotifEnabled = NO;+ [defaults setBool:NO forKey:@"receive_notif_enabled"];+ [defaults synchronize];+ }+ [self.tableView reloadData];+ });+ }];+}++- (void)dealloc {+ [[NSNotificationCenter defaultCenter] removeObserver:self];+ [[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"DeviceIPAddress"];+}++- (void)helpButtonTapped {+ NSURL *helpURL = [NSURL URLWithString:@"https://github.com/roryclear/clearcam/?tab=readme-ov-file#clearcam"];+ if ([[UIApplication sharedApplication] canOpenURL:helpURL]) {+ if (@available(iOS 10.0, *)) {+ [[UIApplication sharedApplication] openURL:helpURL options:@{} completionHandler:nil];+ } else {+ [[UIApplication sharedApplication] openURL:helpURL];+ }+ }+}++- (void)updateIPAddressDisplay {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSString *ipAddress = [defaults stringForKey:@"DeviceIPAddress"];+ if (ipAddress && ipAddress.length > 0) {+ self.notificationServerAddress = ipAddress;+ } else {+ self.notificationServerAddress = NSLocalizedString(@"waiting_for_ip", @"Placeholder when IP address is not available");+ }+}++- (void)observeValueForKeyPath:(NSString *)keyPath+ ofObject:(id)object+ change:(NSDictionary *)change+ context:(void *)context {+ if ([keyPath isEqualToString:@"DeviceIPAddress"]) {+ [self updateIPAddressDisplay];+ [self.tableView reloadData];+ }+}++- (void)streamViaWiFiSwitchToggled:(UISwitch *)sender {+ self.streamViaWiFiEnabled = sender.on;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setBool:self.streamViaWiFiEnabled forKey:@"stream_via_wifi_enabled"];+ [defaults synchronize];+}++- (void)liveStreamInternetSwitchToggled:(UISwitch *)sender {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ BOOL isPremium = [defaults boolForKey:@"isSubscribed"];++ if (isPremium) {+ if (sender.on) {+ NSString *password = [self retrievePasswordFromSecretsManager];+ if (!password) {+ [self promptForPasswordWithCompletion:^(BOOL success) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (success) {+ self.liveStreamInternetEnabled = YES;+ [defaults setBool:YES forKey:@"live_stream_internet_enabled"];+ } else {+ self.liveStreamInternetEnabled = NO;+ [defaults setBool:NO forKey:@"live_stream_internet_enabled"];+ sender.on = NO;+ }+ [defaults synchronize];+ [self.tableView reloadData];+ });+ }];+ } else {+ self.liveStreamInternetEnabled = sender.on;+ [defaults setBool:self.liveStreamInternetEnabled forKey:@"live_stream_internet_enabled"];+ [defaults synchronize];+ }+ } else {+ self.liveStreamInternetEnabled = sender.on;+ [defaults setBool:self.liveStreamInternetEnabled forKey:@"live_stream_internet_enabled"];+ [defaults synchronize];+ }+ } else {+ sender.on = NO;+ self.liveStreamInternetEnabled = NO;+ [defaults setBool:NO forKey:@"live_stream_internet_enabled"];+ [defaults synchronize];+ [self showUpgradePopup];+ }+}++- (void)useOwnInferenceServerSwitchToggled:(UISwitch *)sender {+ self.useOwnInferenceServerEnabled = sender.isOn;+ [[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:@"useOwnInferenceServerEnabled"];+ [[NSUserDefaults standardUserDefaults] synchronize];++ if (sender.isOn) {+ [self showInferenceServerAddressInputDialog];+ }++ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];+}++- (void)receiveNotifSwitchToggled:(UISwitch *)sender {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ BOOL hasRequestedPermission = [defaults boolForKey:@"hasRequestedNotificationPermission"];++ self.receiveNotifEnabled = sender.on;+ [defaults setBool:self.receiveNotifEnabled forKey:@"receive_notif_enabled"];+ [defaults synchronize];++ if (sender.on) {+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {+ [FileServer sendDeviceTokenToServer]; // Send token when toggled ON+ } else if (!hasRequestedPermission) {+ [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)+ completionHandler:^(BOOL granted, NSError * _Nullable error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (granted) {+ [[UIApplication sharedApplication] registerForRemoteNotifications];+ [defaults setBool:YES forKey:@"hasRequestedNotificationPermission"];+ [defaults synchronize];++ [FileServer sendDeviceTokenToServer]; // Send token after granting permission+ } else {+ self.receiveNotifEnabled = NO;+ [defaults setBool:NO forKey:@"receive_notif_enabled"];+ [defaults synchronize];+ sender.on = NO;++ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"permission_denied", @"Title for permission denied alert")+ message:NSLocalizedString(@"notification_permission_denied", @"Message when notification permission is denied")+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button") style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ }+ });+ }];+ } else {+ self.receiveNotifEnabled = NO;+ [defaults setBool:NO forKey:@"receive_notif_enabled"];+ [defaults synchronize];+ sender.on = NO;++ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"enable_in_settings", @"Title for enabling notifications in settings")+ message:NSLocalizedString(@"notifications_disabled", @"Message when notifications are disabled")+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button") style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ }+ });+ }];+ } else {+ // Clear any pending notifications when turning off+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center removeAllPendingNotificationRequests];+ [center removeAllDeliveredNotifications];++ // Delete device token from server+ [self deleteDeviceTokenFromServer];+ }+}++- (void)deleteDeviceTokenFromServer {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSString *deviceToken = [defaults stringForKey:@"device_token"];++ if (!deviceToken || deviceToken.length == 0) return;++ // Retrieve session token from Keychain+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (!sessionToken || sessionToken.length == 0) return;+ NSURL *url = [NSURL URLWithString:@"https://rors.ai/delete_device"];+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ request.HTTPMethod = @"DELETE";+ [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];++ NSDictionary *body = @{+ @"device_token": deviceToken,+ @"session_token": sessionToken+ };+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:nil];+ request.HTTPBody = jsonData;++ NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error) return;+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ }];++ [task resume];+}++- (void)subscriptionStatusDidChange:(NSNotification *)notification {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.tableView reloadData];+ });+}++#pragma mark - Orientation Control++- (BOOL)shouldAutorotate {+ return NO;+}++- (UIInterfaceOrientationMask)supportedInterfaceOrientations {+ return UIInterfaceOrientationMaskPortrait;+}++- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {+ return UIInterfaceOrientationPortrait;+}++#pragma mark - UITableView DataSource++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {+ return 6;+}++- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {+ if (section == 0) {+ return NSLocalizedString(@"camera_settings", @"Header for camera settings section");+ } else if (section == 1) {+ return NSLocalizedString(@"live_stream_settings", @"Header for live stream settings section");+ } else if (section == 2) {+ return NSLocalizedString(@"viewer_settings", @"Header for viewer settings section");+ } else if (section == 3) {+ return NSLocalizedString(@"experimental_features", @"Header for advanced settings section");+ } else if (section == 4) {+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ return isSubscribed ? NSLocalizedString(@"subscription", @"Header for subscription section when subscribed") : NSLocalizedString(@"upgrade_to_premium", @"Header for subscription section when not subscribed");+ } else if (section == 5) {+ return nil; // No header for Terms and Privacy section+ }+ return nil;+}++- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {+ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SettingsCell"];+ if (!cell) {+ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"SettingsCell"];+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ }++ // Reset cell state to avoid reuse artifacts+ cell.textLabel.text = nil;+ cell.detailTextLabel.text = nil;+ cell.imageView.image = nil;+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.accessoryView = nil;+ cell.textLabel.textColor = [UIColor labelColor];+ cell.detailTextLabel.textColor = [UIColor secondaryLabelColor];+ cell.textLabel.textAlignment = NSTextAlignmentLeft;+ cell.backgroundColor = [UIColor secondarySystemBackgroundColor];+ cell.userInteractionEnabled = YES;++ for (UIView *subview in cell.contentView.subviews) {+ if ([subview isKindOfClass:[UIButton class]] && [((UIButton *)subview).titleLabel.text isEqualToString:@"Copy"]) {+ [subview removeFromSuperview];+ }+ }++ BOOL isPremium = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];++ if (indexPath.section == 0) { // Camera Settings+ if (indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"stream_via_wifi", @"Label for stream via Wi-Fi setting");+ NSString *ipAddress = [[NSUserDefaults standardUserDefaults] stringForKey:@"DeviceIPAddress"];+ cell.detailTextLabel.text = ipAddress && ipAddress.length > 0 ?+ ipAddress :+ NSLocalizedString(@"waiting_for_ip", @"Placeholder when IP address is not available");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *wifiSwitch = [[UISwitch alloc] init];+ wifiSwitch.on = self.streamViaWiFiEnabled;+ [wifiSwitch addTarget:self action:@selector(streamViaWiFiSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = wifiSwitch;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"resolution", @"Label for resolution setting");+ cell.detailTextLabel.text = self.selectedResolution;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 2) {+ cell.textLabel.text = NSLocalizedString(@"detect_objects", @"Label for detect objects setting");+ cell.detailTextLabel.text = self.selectedPresetKey;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 3) {+ cell.textLabel.text = NSLocalizedString(@"manage_detection_presets", @"Label for manage detection presets setting");+ cell.detailTextLabel.text = nil;+ cell.accessoryType = self.isPresetsSectionExpanded ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator;+ cell.userInteractionEnabled = YES;+ } else if (self.isPresetsSectionExpanded && indexPath.row >= 4 && indexPath.row < 4 + [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys].count + 1) {+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ if (indexPath.row - 4 < presetKeys.count) {+ NSString *presetKey = presetKeys[indexPath.row - 4];+ cell.textLabel.text = presetKey;+ cell.detailTextLabel.text = nil;+ cell.imageView.image = nil;+ cell.userInteractionEnabled = YES;+ } else {+ cell.textLabel.text = nil;+ cell.detailTextLabel.text = nil;+ cell.imageView.image = [UIImage systemImageNamed:@"plus.circle.fill"];+ cell.imageView.tintColor = [UIColor systemGreenColor];+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.userInteractionEnabled = YES;+ }+ } else {+ NSInteger presetOffset = self.isPresetsSectionExpanded ? [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys].count + 1 : 0;+ if (indexPath.row == 4 + presetOffset) {+ cell.textLabel.text = NSLocalizedString(@"detection_certainty_threshold", @"Label for detection certainty threshold setting");+ cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld%%", (long)self.threshold];+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 5 + presetOffset) {+ cell.textLabel.text = NSLocalizedString(@"send_videos_on_detection", @"Label for send videos on detection setting");+ cell.detailTextLabel.text = NSLocalizedString(@"send_videos_description", @"Description for send videos on detection setting");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *sendNotifSwitch = [[UISwitch alloc] init];+ sendNotifSwitch.on = self.sendNotifEnabled;+ [sendNotifSwitch addTarget:self action:@selector(sendNotifSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = sendNotifSwitch;+ BOOL isEnabled = isPremium || self.useOwnServerEnabled;+ sendNotifSwitch.enabled = isEnabled;+ cell.textLabel.textColor = isEnabled ? [UIColor labelColor] : [UIColor grayColor];+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 6 + presetOffset) {+ cell.textLabel.text = NSLocalizedString(@"change_encryption_password", @"Label for change encryption password setting");+ cell.detailTextLabel.text = nil;+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.textLabel.textColor = isPremium ? [UIColor labelColor] : [UIColor grayColor];+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 7 + presetOffset) {+ cell.textLabel.text = NSLocalizedString(@"manage_detection_schedules", @"Label for manage detection schedules setting");+ cell.detailTextLabel.text = NSLocalizedString(@"manage_detection_schedules_description", @"Description for manage detection schedules setting");+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.userInteractionEnabled = YES;+ }+ }+ } else if (indexPath.section == 1) { // Live Stream Settings+ if (indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"live_stream_network", @"Label for live stream over network setting");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *liveStreamSwitch = [[UISwitch alloc] init];+ liveStreamSwitch.on = isPremium ? self.liveStreamInternetEnabled : NO;+ [liveStreamSwitch addTarget:self action:@selector(liveStreamInternetSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = liveStreamSwitch;+ liveStreamSwitch.enabled = isPremium;+ cell.textLabel.textColor = isPremium ? [UIColor labelColor] : [UIColor grayColor];+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"device_name", @"Label for device name setting");+ cell.detailTextLabel.text = self.deviceName;+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ cell.textLabel.textColor = isPremium ? [UIColor labelColor] : [UIColor grayColor];+ cell.userInteractionEnabled = YES;+ }+ } else if (indexPath.section == 2) { // Viewer Settings+ if (indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"receive_notifications", @"Label for receive notifications setting");+ cell.detailTextLabel.text = NSLocalizedString(@"receive_notifications_description", @"Description for receive notifications setting");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *receiveNotifSwitch = [[UISwitch alloc] init];+ receiveNotifSwitch.on = isPremium ? self.receiveNotifEnabled : NO;+ [receiveNotifSwitch addTarget:self action:@selector(receiveNotifSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = receiveNotifSwitch;+ receiveNotifSwitch.enabled = isPremium;+ cell.textLabel.textColor = isPremium ? [UIColor labelColor] : [UIColor grayColor];+ cell.userInteractionEnabled = YES;+ }+ } else if (indexPath.section == 3) { // Advanced Settings+ if (indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"use_own_notification_server", @"Label for use own notification server setting");+ cell.detailTextLabel.text = self.useOwnServerEnabled ?+ (self.notificationServerAddress ?: NSLocalizedString(@"enter_notification_server_address", @"Placeholder for notification server address")) :+ NSLocalizedString(@"use_own_notification_server_description", @"Description for use own notification server setting");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *useOwnNotificationServerSwitch = [[UISwitch alloc] init];+ useOwnNotificationServerSwitch.on = self.useOwnServerEnabled;+ [useOwnNotificationServerSwitch addTarget:self action:@selector(useOwnnotificationServerSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = useOwnNotificationServerSwitch;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"use_own_inference_server", @"Label for use own inference server setting");+ cell.detailTextLabel.text = self.useOwnInferenceServerEnabled ?+ (self.inferenceServerAddress ?: NSLocalizedString(@"enter_inference_server_address", @"Placeholder for inference server address")) :+ NSLocalizedString(@"use_own_inference_server_description", @"Description for use own inference server setting");+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *useOwnInferenceServerSwitch = [[UISwitch alloc] init];+ useOwnInferenceServerSwitch.on = self.useOwnInferenceServerEnabled;+ [useOwnInferenceServerSwitch addTarget:self action:@selector(useOwnInferenceServerSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = useOwnInferenceServerSwitch;+ cell.userInteractionEnabled = YES;+ }+ } else if (indexPath.section == 4) { // Upgrade to Premium / Subscription+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ if (!isSubscribed && indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"upgrade_to_premium", @"Label for upgrade to premium button");+ cell.textLabel.textColor = [UIColor systemBlueColor];+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.accessoryType = UITableViewCellAccessoryNone;+ } else if ((isSubscribed && indexPath.row == 0) || (!isSubscribed && indexPath.row == 1)) {+ cell.textLabel.text = NSLocalizedString(@"restore_purchases", @"Label for restore purchases button");+ cell.textLabel.textColor = [UIColor systemBlueColor];+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.accessoryType = UITableViewCellAccessoryNone;+ } else if (isSubscribed && indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"userid", nil);+ cell.textLabel.textColor = [UIColor labelColor];+ cell.textLabel.textAlignment = NSTextAlignmentLeft;+ if (self.isUserIDVisible) {+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ cell.detailTextLabel.text = sessionToken ?: NSLocalizedString(@"userid", nil);++ // Add copy button+ UIButton *copyButton = [UIButton buttonWithType:UIButtonTypeSystem];+ [copyButton setTitle:@"Copy" forState:UIControlStateNormal];+ [copyButton sizeToFit];+ CGRect buttonFrame = copyButton.frame;+ buttonFrame.origin.x = cell.contentView.frame.size.width - buttonFrame.size.width - 16;+ buttonFrame.origin.y = (cell.contentView.frame.size.height - buttonFrame.size.height) / 2;+ copyButton.frame = buttonFrame;+ copyButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;+ [copyButton addTarget:self action:@selector(copyUserIDToClipboard:) forControlEvents:UIControlEventTouchUpInside];+ [cell.contentView addSubview:copyButton];+ } else {+ cell.detailTextLabel.text = NSLocalizedString(@"tap_for_userid", nil);+ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;+ }+ }+ } else if (indexPath.section == 5) { // Terms and Privacy+ if (indexPath.row == 0) {+ cell.textLabel.text = NSLocalizedString(@"terms_of_use", @"Label for terms of use link");+ cell.textLabel.textColor = [UIColor systemBlueColor];+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"privacy_policy", @"Label for privacy policy link");+ cell.textLabel.textColor = [UIColor systemBlueColor];+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 2) {+ cell.textLabel.text = NSLocalizedString(@"delete_encryption_keys", @"Label for delete encryption keys button");+ cell.textLabel.textColor = [UIColor systemRedColor];+ cell.textLabel.textAlignment = NSTextAlignmentCenter;+ cell.accessoryType = UITableViewCellAccessoryNone;+ cell.userInteractionEnabled = YES;+ }+ }++ return cell;+}++- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {+ if (section == 0) { // Camera Settings+ NSInteger baseRows = 8; // Up to "Manage Detection Schedules"+ if (self.isPresetsSectionExpanded) {+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ baseRows += presetKeys.count + 1; // Preset rows + "Add Preset"+ }+ return baseRows;+ } else if (section == 1) { // Live Stream Settings+ return 2; // Live Stream over the internet and Device name+ } else if (section == 2) { // Viewer Settings+ return 1; // Just Receive Notifications+ } else if (section == 3) { // Advanced Settings+ return 2; // Use Own Notification Server, Use Own Inference Server+ } else if (section == 4) { // Upgrade to Premium / Subscription+ return 2; // 1 row for "Restore Purchases" if subscribed, 2 rows ("Upgrade" + "Restore") if not+ } else if (section == 5) { // Terms and Privacy+ return 3; // Terms of Use, Privacy Policy, Delete Encryption Keys+ }+ return 0;+}++- (void)copyUserIDToClipboard:(UIButton *)sender {+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ if (sessionToken) {+ UIPasteboard.generalPasteboard.string = sessionToken;+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"copied", nil)+ message:NSLocalizedString(@"id_copied", nil)+ preferredStyle:UIAlertControllerStyleAlert];+ [self presentViewController:alert animated:YES completion:^{+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [alert dismissViewControllerAnimated:YES completion:nil];+ });+ }];+ }+}++- (void)showInferenceServerAddressInputDialog {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"enter_inference_server_address_title", @"Title for inference server address input dialog")+ message:NSLocalizedString(@"enter_inference_server_address_message", @"Message for inference server address input dialog")+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"server_address_label", @"Placeholder for server address input");+ textField.text = self.inferenceServerAddress;+ }];++ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *address = alert.textFields.firstObject.text;+ if (address.length > 0) {+ self.inferenceServerAddress = address;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setObject:address forKey:@"own_inference_server_address"];+ [defaults synchronize];+ [self.tableView reloadData];+ }+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];++ [alert addAction:saveAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)showThresholdInputDialog {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"set_threshold_title", @"Title for threshold input dialog")+ message:NSLocalizedString(@"set_threshold_message", @"Message for threshold input dialog")+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"threshold_placeholder", @"Placeholder for threshold input");+ textField.keyboardType = UIKeyboardTypeNumberPad;+ textField.text = [NSString stringWithFormat:@"%ld", (long)self.threshold];+ }];++ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *thresholdText = alert.textFields.firstObject.text;+ NSInteger newThreshold = [thresholdText integerValue];+ if (newThreshold >= 1 && newThreshold <= 100) {+ self.threshold = newThreshold;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setInteger:self.threshold forKey:@"threshold"];+ [defaults synchronize];+ [self.tableView reloadData];+ } else {+ UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"invalid_threshold_title", @"Title for invalid threshold error")+ message:NSLocalizedString(@"invalid_threshold_message", @"Message for invalid threshold error")+ preferredStyle:UIAlertControllerStyleAlert];+ [errorAlert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button") style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:errorAlert animated:YES completion:nil];+ }+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];++ [alert addAction:saveAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)showDeviceNameInputDialog {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"set_device_name_title", @"Title for device name input dialog")+ message:NSLocalizedString(@"set_device_name_message", @"Message for device name input dialog")+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"device_name_placeholder", @"Placeholder for device name input");+ textField.text = self.deviceName;+ }];++ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *name = alert.textFields.firstObject.text;+ if (name.length > 0) {+ self.deviceName = name;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setObject:name forKey:@"device_name"];+ [defaults synchronize];+ [self.tableView reloadData];+ }+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];++ [alert addAction:saveAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)showDeleteEncryptionKeysPrompt {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"delete_encryption_keys_title", @"Title for delete encryption keys confirmation")+ message:NSLocalizedString(@"delete_encryption_keys_message", @"Message for delete encryption keys confirmation")+ preferredStyle:UIAlertControllerStyleAlert];++ UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"delete", @"Delete button")+ style:UIAlertActionStyleDestructive+ handler:^(UIAlertAction * _Nonnull action) {+ // Delete encryption keys+ NSError *error = nil;+ [[SecretManager sharedManager] deleteAllKeysWithError:&error];+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];++ // Turn off "Receive Notifications on This Device" unless "Use Own Server" is on+ if (!self.useOwnServerEnabled) {+ self.sendNotifEnabled = NO;+ [defaults setBool:NO forKey:@"send_notif_enabled"];+ }++ // Turn off "Live Stream over the Internet"+ self.liveStreamInternetEnabled = NO;+ [defaults setBool:NO forKey:@"live_stream_internet_enabled"];++ [defaults synchronize];+ [self.tableView reloadData];+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];++ [alert addAction:deleteAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {+ BOOL isPremium = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];++ if (indexPath.section == 0) { // Camera Settings+ if (indexPath.row == 0) {+ // Stream via Wi-Fi - handled by switch+ } else if (indexPath.row == 1) {+ [self showResolutionPicker];+ } else if (indexPath.row == 2) {+ [self showYoloIndexesPicker];+ } else if (indexPath.row == 3) {+ self.isPresetsSectionExpanded = !self.isPresetsSectionExpanded;+ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];+ } else if (self.isPresetsSectionExpanded && indexPath.row >= 4 && indexPath.row < 4 + [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys].count + 1) {+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ if (indexPath.row - 4 < presetKeys.count) {+ NSString *presetKey = presetKeys[indexPath.row - 4];+ NSArray *selectedIndexes = [[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"][presetKey];+ [self showNumberSelectionForPreset:presetKey selectedIndexes:selectedIndexes];+ } else {+ [self showAddPresetDialog];+ }+ } else {+ NSInteger offset = self.isPresetsSectionExpanded ? [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys].count + 1 : 0;+ if (indexPath.row == 4 + offset) {+ [self showThresholdInputDialog];+ } else if (indexPath.row == 5 + offset) {+ if (!isPremium) {+ [self showUpgradePopup];+ }+ } else if (indexPath.row == 6 + offset) {+ if (isPremium) {+ [self promptForPasswordWithCompletion:^(BOOL success) {+ }];+ } else {+ [self showUpgradePopup];+ }+ } else if (indexPath.row == 7 + offset) {+ ScheduleManagementViewController *scheduleVC = [[ScheduleManagementViewController alloc] init];+ scheduleVC.notificationSchedules = [self.notificationSchedules mutableCopy];+ scheduleVC.completionHandler = ^(NSArray<NSDictionary *> *schedules) {+ self.notificationSchedules = [schedules mutableCopy];+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setObject:self.notificationSchedules forKey:@"notification_schedules"];+ [defaults synchronize];+ [self.tableView reloadData];+ };+ [self.navigationController pushViewController:scheduleVC animated:YES];+ }+ }+ } else if (indexPath.section == 1) { // Live Stream Settings+ if (indexPath.row == 0) {+ if (!isPremium) {+ [self showUpgradePopup];+ } // Switch handles toggle when premium+ } else if (indexPath.row == 1) {+ if (isPremium) {+ [self showDeviceNameInputDialog];+ } else {+ [self showUpgradePopup];+ }+ }+ } else if (indexPath.section == 2) { // Viewer Settings+ if (indexPath.row == 0) {+ if (!isPremium) {+ [self showUpgradePopup];+ } // Switch handles toggle when premium+ }+ } else if (indexPath.section == 3) { // Advanced Settings+ // Rows 0 and 1 (server switches) are handled by their toggles, so do nothing on tap+ } else if (indexPath.section == 4) { // Upgrade to Premium / Subscription+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ if (!isSubscribed && indexPath.row == 0) {+ [self showUpgradePopup];+ } else if ((isSubscribed && indexPath.row == 0) || (!isSubscribed && indexPath.row == 1)) {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"restoring_purchases_title", @"Title for restoring purchases alert")+ message:NSLocalizedString(@"restoring_purchases_message", @"Message for restoring purchases alert")+ preferredStyle:UIAlertControllerStyleAlert];+ [self presentViewController:alert animated:YES completion:nil];++ [[StoreManager sharedInstance] restorePurchases];++ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [self dismissViewControllerAnimated:YES completion:nil];+ });+ } else if (isSubscribed && indexPath.row == 1 && !self.isUserIDVisible) {+ [self authenticateToRevealUserID];+ }+ } else if (indexPath.section == 5) { // Terms and Privacy+ if (indexPath.row == 0) { // Terms of Use+ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.apple.com/legal/internet-services/itunes/dev/stdeula/"] options:@{} completionHandler:nil];+ } else if (indexPath.row == 1) { // Privacy Policy+ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.rors.ai/privacy"] options:@{} completionHandler:nil];+ } else if (indexPath.row == 2) { // Delete Encryption Keys+ [self showDeleteEncryptionKeysPrompt];+ }+ }+ [tableView deselectRowAtIndexPath:indexPath animated:YES];+}++- (void)authenticateToRevealUserID {+ LAContext *context = [[LAContext alloc] init];+ NSError *authError = nil;+ NSString *reason = NSLocalizedString(@"authenticate_to_view_user_id", nil);++ // Check if biometric authentication is available+ if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&authError]) {+ [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication+ localizedReason:reason+ reply:^(BOOL success, NSError *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (success) {+ self.isUserIDVisible = YES;+ [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:4]] withRowAnimation:UITableViewRowAnimationFade];+ }+ });+ }];+ }+}++- (void)showUpgradePopup {+ [[StoreManager sharedInstance] getPremiumProductInfo:^(SKProduct * _Nullable product, NSError * _Nullable error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (!product) {+ NSLog(@"Error fetching product info: %@", error.localizedDescription);+ return;+ }++ // Format price+ NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];+ [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];+ [formatter setLocale:product.priceLocale];+ NSString *localizedPrice = [formatter stringFromNumber:product.price] ?: NSLocalizedString(@"price_unknown", @"Fallback for unknown price");++ // Detect dark mode+ BOOL isDarkMode = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);+ UIColor *cardBackground = isDarkMode ? [UIColor colorWithWhite:0.1 alpha:1.0] : [UIColor colorWithWhite:1.0 alpha:1.0];+ UIColor *textColor = isDarkMode ? UIColor.whiteColor : UIColor.blackColor;++ // Overlay+ UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];+ overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];+ overlay.tag = 999;+ [self.view addSubview:overlay];++ // Card+ UIView *card = [[UIView alloc] init];+ card.translatesAutoresizingMaskIntoConstraints = NO;+ card.backgroundColor = cardBackground;+ card.layer.cornerRadius = 20;+ card.clipsToBounds = YES;+ [overlay addSubview:card];++ // Title+ UILabel *title = [[UILabel alloc] init];+ title.translatesAutoresizingMaskIntoConstraints = NO;+ title.text = NSLocalizedString(@"get_premium_title", @"Title for premium upgrade popup");+ title.textColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0]; // gold+ title.font = [UIFont boldSystemFontOfSize:24];+ title.textAlignment = NSTextAlignmentCenter;++ // Features+ UIStackView *featureStack = [[UIStackView alloc] init];+ featureStack.translatesAutoresizingMaskIntoConstraints = NO;+ featureStack.axis = UILayoutConstraintAxisVertical;+ featureStack.spacing = 8;++ NSArray *features = @[+ NSLocalizedString(@"premium_feature_1", @"Feature 1 description for premium"),+ NSLocalizedString(@"premium_feature_2", @"Feature 2 description for premium"),+ NSLocalizedString(@"premium_feature_3", @"Feature 3 description for premium"),+ NSLocalizedString(@"premium_feature_4", @"Feature 4 description for premium")+ ];++ for (NSString *item in features) {+ UILabel *label = [[UILabel alloc] init];+ label.text = [NSString stringWithFormat:@"• %@", item];+ label.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];+ label.textColor = textColor;+ label.numberOfLines = 0;+ [featureStack addArrangedSubview:label];+ }++ // Upgrade button+ UIButton *upgradeBtn = [UIButton buttonWithType:UIButtonTypeSystem];+ upgradeBtn.translatesAutoresizingMaskIntoConstraints = NO;+ NSString *upgradeTitle = [NSString stringWithFormat:NSLocalizedString(@"upgrade_button", @"Upgrade button text with price"), localizedPrice];+ [upgradeBtn setTitle:upgradeTitle forState:UIControlStateNormal];+ [upgradeBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];+ upgradeBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.84 blue:0 alpha:1.0];+ upgradeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];+ upgradeBtn.layer.cornerRadius = 12;+ [upgradeBtn addTarget:self action:@selector(handleUpgradeTap) forControlEvents:UIControlEventTouchUpInside];++ // Cancel button+ UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];+ cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;+ [cancelBtn setTitle:NSLocalizedString(@"not_now", @"Not now button") forState:UIControlStateNormal];+ [cancelBtn setTitleColor:textColor forState:UIControlStateNormal];+ cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];+ [cancelBtn addTarget:self action:@selector(dismissUpgradePopup) forControlEvents:UIControlEventTouchUpInside];++ // Disclaimer label+ UILabel *disclaimer = [[UILabel alloc] init];+ disclaimer.translatesAutoresizingMaskIntoConstraints = NO;+ disclaimer.text = NSLocalizedString(@"premium_disclaimer", @"Disclaimer for premium subscription limits");+ disclaimer.font = [UIFont systemFontOfSize:13];+ disclaimer.textColor = [textColor colorWithAlphaComponent:0.6];+ disclaimer.numberOfLines = 0;+ disclaimer.textAlignment = NSTextAlignmentCenter;++ // Add all to card+ [card addSubview:title];+ [card addSubview:featureStack];+ [card addSubview:upgradeBtn];+ [card addSubview:cancelBtn];+ [card addSubview:disclaimer];++ // Constraints+ [NSLayoutConstraint activateConstraints:@[+ [card.centerXAnchor constraintEqualToAnchor:overlay.centerXAnchor],+ [card.centerYAnchor constraintEqualToAnchor:overlay.centerYAnchor],+ [card.widthAnchor constraintEqualToConstant:320],++ [title.topAnchor constraintEqualToAnchor:card.topAnchor constant:24],+ [title.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],+ [title.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],++ [featureStack.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:20],+ [featureStack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],+ [featureStack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],++ [upgradeBtn.topAnchor constraintEqualToAnchor:featureStack.bottomAnchor constant:24],+ [upgradeBtn.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],+ [upgradeBtn.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],+ [upgradeBtn.heightAnchor constraintEqualToConstant:48],++ [cancelBtn.topAnchor constraintEqualToAnchor:upgradeBtn.bottomAnchor constant:16],+ [cancelBtn.centerXAnchor constraintEqualToAnchor:card.centerXAnchor],++ [disclaimer.topAnchor constraintEqualToAnchor:cancelBtn.bottomAnchor constant:14],+ [disclaimer.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:20],+ [disclaimer.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-20],+ [disclaimer.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-20]+ ]];+ });+ }];+}++- (void)handleUpgradeTap {+ // Create and show a loading spinner+ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];+ spinner.translatesAutoresizingMaskIntoConstraints = NO;+ spinner.color = UIColor.whiteColor;+ UIView *overlay = [self.view viewWithTag:999];+ [overlay addSubview:spinner];++ // Center the spinner in the overlay+ [NSLayoutConstraint activateConstraints:@[+ [spinner.centerXAnchor constraintEqualToAnchor:overlay.centerXAnchor],+ [spinner.centerYAnchor constraintEqualToAnchor:overlay.centerYAnchor]+ ]];++ [spinner startAnimating];++ // Disable user interaction on the overlay to prevent multiple taps+ overlay.userInteractionEnabled = NO;++ // Fetch and initiate the purchase+ [[StoreManager sharedInstance] fetchAndPurchaseProductWithCompletion:^(BOOL success, NSError * _Nullable error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ // Stop the spinner and re-enable interaction+ [spinner stopAnimating];+ [spinner removeFromSuperview];+ overlay.userInteractionEnabled = YES;++ // Dismiss the upgrade popup+ [self dismissUpgradePopup];++ if (!success && error) {+ // Show error alert if purchase failed+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"purchase_failed", @"Title for purchase failed alert")+ message:error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button") style:UIAlertActionStyleDefault handler:nil]];+ [self presentViewController:alert animated:YES completion:nil];+ }++ // Reload table to reflect subscription status+ [self.tableView reloadData];+ });+ }];+}++- (void)dismissUpgradePopup {+ UIView *overlay = [self.view viewWithTag:999];+ [overlay removeFromSuperview];+}++- (void)useOwnnotificationServerSwitchToggled:(UISwitch *)sender {+ self.useOwnServerEnabled = sender.on;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setBool:self.useOwnServerEnabled forKey:@"use_own_server_enabled"];+ [defaults synchronize];++ // Check subscription status and password+ BOOL isPremium = [defaults boolForKey:@"isSubscribed"];+ NSString *password = [self retrievePasswordFromSecretsManager];++ if (!self.useOwnServerEnabled && (!isPremium || !password)) {+ self.sendNotifEnabled = NO;+ [defaults setBool:NO forKey:@"send_notif_enabled"];+ [defaults synchronize];+ }++ if (sender.on) {+ [self shownotificationServerAddressInputDialog];+ }++ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];+}++- (void)shownotificationServerAddressInputDialog {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"enter_notification_server_address_title", @"Title for notification server address input dialog")+ message:NSLocalizedString(@"enter_notification_server_address_message", @"Message for notification server address input dialog")+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"server_address_label", @"Placeholder for server address input");+ textField.text = self.notificationServerAddress;+ }];++ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *address = alert.textFields.firstObject.text;+ if (address.length > 0) {+ self.notificationServerAddress = address;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setObject:address forKey:@"own_notification_server_address"];+ [defaults synchronize];+ [self.tableView reloadData];+ }+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];++ [alert addAction:saveAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)testnotificationServer {+ [[notification sharedInstance] sendNotification];+ UIAlertController *resultAlert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"test_notification_sent_title", @"Title for test notification sent alert")+ message:NSLocalizedString(@"test_notification_sent_message", @"Message for test notification sent alert")+ preferredStyle:UIAlertControllerStyleAlert];+ UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button")+ style:UIAlertActionStyleDefault+ handler:nil];+ [resultAlert addAction:okAction];+ [self presentViewController:resultAlert animated:YES completion:nil];+}++- (void)sendNotifSwitchToggled:(UISwitch *)sender {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ BOOL isPremium = [defaults boolForKey:@"isSubscribed"];++ if (isPremium || self.useOwnServerEnabled) {+ if (sender.on && !self.useOwnServerEnabled) {+ NSString *password = [self retrievePasswordFromSecretsManager];+ if (!password) {+ [self promptForPasswordWithCompletion:^(BOOL success) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (success) {+ self.sendNotifEnabled = YES;+ [defaults setBool:YES forKey:@"send_notif_enabled"];+ } else {+ self.sendNotifEnabled = NO;+ [defaults setBool:NO forKey:@"send_notif_enabled"];+ sender.on = NO;+ }+ [defaults synchronize];+ [self.tableView reloadData];+ });+ }];+ } else {+ self.sendNotifEnabled = sender.on;+ [defaults setBool:self.sendNotifEnabled forKey:@"send_notif_enabled"];+ [defaults synchronize];+ }+ } else {+ self.sendNotifEnabled = sender.on;+ [defaults setBool:self.sendNotifEnabled forKey:@"send_notif_enabled"];+ [defaults synchronize];+ }+ } else {+ sender.on = NO;+ self.sendNotifEnabled = NO;+ [defaults setBool:NO forKey:@"send_notif_enabled"];+ [defaults synchronize];+ [self showUpgradePopup];+ }+}++- (void)promptForPasswordWithCompletion:(void (^)(BOOL success))completion {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"set_password_title", @"Title for password input dialog")+ message:NSLocalizedString(@"set_password_message", @"Message for password input dialog")+ preferredStyle:UIAlertControllerStyleAlert];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"password_placeholder", @"Placeholder for password input");+ textField.secureTextEntry = YES;+ }];++ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"confirm_password_placeholder", @"Placeholder for confirm password input");+ textField.secureTextEntry = YES;+ }];++ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *password = alert.textFields[0].text;+ NSString *confirmPassword = alert.textFields[1].text;++ if ([password isEqualToString:confirmPassword] && password.length > 0) {+ [self savePasswordToSecretsManager:password];+ completion(YES);+ } else {+ [self showInvalidPasswordAlert];+ completion(NO);+ }+ }];++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:^(UIAlertAction * _Nonnull action) {+ completion(NO);+ }];++ [alert addAction:saveAction];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++- (void)savePasswordToSecretsManager:(NSString *)password {+ if (!password) return;++ NSError *error = nil;+ [[SecretManager sharedManager] saveEncryptionKey:password error:&error];+}++- (NSString *)retrievePasswordFromSecretsManager {+ NSString *storedKey = [[SecretManager sharedManager] getEncryptionKey];+ if (storedKey) {+ return storedKey;+ }+ return nil;+}++- (void)showInvalidPasswordAlert {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"invalid_password_title", @"Title for invalid password alert")+ message:NSLocalizedString(@"invalid_password_message", @"Message for invalid password alert")+ preferredStyle:UIAlertControllerStyleAlert];++ UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"ok", @"OK button")+ style:UIAlertActionStyleDefault+ handler:nil];++ [alert addAction:okAction];+ [self presentViewController:alert animated:YES completion:nil];+}++#pragma mark - UITableView Delegate++- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {+ if (indexPath.section == 0 && self.isPresetsSectionExpanded) { // Only in Camera Settings+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ if (indexPath.row >= 4 && indexPath.row < 4 + presetKeys.count) {+ NSString *presetKey = presetKeys[indexPath.row - 4];+ if (![presetKey isEqualToString:@"all"]) {+ return UITableViewCellEditingStyleDelete;+ }+ }+ }+ return UITableViewCellEditingStyleNone;+}++- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {+ if (editingStyle == UITableViewCellEditingStyleDelete && indexPath.section == 0 && self.isPresetsSectionExpanded) {+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ if (indexPath.row >= 4 && indexPath.row < 4 + presetKeys.count) {+ NSString *presetKey = presetKeys[indexPath.row - 4];++ if ([presetKey isEqualToString:@"all"]) return;++ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSMutableDictionary *yoloPresets = [[defaults objectForKey:@"yolo_presets"] mutableCopy];+ [yoloPresets removeObjectForKey:presetKey];+ [defaults setObject:yoloPresets forKey:@"yolo_presets"];++ if ([self.selectedPresetKey isEqualToString:presetKey]) {+ self.selectedPresetKey = @"all";+ [defaults setObject:@"all" forKey:@"yolo_preset_idx"];+ }++ [defaults synchronize];++ [tableView beginUpdates];+ [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];+ [tableView endUpdates];++ [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];+ }+ }+}++#pragma mark - Resolution Picker++- (void)showResolutionPicker {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"select_resolution_title", @"Title for resolution picker")+ message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];++ NSArray *resolutions = @[@"720p", @"1080p"];++ for (NSString *resolution in resolutions) {+ UIAlertAction *action = [UIAlertAction actionWithTitle:resolution+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ self.selectedResolution = resolution;+ SettingsManager *settingsManager = [SettingsManager sharedManager];+ if ([resolution isEqualToString:@"720p"]) {+ [settingsManager updateResolutionWithWidth:@"1280" height:@"720" textSize:@"2" preset:@"AVCaptureSessionPreset1280x720"];+ } else if ([resolution isEqualToString:@"1080p"]) {+ [settingsManager updateResolutionWithWidth:@"1920" height:@"1080" textSize:@"3" preset:@"AVCaptureSessionPreset1920x1080"];+ }+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.tableView reloadData];+ });+ }];+ [alert addAction:action];+ }++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];+ [alert addAction:cancelAction];++ dispatch_async(dispatch_get_main_queue(), ^{+ [self presentViewController:alert animated:YES completion:nil];+ });+}++#pragma mark - YOLO Indexes Picker++- (void)showYoloIndexesPicker {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"select_objects_preset_title", @"Title for YOLO preset picker")+ message:nil+ preferredStyle:UIAlertControllerStyleActionSheet];+ SettingsManager *settingsManager = [SettingsManager sharedManager];+ NSArray *presetKeys = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"] allKeys];+ for (NSString *presetKey in presetKeys) {+ UIAlertAction *action = [UIAlertAction actionWithTitle:presetKey+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ self.selectedPresetKey = presetKey;+ [settingsManager updateYoloIndexesKey:presetKey];+ [self.tableView reloadData];+ }];+ [alert addAction:action];+ }++ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"Cancel button")+ style:UIAlertActionStyleCancel+ handler:nil];+ [alert addAction:cancelAction];++ [self presentViewController:alert animated:YES completion:nil];+}++#pragma mark - Preset Management++- (void)showAddPresetDialog {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"add_preset_title", @"Title for add preset dialog")+ message:NSLocalizedString(@"add_preset_message", @"Message for add preset name input")+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {+ textField.placeholder = NSLocalizedString(@"preset_name_placeholder", @"Placeholder for preset name input");+ }];+ UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"save", @"Save button")+ style:UIAlertActionStyleDefault+ handler:^(UIAlertAction * _Nonnull action) {+ NSString *presetName = alert.textFields.firstObject.text;+ if (presetName.length > 0) {+ [self showNumberSelectionForPreset:presetName selectedIndexes:@[]];+ }+ }];+ [alert addAction:saveAction];+ [self presentViewController:alert animated:YES completion:nil];+}++- (void)showNumberSelectionForPreset:(NSString *)presetKey selectedIndexes:(NSArray<NSNumber *> *)selectedIndexes {+ NumberSelectionViewController *numberSelectionVC = [[NumberSelectionViewController alloc] init];+ numberSelectionVC.presetKey = presetKey;+ numberSelectionVC.selectedIndexes = [selectedIndexes mutableCopy];+ numberSelectionVC.completionHandler = ^(NSArray<NSNumber *> *selectedIndexes) {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSMutableDictionary *yoloPresets = [[defaults objectForKey:@"yolo_presets"] mutableCopy];++ if (!yoloPresets) {+ yoloPresets = [NSMutableDictionary dictionary];+ }+ yoloPresets[presetKey] = selectedIndexes;+ [defaults setObject:yoloPresets forKey:@"yolo_presets"];+ self.selectedPresetKey = presetKey;+ [defaults setObject:presetKey forKey:@"yolo_preset_idx"];+ [defaults synchronize];+ [self.tableView reloadData];+ };+ [self.navigationController pushViewController:numberSelectionVC animated:YES];+}++@enddiff --git a/ios/clearcam/StoreManager.h b/ios/clearcam/StoreManager.hnew file mode 100644index 0000000..e49e52b--- /dev/null+++ b/ios/clearcam/StoreManager.h@@ -0,0 +1,22 @@+#import <StoreKit/StoreKit.h>++NS_ASSUME_NONNULL_BEGIN++// Define the notification name+extern NSString *const StoreManagerSubscriptionStatusDidChangeNotification;++@interface StoreManager : NSObject <SKProductsRequestDelegate, SKPaymentTransactionObserver>+@property (nonatomic, assign) NSTimeInterval last_check_time;+++ (instancetype)sharedInstance;++- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion;+- (void)verifySubscriptionWithCompletion:(void (^)(BOOL isActive, NSDate * _Nullable expiryDate))completion;+- (void)verifySubscriptionWithCompletionIfSubbed:(void (^)(BOOL isActive, NSDate * _Nullable expiryDate))completion;+- (NSString *)retrieveSessionTokenFromKeychain;+- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion;+- (void)restorePurchases;++@end++NS_ASSUME_NONNULL_ENDdiff --git a/ios/clearcam/StoreManager.m b/ios/clearcam/StoreManager.mnew file mode 100644index 0000000..8ed7e75--- /dev/null+++ b/ios/clearcam/StoreManager.m@@ -0,0 +1,365 @@+#import "StoreManager.h"+#import "FileServer.h"+#import <StoreKit/StoreKit.h>++// Define the notification name+NSString *const StoreManagerSubscriptionStatusDidChangeNotification = @"StoreManagerSubscriptionStatusDidChangeNotification";++@interface StoreManager ()+@property (nonatomic, strong) SKProductsRequest *productsRequest;+@property (nonatomic, strong) SKProduct *premiumProduct;+@property (nonatomic, strong) void (^productInfoCompletionHandler)(SKProduct * _Nullable product, NSError * _Nullable error); // Store completion handler for fetching info+@property (nonatomic, copy) void (^purchaseCompletionHandler)(BOOL success, NSError * _Nullable error);+// Implement SKPaymentTransactionObserver method to handle transaction updates+- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion;+@end++@implementation StoreManager++- (void)restorePurchases {+ [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];+}+++ (StoreManager *)sharedInstance {+ static StoreManager *sharedInstance = nil;+ static dispatch_once_t onceToken;+ dispatch_once(&onceToken, ^{+ sharedInstance = [[StoreManager alloc] init];+ [[SKPaymentQueue defaultQueue] addTransactionObserver:sharedInstance];+ });+ return sharedInstance;+}++- (instancetype)init {+ self = [super init];+ if (self) {+ [[SKPaymentQueue defaultQueue] addTransactionObserver:self];+ }+ return self;+}++- (void)fetchAndPurchaseProductWithCompletion:(void (^)(BOOL success, NSError * _Nullable error))completion {+ [self getPremiumProductInfo:^(SKProduct * _Nullable product, NSError * _Nullable error) {+ if (!product) {+ if (completion) {+ completion(NO, error ?: [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Failed to fetch product information"}]);+ }+ return;+ }++ // Initiate the purchase+ SKPayment *payment = [SKPayment paymentWithProduct:product];+ [[SKPaymentQueue defaultQueue] addPayment:payment];++ // Store the completion handler to call it when the transaction finishes+ self.purchaseCompletionHandler = completion;+ }];+}++- (void)getPremiumProductInfo:(void (^)(SKProduct * _Nullable product, NSError * _Nullable error))completion {+ if (self.premiumProduct) {+ if (completion) {+ completion(self.premiumProduct, nil);+ }+ return;+ }++ // Store the completion handler+ self.productInfoCompletionHandler = completion;++ // Fetch product info from App Store+ NSSet *productIdentifiers = [NSSet setWithObject:@"monthly.premium"]; // Your product ID+ self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];+ self.productsRequest.delegate = self; // Delegate methods will handle the response+ [self.productsRequest start];+}++#pragma mark - SKProductsRequestDelegate++- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {+ NSLog(@"Received product response.");+ if (response.products.count > 0) {+ self.premiumProduct = response.products.firstObject;+ if (self.productInfoCompletionHandler) {+ dispatch_async(dispatch_get_main_queue(), ^{+ self.productInfoCompletionHandler(self.premiumProduct, nil);+ self.productInfoCompletionHandler = nil;+ });+ }+ } else {+ NSError *error = [NSError errorWithDomain:@"StoreManagerError" code:101 userInfo:@{NSLocalizedDescriptionKey: @"No products found."}];+ if (self.productInfoCompletionHandler) {+ dispatch_async(dispatch_get_main_queue(), ^{+ self.productInfoCompletionHandler(nil, error);+ self.productInfoCompletionHandler = nil;+ });+ }+ }+ self.productsRequest.delegate = nil;+ self.productsRequest = nil;+}++- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {+ if (self.productInfoCompletionHandler) {+ dispatch_async(dispatch_get_main_queue(), ^{+ self.productInfoCompletionHandler(nil, error);+ self.productInfoCompletionHandler = nil; // Clear the handler+ });+ }+ self.productsRequest.delegate = nil;+ self.productsRequest = nil;+}++#pragma mark - Purchase Product++- (void)purchaseProduct:(SKProduct *)product {+ if ([SKPaymentQueue canMakePayments] && product) {+ SKPayment *payment = [SKPayment paymentWithProduct:product];+ [[SKPaymentQueue defaultQueue] addPayment:payment];+ }+}++#pragma mark - SKPaymentTransactionObserver++- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {+ for (SKPaymentTransaction *transaction in transactions) {+ switch (transaction.transactionState) {+ case SKPaymentTransactionStatePurchased: {+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];+ [self verifySubscriptionWithCompletion:^(BOOL isActive, NSDate *expiryDate) {+ if (isActive) {+ [[NSNotificationCenter defaultCenter] postNotificationName:StoreManagerSubscriptionStatusDidChangeNotification object:nil];+ if (self.purchaseCompletionHandler) {+ self.purchaseCompletionHandler(YES, nil);+ self.purchaseCompletionHandler = nil;+ }+ } else if (self.purchaseCompletionHandler) {+ self.purchaseCompletionHandler(NO, [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Subscription verification failed"}]);+ self.purchaseCompletionHandler = nil;+ }+ }];+ break;+ }+ case SKPaymentTransactionStateFailed: {+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];+ if (self.purchaseCompletionHandler) {+ self.purchaseCompletionHandler(NO, transaction.error);+ self.purchaseCompletionHandler = nil;+ }+ if (transaction.error.code != SKErrorPaymentCancelled) {+ dispatch_async(dispatch_get_main_queue(), ^{+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Purchase Failed"+ message:transaction.error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;+ while (topController.presentedViewController) {+ topController = topController.presentedViewController;+ }+ [topController presentViewController:alert animated:YES completion:nil];+ });+ }+ break;+ }+ case SKPaymentTransactionStateRestored: {+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];+ [self verifySubscriptionWithCompletion:^(BOOL isActive, NSDate *expiryDate) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (isActive) {+ [[NSNotificationCenter defaultCenter] postNotificationName:StoreManagerSubscriptionStatusDidChangeNotification object:nil];+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Purchases Restored"+ message:@"Your previous purchases have been successfully restored."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;+ while (topController.presentedViewController) {+ topController = topController.presentedViewController;+ }+ [topController presentViewController:alert animated:YES completion:nil];+ if (self.purchaseCompletionHandler) {+ self.purchaseCompletionHandler(YES, nil);+ self.purchaseCompletionHandler = nil;+ }+ } else {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"No Purchases Found"+ message:@"No previous purchases were found to restore."+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;+ while (topController.presentedViewController) {+ topController = topController.presentedViewController;+ }+ [topController presentViewController:alert animated:YES completion:nil];+ if (self.purchaseCompletionHandler) {+ self.purchaseCompletionHandler(NO, [NSError errorWithDomain:@"StoreManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"No valid subscriptions found"}]);+ self.purchaseCompletionHandler = nil;+ }+ }+ });+ }];+ break;+ }+ case SKPaymentTransactionStatePurchasing:+ // No action needed while purchasing+ break;+ default:+ break;+ }+ }+}++- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {+ NSLog(@"Restore completed transactions finished.");+}++- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {+ dispatch_async(dispatch_get_main_queue(), ^{+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Restore Failed"+ message:error.localizedDescription+ preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];+ UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;+ while (topController.presentedViewController) {+ topController = topController.presentedViewController;+ }+ [topController presentViewController:alert animated:YES completion:nil];+ });+}++- (void)verifySubscriptionWithCompletionIfSubbed:(void (^)(BOOL isActive, NSDate *expiryDate))completion {+ NSDate *expiry = [[NSUserDefaults standardUserDefaults] objectForKey:@"expiry"];+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ NSTimeInterval lastCheck = [StoreManager sharedInstance].last_check_time;+ BOOL sessionExpired = !expiry || [expiry compare:[NSDate date]] != NSOrderedDescending;+ BOOL sessionTokenMissing = ![[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];+ BOOL shouldCheckRemote = sessionExpired || sessionTokenMissing || ([[NSDate date] timeIntervalSince1970] - lastCheck > 120.0);++ if (shouldCheckRemote) {+ [self verifySubscriptionWithCompletion:^(BOOL isActive, NSDate *expiryDate) {+ if (completion) completion(isActive, expiryDate);+ }];+ } else {+ if (completion) completion(isSubscribed, expiry);+ }+}++- (void)verifySubscriptionWithCompletion:(void (^)(BOOL isActive, NSDate *expiryDate))completion {+ self.last_check_time = [[NSDate date] timeIntervalSince1970];+ static BOOL isRequestInProgress = NO;++ if (isRequestInProgress) return;++ isRequestInProgress = YES; // Mark request as in progress++ NSString *storedReceipt = [[NSUserDefaults standardUserDefaults] stringForKey:@"subscriptionReceipt"];++ if (!storedReceipt) {+ NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];+ NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];++ if (!receiptData) {+ [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isSubscribed"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ isRequestInProgress = NO; // Reset flag+ completion(NO, nil);+ return;+ }++ storedReceipt = [receiptData base64EncodedStringWithOptions:0];++ [[NSUserDefaults standardUserDefaults] setObject:storedReceipt forKey:@"subscriptionReceipt"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ }++ NSDictionary *requestDict = @{@"receipt": storedReceipt};+ NSError *error;+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestDict options:0 error:&error];++ if (error) {+ [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isSubscribed"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ isRequestInProgress = NO; // Reset flag+ completion(NO, nil);+ return;+ }++ [FileServer performPostRequestWithURL:@"https://www.rors.ai/verify_receipt"+ method:@"POST"+ contentType:@"application/json"+ body:jsonData+ completionHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {+ isRequestInProgress = NO;+ if (error) {+ [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isSubscribed"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ completion(NO, nil);+ return;+ }+ NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (!jsonResponse || ![jsonResponse isKindOfClass:[NSDictionary class]]) {+ [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isSubscribed"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ completion(NO, nil);+ return;+ }+ BOOL isSubscribed = [jsonResponse[@"valid"] boolValue];+ if (isSubscribed) {+ NSString *sessionToken = jsonResponse[@"session_token"];+ if (sessionToken && [sessionToken isKindOfClass:[NSString class]]) {+ [self storeSessionTokenInKeychain:sessionToken];+ [[NSUserDefaults standardUserDefaults] setObject:[NSDate dateWithTimeIntervalSinceNow:45 * 60] forKey:@"expiry"];+ }+ [[NSNotificationCenter defaultCenter] postNotificationName:StoreManagerSubscriptionStatusDidChangeNotification object:nil];+ } else {+ [self clearSessionTokenFromKeychain];+ }+ [[NSUserDefaults standardUserDefaults] setBool:isSubscribed forKey:@"isSubscribed"];+ [[NSUserDefaults standardUserDefaults] synchronize];+ completion(isSubscribed, nil);+ }];+}+++- (void)storeSessionTokenInKeychain:(NSString *)sessionToken {+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: @"com.clearcam.session",+ (__bridge id)kSecAttrAccount: @"sessionToken",+ (__bridge id)kSecValueData: [sessionToken dataUsingEncoding:NSUTF8StringEncoding]+ };++ // Delete any existing token first+ SecItemDelete((__bridge CFDictionaryRef)query);+ // Add the new token+ OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);+}++- (void)clearSessionTokenFromKeychain {+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: @"com.clearcam.session",+ (__bridge id)kSecAttrAccount: @"sessionToken"+ };+ SecItemDelete((__bridge CFDictionaryRef)query);+}++// Optional: Retrieve the session token if needed later+- (NSString *)retrieveSessionTokenFromKeychain {+ NSDictionary *query = @{+ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,+ (__bridge id)kSecAttrService: @"com.clearcam.session",+ (__bridge id)kSecAttrAccount: @"sessionToken",+ (__bridge id)kSecReturnData: @YES,+ (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne+ };++ CFTypeRef dataRef = NULL;+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataRef);+ if (status == errSecSuccess) {+ NSData *data = (__bridge_transfer NSData *)dataRef;+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];+ }+ return nil;+}++@enddiff --git a/ios/clearcam/ViewController.h b/ios/clearcam/ViewController.hnew file mode 100644index 0000000..c3a96ab--- /dev/null+++ b/ios/clearcam/ViewController.h@@ -0,0 +1,8 @@+#import <UIKit/UIKit.h>+#import <AVFoundation/AVFoundation.h>++@interface ViewController : UIViewController <AVCaptureVideoDataOutputSampleBufferDelegate>++@end++diff --git a/ios/clearcam/ViewController.m b/ios/clearcam/ViewController.mnew file mode 100644index 0000000..4c8dae5--- /dev/null+++ b/ios/clearcam/ViewController.m@@ -0,0 +1,1361 @@+#import "ViewController.h"+#import <AVFoundation/AVFoundation.h>+#import <Metal/Metal.h>+#import "Yolo.h"+#import "FileServer.h"+#import "SettingsManager.h"+#import "StoreManager.h"+#import "SecretManager.h"+#import "SceneState.h"+#import <Security/Security.h>+#import <CommonCrypto/CommonCryptor.h>++@interface ViewController ()++@property (nonatomic, strong) AVCaptureSession *captureSession;+@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;+@property (nonatomic, strong) UILabel *fpsLabel;+@property (nonatomic, strong) UIButton *recordButton;+@property (nonatomic, assign) CFTimeInterval lastFrameTime;+@property (nonatomic, assign) NSUInteger frameCount;+@property (nonatomic, strong) Yolo *yolo;+@property (nonatomic, strong) CIContext *ciContext;++@property (atomic, assign) BOOL isProcessing;+@property (nonatomic, assign) BOOL isProcessingCoreData;+@property (nonatomic, assign) BOOL recordPressed;+@property (nonatomic, assign) BOOL isRecording;+@property (nonatomic, assign) BOOL isStreaming; //over the internet+@property (nonatomic, assign) NSTimeInterval last_check_time;+@property (nonatomic, assign) CMTime startTime;+@property (nonatomic, assign) CMTime currentTime;+@property (nonatomic, strong) AVAssetWriter *assetWriter;+@property (nonatomic, strong) AVAssetWriterInput *videoWriterInput;+@property (nonatomic, strong) AVAssetWriterInputPixelBufferAdaptor *adaptor;+@property (nonatomic, strong) FileServer *fileServer;+@property (nonatomic, assign) int seg_number;+@property (nonatomic, assign) NSDate *current_file_timestamp;+@property (nonatomic, strong) NSMutableDictionary *digits;+@property (nonatomic, strong) NSMutableArray *current_segment_squares;+@property (nonatomic, strong) NSLock *segmentLock;+@property (nonatomic, strong) NSManagedObjectContext *backgroundContext;+@property (nonatomic, strong) NSString *dayFolderName;+@property (nonatomic, strong) NSString *streamLink;+@property (nonatomic, strong) dispatch_queue_t segmentQueue;+@property (nonatomic, strong) dispatch_queue_t finishRecordingQueue;+@property (nonatomic, strong) SceneState *scene;++#define MIN_FREE_SPACE_MB 500 //threshold to start deleting++@end++@implementation ViewController++NSMutableDictionary *classColorMap;++- (void)viewDidLoad {+ NSLog(@"NSCameraUsageDescription: %@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSCameraUsageDescription"]);+ [super viewDidLoad];+ NSDate *expiry = [[NSUserDefaults standardUserDefaults] objectForKey:@"expiry"];+ BOOL isSubscribed = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSubscribed"];+ BOOL sessionExpiredOrNow = !expiry || [expiry compare:[NSDate date]] != NSOrderedDescending;+ if(isSubscribed && sessionExpiredOrNow) {+ if (sessionExpiredOrNow) {+ [[StoreManager sharedInstance] verifySubscriptionWithCompletion:^(BOOL isActive, NSDate *expiryDate) {+ }];+ }+ }+ self.streamLink = @"";+ self.recordPressed = NO;+ self.last_check_time = [[NSDate date] timeIntervalSince1970];+ self.scene = [[SceneState alloc] init];+ self.segmentQueue = dispatch_queue_create("com.clearcam.segmentQueue", DISPATCH_QUEUE_SERIAL);+ self.finishRecordingQueue = dispatch_queue_create("com.clearcam.finishRecordingQueue", DISPATCH_QUEUE_SERIAL);++ self.current_segment_squares = [[NSMutableArray alloc] init];+ self.digits = [NSMutableDictionary dictionary];+ self.digits[@"0"] = @[@[ @0, @0, @3, @1], @[ @0, @1, @1 , @3], @[ @2, @1, @1 , @3], @[ @0, @4, @3 , @1]];+ self.digits[@"1"] = @[@[ @2, @0, @1, @5 ]];+ self.digits[@"2"] = @[@[ @0, @0, @3, @1 ], @[ @2, @1, @1, @1 ], @[ @0, @2, @3, @1 ], @[ @0, @3, @1, @1 ], @[ @0, @4, @3, @1 ]];+ self.digits[@"3"] = @[@[ @0, @0, @3, @1 ], @[ @2, @1, @1, @3 ], @[ @0, @2, @3, @1 ], @[ @0, @4, @3, @1 ]];+ self.digits[@"4"] = @[@[ @2, @0, @1, @5 ], @[ @0, @0, @1, @2 ], @[ @0, @2, @3, @1 ]];+ self.digits[@"5"] = @[@[ @0, @0, @3, @1 ], @[ @0, @1, @1, @1 ], @[ @0, @2, @3, @1 ], @[ @2, @3, @1, @1 ], @[ @0, @4, @3, @1 ]];+ self.digits[@"6"] = @[@[ @0, @0, @3, @1 ],@[ @0, @0, @1, @5 ], @[ @1, @2, @2, @1 ], @[ @1, @4, @2, @1 ], @[ @2, @3, @1, @1 ]];+ self.digits[@"7"] = @[@[ @0, @0, @3, @1 ], @[ @2, @1, @1, @4 ]];+ self.digits[@"8"] = @[@[ @0, @0, @1, @5 ], @[ @2, @0, @1, @5 ], @[ @1, @0, @1, @1 ], @[ @1, @2, @1, @1 ], @[ @1, @4, @1, @1 ]];+ self.digits[@"9"] = @[@[ @2, @0, @1, @5 ], @[ @1, @0, @1, @1 ], @[ @0, @0, @1, @2 ], @[ @0, @2, @3, @1 ],@[ @0, @4, @3, @1 ]];+ self.digits[@"-"] = @[@[ @0, @2, @3, @1 ]];+ self.digits[@":"] = @[@[ @1, @1, @1, @1 ], @[ @1, @3, @1, @1 ]];+ self.segmentLock = [[NSLock alloc] init];+ self.isStreaming = NO;++ self.ciContext = [CIContext context];+ self.yolo = [[Yolo alloc] init];+ self.seg_number = 0;+ self.fileServer = [FileServer sharedInstance];+ self.backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];+ self.backgroundContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy;+ self.backgroundContext.parentContext = self.fileServer.context;++ [[NSNotificationCenter defaultCenter] addObserver:self+ selector:@selector(handleDeviceOrientationChange)+ name:UIDeviceOrientationDidChangeNotification+ object:nil];++ [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];++ SettingsManager *settings = [SettingsManager sharedManager];+ [settings addObserver:self forKeyPath:@"width" options:NSKeyValueObservingOptionNew context:nil];+ [settings addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew context:nil];+ [settings addObserver:self forKeyPath:@"text_size" options:NSKeyValueObservingOptionNew context:nil];+ [settings addObserver:self forKeyPath:@"preset" options:NSKeyValueObservingOptionNew context:nil];++ [self setupCameraWithWidth:settings.width height:settings.height];+ [self.captureSession startRunning];+ [self startNewRecording];+ [self setupUI];+ UIDeviceOrientation initialOrientation = [self getCurrentOrientation];+}++- (void)refreshView {+ dispatch_async(dispatch_get_main_queue(), ^{+ // Preserve recording state+ BOOL wasRecording = self.recordPressed;++ // Stop and clean up the current capture session+ if (self.captureSession.isRunning) {+ [self.captureSession stopRunning];+ }+ [self.captureSession.inputs enumerateObjectsUsingBlock:^(AVCaptureInput *input, NSUInteger idx, BOOL *stop) {+ [self.captureSession removeInput:input];+ }];+ [self.captureSession.outputs enumerateObjectsUsingBlock:^(AVCaptureOutput *output, NSUInteger idx, BOOL *stop) {+ [self.captureSession removeOutput:output];+ }];+ self.captureSession = nil;++ // Finish any ongoing recording+ if (self.isRecording) {+ [self finishRecording];+ }++ // Remove notification observers+ [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];+ [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];++ // Reset UI and remove all sublayers+ [self resetUI];+ [self.previewLayer removeFromSuperlayer];+ self.previewLayer = nil;++ self.isProcessing = NO;+ self.isProcessingCoreData = NO;+ self.recordPressed = wasRecording;+ self.isRecording = wasRecording;+ self.startTime = kCMTimeInvalid;+ self.currentTime = kCMTimeZero;++ [[NSNotificationCenter defaultCenter] addObserver:self+ selector:@selector(handleDeviceOrientationChange)+ name:UIDeviceOrientationDidChangeNotification+ object:nil];++ [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];++ SettingsManager *settings = [SettingsManager sharedManager];+ [self setupCameraWithWidth:settings.width height:settings.height];++ // Re-setup UI+ [self setupUI];++ // Update record button state if was recording+ if (self.recordPressed) {+ [self.recordButton setTitle:@"Stop" forState:UIControlStateNormal];+ for (CALayer *layer in self.recordButton.layer.sublayers) {+ if ([layer.name isEqualToString:@"redShape"]) {+ CAShapeLayer *redShape = (CAShapeLayer *)layer;+ [CATransaction begin];+ [CATransaction setAnimationDuration:0.2];+ redShape.path = [UIBezierPath bezierPathWithRect:CGRectMake(25, 25, 30, 30)].CGPath;+ [CATransaction commit];+ break;+ }+ }+ }++ // Set initial orientation+ [self setInitialOrientation];+ [self.captureSession startRunning];+ if (self.recordPressed) {+ [self startNewRecording];+ }+ [UIApplication sharedApplication].idleTimerDisabled = YES;+ });+}++- (void)setInitialOrientation {+ UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];+ AVCaptureVideoOrientation videoOrientation;+ if (deviceOrientation == UIDeviceOrientationUnknown || deviceOrientation == UIDeviceOrientationFaceUp || deviceOrientation == UIDeviceOrientationFaceDown) {+ UIInterfaceOrientation statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;+ if (statusBarOrientation == UIInterfaceOrientationLandscapeLeft) {+ deviceOrientation = UIDeviceOrientationLandscapeRight;+ } else if (statusBarOrientation == UIInterfaceOrientationLandscapeRight) {+ deviceOrientation = UIDeviceOrientationLandscapeLeft;+ } else {+ deviceOrientation = UIDeviceOrientationPortrait;+ }+ }++ if (deviceOrientation == UIDeviceOrientationPortrait) {+ videoOrientation = AVCaptureVideoOrientationPortrait;+ } else if (deviceOrientation == UIDeviceOrientationLandscapeLeft) {+ videoOrientation = AVCaptureVideoOrientationLandscapeRight;+ } else if (deviceOrientation == UIDeviceOrientationLandscapeRight) {+ videoOrientation = AVCaptureVideoOrientationLandscapeLeft;+ } else {+ videoOrientation = AVCaptureVideoOrientationPortrait; // Default+ }++ if (self.previewLayer.connection.isVideoOrientationSupported) {+ self.previewLayer.connection.videoOrientation = videoOrientation;+ }++ // Set preview frame to full view bounds+ self.previewLayer.frame = self.view.bounds;+ [self updateButtonFrames];+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ [UIApplication sharedApplication].idleTimerDisabled = YES;+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ [self.captureSession startRunning];+ });++ // Force button layout after view is about to appear+ UIDeviceOrientation initialOrientation = [self getCurrentOrientation];+ [self setVideoOrientationForOrientation:initialOrientation];+ self.previewLayer.frame = self.view.bounds;+ [self updateButtonFrames];+}++- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {+ if ([keyPath isEqualToString:@"preset"]) {+ [self finishRecording];+ [self resetUI];+ SettingsManager *settings = [SettingsManager sharedManager];+ [self setupCameraWithWidth:settings.width height:settings.height];+ if(self.isRecording) [self startNewRecording];+ [self setupUI];+ }+}++- (void)dealloc {+ [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];+}++- (UIDeviceOrientation)getCurrentOrientation {+ UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];+ UIInterfaceOrientation statusBarOrientation = UIApplication.sharedApplication.statusBarOrientation;++ if (deviceOrientation == UIDeviceOrientationUnknown || deviceOrientation == UIDeviceOrientationFaceUp || deviceOrientation == UIDeviceOrientationFaceDown) {+ if (statusBarOrientation == UIInterfaceOrientationLandscapeLeft) {+ return UIDeviceOrientationLandscapeRight;+ } else if (statusBarOrientation == UIInterfaceOrientationLandscapeRight) {+ return UIDeviceOrientationLandscapeLeft;+ } else {+ return UIDeviceOrientationPortrait;+ }+ }+ return deviceOrientation;+}++- (void)setVideoOrientationForOrientation:(UIDeviceOrientation)orientation {+ AVCaptureVideoOrientation videoOrientation;++ if (orientation == UIDeviceOrientationPortrait) {+ videoOrientation = AVCaptureVideoOrientationPortrait;+ } else if (orientation == UIDeviceOrientationLandscapeLeft) {+ videoOrientation = AVCaptureVideoOrientationLandscapeRight;+ } else if (orientation == UIDeviceOrientationLandscapeRight) {+ videoOrientation = AVCaptureVideoOrientationLandscapeLeft;+ } else {+ videoOrientation = AVCaptureVideoOrientationPortrait;+ }++ if (self.previewLayer.connection.isVideoOrientationSupported) {+ self.previewLayer.connection.videoOrientation = videoOrientation;+ }+}++- (void)handleDeviceOrientationChange {+ UIDeviceOrientation deviceOrientation = [self getCurrentOrientation];+ BOOL isSupportedLayoutOrientation = (deviceOrientation == UIDeviceOrientationPortrait ||+ deviceOrientation == UIDeviceOrientationLandscapeLeft ||+ deviceOrientation == UIDeviceOrientationLandscapeRight);++ if (isSupportedLayoutOrientation) {+ [self setVideoOrientationForOrientation:deviceOrientation];++ [UIView animateWithDuration:0.3 animations:^{+ self.previewLayer.frame = self.view.bounds;+ [self updateButtonFrames];+ }];+ }+}++- (void)setupCameraWithWidth:(NSString *)width height:(NSString *)height {+ self.captureSession = [[AVCaptureSession alloc] init];+ NSString *presetString = [NSString stringWithFormat:@"AVCaptureSessionPreset%@x%@", width, height];+ if(self.isStreaming) presetString = @"AVCaptureSessionPreset640x480";++ if ([self.captureSession canSetSessionPreset:presetString]) {+ self.captureSession.sessionPreset = presetString;+ } else return;++ AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];+ NSError *error = nil;+ AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];+ if (!input) return;+ [self.captureSession addInput:input];++ AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];+ output.videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA)};+ output.alwaysDiscardsLateVideoFrames = YES;+ [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];+ [self.captureSession addOutput:output];++ self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];+ self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect;+ [self.view.layer addSublayer:self.previewLayer];+}++- (NSString*)getDateString {+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"yyyy-MM-dd"];+ return [formatter stringFromDate:[NSDate date]];+}++- (NSString*)fake_getDateString { //todo remove+ NSDate *now = [NSDate date];+ NSCalendar *calendar = [NSCalendar currentCalendar];+ NSDateComponents *nowComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now];++ if (nowComponents.hour < 12 || (nowComponents.hour == 12 && nowComponents.minute < 20)) {+ return @"2025-02-14";+ } else {+ return @"2025-02-15";+ }+}++- (void)startNewRecording {+ self.dayFolderName = [self getDateString];+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss:SSS"];+ self.current_file_timestamp = [NSDate date];+ NSString *timestamp = [formatter stringFromDate:self.current_file_timestamp];+ NSString *segNumberString = [NSString stringWithFormat:@"_%05ld_", (long)self.seg_number];+ self.seg_number += 1;+ NSString *finalTimestamp = [NSString stringWithFormat:@"%@%@%@",+ [[timestamp componentsSeparatedByString:@"_"] firstObject],+ segNumberString,+ [[timestamp componentsSeparatedByString:@"_"] lastObject]];++ // Get resolution settings from SettingsManager+ SettingsManager *settings = [SettingsManager sharedManager];+ int videoWidth = [settings.width intValue];+ int videoHeight = [settings.height intValue];+ if(self.isStreaming){+ videoHeight = 480;+ videoWidth = 640;+ }++ // Create a folder for the day within the documents directory+ NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];+ NSURL *dayFolderURL = [documentsDirectory URLByAppendingPathComponent:self.dayFolderName];++ // Ensure the directory exists+ NSError *error = nil;+ if (![[NSFileManager defaultManager] fileExistsAtPath:dayFolderURL.path]) {+ [[NSFileManager defaultManager] createDirectoryAtURL:dayFolderURL withIntermediateDirectories:YES attributes:nil error:&error];+ if (error) return;+ }++ NSURL *outputURL = [dayFolderURL URLByAppendingPathComponent:[NSString stringWithFormat:@"output_%@.mp4", finalTimestamp]];+ self.assetWriter = [AVAssetWriter assetWriterWithURL:outputURL fileType:AVFileTypeMPEG4 error:&error];+ if (error) return;+ NSDictionary *videoSettings;+ videoSettings = @{+ AVVideoCodecKey: AVVideoCodecTypeH264, // Fallback to H.264+ AVVideoWidthKey: @(videoWidth),+ AVVideoHeightKey: @(videoHeight),+ AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill+ };++ if (self.isStreaming) {+ NSMutableDictionary *mutableSettings = [videoSettings mutableCopy];+ mutableSettings[AVVideoCompressionPropertiesKey] = @{+ AVVideoAverageBitRateKey: @(500000)+ };+ videoSettings = [mutableSettings copy];+ } else {+ NSArray<NSString *> *exportPresets = [AVAssetExportSession allExportPresets];+ if ([exportPresets containsObject:AVAssetExportPresetHEVCHighestQuality]) {+ // HEVC is supported+ videoSettings = @{+ AVVideoCodecKey: AVVideoCodecTypeHEVC, // Use HEVC (H.265)+ AVVideoWidthKey: @(videoWidth),+ AVVideoHeightKey: @(videoHeight),+ AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill+ };+ }+ }++ self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];+ self.videoWriterInput.expectsMediaDataInRealTime = YES;++ if (self.previewLayer.connection.videoOrientation == AVCaptureVideoOrientationPortrait) {+ self.videoWriterInput.transform = CGAffineTransformMakeRotation(M_PI_2); // Rotate for portrait+ } else if (self.previewLayer.connection.videoOrientation == AVCaptureVideoOrientationLandscapeLeft) {+ self.videoWriterInput.transform = CGAffineTransformMakeRotation(M_PI); // Rotate for landscape left+ }++ NSDictionary *sourcePixelBufferAttributes = @{+ (NSString *)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA),+ (NSString *)kCVPixelBufferWidthKey: @(videoWidth),+ (NSString *)kCVPixelBufferHeightKey: @(videoHeight)+ };++ self.adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:self.videoWriterInput sourcePixelBufferAttributes:sourcePixelBufferAttributes];++ if ([self.assetWriter canAddInput:self.videoWriterInput]) {+ [self.assetWriter addInput:self.videoWriterInput];+ } else {+ return;+ }++ self.startTime = kCMTimeInvalid;+ self.currentTime = kCMTimeZero;+ self.isRecording = YES;+ [self.assetWriter startWriting];+ [self.assetWriter startSessionAtSourceTime:kCMTimeZero];+ if(![self ensureFreeDiskSpace]) [self stopRecording];+}++- (void)drawSquareWithTopLeftX:(CGFloat)xOrigin topLeftY:(CGFloat)yOrigin bottomRightX:(CGFloat)bottomRightX bottomRightY:(CGFloat)bottomRightY classIndex:(int)classIndex aspectRatio:(float)aspectRatio {+ CGFloat leftEdgeX = (self.view.bounds.size.width - (self.view.bounds.size.height * aspectRatio)) / 2;+ CGFloat scaledXOrigin, scaledYOrigin, scaledWidth, scaledHeight;++ if (self.view.bounds.size.width < self.view.bounds.size.height) { //portrait+ scaledYOrigin = (self.view.bounds.size.height / 2) - (self.view.bounds.size.width * aspectRatio / 2);+ scaledYOrigin += (yOrigin / self.yolo.yolo_res) * (self.view.bounds.size.width * aspectRatio);+ scaledHeight = ((bottomRightY - yOrigin) / self.yolo.yolo_res) * (self.view.bounds.size.width * aspectRatio);+ scaledXOrigin = (xOrigin / (self.yolo.yolo_res / aspectRatio)) * self.view.bounds.size.width;+ scaledWidth = self.view.bounds.size.width * (bottomRightX - xOrigin) / (self.yolo.yolo_res / aspectRatio);+ } else {+ scaledXOrigin = leftEdgeX + (xOrigin * aspectRatio / self.yolo.yolo_res) * self.view.bounds.size.height;+ scaledYOrigin = (aspectRatio * yOrigin / self.yolo.yolo_res) * self.view.bounds.size.height;+ scaledWidth = (bottomRightX - xOrigin) * (aspectRatio * self.view.bounds.size.height / self.yolo.yolo_res);+ scaledHeight = (bottomRightY - yOrigin) * (aspectRatio * self.view.bounds.size.height / self.yolo.yolo_res);+ }++ UIColor *color = self.yolo.yolo_classes[classIndex][1];+ CAShapeLayer *squareLayer = [CAShapeLayer layer];+ squareLayer.name = @"rectangleLayer";+ squareLayer.strokeColor = color.CGColor;+ squareLayer.lineWidth = 2.0;+ squareLayer.fillColor = [UIColor clearColor].CGColor;+ squareLayer.path = [UIBezierPath bezierPathWithRect:CGRectMake(scaledXOrigin, scaledYOrigin, scaledWidth, scaledHeight)].CGPath;++ [self.view.layer addSublayer:squareLayer];++ NSString *className = self.yolo.yolo_classes[classIndex][0];+ NSDictionary *textAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:12],+ NSForegroundColorAttributeName: [UIColor whiteColor]};+ NSString *labelText = [className lowercaseString];+ CGSize textSize = [labelText sizeWithAttributes:textAttributes];++ CGFloat labelX = scaledXOrigin - 2;+ CGFloat labelY = scaledYOrigin - textSize.height - 2;++ UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, textSize.width + 4, textSize.height + 2)];+ label.backgroundColor = color;+ label.textColor = [UIColor whiteColor];+ label.font = [UIFont systemFontOfSize:12];+ label.text = labelText;++ [self.view addSubview:label];+}++- (void)resetSquares {+ NSMutableArray *layersToRemove = [NSMutableArray array];+ NSMutableArray *labelsToRemove = [NSMutableArray array];++ for (CALayer *layer in self.view.layer.sublayers) {+ if ([layer.name isEqualToString:@"rectangleLayer"]) {+ [layersToRemove addObject:layer];+ }+ }++ for (UIView *subview in self.view.subviews) {+ if ([subview isKindOfClass:[UILabel class]] && subview != self.fpsLabel) {+ [labelsToRemove addObject:subview];+ }+ }++ for (CALayer *layer in layersToRemove) {+ [layer removeFromSuperlayer];+ }++ for (UIView *label in labelsToRemove) {+ [label removeFromSuperview];+ }+}++- (void)resetUI {+ // Remove all subviews+ for (UIView *subview in self.view.subviews) {+ [subview removeFromSuperview];+ }++ // Remove all sublayers (using a copy of the sublayers array)+ NSArray<CALayer *> *sublayers = [self.view.layer.sublayers copy];+ for (CALayer *sublayer in sublayers) {+ [sublayer removeFromSuperlayer];+ }++ // Reset UI-related properties+ self.previewLayer = nil;+}++- (void)setupUI {+ self.fpsLabel = [[UILabel alloc] init];+ self.fpsLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];+ self.fpsLabel.textColor = [UIColor whiteColor];+ self.fpsLabel.font = [UIFont boldSystemFontOfSize:14];+ self.fpsLabel.text = @"FPS: 0";+ [self.fpsLabel sizeToFit]; // Size to fit the text+ self.fpsLabel.frame = CGRectMake(10, 50, self.fpsLabel.frame.size.width + 8, self.fpsLabel.frame.size.height + 4);+ [self.view addSubview:self.fpsLabel];++ self.recordButton = [UIButton buttonWithType:UIButtonTypeCustom];+ CGFloat buttonSize = 80;+ self.recordButton.frame = CGRectMake(0, 0, buttonSize, buttonSize);+ self.recordButton.backgroundColor = [UIColor clearColor];+ self.recordButton.clipsToBounds = YES;+ CAShapeLayer *whiteRing = [CAShapeLayer layer];+ whiteRing.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5, buttonSize - 10, buttonSize - 10)].CGPath;+ whiteRing.fillColor = [UIColor clearColor].CGColor;+ whiteRing.strokeColor = [UIColor whiteColor].CGColor;+ whiteRing.lineWidth = 4.0;+ [self.recordButton.layer addSublayer:whiteRing];++ CAShapeLayer *redShape = [CAShapeLayer layer];+ redShape.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(10, 10, buttonSize - 20, buttonSize - 20)].CGPath;+ redShape.fillColor = [UIColor redColor].CGColor;+ redShape.name = @"redShape";+ [self.recordButton.layer addSublayer:redShape];++ [self.recordButton setTitle:@"Record" forState:UIControlStateNormal];+ self.recordButton.titleLabel.alpha = 0;+ [self.recordButton addTarget:self action:@selector(toggleRecording) forControlEvents:UIControlEventTouchUpInside];+ [self.view addSubview:self.recordButton];++ [self updateButtonFrames]; // Just call it once+}++- (void)updateButtonFrames {+ CGFloat recordButtonSize = 80;+ CGFloat spacing = 60;++ UIEdgeInsets safeAreaInsets = self.view.safeAreaInsets;+ CGFloat screenWidth = self.view.bounds.size.width;+ CGFloat screenHeight = self.view.bounds.size.height;++ self.recordButton.layer.cornerRadius = recordButtonSize / 2;++ UIDeviceOrientation orientation = [self getCurrentOrientation];++ if (orientation == UIDeviceOrientationPortraitUpsideDown ||+ orientation == UIDeviceOrientationFaceUp ||+ orientation == UIDeviceOrientationFaceDown) {+ return;+ }+ if (orientation == UIDeviceOrientationLandscapeRight) {+ CGFloat leftMargin = MAX(20, safeAreaInsets.left + 10);+ self.recordButton.frame = CGRectMake(leftMargin, screenHeight / 2 - recordButtonSize / 2, recordButtonSize, recordButtonSize);+ self.fpsLabel.frame = CGRectMake(screenWidth - self.fpsLabel.frame.size.width - MAX(20, safeAreaInsets.right + 10),+ safeAreaInsets.top + 10,+ self.fpsLabel.frame.size.width,+ self.fpsLabel.frame.size.height);+ } else if (orientation == UIDeviceOrientationLandscapeLeft) {+ CGFloat rightMargin = MAX(20, safeAreaInsets.right + 10);+ self.recordButton.frame = CGRectMake(screenWidth - recordButtonSize - rightMargin, screenHeight / 2 - recordButtonSize / 2, recordButtonSize, recordButtonSize);+ self.fpsLabel.frame = CGRectMake(MAX(10, safeAreaInsets.left + 5),+ safeAreaInsets.top + 10,+ self.fpsLabel.frame.size.width,+ self.fpsLabel.frame.size.height);+ } else {+ CGFloat bottomMargin = MAX(20, safeAreaInsets.bottom + 10);+ CGFloat recordX = (screenWidth - recordButtonSize) / 2;+ self.recordButton.frame = CGRectMake(recordX, screenHeight - recordButtonSize - bottomMargin, recordButtonSize, recordButtonSize);+ self.fpsLabel.frame = CGRectMake(screenWidth - self.fpsLabel.frame.size.width - 20,+ safeAreaInsets.top + 10,+ self.fpsLabel.frame.size.width,+ self.fpsLabel.frame.size.height);+ }+}++- (void)toggleRecording {+ CAShapeLayer *redShape = nil;+ for (CALayer *layer in self.recordButton.layer.sublayers) {+ if ([layer.name isEqualToString:@"redShape"]) {+ redShape = (CAShapeLayer *)layer;+ break;+ }+ }++ if ([[self.recordButton titleForState:UIControlStateNormal] isEqualToString:@"Record"]) {+ self.recordPressed = YES;+ [self.recordButton setTitle:@"Stop" forState:UIControlStateNormal];+ // Change to red square+ if (redShape) {+ [CATransaction begin];+ [CATransaction setAnimationDuration:0.2];+ redShape.path = [UIBezierPath bezierPathWithRect:CGRectMake(25, 25, 30, 30)].CGPath;+ [CATransaction commit];+ }+ } else {+ self.recordPressed = NO;+ [self.recordButton setTitle:@"Record" forState:UIControlStateNormal];+ // Change back to red circle+ if (redShape) {+ [CATransaction begin];+ [CATransaction setAnimationDuration:0.2];+ redShape.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(10, 10, 60, 60)].CGPath;+ [CATransaction commit];+ }+ }+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ self.previewLayer.frame = self.view.bounds;+ [self updateButtonFrames];+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ self.previewLayer.frame = self.view.bounds;+}++- (void)viewWillDisappear:(BOOL)animated {+ [super viewWillDisappear:animated];+ [self.captureSession stopRunning];+ // Enable auto-locking (important!)+ [UIApplication sharedApplication].idleTimerDisabled = NO;+}++- (CGRect)frameForCurrentOrientation {+ CGFloat width = self.view.bounds.size.width;+ CGFloat height = self.view.bounds.size.height;+ return CGRectMake(0, 0, width, height);+}++- (CGImageRef)cropAndResizeCGImage:(CGImageRef)image toSize:(CGSize)size {+ CGFloat originalWidth = CGImageGetWidth(image);+ CGFloat originalHeight = CGImageGetHeight(image);+ CGFloat sideLength = MIN(originalWidth, originalHeight);+ CGRect cropRect = CGRectMake((originalWidth - sideLength) / 2.0,+ (originalHeight - sideLength) / 2.0,+ sideLength,+ sideLength);++ CGImageRef croppedImageRef = CGImageCreateWithImageInRect(image, cropRect);+ UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);+ [[UIImage imageWithCGImage:croppedImageRef] drawInRect:CGRectMake(0, 0, size.width, size.height)];+ UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();+ UIGraphicsEndImageContext();+ CGImageRelease(croppedImageRef);++ return resizedImage.CGImage;+}++- (void)stopRecording {+ if (!(self.isRecording && self.assetWriter.status == AVAssetWriterStatusWriting)) return;+ self.isRecording = NO;+ [self.videoWriterInput markAsFinished];+}++- (void)finishRecording {+ if (!(self.isRecording && self.assetWriter.status == AVAssetWriterStatusWriting)) return;++ NSString *segmentsDirectory = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:self.dayFolderName];+ [[NSFileManager defaultManager] createDirectoryAtPath:segmentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];+ NSCalendar *calendar = [NSCalendar currentCalendar];++ dispatch_async(self.finishRecordingQueue, ^{+ while (self.isProcessingCoreData) {+ [NSThread sleepForTimeInterval:0.001];+ }+ self.isProcessingCoreData = YES;+ self.isRecording = NO;+ [self.videoWriterInput markAsFinished];++ [self.assetWriter finishWritingWithCompletionHandler:^{+ if (!self.assetWriter.outputURL) {+ NSLog(@"❌ No output URL for asset writer");+ dispatch_async(dispatch_get_main_queue(), ^{+ self.isProcessingCoreData = NO;+ [self startNewRecording];+ });+ return;+ }++ AVAsset *asset = [AVAsset assetWithURL:self.assetWriter.outputURL];+ CMTime time = asset.duration;+ NSString *segmentURL = [NSString stringWithFormat:@"%@/%@", [[self.assetWriter.outputURL URLByDeletingLastPathComponent] lastPathComponent], self.assetWriter.outputURL.lastPathComponent];+ NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.current_file_timestamp];+ NSTimeInterval timeStamp = [self.current_file_timestamp timeIntervalSinceDate:[calendar dateFromComponents:components]];+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"yyyy-MM-dd"];+ NSString *thisDayFoler = [formatter stringFromDate:self.current_file_timestamp];++ if(self.isStreaming && CMTimeGetSeconds(((AVAsset *)[AVAsset assetWithURL:self.assetWriter.outputURL]).duration) < 5.0){+ // Prepare file for upload+ NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"segment.mp4.aes"];+ NSError *fileError = nil;+ NSFileManager *fileManager = [NSFileManager defaultManager];+ if ([fileManager fileExistsAtPath:tempFilePath]) {+ [fileManager removeItemAtPath:tempFilePath error:&fileError];+ if (fileError) {+ NSLog(@"❌ Failed to remove existing temp file: %@", fileError);+ }+ }++ if (self.assetWriter.outputURL) {+ [fileManager copyItemAtURL:self.assetWriter.outputURL toURL:[NSURL fileURLWithPath:tempFilePath] error:&fileError];++ // Trigger upload if file was successfully copied+ if ([fileManager fileExistsAtPath:tempFilePath]) {+ [self uploadSegment];+ } else {+ NSLog(@"❌ Temp file not found, skipping upload");+ }+ }+ }++ [self.backgroundContext performBlock:^{+ // Save background context+ NSError *error = nil;+ if ([self.backgroundContext save:&error]) {+ // Save parent context only if necessary+ NSError *parentError = nil;+ [self.fileServer.context save:&parentError];+ } else {+ NSLog(@"❌ Failed to save background context: %@", error);+ }++ // Create a local copy of current_segment_squares+ __block NSArray *segmentSquaresCopy;+ dispatch_sync(self.segmentQueue, ^{+ segmentSquaresCopy = [self.current_segment_squares copy];+ [self.current_segment_squares removeAllObjects];+ });++ // Fetch or create DayEntity efficiently+ NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DayEntity"];+ fetchRequest.predicate = [NSPredicate predicateWithFormat:@"date == %@", thisDayFoler];+ fetchRequest.fetchLimit = 1;++ NSArray *fetchedDays = [self.backgroundContext executeFetchRequest:fetchRequest error:&error];+ NSManagedObject *dayEntity;++ if (error) {+ NSLog(@"❌ Fetch request failed: %@", error);+ return;+ }++ if (fetchedDays.count > 0) {+ dayEntity = fetchedDays.firstObject;+ } else {+ dayEntity = [NSEntityDescription insertNewObjectForEntityForName:@"DayEntity" inManagedObjectContext:self.backgroundContext];+ [dayEntity setValue:self.dayFolderName forKey:@"date"];+ }++ // Insert new SegmentEntity+ NSManagedObject *newSegment = [NSEntityDescription insertNewObjectForEntityForName:@"SegmentEntity" inManagedObjectContext:self.backgroundContext];+ [newSegment setValuesForKeysWithDictionary:@{+ @"url": segmentURL,+ @"timeStamp": @(timeStamp),+ @"duration": @(CMTimeGetSeconds(time)),+ @"orientation": @((int16_t)self.previewLayer.connection.videoOrientation)+ }];+ NSMutableArray<NSManagedObject *> *segmentFrames = [NSMutableArray arrayWithCapacity:segmentSquaresCopy.count];++ for (NSDictionary *frameData in segmentSquaresCopy) {+ NSManagedObject *newFrame = [NSEntityDescription insertNewObjectForEntityForName:@"FrameEntity" inManagedObjectContext:self.backgroundContext];+ [newFrame setValuesForKeysWithDictionary:@{+ @"frame_timeStamp": frameData[@"frame_timeStamp"] ?: @0,+ @"aspect_ratio": frameData[@"aspect_ratio"] ?: @0,+ @"res": frameData[@"res"] ?: @0+ }];++ NSArray *squaresData = frameData[@"squares"];+ NSMutableArray<NSManagedObject *> *frameSquares = [NSMutableArray arrayWithCapacity:squaresData.count];++ for (NSDictionary *squareData in squaresData) {+ NSManagedObject *newSquare = [NSEntityDescription insertNewObjectForEntityForName:@"SquareEntity" inManagedObjectContext:self.backgroundContext];+ [newSquare setValuesForKeysWithDictionary:squareData];+ [frameSquares addObject:newSquare];+ }++ [newFrame setValue:[NSOrderedSet orderedSetWithArray:frameSquares] forKey:@"squares"];+ [segmentFrames addObject:newFrame];+ }++ [newSegment setValue:[NSOrderedSet orderedSetWithArray:segmentFrames] forKey:@"frames"];+ [[dayEntity mutableOrderedSetValueForKey:@"segments"] addObject:newSegment];++ // Save the context again after modifications+ NSError *saveError = nil;+ [self.backgroundContext save:&saveError];+ }];++ dispatch_async(dispatch_get_main_queue(), ^{+ self.isProcessingCoreData = NO;+ [self startNewRecording];+ });+ }];+ });+}++- (void)uploadSegment {+ NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"segment.mp4.aes"];+ NSData *fileData = [NSData dataWithContentsOfFile:filePath];++ if (!fileData) {+ NSLog(@"❌ Failed to read segment.mp4 for upload");+ return;+ }++ // Replace with your actual signed URL+ NSString *signedUrl = self.streamLink;++ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:signedUrl]];+ request.HTTPMethod = @"PUT";+ [request setValue:@"video/mp4" forHTTPHeaderField:@"Content-Type"];+ [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)fileData.length] forHTTPHeaderField:@"Content-Length"];+ NSString *encryptionKey = [[SecretManager sharedManager] getEncryptionKey];+ if (!encryptionKey) return;+ fileData = [[SecretManager sharedManager] encryptData:fileData withKey:encryptionKey];++ [[[NSURLSession sharedSession] uploadTaskWithRequest:request+ fromData:fileData+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ if (error) {+ NSLog(@"❌ Upload failed: %@", error);+ } else if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {+ NSLog(@"✅ Uploaded segment.mp4.aes: %.2f KB", (float)fileData.length / 1024.0);+ } else {+ NSLog(@"❌ Upload failed with status %ld", (long)httpResponse.statusCode);+ }+ }] resume];+}++- (NSString *)jsonStringFromDictionary:(NSDictionary *)dictionary {+ NSError *error;+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];+ if (!error) {+ return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];+ } else {+ return nil;+ }+}++- (uint64_t)getFreeDiskSpace {+ NSError *error = nil;+ NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];++ if (error) return 0;++ uint64_t freeSpace = [[attributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];+ return freeSpace;+}++- (BOOL)ensureFreeDiskSpace {+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ NSInteger lastDeletedDayIndex = [defaults integerForKey:@"LastDeletedDayIndex"];+ NSInteger lastDeletedSegmentIndex = [defaults integerForKey:@"LastDeletedSegmentIndex"];++ @try {+ if ((double)[[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] unsignedLongLongValue] / (1024.0 * 1024.0) < MIN_FREE_SPACE_MB) {+ // Fetch all DayEntities, sorted by date+ NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DayEntity"];+ fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];++ NSError *fetchError = nil;+ NSArray *dayEntities = [self.fileServer.context executeFetchRequest:fetchRequest error:&fetchError];++ if (fetchError) return YES;++ if (dayEntities.count == 0 || lastDeletedDayIndex >= dayEntities.count) {+ [defaults removeObjectForKey:@"LastDeletedDayIndex"];+ [defaults removeObjectForKey:@"LastDeletedSegmentIndex"];+ [defaults synchronize];+ return YES;+ }++ // Fetch event timestamps from Core Data+ NSArray *eventDataArray = [self.fileServer fetchEventDataFromCoreData:self.fileServer.context];+ NSMutableArray<NSNumber *> *eventTimestamps = [NSMutableArray array];+ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];+ [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];++ NSCalendar *calendar = [NSCalendar currentCalendar];+ for (NSDictionary *eventData in eventDataArray) {+ NSString *timestampString = eventData[@"timeStamp"];+ NSDate *eventDate = [dateFormatter dateFromString:timestampString];++ if (eventDate) {+ NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:eventDate];+ double eventSecondsSinceMidnight = (components.hour * 3600) + (components.minute * 60) + components.second;+ [eventTimestamps addObject:@(eventSecondsSinceMidnight)];+ }+ }++ BOOL deletedFile = NO;+ NSManagedObjectContext *context = self.fileServer.context;++ for (NSInteger dayIndex = lastDeletedDayIndex; dayIndex < dayEntities.count; dayIndex++) {+ NSManagedObject *dayEntity = dayEntities[dayIndex];+ NSArray *segments = [[dayEntity valueForKey:@"segments"] allObjects];++ if (lastDeletedSegmentIndex >= segments.count) {+ lastDeletedSegmentIndex = 0; // Reset segment index if we move to the next day+ }++ // Collect segments to delete in a separate array to avoid modifying the collection during iteration+ NSMutableArray<NSManagedObject *> *segmentsToDelete = [NSMutableArray array];++ // Inside the dayIndex loop+ for (NSInteger segmentIndex = lastDeletedSegmentIndex; segmentIndex < segments.count; segmentIndex++) {+ NSManagedObject *segmentEntity = segments[segmentIndex];+ NSString *segmentURL = [segmentEntity valueForKey:@"url"];++ NSNumber *segmentTimeStampNumber = [segmentEntity valueForKey:@"timeStamp"];+ if (!segmentTimeStampNumber) {+ continue;+ }++ double segmentSecondsSinceMidnight = segmentTimeStampNumber.doubleValue;+ BOOL shouldSkipDeletion = NO;+ for (NSNumber *eventTimestamp in eventTimestamps) {+ double eventSecondsSinceMidnight = eventTimestamp.doubleValue;+ double timeDifference = fabs(segmentSecondsSinceMidnight - eventSecondsSinceMidnight);+ if (timeDifference <= 60) { // Within one minute+ shouldSkipDeletion = YES;+ break;+ }+ }++ if (shouldSkipDeletion) {+ continue;+ }++ // Mark this segment for deletion+ [segmentsToDelete addObject:segmentEntity];+ }++ // Delete the collected segments and their files+ for (NSManagedObject *segmentEntity in segmentsToDelete) {+ NSString *segmentURL = [segmentEntity valueForKey:@"url"]; // Declare segmentURL here+ @try {+ NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:segmentURL];++ NSError *deleteError = nil;+ if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {+ if ([[NSFileManager defaultManager] removeItemAtPath:filePath error:&deleteError]) {+ // Delete the segmentEntity from Core Data+ [context deleteObject:segmentEntity];++ deletedFile = YES;+ if ((double)[[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] unsignedLongLongValue] / (1024.0 * 1024.0) >= MIN_FREE_SPACE_MB + 500) {+ // Save the context before returning+ NSError *saveError = nil;+ if ([context save:&saveError]) {+ [defaults setInteger:dayIndex forKey:@"LastDeletedDayIndex"];+ [defaults setInteger:lastDeletedSegmentIndex forKey:@"LastDeletedSegmentIndex"];+ [defaults synchronize];+ return YES;+ }+ }+ }+ }+ } @catch (NSException *exception) {+ NSLog(@"Exception while deleting file: %@, reason: %@", segmentURL, exception.reason); // segmentURL is now in scope+ }+ }++ // Save the context after processing each day+ NSError *saveError = nil;+ if ([context save:&saveError]) {+ [defaults setInteger:dayIndex forKey:@"LastDeletedDayIndex"];+ [defaults setInteger:lastDeletedSegmentIndex forKey:@"LastDeletedSegmentIndex"];+ [defaults synchronize];+ }++ // Reset segment index for the next day+ lastDeletedSegmentIndex = 0;+ }++ // If nothing was deleted, reset the indexes+ if (!deletedFile) {+ [defaults removeObjectForKey:@"LastDeletedDayIndex"];+ [defaults removeObjectForKey:@"LastDeletedSegmentIndex"];+ [defaults synchronize];+ return NO;+ }+ }+ } @catch (NSException *exception) {+ NSLog(@"Exception in ensureFreeDiskSpace: %@", exception.reason);+ return YES;+ }+ return YES;+}++- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {+ @try {+ if (self.recordPressed && self.isRecording && self.assetWriter.status == AVAssetWriterStatusWriting) {+ CMTime timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);+ if (CMTIME_IS_INVALID(self.startTime)) {+ self.startTime = timestamp;+ self.currentTime = kCMTimeZero;+ } else {+ self.currentTime = CMTimeSubtract(timestamp, self.startTime);+ }++ if (self.videoWriterInput.readyForMoreMediaData) {+ CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);+ pixelBuffer = [self addTimeStampToPixelBuffer:pixelBuffer];++ BOOL success = NO;+ int retryCount = 3;++ while (!success && retryCount > 0) {+ success = [self.adaptor appendPixelBuffer:pixelBuffer withPresentationTime:self.currentTime];+ if (!success) {+ retryCount--;+ [NSThread sleepForTimeInterval:0.01];+ }+ }+ if (!success) [self finishRecording];+ }++ NSTimeInterval elapsedTime = CMTimeGetSeconds(self.currentTime);+ if (!self.isStreaming && [FileServer sharedInstance].segment_length < 60 && [[NSDate now] timeIntervalSinceDate:self.fileServer.last_req_time] > 60) { //todo, fix hack in SceneState+ [FileServer sharedInstance].segment_length = 60;+ }+ if([[NSUserDefaults standardUserDefaults] boolForKey:@"live_stream_internet_enabled"]) {+ if ([[NSDate date] timeIntervalSince1970] - self.last_check_time > 5.0) {+ self.last_check_time = [[NSDate date] timeIntervalSince1970];+ [[StoreManager sharedInstance] verifySubscriptionWithCompletionIfSubbed:^(BOOL isActive, NSDate *expiryDate) {+ [self checkUploadLink];+ }];+ }+ }+ if (elapsedTime >= [FileServer sharedInstance].segment_length || (self.isStreaming && elapsedTime > 2.0)) {+ [self finishRecording];+ }+ }+ if(!self.isStreaming){+ AVCaptureVideoOrientation videoOrientation = self.previewLayer.connection.videoOrientation;+ CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);+ CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer];++ if (self.isProcessing) {+ return;+ }++ self.isProcessing = YES;++ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{+ size_t width = CVPixelBufferGetWidth(imageBuffer);+ size_t height = CVPixelBufferGetHeight(imageBuffer);+ CGFloat aspect_ratio = (CGFloat)width / (CGFloat)height;++ NSMutableArray *frameSquares = [[NSMutableArray alloc] init];++ NSCalendar *calendar = [NSCalendar currentCalendar];+ NSDate *now = [NSDate date];+ NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];+ NSDate *midnight = [calendar dateFromComponents:components];+ NSTimeInterval timeStamp = [now timeIntervalSinceDate:midnight];++ NSMutableDictionary *frame = [[NSMutableDictionary alloc] init];+ frame[@"frame_timeStamp"] = @(timeStamp);+ frame[@"res"] = @(self.yolo.yolo_res);+ frame[@"aspect_ratio"] = @(aspect_ratio);++ CGFloat targetWidth = self.yolo.yolo_res;+ CGSize targetSize = CGSizeMake(targetWidth, targetWidth / aspect_ratio);++ CGFloat scaleX = targetSize.width / width;+ CGFloat scaleY = targetSize.height / height;+ CIImage *resizedImage = [ciImage imageByApplyingTransform:CGAffineTransformMakeScale(scaleX, scaleY)];++ CGRect cropRect = CGRectMake(0, 0, targetSize.width, targetSize.height);+ CIImage *croppedImage = [resizedImage imageByCroppingToRect:cropRect];++ CGImageRef cgImage = [self.ciContext createCGImage:croppedImage fromRect:cropRect];++ NSArray *output = [self.yolo yolo_infer:cgImage withOrientation:videoOrientation];+ if(self.recordPressed) [self.scene processOutput:output withImage:ciImage orientation:self.previewLayer.connection.videoOrientation];+ CGImageRelease(cgImage);++ __weak typeof(self) weak_self = self;+ dispatch_async(dispatch_get_main_queue(), ^{+ @try {+ __strong typeof(weak_self) strongSelf = weak_self;+ if (!strongSelf) {+ return;+ }++ [strongSelf resetSquares];++ for (NSArray *detection in output) {+ NSMutableDictionary *frameSquare = [[NSMutableDictionary alloc] init];+ frameSquare[@"originX"] = detection[0];+ frameSquare[@"originY"] = detection[1];+ frameSquare[@"bottomRightX"] = detection[2];+ frameSquare[@"bottomRightY"] = detection[3];+ frameSquare[@"classIndex"] = detection[4];+ [frameSquares addObject:frameSquare];++ [strongSelf drawSquareWithTopLeftX:[detection[0] floatValue]+ topLeftY:[detection[1] floatValue]+ bottomRightX:[detection[2] floatValue]+ bottomRightY:[detection[3] floatValue]+ classIndex:[detection[4] intValue]+ aspectRatio:aspect_ratio];+ }++ frame[@"squares"] = frameSquares;++ dispatch_async(self.segmentQueue, ^{+ if (!self.current_segment_squares) {+ self.current_segment_squares = [[NSMutableArray alloc] init];+ }+ [self.current_segment_squares addObject:frame];+ });++ [strongSelf updateFPS];+ strongSelf.isProcessing = NO;+ } @catch (NSException *exception) {+ NSLog(@"Exception in main queue block: %@", exception);+ }+ });+ });+ }+ } @catch (NSException *exception) {+ NSLog(@"Exception occurred: %@, %@", exception, [exception callStackSymbols]);+ }+}++- (CVPixelBufferRef)addColoredRectangleToPixelBuffer:(CVPixelBufferRef)pixelBuffer withColor:(UIColor *)color originX:(CGFloat)originX originY:(CGFloat)originY width:(CGFloat)width height:(CGFloat)height opacity:(CGFloat)opacity {+ CVPixelBufferLockBaseAddress(pixelBuffer, 0);++ CGContextRef context = [self createContextForPixelBuffer:pixelBuffer];++ size_t pixelBufferHeight = CVPixelBufferGetHeight(pixelBuffer);+ // Adjust originY to be relative to the top-left corner+ CGRect rectangleRect = CGRectMake(originX, pixelBufferHeight - originY - height, width, height);++ // Set the fill color with the adjusted opacity+ UIColor *colorWithOpacity = [color colorWithAlphaComponent:opacity];+ CGContextSetFillColorWithColor(context, colorWithOpacity.CGColor);+ CGContextFillRect(context, rectangleRect);++ CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);+ CGContextRelease(context);++ return pixelBuffer;+}++- (CVPixelBufferRef)addTimeStampToPixelBuffer:(CVPixelBufferRef)pixelBuffer {+ // Get text_size from SettingsManager+ SettingsManager *settings = [SettingsManager sharedManager];+ NSInteger textSize = [settings.text_size intValue];+ if(self.isStreaming) textSize = 2;+ NSInteger pixelSize = textSize * 2;+ NSInteger spaceSize = textSize;+ NSInteger digitOriginX = spaceSize;+ NSInteger digitOriginY = spaceSize;+ NSInteger height = spaceSize * 2 + pixelSize * 5;++ NSDate *currentDate = [NSDate date];+ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];+ [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];+ NSString *timestamp = [dateFormatter stringFromDate:currentDate];++ // Check rotation+ CGAffineTransform transform = self.videoWriterInput.transform;+ CGFloat angle = atan2(transform.b, transform.a);+ CGFloat degrees = angle * (180.0 / M_PI);+ size_t width_res = CVPixelBufferGetWidth(pixelBuffer);+ size_t height_res = CVPixelBufferGetHeight(pixelBuffer);++ if (degrees == 90 || degrees == -90) {+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor blackColor]+ originX:0+ originY:height_res - (pixelSize * 3 + spaceSize) * timestamp.length+ width:height+ height:(pixelSize * 3 + spaceSize) * timestamp.length+ opacity:0.4];+ } else if (degrees == 180 || degrees == -180) {+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor blackColor]+ originX:width_res - (pixelSize * 3 + spaceSize) * timestamp.length+ originY:height_res - height+ width:(pixelSize * 3 + spaceSize) * timestamp.length+ height:height+ opacity:0.4];+ } else {+ // No rotation+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor blackColor]+ originX:0+ originY:0+ width:(pixelSize * 3 + spaceSize) * timestamp.length+ height:height+ opacity:0.4];+ }++ for (NSUInteger k = 0; k < [timestamp length]; k++) {+ unichar character = [timestamp characterAtIndex:k];+ if (character == ' ') {+ digitOriginX += pixelSize * 3;+ continue;+ }+ NSString *key = [NSString stringWithFormat:@"%C", character];+ for (int i = 0; i < [self.digits[key] count]; i++) {+ if (degrees == 90 || degrees == -90) {+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor whiteColor]+ originX:digitOriginY + [self.digits[key][i][1] doubleValue] * pixelSize+ originY:height_res - (digitOriginX + [self.digits[key][i][0] doubleValue] * pixelSize) - ([self.digits[key][i][2] doubleValue] * pixelSize)+ width:[self.digits[key][i][3] doubleValue] * pixelSize+ height:[self.digits[key][i][2] doubleValue] * pixelSize+ opacity:1];+ } else if (degrees == 180 || degrees == -180) {+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor whiteColor]+ originX:width_res - (digitOriginX + [self.digits[key][i][0] doubleValue] * pixelSize) - ([self.digits[key][i][2] doubleValue] * pixelSize)+ originY:height_res - (digitOriginY + [self.digits[key][i][1] doubleValue] * pixelSize) - ([self.digits[key][i][3] doubleValue] * pixelSize)+ width:[self.digits[key][i][2] doubleValue] * pixelSize+ height:[self.digits[key][i][3] doubleValue] * pixelSize+ opacity:1];+ } else {+ pixelBuffer = [self addColoredRectangleToPixelBuffer:pixelBuffer+ withColor:[UIColor whiteColor]+ originX:digitOriginX + [self.digits[key][i][0] doubleValue] * pixelSize+ originY:digitOriginY + [self.digits[key][i][1] doubleValue] * pixelSize+ width:[self.digits[key][i][2] doubleValue] * pixelSize+ height:[self.digits[key][i][3] doubleValue] * pixelSize+ opacity:1];+ }+ }+ digitOriginX += pixelSize * 3 + spaceSize;+ }+ return pixelBuffer;+}++// Helper method to create a CGContext for a CVPixelBufferRef+- (CGContextRef)createContextForPixelBuffer:(CVPixelBufferRef)pixelBuffer {+ size_t width = CVPixelBufferGetWidth(pixelBuffer);+ size_t height = CVPixelBufferGetHeight(pixelBuffer);+ size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);++ void *baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer);++ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();+ CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);+ CGColorSpaceRelease(colorSpace);++ return context;+}++- (void)checkUploadLink {+ NSString *deviceName = [[NSUserDefaults standardUserDefaults] stringForKey:@"device_name"];+ NSString *sessionToken = [[StoreManager sharedInstance] retrieveSessionTokenFromKeychain];++ NSString *encodedDeviceName = [deviceName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];+ NSString *encodedSessionToken = [sessionToken stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];+ NSURLComponents *components = [NSURLComponents componentsWithString:@"https://rors.ai/get_stream_upload_link"];+ components.queryItems = @[+ [NSURLQueryItem queryItemWithName:@"name" value:encodedDeviceName],+ [NSURLQueryItem queryItemWithName:@"session_token" value:encodedSessionToken]+ ];++ NSURL *url = components.URL;++ NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error) {+ NSLog(@"❌ Error: %@", error.localizedDescription);+ return;+ }++ NSError *jsonError;+ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];+ if (jsonError) {+ NSLog(@"⚠️ JSON Parsing Error: %@", jsonError.localizedDescription);+ return;+ }++ NSString *uploadLink = json[@"upload_link"];+ dispatch_async(dispatch_get_main_queue(), ^{+ if (uploadLink && ![uploadLink isKindOfClass:[NSNull class]]) {+ self.streamLink = uploadLink;+ if (!self.isStreaming) {+ NSLog(@"📤 Upload link received: %@", uploadLink);+ self.isStreaming = YES;+ [self refreshView];+ }+ } else {+ if (self.isStreaming) {+ self.scene.left_live_time = [NSDate now];+ self.isStreaming = NO;+ [self refreshView];+ NSLog(@"no link");+ }+ }+ });+ }];+ [task resume];+}++- (void)updateFPS {+ CFTimeInterval currentTime = CACurrentMediaTime();+ if (self.lastFrameTime > 0) {+ CFTimeInterval deltaTime = currentTime - self.lastFrameTime;+ self.frameCount++;+ if (deltaTime >= 1.0) {+ CGFloat fps = self.frameCount / deltaTime;+ self.fpsLabel.text = [NSString stringWithFormat:@"FPS: %.1f", fps];+ [self.fpsLabel sizeToFit]; // Adjust size to fit new text+ self.fpsLabel.frame = CGRectMake(self.fpsLabel.frame.origin.x,+ self.fpsLabel.frame.origin.y,+ self.fpsLabel.frame.size.width + 8,+ self.fpsLabel.frame.size.height + 4); // Add padding+ self.frameCount = 0;+ self.lastFrameTime = currentTime;+ }+ } else {+ self.lastFrameTime = currentTime;+ }+}+@enddiff --git a/ios/clearcam/Yolo.h b/ios/clearcam/Yolo.hnew file mode 100644index 0000000..05c3d8c--- /dev/null+++ b/ios/clearcam/Yolo.h@@ -0,0 +1,34 @@+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#import <AVFoundation/AVFoundation.h>++NS_ASSUME_NONNULL_BEGIN++@interface Yolo : NSObject++@property (nonatomic, strong) id<MTLDevice> device;+@property (nonatomic, strong) NSMutableDictionary<NSString *, id> *pipeline_states;+@property (nonatomic, strong) NSMutableDictionary<NSString *, id> *buffers;+@property (nonatomic, strong) id<MTLCommandQueue> mtl_queue;+@property (nonatomic, strong) NSMutableArray<id<MTLCommandBuffer>> *mtl_buffers_in_flight;+@property (nonatomic, assign) int yolo_res;+@property (nonatomic, strong) NSArray *yolo_classes;+@property (nonatomic, assign) CFDataRef data;+@property (nonatomic, strong) NSMutableDictionary *_h;+@property (nonatomic, strong) NSMutableArray *_q;+@property (nonatomic, strong) NSString *input_buffer;+@property (nonatomic, strong) NSString *output_buffer;+@property (nonatomic, assign) UInt8 *rgbData;+@property (nonatomic, assign) UInt8 *last_rgbData;+@property (nonatomic, strong) NSSet<NSNumber *> *yoloIndexSet;+@property (nonatomic, strong) NSString *sessionID;+- (NSArray *)yolo_infer:(CGImageRef)cgImage withOrientation:(AVCaptureVideoOrientation)orientation;++// Initializer+- (instancetype)init;+- (NSMutableDictionary<NSString *, id> *)extractValues:(NSString *)x;++@end++NS_ASSUME_NONNULL_END+diff --git a/ios/clearcam/Yolo.m b/ios/clearcam/Yolo.mnew file mode 100644index 0000000..95a1b87--- /dev/null+++ b/ios/clearcam/Yolo.m@@ -0,0 +1,407 @@+#import "Yolo.h"+#import <Metal/Metal.h>+#import <UIKit/UIKit.h>+#import <sys/utsname.h>+#import "SettingsManager.h"+#include <arm_neon.h>++@implementation Yolo++id<MTLDevice> device;+NSMutableDictionary<NSString *, id> *pipeline_states;+NSMutableDictionary<NSString *, id> *buffers;+id<MTLCommandQueue> mtl_queue;+NSMutableArray<id<MTLCommandBuffer>> *mtl_buffers_in_flight;+int yolo_res;+NSArray *yolo_classes;+CFDataRef data;+NSMutableDictionary *_h;+NSMutableArray *_q;+NSString *input_buffer;+NSString *output_buffer;+UInt8 *rgbData;+UInt8 *last_rgbData; //for diff+NSString *sessionID;++- (instancetype)init {+ self = [super init];+ self.device = MTLCreateSystemDefaultDevice();+ self.pipeline_states = [[NSMutableDictionary alloc] init];+ self.buffers = [[NSMutableDictionary alloc] init];+ self.mtl_queue = [self.device newCommandQueueWithMaxCommandBufferCount:1024];+ self.mtl_buffers_in_flight = [[NSMutableArray alloc] init];+ self.yolo_res = 640;+ self.rgbData = (UInt8 *)malloc(self.yolo_res * self.yolo_res * 3);+ self.last_rgbData = (UInt8 *)malloc(self.yolo_res * self.yolo_res * 3);+++ self.yolo_classes = @[+ @[NSLocalizedString(@"person", nil), [UIColor redColor]],+ @[NSLocalizedString(@"bicycle", nil), [UIColor greenColor]],+ @[NSLocalizedString(@"car", nil), [UIColor blueColor]],+ @[NSLocalizedString(@"motorcycle", nil), [UIColor cyanColor]],+ @[NSLocalizedString(@"airplane", nil), [UIColor magentaColor]],+ @[NSLocalizedString(@"bus", nil), [UIColor yellowColor]],+ @[NSLocalizedString(@"train", nil), [UIColor orangeColor]],+ @[NSLocalizedString(@"truck", nil), [UIColor purpleColor]],+ @[NSLocalizedString(@"boat", nil), [UIColor brownColor]],+ @[NSLocalizedString(@"traffic light", nil), [UIColor colorWithRed:0.5 green:0.7 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"fire hydrant", nil), [UIColor colorWithRed:0.8 green:0.1 blue:0.1 alpha:1.0]],+ @[NSLocalizedString(@"stop sign", nil), [UIColor colorWithRed:0.3 green:0.3 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"parking meter", nil), [UIColor colorWithRed:0.7 green:0.5 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"bench", nil), [UIColor colorWithRed:0.4 green:0.4 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"bird", nil), [UIColor colorWithRed:0.1 green:0.5 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"cat", nil), [UIColor colorWithRed:0.8 green:0.2 blue:0.6 alpha:1.0]],+ @[NSLocalizedString(@"dog", nil), [UIColor colorWithRed:0.9 green:0.3 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"horse", nil), [UIColor colorWithRed:0.2 green:0.6 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"sheep", nil), [UIColor colorWithRed:0.7 green:0.3 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"cow", nil), [UIColor colorWithRed:0.4 green:0.8 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"elephant", nil), [UIColor colorWithRed:0.3 green:0.4 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"bear", nil), [UIColor colorWithRed:0.6 green:0.2 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"zebra", nil), [UIColor colorWithRed:0.8 green:0.5 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"giraffe", nil), [UIColor colorWithRed:0.5 green:0.9 blue:0.1 alpha:1.0]],+ @[NSLocalizedString(@"backpack", nil), [UIColor colorWithRed:0.3 green:0.7 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"umbrella", nil), [UIColor colorWithRed:0.4 green:0.6 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"handbag", nil), [UIColor colorWithRed:0.9 green:0.2 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"tie", nil), [UIColor colorWithRed:0.5 green:0.3 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"suitcase", nil), [UIColor colorWithRed:0.6 green:0.7 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"frisbee", nil), [UIColor colorWithRed:0.7 green:0.2 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"skis", nil), [UIColor colorWithRed:0.3 green:0.9 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"snowboard", nil), [UIColor colorWithRed:0.8 green:0.1 blue:0.6 alpha:1.0]],+ @[NSLocalizedString(@"sports ball", nil), [UIColor colorWithRed:0.4 green:0.3 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"kite", nil), [UIColor colorWithRed:0.2 green:0.5 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"baseball bat", nil), [UIColor colorWithRed:0.6 green:0.4 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"baseball glove", nil), [UIColor colorWithRed:0.7 green:0.1 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"skateboard", nil), [UIColor colorWithRed:0.5 green:0.8 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"surfboard", nil), [UIColor colorWithRed:0.8 green:0.3 blue:0.6 alpha:1.0]],+ @[NSLocalizedString(@"tennis racket", nil), [UIColor colorWithRed:0.2 green:0.7 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"bottle", nil), [UIColor colorWithRed:0.9 green:0.2 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"wine glass", nil), [UIColor colorWithRed:0.6 green:0.6 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"cup", nil), [UIColor colorWithRed:0.3 green:0.4 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"fork", nil), [UIColor colorWithRed:0.4 green:0.7 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"knife", nil), [UIColor colorWithRed:0.8 green:0.2 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"spoon", nil), [UIColor colorWithRed:0.6 green:0.3 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"bowl", nil), [UIColor colorWithRed:0.2 green:0.8 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"banana", nil), [UIColor colorWithRed:0.7 green:0.7 blue:0.1 alpha:1.0]],+ @[NSLocalizedString(@"apple", nil), [UIColor colorWithRed:0.9 green:0.1 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"sandwich", nil), [UIColor colorWithRed:0.4 green:0.5 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"orange", nil), [UIColor colorWithRed:0.8 green:0.6 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"broccoli", nil), [UIColor colorWithRed:0.3 green:0.8 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"carrot", nil), [UIColor colorWithRed:0.7 green:0.2 blue:0.6 alpha:1.0]],+ @[NSLocalizedString(@"hot dog", nil), [UIColor colorWithRed:0.9 green:0.3 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"pizza", nil), [UIColor colorWithRed:0.5 green:0.3 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"donut", nil), [UIColor colorWithRed:0.8 green:0.1 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"cake", nil), [UIColor colorWithRed:0.7 green:0.5 blue:0.1 alpha:1.0]],+ @[NSLocalizedString(@"chair", nil), [UIColor colorWithRed:0.6 green:0.2 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"couch", nil), [UIColor colorWithRed:0.4 green:0.6 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"potted plant", nil), [UIColor colorWithRed:0.8 green:0.4 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"bed", nil), [UIColor colorWithRed:0.3 green:0.7 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"dining table", nil), [UIColor colorWithRed:0.5 green:0.8 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"toilet", nil), [UIColor colorWithRed:0.7 green:0.4 blue:0.6 alpha:1.0]],+ @[NSLocalizedString(@"tv", nil), [UIColor colorWithRed:0.9 green:0.5 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"laptop", nil), [UIColor colorWithRed:0.6 green:0.3 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"mouse", nil), [UIColor colorWithRed:0.2 green:0.9 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"remote", nil), [UIColor colorWithRed:0.8 green:0.4 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"keyboard", nil), [UIColor colorWithRed:0.3 green:0.6 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"cell phone", nil), [UIColor colorWithRed:0.7 green:0.3 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"microwave", nil), [UIColor colorWithRed:0.4 green:0.9 blue:0.4 alpha:1.0]],+ @[NSLocalizedString(@"oven", nil), [UIColor colorWithRed:0.5 green:0.7 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"toaster", nil), [UIColor colorWithRed:0.9 green:0.2 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"sink", nil), [UIColor colorWithRed:0.6 green:0.8 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"refrigerator", nil), [UIColor colorWithRed:0.8 green:0.4 blue:0.7 alpha:1.0]],+ @[NSLocalizedString(@"book", nil), [UIColor colorWithRed:0.3 green:0.5 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"clock", nil), [UIColor colorWithRed:0.7 green:0.7 blue:0.2 alpha:1.0]],+ @[NSLocalizedString(@"vase", nil), [UIColor colorWithRed:0.9 green:0.4 blue:0.5 alpha:1.0]],+ @[NSLocalizedString(@"scissors", nil), [UIColor colorWithRed:0.2 green:0.7 blue:0.8 alpha:1.0]],+ @[NSLocalizedString(@"teddy bear", nil), [UIColor colorWithRed:0.6 green:0.3 blue:0.9 alpha:1.0]],+ @[NSLocalizedString(@"hair drier", nil), [UIColor colorWithRed:0.8 green:0.2 blue:0.3 alpha:1.0]],+ @[NSLocalizedString(@"toothbrush", nil), [UIColor colorWithRed:0.4 green:0.7 blue:0.6 alpha:1.0]]+ ];++ NSString *fileName = @"batch_data";+ NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];+ NSData *ns_data = nil;+ if (filePath) ns_data = [NSData dataWithContentsOfFile:filePath];++ self.data = CFDataCreate(NULL, [ns_data bytes], [ns_data length]);++ const UInt8 *bytes = CFDataGetBytePtr(self.data);+ NSInteger length = CFDataGetLength(self.data);+ NSData *range_data;+ self._h = [[NSMutableDictionary alloc] init];+ NSInteger ptr = 0;+ NSString *string_data;+ NSMutableString *datahash = [NSMutableString stringWithCapacity:0x40];+ while (ptr < length) {+ NSData *slicedData = [NSData dataWithBytes:bytes + ptr + 0x20 length:0x28 - 0x20];+ uint64_t datalen = 0;+ [slicedData getBytes:&datalen length:sizeof(datalen)];+ datalen = CFSwapInt64LittleToHost(datalen);+ const UInt8 *datahash_bytes = bytes + ptr;+ datahash = [NSMutableString stringWithCapacity:0x40];+ for (int i = 0; i < 0x20; i++) {+ [datahash appendFormat:@"%02x", datahash_bytes[i]];+ }+ range_data = [NSData dataWithBytes:bytes + (ptr + 0x28) length:datalen];+ self._h[datahash] = range_data;+ ptr += 0x28 + datalen;+ }+ CFRelease(self.data);+ string_data = [[NSString alloc] initWithData:range_data encoding:NSUTF8StringEncoding];+ self._q = [NSMutableArray array];+ NSMutableArray *_q_exec = [NSMutableArray array];+ NSArray *ops = @[@"BufferAlloc", @"CopyIn", @"ProgramAlloc",@"ProgramExec",@"CopyOut"];+ NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)\\(", [ops componentsJoinedByString:@"|"]] options:0 error:nil];+ __block NSInteger lastIndex = 0;+ [regex enumerateMatchesInString:string_data options:0 range:NSMakeRange(0, string_data.length) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {+ [self._q addObject:[self extractValues:([[string_data substringWithRange:NSMakeRange(lastIndex, match.range.location - lastIndex)] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]])]];+ lastIndex = match.range.location;+ }];+ [self._q addObject:[self extractValues:([[string_data substringFromIndex:lastIndex] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]])]];+ for (NSMutableDictionary *values in self._q) {+ if ([values[@"op"] isEqualToString:@"BufferAlloc"]) {+ [self.buffers setObject:[self.device newBufferWithLength:[values[@"size"][0] intValue] options:MTLResourceStorageModeShared] forKey:values[@"buffer_num"][0]];+ } else if ([values[@"op"] isEqualToString:@"CopyIn"]) {+ id<MTLBuffer> buffer = self.buffers[values[@"buffer_num"][0]];+ NSData *data = self._h[values[@"datahash"][0]];+ memcpy(buffer.contents, data.bytes, data.length);+ self.input_buffer = values[@"buffer_num"][0];+ } else if ([values[@"op"] isEqualToString:@"ProgramAlloc"]) {+ NSString *key = [NSString stringWithFormat:@"%@_%@", values[@"name"][0], values[@"datahash"][0]];+ if ([self.pipeline_states objectForKey:key]) continue;+ NSString *prg = [[NSString alloc] initWithData:self._h[values[@"datahash"][0]] encoding:NSUTF8StringEncoding];+ NSError *error = nil;+ id<MTLLibrary> library = [self.device newLibraryWithSource:prg+ options:nil+ error:&error];+ MTLComputePipelineDescriptor *descriptor = [[MTLComputePipelineDescriptor alloc] init];+ descriptor.computeFunction = [library newFunctionWithName:values[@"name"][0]];;+ descriptor.supportIndirectCommandBuffers = YES;+ MTLComputePipelineReflection *reflection = nil;+ id<MTLComputePipelineState> pipeline_state = [self.device newComputePipelineStateWithDescriptor:descriptor+ options:MTLPipelineOptionNone+ reflection:&reflection+ error:&error];+ [self.pipeline_states setObject:pipeline_state forKey:@[values[@"name"][0],values[@"datahash"][0]]];+ } else if ([values[@"op"] isEqualToString:@"ProgramExec"]) {+ [_q_exec addObject:values];+ } else if ([values[@"op"] isEqualToString:@"CopyOut"]) {+ self.output_buffer = values[@"buffer_num"][0];+ }+ }+ self._q = [_q_exec mutableCopy];+ [self._h removeAllObjects];++ return self;+}++// Extract values from a string+- (NSMutableDictionary<NSString *, id> *)extractValues:(NSString *)x {+ NSMutableDictionary<NSString *, id> *values = [@{@"op": [x componentsSeparatedByString:@"("][0]} mutableCopy];+ NSDictionary<NSString *, NSString *> *patterns = @{@"name": @"name='([^']+)'", @"datahash": @"datahash='([^']+)'", @"global_sizes": @"global_size=\\(([^)]+)\\)",+ @"local_sizes": @"local_size=\\(([^)]+)\\)", @"bufs": @"bufs=\\(([^)]+)",+ @"vals": @"vals=\\(([^)]+)", @"buffer_num": @"buffer_num=(\\d+)", @"size": @"size=(\\d+)"};+ [patterns enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *pattern, BOOL *stop) {+ NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];+ NSTextCheckingResult *match = [regex firstMatchInString:x options:0 range:NSMakeRange(0, x.length)];+ if (match) {+ NSString *contents = [x substringWithRange:[match rangeAtIndex:1]];+ NSMutableArray<NSString *> *extracted_values = [NSMutableArray array];+ for (NSString *value in [contents componentsSeparatedByString:@","]) {+ NSString *trimmed_value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];+ if (trimmed_value.length > 0) {+ [extracted_values addObject:trimmed_value];+ }+ }+ values[key] = [extracted_values copy];+ }+ }];+ return values;+}++- (NSArray *)yolo_infer:(CGImageRef)cgImage withOrientation:(AVCaptureVideoOrientation)orientation {++ NSDictionary<NSString *, NSArray<NSNumber *> *> *presets = [[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_presets"];+ NSString *presetKey = [[NSUserDefaults standardUserDefaults] objectForKey:@"yolo_preset_idx"];++ NSArray<NSNumber *> *presetIndexes = presets[presetKey];+ if ([presetIndexes isKindOfClass:[NSArray class]]) {+ self.yoloIndexSet = [NSSet setWithArray:presetIndexes]; //todo, make into a set!+ } else {+ NSLog(@"Invalid preset key or data format");+ self.yoloIndexSet = [NSSet set];+ }+++ CFDataRef rawData = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));+ if (!rawData) return nil;++ const UInt8 *rawBytes = CFDataGetBytePtr(rawData);+ size_t length = CFDataGetLength(rawData);+ size_t width = CGImageGetWidth(cgImage);+ size_t height = CGImageGetHeight(cgImage);+ size_t rgbLength = (length / 4) * 3;++ if (orientation == AVCaptureVideoOrientationLandscapeRight) {+ for (size_t i = 0, j = 0; i < length; i += 4, j += 3) {+ self.rgbData[j] = rawBytes[i];+ self.rgbData[j + 1] = rawBytes[i + 1];+ self.rgbData[j + 2] = rawBytes[i + 2];+ }+ } else if (orientation == AVCaptureVideoOrientationLandscapeLeft) {+ for (size_t i = 0, j = 0; i < length; i += 4, j += 3) {+ self.rgbData[rgbLength - 1 - j - 2] = rawBytes[i];+ self.rgbData[rgbLength - 1 - j - 1] = rawBytes[i + 1];+ self.rgbData[rgbLength - 1 - j] = rawBytes[i + 2];+ }+ } else if (orientation == AVCaptureVideoOrientationPortrait) {+ for (size_t i = 0; i < length; i += 4) {+ int row = (int)(i / (width * 4));+ int col = (int)((i % (width * 4)) / 4);+ self.rgbData[col * (width * 3) + ((height - 1 - row) * 3)] = rawBytes[i];+ self.rgbData[col * (width * 3) + ((height - 1 - row) * 3) + 1] = rawBytes[i + 1];+ self.rgbData[col * (width * 3) + ((height - 1 - row) * 3) + 2] = rawBytes[i + 2];+ }+ }++ CFRelease(rawData);++ if ([[NSUserDefaults standardUserDefaults] boolForKey:@"useOwnInferenceServerEnabled"]) {+ int total_bytes = self.yolo_res * self.yolo_res * 3;+ int diff_count = 0;+ int diff_limit = total_bytes / 10; // 10%+ uint8_t *diff_buffer = malloc(total_bytes);+ int diff_offset = 0;+ uint8_t *curr = self.rgbData;+ uint8_t *prev = self.last_rgbData;++ for (int i = 0; i < total_bytes; i++) {+ int delta = (int)curr[i] - (int)prev[i];+ if (delta > 10 || delta < -10) {+ prev[i] = curr[i];+ diff_count++;+ int32_t index = i;+ *(int32_t *)(diff_buffer + diff_offset) = index;+ diff_offset += 4;+ diff_buffer[diff_offset++] = curr[i];++ if (diff_count >= diff_limit) {+ memcpy(prev, curr, total_bytes);+ NSArray *yoloResults = [self sendYOLORequestWithDiffData:nil length:0];+ if (yoloResults.count > 0) {+ free(diff_buffer);+ return yoloResults;+ }+ break;+ }+ }+ }+ NSArray *yoloResults = [self sendYOLORequestWithDiffData:diff_buffer length:diff_offset];+ free(diff_buffer);+ if (yoloResults.count > 0) return yoloResults;+ }++ id<MTLBuffer> buffer = self.buffers[self.input_buffer];+ if (!buffer || !buffer.contents) return nil;++ memset(buffer.contents, 0, buffer.length);+ memcpy(buffer.contents, self.rgbData, MIN(buffer.length, width * width * 3));++ for (NSMutableDictionary *values in self._q) {+ id<MTLCommandBuffer> commandBuffer = [self.mtl_queue commandBuffer];+ if (!commandBuffer) continue;+ id<MTLComputeCommandEncoder> encoder = [commandBuffer computeCommandEncoder];+ if (!encoder) continue;++ [encoder setComputePipelineState:self.pipeline_states[@[values[@"name"][0], values[@"datahash"][0]]]]; //ignore warning+ for (int i = 0; i < [(NSArray *)values[@"bufs"] count]; i++) {+ [encoder setBuffer:self.buffers[values[@"bufs"][i]] offset:0 atIndex:i];+ }+ for (int i = 0; i < [(NSArray *)values[@"vals"] count]; i++) {+ NSInteger value = [values[@"vals"][i] integerValue];+ [encoder setBytes:&value length:sizeof(NSInteger) atIndex:i + [(NSArray *)values[@"bufs"] count]];+ }++ MTLSize globalSize = MTLSizeMake([values[@"global_sizes"][0] intValue], [values[@"global_sizes"][1] intValue], [values[@"global_sizes"][2] intValue]);+ MTLSize localSize = MTLSizeMake([values[@"local_sizes"][0] intValue], [values[@"local_sizes"][1] intValue], [values[@"local_sizes"][2] intValue]);+ [encoder dispatchThreadgroups:globalSize threadsPerThreadgroup:localSize];+ [encoder endEncoding];+ [commandBuffer commit];+ [self.mtl_buffers_in_flight addObject:commandBuffer];+ }++ for (int i = 0; i < self.mtl_buffers_in_flight.count; i++) {+ [self.mtl_buffers_in_flight[i] waitUntilCompleted];+ }+ [self.mtl_buffers_in_flight removeAllObjects];++ buffer = self.buffers[self.output_buffer];+ if (!buffer || !buffer.contents) return nil;++ const void *bufferPointer = buffer.contents;+ float *floatArray = malloc(buffer.length);+ if (!floatArray) return nil;+ memcpy(floatArray, bufferPointer, buffer.length);+ NSMutableArray *output = [[NSMutableArray alloc] init];+ for(int i = 0; i < buffer.length/4; i+=6){ //4 sides + class + conf = 6+ if ([self.yoloIndexSet containsObject:@(floatArray[i + 5])] && floatArray[i + 4] > ([[[NSUserDefaults standardUserDefaults] objectForKey:@"threshold"] ?: @(25) floatValue] / 100.0)) {+ NSArray *shape = @[+ @(floatArray[i]),+ @(floatArray[i+1]),+ @(floatArray[i+2]),+ @(floatArray[i+3]),+ @(floatArray[i+5]), //switched 4 and 5 for now+ @(floatArray[i+4])+ ];+ [output addObject:shape];+ }+ }+ free(floatArray);+ return output;+}++- (NSArray *)sendYOLORequestWithDiffData:(uint8_t *)diffData length:(NSInteger)length {+ BOOL isDiff = (diffData != nil && length > 0);+ NSString *endpoint = isDiff ? @"diff" : @"yolo";+ NSURL *url = [NSURL URLWithString:[[[NSUserDefaults standardUserDefaults] stringForKey:@"own_inference_server_address"] stringByAppendingPathComponent:endpoint]];+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ [request setHTTPMethod:@"POST"];+ if (isDiff) {+ [request setHTTPBody:[NSData dataWithBytesNoCopy:diffData length:length freeWhenDone:NO]];+ } else {+ [request setHTTPBody:[NSData dataWithBytesNoCopy:self.rgbData length:self.yolo_res * self.yolo_res * 3 freeWhenDone:NO]];+ }+ if (self.sessionID) [request setValue:self.sessionID forHTTPHeaderField:@"x-session-id"];+ NSURLResponse *response = nil;+ NSError *error = nil;+ NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];+ if (error || !responseData) {+ return @[];+ }+ if (!self.sessionID && [response isKindOfClass:[NSHTTPURLResponse class]]) {+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;+ NSString *newSessionID = httpResponse.allHeaderFields[@"x-session-id"];+ if (newSessionID) self.sessionID = newSessionID;+ }+ float *floatArray = (float *)responseData.bytes;+ NSUInteger floatCount = responseData.length / sizeof(float);+ NSMutableArray *output = [NSMutableArray new];+ float threshold = [[[NSUserDefaults standardUserDefaults] objectForKey:@"threshold"] ?: @(25) floatValue] / 100.0;++ for (NSUInteger i = 0; i < floatCount; i += 6) {+ float confidence = floatArray[i + 4];+ NSNumber *classId = @(floatArray[i + 5]);+ if ([self.yoloIndexSet containsObject:classId] && confidence > threshold) {+ [output addObject:@[+ @(floatArray[i]), @(floatArray[i+1]),+ @(floatArray[i+2]), @(floatArray[i+3]),+ classId, @(confidence)+ ]];+ }+ }+ return output;+}++@end++diff --git a/ios/clearcam/batch_data b/ios/clearcam/batch_datanew file mode 100644index 0000000..d8aaa9aBinary files /dev/null and b/ios/clearcam/batch_data differdiff --git a/ios/clearcam/clearcam.entitlements b/ios/clearcam/clearcam.entitlementsnew file mode 100644index 0000000..903def2--- /dev/null+++ b/ios/clearcam/clearcam.entitlements@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>aps-environment</key>+ <string>development</string>+</dict>+</plist>diff --git a/ios/clearcam/en.lproj/Localizable.strings b/ios/clearcam/en.lproj/Localizable.stringsnew file mode 100644index 0000000..96ed356--- /dev/null+++ b/ios/clearcam/en.lproj/Localizable.strings@@ -0,0 +1,108 @@+"settings" = "Settings";+"events" = "Events";+"live"="Live";+"default_device_name" = "My Device";+"waiting_for_ip" = "Waiting for Wi-Fi...";+"streaming_over_wifi" = "Streaming over local Wi-Fi at: %@";+"permission_denied" = "Permission Denied";+"notification_permission_denied" = "Notification permission was denied. You can enable it in Settings.";+"ok" = "OK";+"enable_in_settings" = "Enable in Settings";+"notifications_disabled" = "Notifications are disabled. Please enable them in the Settings app.";+"camera_settings" = "Camera Settings";+"live_stream_settings" = "Live Stream Settings";+"viewer_settings" = "Viewer Settings";+"subscription" = "Subscription";+"upgrade_to_premium" = "Upgrade to Premium";+"stream_via_wifi" = "Stream via Wi-Fi";+"resolution" = "Resolution";+"detect_objects" = "Detect Objects";+"manage_detection_presets" = "Manage Detection Presets";+"detection_certainty_threshold" = "Detection Certainty Threshold";+"send_videos_on_detection" = "Send Videos on Detection";+"send_videos_description" = "Enable to view events on other devices from anywhere.";+"change_encryption_password" = "Change Encryption Password";+"manage_detection_schedules" = "Manage Detection Schedules";+"manage_detection_schedules_description" = "Choose when to detect objects.";+"use_own_notification_server" = "Use Own Notification Server";+"use_own_notification_server_description" = "Send videos to a server that you own.";+"server_address" = "Server Address";+"test_own_server" = "Test own server";+"use_own_inference_server" = "Use Own Inference Server";+"use_own_inference_server_description" = "Use a custom server for object detection.";+"enter_inference_server_address" = "Enter server address: e.g http://192.168.1.1:6667";+"live_stream_network" = "Live Stream over Network";+"device_name" = "Device Name";+"receive_notifications" = "Receive Notifications";+"receive_notifications_description" = "Get notified when a camera catches an event.";+"restore_purchases" = "Restore Purchases";+"terms_of_use" = "Terms of Use";+"privacy_policy" = "Privacy Policy";+"delete_encryption_keys" = "Delete Encryption Keys";+"enter_inference_server_address_title" = "Enter Inference Server Address";+"enter_inference_server_address_message" = "Please enter the address of your inference server.";+"server_address_label" = "Server Address";+"save" = "Save";+"cancel" = "Cancel";+"set_threshold_title" = "Set Threshold";+"set_threshold_message" = "Enter a % value between 1 and 100 (default is 25).";+"threshold_placeholder" = "Threshold (1-100)";+"invalid_threshold_title" = "Invalid Threshold";+"invalid_threshold_message" = "Please enter a valid value between 1 and 100";+"set_device_name_title" = "Set Device Name";+"set_device_name_message" = "Enter a name for this device.";+"device_name_placeholder" = "Device Name";+"delete_encryption_keys_title" = "Delete Encryption Keys";+"delete_encryption_keys_message" = "Are you sure you want to delete all keys from this device?";+"delete" = "Yes";+"price_unknown" = "Price";+"get_premium_title" = "Get Clearcam Premium";+"premium_feature_1" = "View captured events from anywhere";+"premium_feature_2" = "Receive real-time event notifications";+"premium_feature_3" = "Live stream from anywhere";+"premium_feature_4" = "End-to-end encryption on all camera data sent from your phone.";+"upgrade_button" = "Upgrade for %@ per month";+"not_now" = "Not now";+"premium_disclaimer" = "Monthly limit of 5,000 clip uploads and 1,000 minutes or sessions of live stream viewing.";+"purchase_failed" = "Purchase Failed";+"enter_notification_server_address_title" = "Enter Server Address";+"enter_notification_server_address_message" = "Please enter the address of your notification server.";+"test_notification_sent_title" = "Sent";+"test_notification_sent_message" = "Test notification sent. Check your server.";+"set_password_title" = "Set Password";+"set_password_message" = "Enter a password to encrypt your data";+"password_placeholder" = "Password";+"confirm_password_placeholder" = "Confirm Password";+"invalid_password_title" = "Invalid Password";+"invalid_password_message" = "Passwords do not match or are empty.";+"select_resolution_title" = "Select Resolution";+"select_objects_preset_title" = "Select objects preset";+"add_preset_title" = "Add Preset";+"add_preset_message" = "Enter a name for the new preset";+"preset_name_placeholder" = "Preset Name";+"restoring_purchases_title" = "Restoring Purchases";+"restoring_purchases_message" = "Please wait while we restore your previous purchases...";+"steps_text_live" = "1. Install Clearcam on another phone or rtsp enabled camera.\n2. Upgrade to Clearcam Premium.\n3. Turn on \"Live Stream over Network\" on your other phone (or live on your computer) and choose a secure password and device name.\n4. Start recording.";+"steps_text_clips" = "1. Install Clearcam on another phone or rtsp enabled camera.\n2. Upgrade to Clearcam Premium.\n3. Turn on \"Send Videos on Detection\" (or notifications on your computer) and choose a secure password.\n4. (Optional) Configure your detection settings and schedule.\n5. Start recording.\n";+"no_live_devices" = "No Live Devices\n";+"no_videos_available" = "No Videos Available\n";+"share" = "Share";+"delete" = "Delete";+"cancel" = "Cancel";+"online" = "Online";+"experimental_features" = "Experimental Features";+"docs" = "Docs";+"app_name" = "Clearcam";+"home" = "Home";+"camera_desc" = "Record and broadcast footage, with AI object detection";+"gallery_desc" = "View captured events and live camera feeds (Premium required)";+"settings_desc" = "Configure cameras and detection";+"all" = "all";+"people+vehicles" = "people+vehicles";++"authenticate_to_view_user_id" = "authenticate to view your userID.";+"tap_for_userid" = "Tap to reveal your user ID, do not share this.";+"id_copied" = "UserID copied to clipboard.";+"copied" = "Copied";+"userid" = "UserID";+diff --git a/ios/clearcam/es.lproj/Localizable.strings b/ios/clearcam/es.lproj/Localizable.stringsnew file mode 100644index 0000000..4ba81f8--- /dev/null+++ b/ios/clearcam/es.lproj/Localizable.strings@@ -0,0 +1,188 @@+"settings" = "Ajustes";+"events" = "Eventos";+"live" = "En vivo";+"default_device_name" = "Mi dispositivo";+"waiting_for_ip" = "Esperando Wi-Fi...";+"streaming_over_wifi" = "Transmitiendo por Wi-Fi local en: %@";+"permission_denied" = "Permiso denegado";+"notification_permission_denied" = "Permiso de notificaciones denegado. Actívalo en Ajustes.";+"ok" = "Aceptar";+"enable_in_settings" = "Activar en Ajustes";+"notifications_disabled" = "Notificaciones desactivadas. Actívalas en Ajustes.";+"camera_settings" = "Ajustes de cámara";+"live_stream_settings" = "Ajustes de transmisión";+"viewer_settings" = "Ajustes del visor";+"subscription" = "Suscripción";+"upgrade_to_premium" = "Mejorar a Premium";+"stream_via_wifi" = "Transmitir por Wi-Fi";+"resolution" = "Resolución";+"detect_objects" = "Detectar objetos";+"manage_detection_presets" = "Gestionar presets";+"detection_certainty_threshold" = "Umbral de detección";+"send_videos_on_detection" = "Enviar videos al detectar";+"send_videos_description" = "Actívalo para ver eventos en otros dispositivos.";+"change_encryption_password" = "Cambiar contraseña";+"manage_detection_schedules" = "Gestionar horarios";+"manage_detection_schedules_description" = "Elige cuándo detectar objetos.";+"use_own_notification_server" = "Usar servidor propio";+"use_own_notification_server_description" = "Envía videos a tu servidor.";+"server_address" = "Dirección del servidor";+"test_own_server" = "Probar servidor";+"use_own_inference_server" = "Usar servidor de inferencia";+"use_own_inference_server_description" = "Usa un servidor personalizado.";+"enter_inference_server_address" = "Dirección del servidor: ej. http://192.168.1.1:6667";+"live_stream_network" = "Transmisión en red";+"device_name" = "Nombre del dispositivo";+"receive_notifications" = "Recibir notificaciones";+"receive_notifications_description" = "Notificaciones al detectar eventos.";+"restore_purchases" = "Restaurar compras";+"terms_of_use" = "Términos de uso";+"privacy_policy" = "Política de privacidad";+"delete_encryption_keys" = "Eliminar claves";+"enter_inference_server_address_title" = "Dirección del servidor";+"enter_inference_server_address_message" = "Ingresa la dirección del servidor.";+"server_address_label" = "Dirección del servidor";+"save" = "Guardar";+"cancel" = "Cancelar";+"set_threshold_title" = "Establecer umbral";+"set_threshold_message" = "Ingresa un valor entre 1 y 100 (predeterminado: 25).";+"threshold_placeholder" = "Umbral (1-100)";+"invalid_threshold_title" = "Umbral inválido";+"invalid_threshold_message" = "Ingresa un valor entre 1 y 100.";+"set_device_name_title" = "Nombre del dispositivo";+"set_device_name_message" = "Ingresa un nombre para este dispositivo.";+"device_name_placeholder" = "Nombre del dispositivo";+"delete_encryption_keys_title" = "Eliminar claves";+"delete_encryption_keys_message" = "¿Seguro que quieres eliminar todas las claves?";+"delete" = "Sí";+"price_unknown" = "Precio";+"get_premium_title" = "Obtener Clearcam Premium";+"premium_feature_1" = "Ver eventos desde cualquier lugar";+"premium_feature_2" = "Notificaciones en tiempo real";+"premium_feature_3" = "Transmisión en vivo remota";+"premium_feature_4" = "Cifrado de extremo a extremo.";+"upgrade_button" = "Mejorar por %@/mes";+"not_now" = "Ahora no";+"premium_disclaimer" = "Límite mensual: 5,000 clips y 1,000 minutos de transmisión.";+"purchase_failed" = "Error de compra";+"enter_notification_server_address_title" = "Dirección del servidor";+"enter_notification_server_address_message" = "Ingresa la dirección del servidor.";+"test_notification_sent_title" = "Enviado";+"test_notification_sent_message" = "Notificación de prueba enviada. Verifica tu servidor.";+"set_password_title" = "Establecer contraseña";+"set_password_message" = "Ingresa una contraseña para cifrar los datos.";+"password_placeholder" = "Contraseña";+"confirm_password_placeholder" = "Confirmar contraseña";+"invalid_password_title" = "Contraseña inválida";+"invalid_password_message" = "Las contraseñas no coinciden.";+"select_resolution_title" = "Seleccionar resolución";+"select_objects_preset_title" = "Seleccionar preset";+"add_preset_title" = "Agregar preset";+"add_preset_message" = "Ingresa un nombre para el preset.";+"preset_name_placeholder" = "Nombre del preset";+"restoring_purchases_title" = "Restaurando compras";+"restoring_purchases_message" = "Restaurando tus compras...";+"steps_text_live" = "1. Instala Clearcam en otro teléfono o cámara compatible con RTSP.\n2. Actualiza a Clearcam Premium.\n3. Activa \"Transmisión en vivo por red\" en tu otro teléfono (o en la computadora) y elige una contraseña segura y nombre del dispositivo.\n4. Comienza a grabar.";+"steps_text_clips" = "1. Instala Clearcam en otro teléfono o cámara compatible con RTSP.\n2. Actualiza a Clearcam Premium.\n3. Activa \"Enviar videos al detectar movimiento\" (o notificaciones en tu computadora) y elige una contraseña segura.\n4. (Opcional) Configura los ajustes de detección y horario.\n5. Comienza a grabar.";+"no_live_devices" = "No hay dispositivos en vivo\n";+"no_videos_available" = "No hay videos disponibles\n";+"share" = "Compartir";+"delete" = "Eliminar";+"cancel" = "Cancelar";+"online" = "En línea";+"experimental_features" = "Funciones experimentales";+"docs" = "Documentación";+"app_name" = "Clearcam";+"home" = "Inicio";+"camera_desc" = "Graba y transmite imágenes con detección de objetos por IA";+"gallery_desc" = "Ve eventos capturados y transmisiones en vivo (se requiere Premium)";+"settings_desc" = "Configura cámaras y detección";+"all" = "todos";+"people+vehicles" = "personas+vehículos";++"authenticate_to_view_user_id" = "Autentícate para ver tu ID de usuario.";+"tap_for_userid" = "Toca para revelar tu ID de usuario, no lo compartas.";+"id_copied" = "ID de usuario copiado al portapapeles.";+"copied" = "Copiado";+"userid" = "ID de usuario";++"person" = "persona";+"bicycle" = "bicicleta";+"car" = "coche";+"motorcycle" = "motocicleta";+"airplane" = "avión";+"bus" = "autobús";+"train" = "tren";+"truck" = "camión";+"boat" = "barco";+"traffic light" = "semáforo";+"fire hydrant" = "hidrante";+"stop sign" = "señal de stop";+"parking meter" = "parquímetro";+"bench" = "banco";+"bird" = "pájaro";+"cat" = "gato";+"dog" = "perro";+"horse" = "caballo";+"sheep" = "oveja";+"cow" = "vaca";+"elephant" = "elefante";+"bear" = "oso";+"zebra" = "cebra";+"giraffe" = "jirafa";+"backpack" = "mochila";+"umbrella" = "paraguas";+"handbag" = "bolso";+"tie" = "corbata";+"suitcase" = "maleta";+"frisbee" = "frisbee";+"skis" = "esquís";+"snowboard" = "snowboard";+"sports ball" = "pelota";+"kite" = "cometa";+"baseball bat" = "bate de béisbol";+"baseball glove" = "guante de béisbol";+"skateboard" = "monopatín";+"surfboard" = "tabla de surf";+"tennis racket" = "raqueta de tenis";+"bottle" = "botella";+"wine glass" = "copa de vino";+"cup" = "taza";+"fork" = "tenedor";+"knife" = "cuchillo";+"spoon" = "cuchara";+"bowl" = "cuenco";+"banana" = "plátano";+"apple" = "manzana";+"sandwich" = "sándwich";+"orange" = "naranja";+"broccoli" = "brócoli";+"carrot" = "zanahoria";+"hot dog" = "perrito caliente";+"pizza" = "pizza";+"donut" = "dónut";+"cake" = "pastel";+"chair" = "silla";+"couch" = "sofá";+"potted plant" = "planta en maceta";+"bed" = "cama";+"dining table" = "mesa de comedor";+"toilet" = "inodoro";+"tv" = "televisor";+"laptop" = "portátil";+"mouse" = "ratón";+"remote" = "mando";+"keyboard" = "teclado";+"cell phone" = "teléfono móvil";+"microwave" = "microondas";+"oven" = "horno";+"toaster" = "tostadora";+"sink" = "fregadero";+"refrigerator" = "refrigerador";+"book" = "libro";+"clock" = "reloj";+"vase" = "florero";+"scissors" = "tijeras";+"teddy bear" = "oso de peluche";+"hair drier" = "secador de pelo";+"toothbrush" = "cepillo de dientes";diff --git a/ios/clearcam/events.html b/ios/clearcam/events.htmlnew file mode 100644index 0000000..56d7c1f--- /dev/null+++ b/ios/clearcam/events.html@@ -0,0 +1,602 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Events</title>+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">+ <script>+ // --- JAVASCRIPT ---+ let currentTimestamp = null;+ const defaultOffset = 30;+ let allEvents = [];+ let expandedDates = new Set();++ async function fetchEvents() {+ try {+ console.log('Fetching events...');+ const response = await fetch('/get-events'); // Adjust endpoint if needed+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);+ const events = await response.json();+ console.log('Events received:', events);+ allEvents = events;+ renderEvents(events);+ } catch (error) {+ console.error('Error fetching events:', error);+ document.getElementById('eventsContainer').innerHTML = '<p style="color:red;">Failed to load events. Check console for details.</p>';+ }+ }++ function renderEvents(events) {+ console.log('Rendering events:', events);+ const container = document.getElementById('eventsContainer');+ container.innerHTML = '';++ if (!events || events.length === 0) {+ container.innerHTML = '<p>No events available.</p>';+ return;+ }++ const sortedEvents = [...events].sort((a, b) => new Date(b.timeStamp) - new Date(a.timeStamp));+ const eventsByDate = {};+ sortedEvents.forEach(event => {+ const dateObj = new Date(event.timeStamp);+ const dateKey = dateObj.toDateString();+ if (!eventsByDate[dateKey]) {+ eventsByDate[dateKey] = [];+ }+ eventsByDate[dateKey].push(event);+ });++ const dateKeys = Object.keys(eventsByDate);+ // console.log('Date keys:', dateKeys); // Less noisy console++ dateKeys.forEach((dateKey, index) => { // Added index for default expand+ const isExpanded = expandedDates.has(dateKey) || (expandedDates.size === 0 && index === 0); // Expand first date by default++ const section = document.createElement('div');+ section.className = 'collapsible-section';++ const dateHeader = document.createElement('div');+ dateHeader.className = 'date-header';+ dateHeader.innerHTML = `+ <button class="toggle-btn" onclick="toggleSection(this, '${dateKey}')" aria-expanded="${isExpanded}">+ <i class="fas ${isExpanded ? 'fa-chevron-down' : 'fa-chevron-right'}"></i>+ </button>+ ${dateKey}+ `;+ // Make header clickable too+ dateHeader.onclick = (e) => { if (!e.target.closest('.toggle-btn')) toggleSection(dateHeader.querySelector('.toggle-btn'), dateKey); };+ section.appendChild(dateHeader);++ const dateContainer = document.createElement('div');+ dateContainer.className = 'date-events';+ // Use grid display, responsive rules will handle columns+ dateContainer.style.display = isExpanded ? 'grid' : 'none';++ eventsByDate[dateKey].forEach(event => {+ const dateObj = new Date(event.timeStamp);+ const year = dateObj.getFullYear();+ const month = String(dateObj.getMonth() + 1).padStart(2, '0');+ const day = String(dateObj.getDate()).padStart(2, '0');+ const date = `${year}-${month}-${day}`;+ const startSeconds = Math.max(0, dateObj.getHours() * 3600 + dateObj.getMinutes() * 60 + dateObj.getSeconds() - 2);++ const card = document.createElement('div');+ card.className = 'event-card';+ // *** HTML Correction: Added image-container, moved onclick, removed spacer ***+ card.innerHTML = `+ <div class="event-content">+ <div class="image-container" onclick="playEvent('${date}', ${startSeconds})">+ <img+ src="${event.imageURL || ''}"+ alt="Event Image on ${dateKey}"+ class="event-image"+ loading="lazy"+ data-retry="0"+ onerror="retryImageLoad(this, '${event.imageURL || ''}', 3)"+ >+ </div>+ <div class="button-group">+ <button class="action-btn download-btn" onclick="downloadEvent(${dateObj.getTime() / 1000})" title="Download Clip">+ <i class="fas fa-download"></i>+ </button>+ <button class="action-btn delete-btn" onclick="deleteEvent(this, ${dateObj.getTime() / 1000})" title="Delete Event">+ <i class="fas fa-trash"></i>+ </button>+ </div>+ </div>+ `;+ dateContainer.appendChild(card);+ });++ section.appendChild(dateContainer);+ container.appendChild(section);++ if (isExpanded) { // Ensure added only if it should be+ expandedDates.add(dateKey);+ }+ });++ const currentKeysSet = new Set(dateKeys);+ expandedDates.forEach(dateKey => {+ if (!currentKeysSet.has(dateKey)) {+ expandedDates.delete(dateKey);+ }+ });+ }++ function toggleSection(button, dateKey) {+ const section = button.closest('.collapsible-section');+ const content = section.querySelector('.date-events');+ const icon = button.querySelector('i');+ if (!content || !icon || !section) return;++ const isCurrentlyVisible = window.getComputedStyle(content).display !== 'none';++ if (!isCurrentlyVisible) {+ content.style.display = 'grid'; // Always use grid+ icon.classList.remove('fa-chevron-right');+ icon.classList.add('fa-chevron-down');+ button.setAttribute('aria-expanded', 'true');+ expandedDates.add(dateKey);+ } else {+ content.style.display = 'none';+ icon.classList.remove('fa-chevron-down');+ icon.classList.add('fa-chevron-right');+ button.setAttribute('aria-expanded', 'false');+ expandedDates.delete(dateKey);+ }+ }++ function retryImageLoad(imgElement, imageURL, maxRetries) {+ const retryCount = parseInt(imgElement.getAttribute('data-retry') || '0');+ if (retryCount < maxRetries) {+ imgElement.setAttribute('data-retry', retryCount + 1);+ const delay = Math.pow(2, retryCount) * 1000; // Exponential backoff+ setTimeout(() => {+ const cacheBuster = `?retry=${Date.now()}`;+ imgElement.src = imageURL + cacheBuster;+ }, delay);+ } else {+ imgElement.alt = 'Image failed to load';+ imgElement.style.display = 'none'; // Hide broken img icon+ const container = imgElement.closest('.image-container');+ if (container) {+ container.classList.add('image-load-failed');+ container.onclick = null;+ container.title = 'Image failed to load';+ }+ }+ }++ // *** Fast deleteEvent function (from Msg #18) ***+ async function deleteEvent(buttonElement, timeStamp) {+ const cardElement = buttonElement.closest('.event-card');+ if (!cardElement) {+ console.error('Could not find parent event card element.');+ return;+ }+ cardElement.style.opacity = '0.5'; // Visual feedback+ buttonElement.disabled = true;++ try {+ console.log('Deleting event with timestamp:', timeStamp);+ const response = await fetch(`/delete-event?timeStamp=${timeStamp}`, { method: 'GET' });++ if (!response.ok) {+ cardElement.style.opacity = '1'; // Restore on failure+ buttonElement.disabled = false;+ throw new Error(`Failed to delete event: ${response.status}`);+ }++ console.log('Event deleted successfully on server.');+ cardElement.remove(); // Remove directly from DOM++ // Update local array (helps 'Delete Range' accuracy)+ const indexToRemove = allEvents.findIndex(event => event.timeStamp === timeStamp * 1000);+ if (indexToRemove > -1) {+ allEvents.splice(indexToRemove, 1);+ }+ // DO NOT fetchEvents() here++ } catch (error) {+ console.error('Error deleting event:', error);+ alert(`Error deleting event: ${error.message}`);+ if (cardElement) cardElement.style.opacity = '1'; // Ensure restored on error+ if (buttonElement) buttonElement.disabled = false;+ }+ }++ function playEvent(date, startSeconds) {+ let referrer = '/';+ if (document.referrer) {+ referrer = document.referrer.split('?')[0];+ }+ if (referrer.endsWith('/events')) referrer = referrer.substring(0, referrer.lastIndexOf('/'));+ if (!referrer.endsWith('/')) referrer += '/';+ window.location.href = `${referrer}?date=${date}&start=${startSeconds}`;+ }++ function downloadEvent(timeStamp) {+ currentTimestamp = timeStamp;+ const eventTime = new Date(timeStamp * 1000);+ const startTime = new Date(eventTime.getTime() - defaultOffset * 1000);+ const endTime = new Date(eventTime.getTime() + defaultOffset * 1000);+ document.getElementById("startTime").value = formatDateTimeLocal(startTime);+ document.getElementById("endTime").value = formatDateTimeLocal(endTime);+ document.getElementById("timePickerModal").style.display = "block";+ }++ function showDeleteAllModal() {+ if (allEvents.length === 0) {+ alert("No events available to delete.");+ return;+ }+ // Use current state of allEvents+ const sortedEvents = [...allEvents].sort((a, b) => new Date(a.timeStamp) - new Date(b.timeStamp));+ const earliestTime = new Date(sortedEvents[0].timeStamp);+ const latestTime = new Date(sortedEvents[sortedEvents.length - 1].timeStamp);+ document.getElementById("deleteStartTime").value = formatDateTimeLocal(earliestTime);+ document.getElementById("deleteEndTime").value = formatDateTimeLocal(latestTime);+ document.getElementById("deleteAllModal").style.display = "block";+ }++ async function confirmDeleteAll() {+ const startTimeInput = document.getElementById("deleteStartTime").value;+ const endTimeInput = document.getElementById("deleteEndTime").value;+ if (!startTimeInput || !endTimeInput) return alert("Please select both start and end times.");++ const startTime = new Date(startTimeInput).getTime() / 1000;+ const endTime = new Date(endTimeInput).getTime() / 1000;+ if (isNaN(startTime) || isNaN(endTime)) return alert("Invalid date/time selected.");+ if (endTime < startTime) return alert("End time cannot be earlier than start time.");++ if (!confirm(`Are you sure you want to delete all events between ${new Date(startTime*1000).toLocaleString()} and ${new Date(endTime*1000).toLocaleString()}? This cannot be undone.`)) return;++ try {+ const response = await fetch(`/delete-event?timeStamp=${startTime}&end=${endTime}`, { method: 'GET' });+ if (!response.ok) throw new Error(`Failed to delete events batch: ${response.status}`);+ closeDeleteAllModal();+ expandedDates.clear(); // Must reset state+ fetchEvents(); // Full refresh needed here+ } catch (error) {+ console.error('Error deleting batch of events:', error);+ alert(`Failed to delete events: ${error.message}`);+ }+ }++ function closeDeleteAllModal() {+ document.getElementById("deleteAllModal").style.display = "none";+ }++ function formatDateTimeLocal(date) {+ const offset = date.getTimezoneOffset() * 60000;+ const localDate = new Date(date.getTime() - offset);+ return localDate.toISOString().slice(0, 19); // YYYY-MM-DDTHH:mm:ss+ }++ function confirmDownload() {+ const startTimeInput = document.getElementById("startTime").value;+ const endTimeInput = document.getElementById("endTime").value;+ if (!startTimeInput || !endTimeInput) return alert("Please select both start and end times.");++ const startTime = new Date(startTimeInput).getTime() / 1000;+ const endTime = new Date(endTimeInput).getTime() / 1000;+ if (isNaN(startTime) || isNaN(endTime)) return alert("Invalid date/time selected.");+ if (endTime <= startTime) return alert("End time must be after start time.");++ window.location.href = `/download?start=${startTime}&end=${endTime}`;+ closeModal();+ }++ function closeModal() {+ document.getElementById("timePickerModal").style.display = "none";+ }++ window.onclick = function(event) { // Close modal on overlay click+ const timeModal = document.getElementById("timePickerModal");+ const deleteModal = document.getElementById("deleteAllModal");+ if (event.target == timeModal) closeModal();+ if (event.target == deleteModal) closeDeleteAllModal();+ }++ window.onload = fetchEvents;++ </script>+ <style>+ /* --- CSS --- */+ :root { /* Define colors */+ --bg-color: #f4f4f4;+ --card-bg: white;+ --header-bg: #e9e9e9;+ --text-color: #333;+ --icon-color: #555;+ --icon-hover: #000;+ --image-bg: #eee; /* BG for aspect ratio box */+ --image-fail-bg: #fdd;+ --delete-color: red;+ --download-color: blue;+ --modal-bg: white;+ --modal-overlay: rgba(0,0,0,0.4);+ --btn-confirm-bg: #4CAF50;+ --btn-cancel-bg: #aaa;+ --btn-delete-bg: #e53935;+ }++ body {+ font-family: Arial, sans-serif;+ text-align: center;+ margin: 0;+ padding: 20px;+ background-color: var(--bg-color);+ color: var(--text-color);+ }++ #header { /* Simple header from user code */+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ margin-bottom: 20px;+ }++ #eventsContainer {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 15px; /* Increased gap slightly */+ width: 100%;+ }++ .collapsible-section {+ width: 100%;+ max-width: 1240px;+ }++ .date-header {+ display: flex;+ align-items: center;+ width: 100%;+ text-align: left;+ margin: 10px 0;+ color: var(--text-color);+ cursor: pointer;+ padding: 8px 10px; /* Padding */+ background-color: var(--header-bg); /* Background */+ border-radius: 5px; /* Rounded corners */+ box-sizing: border-box;+ transition: background-color 0.2s;+ }+ .date-header:hover {+ background-color: #ddd;+ }++ .toggle-btn {+ background: none;+ border: none;+ font-size: 1em;+ margin-right: 10px;+ cursor: pointer;+ color: var(--icon-color);+ padding: 0 5px;+ line-height: 1;+ flex-shrink: 0;+ }+ .toggle-btn:hover { color: var(--icon-hover); }++ .date-events {+ /* display: grid; is set via JS */+ grid-template-columns: 1fr; /* Default: single column */+ gap: 15px;+ width: 100%;+ padding: 0 5px; /* Minimal horizontal padding */+ box-sizing: border-box;+ }++ .event-card {+ background: var(--card-bg);+ padding: 15px;+ border-radius: 10px;+ box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);+ width: 100%;+ max-width: 600px; /* Max width for readability on smaller screens */+ box-sizing: border-box;+ margin: 0 auto; /* Center card in grid areas */+ transition: opacity 0.3s ease-out; /* For delete feedback */+ }++ /* *** Corrected event-content styles *** */+ .event-content {+ display: flex;+ align-items: stretch; /* Make container and buttons same height */+ gap: 10px;+ width: 100%;+ }++ /* *** Re-added image-container styles *** */+ .image-container {+ flex-grow: 1; /* Take up space */+ aspect-ratio: 16 / 9; /* Maintains proportion */+ background-color: var(--image-bg); /* Whitespace color */+ border-radius: 5px;+ overflow: hidden;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ min-width: 0; /* Prevent flexbox overflow */+ position: relative;+ transition: background-color 0.2s;+ max-width: 100%; /* Prevents image from exceeding card width */+ }+ .image-container:hover { background-color: #e0e0e0; }+ .image-container.image-load-failed {+ background-colorplaatsen: var(--image-fail-bg);+ cursor: default;+ }+ .image-container.image-load-failed:hover { background-color: var(--image-fail-bg); }++ /* *** Corrected event-image styles *** */+ .event-image {+ display: block;+ max-width: 100%;+ max-height: 100%;+ width: auto; /* Let max values and object-fit handle it */+ height: auto;+ object-fit: contain; /* Fit entire image within container */+ /* Removed explicit width/height, border-radius, etc */+ }++ /* *** Corrected button-group styles *** */+ .button-group {+ display: flex;+ flex-direction: column;+ justify-content: space-between; /* Space out buttons */+ margin-left: 0; /* No margin needed */+ flex-shrink: 0; /* Don't shrink */+ }++ /* .spacer CSS removed */++ .action-btn { /* Base style for all action buttons */+ background: none;+ border: none;+ cursor: pointer;+ font-size: 1.1em; /* Slightly larger icons */+ color: var(--icon-color);+ padding: 5px;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 35px;+ height: 35px;+ border-radius: 4px;+ transition: background-color 0.2s, color 0.2s, opacity 0.2s;+ }+ .action-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }++ /* General hover for non-delete/download */+ .action-btn:not(.delete-btn):not(.download-btn):not(.delete-all-btn):hover {+ color: var(--icon-hover);+ background-color: #f0f0f0;+ }++ /* Original hover styles from user code for specific buttons */+ .delete-btn:hover,+ .delete-all-btn:hover {+ color: var(--delete-color);+ }+ .download-btn:hover {+ color: var(--download-color);+ }++ /* Active state provides better feedback */+ .action-btn:active { background-color: #ddd; }+ .delete-btn:active, .delete-all-btn:active { color: white; background-color: #d32f2f; }+ .download-btn:active { color: white; background-color: #1565c0; }++ /* Media Query Overrides */+ @media (hover: none) { /* Remove hover effects for touch */+ .action-btn:hover, .delete-btn:hover, .delete-all-btn:hover, .download-btn:hover {+ color: var(--icon-color); /* Reset color */+ background-color: transparent; /* Remove background */+ }+ /* Keep active states for tap feedback */+ }++ @media (max-width: 600px) {+ .event-card {+ max-width: 95%;+ padding: 12px;+ }+ .action-btn { /* Smaller buttons on small screens */+ font-size: 1em;+ width: 30px;+ height: 30px;+ }+ /* Ensure single column below 600px */+ .date-events { grid-template-columns: 1fr; padding: 0 2px; }+ }++ /* Responsive grid columns */+ @media (min-width: 768px) {+ .date-events {+ display: grid; /* Ensure grid display if hidden */+ grid-template-columns: repeat(auto-fill, minmax(320px, 400px)); /* Changed from auto-fit to auto-fill, capped at 400px */+ gap: 20px; /* Wider gap for grid */+ justify-content: center; /* Center the grid items */+ max-width: 1240px; /* Limit overall width */+ margin: 0 auto; /* Center the grid container */+ padding: 0; /* Remove padding */+ }+ .event-card {+ width: 100%; /* Fit the grid cell */+ max-width: 400px; /* Consistent max size */+ margin: 0; /* Let grid handle spacing */+ }+ }++ /* Simple Modal Styles (from user code preference) */+ .modal {+ display: none;+ position: fixed;+ z-index: 1000;+ left: 50%;+ top: 50%;+ transform: translate(-50%, -50%);+ width: auto;+ max-width: 90%;+ background: var(--modal-bg);+ padding: 20px 25px; /* Adjusted padding */+ border-radius: 10px;+ box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.2); /* Slightly more shadow */+ text-align: center;+ }+ /* Modal Content styling */+ .modal h3 { margin-top: 0; margin-bottom: 15px; }+ .modal label { display: block; margin: 8px 0 3px; text-align: left; font-weight: bold; font-size: 0.9em;}+ .modal input[type="datetime-local"] { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 0.95em; }+ .modal button { color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; margin: 10px 5px 0; transition: background-color 0.2s, opacity 0.2s; min-width: 90px; }+ .modal button:hover { opacity: 0.85; }+ .modal button.confirm-btn { background-color: var(--btn-confirm-bg); }+ .modal button.cancel-btn { background-color: var(--btn-cancel-bg); }+ .modal button.confirm-delete-btn { background-color: var(--btn-delete-bg); }+ </style>+</head>+<body>+ <div id="header">+ <h1>Events</h1>+ <button class="action-btn delete-all-btn" onclick="showDeleteAllModal()" title="Delete Events by Range">+ <i class="fas fa-trash-alt"></i>+ </button>+ </div>++ <div id="eventsContainer">+ <p>Loading events...</p> </div>++ <div id="timePickerModal" class="modal" aria-labelledby="dlModalTitle" role="dialog" aria-modal="true">+ <h3 id="dlModalTitle">Select Download Time Range</h3>+ <label for="startTime">Start Time:</label>+ <input type="datetime-local" id="startTime" name="startTime">+ <label for="endTime">End Time:</label>+ <input type="datetime-local" id="endTime" name="endTime">+ <button class="confirm-btn" onclick="confirmDownload()">Download</button>+ <button class="cancel-btn" onclick="closeModal()">Cancel</button>+ </div>++ <div id="deleteAllModal" class="modal" aria-labelledby="delModalTitle" role="dialog" aria-modal="true">+ <h3 id="delModalTitle">Delete Events by Range</h3>+ <label for="deleteStartTime">Delete From (Inclusive):</label>+ <input type="datetime-local" id="deleteStartTime" name="deleteStartTime">+ <label for="deleteEndTime">Delete To (Inclusive):</label>+ <input type="datetime-local" id="deleteEndTime" name="deleteEndTime">+ <button class="confirm-delete-btn" onclick="confirmDeleteAll()">Delete</button>+ <button class="cancel-btn" onclick="closeDeleteAllModal()">Cancel</button>+ </div>++</body>+</html>diff --git a/ios/clearcam/hi.lproj/Localizable.strings b/ios/clearcam/hi.lproj/Localizable.stringsnew file mode 100644index 0000000..fc0280c--- /dev/null+++ b/ios/clearcam/hi.lproj/Localizable.strings@@ -0,0 +1,188 @@+"settings" = "सेटिंग्स";+"events" = "ईवेंट्स";+"live" = "लाइव";+"default_device_name" = "मेरा डिवाइस";+"waiting_for_ip" = "Wi-Fi का इंतज़ार कर रहे...";+"streaming_over_wifi" = "स्थानीय Wi-Fi पर स्ट्रीमिंग: %@";+"permission_denied" = "अनुमति अस्वीकृत";+"notification_permission_denied" = "सूचना की अनुमति अस्वीकृत कर दी गई है। आप इसे सेटिंग्स में सक्षम कर सकते हैं।";+"ok" = "ठीक है";+"enable_in_settings" = "सेटिंग्स में सक्षम करें";+"notifications_disabled" = "सूचनाएँ अक्षम हैं। कृपया उन्हें सेटिंग्स ऐप में सक्षम करें।";+"camera_settings" = "कैमरा सेटिंग्स";+"live_stream_settings" = "लाइव स्ट्रीम सेटिंग्स";+"viewer_settings" = "व्यूअर सेटिंग्स";+"subscription" = "सदस्यता";+"upgrade_to_premium" = "प्रीमियम में अपग्रेड करें";+"stream_via_wifi" = "Wi-Fi के माध्यम से स्ट्रीम करें";+"resolution" = "रिज़ॉल्यूशन";+"detect_objects" = "वस्तुओं का पता लगाएं";+"manage_detection_presets" = "डिटेक्शन प्रीसेट प्रबंधित करें";+"detection_certainty_threshold" = "डिटेक्शन निश्चितता सीमा";+"send_videos_on_detection" = "डिटेक्शन पर वीडियो भेजें";+"send_videos_description" = "इवेंट्स को किसी भी डिवाइस पर देखने के लिए सक्षम करें।";+"change_encryption_password" = "एन्क्रिप्शन पासवर्ड बदलें";+"manage_detection_schedules" = "डिटेक्शन शेड्यूल प्रबंधित करें";+"manage_detection_schedules_description" = "कब वस्तुओं का पता लगाना है, चुनें।";+"use_own_notification_server" = "स्वयं का नोटिफिकेशन सर्वर उपयोग करें";+"use_own_notification_server_description" = "वीडियो अपने सर्वर पर भेजें।";+"server_address" = "सर्वर पता";+"test_own_server" = "अपना सर्वर जांचें";+"use_own_inference_server" = "स्वयं का इनफेरेंस सर्वर उपयोग करें";+"use_own_inference_server_description" = "वस्तु पहचान के लिए कस्टम सर्वर उपयोग करें।";+"enter_inference_server_address" = "सर्वर पता दर्ज करें: जैसे http://192.168.1.1:6667";+"live_stream_network" = "नेटवर्क पर लाइव स्ट्रीम";+"device_name" = "डिवाइस का नाम";+"receive_notifications" = "सूचनाएँ प्राप्त करें";+"receive_notifications_description" = "जब कैमरा कोई इवेंट कैप्चर करे तो सूचित किया जाए।";+"restore_purchases" = "खरीदारी पुनर्स्थापित करें";+"terms_of_use" = "उपयोग की शर्तें";+"privacy_policy" = "गोपनीयता नीति";+"delete_encryption_keys" = "एन्क्रिप्शन कुंजियाँ हटाएं";+"enter_inference_server_address_title" = "इनफेरेंस सर्वर का पता दर्ज करें";+"enter_inference_server_address_message" = "कृपया अपने इनफेरेंस सर्वर का पता दर्ज करें।";+"server_address_label" = "सर्वर पता";+"save" = "सेव करें";+"cancel" = "रद्द करें";+"set_threshold_title" = "सीमा निर्धारित करें";+"set_threshold_message" = "1 से 100 के बीच का प्रतिशत दर्ज करें (डिफ़ॉल्ट 25 है)।";+"threshold_placeholder" = "सीमा (1-100)";+"invalid_threshold_title" = "अमान्य सीमा";+"invalid_threshold_message" = "कृपया 1 से 100 के बीच का मान्य मान दर्ज करें";+"set_device_name_title" = "डिवाइस नाम सेट करें";+"set_device_name_message" = "इस डिवाइस के लिए नाम दर्ज करें।";+"device_name_placeholder" = "डिवाइस का नाम";+"delete_encryption_keys_title" = "एन्क्रिप्शन कुंजियाँ हटाएं";+"delete_encryption_keys_message" = "क्या आप वाकई इस डिवाइस से सभी कुंजियाँ हटाना चाहते हैं?";+"delete" = "हाँ";+"price_unknown" = "मूल्य";+"get_premium_title" = "Clearcam प्रीमियम प्राप्त करें";+"premium_feature_1" = "कहीं से भी कैप्चर किए गए इवेंट देखें";+"premium_feature_2" = "वास्तविक समय में इवेंट सूचनाएँ प्राप्त करें";+"premium_feature_3" = "कहीं से भी लाइव स्ट्रीम करें";+"premium_feature_4" = "आपके फ़ोन से भेजे गए सभी कैमरा डेटा पर एंड-टू-एंड एन्क्रिप्शन।";+"upgrade_button" = "₹%@ प्रति माह में अपग्रेड करें";+"not_now" = "अभी नहीं";+"premium_disclaimer" = "प्रति माह 5,000 क्लिप अपलोड और 1,000 मिनट या सत्र की लाइव स्ट्रीम सीमा।";+"purchase_failed" = "खरीद विफल रही";+"enter_notification_server_address_title" = "सर्वर पता दर्ज करें";+"enter_notification_server_address_message" = "कृपया अपने नोटिफिकेशन सर्वर का पता दर्ज करें।";+"test_notification_sent_title" = "भेजा गया";+"test_notification_sent_message" = "टेस्ट नोटिफिकेशन भेजा गया। अपने सर्वर की जाँच करें।";+"set_password_title" = "पासवर्ड सेट करें";+"set_password_message" = "अपने डेटा को एन्क्रिप्ट करने के लिए पासवर्ड दर्ज करें";+"password_placeholder" = "पासवर्ड";+"confirm_password_placeholder" = "पासवर्ड की पुष्टि करें";+"invalid_password_title" = "अमान्य पासवर्ड";+"invalid_password_message" = "पासवर्ड मेल नहीं खा रहे हैं या खाली हैं।";+"select_resolution_title" = "रिज़ॉल्यूशन चुनें";+"select_objects_preset_title" = "वस्तु प्रीसेट चुनें";+"add_preset_title" = "प्रीसेट जोड़ें";+"add_preset_message" = "नए प्रीसेट के लिए नाम दर्ज करें";+"preset_name_placeholder" = "प्रीसेट नाम";+"restoring_purchases_title" = "खरीदारी पुनर्स्थापित की जा रही है";+"restoring_purchases_message" = "कृपया प्रतीक्षा करें, हम आपकी पिछली खरीदारी पुनर्स्थापित कर रहे हैं...";+"steps_text_live" = "1. किसी अन्य फोन या RTSP सक्षम कैमरे पर Clearcam इंस्टॉल करें।\n2. Clearcam Premium में अपग्रेड करें।\n3. अपने दूसरे फोन (या कंप्यूटर) पर \"नेटवर्क पर लाइव स्ट्रीम\" चालू करें और एक सुरक्षित पासवर्ड तथा डिवाइस नाम चुनें।\n4. रिकॉर्डिंग शुरू करें।";+"steps_text_clips" = "1. किसी अन्य फोन या RTSP सक्षम कैमरे पर Clearcam इंस्टॉल करें।\n2. Clearcam Premium में अपग्रेड करें।\n3. \"पता चलने पर वीडियो भेजें\" (या कंप्यूटर पर नोटिफिकेशन) चालू करें और एक सुरक्षित पासवर्ड चुनें।\n4. (वैकल्पिक) अपनी डिटेक्शन सेटिंग्स और शेड्यूल कॉन्फ़िगर करें।\n5. रिकॉर्डिंग शुरू करें।";+"no_live_devices" = "कोई लाइव डिवाइस नहीं\n";+"no_videos_available" = "कोई वीडियो उपलब्ध नहीं\n";+"share" = "साझा करें";+"delete" = "हटाएं";+"cancel" = "रद्द करें";+"online" = "ऑनलाइन";+"experimental_features" = "प्रायोगिक विशेषताएँ";+"docs" = "दस्तावेज़";+"app_name" = "Clearcam";+"home" = "होम";+"camera_desc" = "एआई ऑब्जेक्ट डिटेक्शन के साथ वीडियो रिकॉर्ड और प्रसारित करें";+"gallery_desc" = "कैप्चर किए गए इवेंट और लाइव फीड देखें (प्रीमियम आवश्यक)";+"settings_desc" = "कैमरों और डिटेक्शन को कॉन्फ़िगर करें";+"all" = "सभी";+"people+vehicles" = "लोग+वाहन";++"authenticate_to_view_user_id" = "अपना यूज़र ID देखने के लिए प्रमाणित करें।";+"tap_for_userid" = "अपना यूज़र ID देखने के लिए टैप करें, इसे साझा न करें।";+"id_copied" = "यूज़र ID क्लिपबोर्ड पर कॉपी किया गया।";+"copied" = "कॉपी किया गया";+"userid" = "यूज़र ID";++"person" = "व्यक्ति";+"bicycle" = "साइकिल";+"car" = "कार";+"motorcycle" = "मोटरसाइकिल";+"airplane" = "विमान";+"bus" = "बस";+"train" = "रेलगाड़ी";+"truck" = "ट्रक";+"boat" = "नाव";+"traffic light" = "ट्रैफिक लाइट";+"fire hydrant" = "फायर हाइड्रेंट";+"stop sign" = "रुकने का संकेत";+"parking meter" = "पार्किंग मीटर";+"bench" = "बेंच";+"bird" = "पक्षी";+"cat" = "बिल्ली";+"dog" = "कुत्ता";+"horse" = "घोड़ा";+"sheep" = "भेड़";+"cow" = "गाय";+"elephant" = "हाथी";+"bear" = "भालू";+"zebra" = "ज़ेबरा";+"giraffe" = "जिराफ";+"backpack" = "बैकपैक";+"umbrella" = "छाता";+"handbag" = "हैंडबैग";+"tie" = "टाई";+"suitcase" = "सूटकेस";+"frisbee" = "फ्रिसबी";+"skis" = "स्की";+"snowboard" = "स्नोबोर्ड";+"sports ball" = "खेल की गेंद";+"kite" = "पतंग";+"baseball bat" = "बेसबॉल बैट";+"baseball glove" = "बेसबॉल ग्लव";+"skateboard" = "स्केटबोर्ड";+"surfboard" = "सर्फबोर्ड";+"tennis racket" = "टेनिस रैकेट";+"bottle" = "बोतल";+"wine glass" = "वाइन ग्लास";+"cup" = "कप";+"fork" = "कांटा";+"knife" = "चाकू";+"spoon" = "चम्मच";+"bowl" = "कटोरा";+"banana" = "केला";+"apple" = "सेब";+"sandwich" = "सैंडविच";+"orange" = "संतरा";+"broccoli" = "ब्रोकली";+"carrot" = "गाजर";+"hot dog" = "हॉट डॉग";+"pizza" = "पिज़्ज़ा";+"donut" = "डोनट";+"cake" = "केक";+"chair" = "कुर्सी";+"couch" = "सोफ़ा";+"potted plant" = "गमले वाला पौधा";+"bed" = "बिस्तर";+"dining table" = "भोजन मेज़";+"toilet" = "शौचालय";+"tv" = "टीवी";+"laptop" = "लैपटॉप";+"mouse" = "माउस";+"remote" = "रिमोट";+"keyboard" = "कीबोर्ड";+"cell phone" = "मोबाइल फोन";+"microwave" = "माइक्रोवेव";+"oven" = "ओवन";+"toaster" = "टोस्टर";+"sink" = "सिंक";+"refrigerator" = "फ्रिज";+"book" = "किताब";+"clock" = "घड़ी";+"vase" = "फूलदान";+"scissors" = "कैंची";+"teddy bear" = "टेडी बियर";+"hair drier" = "हेयर ड्रायर";+"toothbrush" = "टूथब्रश";diff --git a/ios/clearcam/ja.lproj/Localizable.strings b/ios/clearcam/ja.lproj/Localizable.stringsnew file mode 100644index 0000000..270bd3e--- /dev/null+++ b/ios/clearcam/ja.lproj/Localizable.strings@@ -0,0 +1,188 @@+"settings" = "設定";+"events" = "イベント";+"live" = "ライブ";+"default_device_name" = "マイデバイス";+"waiting_for_ip" = "Wi-Fiを待機中...";+"streaming_over_wifi" = "ローカルWi-Fiでストリーミング中: %@";+"permission_denied" = "アクセス拒否されました";+"notification_permission_denied" = "通知許可が拒否されました。設定から有効にできます。";+"ok" = "OK";+"enable_in_settings" = "設定で有効化";+"notifications_disabled" = "通知が無効です。設定アプリで有効にしてください。";+"camera_settings" = "カメラ設定";+"live_stream_settings" = "ライブ配信設定";+"viewer_settings" = "ビューア設定";+"subscription" = "サブスクリプション";+"upgrade_to_premium" = "プレミアム版にアップグレード";+"stream_via_wifi" = "Wi-Fiで配信";+"resolution" = "解像度";+"detect_objects" = "物体検出";+"manage_detection_presets" = "検出プリセット管理";+"detection_certainty_threshold" = "検出確信度の閾値";+"send_videos_on_detection" = "検出時に動画を送信";+"send_videos_description" = "有効にすると他のデバイスからイベントを確認できます。";+"change_encryption_password" = "暗号化パスワード変更";+"manage_detection_schedules" = "検出スケジュール管理";+"manage_detection_schedules_description" = "物体検出を行う時間帯を選択します。";+"use_own_notification_server" = "独自通知サーバーを使用";+"use_own_notification_server_description" = "所有サーバーに動画を送信します。";+"server_address" = "サーバーアドレス";+"test_own_server" = "サーバーをテスト";+"use_own_inference_server" = "独自推論サーバーを使用";+"use_own_inference_server_description" = "物体検出用のカスタムサーバーを使用します。";+"enter_inference_server_address" = "サーバーアドレスを入力: 例 http://192.168.1.1:6667";+"live_stream_network" = "ネットワーク経由でライブ配信";+"device_name" = "デバイス名";+"receive_notifications" = "通知を受信";+"receive_notifications_description" = "カメラがイベントを検出した際に通知を受け取ります。";+"restore_purchases" = "購入を復元";+"terms_of_use" = "利用規約";+"privacy_policy" = "プライバシーポリシー";+"delete_encryption_keys" = "暗号化キーを削除";+"enter_inference_server_address_title" = "推論サーバーアドレス入力";+"enter_inference_server_address_message" = "推論サーバーのアドレスを入力してください。";+"server_address_label" = "サーバーアドレス";+"save" = "保存";+"cancel" = "キャンセル";+"set_threshold_title" = "閾値を設定";+"set_threshold_message" = "1から100の間の値を入力してください(デフォルトは25)。";+"threshold_placeholder" = "閾値 (1-100)";+"invalid_threshold_title" = "無効な閾値";+"invalid_threshold_message" = "1から100の間の有効な値を入力してください。";+"set_device_name_title" = "デバイス名を設定";+"set_device_name_message" = "このデバイスの名前を入力してください。";+"device_name_placeholder" = "デバイス名";+"delete_encryption_keys_title" = "暗号化キー削除";+"delete_encryption_keys_message" = "このデバイスからすべてのキーを削除してもよろしいですか?";+"delete" = "はい";+"price_unknown" = "価格";+"get_premium_title" = "Clearcamプレミアムを取得";+"premium_feature_1" = "どこからでも検出イベントを確認";+"premium_feature_2" = "リアルタイム通知を受信";+"premium_feature_3" = "どこからでもライブ配信を視聴";+"premium_feature_4" = "送信される全てのカメラデータにエンドツーエンド暗号化を適用。";+"upgrade_button" = "月額%@でアップグレード";+"not_now" = "後で";+"premium_disclaimer" = "月間制限: 5,000クリップのアップロードと1,000分のライブ配信視聴。";+"purchase_failed" = "購入に失敗しました";+"enter_notification_server_address_title" = "サーバーアドレス入力";+"enter_notification_server_address_message" = "通知サーバーのアドレスを入力してください。";+"test_notification_sent_title" = "送信済み";+"test_notification_sent_message" = "テスト通知を送信しました。サーバーを確認してください。";+"set_password_title" = "パスワード設定";+"set_password_message" = "データ暗号化用のパスワードを入力";+"password_placeholder" = "パスワード";+"confirm_password_placeholder" = "パスワード確認";+"invalid_password_title" = "無効なパスワード";+"invalid_password_message" = "パスワードが一致しないか空です。";+"select_resolution_title" = "解像度を選択";+"select_objects_preset_title" = "物体プリセットを選択";+"add_preset_title" = "プリセットを追加";+"add_preset_message" = "新しいプリセット名を入力";+"preset_name_placeholder" = "プリセット名";+"restoring_purchases_title" = "購入を復元中";+"restoring_purchases_message" = "以前の購入を復元しています...";+"steps_text_live" = "1. 別のスマートフォンまたはRTSP対応カメラにClearcamをインストールします。\n2. Clearcam Premiumにアップグレードします。\n3. 別のスマートフォン(またはPC)で「ネットワーク経由でライブ配信」を有効にし、安全なパスワードとデバイス名を設定します。\n4. 録画を開始します。";+"steps_text_clips" = "1. 別のスマートフォンまたはRTSP対応カメラにClearcamをインストールします。\n2. Clearcam Premiumにアップグレードします。\n3. 「検知時に動画を送信」(またはPCで通知を受け取る)を有効にし、安全なパスワードを設定します。\n4. (任意)検知設定とスケジュールを構成します。\n5. 録画を開始します。";+"no_live_devices" = "配信中のデバイスなし\n";+"no_videos_available" = "利用可能な動画なし\n";+"share" = "共有";+"delete" = "削除";+"cancel" = "キャンセル";+"online" = "オンライン";+"experimental_features" = "実験的機能";+"docs" = "ドキュメント";+"app_name" = "Clearcam";+"home" = "ホーム";+"camera_desc" = "映像を録画・配信し、AIで物体検出を行います";+"gallery_desc" = "撮影されたイベントやライブ映像を表示(プレミアムが必要)";+"settings_desc" = "カメラと検出機能の設定";+"all" = "すべて";+"people+vehicles" = "人+車両";++"authenticate_to_view_user_id" = "ユーザーIDを表示するには認証が必要です。";+"tap_for_userid" = "タップしてユーザーIDを表示、共有しないでください。";+"id_copied" = "ユーザーIDがクリップボードにコピーされました。";+"copied" = "コピーしました";+"userid" = "ユーザーID";++"person" = "人";+"bicycle" = "自転車";+"car" = "車";+"motorcycle" = "バイク";+"airplane" = "飛行機";+"bus" = "バス";+"train" = "電車";+"truck" = "トラック";+"boat" = "ボート";+"traffic light" = "信号機";+"fire hydrant" = "消火栓";+"stop sign" = "一時停止標識";+"parking meter" = "パーキングメーター";+"bench" = "ベンチ";+"bird" = "鳥";+"cat" = "猫";+"dog" = "犬";+"horse" = "馬";+"sheep" = "羊";+"cow" = "牛";+"elephant" = "象";+"bear" = "熊";+"zebra" = "シマウマ";+"giraffe" = "キリン";+"backpack" = "リュックサック";+"umbrella" = "傘";+"handbag" = "ハンドバッグ";+"tie" = "ネクタイ";+"suitcase" = "スーツケース";+"frisbee" = "フリスビー";+"skis" = "スキー板";+"snowboard" = "スノーボード";+"sports ball" = "ボール";+"kite" = "凧";+"baseball bat" = "バット";+"baseball glove" = "グローブ";+"skateboard" = "スケートボード";+"surfboard" = "サーフボード";+"tennis racket" = "テニスラケット";+"bottle" = "瓶";+"wine glass" = "ワイングラス";+"cup" = "カップ";+"fork" = "フォーク";+"knife" = "ナイフ";+"spoon" = "スプーン";+"bowl" = "ボウル";+"banana" = "バナナ";+"apple" = "リンゴ";+"sandwich" = "サンドイッチ";+"orange" = "オレンジ";+"broccoli" = "ブロッコリー";+"carrot" = "人参";+"hot dog" = "ホットドッグ";+"pizza" = "ピザ";+"donut" = "ドーナツ";+"cake" = "ケーキ";+"chair" = "椅子";+"couch" = "ソファ";+"potted plant" = "鉢植え";+"bed" = "ベッド";+"dining table" = "食卓";+"toilet" = "トイレ";+"tv" = "テレビ";+"laptop" = "ノートPC";+"mouse" = "マウス";+"remote" = "リモコン";+"keyboard" = "キーボード";+"cell phone" = "スマートフォン";+"microwave" = "電子レンジ";+"oven" = "オーブン";+"toaster" = "トースター";+"sink" = "流し台";+"refrigerator" = "冷蔵庫";+"book" = "本";+"clock" = "時計";+"vase" = "花瓶";+"scissors" = "ハサミ";+"teddy bear" = "テディベア";+"hair drier" = "ヘアドライヤー";+"toothbrush" = "歯ブラシ";diff --git a/ios/clearcam/ko.lproj/Localizable.strings b/ios/clearcam/ko.lproj/Localizable.stringsnew file mode 100644index 0000000..38617bf--- /dev/null+++ b/ios/clearcam/ko.lproj/Localizable.strings@@ -0,0 +1,188 @@+"settings" = "설정";+"events" = "이벤트";+"live" = "라이브";+"default_device_name" = "내 장치";+"waiting_for_ip" = "Wi-Fi 연결 대기 중...";+"streaming_over_wifi" = "로컬 Wi-Fi로 스트리밍 중: %@";+"permission_denied" = "권한 거부됨";+"notification_permission_denied" = "알림 권한이 거부되었습니다. 설정에서 활성화할 수 있습니다.";+"ok" = "확인";+"enable_in_settings" = "설정에서 활성화";+"notifications_disabled" = "알림이 비활성화되었습니다. 설정 앱에서 활성화해 주세요.";+"camera_settings" = "카메라 설정";+"live_stream_settings" = "라이브 스트림 설정";+"viewer_settings" = "뷰어 설정";+"subscription" = "구독";+"upgrade_to_premium" = "프리미엄으로 업그레이드";+"stream_via_wifi" = "Wi‑Fi로 스트리밍";+"resolution" = "해상도";+"detect_objects" = "물체 감지";+"manage_detection_presets" = "감지 사전 설정 관리";+"detection_certainty_threshold" = "감지 확률 기준값";+"send_videos_on_detection" = "감지 시 영상 전송";+"send_videos_description" = "어디서든 다른 기기에서 이벤트를 확인하려면 활성화하세요.";+"change_encryption_password" = "암호화 암호 변경";+"manage_detection_schedules" = "감지 일정 관리";+"manage_detection_schedules_description" = "물체를 감지할 시간을 선택하세요.";+"use_own_notification_server" = "자체 알림 서버 사용";+"use_own_notification_server_description" = "직접 소유한 서버로 영상을 전송합니다.";+"server_address" = "서버 주소";+"test_own_server" = "서버 테스트";+"use_own_inference_server" = "자체 추론 서버 사용";+"use_own_inference_server_description" = "객체 감지를 위한 사용자 지정 서버를 사용합니다.";+"enter_inference_server_address" = "서버 주소 입력: 예) http://192.168.1.1:6667";+"live_stream_network" = "네트워크를 통한 라이브 스트림";+"device_name" = "장치 이름";+"receive_notifications" = "알림 수신";+"receive_notifications_description" = "카메라에서 이벤트가 감지되면 알림을 받습니다.";+"restore_purchases" = "구매 복원";+"terms_of_use" = "이용 약관";+"privacy_policy" = "개인정보처리방침";+"delete_encryption_keys" = "암호화 키 삭제";+"enter_inference_server_address_title" = "추론 서버 주소 입력";+"enter_inference_server_address_message" = "추론 서버 주소를 입력하세요.";+"server_address_label" = "서버 주소";+"save" = "저장";+"cancel" = "취소";+"set_threshold_title" = "기준값 설정";+"set_threshold_message" = "1에서 100 사이의 % 값을 입력하세요 (기본값은 25).";+"threshold_placeholder" = "기준값 (1–100)";+"invalid_threshold_title" = "잘못된 기준값";+"invalid_threshold_message" = "1에서 100 사이의 유효한 값을 입력해 주세요.";+"set_device_name_title" = "장치 이름 설정";+"set_device_name_message" = "이 장치의 이름을 입력하세요.";+"device_name_placeholder" = "장치 이름";+"delete_encryption_keys_title" = "암호화 키 삭제";+"delete_encryption_keys_message" = "이 장치에서 모든 키를 삭제하시겠습니까?";+"delete" = "예";+"price_unknown" = "가격";+"get_premium_title" = "Clearcam 프리미엄 받기";+"premium_feature_1" = "어디서든 캡처된 이벤트 보기";+"premium_feature_2" = "실시간 이벤트 알림 받기";+"premium_feature_3" = "어디서든 라이브 스트림";+"premium_feature_4" = "휴대폰에서 전송되는 모든 카메라 데이터에 대해 종단 간 암호화";+"upgrade_button" = "%@/월에 업그레이드";+"not_now" = "지금은 아니요";+"premium_disclaimer" = "월 최대 5,000개 클립 업로드 및 1,000분 또는 세션의 라이브 스트림 시청 제한이 있습니다.";+"purchase_failed" = "구매 실패";+"enter_notification_server_address_title" = "서버 주소 입력";+"enter_notification_server_address_message" = "알림 서버 주소를 입력하세요.";+"test_notification_sent_title" = "전송됨";+"test_notification_sent_message" = "테스트 알림이 전송되었습니다. 서버를 확인해 주세요.";+"set_password_title" = "암호 설정";+"set_password_message" = "데이터를 암호화할 암호를 입력하세요.";+"password_placeholder" = "암호";+"confirm_password_placeholder" = "암호 확인";+"invalid_password_title" = "잘못된 암호";+"invalid_password_message" = "암호가 서로 다르거나 비어 있습니다.";+"select_resolution_title" = "해상도 선택";+"select_objects_preset_title" = "물체 사전 설정 선택";+"add_preset_title" = "사전 설정 추가";+"add_preset_message" = "새 사전 설정의 이름을 입력하세요.";+"preset_name_placeholder" = "사전 설정 이름";+"restoring_purchases_title" = "구매 복원 중";+"restoring_purchases_message" = "이전 구매를 복원하는 중입니다...";+"steps_text_live" = "1. 다른 휴대폰 또는 RTSP 지원 카메라에 Clearcam을 설치하세요.\n2. Clearcam Premium으로 업그레이드하세요.\n3. 다른 휴대폰(또는 컴퓨터)에서 \"네트워크 라이브 스트리밍\"을 켜고 안전한 비밀번호와 기기 이름을 선택하세요.\n4. 녹화를 시작하세요.";+"steps_text_clips" = "1. 다른 휴대폰 또는 RTSP 지원 카메라에 Clearcam을 설치하세요.\n2. Clearcam Premium으로 업그레이드하세요.\n3. \"감지 시 동영상 전송\" (또는 컴퓨터에서 알림 수신)을 활성화하고 안전한 비밀번호를 설정하세요.\n4. (선택 사항) 감지 설정 및 일정을 구성하세요.\n5. 녹화를 시작하세요.";+"no_live_devices" = "실시간 장치 없음\n";+"no_videos_available" = "사용 가능한 영상 없음\n";+"share" = "공유";+"delete" = "삭제";+"cancel" = "취소";+"online" = "온라인";+"experimental_features" = "실험적 기능";+"docs" = "문서";+"app_name" = "Clearcam";+"home" = "홈";+"camera_desc" = "AI 객체 감지 기능으로 영상을 녹화하고 방송합니다";+"gallery_desc" = "캡처된 이벤트와 실시간 영상을 확인하세요 (프리미엄 필요)";+"settings_desc" = "카메라 및 감지 설정";+"all" = "전체";+"people+vehicles" = "사람+차량";++"authenticate_to_view_user_id" = "사용자 ID를 보려면 인증하세요.";+"tap_for_userid" = "사용자 ID를 보려면 탭하세요, 공유하지 마세요.";+"id_copied" = "사용자 ID가 클립보드에 복사되었습니다.";+"copied" = "복사됨";+"userid" = "사용자 ID";++"person" = "사람";+"bicycle" = "자전거";+"car" = "자동차";+"motorcycle" = "오토바이";+"airplane" = "비행기";+"bus" = "버스";+"train" = "기차";+"truck" = "트럭";+"boat" = "보트";+"traffic light" = "신호등";+"fire hydrant" = "소화전";+"stop sign" = "정지 표지판";+"parking meter" = "주차 미터기";+"bench" = "벤치";+"bird" = "새";+"cat" = "고양이";+"dog" = "강아지";+"horse" = "말";+"sheep" = "양";+"cow" = "소";+"elephant" = "코끼리";+"bear" = "곰";+"zebra" = "얼룩말";+"giraffe" = "기린";+"backpack" = "배낭";+"umbrella" = "우산";+"handbag" = "핸드백";+"tie" = "넥타이";+"suitcase" = "여행가방";+"frisbee" = "프리스비";+"skis" = "스키";+"snowboard" = "스노보드";+"sports ball" = "스포츠공";+"kite" = "연";+"baseball bat" = "야구 방망이";+"baseball glove" = "야구 글러브";+"skateboard" = "스케이트보드";+"surfboard" = "서핑보드";+"tennis racket" = "테니스 라켓";+"bottle" = "병";+"wine glass" = "와인잔";+"cup" = "컵";+"fork" = "포크";+"knife" = "칼";+"spoon" = "숟가락";+"bowl" = "그릇";+"banana" = "바나나";+"apple" = "사과";+"sandwich" = "샌드위치";+"orange" = "오렌지";+"broccoli" = "브로콜리";+"carrot" = "당근";+"hot dog" = "핫도그";+"pizza" = "피자";+"donut" = "도넛";+"cake" = "케이크";+"chair" = "의자";+"couch" = "소파";+"potted plant" = "화분";+"bed" = "침대";+"dining table" = "식탁";+"toilet" = "변기";+"tv" = "TV";+"laptop" = "노트북";+"mouse" = "마우스";+"remote" = "리모컨";+"keyboard" = "키보드";+"cell phone" = "휴대폰";+"microwave" = "전자레인지";+"oven" = "오븐";+"toaster" = "토스터기";+"sink" = "싱크대";+"refrigerator" = "냉장고";+"book" = "책";+"clock" = "시계";+"vase" = "꽃병";+"scissors" = "가위";+"teddy bear" = "곰인형";+"hair drier" = "헤어드라이어";+"toothbrush" = "칫솔";diff --git a/ios/clearcam/main.m b/ios/clearcam/main.mnew file mode 100644index 0000000..3631c94--- /dev/null+++ b/ios/clearcam/main.m@@ -0,0 +1,10 @@+#import <UIKit/UIKit.h>+#import "AppDelegate.h"++int main(int argc, char * argv[]) {+ NSString * appDelegateClassName;+ @autoreleasepool {+ appDelegateClassName = NSStringFromClass([AppDelegate class]);+ }+ return UIApplicationMain(argc, argv, nil, appDelegateClassName);+}diff --git a/ios/clearcam/multicamera.html b/ios/clearcam/multicamera.htmlnew file mode 100644index 0000000..b4ce9aa--- /dev/null+++ b/ios/clearcam/multicamera.html@@ -0,0 +1,371 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Multi-camera view</title>+ <style>+ body {+ margin: 0;+ height: 100vh;+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ background-color: #f0f0f0;+ overflow: hidden;+ }+ .container {+ position: absolute;+ width: 360px; /* Initial width */+ height: calc(360px * 9 / 16); /* Initial height */+ border: 2px solid black;+ touch-action: none;+ }+ .handle {+ position: absolute;+ width: 20px;+ height: 20px;+ background: transparent;+ bottom: -10px;+ right: -10px;+ cursor: nwse-resize;+ border: none;+ outline: none;+ }+ .drag-bottom, .drag-left, .drag-right {+ position: absolute;+ background: rgba(0, 0, 0, 0);+ cursor: move;+ z-index: 3;+ }+ .drag-left {+ top: 0;+ left: 0;+ height: 80%;+ width: 5%;+ }+ .drag-right {+ top: 0;+ right: 0;+ height: 70%;+ width: 1%;+ }+ iframe {+ width: 100%;+ height: 100%;+ border: none;+ position: relative;+ z-index: 1;+ }+ </style>+</head>+<body>+ <script>+ let isPortrait = false; // Track the current orientation++ const existingUrls = new Set();+ const rectangles = new Map();+ const MIN_DIMENSION = 360; // Minimum dimension (width for landscape, height for portrait)++ async function fetchDevices() {+ try {+ console.log('Fetching devices...');+ const response = await fetch('/get-devices');+ const devices = await response.json();+ console.log('Devices fetched:', devices);+ const newUrls = new Set(devices.map(ip => `http://${ip}`));++ newUrls.forEach(url => {+ if (!existingUrls.has(url)) {+ existingUrls.add(url);+ const rect = createRectangle(url);+ rectangles.set(url, rect);+ updateURL();+ }+ });++ [...existingUrls].forEach(url => {+ if (!newUrls.has(url)) {+ removeRectangle(url);+ existingUrls.delete(url);+ rectangles.delete(url);+ updateURL();+ }+ });+ } catch (error) {+ console.error('Error fetching devices:', error);+ }+ }++ function removeRectangle(url) {+ const rect = rectangles.get(url);+ if (rect) {+ const rectHeight = rect.offsetHeight;+ rect.remove();++ if (window.innerWidth <= 600) {+ const allRectangles = Array.from(document.querySelectorAll('.container'));+ let currentTop = 0;+ allRectangles.forEach(rectangle => {+ rectangle.style.top = `${currentTop}px`;+ currentTop += rectangle.offsetHeight + 2;+ });+ currentTopPosition = currentTop;+ }++ console.log('Removed element from DOM:', rect);+ } else {+ console.warn('Rectangle not found for URL:', url);+ }+ }++ function startPolling() {+ const pollingInterval = 5000;+ setInterval(fetchDevices, pollingInterval);+ }++ function loadFromURL() {+ const params = new URLSearchParams(window.location.search);+ params.forEach((value, url) => {+ const rectInfo = JSON.parse(value);+ const rect = createRectangle(url);+ rect.style.left = rectInfo.left;+ rect.style.top = rectInfo.top;+ rect.style.width = rectInfo.width;+ rect.style.height = rectInfo.height;+ rect.dataset.portrait = rectInfo.portrait ? "true" : "false";+ rectangles.set(url, rect);+ existingUrls.add(url);+ });+ }++ document.addEventListener('DOMContentLoaded', () => {+ loadFromURL();+ fetchDevices();+ startPolling();+ });++ let currentTopPosition = 0;+ function createRectangle(url) {+ const rectangle = document.createElement('div');+ rectangle.className = 'container';++ if (window.innerWidth <= 600) {+ rectangle.style.left = '0';+ rectangle.style.width = '100%';+ const screenWidth = window.innerWidth;+ const rectangleHeight = screenWidth * (9 / 16);+ rectangle.style.height = `${rectangleHeight}px`;+ rectangle.style.top = `${currentTopPosition}px`;+ currentTopPosition += rectangleHeight + 2;+ } else {+ rectangle.style.left = `${Math.random() * (window.innerWidth - MIN_DIMENSION)}px`;+ rectangle.style.top = `${Math.random() * (window.innerHeight - (MIN_DIMENSION * 9 / 16))}px`;+ rectangle.style.width = `${MIN_DIMENSION}px`;+ rectangle.style.height = `calc(${MIN_DIMENSION}px * 9 / 16)`;+ }++ const iframe = document.createElement('iframe');+ iframe.src = url;+ const handle = document.createElement('div');+ handle.className = 'handle';+ const dragLeft = document.createElement('div');+ dragLeft.className = 'drag-left';+ const dragRight = document.createElement('div');+ dragRight.className = 'drag-right';++ rectangle.append(iframe, handle);+ if (window.innerWidth > 600) {+ rectangle.append(dragLeft, dragRight);+ addDragListeners(dragLeft, rectangle);+ addDragListeners(dragRight, rectangle);+ }++ document.body.appendChild(rectangle);+ addResizeListeners(handle, rectangle);+ return rectangle;+ }++ function addResizeListeners(handle, rectangle) {+ handle.addEventListener('mousedown', (e) => startResize(e, rectangle));+ handle.addEventListener('touchstart', (e) => startResize(e, rectangle));+ }++ function addDragListeners(handle, rectangle) {+ handle.addEventListener('mousedown', (e) => startDrag(e, rectangle));+ handle.addEventListener('touchstart', (e) => startDrag(e, rectangle));+ }++ function startDrag(e, rectangle) {+ e.preventDefault();+ let offsetX = (e.touches ? e.touches[0].clientX : e.clientX) - rectangle.offsetLeft;+ let offsetY = (e.touches ? e.touches[0].clientY : e.clientY) - rectangle.offsetTop;++ function drag(e) {+ let clientX = e.touches ? e.touches[0].clientX : e.clientX;+ let clientY = e.touches ? e.touches[0].clientY : e.clientY;+ rectangle.style.left = `${clientX - offsetX}px`;+ rectangle.style.top = `${clientY - offsetY}px`;+ }++ function stopDrag() {+ document.removeEventListener('mousemove', drag);+ document.removeEventListener('mouseup', stopDrag);+ document.removeEventListener('touchmove', drag);+ document.removeEventListener('touchend', stopDrag);+ rectangle.querySelector('iframe').style.pointerEvents = "auto";+ updateURL();+ }++ rectangle.querySelector('iframe').style.pointerEvents = "none";+ document.addEventListener('mousemove', drag);+ document.addEventListener('mouseup', stopDrag);+ document.addEventListener('touchmove', drag);+ document.addEventListener('touchend', stopDrag);+ }++ function startResize(e, rectangle) {+ e.preventDefault();+ let startX = e.touches ? e.touches[0].clientX : e.clientX;+ let startWidth = rectangle.offsetWidth;+ let startHeight = rectangle.offsetHeight;+ let isPortrait = rectangle.dataset.portrait === "true";++ function resize(e) {+ let clientX = e.touches ? e.touches[0].clientX : e.clientX;+ let newWidth = startWidth + (clientX - startX);+ let newHeight;++ if (isPortrait) {+ newHeight = Math.max(MIN_DIMENSION, newWidth * (16 / 9));+ newWidth = newHeight * (9 / 16);+ } else {+ newWidth = Math.max(MIN_DIMENSION, newWidth);+ newHeight = newWidth * (9 / 16);+ }++ if (Math.abs(parseFloat(rectangle.style.width) - newWidth) > 1 ||+ Math.abs(parseFloat(rectangle.style.height) - newHeight) > 1) {+ rectangle.style.width = `${newWidth}px`;+ rectangle.style.height = `${newHeight}px`;+ }+ }++ function stopResize() {+ document.removeEventListener('mousemove', resize);+ document.removeEventListener('mouseup', stopResize);+ document.removeEventListener('touchmove', resize);+ document.removeEventListener('touchend', stopResize);+ rectangle.querySelector('iframe').style.pointerEvents = "auto";+ updateURL();+ }++ rectangle.querySelector('iframe').style.pointerEvents = "none";+ document.addEventListener('mousemove', resize);+ document.addEventListener('mouseup', stopResize);+ document.addEventListener('touchmove', resize);+ document.addEventListener('touchend', stopResize);+ }++ function addEventListeners(handle, downEvent, moveEvent, upEvent) {+ handle.addEventListener(downEvent, (e) => {+ e.preventDefault();+ isResizing = true;+ startX = e.touches ? e.touches[0].clientX : e.clientX;+ startY = e.touches ? e.touches[0].clientY : e.clientY;+ startWidth = handle.parentElement.offsetWidth;+ startHeight = handle.parentElement.offsetHeight;+ handle.parentElement.querySelector('iframe').style.pointerEvents = "none";+ document.addEventListener(moveEvent, resize);+ document.addEventListener(upEvent, stopResize);+ document.body.style.cursor = "nwse-resize";+ });+ }++ window.addEventListener('message', (event) => {+ const message = event.data;++ if (message.type === 'videoContainerUpdate') {+ const { portrait } = message;++ const iframes = document.querySelectorAll('.container iframe');+ let targetIframe = null;++ for (let iframe of iframes) {+ if (iframe.contentWindow === event.source) {+ targetIframe = iframe;+ break;+ }+ }++ if (!targetIframe) return;+ const rectangle = targetIframe.closest('.container');+ if (!rectangle) return;++ const currentIsPortrait = rectangle.dataset.portrait === "true";+ if (currentIsPortrait === portrait) return;++ rectangle.dataset.portrait = portrait ? "true" : "false";++ if (window.innerWidth <= 600) {+ const currentWidth = rectangle.clientWidth;+ const newHeight = portrait+ ? Math.max(MIN_DIMENSION, currentWidth * (16 / 9))+ : Math.floor(currentWidth * (9 / 16));+ rectangle.style.height = `${newHeight}px`;++ const allRectangles = Array.from(document.querySelectorAll('.container'));+ let currentTop = 0;++ for (let i = 0; i < allRectangles.length; i++) {+ const rect = allRectangles[i];+ rect.style.top = `${currentTop}px`;+ currentTop += rect.clientHeight + 2;+ }++ const lastRectangle = allRectangles[allRectangles.length - 1];+ const lastRectangleBottom = parseInt(lastRectangle.style.top, 10) + lastRectangle.clientHeight;+ document.body.style.overflowY = 'scroll';+ document.body.style.minHeight = `${lastRectangleBottom}px`;+ } else {+ const currentWidth = rectangle.offsetWidth;+ const currentHeight = rectangle.offsetHeight;++ if (portrait) {+ // Switching to portrait: base on current height or min dimension+ const baseHeight = Math.max(MIN_DIMENSION, currentHeight);+ const newWidth = baseHeight * (9 / 16);+ const newHeight = baseHeight;+ rectangle.style.width = `${newWidth}px`;+ rectangle.style.height = `${newHeight}px`;+ } else {+ // Switching to landscape: base on current width or min dimension+ const baseWidth = Math.max(MIN_DIMENSION, currentWidth);+ const newHeight = baseWidth * (9 / 16);+ const newWidth = baseWidth;+ rectangle.style.width = `${newWidth}px`;+ rectangle.style.height = `${newHeight}px`;+ }+ }+ updateURL();+ }+ });++ function updateURL() {+ const params = new URLSearchParams();+ rectangles.forEach((rect, url) => {+ const rectInfo = {+ left: rect.style.left,+ top: rect.style.top,+ width: rect.style.width,+ height: rect.style.height,+ portrait: rect.dataset.portrait === "true"+ };+ params.append(url, JSON.stringify(rectInfo));+ });+ window.history.replaceState({}, '', `${window.location.pathname}?${params}`);+ }+ </script>+</body>+</html>diff --git a/ios/clearcam/player.html b/ios/clearcam/player.htmlnew file mode 100644index 0000000..9c2fbe1--- /dev/null+++ b/ios/clearcam/player.html@@ -0,0 +1,1213 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <style>+ body {+ font-family: Arial, sans-serif;+ text-align: center;+ margin: 0;+ padding: 0;+ overflow: hidden; /* Prevents body scrolling */+ height: 100vh;+ width: 100vw;+ }+ #videoContainer {+ position: absolute;+ top: 0;+ left: 0;+ width: 100vw;+ height: 100vh;+ background: black;+ display: flex;+ justify-content: center;+ align-items: center;+ overflow: hidden;+ }+ .video-wrapper {+ width: 100%;+ height: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ }+ video {+ width: 100%;+ height: 100%;+ object-fit: contain; /* Ensures the video fits within the container with letterboxing or pillarboxing */+ }++ .videoPlayer {+ width: 100%;+ height: 100%;+ object-fit: contain; /* Ensure video fits within the container */+ }+ #controls {+ position: absolute;+ bottom: 0;+ width: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ background: rgba(0, 0, 0, 0.5);+ padding: 10px;+ opacity: 0;+ transition: opacity 0.3s;+ box-sizing: border-box;+ }+ #controls.show {+ opacity: 1;+ }+ .top-controls {+ display: flex;+ align-items: center;+ width: 100%;+ justify-content: space-between;+ margin-bottom: 10px;+ box-sizing: border-box;+ }+ #progress {+ width: 100%;+ height: 10px;+ background-color: #ccc;+ cursor: pointer;+ position: relative;+ border-radius: 5px;+ box-sizing: border-box;+ overflow: hidden;+ }++ #progress-bar {+ height: 100%;+ background-color: #007bff;+ border-radius: 5px;+ position: absolute;+ top: 0;+ left: 0;+ width: 0;+ }++ .gap-indicator {+ position: absolute;+ top: 0;+ height: 100%;+ background: repeating-linear-gradient(+ -45deg,+ black,+ black 3px,+ grey 3px,+ grey 6px+ );+ pointer-events: none;+ }++ button {+ background: none;+ border: none;+ padding: 0;+ margin: 0;+ }+ #timeDisplay {+ color: white;+ margin-left: 10px;+ }+ #fullscreenBtn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 40px;+ padding: 8px;+ cursor: pointer;+ background: transparent;+ border: none;+ outline: none;+ }++ #controls {+ position: absolute;+ bottom: 0;+ width: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ background: rgba(0, 0, 0, 0.5);+ padding: 10px;+ opacity: 0;+ visibility: hidden;+ transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s;+ box-sizing: border-box;+ }++ #controls.show {+ opacity: 1;+ visibility: visible;+ transition: opacity 0.3s ease-in-out;+ }++ #playPauseBtn {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: 10;+ background: rgba(0, 0, 0, 0.5);+ border-radius: 50%;+ width: 60px;+ height: 60px;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s, background 0.3s;+ opacity: 0; /* Start hidden */+ visibility: hidden; /* Start hidden */+ }++ #playPauseBtn.show {+ opacity: 1; /* Show when .show is added */+ visibility: visible; /* Show when .show is added */+ transition: opacity 0.3s ease-in-out;+ }++ #playPauseBtn:hover {+ background: rgba(0, 0, 0, 0.7);+ }++ #playPauseBtn svg {+ width: 30px;+ height: 30px;+ }++ /* Adjust the top controls to align time and fullscreen button to the right */+ .top-controls {+ justify-content: flex-end;+ }++ .top-controls #timeDisplay {+ margin-right: 10px;+ }+ /* Existing styles remain the same until .top-controls */++++ #classSelector {+ margin-right: 0; /* Remove margin for the last element */+ }++ /* Adjust the bottom controls to remove the date picker and select dropdown */+ #controls {+ position: absolute;+ bottom: 0;+ width: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ background: rgba(0, 0, 0, 0.5);+ padding: 10px;+ opacity: 0;+ visibility: hidden;+ transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s;+ box-sizing: border-box;+ }++ #controls.show {+ opacity: 1;+ visibility: visible;+ transition: opacity 0.3s ease-in-out;+ }++ /* Adjust the time display and fullscreen button container */+ .top-controls {+ display: flex;+ align-items: center;+ width: 100%;+ justify-content: flex-end; /* Align to the right */+ gap: 10px; /* Add gap between elements */+ }++ #timeDisplay {+ font-size: 14px; /* Smaller font size for compactness */+ white-space: nowrap; /* Prevent wrapping */+ color: white; /* White text */+ }++ #fullscreenBtn {+ width: 30px; /* Smaller button for compactness */+ height: 30px;+ padding: 5px;+ background: transparent;+ border: none;+ cursor: pointer;+ }++ #topControls {+ position: absolute;+ top: 0;+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: flex-end; /* Align items to the right */+ background: rgba(0, 0, 0, 0.5);+ padding: 10px;+ box-sizing: border-box;+ opacity: 0;+ visibility: hidden;+ transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s;+ z-index: 5; /* Ensure it's above the video */+ gap: 10px; /* Add gap between elements */+ }++ #topControls.show {+ opacity: 1;+ visibility: visible;+ transition: opacity 0.3s ease-in-out;+ }++ #datePicker, #classSelector {+ flex: 0 1 auto; /* Don't grow, but allow shrinking */+ min-width: 120px; /* Set a minimum width */+ max-width: 200px; /* Set a maximum width */+ font-size: 14px; /* Smaller font size for compactness */+ padding: 5px; /* Smaller padding for compactness */+ background: rgba(255, 255, 255, 0.1); /* Slightly transparent background */+ border: 1px solid rgba(255, 255, 255, 0.3); /* Light border */+ color: white; /* White text */+ border-radius: 4px; /* Rounded corners */+ }++ /* Media query for smaller screens */+ @media (max-width: 600px) {+ #datePicker, #classSelector {+ min-width: 100px; /* Smaller minimum width for mobile */+ max-width: 150px; /* Smaller maximum width for mobile */+ font-size: 12px; /* Even smaller font size for mobile */+ padding: 4px; /* Even smaller padding for mobile */+ }++ #timeDisplay {+ font-size: 12px; /* Smaller font size for mobile */+ }++ #fullscreenBtn {+ width: 24px; /* Smaller button for mobile */+ height: 24px;+ padding: 4px;+ }+ }++ </style>+</head>+<body>+ <div id="videoContainer">+ <div class="video-wrapper">+ <!-- Video elements remain the same -->+ <video class="videoPlayer" playsinline webkit-playsinline muted></video>+ <video class="videoPlayer" playsinline webkit-playsinline muted style="display: none;"></video>+ <video class="videoPlayer" playsinline webkit-playsinline muted style="display: none;"></video>+ <video class="videoPlayer" playsinline webkit-playsinline muted style="display: none;"></video>+ <video class="videoPlayer" playsinline webkit-playsinline muted style="display: none;"></video>+ <video class="videoPlayer" playsinline webkit-playsinline muted style="display: none;"></video>++ <!-- New top controls bar, to find less shit icon -->+ <div id="topControls">+ <!-- Existing download icon -->+ <a href="/events.html" id="downloadIcon" target="_blank" rel="noopener noreferrer">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px">+ <path d="M15.5 14h-.79l-.28-.27a6.471 6.471 0 0 0 1.48-4.23C15.91 6.01 13.43 3.5 10.5 3.5S5.09 6.01 5.09 9.5 7.57 15.5 10.5 15.5c1.61 0 3.09-.59 4.23-1.48l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-5 0C8.01 14 6 11.99 6 9.5S8.01 5 10.5 5 15 7.01 15 9.5 12.99 14 10.5 14z"/>+ </svg>+ </a>+ <input type="date" id="datePicker" name="datePicker">+ </div>++ <!-- Bottom controls (progress bar, time display, fullscreen button) -->+ <div id="controls">+ <div class="top-controls">+ <div id="timeDisplay">0:00 / 0:00</div>+ <button id="fullscreenBtn">+ <svg id="fullscreenIcon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px">+ <path d="M3 3h6v2H5v4H3zm12 0h6v6h-2V5h-4zm6 12v6h-6v-2h4v-4zm-12 6H3v-6h2v4h4z"/>+ </svg>+ </button>+ </div>+ <div id="progress">+ <div id="progress-bar"></div>+ <div id="gaps-container"></div>+ </div>+ </div>++ <!-- Play/Pause button -->+ <button id="playPauseBtn">+ <svg id="playIcon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px">+ <path d="M8 5v14l11-7z"/>+ </svg>+ <svg id="pauseIcon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px" style="display: none;">+ <path d="M6 19h4V5H6zm8-14v14h4V5h-4z"/>+ </svg>+ </button>+ </div>+ </div>+ <script>+ let n_segments = 0; //not all new segments will get added to segments if some are removed, indexes will be maintained at backend though+ const yolo_classes = [+ ["person", "red"], ["bicycle", "green"], ["car", "blue"],+ ["motorcycle", "cyan"], ["airplane", "magenta"], ["bus", "yellow"],+ ["train", "orange"], ["truck", "purple"], ["boat", "brown"],+ ["traffic light", "rgb(128, 179, 51)"], ["fire hydrant", "rgb(204, 26, 26)"],+ ["stop sign", "rgb(77, 77, 204)"], ["parking meter", "rgb(179, 128, 77)"],+ ["bench", "rgb(102, 102, 51)"], ["bird", "rgb(26, 128, 230)"],+ ["cat", "rgb(204, 51, 153)"], ["dog", "rgb(230, 77, 77)"],+ ["horse", "rgb(51, 153, 179)"], ["sheep", "rgb(179, 77, 128)"],+ ["cow", "rgb(102, 204, 102)"], ["elephant", "rgb(77, 102, 230)"],+ ["bear", "rgb(153, 51, 204)"], ["zebra", "rgb(204, 128, 51)"],+ ["giraffe", "rgb(128, 230, 26)"], ["backpack", "rgb(77, 179, 102)"],+ ["umbrella", "rgb(102, 153, 230)"], ["handbag", "rgb(230, 51, 128)"],+ ["tie", "rgb(128, 77, 179)"], ["suitcase", "rgb(153, 179, 51)"],+ ["frisbee", "rgb(179, 51, 102)"], ["skis", "rgb(77, 230, 77)"],+ ["snowboard", "rgb(204, 26, 153)"], ["sports ball", "rgb(102, 77, 204)"],+ ["kite", "rgb(51, 128, 179)"], ["baseball bat", "rgb(153, 102, 51)"],+ ["baseball glove", "rgb(179, 26, 102)"], ["skateboard", "rgb(128, 204, 128)"],+ ["surfboard", "rgb(204, 77, 153)"], ["tennis racket", "rgb(51, 179, 230)"],+ ["bottle", "rgb(230, 51, 77)"], ["wine glass", "rgb(153, 153, 77)"],+ ["cup", "rgb(77, 102, 230)"], ["fork", "rgb(102, 179, 51)"],+ ["knife", "rgb(204, 51, 128)"], ["spoon", "rgb(153, 77, 179)"],+ ["bowl", "rgb(51, 204, 102)"], ["banana", "rgb(179, 179, 26)"],+ ["apple", "rgb(230, 26, 102)"], ["sandwich", "rgb(102, 128, 204)"],+ ["orange", "rgb(204, 153, 51)"], ["broccoli", "rgb(77, 204, 77)"],+ ["carrot", "rgb(179, 51, 153)"], ["hot dog", "rgb(230, 77, 128)"],+ ["pizza", "rgb(128, 77, 204)"], ["donut", "rgb(204, 26, 102)"],+ ["cake", "rgb(179, 128, 26)"], ["chair", "rgb(153, 51, 102)"],+ ["couch", "rgb(102, 153, 51)"], ["potted plant", "rgb(204, 102, 128)"],+ ["bed", "rgb(77, 179, 179)"], ["dining table", "rgb(128, 204, 77)"],+ ["toilet", "rgb(179, 102, 153)"], ["tv", "rgb(230, 128, 51)"],+ ["laptop", "rgb(153, 77, 179)"], ["mouse", "rgb(51, 230, 128)"],+ ["remote", "rgb(204, 102, 77)"], ["keyboard", "rgb(77, 153, 204)"],+ ["cell phone", "rgb(179, 77, 230)"], ["microwave", "rgb(102, 230, 102)"],+ ["oven", "rgb(128, 179, 51)"], ["toaster", "rgb(230, 51, 77)"],+ ["sink", "rgb(153, 204, 77)"], ["refrigerator", "rgb(204, 102, 179)"],+ ["book", "rgb(77, 128, 230)"], ["clock", "rgb(179, 179, 51)"],+ ["vase", "rgb(230, 102, 128)"], ["scissors", "rgb(51, 179, 204)"],+ ["teddy bear", "rgb(153, 77, 230)"], ["hair drier", "rgb(204, 51, 77)"],+ ["toothbrush", "rgb(102, 179, 153)"]+ ];+++ let currentDate = "";+ const dateParam = getQueryParam("date");+ if (!dateParam) {+ const fetchStartTime = new Date();+ currentDate = formatDate(fetchStartTime);+ } else{+ currentDate = dateParam;+ }++ let segments = [];+ let gaps = [];+ let totalDuration = 0;+ let retryTimeout = 2000;+++ const videoPlayers = document.querySelectorAll(".videoPlayer");+ let is_prepared = new Array(videoPlayers.length).fill(false); //todo, store in one obj+ const playPauseBtn = document.getElementById('playPauseBtn');+ const playIcon = document.getElementById('playIcon');+ const pauseIcon = document.getElementById('pauseIcon');+ const progressBar = document.getElementById('progress-bar');+ const progress = document.getElementById('progress');+ const timeDisplay = document.getElementById('timeDisplay');++ let video_index = 0;+ let currentSegment = 0;+ let isPlaying = false;+ let isScrubbing = false;+ let isWaitingForNextSegment = false;+ let wasPlayingBeforeScrub = false;+ let shape_idx = -1;++ let hideControlsTimeout;+ const controls = document.getElementById('controls');+ const topControls = document.getElementById('topControls');+ const videoContainer = document.getElementById('videoContainer');++ //todo+ topControls.addEventListener('focusin', showControls);+ topControls.addEventListener('focusout', hideControls);+ controls.addEventListener('focusin', showControls);+ controls.addEventListener('focusout', hideControls);++ function showControls() {+ controls.classList.add('show');+ topControls.classList.add('show');+ playPauseBtn.classList.add('show'); // Show the play/pause button+ clearTimeout(hideControlsTimeout);+ hideControlsTimeout = setTimeout(() => {+ topControls.classList.remove('show');+ controls.classList.remove('show');+ playPauseBtn.classList.remove('show'); // Hide the play/pause button+ controls.style.transform = 'translateY(0.0001px)'; // Tiny nudge to force repaint+ topControls.style.transform = 'translateY(0.0001px)'; // Tiny nudge to force repaint+ }, 4000);+ }++ function hideControls() {+ if (!document.activeElement.closest('#topControls') && !document.activeElement.closest('#controls')) {+ topControls.classList.remove('show');+ controls.classList.remove('show');+ playPauseBtn.classList.remove('show'); // Hide the play/pause button+ topControls.style.transform = 'translateY(0.0001px)'; // Safari-specific hack+ controls.style.transform = 'translateY(0.0001px)'; // Safari-specific hack+ }+ }++ function toggleControls() {+ if (controls.classList.contains('show')) {+ hideControls();+ } else {+ showControls();+ }+ }++ // Event listeners to show/hide controls+ videoContainer.addEventListener('mousemove', showControls);+ videoContainer.addEventListener('mouseleave', hideControls);+ videoContainer.addEventListener('touchend', toggleControls);+ videoContainer.addEventListener('click', toggleControls);++ function retrySegment(videoElement) {+ console.warn(`Retrying segment: ${segments[currentSegment].url}`);+ setTimeout(() => {+ videoElement.src = segments[currentSegment].url;+ videoElement.load();+ videoElement.play();+ }, retryTimeout);+ }++ async function updateTimeline() {+ const startTimestamp = segments[0].timeStamp;+ let adjustedStartTimestamp;++ if (startTimestamp < 0) {+ adjustedStartTimestamp = (24 * 3600) + startTimestamp; // Possible hack?+ } else {+ adjustedStartTimestamp = startTimestamp;+ }++ const currentTime = adjustedStartTimestamp + videoPlayers[video_index].currentTime + segments[currentSegment].cumulativeStart;+ let frames = segments[currentSegment].frames;+ let show_new = false;++ if (frames) {+ while ((shape_idx + 1 < frames.length) && (currentTime > frames[shape_idx + 1].frame_timeStamp)) {+ shape_idx += 1;+ show_new = true;+ }++ if (show_new) {+ let n_boxes = document.querySelectorAll(".bounding-box").length;+ let aspect_ratio = frames[shape_idx].aspect_ratio;+ let res = frames[shape_idx].res;++ for (let i = 0; i < frames[shape_idx].squares.length; i++) {+ if (portrait) {+ let originX = frames[shape_idx].squares[i].originX / (res / aspect_ratio);+ let originY = frames[shape_idx].squares[i].originY / res;+ let length = (frames[shape_idx].squares[i].bottomRightX - frames[shape_idx].squares[i].originX) / (res / aspect_ratio);+ let height = (frames[shape_idx].squares[i].bottomRightY - frames[shape_idx].squares[i].originY) / res;+ if (aspect_ratio !== 9 / 16) {+ let scale = aspect_ratio / (16 / 9);+ let offset = (1 - scale) / 2;+ originY = originY * scale + offset;+ height *= scale;+ }+ drawBoundingBox(originX, originY, length, height, yolo_classes[frames[shape_idx].squares[i].classIndex][1], yolo_classes[frames[shape_idx].squares[i].classIndex][0]);+ } else {+ let originX = frames[shape_idx].squares[i].originX / res;+ let originY = frames[shape_idx].squares[i].originY / (res / aspect_ratio);+ let length = (frames[shape_idx].squares[i].bottomRightX - frames[shape_idx].squares[i].originX) / res;+ let height = (frames[shape_idx].squares[i].bottomRightY - frames[shape_idx].squares[i].originY) / (res / aspect_ratio);+ if (aspect_ratio !== 16 / 9) {+ let scale = aspect_ratio / (16 / 9);+ let offset = (1 - scale) / 2;+ originX = originX * scale + offset;+ length *= scale;+ }+ drawBoundingBox(originX, originY, length, height, yolo_classes[frames[shape_idx].squares[i].classIndex][1], yolo_classes[frames[shape_idx].squares[i].classIndex][0]);+ }+ }++ // Remove old bounding boxes+ let boundingBoxes = document.querySelectorAll(".bounding-box");+ for (let i = 0; i < n_boxes; i++) {+ boundingBoxes[i].remove();+ }+ }+ }++ progressBar.style.width = `${(currentTime - adjustedStartTimestamp) / totalDuration * 100}%`;+ timeDisplay.innerText = `${formatTime(currentTime)} / ${formatTime(adjustedStartTimestamp + totalDuration)}`;+ updateGaps();+ }++ function hideMultiWindowIconInIframe() {+ const multiWindowIcon = document.getElementById('multiWindowIcon');+ if (window.self !== window.top) { // Page is in an iframe+ multiWindowIcon.style.display = 'none';+ } else { // Page is standalone+ multiWindowIcon.style.display = 'inline-block';+ }+ }+ document.addEventListener('DOMContentLoaded', hideMultiWindowIconInIframe);+++ function updateGaps() {+ const progressBar = document.getElementById("progress");+ const gapsContainer = document.getElementById("gaps-container");+ gapsContainer.innerHTML = ''; // Clear existing gaps++ gaps.forEach(([start, duration]) => {+ const gapElement = document.createElement("div");+ gapElement.classList.add("gap-indicator");+++ const gapStartPercent = (start / totalDuration) * 100;+ const gapWidthPercent = (duration / totalDuration) * 100;++ gapElement.style.left = `${gapStartPercent}%`;+ gapElement.style.width = `${gapWidthPercent}%`;++ gapsContainer.appendChild(gapElement);+ });+ }++ function togglePlayPause() {+ if (isPlaying) {+ videoPlayers[video_index].pause();+ playIcon.style.display = 'block';+ pauseIcon.style.display = 'none';+ isPlaying = false;+ } else {+ videoPlayers[video_index].play();+ playIcon.style.display = 'none';+ pauseIcon.style.display = 'block';+ isPlaying = true;+ }+ updateTimeline();+ }++ playPauseBtn.addEventListener('click', togglePlayPause);+++ videoContainer.addEventListener('dblclick', (e) => {+ const containerWidth = videoContainer.clientWidth;+ const x = e.clientX;+ const currentTime = videoPlayers[video_index].currentTime + segments[currentSegment].cumulativeStart;++ if (x > containerWidth * 0.6) {+ // Double-tap/click on the right side to skip forward 10s+ let newTime = Math.min(currentTime + 10, totalDuration);+ seekToTime(newTime);+ } else if (x < containerWidth * 0.4) {+ // Double-tap/click on the left side to rewind 10s+ let newTime = Math.max(currentTime - 10, 0);+ seekToTime(newTime);+ }++ updateTimeline();+ });+++ function seekToTime(time) {+ clearBoundingBoxes();+ is_prepared = new Array(videoPlayers.length).fill(false);+ let targetSegment = segments.findIndex(segment => time < segment.cumulativeStart + segment.duration);+ targetSegment = targetSegment === -1 ? segments.length - 1 : targetSegment;+ currentSegment = targetSegment;+ videoPlayers[video_index].src = segments[currentSegment].url;+ videoPlayers[video_index].currentTime = time - segments[currentSegment].cumulativeStart;++ shape_idx = 0;+ if (isPlaying) {+ videoPlayers[video_index].play();+ }+ }++ function getQueryParam(name) {+ const urlParams = new URLSearchParams(window.location.search);+ return urlParams.get(name);+ }++ function formatDate(date) {+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, '0');+ const day = String(date.getDate()).padStart(2, '0');+ return `${year}-${month}-${day}`;+ }++ document.addEventListener('DOMContentLoaded', function() {+ const datePicker = document.getElementById('datePicker');+ datePicker.value = currentDate;+ datePicker.addEventListener('change', function() {+ n_segments = 0;+ const selectedDate = new Date(this.value);+ const formattedDate = formatDate(selectedDate);+ window.location.href = `${window.location.pathname}?date=${formattedDate}`;+ });+ });++ let isFetchingSegments = false;+ async function fetchSegments() {+ if (isFetchingSegments) return;+ isFetchingSegments = true;++ try {+ let start = -1;+ if(n_segments > 0){+ start = segments[n_segments - 1].timeStamp + segments[n_segments - 1].duration;+ }+ const response = await fetch(`/get-segments?date=${currentDate}&start=${start}`);+ if (response.ok) {+ const newSegments = await response.json();+ if (Array.isArray(newSegments)) {+ const oldTotalDuration = totalDuration;++ let cumulativeStart = totalDuration;+ let i = 0;+ let next_i = 1;+ while(next_i < newSegments.length) {+ if(newSegments[i].url.length == 0){+ i=next_i;+ next_i+=1;+ }+ while(newSegments[next_i].url.length == 0 && next_i < newSegments.length){+ next_i += 1;+ }+ if(next_i >= newSegments.length){+ break;+ }+ const segment = newSegments[i];+ const timeDifference = newSegments[next_i].timeStamp - newSegments[i].timeStamp;+ const lostFrames = timeDifference - segment.duration;+ const currentCumulativeStart = cumulativeStart;+ cumulativeStart += timeDifference;+ segments.push({+ ...segment,+ cumulativeStart: currentCumulativeStart,+ lostFrames: lostFrames > 0 ? lostFrames : 0,+ });+ if(lostFrames > 1){ //todo why 60+ gaps.push([currentCumulativeStart + segment.duration,lostFrames]);+ }+ i=next_i;+ next_i+=1;+ }+ n_segments += i;+ totalDuration = segments[segments.length-1].duration + (segments[segments.length - 1].timeStamp - segments[0].timeStamp);+ if (totalDuration !== oldTotalDuration) {+ updateTimeline();+ preloadNextSegments();++ if (videoPlayers[video_index].currentTime + segments[currentSegment].cumulativeStart === 0 ||+ (isPlaying && isWaitingForNextSegment && segments.length < currentSegment + 1)) {+ const currentVideo = videoPlayers[video_index];+ currentVideo.src = segments[currentSegment].url;+ currentVideo.currentTime = 0;+ currentVideo.style.display = "block";++ // Hide other video players+ for (let i = 1; i < videoPlayers.length; i++) {+ videoPlayers[(video_index + i) % videoPlayers.length].style.display = "none";+ }++ currentVideo.play();+ isPlaying = true;+ playIcon.style.display = "none";+ pauseIcon.style.display = "block";++ // Adjust container dimensions based on video orientation+ currentVideo.addEventListener('loadedmetadata', () => {+ adjustContainerForOrientation(currentVideo);+ });+ preloadNextSegments();+ }+ if (isWaitingForNextSegment && segments.length > currentSegment + 1) {+ isWaitingForNextSegment = false;+ switchToNextSegment();+ }+ }+ }+ }+ } catch (error) {+ console.error('Failed to fetch segments:', error);+ } finally {+ isFetchingSegments = false;+ }+ }+++ function formatTime(seconds) {+ const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');+ const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');+ const secs = Math.floor(seconds % 60).toString().padStart(2, '0');+ return `${hours}:${minutes}:${secs}`;+ }++ function scrub(e) {+ const scrubTime = Math.min(((e.offsetX || e.touches[0].clientX - progress.getBoundingClientRect().left) / progress.offsetWidth) * totalDuration, totalDuration - 1);++ let targetSegment = segments.findIndex(segment => scrubTime < segment.cumulativeStart + segment.duration);+ targetSegment = targetSegment === -1 ? segments.length - 1 : targetSegment;++ const targetTime = scrubTime - segments[targetSegment].cumulativeStart;++ if (targetSegment >= 0 && targetSegment < segments.length) {+ currentSegment = targetSegment;+ videoPlayers[video_index].src = segments[currentSegment].url;+ videoPlayers[video_index].currentTime = targetTime;+ if (wasPlayingBeforeScrub) {+ videoPlayers[video_index].play();+ }+ }++ updateTimeline();+ preloadNextSegments();+ }++ function startScrubbing(e) {+ wasPlayingBeforeScrub = !videoPlayers[video_index].paused;+ isScrubbing = true;+ scrub(e);+ document.addEventListener("mousemove", scrubWhileDragging);+ document.addEventListener("mouseup", stopScrubbing);+ document.addEventListener("touchmove", scrubWhileDragging);+ document.addEventListener("touchend", stopScrubbing);+ }++ function scrubWhileDragging(e) {+ if (isScrubbing) {+ scrub(e);+ }+ }++ function stopScrubbing() {+ clearBoundingBoxes();+ isScrubbing = false;+ if (!wasPlayingBeforeScrub) {+ videoPlayers[video_index].pause();+ }+ document.removeEventListener("mousemove", scrubWhileDragging);+ document.removeEventListener("mouseup", stopScrubbing);+ document.removeEventListener("touchmove", scrubWhileDragging);+ document.removeEventListener("touchend", stopScrubbing);+ }++ async function preloadNextSegments() {+ let x = 1;+ while (x < videoPlayers.length) {+ let current_x = x;++ if (currentSegment + x < segments.length) {+ let segment = segments[currentSegment + current_x];+ let player = videoPlayers[(video_index + current_x) % videoPlayers.length];++ // Preload video if not already loaded+ if (!player.src.endsWith(segment.url)) {+ player.src = segment.url;+ player.load();+ player.preload = 'auto';+ }++ // Preload frames if not already loaded or fetching+ if (!segment.frames && !segment.fetchingFrames) {+ segment.fetchingFrames = true; // Set fetching flag to avoid duplicate requests+ try {+ const response = await fetch(`/get-frames?url=${encodeURIComponent(segment.url)}`);+ if (!response.ok) throw new Error(`Failed to fetch frames for ${segment.url}`);+ const frames = await response.json();+ segment.frames = frames; // Store frames to prevent refetching+ } catch (error) {+ console.error("Error fetching frames:", error);+ }+ segment.fetchingFrames = false; // Reset fetching flag+ }+ }+ x++;+ }+ }++ let portrait = false;++ function adjustContainerForOrientation(videoElement) {+ const videoContainer = document.getElementById('videoContainer');++ // Get the video's dimensions+ const videoWidth = videoElement.videoWidth;+ const videoHeight = videoElement.videoHeight;++ // Determine if the video is in portrait mode+ portrait = videoHeight > videoWidth;++ // Get the window's dimensions+ const windowWidth = window.innerWidth;+ const windowHeight = window.innerHeight;++ // Adjust the container's dimensions based on the video's orientation+ if (portrait) {+ // Portrait mode (9:16 aspect ratio)+ const containerHeight = Math.min(windowHeight, windowWidth * (16 / 9));+ const containerWidth = containerHeight * (9 / 16);++ videoContainer.style.width = containerWidth + 'px';+ videoContainer.style.height = containerHeight + 'px';+ } else {+ // Landscape mode (16:9 aspect ratio)+ const containerWidth = Math.min(windowWidth, windowHeight * (16 / 9));+ const containerHeight = containerWidth * (9 / 16);++ videoContainer.style.width = containerWidth + 'px';+ videoContainer.style.height = containerHeight + 'px';+ }++ // Ensure the container doesn't exceed the viewport dimensions+ videoContainer.style.maxWidth = '100vw';+ videoContainer.style.maxHeight = '100vh';++ // Send the container's dimensions and orientation to the parent page+ const message = {+ type: 'videoContainerUpdate',+ width: videoContainer.offsetWidth,+ height: videoContainer.offsetHeight,+ portrait: portrait,+ };+ window.parent.postMessage(message, '*'); // Send to the parent page+ }++ // Example usage with a video element+ const videoElement = document.querySelector('video'); // Replace with your video element+ videoElement.addEventListener('loadedmetadata', () => {+ adjustContainerForOrientation(videoElement);+ });++ // Optional: Handle window resizing to keep the container responsive+ window.addEventListener('resize', () => {+ adjustContainerForOrientation(videoElement);+ });+++ function switchToNextSegment() {+ if (currentSegment + 1 < segments.length) {+ let lostFrames = segments[currentSegment].lostFrames+ currentSegment++;+ is_prepared[video_index] = false;+ video_index = (video_index + 1) % videoPlayers.length;++ // Hide other video players+ for (let i = 1; i < videoPlayers.length; i++) {+ videoPlayers[(video_index + i) % videoPlayers.length].style.display = "none";+ }++ const currentVideo = videoPlayers[video_index];+ currentVideo.style.display = "block";++ // Play the video+ if(lostFrames < 60){+ console.log(`${lostFrames} - ${segments.length}`);+ setTimeout(() => {+ currentVideo.play().catch(() => {+ retrySegment(currentVideo);+ });+ }, lostFrames*1000 + 28); // to ms //todo +28ms is a hack to stop the playback playing slightly too fast,+ //+28 was picked from trial and error, but may be proportional to frame rate+ } else {+ currentVideo.play().catch(() => {+ retrySegment(currentVideo);+ });+ }++ // Adjust container dimensions based on video orientation+ currentVideo.addEventListener('loadedmetadata', () => {+ adjustContainerForOrientation(currentVideo);+ });++ // Preload the next segments+ preloadNextSegments();+ } else {+ isWaitingForNextSegment = true;+ }+ shape_idx = -1;+ }++ setInterval(updateTimeline, 50);++ for(let i = 0; i < videoPlayers.length; i++) {+ videoPlayers[i].addEventListener("timeupdate", updateTimeline);+ videoPlayers[i].addEventListener("ended", switchToNextSegment);+ videoPlayers[i].addEventListener("error", () => retrySegment(videoPlayers[i]));+ }++ progress.addEventListener("mousedown", startScrubbing);+ progress.addEventListener("touchstart", startScrubbing);++ setInterval(fetchSegments, 500);++ const fullscreenBtn = document.getElementById('fullscreenBtn');+ fullscreenBtn.addEventListener('click', () => {+ clearBoundingBoxes(); //todo, redraw instead?+ if (!document.fullscreenElement) {+ if (videoContainer.requestFullscreen) {+ videoContainer.requestFullscreen();+ } else if (videoContainer.mozRequestFullScreen) { /* Firefox */+ videoContainer.mozRequestFullScreen();+ } else if (videoContainer.webkitRequestFullscreen) { /* Chrome, Safari and Opera */+ videoContainer.webkitRequestFullscreen();+ } else if (videoContainer.msRequestFullscreen) { /* IE/Edge */+ videoContainer.msRequestFullscreen();+ }+ } else {+ if (document.exitFullscreen) {+ document.exitFullscreen();+ } else if (document.mozCancelFullScreen) { /* Firefox */+ document.mozCancelFullScreen();+ } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */+ document.webkitExitFullscreen();+ } else if (document.msExitFullscreen) { /* IE/Edge */+ document.msExitFullscreen();+ }+ }+ });++ function isMobile() {+ return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);+ }++ if (isMobile()) {+ document.getElementById('fullscreenBtn').style.display = 'none';+ }++ async function handleVisibilityAndLoad() { //todo, clean++ if (isFetchingSegments) return;+ isFetchingSegments = true;++ try {+ let start = -1;+ if(n_segments > 0){+ start = segments[n_segments - 1].timeStamp + segments[n_segments - 1].duration;+ }+ const response = await fetch(`/get-segments?date=${currentDate}&start=${start}`);+ if (response.ok) {+ const newSegments = await response.json();+ if (Array.isArray(newSegments)) {+ const oldTotalDuration = totalDuration;++ let cumulativeStart = totalDuration;+ let i = 0;+ let next_i = 1;+ while(next_i < newSegments.length) {+ if(newSegments[i].url.length == 0){+ i=next_i;+ next_i+=1;+ }+ while(newSegments[next_i].url.length == 0 && next_i < newSegments.length){+ next_i += 1;+ }+ if(next_i >= newSegments.length){+ break;+ }+ const segment = newSegments[i];+ const timeDifference = newSegments[next_i].timeStamp - newSegments[i].timeStamp;+ const lostFrames = timeDifference - segment.duration;+ const currentCumulativeStart = cumulativeStart;+ cumulativeStart += timeDifference;+ segments.push({+ ...segment,+ cumulativeStart: currentCumulativeStart,+ lostFrames: lostFrames > 0 ? lostFrames : 0,+ });+ if(lostFrames > 1){ //todo why 60+ gaps.push([currentCumulativeStart + segment.duration,lostFrames]);+ }+ i=next_i;+ next_i+=1;+ }+ n_segments += i;+ totalDuration = segments[segments.length-1].duration + (segments[segments.length - 1].timeStamp - segments[0].timeStamp);+ if (totalDuration !== oldTotalDuration) {+ updateTimeline();+ //await preloadNextSegments();++ if (videoPlayers[video_index].currentTime + segments[currentSegment].cumulativeStart === 0 ||+ (isPlaying && isWaitingForNextSegment && segments.length < currentSegment + 1)) {+ const currentVideo = videoPlayers[video_index];+ currentVideo.src = segments[currentSegment].url;+ currentVideo.currentTime = 0;+ currentVideo.style.display = "block";++ // Hide other video players+ for (let i = 1; i < videoPlayers.length; i++) {+ videoPlayers[(video_index + i) % videoPlayers.length].style.display = "none";+ }++ currentVideo.play();+ isPlaying = true;+ playIcon.style.display = "none";+ pauseIcon.style.display = "block";++ // Adjust container dimensions based on video orientation+ currentVideo.addEventListener('loadedmetadata', () => {+ adjustContainerForOrientation(currentVideo);+ });+ }+ if (isWaitingForNextSegment && segments.length > currentSegment + 1) {+ isWaitingForNextSegment = false;+ switchToNextSegment();+ }+ }+ }+ }+ } catch (error) {+ console.error('Failed to fetch segments:', error);+ } finally {+ isFetchingSegments = false;+ let currentDate = "";+ const dateParam = getQueryParam("date");+ const fetchStartTime = new Date();+ currentDate = formatDate(fetchStartTime);+ const startParam = getQueryParam("start");+ if ((currentDate == dateParam || !dateParam) && !startParam) {+ if (isPlaying && segments.length > 0) {+ currentSegment = segments.length - 1;+ const currentVideo = videoPlayers[video_index];+ currentVideo.src = segments[currentSegment].url;++ currentVideo.addEventListener('loadedmetadata', function onMetadata() {+ currentVideo.currentTime = segments[currentSegment].duration;+ currentVideo.play().catch(() => {}); // Ensure play() is only called after metadata is loaded+ currentVideo.removeEventListener('loadedmetadata', onMetadata); // Cleanup event listener+ });+ }+ } else if (startParam) {+ for (let i = 0; i < segments.length; i++) {+ if (segments[i].timeStamp > startParam) {+ break;+ }+ currentSegment = i;+ }++ const currentVideo = videoPlayers[video_index];+ currentVideo.src = segments[currentSegment].url;++ currentVideo.addEventListener('loadedmetadata', function onMetadata() {+ let eventTime = startParam - segments[currentSegment].timeStamp;+ if (eventTime < segments[currentSegment].duration) {+ currentVideo.currentTime = eventTime;+ } else {+ currentVideo.currentTime = segments[currentSegment].duration;+ }++ currentVideo.play().catch(() => {}); // Ensure play() is only called after metadata is loaded+ currentVideo.removeEventListener('loadedmetadata', onMetadata); // Cleanup listener+ });+ }+++ //fetch first segment's frames! preload only does future ones+ if (!segments[currentSegment].frames && !segments[currentSegment].fetchingFrames) {+ segments[currentSegment].fetchingFrames = true; // Set fetching flag to avoid duplicate requests+ try {+ const response = await fetch(`/get-frames?url=${encodeURIComponent(segments[currentSegment].url)}`);+ if (!response.ok) throw new Error(`Failed to fetch frames for ${segments[currentSegment].url}`);+ const frames = await response.json();+ segments[currentSegment].frames = frames; // Store frames to prevent refetching+ } catch (error) {+ console.error("Error fetching frames:", error);+ }+ segments[currentSegment].fetchingFrames = false; // Reset fetching flag+ }++ await preloadNextSegments();++ //alert("PLAY!");+ videoPlayers[video_index].play().catch(() => {});+ window.history.replaceState({}, document.title, window.location.pathname); //remove params+ //alert(segments.length);+ }+ }++ // Handle visibility change+ document.addEventListener("visibilitychange", async () => {+ if (!document.hidden) {+ await handleVisibilityAndLoad();+ }+ });++ // Handle page load/refresh+ window.addEventListener("load", async () => {+ await handleVisibilityAndLoad();+ });++ function drawBoundingBox(relativeX, relativeY, relativeWidth, relativeHeight, color, label) {+ const container = document.getElementById("videoContainer");+ const video = container.querySelector("video");++ const containerAspectRatio = container.clientWidth / container.clientHeight;+ let videoWidth, videoHeight, offsetX, offsetY;++ if (portrait) {+ // Video is pillarboxed+ videoHeight = container.clientHeight;+ videoWidth = videoHeight * containerAspectRatio;+ } else {+ // Video is letterboxed+ videoWidth = container.clientWidth;+ videoHeight = videoWidth / containerAspectRatio;+ }++ let boxWrapper = document.createElement("div");+ boxWrapper.classList.add("bounding-box");++ // Create the bounding box+ let box = document.createElement("div");+ box.style.position = "absolute";+ box.style.left = `${relativeX * videoWidth}px`;+ box.style.top = `${relativeY * videoHeight}px`;+ box.style.width = `${relativeWidth * videoWidth}px`;+ box.style.height = `${relativeHeight * videoHeight}px`;+ box.style.border = `2px solid ${color}`;+ box.style.boxSizing = "border-box";+ box.style.pointerEvents = "none";++ // Create the label (interactive)+ let labelDiv = document.createElement("span");+ labelDiv.textContent = label;+ labelDiv.style.position = "absolute";+ labelDiv.style.top = "-20px";+ labelDiv.style.left = "0";+ labelDiv.style.background = color;+ labelDiv.style.color = "white";+ labelDiv.style.padding = "2px 5px";+ labelDiv.style.fontSize = "12px";+ labelDiv.style.fontFamily = "Arial, sans-serif";+ labelDiv.style.whiteSpace = "nowrap";+ labelDiv.style.pointerEvents = "auto"; //Keeps label clickable if needed+ box.style.zIndex = "1000";+ labelDiv.style.zIndex = "1001";++ box.appendChild(labelDiv);+ boxWrapper.appendChild(box);+ container.appendChild(boxWrapper);+ }++ function clearBoundingBoxes() {+ document.querySelectorAll(".bounding-box").forEach(box => box.remove());+ }++ function hideBoundingBoxes() {+ document.querySelectorAll(".bounding-box").forEach(box => box.style.display = "none");+ }+ function showBoundingBoxes() {+ document.querySelectorAll(".bounding-box").forEach(box => box.style.display = "");+ }+ </script>+</body>+</html>diff --git a/ios/clearcam/yolov8.py b/ios/clearcam/yolov8.pynew file mode 100644index 0000000..72ee4bc--- /dev/null+++ b/ios/clearcam/yolov8.py@@ -0,0 +1,410 @@+from tinygrad.nn import Conv2d, BatchNorm2d+from tinygrad.tensor import Tensor+from tinygrad.device import is_dtype_supported+from tinygrad import dtypes+import numpy as np+from itertools import chain+from pathlib import Path+import cv2+from collections import defaultdict+import time, sys+from tinygrad.helpers import fetch+from tinygrad.nn.state import safe_load, load_state_dict+import json++#Model architecture from https://github.com/ultralytics/ultralytics/issues/189+#The upsampling class has been taken from this pull request https://github.com/tinygrad/tinygrad/pull/784 by dc-dc-dc. Now 2(?) models use upsampling. (retinet and this)++#Pre processing image functions.+def compute_transform(image, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, stride=32) -> Tensor:+ shape = image.shape[:2] # current shape [height, width]+ new_shape = (new_shape, new_shape) if isinstance(new_shape, int) else new_shape+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])+ r = min(r, 1.0) if not scaleup else r+ new_unpad = (int(round(shape[1] * r)), int(round(shape[0] * r)))+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]+ dw, dh = (np.mod(dw, stride), np.mod(dh, stride)) if auto else (0.0, 0.0)+ new_unpad = (new_shape[1], new_shape[0]) if scaleFill else new_unpad+ dw /= 2+ dh /= 2+ image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR) if shape[::-1] != new_unpad else image+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))+ image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114))+ return Tensor(image)++def preprocess(im, imgsz=640, model_stride=32, model_pt=True):+ same_shapes = all(x.shape == im[0].shape for x in im)+ auto = same_shapes and model_pt+ im = [compute_transform(x, new_shape=imgsz, auto=auto, stride=model_stride) for x in im]+ im = Tensor.stack(*im) if len(im) > 1 else im[0].unsqueeze(0)+ im = im[..., ::-1].permute(0, 3, 1, 2) # BGR to RGB, BHWC to BCHW, (n, 3, h, w)+ im = im / 255.0 # 0 - 255 to 0.0 - 1.0+ return im+++def draw_bounding_boxes_and_save(orig_img_paths, output_img_paths, all_predictions, class_labels,size=640, conf_threshold=0.25):+ all_predictions = [all_predictions]+ color_dict = {label: tuple((((i+1) * 50) % 256, ((i+1) * 100) % 256, ((i+1) * 150) % 256)) for i, label in enumerate(class_labels)}+ font = cv2.FONT_HERSHEY_SIMPLEX++ def is_bright_color(color):+ r, g, b = color+ brightness = (r * 299 + g * 587 + b * 114) / 1000+ return brightness > 127++ for img_idx, (orig_img_path, output_img_path, predictions) in enumerate(zip(orig_img_paths, output_img_paths, all_predictions)):+ predictions = np.array(predictions)+ orig_img = cv2.imread(orig_img_path) if not isinstance(orig_img_path, np.ndarray) else cv2.imdecode(orig_img_path, 1)+ height, width, _ = orig_img.shape+ box_thickness = int((height + width) / 400)+ font_scale = (height + width) / 2500++ grouped_preds = defaultdict(list)+ object_count = defaultdict(int)++ for pred_np in predictions:+ grouped_preds[int(pred_np[-1])].append(pred_np)++ for pred in predictions:+ x1, y1, x2, y2, conf, class_id = pred+ if conf < conf_threshold: continue+ color = color_dict[class_labels[int(class_id)]]+ x1, y1, x2, y2 = map(int, (x1, y1, x2, y2))+ cv2.rectangle(orig_img, (x1, y1), (x2, y2), color, box_thickness)+ label = f"{class_labels[int(class_id)]} {conf:.2f}"+ text_size, _ = cv2.getTextSize(label, font, font_scale, 1)+ label_y, bg_y = (y1 - 4, y1 - text_size[1] - 4) if y1 - text_size[1] - 4 > 0 else (y1 + text_size[1], y1)+ cv2.rectangle(orig_img, (x1, bg_y), (x1 + text_size[0], bg_y + text_size[1]), color, -1)+ font_color = (0, 0, 0) if is_bright_color(color) else (255, 255, 255)+ cv2.putText(orig_img, label, (x1, label_y), font, font_scale, font_color, 1, cv2.LINE_AA)+ object_count[class_labels[int(class_id)]] += 1++ print(f"Image {img_idx + 1}:")+ print("Objects detected:")+ for obj, count in object_count.items():+ print(f"- {obj}: {count}")++ cv2.imwrite(output_img_path, orig_img)+ print(f'saved detections at {output_img_path}')++# utility functions for forward pass.+def dist2bbox(distance, anchor_points, xywh=True, dim=-1):+ lt, rb = distance.chunk(2, dim)+ x1y1 = anchor_points - lt+ x2y2 = anchor_points + rb+ if xywh:+ c_xy = (x1y1 + x2y2) / 2+ wh = x2y2 - x1y1+ return c_xy.cat(wh, dim=1)+ return x1y1.cat(x2y2, dim=1)++def make_anchors(feats, strides, grid_cell_offset=0.5):+ anchor_points, stride_tensor = [], []+ assert feats is not None+ for i, stride in enumerate(strides):+ _, _, h, w = feats[i].shape+ sx = Tensor.arange(w) + grid_cell_offset+ sy = Tensor.arange(h) + grid_cell_offset++ # this is np.meshgrid but in tinygrad+ sx = sx.reshape(1, -1).repeat([h, 1]).reshape(-1)+ sy = sy.reshape(-1, 1).repeat([1, w]).reshape(-1)++ anchor_points.append(Tensor.stack(sx, sy, dim=-1).reshape(-1, 2))+ stride_tensor.append(Tensor.full((h * w), stride))+ anchor_points = anchor_points[0].cat(anchor_points[1], anchor_points[2])+ stride_tensor = stride_tensor[0].cat(stride_tensor[1], stride_tensor[2]).unsqueeze(1)+ return anchor_points, stride_tensor++# this function is from the original implementation+def autopad(k, p=None, d=1): # kernel, padding, dilation+ if d > 1:+ k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size+ if p is None:+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad+ return p++def get_variant_multiples(variant):+ return {'n':(0.33, 0.25, 2.0), 's':(0.33, 0.50, 2.0), 'm':(0.67, 0.75, 1.5), 'l':(1.0, 1.0, 1.0), 'x':(1, 1.25, 1.0) }.get(variant, None)++def label_predictions(all_predictions):+ predictions_list = all_predictions.numpy()+ class_counts = defaultdict(int)+ for pred in predictions_list:+ prob = pred[4]+ class_id = int(pred[5])+ if prob != 0: class_counts[class_id] += 1+ return dict(class_counts)++#this is taken from https://github.com/tinygrad/tinygrad/pull/784/files by dc-dc-dc (Now 2 models use upsampling)+class Upsample:+ def __init__(self, scale_factor:int, mode: str = "nearest") -> None:+ assert mode == "nearest" # only mode supported for now+ self.mode = mode+ self.scale_factor = scale_factor++ def __call__(self, x: Tensor) -> Tensor:+ assert len(x.shape) > 2 and len(x.shape) <= 5+ (b, c), _lens = x.shape[:2], len(x.shape[2:])+ tmp = x.reshape([b, c, -1] + [1] * _lens) * Tensor.ones(*[1, 1, 1] + [self.scale_factor] * _lens)+ return tmp.reshape(list(x.shape) + [self.scale_factor] * _lens).permute([0, 1] + list(chain.from_iterable([[y+2, y+2+_lens] for y in range(_lens)]))).reshape([b, c] + [x * self.scale_factor for x in x.shape[2:]])++class Conv_Block:+ def __init__(self, c1, c2, kernel_size=1, stride=1, groups=1, dilation=1, padding=None):+ self.conv = Conv2d(c1,c2, kernel_size, stride, padding=autopad(kernel_size, padding, dilation), bias=False, groups=groups, dilation=dilation)+ self.bn = BatchNorm2d(c2, eps=0.001)++ def __call__(self, x):+ return self.bn(self.conv(x)).silu()++class Bottleneck:+ def __init__(self, c1, c2 , shortcut: bool, g=1, kernels: list = (3,3), channel_factor=0.5):+ c_ = int(c2 * channel_factor)+ self.cv1 = Conv_Block(c1, c_, kernel_size=kernels[0], stride=1, padding=None)+ self.cv2 = Conv_Block(c_, c2, kernel_size=kernels[1], stride=1, padding=None, groups=g)+ self.residual = c1 == c2 and shortcut++ def __call__(self, x):+ return x + self.cv2(self.cv1(x)) if self.residual else self.cv2(self.cv1(x))++class C2f:+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):+ self.c = int(c2 * e)+ self.cv1 = Conv_Block(c1, 2 * self.c, 1,)+ self.cv2 = Conv_Block((2 + n) * self.c, c2, 1)+ self.bottleneck = [Bottleneck(self.c, self.c, shortcut, g, kernels=[(3, 3), (3, 3)], channel_factor=1.0) for _ in range(n)]++ def __call__(self, x):+ y= list(self.cv1(x).chunk(2, 1))+ y.extend(m(y[-1]) for m in self.bottleneck)+ z = y[0]+ for i in y[1:]: z = z.cat(i, dim=1)+ return self.cv2(z)++class SPPF:+ def __init__(self, c1, c2, k=5):+ c_ = c1 // 2 # hidden channels+ self.cv1 = Conv_Block(c1, c_, 1, 1, padding=None)+ self.cv2 = Conv_Block(c_ * 4, c2, 1, 1, padding=None)++ # TODO: this pads with 0s, whereas torch function pads with -infinity. This results in a < 2% difference in prediction which does not make a difference visually.+ self.maxpool = lambda x : x.pad((k // 2, k // 2, k // 2, k // 2)).max_pool2d(kernel_size=k, stride=1)++ def __call__(self, x):+ x = self.cv1(x)+ x2 = self.maxpool(x)+ x3 = self.maxpool(x2)+ x4 = self.maxpool(x3)+ return self.cv2(x.cat(x2, x3, x4, dim=1))++class DFL:+ def __init__(self, c1=16):+ self.conv = Conv2d(c1, 1, 1, bias=False)+ x = Tensor.arange(c1)+ self.conv.weight.replace(x.reshape(1, c1, 1, 1))+ self.c1 = c1++ def __call__(self, x):+ b, c, a = x.shape # batch, channels, anchors+ return self.conv(x.reshape(b, 4, self.c1, a).transpose(2, 1).softmax(1)).reshape(b, 4, a)++#backbone+class Darknet:+ def __init__(self, w, r, d):+ self.b1 = [Conv_Block(c1=3, c2= int(64*w), kernel_size=3, stride=2, padding=1), Conv_Block(int(64*w), int(128*w), kernel_size=3, stride=2, padding=1)]+ self.b2 = [C2f(c1=int(128*w), c2=int(128*w), n=round(3*d), shortcut=True), Conv_Block(int(128*w), int(256*w), 3, 2, 1), C2f(int(256*w), int(256*w), round(6*d), True)]+ self.b3 = [Conv_Block(int(256*w), int(512*w), kernel_size=3, stride=2, padding=1), C2f(int(512*w), int(512*w), round(6*d), True)]+ self.b4 = [Conv_Block(int(512*w), int(512*w*r), kernel_size=3, stride=2, padding=1), C2f(int(512*w*r), int(512*w*r), round(3*d), True)]+ self.b5 = [SPPF(int(512*w*r), int(512*w*r), 5)]++ def return_modules(self):+ return [*self.b1, *self.b2, *self.b3, *self.b4, *self.b5]++ def __call__(self, x):+ x1 = x.sequential(self.b1)+ x2 = x1.sequential(self.b2)+ x3 = x2.sequential(self.b3)+ x4 = x3.sequential(self.b4)+ x5 = x4.sequential(self.b5)+ return (x2, x3, x5)++#yolo fpn (neck)+class Yolov8NECK:+ def __init__(self, w, r, d): #width_multiple, ratio_multiple, depth_multiple+ self.up = Upsample(2, mode='nearest')+ self.n1 = C2f(c1=int(512*w*(1+r)), c2=int(512*w), n=round(3*d), shortcut=False)+ self.n2 = C2f(c1=int(768*w), c2=int(256*w), n=round(3*d), shortcut=False)+ self.n3 = Conv_Block(c1=int(256*w), c2=int(256*w), kernel_size=3, stride=2, padding=1)+ self.n4 = C2f(c1=int(768*w), c2=int(512*w), n=round(3*d), shortcut=False)+ self.n5 = Conv_Block(c1=int(512* w), c2=int(512 * w), kernel_size=3, stride=2, padding=1)+ self.n6 = C2f(c1=int(512*w*(1+r)), c2=int(512*w*r), n=round(3*d), shortcut=False)++ def return_modules(self):+ return [self.n1, self.n2, self.n3, self.n4, self.n5, self.n6]++ def __call__(self, p3, p4, p5):+ x = self.n1(self.up(p5).cat(p4, dim=1))+ head_1 = self.n2(self.up(x).cat(p3, dim=1))+ head_2 = self.n4(self.n3(head_1).cat(x, dim=1))+ head_3 = self.n6(self.n5(head_2).cat(p5, dim=1))+ return [head_1, head_2, head_3]++#task specific head.+class DetectionHead:+ def __init__(self, nc=80, filters=()):+ self.ch = 16+ self.nc = nc # number of classes+ self.nl = len(filters)+ self.no = nc + self.ch * 4 #+ self.stride = [8, 16, 32]+ c1 = max(filters[0], self.nc)+ c2 = max((filters[0] // 4, self.ch * 4))+ self.dfl = DFL(self.ch)+ self.cv3 = [[Conv_Block(x, c1, 3), Conv_Block(c1, c1, 3), Conv2d(c1, self.nc, 1)] for x in filters]+ self.cv2 = [[Conv_Block(x, c2, 3), Conv_Block(c2, c2, 3), Conv2d(c2, 4 * self.ch, 1)] for x in filters]++ def __call__(self, x):+ for i in range(self.nl):+ x[i] = (x[i].sequential(self.cv2[i]).cat(x[i].sequential(self.cv3[i]), dim=1))+ self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))+ y = [(i.reshape(x[0].shape[0], self.no, -1)) for i in x]+ x_cat = y[0].cat(y[1], y[2], dim=2)+ box, cls = x_cat[:, :self.ch * 4], x_cat[:, self.ch * 4:]+ dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides+ z = dbox.cat(cls.sigmoid(), dim=1)+ return z++class YOLOv8:+ def __init__(self, w, r, d, num_classes): #width_multiple, ratio_multiple, depth_multiple+ self.net = Darknet(w, r, d)+ self.fpn = Yolov8NECK(w, r, d)+ self.head = DetectionHead(num_classes, filters=(int(256*w), int(512*w), int(512*w*r)))++ def __call__(self, x, do_postprocess=True):+ x = self.net(x)+ x = self.fpn(*x)+ x = self.head(x)+ return postprocess(x) if do_postprocess else x++ def return_all_trainable_modules(self):+ backbone_modules = [*range(10)]+ yolov8neck_modules = [12, 15, 16, 18, 19, 21]+ yolov8_head_weights = [(22, self.head)]+ return [*zip(backbone_modules, self.net.return_modules()), *zip(yolov8neck_modules, self.fpn.return_modules()), *yolov8_head_weights]++def convert_f16_safetensor_to_f32(input_file: Path, output_file: Path):+ with open(input_file, 'rb') as f:+ metadata_length = int.from_bytes(f.read(8), 'little')+ metadata = json.loads(f.read(metadata_length).decode())+ float32_values = np.fromfile(f, dtype=np.float16).astype(np.float32)++ for v in metadata.values():+ if v["dtype"] == "F16": v.update({"dtype": "F32", "data_offsets": [offset * 2 for offset in v["data_offsets"]]})++ with open(output_file, 'wb') as f:+ new_metadata_bytes = json.dumps(metadata).encode()+ f.write(len(new_metadata_bytes).to_bytes(8, 'little'))+ f.write(new_metadata_bytes)+ float32_values.tofile(f)++def compute_iou_matrix(boxes):+ x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]+ areas = (x2 - x1) * (y2 - y1)+ x1 = Tensor.maximum(x1[:, None], x1[None, :])+ y1 = Tensor.maximum(y1[:, None], y1[None, :])+ x2 = Tensor.minimum(x2[:, None], x2[None, :])+ y2 = Tensor.minimum(y2[:, None], y2[None, :])+ w = Tensor.maximum(Tensor(0),x2-x1)+ h = Tensor.maximum(Tensor(0),y2-y1)+ intersection = w * h+ iou = intersection / (areas[:, None] + areas[None, :] - intersection)+ return iou++def postprocess(output, max_det=300, conf_threshold=0.25):+ xc, yc, w, h, class_scores = output[0][0], output[0][1], output[0][2], output[0][3], output[0][4:]+ class_ids = Tensor.argmax(class_scores, axis=0)+ probs = Tensor.max(class_scores, axis=0)+ #probs = Tensor.where(probs >= conf_threshold, probs, 0) #dont use line in ios export+ x1 = xc - w / 2+ y1 = yc - h / 2+ x2 = xc + w / 2+ y2 = yc + h / 2+ boxes = Tensor.stack(x1, y1, x2, y2, probs, class_ids, dim=1)+ order = Tensor.topk(probs, max_det)[1]+ boxes = boxes[order]+ iou = compute_iou_matrix(boxes[:, :4])+ iou = Tensor.triu(iou, diagonal=1)+ same_class_mask = boxes[:, -1][:, None] == boxes[:, -1][None, :]+ high_iou_mask = (iou > 0.45) & same_class_mask+ no_overlap_mask = high_iou_mask.sum(axis=0) == 0+ boxes = boxes * no_overlap_mask.unsqueeze(-1)+ return boxes++def clip_boxes(boxes, shape):+ boxes[..., [0, 2]] = np.clip(boxes[..., [0, 2]], 0, shape[1]) # x1, x2+ boxes[..., [1, 3]] = np.clip(boxes[..., [1, 3]], 0, shape[0]) # y1, y2+ return boxes++def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):+ gain = ratio_pad if ratio_pad else min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])+ pad = ((img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2)+ boxes_np = boxes.numpy() if isinstance(boxes, Tensor) else boxes+ boxes_np[..., [0, 2]] -= pad[0]+ boxes_np[..., [1, 3]] -= pad[1]+ boxes_np[..., :4] /= gain+ boxes_np = clip_boxes(boxes_np, img0_shape)+ return boxes_np++def get_weights_location(yolo_variant: str) -> Path:+ weights_location = Path(__file__).parents[1] / "weights" / f'yolov8{yolo_variant}.safetensors'+ fetch(f'https://gitlab.com/r3sist/yolov8_weights/-/raw/master/yolov8{yolo_variant}.safetensors', weights_location)++ if not is_dtype_supported(dtypes.half):+ f32_weights = weights_location.with_name(f"{weights_location.stem}_f32.safetensors")+ if not f32_weights.exists(): convert_f16_safetensor_to_f32(weights_location, f32_weights)+ weights_location = f32_weights++ return weights_location++if __name__ == '__main__':++ # usage : python3 yolov8.py "image_URL OR image_path" "v8 variant" (optional, n is default)+ if len(sys.argv) < 2:+ print("Error: Image URL or path not provided.")+ sys.exit(1)++ img_path = sys.argv[1]+ yolo_variant = sys.argv[2] if len(sys.argv) >= 3 else (print("No variant given, so choosing 'n' as the default. Yolov8 has different variants, you can choose from ['n', 's', 'm', 'l', 'x']") or 'n')+ print(f'running inference for YOLO version {yolo_variant}')++ output_folder_path = Path('./outputs_yolov8')+ output_folder_path.mkdir(parents=True, exist_ok=True)+ #absolute image path or URL+ image_location = [np.frombuffer(fetch(img_path).read_bytes(), np.uint8)]+ image = [cv2.imdecode(image_location[0], 1)]+ out_paths = [(output_folder_path / f"{Path(img_path).stem}_output{Path(img_path).suffix or '.png'}").as_posix()]+ if not isinstance(image[0], np.ndarray):+ print('Error in image loading. Check your image file.')+ sys.exit(1)+ pre_processed_image = preprocess(image)+ # Different YOLOv8 variants use different w , r, and d multiples. For a list , refer to this yaml file (the scales section) https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/models/v8/yolov8.yaml+ depth, width, ratio = get_variant_multiples(yolo_variant)+ yolo_infer = YOLOv8(w=width, r=ratio, d=depth, num_classes=80)+ state_dict = safe_load(get_weights_location(yolo_variant))+ load_state_dict(yolo_infer, state_dict)++ st = time.time()+ predictions = yolo_infer(pre_processed_image).numpy()++ print(f'did inference in {int(round(((time.time() - st) * 1000)))}ms')+ #v8 and v3 have same 80 class names for Object Detection+ class_labels = fetch('https://raw.githubusercontent.com/pjreddie/darknet/master/data/coco.names').read_text().split("\n")+ for pred in predictions: pred[:4] = scale_boxes(pre_processed_image.shape[2:],pred[:4],image[0].shape)+ draw_bounding_boxes_and_save(orig_img_paths=image_location, output_img_paths=out_paths, all_predictions=predictions, class_labels=class_labels)++# TODO for later:+# 1. Fix SPPF minor difference due to maxpool+# 2. AST exp overflow warning while on cpu+# 3. Make NMS faster+# 4. Add video inference and webcam supportdiff --git a/ios/clearcam/zh-Hans.lproj/Localizable.strings b/ios/clearcam/zh-Hans.lproj/Localizable.stringsnew file mode 100644index 0000000..9065130--- /dev/null+++ b/ios/clearcam/zh-Hans.lproj/Localizable.strings@@ -0,0 +1,188 @@+"settings" = "设置";+"events" = "事件";+"live" = "直播";+"default_device_name" = "我的设备";+"waiting_for_ip" = "等待Wi-Fi连接...";+"streaming_over_wifi" = "正在通过本地Wi-Fi串流,地址: %@";+"permission_denied" = "权限被拒绝";+"notification_permission_denied" = "通知权限被拒绝。您可以在设置中启用它。";+"ok" = "确定";+"enable_in_settings" = "在设置中启用";+"notifications_disabled" = "通知已禁用。请在设置应用中启用它们。";+"camera_settings" = "摄像头设置";+"live_stream_settings" = "直播设置";+"viewer_settings" = "查看器设置";+"subscription" = "订阅";+"upgrade_to_premium" = "升级至高级版";+"stream_via_wifi" = "通过Wi-Fi传输";+"resolution" = "分辨率";+"detect_objects" = "检测物体";+"manage_detection_presets" = "管理检测预设";+"detection_certainty_threshold" = "检测置信度阈值";+"send_videos_on_detection" = "检测时发送视频";+"send_videos_description" = "启用后可在任何设备上查看事件。";+"change_encryption_password" = "更改加密密码";+"manage_detection_schedules" = "管理检测计划";+"manage_detection_schedules_description" = "选择何时检测物体。";+"use_own_notification_server" = "使用自建通知服务器";+"use_own_notification_server_description" = "将视频发送到您自己的服务器。";+"server_address" = "服务器地址";+"test_own_server" = "测试自建服务器";+"use_own_inference_server" = "使用自建推理服务器";+"use_own_inference_server_description" = "使用自定义服务器进行物体检测。";+"enter_inference_server_address" = "输入服务器地址:例如 http://192.168.1.1:6667";+"live_stream_network" = "通过网络直播";+"device_name" = "设备名称";+"receive_notifications" = "接收通知";+"receive_notifications_description" = "当摄像头捕捉到事件时接收通知。";+"restore_purchases" = "恢复购买";+"terms_of_use" = "使用条款";+"privacy_policy" = "隐私政策";+"delete_encryption_keys" = "删除加密密钥";+"enter_inference_server_address_title" = "输入推理服务器地址";+"enter_inference_server_address_message" = "请输入您的推理服务器地址。";+"server_address_label" = "服务器地址";+"save" = "保存";+"cancel" = "取消";+"set_threshold_title" = "设置阈值";+"set_threshold_message" = "输入1到100之间的百分比值(默认为25)。";+"threshold_placeholder" = "阈值 (1-100)";+"invalid_threshold_title" = "无效阈值";+"invalid_threshold_message" = "请输入1到100之间的有效值";+"set_device_name_title" = "设置设备名称";+"set_device_name_message" = "输入此设备的名称。";+"device_name_placeholder" = "设备名称";+"delete_encryption_keys_title" = "删除加密密钥";+"delete_encryption_keys_message" = "确定要删除此设备上的所有密钥吗?";+"delete" = "是";+"price_unknown" = "价格";+"get_premium_title" = "获取Clearcam高级版";+"premium_feature_1" = "随时随地查看捕获的事件";+"premium_feature_2" = "接收实时事件通知";+"premium_feature_3" = "随时随地直播";+"premium_feature_4" = "手机发送的所有摄像头数据均采用端到端加密。";+"upgrade_button" = "升级至每月%@";+"not_now" = "暂不";+"premium_disclaimer" = "每月限制5000个片段上传和1000分钟或次数的直播观看。";+"purchase_failed" = "购买失败";+"enter_notification_server_address_title" = "输入服务器地址";+"enter_notification_server_address_message" = "请输入您的通知服务器地址。";+"test_notification_sent_title" = "已发送";+"test_notification_sent_message" = "测试通知已发送。请检查您的服务器。";+"set_password_title" = "设置密码";+"set_password_message" = "输入密码以加密您的数据";+"password_placeholder" = "密码";+"confirm_password_placeholder" = "确认密码";+"invalid_password_title" = "密码无效";+"invalid_password_message" = "密码不匹配或为空。";+"select_resolution_title" = "选择分辨率";+"select_objects_preset_title" = "选择物体预设";+"add_preset_title" = "添加预设";+"add_preset_message" = "输入新预设的名称";+"preset_name_placeholder" = "预设名称";+"restoring_purchases_title" = "正在恢复购买";+"restoring_purchases_message" = "请稍候,我们正在恢复您之前的购买...";+"steps_text_live" = "1. 在另一部手机或支持RTSP的摄像头上安装Clearcam。\n2. 升级至Clearcam高级版。\n3. 在另一部手机(或电脑)上开启“网络直播”功能,并设置安全密码和设备名称。\n4. 开始录制。";+"steps_text_clips" = "1. 在另一部手机或支持RTSP的摄像头上安装Clearcam。\n2. 升级至Clearcam高级版。\n3. 开启“检测到运动时发送视频”(或在电脑上接收通知)并设置安全密码。\n4. (可选)配置检测设置和时间表。\n5. 开始录制。";+"no_live_devices" = "无在线设备\n";+"no_videos_available" = "无可用视频\n";+"share" = "分享";+"delete" = "删除";+"cancel" = "取消";+"online" = "在线";+"experimental_features" = "实验性功能";+"docs" = "文档";+"app_name" = "Clearcam";+"home" = "首页";+"camera_desc" = "录制并直播画面,支持AI目标识别";+"gallery_desc" = "查看捕捉事件和实时画面(需订阅高级版)";+"settings_desc" = "配置摄像头和识别功能";+"all" = "全部";+"people+vehicles" = "人+车辆";++"authenticate_to_view_user_id" = "验证以查看您的用户ID。";+"tap_for_userid" = "点击显示您的用户ID,请勿分享。";+"id_copied" = "用户ID已复制到剪贴板。";+"copied" = "已复制";+"userid" = "用户ID";++"person" = "人";+"bicycle" = "自行车";+"car" = "汽车";+"motorcycle" = "摩托车";+"airplane" = "飞机";+"bus" = "公交车";+"train" = "火车";+"truck" = "卡车";+"boat" = "船";+"traffic light" = "交通灯";+"fire hydrant" = "消防栓";+"stop sign" = "停车标志";+"parking meter" = "停车收费表";+"bench" = "长凳";+"bird" = "鸟";+"cat" = "猫";+"dog" = "狗";+"horse" = "马";+"sheep" = "羊";+"cow" = "牛";+"elephant" = "大象";+"bear" = "熊";+"zebra" = "斑马";+"giraffe" = "长颈鹿";+"backpack" = "背包";+"umbrella" = "雨伞";+"handbag" = "手提包";+"tie" = "领带";+"suitcase" = "手提箱";+"frisbee" = "飞盘";+"skis" = "滑雪板";+"snowboard" = "滑雪板";+"sports ball" = "运动球";+"kite" = "风筝";+"baseball bat" = "棒球棒";+"baseball glove" = "棒球手套";+"skateboard" = "滑板";+"surfboard" = "冲浪板";+"tennis racket" = "网球拍";+"bottle" = "瓶子";+"wine glass" = "酒杯";+"cup" = "杯子";+"fork" = "叉子";+"knife" = "刀";+"spoon" = "勺子";+"bowl" = "碗";+"banana" = "香蕉";+"apple" = "苹果";+"sandwich" = "三明治";+"orange" = "橙子";+"broccoli" = "西兰花";+"carrot" = "胡萝卜";+"hot dog" = "热狗";+"pizza" = "披萨";+"donut" = "甜甜圈";+"cake" = "蛋糕";+"chair" = "椅子";+"couch" = "沙发";+"potted plant" = "盆栽植物";+"bed" = "床";+"dining table" = "餐桌";+"toilet" = "马桶";+"tv" = "电视";+"laptop" = "笔记本电脑";+"mouse" = "鼠标";+"remote" = "遥控器";+"keyboard" = "键盘";+"cell phone" = "手机";+"microwave" = "微波炉";+"oven" = "烤箱";+"toaster" = "烤面包机";+"sink" = "水槽";+"refrigerator" = "冰箱";+"book" = "书";+"clock" = "时钟";+"vase" = "花瓶";+"scissors" = "剪刀";+"teddy bear" = "泰迪熊";+"hair drier" = "吹风机";+"toothbrush" = "牙刷";