Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(recording): enhance recording handling with MediaStore integration and improved file management
Durganshu Mishra5c08b6bedcae
diff --git a/app/src/main/java/com/gotcha/data/GotchaStorage.kt b/app/src/main/java/com/gotcha/data/GotchaStorage.ktindex 642c871..3212ba9 100644--- a/app/src/main/java/com/gotcha/data/GotchaStorage.kt+++ b/app/src/main/java/com/gotcha/data/GotchaStorage.kt@@ -4,8 +4,10 @@ import android.content.ContentValuesimport android.content.Contextimport android.graphics.Bitmapimport android.media.MediaScannerConnection+import android.net.Uriimport android.os.Buildimport android.os.Environment+import android.os.ParcelFileDescriptorimport android.provider.MediaStoreimport java.io.Fileimport java.io.IOException@@ -146,4 +148,54 @@ object GotchaStorage {} ?: throw IOException("Could not open Pictures/Gotcha for writing")return "Pictures/Gotcha"}++ sealed class RecordingTarget {+ /** Pre-Q direct filesystem path, or a caller-supplied [FileResolver] path. */+ data class DirectFile(val file: File) : RecordingTarget()+ /** Q+ MediaStore entry; [MediaRecorder] writes through the held fd. */+ data class MediaStoreEntry(val uri: Uri, val pfd: ParcelFileDescriptor, val displayPath: String) :+ RecordingTarget()+ }++ /**+ * Opens a target for [fileName] in the system-wide public Recordings folder+ * (visible to the system Recorder/Files apps), not the per-chat working+ * directory.+ *+ * API 29+ has no direct filesystem access to public folders without "All+ * files access", so recordings go through a MediaStore insert + file+ * descriptor instead; [MediaRecorder.setOutputFile] accepts that fd directly.+ */+ fun createRecordingTarget(context: Context, fileName: String): RecordingTarget {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)+ put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp4")+ put(MediaStore.MediaColumns.RELATIVE_PATH, "Recordings")+ put(MediaStore.MediaColumns.IS_PENDING, 1)+ }+ val resolver = context.contentResolver+ val uri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)+ ?: throw IOException("Could not create $fileName in Recordings")+ val pfd = resolver.openFileDescriptor(uri, "w")+ ?: throw IOException("Could not open Recordings for writing")+ return RecordingTarget.MediaStoreEntry(uri, pfd, "Recordings/$fileName")+ }+ val dir = Environment.getExternalStoragePublicDirectory("Recordings")+ dir.mkdirs()+ return RecordingTarget.DirectFile(File(dir, fileName))+ }++ /** Clears the pending flag so other apps can see/play the finished recording. */+ fun finalizeRecording(context: Context, uri: Uri) {+ val values = ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }+ context.contentResolver.update(uri, values, null, null)+ }++ /** Removes an abandoned pending entry if [startAudioRecording] failed after the insert. */+ fun discardPendingRecording(context: Context, uri: Uri) {+ try {+ context.contentResolver.delete(uri, null, null)+ } catch (_: Exception) { }+ }}diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktindex 45e29af..0f39047 100644--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -28,6 +28,9 @@ class MediaCaptureTool(private val context: Context) {private var recorder: MediaRecorder? = nullprivate var recordingFile: File? = null+ private var recordingUri: android.net.Uri? = null+ private var recordingPfd: android.os.ParcelFileDescriptor? = null+ private var recordingDisplayPath: String = ""private var recordingStartTime: Long = 0Lprivate var recordingPaused: Boolean = false@@ -130,20 +133,39 @@ class MediaCaptureTool(private val context: Context) {// following stop must report the real error, not a stale saved file.lastSavedPath = nulllastSavedDurationSeconds = 0L+ recordingFile = null+ recordingUri = null+ recordingPfd = nullreturn try {- val file = if (!outputPath.isNullOrBlank()) {+ if (!outputPath.isNullOrBlank()) {val resolved = FileResolver(context).resolveForWrite(outputPath)- when (resolved) {+ val file = when (resolved) {is FileResolver.ResolveResult.Ok -> resolved.file.also { it.parentFile?.mkdirs() }is FileResolver.ResolveResult.PermissionNeeded -> return resolved.resultis FileResolver.ResolveResult.Error -> return ToolResult.error(resolved.message)}+ recordingFile = file+ recordingDisplayPath = file.absolutePath} else {- val dir = com.gotcha.data.GotchaStorage.subdir(- File(FileResolver.WORKING_DIR_BASE),- com.gotcha.data.GotchaStorage.Kind.RECORDINGS- )- File(dir, "recording_${timestamp()}.m4a")+ // Default location: the system-wide public Recordings folder, not+ // the per-chat working directory — recordings should be findable+ // like any other device recording, independent of which chat made them.+ when (+ val target = com.gotcha.data.GotchaStorage.createRecordingTarget(+ context,+ "recording_${timestamp()}.m4a"+ )+ ) {+ is com.gotcha.data.GotchaStorage.RecordingTarget.DirectFile -> {+ recordingFile = target.file+ recordingDisplayPath = target.file.absolutePath+ }+ is com.gotcha.data.GotchaStorage.RecordingTarget.MediaStoreEntry -> {+ recordingUri = target.uri+ recordingPfd = target.pfd+ recordingDisplayPath = target.displayPath+ }+ }}val audioSource = when (source?.trim()?.lowercase()) {@@ -180,22 +202,27 @@ class MediaCaptureTool(private val context: Context) {if (maxDurationSeconds != null && maxDurationSeconds > 0) {rec.setMaxDuration(maxDurationSeconds * 1000)}- rec.setOutputFile(file.absolutePath)+ val pfd = recordingPfd+ if (pfd != null) {+ rec.setOutputFile(pfd.fileDescriptor)+ } else {+ rec.setOutputFile(recordingFile!!.absolutePath)+ }rec.prepare()rec.start()recorder = rec- recordingFile = filerecordingStartTime = System.currentTimeMillis()recordingPaused = falseval extras = buildString {if (source != null) append(" ($source)")if (maxDurationSeconds != null && maxDurationSeconds > 0) append(", max ${maxDurationSeconds}s")- append(" at ${file.absolutePath}")+ append(" at $recordingDisplayPath")if (quality != null) append(", $quality quality")}ToolResult.ok("Recording started$extras.")} catch (e: Exception) {+ recordingUri?.let { com.gotcha.data.GotchaStorage.discardPendingRecording(context, it) }releaseRecorder()ToolResult.error("Could not start recording: ${e.message}")}@@ -205,14 +232,18 @@ class MediaCaptureTool(private val context: Context) {val rec = recorder ?: return alreadyStoppedResult()return try {rec.stop()- val file = recordingFile- val path = file?.absolutePath ?: "unknown"+ val path = recordingDisplayPathval dur = (System.currentTimeMillis() - recordingStartTime) / 1000- // Make the file accessible to other apps- file?.setReadable(true, false)+ val file = recordingFile+ val uri = recordingUriif (file != null) {+ // Make the file accessible to other apps+ file.setReadable(true, false)com.gotcha.data.GotchaStorage.publishToGallery(context, file)}+ if (uri != null) {+ com.gotcha.data.GotchaStorage.finalizeRecording(context, uri)+ }releaseRecorder()lastSavedPath = pathlastSavedDurationSeconds = dur@@ -245,7 +276,7 @@ class MediaCaptureTool(private val context: Context) {val rec = recorderif (rec == null) return ToolResult.ok("No recording is active.")val elapsed = (System.currentTimeMillis() - recordingStartTime) / 1000- val path = recordingFile?.absolutePath ?: "unknown"+ val path = recordingDisplayPath.ifEmpty { "unknown" }val state = if (recordingPaused) "paused" else "recording"return ToolResult.ok("$state for ${elapsed / 60}m ${elapsed % 60}s at $path.")}@@ -296,8 +327,12 @@ class MediaCaptureTool(private val context: Context) {private fun releaseRecorder() {try { recorder?.release() } catch (_: Exception) {}+ try { recordingPfd?.close() } catch (_: Exception) {}recorder = nullrecordingFile = null+ recordingUri = null+ recordingPfd = null+ recordingDisplayPath = ""recordingStartTime = 0LrecordingPaused = false}