├── .github
└── FUNDING.yml
├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable
│ │ │ ├── ic_about_logo.webp
│ │ │ ├── ic_file_open.xml
│ │ │ ├── ic_kofi.xml
│ │ │ ├── ic_github.xml
│ │ │ ├── ic_apk_install.xml
│ │ │ ├── ic_launcher_foreground.xml
│ │ │ └── ic_launcher_background.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.webp
│ │ │ └── ic_launcher_round.webp
│ │ ├── values
│ │ │ ├── themes.xml
│ │ │ ├── colors.xml
│ │ │ └── strings.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── xml
│ │ │ ├── backup_rules.xml
│ │ │ └── data_extraction_rules.xml
│ │ ├── values-zh-rCN
│ │ │ └── strings.xml
│ │ ├── values-b+zh+Hant
│ │ │ └── strings.xml
│ │ └── values-vi
│ │ │ └── strings.xml
│ │ ├── java
│ │ └── com
│ │ │ └── leadrdrk
│ │ │ └── umapatcher
│ │ │ ├── core
│ │ │ ├── GitHubReleases.kt
│ │ │ ├── DataStore.kt
│ │ │ ├── GameChecker.kt
│ │ │ └── UpdateChecker.kt
│ │ │ ├── zip
│ │ │ ├── ZipExtractor.kt
│ │ │ ├── ZipFileExtractor.kt
│ │ │ └── MappedZipFileExtractor.kt
│ │ │ ├── utils
│ │ │ ├── ContextExtensions.kt
│ │ │ ├── DocumentFileExtensions.kt
│ │ │ └── Utils.kt
│ │ │ ├── ui
│ │ │ ├── component
│ │ │ │ ├── BackButton.kt
│ │ │ │ ├── TopBar.kt
│ │ │ │ ├── SimpleDialog.kt
│ │ │ │ └── Option.kt
│ │ │ ├── theme
│ │ │ │ ├── Type.kt
│ │ │ │ ├── Color.kt
│ │ │ │ └── Theme.kt
│ │ │ ├── patcher
│ │ │ │ ├── PatcherLauncher.kt
│ │ │ │ ├── PatcherCard.kt
│ │ │ │ └── AppPatcherCard.kt
│ │ │ └── screen
│ │ │ │ ├── BottomBarDestination.kt
│ │ │ │ ├── OpenSourceLicensesScreen.kt
│ │ │ │ ├── AppSelectScreen.kt
│ │ │ │ ├── HomeScreen.kt
│ │ │ │ ├── AboutScreen.kt
│ │ │ │ ├── SettingsScreen.kt
│ │ │ │ └── PatchingScreen.kt
│ │ │ ├── patcher
│ │ │ ├── PackageInstallerStatusReceiver.kt
│ │ │ ├── RootUtils.kt
│ │ │ ├── ApkSigner.kt
│ │ │ ├── Patcher.kt
│ │ │ └── AppPatcher.kt
│ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── config
└── libraries
│ └── libsu.json
├── settings.gradle
├── .gitmodules
├── README.md
├── gradle.properties
├── gradlew.bat
├── gradlew
└── LICENSE
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | ko_fi: leadrdrk
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /release
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_about_logo.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/drawable/ic_about_logo.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LeadRDRK/UmaPatcher/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Dec 05 11:43:48 ICT 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/config/libraries/libsu.json:
--------------------------------------------------------------------------------
1 | {
2 | "uniqueId": "com.github.topjohnwu.libsu:core",
3 | "developers": [
4 | { "name": "John Wu" }
5 | ],
6 | "description": "A complete solution for apps using root permissions.",
7 | "name": "libsu",
8 | "website": "https://github.com/topjohnwu/libsu",
9 | "licenses": ["Apache-2.0"]
10 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | maven { url 'https://jitpack.io' }
14 | }
15 | }
16 | rootProject.name = "UmaPatcher"
17 | include ':app'
18 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "app/src/main/cpp/libgit2"]
2 | path = app/src/main/cpp/libgit2
3 | url = https://github.com/libgit2/libgit2.git
4 | [submodule "app/src/main/cpp/openssl"]
5 | path = app/src/main/cpp/openssl
6 | url = https://github.com/openssl/openssl.git
7 | [submodule "app/src/main/c/openssl"]
8 | path = app/src/main/c/openssl
9 | url = https://github.com/openssl/openssl.git
10 | [submodule "app/src/main/c/libgit2"]
11 | path = app/src/main/c/libgit2
12 | url = https://github.com/libgit2/libgit2.git
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_file_open.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/core/GitHubReleases.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.core
2 |
3 | import android.net.Uri
4 | import java.net.URL
5 | import com.leadrdrk.umapatcher.utils.fetchJson as utilsFetchJson
6 |
7 | class GitHubReleases(
8 | private val repoPath: String
9 | ) {
10 | private val releasesApi = URL("https://api.github.com/repos/$repoPath/releases")
11 | private val latestApi = URL("https://api.github.com/repos/$repoPath/releases/latest")
12 |
13 | private fun fetchJson(url: URL): HashMap<*, *> =
14 | utilsFetchJson(url, "application/vnd.github+json")
15 |
16 | fun fetchReleases() = fetchJson(releasesApi)
17 | fun fetchLatest() = fetchJson(latestApi)
18 |
19 | fun getReleaseUrl(tagName: String) =
20 | "https://github.com/$repoPath/releases/tag/${Uri.encode(tagName)}"
21 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/zip/ZipExtractor.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.zip
2 |
3 | import android.os.Build
4 | import net.lingala.zip4j.model.AbstractFileHeader
5 | import java.io.File
6 |
7 | private const val MAX_MAPPED_SIZE = 104857600 // 100MiB
8 |
9 | abstract class ZipExtractor(val file: File): AutoCloseable {
10 | abstract suspend fun extractAll(dir: File, progressCallback: (Float) -> Unit)
11 |
12 | abstract val fileHeaders: List
13 |
14 | companion object {
15 | fun maybeMapped(file: File): ZipExtractor {
16 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && file.length() <= MAX_MAPPED_SIZE) {
17 | MappedZipFileExtractor(file)
18 | } else {
19 | ZipFileExtractor(file)
20 | }
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/utils/ContextExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.utils
2 |
3 | import android.content.Context
4 | import android.content.ContextWrapper
5 | import android.widget.Toast
6 | import androidx.activity.ComponentActivity
7 | import java.io.File
8 |
9 | val Context.workDir: File
10 | get() = cacheDir.resolve("work")
11 |
12 | val Context.repoDir: File
13 | get() = filesDir.resolve("repo")
14 |
15 | val Context.ksFile: File
16 | get() = filesDir.resolve("keystore.bks")
17 |
18 | fun Context.getActivity(): ComponentActivity? = when (this) {
19 | is ComponentActivity -> this
20 | is ContextWrapper -> baseContext.getActivity()
21 | else -> null
22 | }
23 |
24 | fun Context.showToast(text: String, duration: Int) {
25 | getActivity()?.runOnUiThread {
26 | Toast.makeText(this, text, duration).show()
27 | }
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/utils/DocumentFileExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.utils
2 |
3 | import androidx.documentfile.provider.DocumentFile
4 |
5 | fun DocumentFile.deleteRecursive(): Boolean {
6 | if (isDirectory) {
7 | listFiles().forEach {
8 | if (!it.deleteRecursive()) return false
9 | }
10 | }
11 | return delete()
12 | }
13 |
14 | fun DocumentFile.createDirectoryOverwrite(name: String): DocumentFile? {
15 | val dir = findFile(name) ?: return createDirectory(name)
16 | if (dir.isFile) {
17 | dir.delete()
18 | return createDirectory(name)
19 | }
20 | return dir
21 | }
22 |
23 | fun DocumentFile.createFileOverwrite(name: String): DocumentFile? {
24 | val file = findFile(name) ?: return createFile("*/*", name)
25 | if (file.isDirectory) {
26 | file.deleteRecursive()
27 | return createFile("*/*", name)
28 | }
29 | return file
30 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # UmaPatcher
2 |
3 |
4 | [](https://discord.gg/BVEt5FcxEn)
5 | [](https://ko-fi.com/Q5Q3QEHRA)
6 |
7 | UmaPatcher is an UM:PD Hachimi mod patching tool for Android. Its main purpose is to provide you
8 | with translation patches within the game, among other features.
9 |
10 | For more information, please check out [Hachimi](https://github.com/Hachimi-Hachimi/Hachimi).
11 |
12 | # Requirements
13 | - Android 7.0 or above
14 |
15 | # Download
16 | Download the latest release from the [Releases page](https://github.com/LeadRDRK/UmaPatcher/releases).
17 |
18 | # How to use
19 | Please see [Getting Started | Hachimi](https://hachimi.leadrdrk.com/docs/getting-started.html#android).
20 |
21 | # License
22 | [Apache License 2.0](LICENSE)
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/component/BackButton.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.component
2 |
3 | import androidx.compose.material.icons.Icons
4 | import androidx.compose.material.icons.filled.ArrowBack
5 | import androidx.compose.material3.Icon
6 | import androidx.compose.material3.IconButton
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.platform.LocalLifecycleOwner
9 | import com.leadrdrk.umapatcher.utils.safeNavigate
10 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
11 |
12 | @Composable
13 | fun BackButton(navigator: DestinationsNavigator, enabled: Boolean = true) {
14 | val lifecycleOwner = LocalLifecycleOwner.current
15 | IconButton(
16 | onClick = {
17 | safeNavigate(lifecycleOwner) {
18 | navigator.popBackStack()
19 | }
20 | },
21 | enabled = enabled
22 | ) {
23 | Icon(Icons.Filled.ArrowBack, contentDescription = null)
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_kofi.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/zip/ZipFileExtractor.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.zip
2 |
3 | import kotlinx.coroutines.delay
4 | import net.lingala.zip4j.ZipFile
5 | import net.lingala.zip4j.model.AbstractFileHeader
6 | import net.lingala.zip4j.progress.ProgressMonitor
7 | import java.io.File
8 |
9 | class ZipFileExtractor(
10 | file: File
11 | ): ZipExtractor(file) {
12 | private val zip = ZipFile(file).apply {
13 | isRunInThread = true
14 | }
15 |
16 | override suspend fun extractAll(dir: File, progressCallback: (Float) -> Unit) {
17 | zip.extractAll(dir.path)
18 | val progressMonitor = zip.progressMonitor
19 | while (!progressMonitor.state.equals(ProgressMonitor.State.READY)) {
20 | progressCallback(progressMonitor.percentDone / 100f)
21 | delay(100)
22 | }
23 | }
24 |
25 | override val fileHeaders: List
26 | get() = zip.fileHeaders
27 |
28 | override fun close() {
29 | zip.close()
30 | }
31 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/component/TopBar.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.component
2 |
3 | import androidx.compose.foundation.layout.RowScope
4 | import androidx.compose.material3.ExperimentalMaterial3Api
5 | import androidx.compose.material3.MaterialTheme
6 | import androidx.compose.material3.Text
7 | import androidx.compose.material3.TopAppBar
8 | import androidx.compose.material3.TopAppBarDefaults
9 | import androidx.compose.runtime.Composable
10 |
11 | @OptIn(ExperimentalMaterial3Api::class)
12 | @Composable
13 | fun TopBar(
14 | title: String,
15 | navigationIcon: @Composable () -> Unit = {},
16 | actions: @Composable RowScope.() -> Unit = {},
17 | ) {
18 | TopAppBar(
19 | colors = TopAppBarDefaults.topAppBarColors(
20 | containerColor = MaterialTheme.colorScheme.background,
21 | titleContentColor = MaterialTheme.colorScheme.onSurface,
22 | scrolledContainerColor = MaterialTheme.colorScheme.secondary
23 | ),
24 | title = {
25 | Text(title)
26 | },
27 | navigationIcon = navigationIcon,
28 | actions = actions
29 | )
30 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_github.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_apk_install.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/patcher/PatcherLauncher.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.patcher
2 |
3 | import android.content.Context
4 | import com.leadrdrk.umapatcher.MainActivity
5 | import com.leadrdrk.umapatcher.patcher.Patcher
6 | import com.leadrdrk.umapatcher.ui.screen.destinations.PatchingScreenDestination
7 | import com.leadrdrk.umapatcher.utils.getActivity
8 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
9 | import kotlinx.coroutines.Dispatchers
10 | import kotlinx.coroutines.withContext
11 |
12 | object PatcherLauncher {
13 | var patcher: Patcher? = null
14 | var patching = false
15 |
16 | fun launch(navigator: DestinationsNavigator, patcher: Patcher) {
17 | if (patching) return
18 |
19 | this.patcher = patcher
20 | navigator.navigate(PatchingScreenDestination)
21 | }
22 |
23 | suspend fun runPatcher(context: Context, callback: (Boolean) -> Unit) {
24 | val patcher = this.patcher
25 | if (patcher == null || patching) return
26 |
27 | val activity = context.getActivity() as MainActivity
28 | withContext(Dispatchers.IO) {
29 | activity.useKeepScreenOn {
30 | patching = true
31 | callback(patcher.safeRun(context))
32 | patching = false
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/BottomBarDestination.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import androidx.annotation.StringRes
4 | import androidx.compose.material.icons.Icons
5 | import androidx.compose.material.icons.filled.Home
6 | import androidx.compose.material.icons.filled.Info
7 | import androidx.compose.material.icons.filled.Settings
8 | import androidx.compose.material.icons.outlined.Home
9 | import androidx.compose.material.icons.outlined.Info
10 | import androidx.compose.material.icons.outlined.Settings
11 | import androidx.compose.ui.graphics.vector.ImageVector
12 | import com.leadrdrk.umapatcher.R
13 | import com.leadrdrk.umapatcher.ui.screen.destinations.AboutScreenDestination
14 | import com.leadrdrk.umapatcher.ui.screen.destinations.HomeScreenDestination
15 | import com.leadrdrk.umapatcher.ui.screen.destinations.SettingsScreenDestination
16 | import com.ramcosta.composedestinations.spec.DirectionDestinationSpec
17 |
18 | @Suppress("unused")
19 | enum class BottomBarDestination(
20 | val direction: DirectionDestinationSpec,
21 | @StringRes val label: Int,
22 | val iconSelected: ImageVector,
23 | val iconNotSelected: ImageVector
24 | ) {
25 | Home(HomeScreenDestination, R.string.home, Icons.Filled.Home, Icons.Outlined.Home),
26 | Settings(SettingsScreenDestination, R.string.settings, Icons.Filled.Settings, Icons.Outlined.Settings),
27 | About(AboutScreenDestination, R.string.about, Icons.Filled.Info, Icons.Outlined.Info)
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/core/DataStore.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.core
2 |
3 | import android.content.Context
4 | import androidx.datastore.core.DataStore
5 | import androidx.datastore.preferences.core.Preferences
6 | import androidx.datastore.preferences.core.booleanPreferencesKey
7 | import androidx.datastore.preferences.core.longPreferencesKey
8 | import androidx.datastore.preferences.core.stringPreferencesKey
9 | import androidx.datastore.preferences.preferencesDataStore
10 | import kotlinx.coroutines.Dispatchers
11 | import kotlinx.coroutines.flow.firstOrNull
12 | import kotlinx.coroutines.flow.map
13 | import kotlinx.coroutines.withContext
14 |
15 | val Context.dataStore: DataStore by preferencesDataStore(name = "config")
16 |
17 | object PrefKey {
18 | val CHECK_FOR_UPDATES = booleanPreferencesKey("check_for_updates")
19 | val LAST_UPDATE_CHECK = longPreferencesKey("last_update_check")
20 | val APP_LIBS_VERSION = stringPreferencesKey("app_libs_version")
21 | }
22 |
23 | val defaultValues = mapOf(
24 | Pair(PrefKey.CHECK_FOR_UPDATES, true),
25 | Pair(PrefKey.LAST_UPDATE_CHECK, 0L),
26 | Pair(PrefKey.APP_LIBS_VERSION, "")
27 | )
28 |
29 | suspend fun Context.getPrefValue(key: Preferences.Key<*>): Any? {
30 | return withContext(Dispatchers.IO) {
31 | val value = dataStore.data
32 | .map {
33 | it[key]
34 | }
35 | return@withContext value.firstOrNull() ?: defaultValues[key]
36 | }
37 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | android.nonFinalResIds=true
25 | # Breaks AboutLibraries, disabling it for now.
26 | # org.gradle.configuration-cache=true
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/patcher/PackageInstallerStatusReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.patcher
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.content.pm.PackageInstaller
7 | import kotlin.coroutines.Continuation
8 | import kotlin.coroutines.resume
9 | import kotlin.coroutines.suspendCoroutine
10 |
11 | class PackageInstallerStatusReceiver : BroadcastReceiver() {
12 | override fun onReceive(context: Context, intent: Intent) {
13 | val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)
14 | when (status) {
15 | PackageInstaller.STATUS_PENDING_USER_ACTION -> {
16 | val confirmationIntent = intent.getParcelableExtra(Intent.EXTRA_INTENT)
17 | if (confirmationIntent != null) {
18 | context.startActivity(confirmationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
19 | }
20 | }
21 | PackageInstaller.STATUS_SUCCESS -> {
22 | contList.forEach { it.resume(true) }
23 | contList.clear()
24 | }
25 | else -> {
26 | contList.forEach { it.resume(false) }
27 | contList.clear()
28 | }
29 | }
30 | }
31 |
32 | companion object {
33 | val contList: MutableList> = mutableListOf()
34 | suspend fun waitForInstallFinish(): Boolean {
35 | return suspendCoroutine { cont ->
36 | contList.add(cont)
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/core/GameChecker.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.core
2 |
3 | import android.content.pm.PackageInfo
4 | import android.content.pm.PackageManager
5 |
6 | object GameChecker {
7 | private val packageNames = arrayOf(
8 | "jp.co.cygames.umamusume",
9 | "com.komoe.kmumamusumegp",
10 | "com.komoe.umamusumeofficial",
11 | "com.kakaogames.umamusume"
12 | )
13 |
14 | var currentPackageName: String? = null
15 |
16 | fun init(pm: PackageManager) {
17 | // Defaults to whichever version is installed
18 | for (packageName in packageNames) {
19 | currentPackageName = packageName
20 | if (getPackageInfo(pm) != null) {
21 | return
22 | }
23 | }
24 | // Otherwise, the jp ver
25 | currentPackageName = packageNames[0]
26 | }
27 |
28 | fun getPackageInfo(pm: PackageManager): PackageInfo? {
29 | val packageName = currentPackageName ?: return null
30 | return try {
31 | pm.getPackageInfo(packageName, 0)
32 | } catch (e: PackageManager.NameNotFoundException) {
33 | null
34 | }
35 | }
36 |
37 | fun isPackageInstalled(pm: PackageManager): Boolean {
38 | return getPackageInfo(pm) != null
39 | }
40 |
41 | fun getAllPackageInfo(pm: PackageManager): Array {
42 | return Array(packageNames.size) {
43 | try {
44 | pm.getPackageInfo(packageNames[it], 0)
45 | } catch (e: PackageManager.NameNotFoundException) {
46 | null
47 | }
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
18 |
23 |
24 |
25 |
26 |
27 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/OpenSourceLicensesScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import androidx.compose.foundation.layout.fillMaxSize
4 | import androidx.compose.material3.MaterialTheme
5 | import androidx.compose.material3.Scaffold
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.ui.Modifier
8 | import androidx.compose.ui.res.stringResource
9 | import com.leadrdrk.umapatcher.R
10 | import com.leadrdrk.umapatcher.ui.component.BackButton
11 | import com.leadrdrk.umapatcher.ui.component.TopBar
12 | import com.mikepenz.aboutlibraries.ui.compose.LibrariesContainer
13 | import com.mikepenz.aboutlibraries.ui.compose.LibraryDefaults
14 | import com.ramcosta.composedestinations.annotation.Destination
15 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
16 |
17 | @Destination
18 | @Composable
19 | fun OpenSourceLicensesScreen(navigator: DestinationsNavigator) {
20 | Scaffold(
21 | topBar = {
22 | TopBar(
23 | title = stringResource(R.string.open_source_licenses),
24 | navigationIcon = { BackButton(navigator) }
25 | )
26 | }
27 | ) { contentPadding ->
28 | LibrariesContainer(
29 | modifier = Modifier
30 | .fillMaxSize(),
31 | contentPadding = contentPadding,
32 | colors = LibraryDefaults.libraryColors(
33 | backgroundColor = MaterialTheme.colorScheme.background,
34 | contentColor = MaterialTheme.colorScheme.onBackground,
35 | badgeBackgroundColor = MaterialTheme.colorScheme.primary,
36 | badgeContentColor = MaterialTheme.colorScheme.onPrimary,
37 | ),
38 | )
39 | }
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/patcher/PatcherCard.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.patcher
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.Row
6 | import androidx.compose.foundation.layout.RowScope
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxWidth
9 | import androidx.compose.foundation.layout.height
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.foundation.layout.width
12 | import androidx.compose.material3.ElevatedCard
13 | import androidx.compose.material3.MaterialTheme
14 | import androidx.compose.material3.Text
15 | import androidx.compose.runtime.Composable
16 | import androidx.compose.ui.Alignment
17 | import androidx.compose.ui.Modifier
18 | import androidx.compose.ui.unit.dp
19 |
20 | @Composable
21 | fun PatcherCard(
22 | label: String,
23 | rootRequired: Boolean = false,
24 | icon: @Composable () -> Unit,
25 | buttons: @Composable RowScope.() -> Unit,
26 | content: @Composable () -> Unit
27 | ) {
28 | ElevatedCard {
29 | Column(modifier = Modifier
30 | .fillMaxWidth()
31 | .padding(24.dp)
32 | ) {
33 | Row {
34 | icon()
35 | Spacer(Modifier.width(20.dp))
36 | Text(
37 | text = label,
38 | style = MaterialTheme.typography.titleMedium
39 | )
40 | }
41 | Spacer(Modifier.height(4.dp))
42 | content()
43 | Spacer(Modifier.height(4.dp))
44 | Row(
45 | modifier = Modifier.fillMaxWidth(),
46 | horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally),
47 | content = buttons
48 | )
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | -dontobfuscate
2 |
3 | -keep,allowoptimization class com.leadrdrk.** { *; }
4 |
5 | # I hate R8!!!
6 | -keep class androidx.compose.ui.res.** { *; }
7 | -keep class android.content.res.** { *; }
8 | -keep class com.android.apksig.** { *; }
9 | -keep class org.bouncycastle.jcajce.provider.** { *; }
10 | -keep class org.bouncycastle.jce.provider.** { *; }
11 |
12 | -dontwarn javax.naming.**
13 |
14 | ##---------------Begin: proguard configuration for Gson ----------
15 | # Gson uses generic type information stored in a class file when working with fields. Proguard
16 | # removes such information by default, so configure it to keep all of it.
17 | -keepattributes Signature
18 |
19 | # For using GSON @Expose annotation
20 | -keepattributes *Annotation*
21 |
22 | # Gson specific classes
23 | -dontwarn sun.misc.**
24 | #-keep class com.google.gson.stream.** { *; }
25 |
26 | # Application classes that will be serialized/deserialized over Gson
27 | -keep class com.google.gson.examples.android.model.** { ; }
28 |
29 | # Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
30 | # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
31 | -keep class * extends com.google.gson.TypeAdapter
32 | -keep class * implements com.google.gson.TypeAdapterFactory
33 | -keep class * implements com.google.gson.JsonSerializer
34 | -keep class * implements com.google.gson.JsonDeserializer
35 |
36 | # Prevent R8 from leaving Data object members always null
37 | -keepclassmembers,allowobfuscation class * {
38 | @com.google.gson.annotations.SerializedName ;
39 | }
40 |
41 | # Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
42 | -keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
43 | -keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken
44 |
45 | ##---------------End: proguard configuration for Gson ----------
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/patcher/RootUtils.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.patcher
2 |
3 | import android.content.Context
4 | import com.leadrdrk.umapatcher.core.GameChecker
5 | import com.topjohnwu.superuser.Shell
6 |
7 | object RootUtils {
8 | fun isRootOperationAllowed(context: Context): Boolean {
9 | return Shell.isAppGrantedRoot() == true && GameChecker.isPackageInstalled(context.packageManager)
10 | }
11 |
12 | fun testFile(path: String): Boolean {
13 | return Shell.cmd("test -f '$path'").exec().isSuccess
14 | }
15 |
16 | fun testDirectory(path: String): Boolean {
17 | return Shell.cmd("test -d '$path'").exec().isSuccess
18 | }
19 |
20 | fun createDirectory(path: String): Shell.Result {
21 | return Shell.cmd(
22 | "mkdir -p '$path'"
23 | ).exec()
24 | }
25 |
26 | fun removeDirectory(path: String): Shell.Result {
27 | return Shell.cmd(
28 | "rm -rf '$path'"
29 | ).exec()
30 | }
31 |
32 | fun moveFile(src: String, dest: String): Shell.Result {
33 | return Shell.cmd(
34 | "mv '$src' '$dest'"
35 | ).exec()
36 | }
37 |
38 | fun chmod(path: String, perm: String): Shell.Result {
39 | return Shell.cmd(
40 | "chmod $perm '$path'"
41 | ).exec()
42 | }
43 |
44 | fun chown(path: String, owner: String): Shell.Result {
45 | return Shell.cmd(
46 | "chown $owner '$path'"
47 | ).exec()
48 | }
49 |
50 | fun copyGameLibrary(src: String, dest: String): Shell.Result {
51 | return Shell.cmd(
52 | "cp '$src' '$dest'",
53 | "chown system:system '$dest'",
54 | "chmod 755 '$dest'"
55 | ).exec()
56 | }
57 |
58 | fun moveGameLibrary(src: String, dest: String): Shell.Result {
59 | return Shell.cmd(
60 | "mv '$src' '$dest'",
61 | "chown system:system '$dest'",
62 | "chmod 755 '$dest'"
63 | ).exec()
64 | }
65 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/core/UpdateChecker.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.core
2 |
3 | import android.content.Context
4 | import android.widget.Toast
5 | import androidx.datastore.preferences.core.edit
6 | import com.leadrdrk.umapatcher.BuildConfig
7 | import com.leadrdrk.umapatcher.R
8 | import com.leadrdrk.umapatcher.utils.showToast
9 | import kotlinx.coroutines.CoroutineScope
10 | import kotlinx.coroutines.Dispatchers
11 | import kotlinx.coroutines.launch
12 |
13 | object UpdateChecker {
14 | private const val CHECK_TIMEOUT = 300000 // 5 minutes
15 |
16 | private val releases = GitHubReleases("LeadRDRK/UmaPatcher")
17 | private const val currentTag = "v${BuildConfig.VERSION_NAME}"
18 | private val scope = CoroutineScope(Dispatchers.IO)
19 |
20 | private var running = false
21 | var callback: (String) -> Unit = {}
22 |
23 | fun init(context: Context) {
24 | scope.launch {
25 | if (context.getPrefValue(PrefKey.CHECK_FOR_UPDATES) as Boolean) {
26 | val lastUpdateCheck = context.getPrefValue(PrefKey.LAST_UPDATE_CHECK) as Long
27 | val currentTime = System.currentTimeMillis()
28 | if (currentTime - lastUpdateCheck < CHECK_TIMEOUT)
29 | return@launch
30 |
31 | context.dataStore.edit { preferences ->
32 | preferences[PrefKey.LAST_UPDATE_CHECK] = currentTime
33 | }
34 |
35 | try {
36 | running = true
37 | rawRun()
38 | }
39 | catch (_: Exception) {}
40 | running = false
41 | }
42 | }
43 | }
44 |
45 | fun run(context: Context? = null) {
46 | if (running) return
47 | running = true
48 |
49 | scope.launch {
50 | try {
51 | if (!rawRun()) {
52 | context?.showToast(
53 | context.getString(R.string.no_updates_available),
54 | Toast.LENGTH_SHORT
55 | )
56 | }
57 | }
58 | catch (_: Exception) {
59 | context?.showToast(
60 | context.getString(R.string.failed_to_check_for_updates),
61 | Toast.LENGTH_SHORT
62 | )
63 | }
64 | running = false
65 | }
66 | }
67 |
68 | private fun rawRun(): Boolean {
69 | val release = releases.fetchLatest()
70 | val tagName = release["tag_name"] as String
71 |
72 | return if (tagName != currentTag) {
73 | callback(tagName)
74 | true
75 | } else false
76 | }
77 |
78 | fun getReleaseUrl(tagName: String) = releases.getReleaseUrl(tagName)
79 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'com.google.devtools.ksp' version '1.9.20-1.0.14'
5 | id 'com.mikepenz.aboutlibraries.plugin'
6 | }
7 |
8 | android {
9 | compileSdk 34
10 |
11 | defaultConfig {
12 | applicationId "com.leadrdrk.umapatcher"
13 | minSdk 24
14 | targetSdk 34
15 | versionCode 7
16 | versionName "1.0.1"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | shrinkResources true
22 | minifyEnabled true
23 | proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 | buildFeatures {
34 | compose true
35 | buildConfig true
36 | }
37 | composeOptions {
38 | kotlinCompilerExtensionVersion compose_version
39 | }
40 | packagingOptions {
41 | resources {
42 | excludes += "META-INF/*"
43 | }
44 | }
45 | namespace 'com.leadrdrk.umapatcher'
46 | }
47 |
48 | kotlin {
49 | jvmToolchain(8)
50 | }
51 |
52 | aboutLibraries {
53 | configPath = "config"
54 | }
55 |
56 | dependencies {
57 | implementation 'androidx.core:core-ktx:1.12.0'
58 | implementation "androidx.compose.ui:ui:$compose_version"
59 | implementation 'androidx.compose.material3:material3:1.1.2'
60 | implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
61 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2'
62 | implementation 'androidx.activity:activity-compose:1.8.2'
63 | implementation 'androidx.navigation:navigation-compose:2.7.6'
64 | implementation 'androidx.datastore:datastore-preferences:1.0.0'
65 | implementation 'androidx.documentfile:documentfile:1.0.1'
66 | implementation 'io.github.raamcosta.compose-destinations:animations-core:1.9.55'
67 | ksp 'io.github.raamcosta.compose-destinations:ksp:1.9.55'
68 | implementation 'com.mikepenz:aboutlibraries-core:10.9.2'
69 | implementation 'com.mikepenz:aboutlibraries-compose:10.9.2'
70 | implementation 'com.google.code.gson:gson:2.10.1'
71 | implementation 'com.github.topjohnwu.libsu:core:5.2.2'
72 | implementation 'net.lingala.zip4j:zip4j:2.11.5'
73 | implementation 'com.android.tools.build:apksig:8.2.2'
74 | implementation 'org.bouncycastle:bcpkix-jdk18on:1.77'
75 | implementation 'io.github.reandroid:ARSCLib:1.2.4'
76 |
77 | debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
78 | debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
79 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/component/SimpleDialog.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.component
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.ColumnScope
6 | import androidx.compose.foundation.layout.Row
7 | import androidx.compose.foundation.layout.RowScope
8 | import androidx.compose.foundation.layout.Spacer
9 | import androidx.compose.foundation.layout.fillMaxWidth
10 | import androidx.compose.foundation.layout.height
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.foundation.shape.RoundedCornerShape
13 | import androidx.compose.material3.Card
14 | import androidx.compose.material3.MaterialTheme
15 | import androidx.compose.material3.Text
16 | import androidx.compose.material3.TextButton
17 | import androidx.compose.runtime.Composable
18 | import androidx.compose.ui.Modifier
19 | import androidx.compose.ui.res.stringResource
20 | import androidx.compose.ui.unit.dp
21 | import androidx.compose.ui.window.Dialog
22 | import com.leadrdrk.umapatcher.R
23 |
24 | @Composable
25 | fun SimpleDialog(
26 | title: String,
27 | onDismissRequest: () -> Unit,
28 | buttons: @Composable RowScope.() -> Unit,
29 | content: @Composable ColumnScope.() -> Unit
30 | ) {
31 | Dialog(
32 | onDismissRequest = onDismissRequest
33 | ) {
34 | Card(
35 | modifier = Modifier
36 | .fillMaxWidth(),
37 | shape = RoundedCornerShape(16.dp),
38 | ) {
39 | Column(
40 | modifier = Modifier
41 | .padding(16.dp)
42 | ) {
43 | Text(
44 | text = title,
45 | style = MaterialTheme.typography.titleLarge
46 | )
47 | Spacer(Modifier.height(8.dp))
48 | content()
49 | Spacer(Modifier.height(8.dp))
50 | Row(
51 | modifier = Modifier
52 | .fillMaxWidth(),
53 | horizontalArrangement = Arrangement.End,
54 | content = buttons
55 | )
56 | }
57 | }
58 | }
59 | }
60 |
61 | @Composable
62 | fun SimpleOkCancelDialog(
63 | title: String,
64 | onClose: (Boolean) -> Unit,
65 | content: @Composable ColumnScope.() -> Unit
66 | ) {
67 | SimpleDialog(
68 | title = title,
69 | onDismissRequest = { onClose(false) },
70 | buttons = {
71 | TextButton(
72 | onClick = { onClose(false) }
73 | ) {
74 | Text(stringResource(R.string.cancel))
75 | }
76 | TextButton(
77 | onClick = { onClose(true) }
78 | ) {
79 | Text(stringResource(R.string.ok))
80 | }
81 | },
82 | content = content
83 | )
84 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val md_theme_light_primary = Color(0xFF3E6A00)
6 | val md_theme_light_onPrimary = Color(0xFFFFFFFF)
7 | val md_theme_light_primaryContainer = Color(0xFFA7F945)
8 | val md_theme_light_onPrimaryContainer = Color(0xFF0F2000)
9 | val md_theme_light_secondary = Color(0xFF57624A)
10 | val md_theme_light_onSecondary = Color(0xFFFFFFFF)
11 | val md_theme_light_secondaryContainer = Color(0xFFDBE7C8)
12 | val md_theme_light_onSecondaryContainer = Color(0xFF151E0B)
13 | val md_theme_light_tertiary = Color(0xFF386663)
14 | val md_theme_light_onTertiary = Color(0xFFFFFFFF)
15 | val md_theme_light_tertiaryContainer = Color(0xFFBBECE8)
16 | val md_theme_light_onTertiaryContainer = Color(0xFF00201E)
17 | val md_theme_light_error = Color(0xFFBA1A1A)
18 | val md_theme_light_errorContainer = Color(0xFFFFDAD6)
19 | val md_theme_light_onError = Color(0xFFFFFFFF)
20 | val md_theme_light_onErrorContainer = Color(0xFF410002)
21 | val md_theme_light_background = Color(0xFFFDFCF5)
22 | val md_theme_light_onBackground = Color(0xFF1B1C18)
23 | val md_theme_light_surface = Color(0xFFFDFCF5)
24 | val md_theme_light_onSurface = Color(0xFF1B1C18)
25 | val md_theme_light_surfaceVariant = Color(0xFFE1E4D5)
26 | val md_theme_light_onSurfaceVariant = Color(0xFF44483D)
27 | val md_theme_light_outline = Color(0xFF75796C)
28 | val md_theme_light_inverseOnSurface = Color(0xFFF2F1E9)
29 | val md_theme_light_inverseSurface = Color(0xFF30312C)
30 | val md_theme_light_inversePrimary = Color(0xFF8CDC26)
31 | val md_theme_light_surfaceTint = Color(0xFF3E6A00)
32 | val md_theme_light_outlineVariant = Color(0xFFC5C8BA)
33 | val md_theme_light_scrim = Color(0xFF000000)
34 |
35 | val md_theme_dark_primary = Color(0xFF8CDC26)
36 | val md_theme_dark_onPrimary = Color(0xFF1E3700)
37 | val md_theme_dark_primaryContainer = Color(0xFF2D5000)
38 | val md_theme_dark_onPrimaryContainer = Color(0xFFA7F945)
39 | val md_theme_dark_secondary = Color(0xFFBFCBAD)
40 | val md_theme_dark_onSecondary = Color(0xFF2A331E)
41 | val md_theme_dark_secondaryContainer = Color(0xFF404A33)
42 | val md_theme_dark_onSecondaryContainer = Color(0xFFDBE7C8)
43 | val md_theme_dark_tertiary = Color(0xFFA0CFCC)
44 | val md_theme_dark_onTertiary = Color(0xFF003735)
45 | val md_theme_dark_tertiaryContainer = Color(0xFF1F4E4B)
46 | val md_theme_dark_onTertiaryContainer = Color(0xFFBBECE8)
47 | val md_theme_dark_error = Color(0xFFFFB4AB)
48 | val md_theme_dark_errorContainer = Color(0xFF93000A)
49 | val md_theme_dark_onError = Color(0xFF690005)
50 | val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
51 | val md_theme_dark_background = Color(0xFF1B1C18)
52 | val md_theme_dark_onBackground = Color(0xFFE3E3DB)
53 | val md_theme_dark_surface = Color(0xFF1B1C18)
54 | val md_theme_dark_onSurface = Color(0xFFE3E3DB)
55 | val md_theme_dark_surfaceVariant = Color(0xFF44483D)
56 | val md_theme_dark_onSurfaceVariant = Color(0xFFC5C8BA)
57 | val md_theme_dark_outline = Color(0xFF8E9285)
58 | val md_theme_dark_inverseOnSurface = Color(0xFF1B1C18)
59 | val md_theme_dark_inverseSurface = Color(0xFFE3E3DB)
60 | val md_theme_dark_inversePrimary = Color(0xFF3E6A00)
61 | val md_theme_dark_surfaceTint = Color(0xFF8CDC26)
62 | val md_theme_dark_outlineVariant = Color(0xFF44483D)
63 | val md_theme_dark_scrim = Color(0xFF000000)
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/patcher/ApkSigner.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.patcher
2 |
3 | import com.android.apksig.ApkSigner
4 | import org.bouncycastle.asn1.x500.X500Name
5 | import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
6 | import org.bouncycastle.cert.X509v3CertificateBuilder
7 | import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
8 | import org.bouncycastle.jce.provider.BouncyCastleProvider
9 | import org.bouncycastle.operator.ContentSigner
10 | import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
11 | import java.io.File
12 | import java.io.FileInputStream
13 | import java.io.FileOutputStream
14 | import java.math.BigInteger
15 | import java.security.KeyPairGenerator
16 | import java.security.KeyStore
17 | import java.security.PrivateKey
18 | import java.security.SecureRandom
19 | import java.security.Security
20 | import java.security.cert.X509Certificate
21 | import java.util.Date
22 | import java.util.Locale
23 |
24 | internal class ApkSigner(
25 | private val cn: String, password: String
26 | ) {
27 | private val passwordCharArray = password.toCharArray()
28 | private fun newKeystore(out: File) {
29 | val (publicKey, privateKey) = createKey()
30 | val privateKS = KeyStore.getInstance("BKS", "BC")
31 | privateKS.load(null, passwordCharArray)
32 | privateKS.setKeyEntry("alias", privateKey, passwordCharArray, arrayOf(publicKey))
33 | privateKS.store(FileOutputStream(out), passwordCharArray)
34 | }
35 |
36 | private fun createKey(): Pair {
37 | val gen = KeyPairGenerator.getInstance("RSA")
38 | gen.initialize(2048)
39 | val pair = gen.generateKeyPair()
40 | var serialNumber: BigInteger
41 | do serialNumber =
42 | BigInteger.valueOf(SecureRandom().nextLong()) while (serialNumber < BigInteger.ZERO)
43 | val x500Name = X500Name("CN=$cn")
44 | val builder = X509v3CertificateBuilder(
45 | x500Name,
46 | serialNumber,
47 | Date(System.currentTimeMillis() - 1000L * 60L * 60L * 24L * 30L),
48 | Date(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * 366L * 30L),
49 | Locale.ENGLISH,
50 | x500Name,
51 | SubjectPublicKeyInfo.getInstance(pair.public.encoded)
52 | )
53 | val signer: ContentSigner = JcaContentSignerBuilder("SHA256withRSA").build(pair.private)
54 | return JcaX509CertificateConverter().getCertificate(builder.build(signer)) to pair.private
55 | }
56 |
57 | fun signApk(input: File, output: File, ks: File) {
58 | Security.addProvider(BouncyCastleProvider())
59 |
60 | if (!ks.exists()) newKeystore(ks)
61 |
62 | val keyStore = KeyStore.getInstance("BKS", "BC")
63 | FileInputStream(ks).use { fis -> keyStore.load(fis, null) }
64 | val alias = keyStore.aliases().nextElement()
65 |
66 | val config = ApkSigner.SignerConfig.Builder(
67 | cn,
68 | keyStore.getKey(alias, passwordCharArray) as PrivateKey,
69 | listOf(keyStore.getCertificate(alias) as X509Certificate)
70 | ).build()
71 |
72 | val signer = ApkSigner.Builder(listOf(config))
73 | signer.setCreatedBy(cn)
74 | signer.setInputApk(input)
75 | signer.setOutputApk(output)
76 |
77 | signer.build().sign()
78 | }
79 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/zip/MappedZipFileExtractor.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.zip
2 |
3 | import android.os.Build
4 | import android.util.Log
5 | import androidx.annotation.RequiresApi
6 | import net.lingala.zip4j.ZipFile
7 | import net.lingala.zip4j.io.inputstream.ZipInputStream
8 | import net.lingala.zip4j.model.FileHeader
9 | import net.lingala.zip4j.model.LocalFileHeader
10 | import java.io.File
11 | import java.io.IOException
12 | import java.io.InputStream
13 | import java.nio.ByteBuffer
14 | import java.nio.channels.FileChannel
15 | import java.nio.channels.FileChannel.MapMode
16 | import kotlin.math.min
17 |
18 |
19 | @RequiresApi(Build.VERSION_CODES.O)
20 | class MappedZipFileExtractor(
21 | file: File
22 | ): ZipExtractor(file) {
23 | // Peek total uncompressed size with normal ZipFile
24 | override val fileHeaders: List = ZipFile(file).use { it.fileHeaders }
25 | private val totalSize = run {
26 | var value = 0L
27 | fileHeaders.forEach { value += it.uncompressedSize }
28 | value.toFloat()
29 | }
30 | private val fileChannel = FileChannel.open(file.toPath())
31 | private val buffer = fileChannel.map(MapMode.READ_ONLY, 0, fileChannel.size())
32 | private val inputStream = ByteBufferInputStream(buffer)
33 | private val zip = ZipInputStream(inputStream)
34 |
35 | override suspend fun extractAll(dir: File, progressCallback: (Float) -> Unit) {
36 | var localFileHeader: LocalFileHeader?
37 | var readLen: Int
38 | val readBuffer = ByteArray(524288)
39 | var totalReadLen = 0L
40 | while ((zip.nextEntry.also { localFileHeader = it }) != null) {
41 | val extractedFile = dir.resolve(localFileHeader!!.fileName)
42 | val areRelated =
43 | extractedFile.canonicalPath.startsWith(dir.canonicalPath + File.separator)
44 | if (!areRelated) {
45 | Log.w("UmaPatcher", "File path sanitized: $extractedFile")
46 | continue
47 | }
48 | val extractDir = extractedFile.parentFile!!
49 | if (!extractDir.exists()) extractDir.mkdirs()
50 |
51 | extractedFile.outputStream().use { output ->
52 | while (zip.read(readBuffer).also { readLen = it } != -1) {
53 | output.write(readBuffer, 0, readLen)
54 | totalReadLen += readLen
55 | progressCallback(totalReadLen / totalSize)
56 | }
57 | }
58 | }
59 | }
60 |
61 | override fun close() {
62 | zip.close()
63 | inputStream.close()
64 | fileChannel.close()
65 | }
66 |
67 | class ByteBufferInputStream(private val buf: ByteBuffer) : InputStream() {
68 | @Throws(IOException::class)
69 | override fun read(): Int {
70 | if (!buf.hasRemaining()) {
71 | return -1
72 | }
73 | return buf.get().toInt() and 0xFF
74 | }
75 |
76 | @Throws(IOException::class)
77 | override fun read(bytes: ByteArray, off: Int, length: Int): Int {
78 | var len = length
79 | if (!buf.hasRemaining()) {
80 | return -1
81 | }
82 |
83 | len = min(len.toDouble(), buf.remaining().toDouble()).toInt()
84 | buf[bytes, off, len]
85 | return len
86 | }
87 | }
88 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
14 |
21 |
28 |
34 |
35 |
41 |
42 |
43 |
44 |
45 |
46 |
53 |
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/patcher/Patcher.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.patcher
2 |
3 | import android.content.Context
4 | import android.util.Log
5 | import com.leadrdrk.umapatcher.R
6 | import com.leadrdrk.umapatcher.core.GameChecker
7 | import com.leadrdrk.umapatcher.utils.copyTo
8 | import com.topjohnwu.superuser.Shell
9 | import java.io.File
10 | import java.io.InputStream
11 | import java.io.OutputStream
12 | import java.io.PrintWriter
13 | import java.io.StringWriter
14 | import kotlin.coroutines.resume
15 | import kotlin.coroutines.suspendCoroutine
16 |
17 | abstract class Patcher(
18 | private var onLog: (String) -> Unit = {},
19 | private var onProgress: (Float) -> Unit = {},
20 | private var onTask: (String) -> Unit = {},
21 | private var onSaveFile: (String, File, (Boolean) -> Unit) -> Unit = { _: String, _: File, _: (Boolean) -> Unit -> }
22 | ) {
23 | var progress: Float = 0f
24 | set(value) {
25 | field = value
26 | onProgress(value)
27 | }
28 |
29 | var task: String = ""
30 | set(value) {
31 | if (field == value) return
32 | field = value
33 | onTask(value)
34 | }
35 |
36 | fun setCallbacks(
37 | onLog: (String) -> Unit = {},
38 | onProgress: (Float) -> Unit = {},
39 | onTask: (String) -> Unit = {},
40 | onSaveFile: (String, File, (Boolean) -> Unit) -> Unit
41 | ) {
42 | this.onLog = onLog
43 | this.onProgress = onProgress
44 | this.onTask = onTask
45 | this.onSaveFile = onSaveFile
46 | }
47 |
48 | abstract fun run(context: Context): Boolean
49 |
50 | fun safeRun(context: Context): Boolean {
51 | return try {
52 | run(context)
53 | } catch (ex: Exception) {
54 | logException(ex)
55 | false
56 | }
57 | }
58 |
59 | protected fun log(line: String) {
60 | onLog(line)
61 | }
62 |
63 | protected fun logAll(lines: Iterable) {
64 | lines.forEach(onLog)
65 | }
66 |
67 | protected fun logException(ex: Exception) {
68 | val sw = StringWriter()
69 | PrintWriter(sw).use {
70 | ex.printStackTrace(it)
71 | }
72 | log(sw.toString())
73 | Log.e("UmaPatcher", "logException", ex)
74 | }
75 |
76 | protected suspend fun saveFile(filename: String, file: File): Boolean {
77 | return suspendCoroutine { cont ->
78 | onSaveFile(filename, file) { cont.resume(it) }
79 | }
80 | }
81 |
82 | protected fun copyFileProgress(srcFile: File, dstFile: File) {
83 | srcFile.inputStream().use { input ->
84 | dstFile.outputStream().use { output ->
85 | copyStreamProgress(input, output, srcFile.length())
86 | }
87 | }
88 | }
89 |
90 | protected fun copyStreamProgress(input: InputStream, output: OutputStream, length: Long) {
91 | val lengthFloat = length.toFloat()
92 | input.copyTo(output) { current ->
93 | progress = current / lengthFloat
94 | }
95 | }
96 |
97 | protected fun isDirectInstallAllowed(context: Context): Boolean {
98 | if (!GameChecker.isPackageInstalled(context.packageManager)) {
99 | log(context.getString(R.string.direct_install_unavailable))
100 | return false
101 | }
102 | if (Shell.isAppGrantedRoot() != true) {
103 | log(context.getString(R.string.root_required))
104 | return false
105 | }
106 | return true
107 | }
108 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/utils/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.utils
2 |
3 | import androidx.lifecycle.Lifecycle
4 | import androidx.lifecycle.LifecycleOwner
5 | import com.google.gson.Gson
6 | import java.io.ByteArrayOutputStream
7 | import java.io.File
8 | import java.io.IOException
9 | import java.io.InputStream
10 | import java.io.OutputStream
11 | import java.net.HttpURLConnection
12 | import java.net.URL
13 | import java.security.MessageDigest
14 |
15 | fun safeNavigate(lifecycleOwner: LifecycleOwner, callback: () -> Unit) {
16 | val currentState = lifecycleOwner.lifecycle.currentState
17 | if (currentState.isAtLeast(Lifecycle.State.RESUMED)) {
18 | callback()
19 | }
20 | }
21 |
22 | fun deleteRecursive(fileOrDirectory: File, deleteRoot: Boolean = true) {
23 | if (fileOrDirectory.isDirectory)
24 | for (child in fileOrDirectory.listFiles()!!)
25 | deleteRecursive(child)
26 |
27 | if (deleteRoot) fileOrDirectory.delete()
28 | }
29 |
30 | fun downloadFileAndDigestSHA1(url: URL, outputFile: File, onProgress: (Float) -> Unit): ByteArray {
31 | val conn = url.openConnection() as HttpURLConnection
32 | conn.doInput = true
33 | conn.instanceFollowRedirects = true
34 | conn.connect()
35 |
36 | if (conn.responseCode != 200) throw IOException()
37 | val contentLength = conn.contentLengthLong
38 |
39 | val sha1 = MessageDigest.getInstance("SHA-1")
40 | conn.inputStream.use { input ->
41 | outputFile.outputStream().use { output ->
42 | val dataBuffer = ByteArray(1024)
43 | var totalBytesRead = 0L
44 | var bytesRead: Int
45 | while (input.read(dataBuffer, 0, 1024).also { bytesRead = it } != -1) {
46 | output.write(dataBuffer, 0, bytesRead)
47 | sha1.update(dataBuffer, 0, bytesRead)
48 |
49 | totalBytesRead += bytesRead
50 | if (contentLength != -1L) {
51 | onProgress(totalBytesRead.toFloat() / contentLength)
52 | }
53 | }
54 | }
55 | }
56 |
57 | return sha1.digest()
58 | }
59 |
60 | private val gson = Gson()
61 | fun fetchJson(url: URL, accept: String = "application/json"): HashMap<*, *> {
62 | val conn = url.openConnection() as HttpURLConnection
63 | conn.setRequestProperty("Accept", accept)
64 | conn.doInput = true
65 | conn.instanceFollowRedirects = true
66 | conn.connect()
67 |
68 | if (conn.responseCode != 200) throw IOException()
69 |
70 | val body = conn.inputStream.use { input ->
71 | val result = ByteArrayOutputStream()
72 | val buffer = ByteArray(1024)
73 |
74 | var length: Int
75 | while (input.read(buffer).also { length = it } != -1) {
76 | result.write(buffer, 0, length)
77 | }
78 | result.toString("UTF-8")
79 | }
80 |
81 | return gson.fromJson(body, HashMap::class.java)
82 | }
83 |
84 | private val HEX_ARRAY = "0123456789abcdef".toCharArray()
85 | fun bytesToHex(bytes: ByteArray): String {
86 | val hexChars = CharArray(bytes.size * 2)
87 | for (j in bytes.indices) {
88 | val v = bytes[j].toInt() and 0xFF
89 | hexChars[j * 2] = HEX_ARRAY[v ushr 4]
90 | hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F]
91 | }
92 | return String(hexChars)
93 | }
94 |
95 | fun InputStream.copyTo(out: OutputStream, onProgress: (currentBytes: Int) -> Unit) {
96 | val buffer = ByteArray(524288) // 512KiB
97 | var lengthRead: Int
98 | var currentBytes = 0
99 | while (read(buffer).also { lengthRead = it } > 0) {
100 | out.write(buffer, 0, lengthRead)
101 | currentBytes += lengthRead
102 | onProgress(currentBytes)
103 | }
104 | out.flush()
105 | }
--------------------------------------------------------------------------------
/app/src/main/res/values-zh-rCN/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 主页
4 | 设置
5 | 关于
6 | 游戏已安装
7 | 游戏未安装
8 | 某些功能可能不可用。
9 | "包名:"
10 | "版本:"
11 | 点击此处选择其他应用
12 | 应用补丁
13 | 开始补丁
14 | 选择一个应用
15 | 已选择 %d 个文件
16 | 点击此处选择文件
17 | 支持的文件:APK / 拆分的 APK,XAPK
18 | 应用启动时偶尔检查更新。
19 | 导出签名密钥
20 | 导出用于签署 APK 文件的 BKS 密钥库。
21 | 导入签名密钥
22 | 导入用于签署 APK 文件的 BKS 密钥库。
23 | 没有可导出的密钥库。
24 | 密钥库已导入。
25 | 密钥库导入失败。
26 | 强制重新下载 Hachimi
27 | 使现有库失效并强制重新下载。
28 | Hachimi 将在下次应用补丁时重新下载。
29 | 某赛马拟人化游戏的安卓插件 Hachimi 补丁工具。
30 | 检查更新
31 | 开源许可
32 | 查看源代码
33 | 在 Ko-fi 支持我
34 | 安装方式
35 | 你希望如何安装补丁。
36 | 直接安装(需要 root)
37 | 保存已补丁的文件
38 | 普通安装
39 | 处理中...
40 | 已完成
41 | [补丁成功]
42 | [补丁失败]
43 | 仅当游戏已安装时才能使用直接安装。
44 | 此操作需要 Root 权限。
45 | 读取文件失败:%s
46 | 移动文件失败:%s
47 | 正在复制文件
48 | 正在复制文件:%s
49 | 正在打补丁
50 | 正在安装
51 | 安装完成。
52 | 安装失败。
53 | 文件已保存。
54 | 保存文件失败。
55 | 正在解压文件:%s
56 | 正在创建文件:%s
57 | 正在清理
58 | 正在同步 Hachimi 库
59 | 正在下载文件:%s
60 | 下载 Hachimi 库失败。
61 | 同步 Hachimi 库失败,已跳过。
62 | Hachimi 已更新。
63 | 正在使用 Hachimi %s
64 | 检测到文件损坏,正在中止下载。
65 | 正在签名 APK 文件:%s
66 | APK 文件无效或不完整(缺少本地库)
67 | 未找到应用库目录。未安装任何内容。
68 | 无效的 APK 文件。
69 | 无效的 APK 文件:%s
70 | 检测到 APK 拆分类型:%s
71 | 已补丁库:%s
72 | 无效的拆分 APK;发现了另一个 %s APK。
73 | 拆分 APK 中缺少 Base APK。
74 | 无效的拆分 APK。在一个文件中检测到多种类型。
75 | 检测到 XAPK 文件。
76 | 检测到普通 APK 文件。
77 | 作为拆分 APK 补丁。
78 | 准备应用
79 | 正在移除旧文件
80 | 取消
81 | 确定
82 | 有可用更新
83 | 有新版本可用:%s\n要打开下载页面吗?
84 | 检查更新失败
85 | 没有可用更新
86 |
87 |
--------------------------------------------------------------------------------
/app/src/main/res/values-b+zh+Hant/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 主頁
4 | 設定
5 | 關於
6 | 遊戲已安裝
7 | 遊戲未安裝
8 | 某些功能可能無法使用。
9 | 軟體包名:
10 | 版本:
11 | 點擊此處選擇其他程式
12 | 已選擇 %d 個檔案
13 | 點擊這裡選擇檔案
14 | 選擇安裝補丁的方式。
15 | 直接安裝(需要root)
16 | 儲存已修改的檔案
17 | 一般安裝
18 | 處理中...
19 | 已完成
20 | 檢查更新
21 | 開源許可
22 | 查看源碼
23 | 在 Ko-fi 資助我
24 | 安裝方式
25 | 作為拆分 APK 修改。
26 | 正在準備應用程式
27 | 正在刪除舊檔案
28 | 取消
29 | 確定
30 | 有可用更新
31 | 有新版本可用:%s[...]
32 | 檢查更新失敗
33 | 沒有可用更新
34 | 正在修改
35 | 正在安裝
36 | 安裝完成。
37 | 未能移動檔案:%s
38 | 正在複製檔案
39 | 正在複製檔案:%s
40 | [修改成功]
41 | [修改失敗]
42 | 安裝失敗。
43 | 直接安裝只能在遊戲已安裝時使用。
44 | 修改應用程式
45 | 開始修改
46 | 選擇一個應用程式
47 | 檔案已儲存。
48 | 未能儲存檔案。
49 | 此操作需要 Root 權限。
50 | Hachimi 將在下次套用補丁時重新下載。
51 | 某賽馬擬人化遊戲的 Android 插件 Hachimi 修改工具。
52 | 未找到應用庫目錄。未安裝任何內容。
53 | 無效的 APK 檔案
54 | 無效的 APK 檔案:%s
55 | 偵測到 APK 拆分類型:%s
56 | 未能讀取檔案:%s
57 | 正在解壓縮檔案:%s
58 | 正在建立檔案:%s
59 | 正在清理
60 | 正在同步 Hachimi 程式庫
61 | 正在下載檔案:%s
62 | 未能同步 Hachimi 程式庫,已跳過。
63 | Hachimi 已更新。
64 | 正在使用 Hachimi %s
65 | 發現檔案損壞,正在停止下載。
66 | 支持的檔案格式:APK / 拆分APK、XAPK
67 | 啟動時偶爾檢查更新。
68 | 無效的拆分 APK。同一個檔案中檢測到多種類型。
69 | 檢測到 XAPK 檔案。
70 | 未能匯入密鑰庫。
71 | 強制重新下載 Hachimi
72 | 匯出簽署密鑰
73 | 匯出用於簽署 APK 檔案的 BKS 密鑰庫。
74 | 偵測到一般 APK 檔案。
75 | 已修改的程式庫:%s
76 | 未能下載 Hachimi 程式庫。
77 | 正在簽署 APK 檔案:%s
78 | 匯入簽署密鑰
79 | 匯入用於簽署 APK 檔案的 BKS 密鑰庫。
80 | 沒有可匯出的密鑰庫。
81 | 已匯入密鑰庫。
82 | 使現有程式庫無效化並強制重新下載。
83 | APK 檔案無效或不完整(缺少本地程式庫)
84 | 無效的拆分 APK:偵測到另一個 %s APK。
85 | 拆分 APK 中缺少 Base APK。
86 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/AppSelectScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Row
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.height
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.layout.size
11 | import androidx.compose.foundation.layout.width
12 | import androidx.compose.foundation.rememberScrollState
13 | import androidx.compose.foundation.verticalScroll
14 | import androidx.compose.material3.Divider
15 | import androidx.compose.material3.MaterialTheme
16 | import androidx.compose.material3.Scaffold
17 | import androidx.compose.material3.Text
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.ui.Alignment
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.graphics.ImageBitmap
22 | import androidx.compose.ui.graphics.asImageBitmap
23 | import androidx.compose.ui.platform.LocalContext
24 | import androidx.compose.ui.platform.LocalLifecycleOwner
25 | import androidx.compose.ui.res.stringResource
26 | import androidx.compose.ui.unit.dp
27 | import androidx.core.graphics.drawable.toBitmap
28 | import com.leadrdrk.umapatcher.R
29 | import com.leadrdrk.umapatcher.core.GameChecker
30 | import com.leadrdrk.umapatcher.ui.component.BackButton
31 | import com.leadrdrk.umapatcher.ui.component.TopBar
32 | import com.leadrdrk.umapatcher.utils.safeNavigate
33 | import com.ramcosta.composedestinations.annotation.Destination
34 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
35 |
36 | @Destination
37 | @Composable
38 | fun AppSelectScreen(navigator: DestinationsNavigator) {
39 | val context = LocalContext.current
40 | val pm = context.packageManager
41 | val lifecycleOwner = LocalLifecycleOwner.current
42 |
43 | Scaffold(
44 | topBar = {
45 | TopBar(
46 | title = stringResource(R.string.select_an_app),
47 | navigationIcon = { BackButton(navigator) }
48 | )
49 | }
50 | ) { innerPadding ->
51 | Column(
52 | modifier = Modifier
53 | .padding(innerPadding)
54 | .verticalScroll(rememberScrollState())
55 | ) {
56 | for (packageInfo in GameChecker.getAllPackageInfo(pm)) {
57 | if (packageInfo == null) continue
58 |
59 | val appInfo = pm.getApplicationInfo(packageInfo.packageName, 0)
60 | AppEntry(
61 | appName = pm.getApplicationLabel(appInfo).toString(),
62 | packageName = packageInfo.packageName,
63 | version = packageInfo.versionName,
64 | icon = appInfo.loadIcon(pm).toBitmap().asImageBitmap(),
65 | onClick = {
66 | GameChecker.currentPackageName = packageInfo.packageName
67 | safeNavigate(lifecycleOwner) {
68 | navigator.popBackStack()
69 | }
70 | }
71 | )
72 | }
73 | }
74 | }
75 | }
76 |
77 | @Composable
78 | fun AppEntry(
79 | appName: String,
80 | packageName: String,
81 | version: String,
82 | icon: ImageBitmap,
83 | onClick: () -> Unit
84 | ) {
85 | Column(
86 | modifier = Modifier
87 | .clickable(onClick = onClick)
88 | ) {
89 | Row(
90 | modifier = Modifier
91 | .padding(all = 16.dp),
92 | verticalAlignment = Alignment.CenterVertically
93 | ) {
94 | Image(
95 | bitmap = icon,
96 | contentDescription = null,
97 | modifier = Modifier
98 | .size(48.dp)
99 | )
100 | Spacer(Modifier.width(16.dp))
101 | Column(
102 | modifier = Modifier
103 | .weight(1f)
104 | ) {
105 | Text(
106 | text = appName,
107 | style = MaterialTheme.typography.bodyLarge
108 | )
109 | Spacer(Modifier.height(4.dp))
110 | Text(
111 | text = stringResource(R.string.package_name_prefix) + packageName,
112 | style = MaterialTheme.typography.bodyMedium,
113 | color = MaterialTheme.colorScheme.onSurfaceVariant
114 | )
115 | Spacer(Modifier.height(4.dp))
116 | Text(
117 | text = stringResource(R.string.version_name_prefix) + version,
118 | style = MaterialTheme.typography.bodyMedium,
119 | color = MaterialTheme.colorScheme.onSurfaceVariant
120 | )
121 | }
122 | }
123 | Divider()
124 | }
125 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = md_theme_dark_primary,
20 | onPrimary = md_theme_dark_onPrimary,
21 | primaryContainer = md_theme_dark_primaryContainer,
22 | onPrimaryContainer = md_theme_dark_onPrimaryContainer,
23 | secondary = md_theme_dark_secondary,
24 | onSecondary = md_theme_dark_onSecondary,
25 | secondaryContainer = md_theme_dark_secondaryContainer,
26 | onSecondaryContainer = md_theme_dark_onSecondaryContainer,
27 | tertiary = md_theme_dark_tertiary,
28 | onTertiary = md_theme_dark_onTertiary,
29 | tertiaryContainer = md_theme_dark_tertiaryContainer,
30 | onTertiaryContainer = md_theme_dark_onTertiaryContainer,
31 | error = md_theme_dark_error,
32 | errorContainer = md_theme_dark_errorContainer,
33 | onError = md_theme_dark_onError,
34 | onErrorContainer = md_theme_dark_onErrorContainer,
35 | background = md_theme_dark_background,
36 | onBackground = md_theme_dark_onBackground,
37 | surface = md_theme_dark_surface,
38 | onSurface = md_theme_dark_onSurface,
39 | surfaceVariant = md_theme_dark_surfaceVariant,
40 | onSurfaceVariant = md_theme_dark_onSurfaceVariant,
41 | outline = md_theme_dark_outline,
42 | inverseOnSurface = md_theme_dark_inverseOnSurface,
43 | inverseSurface = md_theme_dark_inverseSurface,
44 | inversePrimary = md_theme_dark_inversePrimary,
45 | surfaceTint = md_theme_dark_surfaceTint,
46 | outlineVariant = md_theme_dark_outlineVariant,
47 | scrim = md_theme_dark_scrim,
48 | )
49 |
50 | private val LightColorScheme = lightColorScheme(
51 | primary = md_theme_light_primary,
52 | onPrimary = md_theme_light_onPrimary,
53 | primaryContainer = md_theme_light_primaryContainer,
54 | onPrimaryContainer = md_theme_light_onPrimaryContainer,
55 | secondary = md_theme_light_secondary,
56 | onSecondary = md_theme_light_onSecondary,
57 | secondaryContainer = md_theme_light_secondaryContainer,
58 | onSecondaryContainer = md_theme_light_onSecondaryContainer,
59 | tertiary = md_theme_light_tertiary,
60 | onTertiary = md_theme_light_onTertiary,
61 | tertiaryContainer = md_theme_light_tertiaryContainer,
62 | onTertiaryContainer = md_theme_light_onTertiaryContainer,
63 | error = md_theme_light_error,
64 | errorContainer = md_theme_light_errorContainer,
65 | onError = md_theme_light_onError,
66 | onErrorContainer = md_theme_light_onErrorContainer,
67 | background = md_theme_light_background,
68 | onBackground = md_theme_light_onBackground,
69 | surface = md_theme_light_surface,
70 | onSurface = md_theme_light_onSurface,
71 | surfaceVariant = md_theme_light_surfaceVariant,
72 | onSurfaceVariant = md_theme_light_onSurfaceVariant,
73 | outline = md_theme_light_outline,
74 | inverseOnSurface = md_theme_light_inverseOnSurface,
75 | inverseSurface = md_theme_light_inverseSurface,
76 | inversePrimary = md_theme_light_inversePrimary,
77 | surfaceTint = md_theme_light_surfaceTint,
78 | outlineVariant = md_theme_light_outlineVariant,
79 | scrim = md_theme_light_scrim,
80 | )
81 |
82 | @Composable
83 | fun UmaPatcherTheme(
84 | darkTheme: Boolean = isSystemInDarkTheme(),
85 | // Dynamic color is available on Android 12+
86 | dynamicColor: Boolean = true,
87 | content: @Composable () -> Unit
88 | ) {
89 | val colorScheme = when {
90 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
91 | val context = LocalContext.current
92 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
93 | }
94 | darkTheme -> DarkColorScheme
95 | else -> LightColorScheme
96 | }
97 |
98 | val view = LocalView.current
99 | if (!view.isInEditMode) {
100 | val currentWindow = (view.context as? Activity)?.window
101 | ?: throw Exception("Not in an activity - unable to get Window reference")
102 |
103 | SideEffect {
104 | currentWindow.statusBarColor = colorScheme.surface.toArgb()
105 | WindowCompat.getInsetsController(currentWindow, view).isAppearanceLightStatusBars = !darkTheme
106 | }
107 | }
108 |
109 | MaterialTheme(
110 | colorScheme = colorScheme,
111 | typography = Typography,
112 | content = content
113 | )
114 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
7 |
13 |
14 |
20 |
21 |
22 |
23 |
24 |
25 |
31 |
32 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/HomeScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.foundation.layout.Arrangement
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Row
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxWidth
9 | import androidx.compose.foundation.layout.height
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.foundation.layout.size
12 | import androidx.compose.foundation.rememberScrollState
13 | import androidx.compose.foundation.verticalScroll
14 | import androidx.compose.material.icons.Icons
15 | import androidx.compose.material.icons.outlined.Info
16 | import androidx.compose.material3.CardDefaults
17 | import androidx.compose.material3.ElevatedCard
18 | import androidx.compose.material3.Icon
19 | import androidx.compose.material3.MaterialTheme
20 | import androidx.compose.material3.Scaffold
21 | import androidx.compose.material3.Text
22 | import androidx.compose.runtime.Composable
23 | import androidx.compose.ui.Alignment
24 | import androidx.compose.ui.Modifier
25 | import androidx.compose.ui.platform.LocalContext
26 | import androidx.compose.ui.platform.LocalLifecycleOwner
27 | import androidx.compose.ui.res.painterResource
28 | import androidx.compose.ui.res.stringResource
29 | import androidx.compose.ui.unit.dp
30 | import com.leadrdrk.umapatcher.R
31 | import com.leadrdrk.umapatcher.core.GameChecker
32 | import com.leadrdrk.umapatcher.ui.component.TopBar
33 | import com.leadrdrk.umapatcher.ui.patcher.AppPatcherCard
34 | import com.leadrdrk.umapatcher.ui.screen.destinations.AppSelectScreenDestination
35 | import com.leadrdrk.umapatcher.utils.safeNavigate
36 | import com.ramcosta.composedestinations.annotation.Destination
37 | import com.ramcosta.composedestinations.annotation.RootNavGraph
38 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
39 |
40 | @RootNavGraph(start = true)
41 | @Destination
42 | @Composable
43 | fun HomeScreen(navigator: DestinationsNavigator) {
44 | Scaffold(
45 | topBar = {
46 | TopBar(
47 | title = stringResource(R.string.app_name),
48 | navigationIcon = {
49 | Icon(
50 | painter = painterResource(R.drawable.ic_launcher_foreground),
51 | contentDescription = null,
52 | modifier = Modifier.size(54.dp)
53 | )
54 | }
55 | )
56 | }
57 | ) { innerPadding ->
58 | Column(
59 | modifier = Modifier
60 | .padding(innerPadding)
61 | .padding(horizontal = 16.dp)
62 | .verticalScroll(rememberScrollState()),
63 | verticalArrangement = Arrangement.spacedBy(16.dp)
64 | ) {
65 | InstallStatusCard(navigator)
66 | AppPatcherCard(navigator)
67 | Spacer(Modifier.height(8.dp))
68 | }
69 | }
70 | }
71 |
72 | @Composable
73 | fun InstallStatusCard(navigator: DestinationsNavigator) {
74 | val pm = LocalContext.current.packageManager
75 | val packageInfo = GameChecker.getPackageInfo(pm)
76 | val lifecycleOwner = LocalLifecycleOwner.current
77 | ElevatedCard(
78 | colors = CardDefaults.elevatedCardColors(
79 | containerColor = MaterialTheme.colorScheme.secondaryContainer
80 | ),
81 | modifier = Modifier
82 | .clickable {
83 | safeNavigate(lifecycleOwner) {
84 | navigator.navigate(AppSelectScreenDestination)
85 | }
86 | }
87 | ) {
88 | Row(modifier = Modifier
89 | .fillMaxWidth()
90 | .padding(24.dp),
91 | verticalAlignment = Alignment.CenterVertically
92 | ) {
93 | if (packageInfo != null) {
94 | val title = stringResource(R.string.game_installed)
95 | Icon(Icons.Outlined.Info, title)
96 | Column(Modifier.padding(start = 20.dp)) {
97 | Text(
98 | text = title,
99 | style = MaterialTheme.typography.titleMedium
100 | )
101 | Spacer(Modifier.height(4.dp))
102 | Text(
103 | text = stringResource(R.string.package_name_prefix) + packageInfo.packageName,
104 | style = MaterialTheme.typography.bodyMedium
105 | )
106 | Spacer(Modifier.height(4.dp))
107 | Text(
108 | text = stringResource(R.string.version_name_prefix) + packageInfo.versionName,
109 | style = MaterialTheme.typography.bodyMedium
110 | )
111 | Spacer(Modifier.height(4.dp))
112 | Text(
113 | text = stringResource(R.string.tap_to_select_app),
114 | style = MaterialTheme.typography.bodySmall,
115 | color = MaterialTheme.colorScheme.onSurfaceVariant
116 | )
117 | }
118 | }
119 | else {
120 | val title = stringResource(R.string.game_not_installed)
121 | Icon(Icons.Outlined.Info, title)
122 | Column(Modifier.padding(start = 20.dp)) {
123 | Text(
124 | text = title,
125 | style = MaterialTheme.typography.titleMedium
126 | )
127 | Spacer(Modifier.height(4.dp))
128 | Text(
129 | text = stringResource(R.string.game_not_installed_info),
130 | style = MaterialTheme.typography.bodyMedium
131 | )
132 | }
133 | }
134 | }
135 | }
136 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/patcher/AppPatcherCard.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.patcher
2 |
3 | import android.content.Intent
4 | import android.net.Uri
5 | import androidx.activity.compose.rememberLauncherForActivityResult
6 | import androidx.activity.result.contract.ActivityResultContracts
7 | import androidx.compose.foundation.clickable
8 | import androidx.compose.foundation.layout.Column
9 | import androidx.compose.foundation.layout.Row
10 | import androidx.compose.foundation.layout.Spacer
11 | import androidx.compose.foundation.layout.fillMaxWidth
12 | import androidx.compose.foundation.layout.height
13 | import androidx.compose.foundation.layout.padding
14 | import androidx.compose.foundation.layout.width
15 | import androidx.compose.material3.Button
16 | import androidx.compose.material3.CardDefaults
17 | import androidx.compose.material3.ElevatedCard
18 | import androidx.compose.material3.Icon
19 | import androidx.compose.material3.MaterialTheme
20 | import androidx.compose.material3.Text
21 | import androidx.compose.runtime.Composable
22 | import androidx.compose.runtime.getValue
23 | import androidx.compose.runtime.mutableIntStateOf
24 | import androidx.compose.runtime.mutableStateOf
25 | import androidx.compose.runtime.saveable.rememberSaveable
26 | import androidx.compose.runtime.setValue
27 | import androidx.compose.ui.Modifier
28 | import androidx.compose.ui.res.painterResource
29 | import androidx.compose.ui.res.stringResource
30 | import androidx.compose.ui.unit.dp
31 | import com.leadrdrk.umapatcher.R
32 | import com.leadrdrk.umapatcher.patcher.AppPatcher
33 | import com.leadrdrk.umapatcher.ui.component.RadioGroupOption
34 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
35 |
36 | @Composable
37 | fun AppPatcherCard(navigator: DestinationsNavigator) {
38 | // Options
39 | val installMethod = rememberSaveable { mutableIntStateOf(0) }
40 | var fileUris by rememberSaveable { mutableStateOf>(arrayOf()) }
41 | val fileSelectLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
42 | val data = it.data ?: return@rememberLauncherForActivityResult
43 |
44 | val clipData = data.clipData
45 | if (clipData != null) {
46 | fileUris = Array(clipData.itemCount) { i ->
47 | clipData.getItemAt(i).uri
48 | }
49 | return@rememberLauncherForActivityResult
50 | }
51 |
52 | val uri = data.data
53 | if (uri != null) {
54 | fileUris = Array(1) { uri }
55 | }
56 | }
57 |
58 | PatcherCard(
59 | label = stringResource(R.string.app_patcher_label),
60 | icon = { Icon(painterResource(R.drawable.ic_apk_install), null) },
61 | buttons = {
62 | Button(
63 | enabled = (installMethod.intValue == 1 || fileUris.isNotEmpty()),
64 | onClick = {
65 | PatcherLauncher.launch(
66 | navigator,
67 | AppPatcher(
68 | fileUris = if (installMethod.intValue == 1) arrayOf()
69 | else fileUris,
70 | install = installMethod.intValue == 0,
71 | directInstall = installMethod.intValue == 1,
72 | )
73 | )
74 | }
75 | ) {
76 | Text(stringResource(R.string.patch))
77 | }
78 | }
79 | ) {
80 | RadioGroupOption(
81 | title = stringResource(R.string.install_method),
82 | desc = stringResource(R.string.install_method_desc),
83 | choices = arrayOf(
84 | stringResource(R.string.normal_install),
85 | stringResource(R.string.direct_install),
86 | stringResource(R.string.save_patched_file)
87 | ),
88 | state = installMethod
89 | )
90 | if (installMethod.intValue != 1) {
91 | Spacer(Modifier.height(16.dp))
92 | ElevatedCard(
93 | colors = CardDefaults.elevatedCardColors(
94 | containerColor = MaterialTheme.colorScheme.secondaryContainer
95 | ),
96 | modifier = Modifier
97 | .clickable {
98 | val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
99 | .apply {
100 | addCategory(Intent.CATEGORY_OPENABLE)
101 | putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
102 | type = "*/*"
103 | }
104 | fileSelectLauncher.launch(intent)
105 | }
106 | ) {
107 | Row(
108 | modifier = Modifier
109 | .fillMaxWidth()
110 | .padding(16.dp)
111 | ) {
112 | Icon(painterResource(R.drawable.ic_file_open), null)
113 | Spacer(Modifier.width(16.dp))
114 | Column {
115 | Text(
116 | text = stringResource(R.string.tap_to_select_file),
117 | style = MaterialTheme.typography.titleMedium
118 | )
119 | Spacer(Modifier.height(4.dp))
120 | Text(
121 | text = stringResource(R.string.n_files_selected).format(fileUris.size),
122 | style = MaterialTheme.typography.bodyMedium
123 | )
124 | Spacer(Modifier.height(4.dp))
125 | Text(
126 | text = stringResource(R.string.app_patcher_supported_files),
127 | style = MaterialTheme.typography.bodySmall,
128 | color = MaterialTheme.colorScheme.onSurfaceVariant
129 | )
130 | }
131 | }
132 | }
133 | }
134 | }
135 | }
--------------------------------------------------------------------------------
/app/src/main/res/values-vi/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Trang chính
4 | Cài đặt
5 | Giới thiệu
6 | Game đã được cài đặt
7 | Game chưa cài đặt
8 | Một số tính năng sẽ không có sẵn.
9 | "Tên gói: "
10 | "Phiên bản: "
11 | Nhấn vào đây để chọn ứng dụng khác
12 | Vá ứng dụng
13 | Vá
14 | Chọn một ứng dụng
15 | %d file đã được chọn
16 | Nhấn vào đây để chọn file
17 | Hỗ trợ: APK / Split APKs, XAPK
18 | Thỉnh thoảng kiểm tra cập nhật khi ứng dụng được mở.
19 | Xuất khóa ký
20 | Xuất keystore BKS được sử dụng để ký các file APK.
21 | Nhập khóa ký
22 | Nhập keystore BKS sẽ được sử dụng để ký các file APK.
23 | Không có keystore để xuất.
24 | Keystore đã được nhập.
25 | Không thể nhập keystore.
26 | Buộc tải lại Hachimi
27 | Vô hiệu hóa các file thư viện hiện có và buộc phải tải lại.
28 | Hachimi sẽ được tải lại trong phiên vá ứng dụng tiếp theo.
29 | Công cụ vá mod Hachimi dành cho Android.
30 | Kiểm tra cập nhật
31 | Các giấy phép mã nguồn mở
32 | Xem mã nguồn
33 | Ủng hộ tôi trên Ko-fi
34 | Phương thức cài đặt
35 | Cách mà bạn muốn bản vá được cài đặt.
36 | Cài trực tiếp (cần root)
37 | Lưu file đã được vá
38 | Cài đặt thường
39 | Đang xử lý...
40 | Hoàn tất
41 | [Vá thành công]
42 | [Vá thất bại]
43 | Cài trực tiếp chỉ có thể được sử dụng khi game đã được cài đặt.
44 | Cần có quyền root để có thể thực hiện tác vụ này.
45 | Không thể đọc file: %s
46 | Không thể di chuyển file: %s
47 | Đang sao chép file
48 | Đang sao chép file: %s
49 | Đang vá
50 | Đang cài đặt
51 | Cài đặt hoàn tất.
52 | Cài đặt thất bại.
53 | Đã lưu file.
54 | Không thể lưu file.
55 | Đang giải nén: %s
56 | Đang tạo file: %s
57 | Đang dọn dẹp
58 | Đang đồng bộ hóa Hachimi
59 | Đang tải: %s
60 | Không thể tải các thư viện Hachimi.
61 | Không thể đồng bộ hóa Hachimi. Sẽ bỏ qua.
62 | Hachimi đã được cập nhật.
63 | Đang sử dụng Hachimi %s
64 | Đã phát hiện file bị hỏng, sẽ hủy bỏ quá trình tải xuống.
65 | Đang ký file APK: %s
66 | Các file APK không hợp lệ hoặc không toàn vẹn (thiếu các file thư viện)
67 | Không tìm thấy thư mục thư viện của ứng dụng. Không có gì đã được cài đặt.
68 | File APK không hợp lệ.
69 | File APK không hợp lệ: %s
70 | Phát hiểu kiểu file split APK: %s
71 | Các thư viện đã được vá: %s
72 | Các file split APK không hợp lệ; một file APK %s khác đã được tìm thấy.
73 | Thiếu file APK Base.
74 | File split APK không hợp lệ. Nhiều dạng đã được phát hiện trong một file.
75 | Phát hiện file XAPK.
76 | Phát hiện file APK thường.
77 | Đang vá theo dạng APK split.
78 | Đang dàn dựng ứng dụng
79 | Đang xóa các file cũ
80 | Hủy
81 | OK
82 | Bản cập nhật mới
83 | Một phiên bản mới đã có sẵn: %s\nBạn có muốn mở trang tải về không?
84 | Không thể kiểm tra cập nhật
85 | Không có cập nhật
86 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/AboutScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Row
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxWidth
9 | import androidx.compose.foundation.layout.height
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.foundation.layout.size
12 | import androidx.compose.foundation.layout.width
13 | import androidx.compose.foundation.rememberScrollState
14 | import androidx.compose.foundation.verticalScroll
15 | import androidx.compose.material.icons.Icons
16 | import androidx.compose.material.icons.outlined.Info
17 | import androidx.compose.material.icons.outlined.Refresh
18 | import androidx.compose.material3.Divider
19 | import androidx.compose.material3.Icon
20 | import androidx.compose.material3.MaterialTheme
21 | import androidx.compose.material3.Scaffold
22 | import androidx.compose.material3.Text
23 | import androidx.compose.runtime.Composable
24 | import androidx.compose.ui.Alignment
25 | import androidx.compose.ui.Modifier
26 | import androidx.compose.ui.layout.ContentScale
27 | import androidx.compose.ui.platform.LocalContext
28 | import androidx.compose.ui.platform.LocalLifecycleOwner
29 | import androidx.compose.ui.platform.LocalUriHandler
30 | import androidx.compose.ui.res.painterResource
31 | import androidx.compose.ui.res.stringResource
32 | import androidx.compose.ui.text.style.TextAlign
33 | import androidx.compose.ui.unit.dp
34 | import com.leadrdrk.umapatcher.BuildConfig
35 | import com.leadrdrk.umapatcher.R
36 | import com.leadrdrk.umapatcher.core.UpdateChecker
37 | import com.leadrdrk.umapatcher.ui.component.TopBar
38 | import com.leadrdrk.umapatcher.ui.screen.destinations.OpenSourceLicensesScreenDestination
39 | import com.leadrdrk.umapatcher.utils.safeNavigate
40 | import com.ramcosta.composedestinations.annotation.Destination
41 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
42 |
43 | @Destination
44 | @Composable
45 | fun AboutScreen(navigator: DestinationsNavigator) {
46 | val context = LocalContext.current
47 |
48 | Scaffold(
49 | topBar = {
50 | TopBar(stringResource(R.string.about))
51 | }
52 | ) { innerPadding ->
53 | Column(
54 | modifier = Modifier
55 | .padding(innerPadding)
56 | .verticalScroll(rememberScrollState())
57 | .fillMaxWidth()
58 | ) {
59 | val lifecycleOwner = LocalLifecycleOwner.current
60 | Column(
61 | modifier = Modifier
62 | .padding(horizontal = 16.dp)
63 | .fillMaxWidth(),
64 | horizontalAlignment = Alignment.CenterHorizontally
65 | ) {
66 | Image(
67 | painter = painterResource(R.drawable.ic_about_logo),
68 | contentDescription = stringResource(R.string.app_name),
69 | modifier = Modifier.size(96.dp, 96.dp),
70 | contentScale = ContentScale.Fit
71 | )
72 | Spacer(Modifier.height(16.dp))
73 | Text(
74 | text = stringResource(R.string.app_name),
75 | style = MaterialTheme.typography.titleLarge
76 | )
77 | Spacer(Modifier.height(4.dp))
78 | Text(
79 | text = "v" + BuildConfig.VERSION_NAME,
80 | style = MaterialTheme.typography.bodyMedium
81 | )
82 | Spacer(Modifier.height(16.dp))
83 | Text(
84 | text = stringResource(R.string.app_desc),
85 | style = MaterialTheme.typography.bodyMedium,
86 | textAlign = TextAlign.Center
87 | )
88 | Spacer(Modifier.height(16.dp))
89 | }
90 | Column(
91 | modifier = Modifier.fillMaxWidth(),
92 | horizontalAlignment = Alignment.CenterHorizontally
93 | ) {
94 | Divider()
95 | Spacer(Modifier.height(4.dp))
96 | TextButtonWithIcon(
97 | text = stringResource(R.string.check_for_updates),
98 | icon = { Icon(Icons.Outlined.Refresh, null) }
99 | ) {
100 | UpdateChecker.run(context)
101 | }
102 | TextButtonWithIcon(
103 | text = stringResource(R.string.open_source_licenses),
104 | icon = { Icon(Icons.Outlined.Info, null) }
105 | ) {
106 | safeNavigate(lifecycleOwner) {
107 | navigator.navigate(OpenSourceLicensesScreenDestination)
108 | }
109 | }
110 | val uriHandler = LocalUriHandler.current
111 | TextButtonWithIcon(
112 | text = stringResource(R.string.view_source_code),
113 | icon = { Icon(painterResource(R.drawable.ic_github), null) }
114 | ) {
115 | uriHandler.openUri("https://github.com/LeadRDRK/UmaPatcher")
116 | }
117 | TextButtonWithIcon(
118 | text = stringResource(R.string.support_me),
119 | icon = { Icon(painterResource(R.drawable.ic_kofi), null) }
120 | ) {
121 | uriHandler.openUri("https://ko-fi.com/leadrdrk")
122 | }
123 | }
124 | }
125 | }
126 | }
127 |
128 | @Composable
129 | fun TextButtonWithIcon(text: String, icon: @Composable () -> Unit, onClick: () -> Unit) {
130 | Row(
131 | modifier = Modifier
132 | .clickable(onClick = onClick)
133 | ) {
134 | Row(
135 | modifier = Modifier
136 | .padding(all = 16.dp)
137 | .fillMaxWidth()
138 | ) {
139 | icon()
140 | Spacer(Modifier.width(16.dp))
141 | Text(
142 | text = text,
143 | style = MaterialTheme.typography.bodyLarge
144 | )
145 | }
146 | }
147 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UmaPatcher
3 | Home
4 | Settings
5 | About
6 |
7 |
8 | Game is installed
9 | Game is not installed
10 | Some features might not be available.
11 | "Package: "
12 | "Version: "
13 | Tap here to select another app
14 |
15 | App patching
16 | Patch
17 | Select an app
18 | %d files selected
19 | Tap here to select files
20 | Supported files: APK / Split APKs, XAPK
21 |
22 |
23 | Occasionally check for updates when the app starts.
24 | Export signing key
25 | Export the BKS keystore used to sign APK files.
26 | Import signing key
27 | Import a BKS keystore that will be used to sign APK files.
28 | No keystore to export.
29 | Keystore imported.
30 | Failed to import keystore.
31 | Force redownload Hachimi
32 | Invalidate the existing libraries and force them to be redownloaded.
33 | Hachimi will be redownloaded on the next app patching session.
34 |
35 |
36 | UM:PD Hachimi mod patching tool for Android.
37 | Check for updates
38 | Open source licenses
39 | View source code
40 | Support me on Ko-fi
41 |
42 |
43 | Install method
44 | How you want the patch to be installed.
45 | Direct install (root required)
46 | Save patched file
47 | Normal install
48 |
49 |
50 | Working...
51 | Completed
52 | [Patching successful]
53 | [Patching failed]
54 | Direct install can only be used when the game is installed.
55 | Root permission is required for this operation.
56 | Failed to read file: %s
57 | Failed to move file: %s
58 | Copying file
59 | Copying file: %s
60 | Patching
61 | Installing
62 | Install completed.
63 | Install failed.
64 | File saved.
65 | Failed to save file.
66 | Extracting file: %s
67 | Creating file: %s
68 | Cleaning up
69 |
70 |
71 | Syncing Hachimi libraries
72 | Downloading file: %s
73 | Failed to download Hachimi libraries.
74 | Failed to sync Hachimi libraries. Skipping.
75 | Hachimi has been updated.
76 | Using Hachimi %s
77 | Corrupted file detected, aborting download.
78 | Signing APK file: %s
79 | Invalid or incomplete APK files (missing native libraries)
80 | No app lib directory was found. Nothing has been installed.
81 | Invalid APK file.
82 | Invalid APK file: %s
83 | Detected APK split type: %s
84 | Libraries patched: %s
85 | Invalid APK splits; another %s APK was found.
86 | Base APK missing from APK splits.
87 | Invalid split APK. Multiple types were detected in one file.
88 | Detected XAPK file.
89 | Detected normal APK file.
90 | Patching as split APKs.
91 | Staging app
92 | Removing legacy files
93 |
94 |
95 | Cancel
96 | OK
97 | Update available
98 | A new version is available: %s\nOpen the download page?
99 | Failed to check for updates
100 | No updates available
101 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/component/Option.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.component
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.Row
6 | import androidx.compose.foundation.layout.Spacer
7 | import androidx.compose.foundation.layout.fillMaxWidth
8 | import androidx.compose.foundation.layout.height
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.layout.width
11 | import androidx.compose.foundation.text.KeyboardOptions
12 | import androidx.compose.material3.Divider
13 | import androidx.compose.material3.MaterialTheme
14 | import androidx.compose.material3.RadioButton
15 | import androidx.compose.material3.Switch
16 | import androidx.compose.material3.Text
17 | import androidx.compose.material3.TextField
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.runtime.LaunchedEffect
20 | import androidx.compose.runtime.MutableIntState
21 | import androidx.compose.runtime.MutableState
22 | import androidx.compose.runtime.getValue
23 | import androidx.compose.runtime.mutableStateOf
24 | import androidx.compose.runtime.remember
25 | import androidx.compose.runtime.setValue
26 | import androidx.compose.ui.Alignment
27 | import androidx.compose.ui.Modifier
28 | import androidx.compose.ui.text.input.KeyboardType
29 | import androidx.compose.ui.unit.dp
30 | import androidx.core.text.isDigitsOnly
31 |
32 | @Composable
33 | fun OptionBase(
34 | title: String,
35 | desc: String,
36 | onClick: () -> Unit,
37 | content: @Composable () -> Unit
38 | ) {
39 | Column(
40 | modifier = Modifier
41 | .clickable(onClick = onClick)
42 | ) {
43 | Row(
44 | modifier = Modifier
45 | .padding(all = 16.dp),
46 | verticalAlignment = Alignment.CenterVertically
47 | ) {
48 | Column(
49 | modifier = Modifier
50 | .weight(1f)
51 | ) {
52 | OptionTitleAndDesc(title, desc)
53 | }
54 | Spacer(Modifier.width(16.dp))
55 | content()
56 | }
57 | Divider()
58 | }
59 | }
60 |
61 | @Composable
62 | fun OptionTitleAndDesc(
63 | title: String,
64 | desc: String
65 | ) {
66 | Text(
67 | text = title,
68 | style = MaterialTheme.typography.bodyLarge
69 | )
70 | Spacer(Modifier.height(4.dp))
71 | Text(
72 | text = desc,
73 | style = MaterialTheme.typography.bodyMedium,
74 | color = MaterialTheme.colorScheme.onSurfaceVariant
75 | )
76 | }
77 |
78 | @Composable
79 | fun BooleanOption(
80 | title: String,
81 | desc: String,
82 | state: MutableState,
83 | enabled: Boolean = true
84 | ) {
85 | OptionBase(
86 | title = title,
87 | desc = desc,
88 | onClick = {
89 | if (enabled)
90 | state.value = !state.value
91 | }
92 | ) {
93 | Switch(
94 | checked = state.value,
95 | onCheckedChange = { state.value = it },
96 | enabled = enabled
97 | )
98 | }
99 | }
100 |
101 | @Composable
102 | fun StringOption(
103 | title: String,
104 | state: MutableState,
105 | placeholder: String? = null,
106 | keyboardOptions: KeyboardOptions = KeyboardOptions()
107 | ) {
108 | var openDialog by remember { mutableStateOf(false) }
109 | OptionBase(
110 | title = title,
111 | desc = state.value,
112 | onClick = { openDialog = true }
113 | ) {}
114 |
115 | var tmpValue by remember { mutableStateOf(state.value) }
116 | LaunchedEffect(openDialog) {
117 | // Reset value every time dialog is reopened
118 | tmpValue = state.value
119 | }
120 |
121 | if (openDialog) {
122 | SimpleOkCancelDialog(
123 | title = title,
124 | onClose = { ok ->
125 | openDialog = false
126 | if (ok) state.value = tmpValue
127 | }
128 | ) {
129 | TextField(
130 | value = tmpValue,
131 | onValueChange = { tmpValue = it },
132 | placeholder = {
133 | if (placeholder != null)
134 | Text(placeholder)
135 | },
136 | keyboardOptions = keyboardOptions
137 | )
138 | }
139 | }
140 | }
141 |
142 | @Composable
143 | fun IntOption(
144 | title: String,
145 | state: MutableIntState,
146 | placeholder: String? = null
147 | ) {
148 | val strValue = remember { mutableStateOf(state.intValue.toString()) }
149 |
150 | LaunchedEffect(strValue.value) {
151 | val str = strValue.value
152 | if (str.isDigitsOnly()) {
153 | val value = str.toInt()
154 | if (state.intValue != value)
155 | state.intValue = value
156 | }
157 | }
158 |
159 | StringOption(
160 | title = title,
161 | state = strValue,
162 | placeholder = placeholder,
163 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
164 | )
165 | }
166 |
167 | @Composable
168 | fun RadioGroupOption(
169 | title: String,
170 | desc: String,
171 | choices: Array,
172 | state: MutableState
173 | ) {
174 | Column(
175 | modifier = Modifier
176 | .fillMaxWidth()
177 | ) {
178 | Column(
179 | modifier = Modifier
180 | .padding(16.dp, 16.dp, 16.dp, bottom = 8.dp)
181 | ) {
182 | OptionTitleAndDesc(title, desc)
183 | }
184 | Column {
185 | choices.forEachIndexed { i, choice ->
186 | Row(
187 | modifier = Modifier
188 | .clickable { state.value = i }
189 | ) {
190 | Row(
191 | verticalAlignment = Alignment.CenterVertically,
192 | modifier = Modifier
193 | .padding(horizontal = 16.dp)
194 | .fillMaxWidth()
195 | ) {
196 | RadioButton(
197 | selected = (state.value == i),
198 | onClick = { state.value = i }
199 | )
200 | Spacer(Modifier.width(8.dp))
201 | Text(
202 | text = choice,
203 | style = MaterialTheme.typography.bodyMedium
204 | )
205 | }
206 | }
207 | }
208 | Spacer(Modifier.height(8.dp))
209 | }
210 | Divider()
211 | }
212 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/SettingsScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import android.content.Intent
4 | import android.widget.Toast
5 | import androidx.activity.compose.rememberLauncherForActivityResult
6 | import androidx.activity.result.contract.ActivityResultContracts
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.padding
9 | import androidx.compose.foundation.rememberScrollState
10 | import androidx.compose.foundation.verticalScroll
11 | import androidx.compose.material3.Scaffold
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.runtime.LaunchedEffect
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.mutableStateOf
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.runtime.setValue
18 | import androidx.compose.ui.Modifier
19 | import androidx.compose.ui.platform.LocalContext
20 | import androidx.compose.ui.res.stringResource
21 | import androidx.datastore.preferences.core.MutablePreferences
22 | import androidx.datastore.preferences.core.edit
23 | import com.leadrdrk.umapatcher.R
24 | import com.leadrdrk.umapatcher.core.PrefKey
25 | import com.leadrdrk.umapatcher.core.dataStore
26 | import com.leadrdrk.umapatcher.core.getPrefValue
27 | import com.leadrdrk.umapatcher.ui.component.BooleanOption
28 | import com.leadrdrk.umapatcher.ui.component.OptionBase
29 | import com.leadrdrk.umapatcher.ui.component.TopBar
30 | import com.leadrdrk.umapatcher.utils.ksFile
31 | import com.leadrdrk.umapatcher.utils.showToast
32 | import com.ramcosta.composedestinations.annotation.Destination
33 |
34 | @Destination
35 | @Composable
36 | fun SettingsScreen() {
37 | val context = LocalContext.current
38 | val checkForUpdates = remember { mutableStateOf(false) }
39 | val appLibsVersion = remember { mutableStateOf("") }
40 | var configRead by remember { mutableStateOf(false) }
41 |
42 | val exportKsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
43 | val uri = it.data?.data ?: return@rememberLauncherForActivityResult
44 | val ksFile = context.ksFile
45 | if (!ksFile.exists()) return@rememberLauncherForActivityResult
46 |
47 | context.contentResolver.openOutputStream(uri).use { output ->
48 | if (output == null) {
49 | context.showToast(
50 | context.getString(R.string.failed_to_save_file),
51 | Toast.LENGTH_SHORT
52 | )
53 | return@use
54 | }
55 | ksFile.inputStream().use { input ->
56 | input.copyTo(output)
57 | context.showToast(
58 | context.getString(R.string.file_saved),
59 | Toast.LENGTH_SHORT
60 | )
61 | }
62 | }
63 | }
64 |
65 | val importKsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
66 | val uri = it.data?.data ?: return@rememberLauncherForActivityResult
67 |
68 | context.contentResolver.openInputStream(uri).use { input ->
69 | if (input == null) {
70 | context.showToast(
71 | context.getString(R.string.failed_to_import_keystore),
72 | Toast.LENGTH_SHORT
73 | )
74 | return@use
75 | }
76 | context.ksFile.outputStream().use { output ->
77 | input.copyTo(output)
78 | context.showToast(
79 | context.getString(R.string.keystore_imported),
80 | Toast.LENGTH_SHORT
81 | )
82 | }
83 | }
84 | }
85 |
86 | @Composable
87 | fun PrefUpdateEffect(key: Any?, transform: suspend (MutablePreferences) -> Unit) {
88 | LaunchedEffect(key) {
89 | if (!configRead) return@LaunchedEffect
90 | context.dataStore.edit(transform)
91 | }
92 | }
93 |
94 | PrefUpdateEffect(checkForUpdates.value) {
95 | it[PrefKey.CHECK_FOR_UPDATES] = checkForUpdates.value
96 | }
97 |
98 | PrefUpdateEffect(appLibsVersion.value) {
99 | it[PrefKey.APP_LIBS_VERSION] = appLibsVersion.value
100 | }
101 |
102 | LaunchedEffect(true) {
103 | checkForUpdates.value = context.getPrefValue(PrefKey.CHECK_FOR_UPDATES) as Boolean
104 | appLibsVersion.value = context.getPrefValue(PrefKey.APP_LIBS_VERSION) as String
105 | configRead = true
106 | }
107 |
108 | Scaffold(
109 | topBar = {
110 | TopBar(stringResource(R.string.settings))
111 | }
112 | ) { innerPadding ->
113 | Column(
114 | modifier = Modifier
115 | .padding(innerPadding)
116 | .verticalScroll(rememberScrollState())
117 | ) {
118 | if (!configRead) return@Column
119 |
120 | BooleanOption(
121 | title = stringResource(R.string.check_for_updates),
122 | desc = stringResource(R.string.check_for_updates_desc),
123 | state = checkForUpdates
124 | )
125 |
126 | OptionBase(
127 | title = stringResource(R.string.export_signing_key),
128 | desc = stringResource(R.string.export_signing_key_desc),
129 | onClick = {
130 | if (context.ksFile.exists()) {
131 | val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
132 | .apply {
133 | addCategory(Intent.CATEGORY_OPENABLE)
134 | type = "*/*"
135 | putExtra(Intent.EXTRA_TITLE, "UmaPatcher.bks")
136 | }
137 | exportKsLauncher.launch(intent)
138 | }
139 | else {
140 | context.showToast(
141 | context.getString(R.string.no_keystore_to_export),
142 | Toast.LENGTH_SHORT
143 | )
144 | }
145 | }
146 | ) {
147 | }
148 |
149 | OptionBase(
150 | title = stringResource(R.string.import_signing_key),
151 | desc = stringResource(R.string.import_signing_key_desc),
152 | onClick = {
153 | val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
154 | .apply {
155 | addCategory(Intent.CATEGORY_OPENABLE)
156 | type = "*/*"
157 | }
158 | importKsLauncher.launch(intent)
159 | }
160 | ) {
161 | }
162 |
163 | OptionBase(
164 | title = stringResource(R.string.force_redownload_mod),
165 | desc = stringResource(R.string.force_redownload_mod_desc),
166 | onClick = {
167 | context.showToast(
168 | context.getString(R.string.force_redownload_mod_notice),
169 | Toast.LENGTH_SHORT
170 | )
171 | appLibsVersion.value = ""
172 | }
173 | ) {
174 | }
175 | }
176 | }
177 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher
2 |
3 | import android.os.Bundle
4 | import android.view.WindowManager
5 | import androidx.activity.ComponentActivity
6 | import androidx.activity.compose.setContent
7 | import androidx.compose.animation.AnimatedContentTransitionScope
8 | import androidx.compose.animation.AnimatedVisibility
9 | import androidx.compose.animation.ExperimentalAnimationApi
10 | import androidx.compose.animation.core.tween
11 | import androidx.compose.animation.fadeIn
12 | import androidx.compose.animation.fadeOut
13 | import androidx.compose.animation.scaleIn
14 | import androidx.compose.animation.scaleOut
15 | import androidx.compose.animation.slideInVertically
16 | import androidx.compose.animation.slideOutVertically
17 | import androidx.compose.foundation.layout.padding
18 | import androidx.compose.material3.Icon
19 | import androidx.compose.material3.NavigationBar
20 | import androidx.compose.material3.NavigationBarItem
21 | import androidx.compose.material3.Scaffold
22 | import androidx.compose.material3.Text
23 | import androidx.compose.runtime.Composable
24 | import androidx.compose.runtime.MutableState
25 | import androidx.compose.runtime.getValue
26 | import androidx.compose.runtime.mutableStateOf
27 | import androidx.compose.runtime.remember
28 | import androidx.compose.runtime.saveable.rememberSaveable
29 | import androidx.compose.runtime.setValue
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.platform.LocalUriHandler
32 | import androidx.compose.ui.res.stringResource
33 | import androidx.compose.ui.tooling.preview.Preview
34 | import androidx.compose.ui.unit.dp
35 | import androidx.navigation.NavHostController
36 | import androidx.navigation.compose.currentBackStackEntryAsState
37 | import androidx.navigation.compose.rememberNavController
38 | import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
39 | import com.leadrdrk.umapatcher.core.GameChecker
40 | import com.leadrdrk.umapatcher.core.UpdateChecker
41 | import com.leadrdrk.umapatcher.ui.component.SimpleOkCancelDialog
42 | import com.leadrdrk.umapatcher.ui.screen.BottomBarDestination
43 | import com.leadrdrk.umapatcher.ui.screen.NavGraphs
44 | import com.leadrdrk.umapatcher.ui.screen.destinations.PatchingScreenDestination
45 | import com.leadrdrk.umapatcher.ui.theme.UmaPatcherTheme
46 | import com.leadrdrk.umapatcher.utils.deleteRecursive
47 | import com.leadrdrk.umapatcher.utils.repoDir
48 | import com.leadrdrk.umapatcher.utils.workDir
49 | import com.ramcosta.composedestinations.DestinationsNavHost
50 | import com.ramcosta.composedestinations.animations.defaults.RootNavGraphDefaultAnimations
51 | import com.ramcosta.composedestinations.animations.rememberAnimatedNavHostEngine
52 | import com.ramcosta.composedestinations.navigation.popBackStack
53 | import com.ramcosta.composedestinations.utils.isRouteOnBackStackAsState
54 | import com.topjohnwu.superuser.Shell
55 |
56 | private val rootInitialized = mutableStateOf(false)
57 |
58 | class MainActivity : ComponentActivity() {
59 | companion object {
60 | init {
61 | Shell.enableVerboseLogging = BuildConfig.DEBUG
62 | Shell.setDefaultBuilder(Shell.Builder.create()
63 | .setFlags(Shell.FLAG_MOUNT_MASTER)
64 | )
65 | }
66 | }
67 |
68 | override fun onCreate(savedInstanceState: Bundle?) {
69 | super.onCreate(savedInstanceState)
70 |
71 | appInit()
72 |
73 | setContent {
74 | UmaPatcherTheme {
75 | MainContent()
76 | }
77 | }
78 |
79 | UpdateChecker.init(this)
80 | }
81 |
82 | private fun appInit() {
83 | GameChecker.init(packageManager)
84 |
85 | // Init work directory
86 | workDir.mkdir()
87 | deleteRecursive(workDir, deleteRoot = false)
88 |
89 | // Remove legacy repo directory (if it exists)
90 | deleteRecursive(repoDir, deleteRoot = true)
91 |
92 | // Request root permissions
93 | Shell.getShell { rootInitialized.value = true }
94 | }
95 |
96 | fun useKeepScreenOn(callback: () -> Unit) {
97 | runOnUiThread {
98 | window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
99 | }
100 | callback()
101 | runOnUiThread {
102 | window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
103 | }
104 | }
105 | }
106 |
107 | @OptIn(ExperimentalMaterialNavigationApi::class, ExperimentalAnimationApi::class)
108 | @Composable
109 | private fun MainContent() {
110 | val navController = rememberNavController()
111 | val navHostEngine = rememberAnimatedNavHostEngine(
112 | rootDefaultAnimations = navAnimations
113 | )
114 |
115 | val bottomBarState = rememberSaveable { mutableStateOf(true) }
116 | val navBackStackEntry by navController.currentBackStackEntryAsState()
117 | when (navBackStackEntry?.destination?.route) {
118 | PatchingScreenDestination.route -> bottomBarState.value = false
119 | else -> bottomBarState.value = true
120 | }
121 |
122 | var openUpdateDialog by remember { mutableStateOf(false) }
123 | var tagName by remember { mutableStateOf("") }
124 | val uriHandler = LocalUriHandler.current
125 |
126 | UpdateChecker.callback = { name ->
127 | tagName = name
128 | openUpdateDialog = true
129 | }
130 |
131 | Scaffold(
132 | bottomBar = { BottomBar(navController, bottomBarState) }
133 | ) { innerPadding ->
134 | if (rootInitialized.value) {
135 | DestinationsNavHost(
136 | modifier = Modifier.padding(innerPadding),
137 | navGraph = NavGraphs.root,
138 | navController = navController,
139 | engine = navHostEngine
140 | )
141 | }
142 | if (openUpdateDialog) {
143 | SimpleOkCancelDialog(
144 | title = stringResource(R.string.update_available),
145 | onClose = { ok ->
146 | openUpdateDialog = false
147 | if (ok) uriHandler.openUri(UpdateChecker.getReleaseUrl(tagName))
148 | }
149 | ) {
150 | Text(
151 | stringResource(R.string.update_available_desc).format(tagName)
152 | )
153 | }
154 | }
155 | }
156 | }
157 |
158 | private val navAnimations = RootNavGraphDefaultAnimations(
159 | enterTransition = {
160 | scaleIn(
161 | animationSpec = tween(200),
162 | initialScale = 0.9f
163 | ) + fadeIn(
164 | animationSpec = tween(200)
165 | )
166 | },
167 | exitTransition = {
168 | scaleOut(
169 | animationSpec = tween(200),
170 | targetScale = 0.9f
171 | ) + fadeOut(
172 | animationSpec = tween(200)
173 | )
174 | },
175 | popExitTransition = {
176 | slideOutOfContainer(
177 | towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
178 | animationSpec = tween(200)
179 | )
180 | }
181 | )
182 |
183 | @Composable
184 | private fun BottomBar(navController: NavHostController, bottomBarState: MutableState) {
185 | AnimatedVisibility(
186 | visible = bottomBarState.value,
187 | enter = slideInVertically(initialOffsetY = { it }),
188 | exit = slideOutVertically(targetOffsetY = { it })
189 | ) {
190 | NavigationBar(tonalElevation = 8.dp) {
191 | BottomBarDestination.entries.forEach { destination ->
192 | val isCurrentDestOnBackStack by navController.isRouteOnBackStackAsState(destination.direction)
193 | NavigationBarItem(
194 | selected = isCurrentDestOnBackStack,
195 | onClick = {
196 | if (isCurrentDestOnBackStack) {
197 | navController.popBackStack(destination.direction, false)
198 | }
199 |
200 | navController.navigate(destination.direction.route) {
201 | popUpTo(NavGraphs.root.route) {
202 | saveState = true
203 | }
204 | launchSingleTop = true
205 | restoreState = true
206 | }
207 | },
208 | icon = {
209 | if (isCurrentDestOnBackStack) {
210 | Icon(destination.iconSelected, stringResource(destination.label))
211 | } else {
212 | Icon(destination.iconNotSelected, stringResource(destination.label))
213 | }
214 | },
215 | label = { Text(stringResource(destination.label)) },
216 | alwaysShowLabel = false
217 | )
218 | }
219 | }
220 | }
221 | }
222 |
223 | @Preview(showBackground = true)
224 | @Composable
225 | fun DefaultPreview() {
226 | MainContent()
227 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/ui/screen/PatchingScreen.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.ui.screen
2 |
3 | import android.content.Intent
4 | import androidx.activity.compose.BackHandler
5 | import androidx.activity.compose.rememberLauncherForActivityResult
6 | import androidx.activity.result.contract.ActivityResultContracts
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.Spacer
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.height
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.layout.width
14 | import androidx.compose.foundation.rememberScrollState
15 | import androidx.compose.foundation.verticalScroll
16 | import androidx.compose.material3.LinearProgressIndicator
17 | import androidx.compose.material3.MaterialTheme
18 | import androidx.compose.material3.Scaffold
19 | import androidx.compose.material3.Text
20 | import androidx.compose.material3.TextField
21 | import androidx.compose.material3.TextFieldDefaults
22 | import androidx.compose.runtime.Composable
23 | import androidx.compose.runtime.LaunchedEffect
24 | import androidx.compose.runtime.getValue
25 | import androidx.compose.runtime.mutableFloatStateOf
26 | import androidx.compose.runtime.mutableStateListOf
27 | import androidx.compose.runtime.mutableStateOf
28 | import androidx.compose.runtime.remember
29 | import androidx.compose.runtime.rememberCoroutineScope
30 | import androidx.compose.runtime.setValue
31 | import androidx.compose.ui.Modifier
32 | import androidx.compose.ui.graphics.Color
33 | import androidx.compose.ui.platform.LocalContext
34 | import androidx.compose.ui.platform.LocalLifecycleOwner
35 | import androidx.compose.ui.res.stringResource
36 | import androidx.compose.ui.text.TextStyle
37 | import androidx.compose.ui.text.font.FontFamily
38 | import androidx.compose.ui.text.style.TextOverflow
39 | import androidx.compose.ui.unit.TextUnit
40 | import androidx.compose.ui.unit.TextUnitType
41 | import androidx.compose.ui.unit.dp
42 | import com.leadrdrk.umapatcher.R
43 | import com.leadrdrk.umapatcher.ui.component.BackButton
44 | import com.leadrdrk.umapatcher.ui.component.TopBar
45 | import com.leadrdrk.umapatcher.ui.patcher.PatcherLauncher
46 | import com.leadrdrk.umapatcher.utils.copyTo
47 | import com.leadrdrk.umapatcher.utils.safeNavigate
48 | import com.ramcosta.composedestinations.annotation.Destination
49 | import com.ramcosta.composedestinations.navigation.DestinationsNavigator
50 | import kotlinx.coroutines.Dispatchers
51 | import kotlinx.coroutines.launch
52 | import java.io.File
53 |
54 | private const val MAX_LOG_LINES = 200
55 |
56 | @Destination
57 | @Composable
58 | fun PatchingScreen(navigator: DestinationsNavigator) {
59 | val workingStr = stringResource(R.string.working)
60 | val completedStr = stringResource(R.string.completed)
61 |
62 | val log = remember { mutableStateListOf() }
63 | var currentTask by remember { mutableStateOf(workingStr) }
64 | var progress by remember { mutableFloatStateOf(-1f) }
65 | var completed by remember { mutableStateOf(false) }
66 | val context = LocalContext.current
67 |
68 | // Patcher callbacks
69 | fun onLog(line: String) {
70 | log.add(line)
71 | if (log.size > MAX_LOG_LINES)
72 | log.removeRange(0, log.size - MAX_LOG_LINES)
73 | }
74 | fun onProgress(p: Float) { progress = p }
75 | fun onTask(task: String) {
76 | currentTask = task
77 | log.add("-- $task")
78 | }
79 |
80 | val coroutineScope = rememberCoroutineScope()
81 | var sfFile by remember { mutableStateOf(null) }
82 | var sfCallback: (Boolean) -> Unit by remember { mutableStateOf({}) }
83 | val sfLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
84 | val uri = it.data?.data
85 | if (uri == null) {
86 | sfCallback(false)
87 | sfFile = null
88 | return@rememberLauncherForActivityResult
89 | }
90 |
91 | coroutineScope.launch(Dispatchers.IO) {
92 | context.contentResolver.openOutputStream(uri).use { output ->
93 | if (output == null) {
94 | sfCallback(false)
95 | sfFile = null
96 | return@launch
97 | }
98 |
99 | val file = sfFile!!
100 | val length = file.length().toFloat()
101 | onTask(context.getString(R.string.copying_file_name).format(file.name))
102 | progress = 0f
103 | file.inputStream().use { input ->
104 | input.copyTo(output) { current ->
105 | progress = current / length
106 | }
107 | }
108 | }
109 | sfCallback(true)
110 | currentTask = completedStr
111 | sfFile = null
112 | }
113 | }
114 |
115 | fun onSaveFile(filename: String, file: File, callback: (Boolean) -> Unit = {}) {
116 | sfFile = file
117 | sfCallback = callback
118 | val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
119 | .apply {
120 | addCategory(Intent.CATEGORY_OPENABLE)
121 | type = "*/*"
122 | putExtra(Intent.EXTRA_TITLE, filename)
123 | }
124 | sfLauncher.launch(intent)
125 | }
126 |
127 | val scrollState = rememberScrollState()
128 | LaunchedEffect(log.size) {
129 | scrollState.scrollTo(scrollState.maxValue)
130 | }
131 |
132 | val lifecycleOwner = LocalLifecycleOwner.current
133 | BackHandler {
134 | if (completed && sfFile == null) {
135 | safeNavigate(lifecycleOwner) {
136 | navigator.popBackStack()
137 | }
138 | }
139 | }
140 |
141 | val patchSuccessMsg = stringResource(R.string.patch_success_msg)
142 | val patchFailedMsg = stringResource(R.string.patch_failed_msg)
143 |
144 | LaunchedEffect(true) {
145 | if (PatcherLauncher.patching) return@LaunchedEffect
146 | val patcher = PatcherLauncher.patcher!!
147 | patcher.setCallbacks(::onLog, ::onProgress, ::onTask, ::onSaveFile)
148 | PatcherLauncher.runPatcher(context) { success ->
149 | completed = true
150 | log.add(if (success) patchSuccessMsg else patchFailedMsg)
151 | progress = 1f
152 | }
153 | }
154 |
155 | LaunchedEffect(completed) {
156 | if (completed) {
157 | currentTask = completedStr
158 | }
159 | }
160 |
161 | Scaffold(
162 | topBar = {
163 | TopBar(
164 | title = if (completed) completedStr else workingStr,
165 | navigationIcon = { BackButton(navigator, enabled = completed && sfFile == null) }
166 | )
167 | }
168 | ) { innerPadding ->
169 | Column(
170 | modifier = Modifier
171 | .padding(innerPadding)
172 | .fillMaxWidth()
173 | ) {
174 | TextField(
175 | value = log.joinToString("\n"),
176 | onValueChange = {},
177 | readOnly = true,
178 | textStyle = TextStyle(
179 | fontFamily = FontFamily.Monospace,
180 | lineHeight = TextUnit(1.4f, TextUnitType.Em)
181 | ),
182 | modifier = Modifier
183 | .fillMaxWidth()
184 | .weight(1f)
185 | .verticalScroll(scrollState),
186 | colors = TextFieldDefaults.colors(
187 | focusedIndicatorColor = Color.Unspecified,
188 | unfocusedIndicatorColor = Color.Unspecified
189 | )
190 | )
191 | Column(
192 | modifier = Modifier
193 | .padding(all = 16.dp)
194 | ) {
195 | Row(
196 | modifier = Modifier
197 | .fillMaxWidth()
198 | ) {
199 | Text(
200 | text = currentTask,
201 | style = MaterialTheme.typography.bodyMedium,
202 | modifier = Modifier
203 | .weight(1f),
204 | maxLines = 1,
205 | overflow = TextOverflow.Ellipsis
206 | )
207 | Spacer(Modifier.width(16.dp))
208 | Text(
209 | text = if (progress < 0) "¯\\_(ツ)_/¯" else "${(progress * 100).toInt()}%",
210 | style = MaterialTheme.typography.bodyMedium
211 | )
212 | }
213 | Spacer(Modifier.height(8.dp))
214 | if (progress < 0) {
215 | // Indeterminate
216 | LinearProgressIndicator(
217 | modifier = Modifier.fillMaxWidth(),
218 | )
219 | }
220 | else {
221 | LinearProgressIndicator(
222 | progress = progress,
223 | modifier = Modifier.fillMaxWidth(),
224 | )
225 | }
226 | Spacer(Modifier.height(8.dp))
227 | }
228 | }
229 | }
230 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/app/src/main/java/com/leadrdrk/umapatcher/patcher/AppPatcher.kt:
--------------------------------------------------------------------------------
1 | package com.leadrdrk.umapatcher.patcher
2 |
3 | import android.app.PendingIntent
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.content.pm.PackageInfo
7 | import android.content.pm.PackageInstaller
8 | import android.content.pm.PackageManager
9 | import android.net.Uri
10 | import android.os.Build
11 | import android.util.Log
12 | import androidx.datastore.preferences.core.edit
13 | import com.leadrdrk.umapatcher.R
14 | import com.leadrdrk.umapatcher.core.GameChecker
15 | import com.leadrdrk.umapatcher.core.GitHubReleases
16 | import com.leadrdrk.umapatcher.core.PrefKey
17 | import com.leadrdrk.umapatcher.core.dataStore
18 | import com.leadrdrk.umapatcher.core.getPrefValue
19 | import com.leadrdrk.umapatcher.utils.bytesToHex
20 | import com.leadrdrk.umapatcher.utils.downloadFileAndDigestSHA1
21 | import com.leadrdrk.umapatcher.utils.fetchJson
22 | import com.leadrdrk.umapatcher.utils.ksFile
23 | import com.leadrdrk.umapatcher.utils.workDir
24 | import com.leadrdrk.umapatcher.zip.ZipExtractor
25 | import com.reandroid.apk.ApkModule
26 | import com.reandroid.archive.Archive
27 | import com.reandroid.archive.FileInputSource
28 | import com.reandroid.archive.ZipEntryMap
29 | import com.topjohnwu.superuser.Shell
30 | import kotlinx.coroutines.delay
31 | import kotlinx.coroutines.runBlocking
32 | import net.lingala.zip4j.ZipFile
33 | import net.lingala.zip4j.model.ZipParameters
34 | import net.lingala.zip4j.model.enums.CompressionMethod
35 | import net.lingala.zip4j.progress.ProgressMonitor
36 | import java.io.File
37 | import java.io.IOException
38 | import java.net.URL
39 |
40 | private const val LIBS_REPO_PATH = "Hachimi-Hachimi/Hachimi"
41 |
42 | private const val MOD_ARM64_LIB_NAME = "libmain-arm64-v8a.so"
43 | private const val APK_ARM64_LIB_DIR = "lib/arm64-v8a"
44 | private const val APK_ARM64_LIB_PATH = "$APK_ARM64_LIB_DIR/libmain.so"
45 | private const val APK_ORIG_ARM64_LIB_PATH = "$APK_ARM64_LIB_DIR/libmain_orig.so"
46 |
47 | private const val MOD_ARM_LIB_NAME = "libmain-armeabi-v7a.so"
48 | private const val APK_ARM_LIB_DIR = "lib/armeabi-v7a"
49 | private const val APK_ARM_LIB_PATH = "$APK_ARM_LIB_DIR/libmain.so"
50 | private const val APK_ORIG_ARM_LIB_PATH = "$APK_ARM_LIB_DIR/libmain_orig.so"
51 |
52 | private const val LEGACY_MOUNT_SCRIPT_DIR = "/data/adb/umapatcher"
53 |
54 | private val Context.libsDir: File
55 | get() = filesDir.resolve("libs")
56 |
57 | private val Context.modArm64Lib: File
58 | get() = libsDir.resolve(MOD_ARM64_LIB_NAME)
59 |
60 | private val Context.modArmLib: File
61 | get() = libsDir.resolve(MOD_ARM_LIB_NAME)
62 |
63 | private val Context.apkExtractDir: File
64 | get() = workDir.resolve("apk_extract")
65 |
66 | private val Context.xapkExtractDir: File
67 | get() = workDir.resolve("xapk_extract")
68 |
69 | class AppPatcher(
70 | private val fileUris: Array,
71 | private val install: Boolean,
72 | private val directInstall: Boolean
73 | ): Patcher() {
74 | override fun run(context: Context): Boolean {
75 | if (directInstall && !isDirectInstallAllowed(context))
76 | return false
77 |
78 | val libVer = runBlocking { syncModLibs(context) } ?: return false
79 | log(context.getString(R.string.using_app_lib_ver).format(libVer))
80 |
81 | if (directInstall)
82 | return runDirectInstall(context)
83 |
84 | if (fileUris.size == 1) {
85 | return runBlocking {
86 | runXapkOrFullApk(context, (copyInputFiles(context) ?: return@runBlocking false)[0])
87 | }
88 | }
89 | else if (fileUris.size > 1) {
90 | return runBlocking { runSplitApks(context) }
91 | }
92 |
93 | return false
94 | }
95 |
96 | private fun runDirectInstall(context: Context): Boolean {
97 | // Check and remove legacy mount script
98 | if (RootUtils.testDirectory(LEGACY_MOUNT_SCRIPT_DIR)) {
99 | task = context.getString(R.string.removing_legacy_files)
100 | progress = -1f
101 |
102 | if (isApkMounted(context)) unmountApk(context)
103 | RootUtils.removeDirectory(LEGACY_MOUNT_SCRIPT_DIR)
104 | }
105 |
106 | task = context.getString(R.string.installing)
107 | progress = -1f
108 |
109 | val modArm64Lib = context.modArm64Lib
110 | val modArmLib = context.modArmLib
111 |
112 | val packageInfo = GameChecker.getPackageInfo(context.packageManager) ?: return false
113 | val appApkDir = File(packageInfo.applicationInfo.publicSourceDir).parentFile ?: return false
114 |
115 | val arm64LibDir = appApkDir.resolve("lib/arm64")
116 | val armLibDir = appApkDir.resolve("lib/arm")
117 |
118 | if (RootUtils.testDirectory(arm64LibDir.path)) {
119 | installModLib(modArm64Lib, arm64LibDir)
120 | }
121 | else if (RootUtils.testDirectory(armLibDir.path)) {
122 | installModLib(modArmLib, armLibDir)
123 | }
124 | else {
125 | log(context.getString(R.string.app_lib_dir_not_found))
126 | return false
127 | }
128 |
129 | return true
130 | }
131 |
132 | private fun installModLib(modLib: File, libDir: File): Boolean {
133 | val lib = libDir.resolve("libmain.so")
134 | val origLib = libDir.resolve("libmain_orig.so")
135 | if (!RootUtils.testFile(origLib.path)) {
136 | RootUtils.moveGameLibrary(lib.path, origLib.path)
137 | .isSuccess || return false
138 | }
139 | RootUtils.copyGameLibrary(modLib.path, lib.path)
140 | .isSuccess || return false
141 |
142 | return true
143 | }
144 |
145 | private suspend fun runXapkOrFullApk(context: Context, file: File): Boolean {
146 | val fileHeaders = ZipFile(file).use { it.fileHeaders }
147 | val zip = ZipExtractor.maybeMapped(file)
148 |
149 | // Detect file type without extracting first
150 | for (header in fileHeaders) {
151 | if (header.fileName.endsWith(".apk")) {
152 | log(context.getString(R.string.detected_xapk_file))
153 | return runXapk(context, zip)
154 | }
155 | else if (header.fileName == "classes.dex") {
156 | log(context.getString(R.string.detected_apk_file))
157 | return runFullApk(context, zip)
158 | }
159 | }
160 |
161 | zip.close()
162 | log(context.getString(R.string.invalid_apk_file))
163 | return false
164 | }
165 |
166 | private suspend fun runXapk(context: Context, zip: ZipExtractor): Boolean {
167 | // Extract the XAPK file
168 | val extractDir = context.xapkExtractDir
169 | extractZipWithProgress(context, zip, extractDir)
170 | zip.close()
171 | zip.file.delete()
172 |
173 | // Patch the split APKs
174 | try {
175 | val apkFiles = extractDir.listFiles { _, name -> name.endsWith(".apk") } ?: return false
176 | if (!patchSplitApks(context, apkFiles))
177 | return false
178 |
179 | // Install or save
180 | return if (install)
181 | installApks(context, apkFiles)
182 | else
183 | createAndSaveXapk(context, apkFiles)
184 | }
185 | catch (ex: Exception) {
186 | logException(ex)
187 | return false
188 | }
189 | finally {
190 | task = context.getString(R.string.cleaning_up)
191 | progress = -1f
192 |
193 | extractDir.deleteRecursively()
194 | context.apkExtractDir.deleteRecursively()
195 | }
196 | }
197 |
198 | private suspend fun runFullApk(context: Context, zip: ZipExtractor): Boolean {
199 | try {
200 | if (!patchApk(context, zip))
201 | return false
202 |
203 | return if (install) {
204 | installApks(context, arrayOf(zip.file))
205 | }
206 | else {
207 | val success = saveFile("patched-${System.currentTimeMillis()}.apk", zip.file)
208 | log(
209 | if (success) context.getString(R.string.file_saved)
210 | else context.getString(R.string.failed_to_save_file)
211 | )
212 | success
213 | }
214 | }
215 | catch (ex: Exception) {
216 | logException(ex)
217 | return false
218 | }
219 | finally {
220 | task = context.getString(R.string.cleaning_up)
221 | progress = -1f
222 |
223 | zip.close()
224 | zip.file.delete()
225 | context.apkExtractDir.deleteRecursively()
226 | }
227 | }
228 |
229 | private suspend fun runSplitApks(context: Context): Boolean {
230 | log(context.getString(R.string.patching_as_split_apks))
231 | val files = copyInputFiles(context, ".apk") ?: return false
232 | try {
233 | if (!patchSplitApks(context, files))
234 | return false
235 |
236 | return if (install)
237 | installApks(context, files)
238 | else
239 | createAndSaveXapk(context, files)
240 | }
241 | catch (ex: Exception) {
242 | logException(ex)
243 | return false
244 | }
245 | finally {
246 | task = context.getString(R.string.cleaning_up)
247 | progress = -1f
248 |
249 | files.forEach { it.delete() }
250 | context.apkExtractDir.deleteRecursively()
251 | }
252 | }
253 |
254 | private fun copyInputFiles(context: Context, ext: String = ""): Array? {
255 | return Array(fileUris.size) {
256 | val filename = "file$it$ext"
257 | val file = context.workDir.resolve(filename)
258 |
259 | task = if (fileUris.size > 1) context.getString(R.string.copying_file_name).format(filename)
260 | else context.getString(R.string.copying_file)
261 | progress = -1f
262 |
263 | context.contentResolver.openInputStream(fileUris[it]).use { input ->
264 | if (input == null) {
265 | log(context.getString(R.string.failed_to_read_file).format(filename))
266 | return null
267 | }
268 |
269 | file.outputStream().use { output ->
270 | input.copyTo(output)
271 | }
272 | }
273 |
274 | file
275 | }
276 | }
277 |
278 | private enum class SplitApkType {
279 | BASE,
280 | CONFIG_ARM,
281 | CONFIG_ARM64
282 | }
283 |
284 | private suspend fun patchSplitApks(context: Context, files: Array): Boolean {
285 | val extractDir = context.apkExtractDir
286 | val res = run {
287 | var success = true
288 | useZipExtractors(files) { zipFiles ->
289 | val processedSplits = mutableMapOf()
290 | for (zip in zipFiles) {
291 | try {
292 | if (!runBlocking { patchApk(context, zip, processedSplits) }) {
293 | success = false
294 | return@useZipExtractors
295 | }
296 | }
297 | catch (ex: Exception) {
298 | logException(ex)
299 | success = false
300 | return@useZipExtractors
301 | }
302 | }
303 |
304 | if (processedSplits[SplitApkType.BASE] != true) {
305 | log(context.getString(R.string.apk_splits_missing_base))
306 | success = false
307 | }
308 |
309 | if (processedSplits[SplitApkType.CONFIG_ARM64] != true &&
310 | processedSplits[SplitApkType.CONFIG_ARM] != true)
311 | {
312 | log(context.getString(R.string.apk_files_missing_lib))
313 | success = false
314 | }
315 | }
316 |
317 | success
318 | }
319 |
320 | extractDir.deleteRecursively()
321 | return res
322 | }
323 |
324 | private fun useZipExtractors(files: Array, callback: (Array) -> Unit) {
325 | val zipFiles = Array(files.size) {
326 | ZipExtractor.maybeMapped(files[it])
327 | }
328 | callback(zipFiles)
329 | zipFiles.forEach { it.close() }
330 | }
331 |
332 | private suspend fun extractZipWithProgress(context: Context, zip: ZipExtractor, extractDir: File) {
333 | task = context.getString(R.string.extracting_file).format(zip.file.name)
334 | progress = -1f
335 |
336 | extractDir.deleteRecursively()
337 | zip.extractAll(extractDir) { progress = it }
338 | }
339 |
340 | private suspend fun monitorZipProgress(zip: ZipFile) {
341 | val progressMonitor = zip.progressMonitor
342 | while (!progressMonitor.state.equals(ProgressMonitor.State.READY)) {
343 | progress = progressMonitor.percentDone / 100f
344 | delay(100)
345 | }
346 | }
347 |
348 | private suspend fun patchApk(
349 | context: Context,
350 | zip: ZipExtractor,
351 | processedSplits: MutableMap? = null
352 | ): Boolean {
353 | // Build do not compress list
354 | val doNotCompress = zip.fileHeaders
355 | .filter { it.compressionMethod == CompressionMethod.STORE }
356 | .map { it.fileName }
357 | .toSet()
358 |
359 | // Extract file
360 | val file = zip.file
361 | val filename = file.name
362 |
363 | val extractDir = context.apkExtractDir
364 | extractZipWithProgress(context, zip, extractDir)
365 | zip.close()
366 | file.delete()
367 |
368 | // Check manifest
369 | if (!extractDir.resolve("AndroidManifest.xml").isFile) {
370 | log(context.getString(R.string.invalid_apk_file_name).format(filename))
371 | return false
372 | }
373 |
374 | // Detect apk type / Patch the lib files
375 | task = context.getString(R.string.patching)
376 | progress = -1f
377 |
378 | val arm64Lib = extractDir.resolve(APK_ARM64_LIB_PATH)
379 | val armLib = extractDir.resolve(APK_ARM_LIB_PATH)
380 | val classesDex = extractDir.resolve("classes.dex")
381 | var processed = false
382 | var libPatched = false
383 |
384 | fun isInvalidSplit(splitType: SplitApkType): Boolean {
385 | if (processedSplits == null) return false
386 | log(context.getString(R.string.detected_apk_split).format(splitType.name))
387 |
388 | if (processed) {
389 | log(context.getString(R.string.invalid_split_apk_multiple_type))
390 | return true
391 | }
392 |
393 | if (processedSplits[splitType] == true) {
394 | log(
395 | context.getString(R.string.invalid_apk_splits_duplicate)
396 | .format(splitType.name)
397 | )
398 | return true
399 | }
400 |
401 | return false
402 | }
403 |
404 | fun patchArchLibs(
405 | splitType: SplitApkType,
406 | lib: File,
407 | modLib: File,
408 | origLibPath: String
409 | ): Boolean {
410 | if (isInvalidSplit(splitType)) return false
411 |
412 | // Only create the orig lib if it hasn't existed yet to allow updating an already patched apk
413 | val origLib = extractDir.resolve(origLibPath)
414 | if (!origLib.exists()) {
415 | lib.renameTo(origLib)
416 | }
417 | modLib.copyTo(lib)
418 |
419 | log(context.getString(R.string.libraries_patched).format(lib.parentFile!!.name))
420 | processed = true
421 | libPatched = true
422 | processedSplits?.put(splitType, true)
423 |
424 | return true
425 | }
426 |
427 | if (arm64Lib.exists()) {
428 | patchArchLibs(
429 | splitType = SplitApkType.CONFIG_ARM64,
430 | lib = arm64Lib,
431 | modLib = context.modArm64Lib,
432 | origLibPath = APK_ORIG_ARM64_LIB_PATH
433 | ) || return false
434 | }
435 |
436 | if (armLib.exists()) {
437 | patchArchLibs(
438 | splitType = SplitApkType.CONFIG_ARM,
439 | lib = armLib,
440 | modLib = context.modArmLib,
441 | origLibPath = APK_ORIG_ARM_LIB_PATH
442 | ) || return false
443 | }
444 |
445 | if (classesDex.exists()) {
446 | val splitType = SplitApkType.BASE
447 | if (isInvalidSplit(splitType)) return false
448 | processed = true
449 | processedSplits?.put(splitType, true)
450 | }
451 |
452 | if (!processed) {
453 | log(context.getString(R.string.invalid_apk_file_name).format(filename))
454 | return false
455 | }
456 |
457 | // Check if libs are patched if this is a full apk
458 | if (processedSplits == null && !libPatched) {
459 | log(context.getString(R.string.apk_files_missing_lib))
460 | return false
461 | }
462 |
463 | // Create new apk file
464 | task = context.getString(R.string.creating_file).format(filename)
465 | progress = -1f
466 |
467 | val zipEntryMap = ZipEntryMap()
468 | val prefixLen = extractDir.canonicalPath.length + 1
469 | var fileCount = 0
470 | extractDir.walkTopDown().forEach { child ->
471 | if (child.isFile) {
472 | val name = child.canonicalPath.substring(prefixLen)
473 | val inputSource = FileInputSource(child, name).apply {
474 | if (doNotCompress.contains(name)) method = Archive.STORED
475 | }
476 | zipEntryMap.add(inputSource)
477 | ++fileCount
478 | }
479 | }
480 |
481 | val apk = ApkModule(zipEntryMap)
482 | var writtenFiles = 0
483 | apk.writeApk(file) { path, _, _ ->
484 | log(path)
485 | progress = ++writtenFiles / fileCount.toFloat()
486 | }
487 |
488 | // Sign APK file
489 | task = context.getString(R.string.signing_apk_file).format(filename)
490 | progress = -1f
491 |
492 | val signedApkFile = context.workDir.resolve("tmp_signed.apk")
493 | val apkSigner = ApkSigner("UmaPatcher", "securep@ssw0rd816-n")
494 | apkSigner.signApk(file, signedApkFile, context.ksFile)
495 | if (!signedApkFile.renameTo(file)) {
496 | log(context.getString(R.string.failed_to_move_file).format(signedApkFile.name))
497 | return false
498 | }
499 |
500 | // we're finally done :')
501 | return true
502 | }
503 |
504 | private suspend fun installApks(context: Context, files: Array): Boolean {
505 | task = context.getString(R.string.staging_app)
506 | progress = -1f
507 |
508 | val sessionParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
509 | sessionParams.setInstallLocation(PackageInfo.INSTALL_LOCATION_AUTO)
510 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
511 | sessionParams.setInstallReason(PackageManager.INSTALL_REASON_USER)
512 | }
513 |
514 | val packageInstaller = context.packageManager.packageInstaller
515 | val sessionId: Int = packageInstaller.createSession(sessionParams)
516 |
517 | packageInstaller.openSession(sessionId).use { session ->
518 | try {
519 | var i = 0
520 | for (file in files) {
521 | val length = file.length()
522 | file.inputStream().use { input ->
523 | session.openWrite("${i++}.apk", 0, length).use { output ->
524 | log(context.getString(R.string.copying_file_name).format(file.name))
525 | copyStreamProgress(input, output, length)
526 | progress = -1f
527 | session.fsync(output)
528 | }
529 | }
530 | }
531 |
532 | task = context.getString(R.string.installing)
533 |
534 | val callbackIntent = Intent(context, PackageInstallerStatusReceiver::class.java)
535 | val pendingIntent =
536 | PendingIntent.getBroadcast(
537 | context,
538 | 0,
539 | callbackIntent,
540 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
541 | PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
542 | } else {
543 | PendingIntent.FLAG_UPDATE_CURRENT
544 | }
545 | )
546 | session.commit(pendingIntent.intentSender)
547 | }
548 | catch (ex: Exception) {
549 | log(context.getString(R.string.install_failed))
550 | logException(ex)
551 | session.abandon()
552 | return false
553 | }
554 | }
555 |
556 | val success = PackageInstallerStatusReceiver.waitForInstallFinish()
557 | log(context.getString(
558 | if (success) R.string.install_completed
559 | else R.string.install_failed
560 | ))
561 | return success
562 | }
563 |
564 | private suspend fun createAndSaveXapk(context: Context, files: Array): Boolean {
565 | task = context.getString(R.string.creating_file).format("patched.xapk")
566 | progress = -1f
567 |
568 | val xapkFile = context.workDir.resolve("patched.xapk")
569 | xapkFile.delete()
570 |
571 | val zip = ZipFile(xapkFile)
572 | zip.isRunInThread = true
573 | zip.addFiles(files.toMutableList(), ZipParameters().apply {
574 | compressionMethod = CompressionMethod.STORE
575 | })
576 | monitorZipProgress(zip)
577 | zip.close()
578 |
579 | val success = saveFile("patched-${System.currentTimeMillis()}.xapk", xapkFile)
580 | log(
581 | if (success) context.getString(R.string.file_saved)
582 | else context.getString(R.string.failed_to_save_file)
583 | )
584 |
585 | task = context.getString(R.string.cleaning_up)
586 | progress = -1f
587 | xapkFile.delete()
588 |
589 | return success
590 | }
591 |
592 | private fun getAssetDownloadUrl(assets: List