Modern Apps git

← Modern-Apps.git

files: create zip files & notifications for progress

Commit
b4ee0d7449d0f054905519d1b54a945d4383bf5a
Author
Vayun Mathur <[email protected]>
When
2026-04-13 02:29 UTC (7 months ago)
Parents
1357ec8

Diff

files/src/main/AndroidManifest.xml
diff --git a/files/src/main/AndroidManifest.xml b/files/src/main/AndroidManifest.xmlindex b42b73865f..065a57b7e3 100644--- a/files/src/main/AndroidManifest.xml+++ b/files/src/main/AndroidManifest.xml@@ -4,6 +4,9 @@      <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"         tools:ignore="AllFilesAccessPolicy,ScopedStorage" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />      <application         android:allowBackup="true"@@ -24,6 +27,11 @@                 android:resource="@xml/file_paths" />         </provider> +        <service+            android:name="androidx.work.impl.foreground.SystemForegroundService"+            android:foregroundServiceType="dataSync"+            tools:node="merge" />+         <activity             android:name=".MainActivity"             android:exported="true"
files/src/main/java/com/vayunmathur/files/MainActivity.kt
diff --git a/files/src/main/java/com/vayunmathur/files/MainActivity.kt b/files/src/main/java/com/vayunmathur/files/MainActivity.ktindex f41acf0563..39599c74c8 100644--- a/files/src/main/java/com/vayunmathur/files/MainActivity.kt+++ b/files/src/main/java/com/vayunmathur/files/MainActivity.kt@@ -1,8 +1,11 @@ package com.vayunmathur.files +import android.Manifest import android.content.ClipData import android.content.ClipDescription+import android.content.Context import android.content.Intent+import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle@@ -27,6 +30,7 @@ import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth@@ -38,6 +42,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider@@ -50,6 +55,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text+import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable@@ -76,11 +82,13 @@ import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconArchive import com.vayunmathur.library.ui.IconChevronRight import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconDelete@@ -111,18 +119,71 @@ class MainActivity : ComponentActivity() { @Composable fun HomeDirectoryPage() {     val context = LocalContext.current-    var isGranted by remember { mutableStateOf(Environment.isExternalStorageManager()) }-    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {-        isGranted = Environment.isExternalStorageManager()+    val prefs = remember { context.getSharedPreferences("files_prefs", Context.MODE_PRIVATE) }+    +    var isFilesGranted by remember { mutableStateOf(Environment.isExternalStorageManager()) }+    var hasPromptedNotifications by remember { mutableStateOf(prefs.getBoolean("has_prompted_notifications", false)) }+    var showNotificationDialog by remember { mutableStateOf(false) }++    val filesLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {+        isFilesGranted = Environment.isExternalStorageManager()+    }++    val notificationsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->+        prefs.edit().putBoolean("has_prompted_notifications", true).apply()+        hasPromptedNotifications = true+        showNotificationDialog = false+    }++    LaunchedEffect(isFilesGranted, hasPromptedNotifications) {+        if (isFilesGranted && !hasPromptedNotifications && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            val isGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED+            if (!isGranted) {+                showNotificationDialog = true+            } else {+                prefs.edit().putBoolean("has_prompted_notifications", true).apply()+                hasPromptedNotifications = true+            }+        }     } -    if (!isGranted) {+    if (showNotificationDialog) {+        AlertDialog(+            onDismissRequest = { +                prefs.edit().putBoolean("has_prompted_notifications", true).apply()+                hasPromptedNotifications = true+                showNotificationDialog = false +            },+            title = { Text("Enable Notifications?") },+            text = { Text("Turning on notifications will allow you to see progress on background actions like zipping and unzipping files.") },+            confirmButton = {+                TextButton(onClick = {+                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                        notificationsLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+                    }+                }) {+                    Text("Enable")+                }+            },+            dismissButton = {+                TextButton(onClick = {+                    prefs.edit().putBoolean("has_prompted_notifications", true).apply()+                    hasPromptedNotifications = true+                    showNotificationDialog = false+                }) {+                    Text("Skip")+                }+            }+        )+    }++    if (!isFilesGranted) {         Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {             Button(onClick = {                 val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {                     data = Uri.fromParts("package", context.packageName, null)                 }-                launcher.launch(intent)+                filesLauncher.launch(intent)             }) {                 Text("Grant All Files Access")             }@@ -165,6 +226,48 @@ fun DirectoryPage(rootFile: Path) {          var selectedPaths by remember(currentDirectory, currentFileSystem) { mutableStateOf(setOf<Path>()) }     var pathBeingRenamed by remember { mutableStateOf<Path?>(null) }+    var showArchiveDialog by remember { mutableStateOf(false) }+    var archiveName by remember { mutableStateOf("archive.zip") }++    if (showArchiveDialog) {+        AlertDialog(+            onDismissRequest = { showArchiveDialog = false },+            title = { Text("Archive Selection") },+            text = {+                TextField(+                    value = archiveName,+                    onValueChange = { archiveName = it },+                    label = { Text("Zip file name") },+                    singleLine = true+                )+            },+            confirmButton = {+                TextButton(onClick = {+                    val destPath = currentDirectory.resolve(if (archiveName.endsWith(".zip")) archiveName else "$archiveName.zip")+                    val zipWork = OneTimeWorkRequestBuilder<ZipWorker>()+                        .setInputData(workDataOf(+                            "source_paths" to selectedPaths.map { it.toString() }.toTypedArray(),+                            "dest_path" to destPath.toString()+                        ))+                        .build()+                    WorkManager.getInstance(context).enqueue(zipWork)+                    selectedPaths = emptySet()+                    pathBeingRenamed = null+                    showArchiveDialog = false+                    scope.launch {+                        snackbarHostState.showSnackbar("Archiving started...")+                    }+                }) {+                    Text("Archive")+                }+            },+            dismissButton = {+                TextButton(onClick = { showArchiveDialog = false }) {+                    Text("Cancel")+                }+            }+        )+    }      val zipToUnzip = remember(selectedPaths) {         if (selectedPaths.size == 1 && !selectedPaths.first().isDirectory(currentFileSystem) && selectedPaths.first().name.endsWith(".zip", ignoreCase = true)) {@@ -376,6 +479,14 @@ fun DirectoryPage(rootFile: Path) {                         }                     }                     if (!isReadOnly) {+                        if (selectedPaths.isNotEmpty()) {+                            IconButton(onClick = {+                                archiveName = if (selectedPaths.size == 1) "${selectedPaths.first().name}.zip" else "archive.zip"+                                showArchiveDialog = true+                            }) {+                                IconArchive()+                            }+                        }                         if (zipToUnzip != null) {                             IconButton(onClick = { treeLauncher.launch(null) }) {                                 IconUnarchive()
files/src/main/java/com/vayunmathur/files/UnzipWorker.kt
diff --git a/files/src/main/java/com/vayunmathur/files/UnzipWorker.kt b/files/src/main/java/com/vayunmathur/files/UnzipWorker.ktindex 1fc20f26fe..e9ac708a4d 100644--- a/files/src/main/java/com/vayunmathur/files/UnzipWorker.kt+++ b/files/src/main/java/com/vayunmathur/files/UnzipWorker.kt@@ -1,14 +1,25 @@ package com.vayunmathur.files +import android.app.NotificationChannel+import android.app.NotificationManager import android.content.Context+import android.content.pm.ServiceInfo+import androidx.core.app.NotificationCompat import androidx.work.CoroutineWorker+import androidx.work.ForegroundInfo import androidx.work.WorkerParameters import okio.FileSystem import okio.Path.Companion.toPath-import okio.source import java.util.zip.ZipInputStream  class UnzipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {++    private val notificationManager =+        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager++    private val channelId = "unzip_progress_channel"+    private val notificationId = 2+     override suspend fun doWork(): Result {         val zipPathString = inputData.getString("zip_path") ?: return Result.failure()         val destPathString = inputData.getString("dest_path") ?: return Result.failure()@@ -16,10 +27,36 @@ class UnzipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(         val zipPath = zipPathString.toPath()         val destPath = destPathString.toPath() +        createNotificationChannel()+        setForeground(createForegroundInfo(0))+         try {             val fileSystem = FileSystem.SYSTEM+            val zipFileSize = fileSystem.metadataOrNull(zipPath)?.size ?: 0L+            var totalBytesRead = 0L+             fileSystem.read(zipPath) {-                ZipInputStream(inputStream()).use { zipInputStream ->+                val countingInputStream = object : java.io.FilterInputStream(inputStream()) {+                    override fun read(): Int {+                        val b = super.read()+                        if (b != -1) {+                            totalBytesRead+++                            updateProgress(totalBytesRead, zipFileSize)+                        }+                        return b+                    }++                    override fun read(b: ByteArray, off: Int, len: Int): Int {+                        val count = super.read(b, off, len)+                        if (count != -1) {+                            totalBytesRead += count+                            updateProgress(totalBytesRead, zipFileSize)+                        }+                        return count+                    }+                }++                ZipInputStream(countingInputStream).use { zipInputStream ->                     var entry = zipInputStream.nextEntry                     while (entry != null) {                         val entryPath = destPath.resolve(entry.name)@@ -28,7 +65,14 @@ class UnzipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(                         } else {                             fileSystem.createDirectories(entryPath.parent!!)                             fileSystem.write(entryPath) {-                                writeAll(zipInputStream.source())+                                // Instead of writeAll(zipInputStream.source()), we can manually read/write to avoid closing issues+                                // and to keep our counting input stream active.+                                // Actually writeAll is fine as long as we don't close the ZipInputStream.+                                val buffer = ByteArray(8192)+                                var bytes: Int+                                while (zipInputStream.read(buffer).also { bytes = it } != -1) {+                                    write(buffer, 0, bytes)+                                }                             }                         }                         zipInputStream.closeEntry()@@ -36,10 +80,49 @@ class UnzipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(                     }                 }             }+            notificationManager.cancel(notificationId)             return Result.success()         } catch (e: Exception) {             e.printStackTrace()+            notificationManager.cancel(notificationId)             return Result.failure()         }     }++    private fun updateProgress(totalBytesRead: Long, zipFileSize: Long) {+        if (zipFileSize > 0) {+            val progress = (totalBytesRead * 100 / zipFileSize).toInt()+            updateNotification(progress)+        }+    }++    private fun createNotificationChannel() {+        val channel = NotificationChannel(+            channelId,+            "Unzip Operations",+            NotificationManager.IMPORTANCE_LOW+        )+        notificationManager.createNotificationChannel(channel)+    }++    private fun createForegroundInfo(progress: Int): ForegroundInfo {+        val notification = NotificationCompat.Builder(applicationContext, channelId)+            .setContentTitle("Unzipping...")+            .setSmallIcon(R.drawable.folder_24px)+            .setProgress(100, progress, false)+            .setOngoing(true)+            .build()++        return ForegroundInfo(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)+    }++    private fun updateNotification(progress: Int) {+        val notification = NotificationCompat.Builder(applicationContext, channelId)+            .setContentTitle("Unzipping...")+            .setSmallIcon(R.drawable.folder_24px)+            .setProgress(100, progress, false)+            .setOngoing(true)+            .build()+        notificationManager.notify(notificationId, notification)+    } }
files/src/main/java/com/vayunmathur/files/ZipWorker.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ZipWorker.kt b/files/src/main/java/com/vayunmathur/files/ZipWorker.ktnew file mode 100644index 0000000000..df181f7ada--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/ZipWorker.kt@@ -0,0 +1,137 @@+package com.vayunmathur.files++import android.app.NotificationChannel+import android.app.NotificationManager+import android.content.Context+import android.content.pm.ServiceInfo+import androidx.core.app.NotificationCompat+import androidx.work.CoroutineWorker+import androidx.work.ForegroundInfo+import androidx.work.WorkerParameters+import okio.FileSystem+import okio.Path+import okio.Path.Companion.toPath+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream++class ZipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {++    private val notificationManager =+        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager++    private val channelId = "zip_progress_channel"+    private val notificationId = 1++    override suspend fun doWork(): Result {+        val sourcePaths = inputData.getStringArray("source_paths") ?: return Result.failure()+        val destPathString = inputData.getString("dest_path") ?: return Result.failure()+        val destPath = destPathString.toPath()++        createNotificationChannel()+        setForeground(createForegroundInfo(0))++        try {+            val fileSystem = FileSystem.SYSTEM+            +            var totalSize = 0L+            sourcePaths.forEach { totalSize += calculateTotalSize(fileSystem, it.toPath()) }+            +            var bytesZipped = 0L++            fileSystem.write(destPath) {+                ZipOutputStream(outputStream()).use { zipOutputStream ->+                    sourcePaths.forEach { pathString ->+                        val path = pathString.toPath()+                        addToZip(fileSystem, path, "", zipOutputStream) { bytes ->+                            bytesZipped += bytes+                            if (totalSize > 0) {+                                val progress = (bytesZipped * 100 / totalSize).toInt()+                                updateNotification(progress)+                            }+                        }+                    }+                }+            }+            notificationManager.cancel(notificationId)+            return Result.success()+        } catch (e: Exception) {+            e.printStackTrace()+            notificationManager.cancel(notificationId)+            return Result.failure()+        }+    }++    private fun calculateTotalSize(fileSystem: FileSystem, path: Path): Long {+        val metadata = fileSystem.metadataOrNull(path) ?: return 0L+        if (metadata.isDirectory) {+            var size = 0L+            fileSystem.list(path).forEach { size += calculateTotalSize(fileSystem, it) }+            return size+        }+        return metadata.size ?: 0L+    }++    private fun addToZip(+        fileSystem: FileSystem,+        path: Path,+        base: String,+        zipOutputStream: ZipOutputStream,+        onProgress: (Long) -> Unit+    ) {+        val entryName = if (base.isEmpty()) path.name else "$base/${path.name}"+        val metadata = fileSystem.metadataOrNull(path) ?: return++        if (metadata.isDirectory) {+            val children = fileSystem.list(path)+            if (children.isEmpty()) {+                zipOutputStream.putNextEntry(ZipEntry("$entryName/"))+                zipOutputStream.closeEntry()+            } else {+                children.forEach { child ->+                    addToZip(fileSystem, child, entryName, zipOutputStream, onProgress)+                }+            }+        } else {+            zipOutputStream.putNextEntry(ZipEntry(entryName))+            fileSystem.read(path) {+                val buffer = ByteArray(8192)+                var bytesRead: Int+                while (inputStream().read(buffer).also { bytesRead = it } != -1) {+                    zipOutputStream.write(buffer, 0, bytesRead)+                    onProgress(bytesRead.toLong())+                }+            }+            zipOutputStream.closeEntry()+        }+    }++    private fun createNotificationChannel() {+        val channel = NotificationChannel(+            channelId,+            "Zip Operations",+            NotificationManager.IMPORTANCE_LOW+        )+        notificationManager.createNotificationChannel(channel)+    }++    private fun createForegroundInfo(progress: Int): ForegroundInfo {+        val notification = NotificationCompat.Builder(applicationContext, channelId)+            .setContentTitle("Archiving...")+            .setSmallIcon(R.drawable.folder_24px)+            .setProgress(100, progress, false)+            .setOngoing(true)+            .build()++        return ForegroundInfo(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)+    }++    private fun updateNotification(progress: Int) {+        val notification = NotificationCompat.Builder(applicationContext, channelId)+            .setContentTitle("Archiving...")+            .setSmallIcon(R.drawable.folder_24px)+            .setProgress(100, progress, false)+            .setOngoing(true)+            .build()+        notificationManager.notify(notificationId, notification)+    }+}
library/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 1cec0b3b5c..306857f8cb 100644--- a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -118,6 +118,11 @@ fun IconUnarchive(tint: Color = LocalContentColor.current) {     Icon(painterResource(R.drawable.unarchive_24px), "Unarchive", tint = tint) } +@Composable+fun IconArchive(tint: Color = LocalContentColor.current) {+    Icon(painterResource(R.drawable.archive_24px), "Archive", tint = tint)+}+ @Composable fun IconChevronRight(tint: Color = LocalContentColor.current) {     Icon(painterResource(R.drawable.chevron_right_24px), "Chevron", tint = tint)
library/src/main/res/drawable/archive_24px.xml
diff --git a/library/src/main/res/drawable/archive_24px.xml b/library/src/main/res/drawable/archive_24px.xmlnew file mode 100644index 0000000000..c23732c424--- /dev/null+++ b/library/src/main/res/drawable/archive_24px.xml@@ -0,0 +1,9 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24">+    <path+        android:fillColor="@android:color/black"+        android:pathData="M20.54,5.23l-1.39,-1.68C18.88,3.21 18.47,3 18,3H6C5.53,3 5.12,3.21 4.84,3.55L3.46,5.23C3.17,5.57 3,6.01 3,6.5V19c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V6.5C21,6.01 20.83,5.57 20.54,5.23zM6.24,5h11.52l0.83,1H5.41L6.24,5zM5,19V8h14v11H5zM12,9l-4,4h3v4h2v-4h3L12,9z" />+</vector>\ No newline at end of file