Repository: Juby210/SwiftBackupPrem Branch: main Commit: 050290fa64fb Files: 30 Total size: 45.9 KB Directory structure: gitextract_aozlix7o/ ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ ├── native_init │ │ └── xposed_init │ ├── cpp/ │ │ ├── CMakeLists.txt │ │ ├── hook.h │ │ └── nativelib.c │ ├── java/ │ │ └── io/ │ │ └── github/ │ │ └── juby210/ │ │ └── swiftbackupprem/ │ │ ├── BackupModule.kt │ │ ├── Consts.kt │ │ ├── DexKit.kt │ │ ├── MainActivity.kt │ │ ├── Module.java │ │ ├── ui/ │ │ │ ├── component/ │ │ │ │ ├── SettingsSwitch.kt │ │ │ │ └── SettingsTextField.kt │ │ │ └── theme/ │ │ │ └── Theme.kt │ │ └── util/ │ │ └── PreferencesManager.kt │ └── res/ │ ├── drawable/ │ │ └── ic_launcher_foreground.xml │ ├── mipmap-anydpi-v26/ │ │ └── ic_launcher.xml │ └── values/ │ └── colors.xml ├── build.gradle.kts ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle.kts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties .idea .DS_Store build /captures .externalNativeBuild .cxx local.properties release ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2022 Juby210 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # SwiftBackupPrem Swift Backup Premium LSPosed module (tested on v4.2.3, v4.2.5 and v5.0.4, but should also work on newer versions - thanks to [DexKit](https://github.com/LuckyPray/DexKit)). Optionally also allows you to set your own firebase credentials, so only your firebase instance is used. It is highly recommened to set your own firebase credentials, because the developer can ban you from accessing original app using his firebase instance. Step-by-step setup for your own firebase instance: https://user-images.githubusercontent.com/31005896/203136303-36079018-3199-4863-864b-40293342f262.mp4 Since October 2023 Google disabled Custom URI schemes by default for new projects. Check `Enable custom URI scheme` while creating Android OAuth client (~3:36 on guide video). ![image](https://github.com/Juby210/SwiftBackupPrem/assets/31005896/8049f7e2-26db-418b-9611-171be77b61f1) ================================================ FILE: app/build.gradle.kts ================================================ @file:Suppress("UnstableApiUsage") plugins { id("com.android.application") id("kotlin-android") } android { namespace = "io.github.juby210.swiftbackupprem" compileSdk = 34 ndkVersion = "25.1.8937393" defaultConfig { applicationId = "io.github.juby210.swiftbackupprem" minSdk = 27 targetSdk = 34 versionCode = 204 versionName = "2.0.4" } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } externalNativeBuild { cmake { path("src/main/cpp/CMakeLists.txt") version = "3.22.1" } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } buildFeatures { buildConfig = true compose = true resValues = false } composeOptions.kotlinCompilerExtensionVersion = "1.5.8" tasks.withType { kotlinOptions { jvmTarget = "11" } } } dependencies { compileOnly("de.robv.android.xposed:api:82") implementation("org.luckypray:dexkit:2.0.0") // AndroidX implementation("androidx.core:core-ktx:1.12.0") implementation("androidx.activity:activity-compose:1.8.2") // Compose val composeVersion = "1.6.0" implementation("androidx.compose.ui:ui:$composeVersion") implementation("androidx.compose.ui:ui-tooling:$composeVersion") implementation("androidx.compose.material3:material3:1.1.2") } ================================================ FILE: app/proguard-rules.pro ================================================ # Uncomment this to preserve the line number information for # debugging stack traces. -keepattributes SourceFile,LineNumberTable # Repackage classes into the top-level. -repackageclasses # Amount of optimization iterations, taken from an SO post -optimizationpasses 5 # Broaden access modifiers to increase results during optimization -allowaccessmodification -keep class io.github.juby210.swiftbackupprem.Module { *; } -keep class io.github.juby210.swiftbackupprem.DexKit { public final void findObfuscatedClasses(android.content.Context, java.lang.ClassLoader, java.lang.String); } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/native_init ================================================ libnativelib.so ================================================ FILE: app/src/main/assets/xposed_init ================================================ io.github.juby210.swiftbackupprem.Module ================================================ FILE: app/src/main/cpp/CMakeLists.txt ================================================ # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.22.1) # Declares and names the project. project("app") # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. add_library( # Sets the name of the library. nativelib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). nativelib.c) target_link_libraries(nativelib) ================================================ FILE: app/src/main/cpp/hook.h ================================================ typedef int (*HookFunType)(void *func, void *replace, void **backup); typedef int (*UnhookFunType)(void *func); typedef void (*NativeOnModuleLoaded)(const char *name, void *handle); typedef struct { uint32_t version; HookFunType hook_func; UnhookFunType unhook_func; } NativeAPIEntries; typedef NativeOnModuleLoaded (*NativeInit)(const NativeAPIEntries *entries); ================================================ FILE: app/src/main/cpp/nativelib.c ================================================ #include #include #include #include #include "hook.h" static HookFunType hook_func = NULL; jint (*backup)(JavaVM *, void *); jint fakeLoad(JavaVM *, void *) { return JNI_VERSION_1_6; } bool ends_with(const char *a, const char *b) { size_t len = strlen(a); size_t len2 = strlen(b); if (len2 > len) return false; return strncmp(a + len - len2, b, len2) == 0; } void on_library_loaded(const char *name, void *handle) { if (ends_with(name, "libnative-lib.so")) { void *target = dlsym(handle, "JNI_OnLoad"); hook_func(target, (void *) fakeLoad, (void **) &backup); } } NativeOnModuleLoaded native_init(const NativeAPIEntries *entries) { hook_func = entries->hook_func; return on_library_loaded; } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/BackupModule.kt ================================================ package io.github.juby210.swiftbackupprem import android.content.Context import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedBridge import io.github.juby210.swiftbackupprem.util.PreferencesManager import org.json.JSONArray import org.json.JSONObject import java.io.File fun hookBackupApk(cl: ClassLoader, ctx: Context, customFirebaseApp: Boolean, prefs: PreferencesManager) { val pathsA = cl.loadClass("${paths!!.name}\$a") XposedBridge.hookMethod(backupApk!!.getDeclaredMethod("c"), object : XC_MethodHook() { override fun afterHookedMethod(param: MethodHookParam) { val pathsClass = paths!! val aInstance = pathsClass.declaredFields.first { it.type == pathsA }.get(null) val instance = pathsA.getDeclaredMethod("d").invoke(aInstance) val basePath = pathsClass.getDeclaredMethod("m").invoke(instance) as String val dir = File(basePath, "sbp") if (!dir.exists()) dir.mkdir() val apkFile = File(dir, "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE}).apk") if (!apkFile.exists()) File(ctx.packageManager.getPackageInfo(BuildConfig.APPLICATION_ID, 0).applicationInfo.sourceDir).copyTo(apkFile, true) if (customFirebaseApp) with(prefs) { val json = JSONObject().apply { put("client", JSONArray().apply { put(JSONObject().apply { put("client_info", JSONObject().apply { put("mobilesdk_app_id", googleAppId) }) put("api_key", JSONArray().apply { put(JSONObject().apply { put("current_key", googleApiKey) }) }) }) }) put("project_info", JSONObject().apply { put("firebase_url", firebaseDatabaseUrl) put("project_number", gcmDefaultSenderId) put("storage_bucket", googleStorageBucket) put(Consts.projectId, projectId) }) put(Consts.oauthClientId, clientId) }.toString() File(dir, "google-services.json").run { if (!exists() || readText() != json) writeText(json) } } } }) } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/Consts.kt ================================================ package io.github.juby210.swiftbackupprem object Consts { const val packageName = "org.swiftapps.swiftbackup" const val googleAppId = "google_app_id" const val googleApiKey = "google_api_key" const val firebaseDatabaseUrl = "firebase_database_url" const val gcmDefaultSenderId = "gcm_defaultSenderId" const val googleStorageBucket = "google_storage_bucket" const val projectId = "project_id" const val oauthClientId = "oauth_client_id" @JvmStatic val classNames = mapOf(561 to "kf.s0", 569 to "rf.r0") } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/DexKit.kt ================================================ @file:JvmName("DexKit") package io.github.juby210.swiftbackupprem import android.content.Context import android.util.Log import android.widget.Toast import org.luckypray.dexkit.DexKitBridge import java.lang.reflect.Modifier private val classesClientId = mapOf(561 to "kf.s0", 569 to "rf.r0", 590 to "eh.u") private val classesBackupApk = mapOf(561 to "org.swiftapps.swiftbackup.common.w1", 569 to "org.swiftapps.swiftbackup.common.n2", 590 to "org.swiftapps.swiftbackup.common.c2") private val classesPaths = mapOf(561 to "me.b", 569 to "te.c", 590 to "org.swiftapps.swiftbackup.a") @JvmField var clientId: Class<*>? = null @JvmField var backupApk: Class<*>? = null @JvmField var paths: Class<*>? = null @Suppress("DEPRECATION") fun findObfuscatedClasses(ctx: Context, cl: ClassLoader, sourceDir: String) { val ver = Integer.valueOf(ctx.packageManager.getPackageInfo(Consts.packageName, 0).versionCode) if (classesClientId.containsKey(ver)) { clientId = cl.loadClass(classesClientId[ver]) backupApk = cl.loadClass(classesBackupApk[ver]) paths = cl.loadClass(classesPaths[ver]) } else { System.loadLibrary("dexkit") val excludePackages = listOf("android", "androidx", "com", "iammert", "java", "javax", "kotlin", "kotlinx", "moe", "nz.mega", "okhttp3", "okio", "retrofit", "rikka") DexKitBridge.create(sourceDir).use { bridge -> bridge.findClass { excludePackages(excludePackages) matcher { fields { add { modifiers(Modifier.PUBLIC or Modifier.STATIC or Modifier.FINAL) name("a") } add { modifiers(Modifier.PRIVATE or Modifier.STATIC or Modifier.FINAL) name("b") } add { modifiers(Modifier.PRIVATE or Modifier.STATIC or Modifier.FINAL) name("c") type("java.lang.String") } add { modifiers(Modifier.PRIVATE or Modifier.STATIC or Modifier.FINAL) name("d") type("android.net.Uri") } count(4) } addMethod { modifiers(Modifier.PUBLIC or Modifier.FINAL) returnType("android.content.Intent") name("f") addParamType("boolean") } } }.singleOrNull()?.let { clientId = it.getInstance(cl) Log.d("SBP", "Found client id class: ${it.name}") } bridge.findClass { searchPackages("org.swiftapps.swiftbackup.common") matcher { fields { addForName("a") count(1) } addMethod { modifiers(Modifier.PRIVATE or Modifier.FINAL) returnType("void") name("c") paramCount(0) usingStrings("stable", "swift_backup_apks/", "SwiftBackupApkSaver") } } }.singleOrNull()?.let { backupApk = it.getInstance(cl) Log.d("SBP", "Found backup apk class: ${it.name}") } bridge.findClass { excludePackages(excludePackages) matcher { methods { add { name("") addParamType("org.swiftapps.swiftbackup.anonymous.MFirebaseUser") addParamType("java.lang.String") paramCount(2) usingStrings("accounts/", "backups/", "cache/", "apps/", "local/", "cloud/", "icon_cache/", "sms/", "calls/") } add { modifiers(Modifier.PUBLIC or Modifier.FINAL) returnType("java.lang.String") name("m") paramCount(0) } } } }.singleOrNull()?.let { paths = it.getInstance(cl) Log.d("SBP", "Found paths class: ${it.name}") } } if (clientId == null || backupApk == null || paths == null) Toast.makeText( ctx, "[SBP] Couldn't fully hook Swift Backup. Check if there's module update or report an issue.", Toast.LENGTH_LONG ).show() } } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/MainActivity.kt ================================================ package io.github.juby210.swiftbackupprem import android.annotation.SuppressLint import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import io.github.juby210.swiftbackupprem.ui.component.SettingsSwitch import io.github.juby210.swiftbackupprem.ui.component.SettingsTextField import io.github.juby210.swiftbackupprem.ui.theme.Theme import io.github.juby210.swiftbackupprem.util.PreferencesManager import kotlinx.coroutines.* import org.json.JSONObject import kotlin.system.exitProcess class MainActivity : ComponentActivity() { @SuppressLint("WorldReadableFiles") @OptIn(ExperimentalMaterial3Api::class) override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) val prefs: PreferencesManager try { @Suppress("DEPRECATION") prefs = PreferencesManager(getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", MODE_WORLD_READABLE)) } catch (e: Throwable) { Toast.makeText(this, "Enable module in LSPosed manager before using it", Toast.LENGTH_SHORT).show() finishAndRemoveTask() exitProcess(0) } setContent { Theme { Scaffold( topBar = { TopAppBar( title = { Text("SwiftBackupPrem") } ) } ) { paddingValues -> Column(modifier = Modifier.padding(paddingValues).fillMaxSize().verticalScroll(state = rememberScrollState())) { SettingsSwitch( label = "Custom firebase app", secondaryLabel = "Recommended, forces Swift Backup to use your own firebase credentials", pref = prefs.customFirebaseApp, onPrefChange = { prefs.customFirebaseApp = it } ) if (prefs.customFirebaseApp) { SettingsTextField( label = "Google App ID", pref = prefs.googleAppId, onPrefChange = { prefs.googleAppId = it } ) SettingsTextField( label = "Google Api Key", pref = prefs.googleApiKey, onPrefChange = { prefs.googleApiKey = it } ) SettingsTextField( label = "Firebase Database URL", pref = prefs.firebaseDatabaseUrl, onPrefChange = { prefs.firebaseDatabaseUrl = it } ) SettingsTextField( label = "GCM Default Sender ID", pref = prefs.gcmDefaultSenderId, onPrefChange = { prefs.gcmDefaultSenderId = it } ) SettingsTextField( label = "Google Storage Bucket", pref = prefs.googleStorageBucket, onPrefChange = { prefs.googleStorageBucket = it } ) SettingsTextField( label = "Project ID", pref = prefs.projectId, onPrefChange = { prefs.projectId = it } ) SettingsTextField( label = "Client ID", pref = prefs.clientId, onPrefChange = { prefs.clientId = it } ) val pickJson = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { if (it != null) { contentResolver.openInputStream(it)?.use { inputStream -> try { val json = JSONObject(inputStream.bufferedReader().use { r -> r.readText() }) with(prefs) { with(json.getJSONArray("client").getJSONObject(0)) { googleAppId = getJSONObject("client_info").getString("mobilesdk_app_id") googleApiKey = getJSONArray("api_key").getJSONObject(0).getString("current_key") } with(json.getJSONObject("project_info")) { firebaseDatabaseUrl = getString("firebase_url") gcmDefaultSenderId = getString("project_number") googleStorageBucket = getString("storage_bucket") projectId = getString(Consts.projectId) } if (json.has(Consts.oauthClientId)) clientId = json.getString(Consts.oauthClientId) } } catch (e: Throwable) { Toast.makeText(this@MainActivity, "Failed to parse json\n$e", Toast.LENGTH_LONG).show() Log.e("SBP", "Failed to parse json", e) } } } } Button( onClick = { pickJson.launch("application/json") }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Import from google-services.json") } val uriHandler = LocalUriHandler.current Button( onClick = { uriHandler.openUri("https://console.firebase.google.com/u/0/") }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Open Firebase Console") } Button( onClick = { uriHandler.openUri("https://console.developers.google.com/") }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Open Google Developer Console") } val clip = LocalClipboardManager.current Button( onClick = { clip.setText( AnnotatedString( "{\n" + " \"rules\": {\n" + " \"users\": {\n" + " \"\$uid\": {\n" + " \".read\": \"\$uid === auth.uid\",\n" + " \".write\": \"\$uid === auth.uid\"\n" + " }\n" + " }\n" + " }\n" + "}" ) ) }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Copy database rules") } Button( onClick = { clip.setText(AnnotatedString(Consts.packageName)) }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Copy Swift Backup package name") } Button( onClick = { clip.setText(AnnotatedString(randomFingerprint())) }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Copy random fingerprint") } Button( onClick = { uriHandler.openUri("https://console.cloud.google.com/apis/library/drive.googleapis.com?project=${prefs.projectId}") }, modifier = Modifier.padding(horizontal = 15.dp, vertical = 5.dp).fillMaxWidth().height(40.dp) ) { Text("Enable Google Drive API") } } } } } } } private val chars = ('A'..'F') + ('0'..'9') private fun randomFingerprint() = List(20) { chars.random().toString() + chars.random() }.joinToString(":") } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/Module.java ================================================ package io.github.juby210.swiftbackupprem; import android.content.Context; import java.util.Arrays; import de.robv.android.xposed.*; import de.robv.android.xposed.callbacks.XC_LoadPackage; import io.github.juby210.swiftbackupprem.util.PreferencesManager; public final class Module implements IXposedHookLoadPackage { public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals(Consts.packageName)) return; System.loadLibrary("nativelib"); var xPrefs = new XSharedPreferences(BuildConfig.APPLICATION_ID); xPrefs.makeWorldReadable(); var prefs = new PreferencesManager(xPrefs); var customFirebaseApp = prefs.getCustomFirebaseApp() && prefs.getGoogleAppId().length() > 0 && prefs.getGoogleApiKey().length() > 0 && prefs.getFirebaseDatabaseUrl().length() > 0 && prefs.getGcmDefaultSenderId().length() > 0 && prefs.getProjectId().length() > 0 && prefs.getClientId().length() > 0; var cl = lpparam.classLoader; var sa = cl.loadClass("org.swiftapps.swiftbackup.SwiftApp"); XposedHelpers.findAndHookMethod(sa, "onCreate", new XC_MethodHook() { @SuppressWarnings("JavaReflectionInvocation") public void beforeHookedMethod(MethodHookParam param) throws Throwable { var ctx = (Context) param.thisObject; DexKit.findObfuscatedClasses(ctx, cl, lpparam.appInfo.sourceDir); var c = cl.loadClass("com.google.firebase.FirebaseApp"); if (customFirebaseApp) { var options = cl.loadClass("com.google.firebase.FirebaseOptions"); var params = new Class[7]; Arrays.fill(params, String.class); var constructor = options.getDeclaredConstructor(params); c.getDeclaredMethod("initializeApp", Context.class, options).invoke( null, ctx, constructor.newInstance( prefs.getGoogleAppId(), prefs.getGoogleApiKey(), prefs.getFirebaseDatabaseUrl(), null, prefs.getGcmDefaultSenderId(), prefs.getGoogleStorageBucket(), prefs.getProjectId() ) ); if (DexKit.clientId != null) XposedBridge.hookMethod(DexKit.clientId.getDeclaredMethod("f", boolean.class), new XC_MethodHook() { public void beforeHookedMethod(MethodHookParam param) throws Throwable { var clientId = DexKit.clientId.getDeclaredField("c"); clientId.setAccessible(true); clientId.set(null, prefs.getClientId()); } }); } else c.getDeclaredMethod("initializeApp", Context.class).invoke(null, param.thisObject); if (DexKit.backupApk != null && DexKit.paths != null) BackupModuleKt.hookBackupApk(cl, ctx, customFirebaseApp, prefs); } }); if (customFirebaseApp) XposedHelpers.findAndHookMethod("org.swiftapps.swiftbackup.cloud.d", cl, "d", XC_MethodReplacement.returnConstant(Boolean.FALSE)); var c = cl.loadClass("org.swiftapps.swiftbackup.common.V$a"); for (var m : c.getDeclaredMethods()) { if (m.getName().equals("invoke")) { XposedBridge.hookMethod(m, XC_MethodReplacement.returnConstant(Boolean.TRUE)); break; } } } } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/ui/component/SettingsSwitch.kt ================================================ package io.github.juby210.swiftbackupprem.ui.component import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun SettingsSwitch( label: String, secondaryLabel: String, pref: Boolean, onPrefChange: (Boolean) -> Unit, ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 5.dp) .clickable { onPrefChange(!pref) }, horizontalArrangement = Arrangement.spacedBy(15.dp), verticalAlignment = Alignment.CenterVertically ) { Column( verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.weight(0.95f, true) ) { ProvideTextStyle( MaterialTheme.typography.titleLarge.copy( fontWeight = FontWeight.Normal, fontSize = 18.sp ) ) { Text(text = label, softWrap = true) } ProvideTextStyle( MaterialTheme.typography.bodyMedium.copy( color = MaterialTheme.colorScheme.onSurface.copy(0.6f) ) ) { Text(text = secondaryLabel) } } Spacer(Modifier.weight(0.05f, true)) Switch( checked = pref, onCheckedChange = { onPrefChange(!pref) } ) } } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/ui/component/SettingsTextField.kt ================================================ package io.github.juby210.swiftbackupprem.ui.component import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsTextField( label: String, pref: String, onPrefChange: (String) -> Unit, ) { Box(modifier = Modifier.padding(horizontal = 15.dp, vertical = 10.dp)) { OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = pref, onValueChange = onPrefChange, label = { Text(label) }, singleLine = true ) } } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/ui/theme/Theme.kt ================================================ package io.github.juby210.swiftbackupprem.ui.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext @Composable fun Theme(content: @Composable () -> Unit) { val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S val isDarkTheme = isSystemInDarkTheme() val colorScheme = when { dynamicColor && isDarkTheme -> dynamicDarkColorScheme(LocalContext.current) dynamicColor && !isDarkTheme -> dynamicLightColorScheme(LocalContext.current) isDarkTheme -> darkColorScheme() else -> lightColorScheme() } MaterialTheme( colorScheme = colorScheme, content = content ) } ================================================ FILE: app/src/main/java/io/github/juby210/swiftbackupprem/util/PreferencesManager.kt ================================================ package io.github.juby210.swiftbackupprem.util import android.content.SharedPreferences import androidx.compose.runtime.* import androidx.core.content.edit import io.github.juby210.swiftbackupprem.Consts import kotlin.reflect.KProperty class PreferencesManager(private val prefs: SharedPreferences) { private class Preference( private val key: String, defaultValue: T, getter: (key: String, defaultValue: T) -> T, private val setter: (key: String, newValue: T) -> Unit ) { var value by mutableStateOf(getter(key, defaultValue)) private set operator fun getValue(thisRef: Any?, property: KProperty<*>) = value operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) { value = newValue setter(key, newValue) } } private fun getString(key: String, defaultValue: String) = prefs.getString(key, defaultValue) ?: defaultValue private fun getBoolean(key: String, defaultValue: Boolean) = prefs.getBoolean(key, defaultValue) private fun putString(key: String, value: String?) = prefs.edit { putString(key, value) } private fun putBoolean(key: String, value: Boolean) = prefs.edit { putBoolean(key, value) } private fun stringPreference( key: String ) = Preference( key = key, defaultValue = "", getter = ::getString, setter = ::putString ) @Suppress("SameParameterValue") private fun booleanPreference( key: String ) = Preference( key = key, defaultValue = false, getter = ::getBoolean, setter = ::putBoolean ) var googleAppId by stringPreference(Consts.googleAppId) var googleApiKey by stringPreference(Consts.googleApiKey) var firebaseDatabaseUrl by stringPreference(Consts.firebaseDatabaseUrl) var gcmDefaultSenderId by stringPreference(Consts.gcmDefaultSenderId) var googleStorageBucket by stringPreference(Consts.googleStorageBucket) var projectId by stringPreference(Consts.projectId) var clientId by stringPreference(Consts.oauthClientId) var customFirebaseApp by booleanPreference("custom_firebase_app") } ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #ffa000 ================================================ FILE: build.gradle.kts ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() //noinspection JcenterRepositoryObsolete jcenter() } dependencies { classpath("com.android.tools.build:gradle:8.2.2") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.22") } } allprojects { repositories { google() //noinspection JcenterRepositoryObsolete jcenter() } } tasks.register("clean") { delete(rootProject.layout.buildDirectory) } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Tue Feb 06 16:02:37 CET 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Enables namespacing of each library's R class so that its R class includes only the # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library android.nonTransitiveRClass=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle.kts ================================================ include(":app") rootProject.name = "SwiftBackupPrem"