Add object detection, tracking, mobile notifications, and search to any security camera.
Delete old clips (#97)
Rory Clear4d077cd22fcc
diff --git a/android/clearcam/app/src/main/java/com/rors/clearcam/HomeScreen.kt b/android/clearcam/app/src/main/java/com/rors/clearcam/HomeScreen.ktindex 76b9b1f..4724e24 100644--- a/android/clearcam/app/src/main/java/com/rors/clearcam/HomeScreen.kt+++ b/android/clearcam/app/src/main/java/com/rors/clearcam/HomeScreen.kt@@ -56,6 +56,7 @@ import androidx.core.content.ContextCompatimport android.Manifestimport android.graphics.BitmapFactoryimport android.widget.Toast+import androidx.annotation.RequiresApiimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.icons.filled.Lockimport androidx.compose.material.icons.filled.Refresh@@ -73,6 +74,9 @@ import java.nio.charset.StandardCharsetsimport androidx.compose.foundation.gestures.detectTransformGesturesimport androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.geometry.Offset+import androidx.datastore.preferences.core.booleanPreferencesKey+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.mapprivate const val APP_VIDEO_DIR = "videos"@@ -160,7 +164,6 @@ object ThumbnailCache {}}-suspend fun deleteVideoFromBackend(userId: String, filename: String) {withContext(Dispatchers.IO) {try {@@ -261,6 +264,7 @@ fun HomeScreen(userId: String) {}fun loadVideosFromStorage() {+ deleteOldClipsIfEnabled(context, videosDir, coroutineScope)eventVideos = loadAllVideos(videosDir)}@@ -268,6 +272,7 @@ fun HomeScreen(userId: String) {coroutineScope.launch {try {if (!videosDir.exists()) videosDir.mkdirs()+ deleteOldClipsIfEnabled(context, videosDir, coroutineScope)val camerasDeferred = async { fetchCameraJson(userId) }val newestTime = getNewestCreationTimeFromFiles(videosDir)val newVideos = fetchEventVideos(userId, newestTime / 1000)@@ -553,6 +558,7 @@ fun SimpleVideoPlayer(videoPath: String, onDismiss: () -> Unit) {var isScrubbing by remember { mutableStateOf(false) }val videoViewRef = remember { mutableStateOf<VideoView?>(null) }val coroutineScope = rememberCoroutineScope()+ val videosDir = remember { File(context.filesDir, APP_VIDEO_DIR) }var isPrepared by remember { mutableStateOf(false) }var isInitialPlay by remember { mutableStateOf(true) }@@ -1554,4 +1560,70 @@ fun EventVideoListItem(}}}+}++@RequiresApi(Build.VERSION_CODES.O)+private fun isVideoOld(filename: String): Boolean {+ return try {+ Log.d("DeleteOldClips", "Checking file: $filename")++ // Extract date-time part from filename (format: "2025-11-16_16-09-58")+ val baseName = filename+ .removeSuffix(".mp4")+ .removeSuffix(".aes")++ // The date-time part is everything before the last underscore (remove the UUID)+ val dateTimePart = baseName.substringBeforeLast("_")+ Log.d("DeleteOldClips", "Date-time part: $dateTimePart")++ // Parse the date-time string (format: "yyyy-MM-dd_HH-mm-ss")+ val formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")+ val fileDateTime = java.time.LocalDateTime.parse(dateTimePart, formatter)++ // Convert to milliseconds since epoch+ val timestamp = fileDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()+ val currentTime = System.currentTimeMillis()+ val timeLimit = currentTime - (12 * 14 * 60 * 60 * 1000) // 14 days++ Log.d("DeleteOldClips", "File timestamp: $timestamp (${java.util.Date(timestamp)})")+ Log.d("DeleteOldClips", "Current time: $currentTime (${java.util.Date(currentTime)})")+ Log.d("DeleteOldClips", "Time limit: $timeLimit (${java.util.Date(timeLimit)})")+ Log.d("DeleteOldClips", "Is old: ${timestamp < timeLimit}")++ timestamp < timeLimit+ } catch (e: Exception) {+ Log.e("DeleteOldClips", "Error parsing timestamp for $filename: ${e.message}")+ false+ }+}++@RequiresApi(Build.VERSION_CODES.O)+private fun deleteOldClipsIfEnabled(+ context: Context,+ videosDir: File,+ coroutineScope: CoroutineScope+) {+ coroutineScope.launch(Dispatchers.IO) {++ // Read from DataStore (NOT SharedPreferences)+ val deleteOldClips = context.dataStore.data+ .map { prefs -> prefs[booleanPreferencesKey("delete_old_clips")] ?: true }+ .first()++ if (!deleteOldClips) return@launch++ try {+ val files = videosDir.listFiles()+ files?.forEach { file ->+ if (file.isFile && (file.name.endsWith(".mp4") || file.name.endsWith(".aes"))) {+ if (isVideoOld(file.name)) {+ file.delete()+ ThumbnailCache.deleteCachedThumbnail(context, file.name)+ }+ }+ }+ } catch (e: Exception) {+ Log.e("DeleteOldClips", "Error deleting old clips", e)+ }+ }}\ No newline at end of filediff --git a/android/clearcam/app/src/main/java/com/rors/clearcam/SettingsScreen.kt b/android/clearcam/app/src/main/java/com/rors/clearcam/SettingsScreen.ktindex fe87d39..6864774 100644--- a/android/clearcam/app/src/main/java/com/rors/clearcam/SettingsScreen.kt+++ b/android/clearcam/app/src/main/java/com/rors/clearcam/SettingsScreen.kt@@ -27,6 +27,7 @@ import androidx.datastore.preferences.preferencesDataStoreimport com.google.firebase.messaging.FirebaseMessagingimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launchimport java.io.OutputStreamWriter@@ -42,15 +43,31 @@ fun SettingsScreen(onBackPressed: () -> Unit) {val coroutineScope = rememberCoroutineScope()val userId = PrefsHelper.getUserId(context) ?: ""val notificationsEnabled = remember { mutableStateOf(false) }+ val deleteOldClipsEnabled = remember { mutableStateOf(true) } // Default to trueval showLogoutDialog = remember { mutableStateOf(false) }- // Load saved preference when screen appears+ // Load saved preferences when screen appearsLaunchedEffect(Unit) {+ // Load notifications preferencecontext.dataStore.data.map { preferences ->preferences[booleanPreferencesKey("notifications_enabled")] ?: false}.collect { enabled ->notificationsEnabled.value = enabled}++ // Load delete old clips preference (defaults to true)+ context.dataStore.data.map { preferences ->+ preferences[booleanPreferencesKey("delete_old_clips")] ?: true+ }.collect { enabled ->+ deleteOldClipsEnabled.value = enabled+ }+ }++ LaunchedEffect(Unit) {+ val enabled = context.dataStore.data+ .map { prefs -> prefs[booleanPreferencesKey("delete_old_clips")] ?: true }+ .first() // get the first (current) value and stop+ deleteOldClipsEnabled.value = enabled}// Logout confirmation dialog@@ -107,6 +124,7 @@ fun SettingsScreen(onBackPressed: () -> Unit) {.fillMaxSize().padding(innerPadding)) {+ // Notifications toggleRow(modifier = Modifier.fillMaxWidth()@@ -115,11 +133,11 @@ fun SettingsScreen(onBackPressed: () -> Unit) {horizontalArrangement = Arrangement.SpaceBetween) {Text(- text = "Receive event notifications",+ text = "Receive Event Notifications",style = MaterialTheme.typography.bodyLarge)- val activity = LocalContext.current as? Activity // todo+ val activity = LocalContext.current as? ActivitySwitch(checked = notificationsEnabled.value,@@ -155,6 +173,45 @@ fun SettingsScreen(onBackPressed: () -> Unit) {)}+ // Delete old clips toggle - added below notifications+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween+ ) {+ Column {+ Text(+ text = "Delete Old Clips",+ style = MaterialTheme.typography.bodyLarge+ )+ Text(+ text = "Automatically delete clips after 14 days.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),+ modifier = Modifier.padding(top = 4.dp)+ )+ }++ Switch(+ checked = deleteOldClipsEnabled.value,+ onCheckedChange = { enabled ->+ deleteOldClipsEnabled.value = enabled+ coroutineScope.launch {+ context.dataStore.edit { prefs ->+ prefs[booleanPreferencesKey("delete_old_clips")] = enabled+ }+ }+ if (enabled) {+ Toast.makeText(context, "Old clips will be automatically deleted", Toast.LENGTH_SHORT).show()+ } else {+ Toast.makeText(context, "Old clips will be kept", Toast.LENGTH_SHORT).show()+ }+ }+ )+ }+// Added logout button at the bottomSpacer(modifier = Modifier.weight(1f))Button(@@ -258,5 +315,4 @@ private fun requestNotificationPermissionAndRegister(}}}-}-+}\ No newline at end of filediff --git a/ios/clearcam.xcodeproj/project.pbxproj b/ios/clearcam.xcodeproj/project.pbxprojindex 8ca86ae..8c36977 100644--- a/ios/clearcam.xcodeproj/project.pbxproj+++ b/ios/clearcam.xcodeproj/project.pbxproj@@ -184,7 +184,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 1.2.15;+ MARKETING_VERSION = 1.3.0;PRODUCT_BUNDLE_IDENTIFIER = roryclear.clearcam;PRODUCT_NAME = "$(TARGET_NAME)";SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";@@ -217,7 +217,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 1.2.15;+ MARKETING_VERSION = 1.3.0;PRODUCT_BUNDLE_IDENTIFIER = roryclear.clearcam;PRODUCT_NAME = "$(TARGET_NAME)";SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";diff --git a/ios/clearcam/GalleryViewController.m b/ios/clearcam/GalleryViewController.mindex 62cb6ba..25666d4 100644--- a/ios/clearcam/GalleryViewController.m+++ b/ios/clearcam/GalleryViewController.m@@ -581,6 +581,14 @@NSError *error;NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.downloadDirectory error:&error];if (!self.loadedFilenames) self.loadedFilenames = [NSMutableSet set];+ BOOL shouldDeleteOldClips = YES;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ if ([defaults objectForKey:@"delete_old_clips"] != nil) {+ shouldDeleteOldClips = [defaults boolForKey:@"delete_old_clips"];+ }+ if (shouldDeleteOldClips) {+ [self deleteOldClips];+ }for (NSString *file in contents) {NSString *filePath = [self.downloadDirectory stringByAppendingPathComponent:file];NSString *outputFilePath = filePath;@@ -618,6 +626,49 @@}}+- (void)deleteOldClips {+ NSFileManager *fileManager = [NSFileManager defaultManager];+ NSError *error = nil;+ NSArray *contents = [fileManager contentsOfDirectoryAtPath:self.downloadDirectory error:&error];+ if (error) return;+ NSDate *cutoffDate = [NSDate dateWithTimeIntervalSinceNow:-24 * 14 * 60 * 60]; // 2 weeks+ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];+ [dateFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];+ BOOL didDeleteFiles = NO;+ for (NSString *file in contents) {+ NSString *filePath = [self.downloadDirectory stringByAppendingPathComponent:file];+ NSError *regexError = nil;+ NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{4}-\\d{2}-\\d{2})_(\\d{2}-\\d{2}-\\d{2})"+ options:0+ error:®exError];+ NSTextCheckingResult *match = [regex firstMatchInString:file options:0 range:NSMakeRange(0, file.length)];+ if (!match) continue;+ NSString *dateStr = [file substringWithRange:[match rangeAtIndex:1]];+ NSString *timeStr = [file substringWithRange:[match rangeAtIndex:2]];+ NSString *fullTimestamp = [NSString stringWithFormat:@"%@_%@", dateStr, timeStr];+ NSDate *fileDate = [dateFormatter dateFromString:fullTimestamp];+ if (fileDate && [fileDate compare:cutoffDate] == NSOrderedAscending) {+ NSError *deleteError = nil;+ BOOL success = [fileManager removeItemAtPath:filePath error:&deleteError];+ if (success) {+ NSLog(@"Deleted old clip: %@", file);+ didDeleteFiles = YES;+ } else {+ NSLog(@"Failed to delete old clip %@: %@", file, deleteError);+ }+ }+ }+ if (didDeleteFiles) {+ dispatch_async(dispatch_get_main_queue(), ^{+ [self.videoFiles removeAllObjects];+ [self.groupedVideos removeAllObjects];+ [self.sectionTitles removeAllObjects];+ [self.loadedFilenames removeAllObjects];+ [self loadExistingVideos];+ });+ }+}+- (void)addVideoFileAtPath:(NSString *)filePath {if (!filePath) return;NSString *filename = [filePath lastPathComponent];diff --git a/ios/clearcam/SettingsViewController.m b/ios/clearcam/SettingsViewController.mindex d681a41..59c5b0c 100644--- a/ios/clearcam/SettingsViewController.m+++ b/ios/clearcam/SettingsViewController.m@@ -30,6 +30,7 @@@property (nonatomic, assign) BOOL useOwnInferenceServerEnabled;@property (nonatomic, strong) NSString *inferenceServerAddress;@property (nonatomic, assign) BOOL isUserIDVisible;+@property (nonatomic, assign) BOOL deleteOldClipsEnabled;@end@@ -112,6 +113,13 @@self.liveStreamInternetEnabled = NO;[defaults setBool:NO forKey:@"live_stream_internet_enabled"];}+ if ([defaults objectForKey:@"delete_old_clips"] != nil) {+ self.deleteOldClipsEnabled = [defaults boolForKey:@"delete_old_clips"];+ } else {+ self.deleteOldClipsEnabled = YES;+ [defaults setBool:YES forKey:@"delete_old_clips"];+ }+self.deviceName = [defaults stringForKey:@"device_name"] ?: NSLocalizedString(@"default_device_name", @"Default device name");[defaults setObject:self.deviceName forKey:@"device_name"];@@ -216,6 +224,13 @@[defaults synchronize];}+- (void)deleteOldClipsSwitchToggled:(UISwitch *)sender {+ self.deleteOldClipsEnabled = sender.on;+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];+ [defaults setBool:self.deleteOldClipsEnabled forKey:@"delete_old_clips"];+ [defaults synchronize];+}+- (void)liveStreamInternetSwitchToggled:(UISwitch *)sender {NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];BOOL isPremium = [defaults boolForKey:@"isSubscribed"];@@ -566,6 +581,15 @@receiveNotifSwitch.enabled = isPremium;cell.textLabel.textColor = isPremium ? [UIColor labelColor] : [UIColor grayColor];cell.userInteractionEnabled = YES;+ } else if (indexPath.row == 1) {+ cell.textLabel.text = NSLocalizedString(@"auto_delete_old_clips", nil);+ cell.detailTextLabel.text = NSLocalizedString(@"auto_delete_old_clips_description", nil);+ cell.accessoryType = UITableViewCellAccessoryNone;+ UISwitch *deleteOldClipsSwitch = [[UISwitch alloc] init];+ deleteOldClipsSwitch.on = self.deleteOldClipsEnabled;+ [deleteOldClipsSwitch addTarget:self action:@selector(deleteOldClipsSwitchToggled:) forControlEvents:UIControlEventValueChanged];+ cell.accessoryView = deleteOldClipsSwitch;+ cell.userInteractionEnabled = YES;}} else if (indexPath.section == 3) { // Advanced Settingsif (indexPath.row == 0) {@@ -668,7 +692,7 @@} else if (section == 1) { // Live Stream Settingsreturn 2; // Live Stream over the internet and Device name} else if (section == 2) { // Viewer Settings- return 1; // Just Receive Notifications+ return 2; // Just Receive Notifications} else if (section == 3) { // Advanced Settingsreturn 2; // Use Own Notification Server, Use Own Inference Server} else if (section == 4) { // Upgrade to Premium / Subscription@@ -906,6 +930,7 @@[[StoreManager sharedInstance] showUpgradePopupInViewController:self completion:^(BOOL success) {}];} // Switch handles toggle when premium}+ // Row 1 (auto delete old clips) is handled by the switch, so no action needed on tap} 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 / Subscriptiondiff --git a/ios/clearcam/en.lproj/Localizable.strings b/ios/clearcam/en.lproj/Localizable.stringsindex 33ceff5..316e436 100644--- a/ios/clearcam/en.lproj/Localizable.strings+++ b/ios/clearcam/en.lproj/Localizable.strings@@ -115,3 +115,6 @@"continue_without_account" = "Continue without an account";"alerts" = "Alerts";++"auto_delete_old_clips" = "Auto Delete Old Clips";+"auto_delete_old_clips_description" = "Delete clips after 14 days.";diff --git a/ios/clearcam/es.lproj/Localizable.strings b/ios/clearcam/es.lproj/Localizable.stringsindex c9bdef6..23f701b 100644--- a/ios/clearcam/es.lproj/Localizable.strings+++ b/ios/clearcam/es.lproj/Localizable.strings@@ -197,3 +197,6 @@"continue_without_account" = "Continuar sin cuenta";"alerts" = "Alertas";++"auto_delete_old_clips" = "Eliminar Clips Antiguos Automáticamente";+"auto_delete_old_clips_description" = "Eliminar clips automáticamente después de 14 días.";diff --git a/ios/clearcam/hi.lproj/Localizable.strings b/ios/clearcam/hi.lproj/Localizable.stringsindex 7b48f34..884a72c 100644--- a/ios/clearcam/hi.lproj/Localizable.strings+++ b/ios/clearcam/hi.lproj/Localizable.strings@@ -197,3 +197,6 @@"continue_without_account" = "बिना खाता के जारी रखें";"alerts" = "अलर्ट";++"auto_delete_old_clips" = "पुराने क्लिप स्वचालित रूप से हटाएं";+"auto_delete_old_clips_description" = "14 दिनों के बाद क्लिप स्वचालित रूप से हटाएं।";diff --git a/ios/clearcam/ja.lproj/Localizable.strings b/ios/clearcam/ja.lproj/Localizable.stringsindex 9139182..ae8ccd8 100644--- a/ios/clearcam/ja.lproj/Localizable.strings+++ b/ios/clearcam/ja.lproj/Localizable.strings@@ -197,3 +197,6 @@"continue_without_account" = "アカウントなしで続ける";"alerts" = "アラート";++"auto_delete_old_clips" = "古いクリップを自動削除";+"auto_delete_old_clips_description" = "14日後にクリップを自動削除します。";diff --git a/ios/clearcam/ko.lproj/Localizable.strings b/ios/clearcam/ko.lproj/Localizable.stringsindex bf4e75b..5cc145e 100644--- a/ios/clearcam/ko.lproj/Localizable.strings+++ b/ios/clearcam/ko.lproj/Localizable.strings@@ -197,3 +197,6 @@"continue_without_account" = "계정 없이 계속하기";"alerts" = "알림";++"auto_delete_old_clips" = "오래된 클립 자동 삭제";+"auto_delete_old_clips_description" = "14일 후에 클립을 자동으로 삭제합니다.";diff --git a/ios/clearcam/pt-BR.lproj/Localizable.strings b/ios/clearcam/pt-BR.lproj/Localizable.stringsindex 6635c7d..9ea7bf1 100644--- a/ios/clearcam/pt-BR.lproj/Localizable.strings+++ b/ios/clearcam/pt-BR.lproj/Localizable.strings@@ -208,3 +208,6 @@"continue_without_account" = "Continuar sem conta";"alerts" = "Alertas";++"auto_delete_old_clips" = "Excluir Clipes Antigos Automaticamente";+"auto_delete_old_clips_description" = "Excluir clipes automaticamente após 14 dias.";diff --git a/ios/clearcam/zh-Hans.lproj/Localizable.strings b/ios/clearcam/zh-Hans.lproj/Localizable.stringsindex d6ca4e6..7e440ac 100644--- a/ios/clearcam/zh-Hans.lproj/Localizable.strings+++ b/ios/clearcam/zh-Hans.lproj/Localizable.strings@@ -196,3 +196,6 @@"continue_without_account" = "继续使用(无账户)";"alerts" = "警报";++"auto_delete_old_clips" = "自动删除旧剪辑";+"auto_delete_old_clips_description" = "14天后自动删除剪辑。";