├── .github └── workflows │ └── gradle.yml ├── .gitignore ├── LICENSE ├── README.md ├── artifacts ├── apache-licence-logo.png └── reschiper-banner.png ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main ├── java └── io │ └── github │ └── goldfish07 │ └── reschiper │ └── plugin │ ├── Extension.java │ ├── ResChiper.java │ ├── ResChiperPlugin.java │ ├── android │ ├── AndroidDebugKeyStoreHelper.java │ ├── AndroidLocation.java │ ├── JarSigner.java │ ├── OpenJDKJarSigner.java │ └── PlatformDetector.java │ ├── bundle │ ├── AppBundleAnalyzer.java │ ├── AppBundlePackager.java │ ├── AppBundleSigner.java │ ├── AppBundleUtils.java │ ├── ResourceMapping.java │ └── ResourceTableBuilder.java │ ├── command │ ├── Command.java │ ├── extensions │ │ ├── BundleFileFilter.java │ │ ├── BundleStringFilter.java │ │ └── DuplicateResourceMerger.java │ └── model │ │ ├── DuplicateResMergerCommand.java │ │ ├── FileFilterCommand.java │ │ ├── ObfuscateBundleCommand.java │ │ └── StringFilterCommand.java │ ├── internal │ ├── AGP.java │ ├── Bundle.java │ └── SigningConfig.java │ ├── model │ └── KeyStore.java │ ├── obfuscation │ ├── ResourcesObfuscator.java │ └── StringObfuscator.java │ ├── operations │ ├── FileOperation.java │ ├── NativeLibrariesOperation.java │ └── ResourceTableOperation.java │ ├── parser │ ├── Parser.java │ ├── ResourcesMappingParser.java │ └── xml │ │ ├── FileFilterConfig.java │ │ ├── ResChiperConfig.java │ │ └── StringFilterConfig.java │ ├── tasks │ └── ResChiperTask.java │ └── utils │ ├── FileUtils.java │ ├── TimeClock.java │ └── Utils.java └── resources └── META-INF └── gradle-plugins └── io.github.goldfish07.reschiper.properties /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time 6 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 7 | 8 | name: Java CI with Gradle 9 | 10 | on: 11 | push: 12 | branches: [ "master" ] 13 | pull_request: 14 | branches: [ "master" ] 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | build: 21 | 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - uses: actions/checkout@v3 26 | - name: Set up JDK 17 27 | uses: actions/setup-java@v3 28 | with: 29 | java-version: '17' 30 | distribution: 'temurin' 31 | - name: Build with Gradle 32 | uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0 33 | with: 34 | arguments: build 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | gradle.properties 7 | 8 | ### IntelliJ IDEA ### 9 | .idea/ 10 | *.iws 11 | *.iml 12 | *.ipr 13 | out/ 14 | !**/src/main/**/out/ 15 | !**/src/test/**/out/ 16 | 17 | ### Eclipse ### 18 | .apt_generated 19 | .classpath 20 | .factorypath 21 | .project 22 | .settings 23 | .springBeans 24 | .sts4-cache 25 | bin/ 26 | !**/src/main/**/bin/ 27 | !**/src/test/**/bin/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | 39 | ### Mac OS ### 40 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 goldfish07(Ayush Bisht) 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ResChiper 2 | 3 |

4 | failed to load artifacts/logo.png 5 |

AAB Resource Obfuscation Tool

6 |

7 | 8 | [![License](https://img.shields.io/badge/license-Apache_2.0-maroon)](LICENSE) 9 | ![Android Gradle Plugin](https://img.shields.io/badge/Dependency-AGP/8.8.0-4CAF50) 10 | [![BundleTool](https://img.shields.io/badge/Dependency-Bundletool/1.17.2-red)](https://github.com/google/bundletool) 11 | ![JDK Version](https://img.shields.io/badge/JDK-17-blue) 12 | ![Gradle Version](https://img.shields.io/badge/Gradle_Wrapper-8.8-darkgreen) 13 | [![ResChiper Version](https://img.shields.io/badge/release-0.1.0--rc6-%23C6782A.svg?style=flat)](https://github.com/goldfish07/ResChiper/releases/tag/0.1.0-rc6) 14 | 15 | ## Table of Contents 16 | 17 | - [Introduction](#introduction) 18 | - [Getting Started](#getting-started) 19 | - [Requirements](#requirements) 20 | - [Installation](#installation) 21 | - [Usage](#usage) 22 | - [Configuration Options](#configuration-options) 23 | - [Example](#example) 24 | - [WhiteList](#whitelist) 25 | - [Output](#output) 26 | - [Acknowledgments](#acknowledgments) 27 | - [License](#license) 28 | 29 | ## Introduction 30 | 31 | ResChiper is a tool designed for obfuscating Android AAB resources. 32 | It allows you to protect your resources from unauthorized access and reduce your app's AAB size. 33 | 34 | ## Getting Started 35 | 36 | Follow these steps to integrate the AAB Resource Obfuscation Tool into your Android project: 37 | 38 | ## Requirements 39 | 40 | Before you begin using ResChiper, ensure that your app meets the following requirements: 41 | 42 | - **Java Development Kit (JDK)**: ResChiper requires JDK 17, Make sure your app is configured with JDK 17. 43 | - **Android Gradle Plugin (AGP)**: version 8.0 or later version. 44 | 45 | ## Installation 46 | 47 | #### 1. Add ResChiper Gradle Plugin 48 | 49 | In your project's root-level `build.gradle` file, add the ResChiper Gradle plugin to the `buildscript` section: 50 | 51 | ```gradle 52 | buildscript { 53 | dependencies { 54 | classpath "io.github.goldfish07.reschiper:plugin:" 55 | } 56 | 57 | repositories { 58 | mavenCentral() 59 | google() 60 | } 61 | } 62 | ``` 63 | 64 | #### 2. Apply the Plugin 65 | 66 | In your app-level `build.gradle` file, apply the ResChiper plugin: 67 | 68 | ```gradle 69 | apply plugin: "io.github.goldfish07.reschiper" 70 | ``` 71 | 72 | #### 3. Configure the Plugin 73 | 74 | In your `app/build.gradle` file, configure the ResChiper plugin by specifying your desired settings. Here's an example 75 | configuration: 76 | 77 | ```gradle 78 | resChiper { 79 | enableObfuscation = true //by default res obfuscate is enabled 80 | obfuscationMode = "default" //["dir", "file", "default"] 81 | obfuscatedBundleName = "reschiper-app.aab" // Obfuscated file name, must end with '.aab' 82 | //mappingFile = file("path/to/your/mapping.txt").toPath() // Mapping file used for incremental obfuscation 83 | whiteList = [ 84 | //Whitelist rule (directory name to exclude) 85 | "res/raw", // raw dir will not be obfuscated 86 | "res/xml", // xml dir will not be obfuscated 87 | 88 | //Whitelist rule (file name to exclude) 89 | "res/raw/*", // all files inside raw directory will not be obfuscated 90 | "res/raw/success_tick.json", // success_tick.json file will not be obfuscated 91 | "res/xml/*", // all files inside xml directory will not be obfuscated 92 | 93 | // White list rules (resource name to exclude) 94 | "*.R.raw.*", 95 | "*.R.xml.*", 96 | 97 | // for google-services 98 | "*.R.string.google_api_key", 99 | "*.R.string.google_app_id", 100 | "*.R.string.default_web_client_id", 101 | "*.R.string.gcm_defaultSenderId", 102 | "*.R.string.ga_trackingId", 103 | "*.R.string.firebase_database_url", 104 | "*.R.string.google_crash_reporting_api_key", 105 | "*.R.string.google_storage_bucket", 106 | "*.R.integer.google_play_services_version", 107 | 108 | //firebase 109 | "*.R.string.project_id", 110 | //firebase crashlytics 111 | "*.R.string.com.google.firebase.crashlytics.mapping_file_id", 112 | "*.R.bool.com.crashlytics.useFirebaseAppId", 113 | "*.R.string.com.crashlytics.useFirebaseAppId", 114 | "*.R.string.google_app_id", 115 | "*.R.bool.com.crashlytics.CollectDeviceIdentifiers", 116 | "*.R.string.com.crashlytics.CollectDeviceIdentifiers", 117 | "*.R.bool.com.crashlytics.CollectUserIdentifiers", 118 | "*.R.string.com.crashlytics.CollectUserIdentifiers", 119 | "*.R.string.com.crashlytics.ApiEndpoint", 120 | "*.R.string.com.crashlytics.android.build_id", 121 | "*.R.bool.com.crashlytics.RequireBuildId", 122 | "*.R.string.com.crashlytics.RequireBuildId", 123 | "*.R.bool.com.crashlytics.CollectCustomLogs", 124 | "*.R.string.com.crashlytics.CollectCustomLogs", 125 | "*.R.bool.com.crashlytics.Trace", 126 | "*.R.string.com.crashlytics.Trace", 127 | "*.R.string.com.crashlytics.CollectCustomKeys" 128 | ] 129 | mergeDuplicateResources = true // allow the merge of duplicate resources 130 | enableFileFiltering = true 131 | enableFilterStrings = true 132 | fileFilterList = [ // file filter rules 133 | "META-INF/*", 134 | // "*/armeabi-v7a/*", 135 | // "*/arm64-v8a/*", 136 | // "*/x86/*", 137 | // "*/x86_64/*" 138 | ] 139 | unusedStringFile = "path/to/your/unused_strings.txt" // strings will be filtered in this file 140 | localeWhiteList = ["en", "in", "fr"] //keep en,en-xx,in,in-xx,fr,fr-xx and remove others locale. 141 | } 142 | ``` 143 | 144 | ## Usage 145 | 146 | To obfuscate your resources and generate an obfuscated AAB, run the following Gradle command in the project's root 147 | directory.: 148 | 149 | ```cmd 150 | ./gradle clean :app:resChiperDebug --stacktrace 151 | ``` 152 | 153 | This command will execute the obfuscation process from the project root, and the obfuscated AAB will be generated in 154 | the `app/build/outputs/bundle/debug` directory. 155 | 156 | ## Configuration Options 157 | 158 | The ResChiper extension provides various configuration options for resource obfuscation, including enabling/disabling 159 | obfuscation, specifying mapping files, white-listing resources, and more. 160 | 161 | - `enableObfuscation`: Enable or disable resource obfuscation.
162 | - `obfuscationMode`: to obfuscate only directories set `obfuscationMode = "dir"`, to obfuscate only files set 163 | `obfuscationMode = "file"` and to obfuscate both directory and files set `obfuscationMode = "default"`.
164 | - `enableFilterStrings`: Input the unused file splits by lines to support remove strings.
165 | - `enableFileFiltering`: Support for filtering files in the bundle package. Currently only supports filtering in 166 | the `META-INFO/` and `lib/` paths.
167 | - `obfuscatedBundleName`: Name of the obfuscated AAB file.
168 | - `mergeDuplicateResources`: eliminate duplicate resource files and reduce package size.
169 | - `mappingFile`: Path to the ProGuard mapping file (set only when mapping.txt used for obfuscation).
170 | - `whiteList`: Set of resource names to exclude from obfuscation.
171 | - `fileFilterList`: List of file patterns to filter out.
172 | - `unusedStringFile`: Path to a file containing unused strings.
173 | - `localeWhiteList`: Set of locales to include in the AAB. 174 | 175 | ## Example 176 | 177 | you can check some configuration example [here](https://github.com/goldfish07/ResChiper/wiki/Example-Configuration-Options) 178 | 179 | ## WhiteList 180 | 181 | resources that are not obfuscated during the build process.
182 | you can find whitsList configs [here](https://github.com/goldfish07/ResChiper/wiki/WhiteList). 183 | 184 | ## Output 185 | 186 | After running the obfuscation process, you can expect the following output files: 187 | 188 | - **aab:** This is the obfuscated bundle package, which contains your Android App Bundle (AAB) with obfuscated 189 | resources. 190 | - **resources-mapping.txt:** This file contains the resource obfuscation mapping. It can be used as input for future 191 | obfuscation processes to achieve incremental obfuscation. This is especially useful if you want to maintain 192 | consistency across different builds. 193 | - **-duplicated.txt:** This log file provides information about merged resources. It helps you identify and track any 194 | duplicate resources that were merged during the obfuscation process. 195 | 196 | These output files will be generated as a result of running the ResChiper tool, and you can find them in the relevant 197 | directories within your project's build output. 198 | 199 | ## Acknowledgments 200 | 201 | ResChiper is inspired by the following projects and tools: 202 | 203 | * [AabResGuard](https://github.com/bytedance/AabResGuard/) 204 | * [AndResGuard](https://github.com/shwenzhang/AndResGuard/) 205 | * [BundleTool](https://github.com/google/bundletool) 206 | 207 | ## License 208 | 209 | [![Apache License v2.0 logo](artifacts/apache-licence-logo.png)](https://www.apache.org/licenses/LICENSE-2.0.txt) 210 | 211 | Copyright (C) 2023 goldfish07 (Ayush Bisht) 212 | This file is part of ResChiper. 213 | 214 | ResChiper is free software: you can redistribute it and/or modify 215 | it under the terms of the Apache License, Version 2.0 as published by 216 | the Apache Software Foundation, either version 2.0 of the License, or 217 | (at your option) any later version. 218 | 219 | Licensed under the Apache License, Version 2.0 (the "License"); 220 | you may not use this file except in compliance with the License. 221 | You may obtain a copy of the License at 222 | 223 | http://www.apache.org/licenses/LICENSE-2.0 224 | 225 | Unless required by applicable law or agreed to in writing, software 226 | distributed under the License is distributed on an "AS IS" BASIS, 227 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 228 | See the License for the specific language governing permissions and 229 | limitations under the License. -------------------------------------------------------------------------------- /artifacts/apache-licence-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/goldfish07/ResChiper/68de8eca1f62e184726b09ded83786e128a21295/artifacts/apache-licence-logo.png -------------------------------------------------------------------------------- /artifacts/reschiper-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/goldfish07/ResChiper/68de8eca1f62e184726b09ded83786e128a21295/artifacts/reschiper-banner.png -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | id("maven-publish") 4 | id("signing") 5 | } 6 | 7 | group = "io.github.goldfish07.reschiper" 8 | version = "0.1.0-rc6" 9 | 10 | java { 11 | sourceCompatibility = JavaVersion.VERSION_17 12 | targetCompatibility = JavaVersion.VERSION_17 13 | } 14 | 15 | val sourcesJar by tasks.registering(Jar::class) { 16 | from(sourceSets["main"].allJava) 17 | archiveClassifier.set("sources") 18 | } 19 | 20 | val javadocJar by tasks.registering(Jar::class) { 21 | from(tasks.javadoc) 22 | archiveClassifier.set("javadoc") 23 | } 24 | 25 | repositories { 26 | mavenCentral() 27 | google() 28 | } 29 | 30 | dependencies { 31 | testImplementation(platform("org.junit:junit-bom:5.10.1")) 32 | testImplementation("org.junit.jupiter:junit-jupiter") 33 | 34 | implementation(gradleApi()) 35 | implementation("org.jetbrains:annotations:24.1.0") 36 | implementation("com.android.tools.build:gradle:8.8.0") 37 | implementation("com.android.tools.build:bundletool:1.17.2") 38 | implementation("com.google.guava:guava:32.1.3-jre") 39 | implementation("io.grpc:grpc-protobuf:1.59.1") 40 | implementation("com.android.tools.build:aapt2-proto:8.8.0-12006047") 41 | implementation("commons-codec:commons-codec:1.16.0") 42 | implementation("commons-io:commons-io:2.15.1") 43 | implementation("org.dom4j:dom4j:2.1.4") 44 | implementation("com.google.auto.value:auto-value:1.5.4") 45 | annotationProcessor("com.google.auto.value:auto-value:1.5.4") 46 | } 47 | 48 | tasks.test { 49 | useJUnitPlatform() 50 | } 51 | 52 | publishing { 53 | publications { 54 | create("mavenJava") { 55 | groupId = rootProject.group.toString() 56 | version = rootProject.version.toString() 57 | artifactId = "plugin" 58 | description = "AAB Resource Obfuscation Tool" 59 | from(components["java"]) 60 | artifact(sourcesJar) 61 | artifact(javadocJar) 62 | 63 | pom { 64 | packaging = "jar" 65 | name.set("ResChiper") 66 | description.set("A tool for obfuscating Android AAB resources") 67 | url.set("https://github.com/goldfish07/reschiper") 68 | 69 | licenses { 70 | license { 71 | name.set("Apache License, Version 2.0") 72 | url.set("https://www.apache.org/licenses/LICENSE-2.0.txt") 73 | } 74 | } 75 | developers { 76 | developer { 77 | id.set(project.findProperty("ossrhUsername").toString()) 78 | name.set(project.findProperty("devSimpleName").toString()) 79 | email.set(project.findProperty("devMail").toString()) 80 | } 81 | } 82 | 83 | scm { 84 | connection.set("scm:git:git://github.com/goldfish07/reschiper.git") 85 | developerConnection.set("scm:git:ssh://github.com/goldfish07/reschiper.git") 86 | url.set("https://github.com/goldfish07/reschiper") 87 | } 88 | } 89 | } 90 | } 91 | 92 | repositories { 93 | mavenLocal() 94 | maven { 95 | url = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") 96 | credentials { 97 | username = project.findProperty("ossrhUsername").toString() 98 | password = project.findProperty("ossrhPassword").toString() 99 | } 100 | } 101 | } 102 | } 103 | 104 | signing { 105 | sign(publishing.publications["mavenJava"]) 106 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/goldfish07/ResChiper/68de8eca1f62e184726b09ded83786e128a21295/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Sep 22 19:47:12 IST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original 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 POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "reschiper" 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/Extension.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin; 2 | 3 | import java.nio.file.Path; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Configuration class for customizing the behavior of the ResChiper tool or plugin. 9 | */ 10 | public class Extension { 11 | private boolean enableObfuscation = true; 12 | private String obfuscationMode = "default"; 13 | private boolean enableFileFiltering = false; 14 | private boolean enableFilterStrings = false; 15 | private boolean mergeDuplicateResources = false; 16 | private Path mappingFile = null; 17 | private String obfuscatedBundleName; 18 | private String unusedStringFile = ""; 19 | private Set fileFilterList = new HashSet<>(); 20 | private Set whiteList = new HashSet<>(); 21 | private Set localeWhiteList = new HashSet<>(); 22 | 23 | /** 24 | * Gets whether obfuscation is enabled. 25 | * 26 | * @return {@code true} if obfuscation is enabled; otherwise, {@code false}. 27 | */ 28 | public boolean getEnableObfuscation() { 29 | return enableObfuscation; 30 | } 31 | 32 | /** 33 | * Sets whether obfuscation should be enabled. 34 | * 35 | * @param enableObfuscation {@code true} to enable obfuscation; {@code false} to disable it. 36 | */ 37 | public void setEnableObfuscation(boolean enableObfuscation) { 38 | this.enableObfuscation = enableObfuscation; 39 | } 40 | 41 | /** 42 | * Gets the current resource obfuscation mode. 43 | * 44 | * @return The resource obfuscation mode as a string. 45 | */ 46 | public String getObfuscationMode() { 47 | return obfuscationMode; 48 | } 49 | 50 | /** 51 | * Sets the resource obfuscation mode. 52 | * 53 | * @param obfuscationMode The resource obfuscation mode to set as a string. 54 | */ 55 | public void setObfuscationMode(String obfuscationMode) { 56 | this.obfuscationMode = obfuscationMode; 57 | } 58 | 59 | /** 60 | * Gets whether file filtering is enabled. 61 | * 62 | * @return {@code true} if file filtering is enabled; otherwise, {@code false}. 63 | */ 64 | public boolean getEnableFileFiltering() { 65 | return enableFileFiltering; 66 | } 67 | 68 | /** 69 | * Sets whether file filtering should be enabled. 70 | * 71 | * @param enableFileFiltering {@code true} to enable file filtering; {@code false} to disable it. 72 | */ 73 | public void setEnableFileFiltering(boolean enableFileFiltering) { 74 | this.enableFileFiltering = enableFileFiltering; 75 | } 76 | 77 | /** 78 | * Gets whether string filtering is enabled. 79 | * 80 | * @return {@code true} if string filtering is enabled; otherwise, {@code false}. 81 | */ 82 | public boolean getEnableFilterStrings() { 83 | return enableFilterStrings; 84 | } 85 | 86 | /** 87 | * Sets whether string filtering should be enabled. 88 | * 89 | * @param enableFilterStrings {@code true} to enable string filtering; {@code false} to disable it. 90 | */ 91 | public void setEnableFilterStrings(boolean enableFilterStrings) { 92 | this.enableFilterStrings = enableFilterStrings; 93 | } 94 | 95 | /** 96 | * Gets whether duplicated resources should be merged. 97 | * 98 | * @return {@code true} if duplicated resources should be merged; otherwise, {@code false}. 99 | */ 100 | public boolean getMergeDuplicateResources() { 101 | return mergeDuplicateResources; 102 | } 103 | 104 | /** 105 | * Sets whether duplicated resources should be merged. 106 | * 107 | * @param mergeDuplicateResources {@code true} to merge duplicated resources; {@code false} to keep them separate. 108 | */ 109 | public void setMergeDuplicateResources(boolean mergeDuplicateResources) { 110 | this.mergeDuplicateResources = mergeDuplicateResources; 111 | } 112 | 113 | /** 114 | * Gets the path to the mapping file used for obfuscation. 115 | * 116 | * @return The path to the mapping file. 117 | */ 118 | public Path getMappingFile() { 119 | return mappingFile; 120 | } 121 | 122 | /** 123 | * Sets the path to the mapping file used for obfuscation. 124 | * 125 | * @param mappingFile The path to the mapping file. 126 | */ 127 | public void setMappingFile(Path mappingFile) { 128 | this.mappingFile = mappingFile; 129 | } 130 | 131 | /** 132 | * Gets the name of the obfuscated bundle file. 133 | * 134 | * @return The name of the obfuscated bundle file. 135 | */ 136 | public String getObfuscatedBundleName() { 137 | return obfuscatedBundleName; 138 | } 139 | 140 | /** 141 | * Sets the name of the obfuscated bundle file. 142 | * 143 | * @param obfuscatedBundleName The name of the obfuscated bundle file. 144 | */ 145 | public void setObfuscatedBundleName(String obfuscatedBundleName) { 146 | this.obfuscatedBundleName = obfuscatedBundleName; 147 | } 148 | 149 | /** 150 | * Gets the path to the file containing unused strings. 151 | * 152 | * @return The path to the unused string file. 153 | */ 154 | public String getUnusedStringFile() { 155 | return unusedStringFile; 156 | } 157 | 158 | /** 159 | * Sets the path to the file containing unused strings. 160 | * 161 | * @param unusedStringFile The path to the unused string file. 162 | */ 163 | public void setUnusedStringFile(String unusedStringFile) { 164 | this.unusedStringFile = unusedStringFile; 165 | } 166 | 167 | /** 168 | * Gets the list of filters for files. 169 | * 170 | * @return A set of file filters. 171 | */ 172 | public Set getFileFilterList() { 173 | return fileFilterList; 174 | } 175 | 176 | /** 177 | * Sets the list of filters for files. 178 | * 179 | * @param fileFilterList A set of file filters to apply. 180 | */ 181 | public void setFileFilterList(Set fileFilterList) { 182 | this.fileFilterList = fileFilterList; 183 | } 184 | 185 | /** 186 | * Gets the whitelist of locales. 187 | * 188 | * @return A set of locale identifiers that are whitelisted. 189 | */ 190 | public Set getLocaleWhiteList() { 191 | return localeWhiteList; 192 | } 193 | 194 | /** 195 | * Sets the whitelist of locales. 196 | * 197 | * @param localeWhiteList A set of locale identifiers to whitelist. 198 | */ 199 | public void setLocaleWhiteList(Set localeWhiteList) { 200 | this.localeWhiteList = localeWhiteList; 201 | } 202 | 203 | /** 204 | * Gets the whitelist of resources. 205 | * 206 | * @return A set of resource names that are whitelisted. 207 | */ 208 | public Set getWhiteList() { 209 | return whiteList; 210 | } 211 | 212 | /** 213 | * Sets the whitelist of resources. 214 | * 215 | * @param whiteList A set of resource names to whitelist. 216 | */ 217 | public void setWhiteList(Set whiteList) { 218 | this.whiteList = whiteList; 219 | } 220 | 221 | /** 222 | * Provides a formatted string representation of the configuration options. 223 | * 224 | * @return A formatted string containing the configuration details. 225 | */ 226 | @Override 227 | public String toString() { 228 | return "-------------- Extension --------------\n" + 229 | "\tenableObfuscation=" + enableObfuscation + "\n" + 230 | "\tobfuscationMode=" + obfuscationMode + "\n" + 231 | "\tenableFileFiltering=" + enableFileFiltering + "\n" + 232 | "\tenableFilterStrings=" + enableFilterStrings + "\n" + 233 | "\tmergeDuplicateResources=" + mergeDuplicateResources + "\n" + 234 | "\tmappingFile=" + mappingFile + "\n" + 235 | "\tobfuscatedBundleName=" + obfuscatedBundleName + "\n" + 236 | "\tunusedStringFile=" + unusedStringFile + "\n" + 237 | "\tfileFilterList=" + fileFilterList + "\n" + 238 | "\tlocaleWhiteList=" + localeWhiteList + "\n" + 239 | "\twhiteList=" + whiteList + "\n"; 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/ResChiper.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin; 2 | 3 | /** 4 | * Main class for the ResChiper command-line tool. 5 | */ 6 | public class ResChiper { 7 | public static final String VERSION = "0.1.0-rc6"; 8 | public static final String BT_VERSION = "1.17.2"; 9 | public static final String AGP_VERSION = "8.8.0"; 10 | public static final String GRADLE_WRAPPER_VERSION = "8.8"; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/ResChiperPlugin.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin; 2 | 3 | import com.android.build.gradle.AppExtension; 4 | import com.android.build.gradle.api.ApplicationVariant; 5 | import io.github.goldfish07.reschiper.plugin.internal.AGP; 6 | import io.github.goldfish07.reschiper.plugin.tasks.ResChiperTask; 7 | import org.gradle.api.GradleException; 8 | import org.gradle.api.Plugin; 9 | import org.gradle.api.Project; 10 | import org.gradle.api.Task; 11 | import org.jetbrains.annotations.NotNull; 12 | 13 | /** 14 | * Plugin for integrating ResChiper into an Android Gradle project. 15 | */ 16 | public class ResChiperPlugin implements Plugin { 17 | 18 | @Override 19 | public void apply(@NotNull Project project) { 20 | checkApplicationPlugin(project); 21 | AppExtension android = (AppExtension) project.getExtensions().getByName("android"); 22 | project.getExtensions().create("resChiper", Extension.class); 23 | project.afterEvaluate(project1 -> android.getApplicationVariants().all(variant -> createResChiperTask(project1, variant))); 24 | } 25 | 26 | /** 27 | * Creates a ResChiper task for the given variant. 28 | * 29 | * @param project The Gradle project. 30 | * @param variant The Android application variant. 31 | */ 32 | private void createResChiperTask(@NotNull Project project, @NotNull ApplicationVariant variant) { 33 | String variantName = variant.getName().substring(0, 1).toUpperCase() + variant.getName().substring(1); 34 | String bundleTaskName = "bundle" + variantName; 35 | if (project.getTasks().findByName(bundleTaskName) == null) 36 | return; 37 | String taskName = "resChiper" + variantName; 38 | ResChiperTask resChiperTask; 39 | if (project.getTasks().findByName(taskName) == null) 40 | resChiperTask = project.getTasks().create(taskName, ResChiperTask.class); 41 | else 42 | resChiperTask = (ResChiperTask) project.getTasks().getByName(taskName); 43 | 44 | resChiperTask.setVariantScope(variant); 45 | resChiperTask.doFirst(task -> { 46 | printResChiperBuildConfiguration(); 47 | printProjectBuildConfiguration(project); 48 | }); 49 | 50 | Task bundleTask = project.getTasks().getByName(bundleTaskName); 51 | Task bundlePackageTask = project.getTasks().getByName("package" + variantName + "Bundle"); 52 | bundleTask.dependsOn(resChiperTask); 53 | resChiperTask.dependsOn(bundlePackageTask); 54 | 55 | String finalizeBundleTaskName = "sign" + variantName + "Bundle"; 56 | if (project.getTasks().findByName(finalizeBundleTaskName) != null) 57 | resChiperTask.dependsOn(project.getTasks().getByName(finalizeBundleTaskName)); 58 | } 59 | 60 | /** 61 | * Checks if the Android Application plugin is applied to the project. 62 | * 63 | * @param project The Gradle project. 64 | */ 65 | private void checkApplicationPlugin(@NotNull Project project) { 66 | if (!project.getPlugins().hasPlugin("com.android.application")) 67 | throw new GradleException("Android Application plugin 'com.android.application' is required"); 68 | } 69 | 70 | /** 71 | * Prints the ResChiper build configuration information. 72 | */ 73 | private void printResChiperBuildConfiguration() { 74 | System.out.println("----------------------------------------"); 75 | System.out.println(" ResChiper Plugin Configuration:"); 76 | System.out.println("----------------------------------------"); 77 | System.out.println("- ResChiper version:\t" + ResChiper.VERSION); 78 | System.out.println("- BundleTool version:\t" + ResChiper.BT_VERSION); 79 | System.out.println("- AGP version:\t\t" + ResChiper.AGP_VERSION); 80 | System.out.println("- Gradle Wrapper:\t" + ResChiper.GRADLE_WRAPPER_VERSION); 81 | } 82 | 83 | /** 84 | * Prints the project's build information. 85 | * 86 | * @param project The Android Gradle project. 87 | */ 88 | private void printProjectBuildConfiguration(@NotNull Project project) { 89 | System.out.println("----------------------------------------"); 90 | System.out.println(" App Build Information:"); 91 | System.out.println("----------------------------------------"); 92 | System.out.println("- Project name:\t\t\t" + project.getRootProject().getName()); 93 | System.out.println("- AGP version:\t\t\t" + AGP.getAGPVersion(project)); 94 | System.out.println("- Running Gradle version:\t" + project.getGradle().getGradleVersion()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/android/AndroidDebugKeyStoreHelper.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.android; 2 | 3 | import org.jetbrains.annotations.Nullable; 4 | 5 | import java.io.File; 6 | import java.nio.file.Path; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | 10 | /** 11 | * Helper class for managing the Android debug keystore and its configurations. 12 | */ 13 | public class AndroidDebugKeyStoreHelper { 14 | 15 | public static final String DEFAULT_PASSWORD = "android"; 16 | public static final String DEFAULT_ALIAS = "AndroidDebugKey"; 17 | private static final Logger logger = Logger.getLogger(AndroidDebugKeyStoreHelper.class.getName()); 18 | 19 | /** 20 | * Retrieves the debug signing configuration for Android. 21 | * 22 | * @return The debug signing configuration as a {@link JarSigner.Signature} object, or null if the keystore is not found. 23 | */ 24 | public static @Nullable JarSigner.Signature debugSigningConfig() { 25 | String debugKeystoreLocation = defaultDebugKeystoreLocation(); 26 | if (debugKeystoreLocation == null || !new File(debugKeystoreLocation).exists()) 27 | return null; 28 | return new JarSigner.Signature( 29 | Path.of(debugKeystoreLocation), 30 | DEFAULT_PASSWORD, 31 | DEFAULT_ALIAS, 32 | DEFAULT_PASSWORD 33 | ); 34 | } 35 | 36 | /** 37 | * Returns the location of the default debug keystore. 38 | * 39 | * @return The location of the default debug keystore, or null if an error occurs. 40 | */ 41 | private static @Nullable String defaultDebugKeystoreLocation() { 42 | try { 43 | String folder = AndroidLocation.getFolder(); 44 | return folder + "debug.keystore"; 45 | } catch (AndroidLocation.AndroidLocationException e) { 46 | logger.log(Level.SEVERE, "Error getting keystore folder", e); 47 | return null; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/android/AndroidLocation.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.android; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.io.File; 7 | import java.io.Serial; 8 | 9 | /** 10 | * Manages the location of Android files, including emulator files, ddms config, and the debug keystore. 11 | */ 12 | public class AndroidLocation { 13 | 14 | /** 15 | * The name of the `.android` folder returned by {@link #getFolder}. 16 | */ 17 | public static final String FOLDER_DOT_ANDROID = ".android"; 18 | 19 | /** 20 | * Virtual Device folder inside the path returned by {@link #getFolder}. 21 | */ 22 | public static final String FOLDER_AVD = "avd"; 23 | 24 | private static String sPrefsLocation = null; 25 | private static String sAvdLocation = null; 26 | 27 | /** 28 | * Returns the folder used to store Android-related files. 29 | * If the folder does not exist yet, it will be created. 30 | * 31 | * @return An OS-specific path, terminated by a separator. 32 | * @throws AndroidLocationException If an error occurs while creating the folder. 33 | */ 34 | public static String getFolder() throws AndroidLocationException { 35 | if (sPrefsLocation == null) { 36 | sPrefsLocation = findHomeFolder(); 37 | } 38 | // Ensure the folder exists 39 | File f = new File(sPrefsLocation); 40 | if (!f.exists()) 41 | try { 42 | f.mkdirs(); 43 | } catch (SecurityException e) { 44 | AndroidLocationException ale = new AndroidLocationException(String.format( 45 | "Unable to create folder '%1$s'. " + 46 | "This is the path of the preference folder expected by the Android tools.", 47 | sPrefsLocation)); 48 | ale.initCause(e); 49 | throw ale; 50 | } 51 | else if (f.isFile()) 52 | throw new AndroidLocationException(String.format("%1$s is not a directory!\n" + 53 | "This is the path of the preference folder expected by the Android tools.", sPrefsLocation)); 54 | return sPrefsLocation; 55 | } 56 | 57 | /** 58 | * Returns the folder used to store Android-related files. 59 | * This method will not create the folder if it doesn't exist yet. 60 | * 61 | * @return An OS-specific path, terminated by a separator, or null if no path is found or an error occurs. 62 | */ 63 | public static @Nullable String getFolderWithoutWrites() { 64 | if (sPrefsLocation == null) { 65 | try { 66 | sPrefsLocation = findHomeFolder(); 67 | } catch (AndroidLocationException e) { 68 | return null; 69 | } 70 | } 71 | return sPrefsLocation; 72 | } 73 | 74 | /** 75 | * Check if ANDROID_SDK_HOME variable points to an SDK. 76 | * 77 | * @throws AndroidLocationException If ANDROID_SDK_HOME is not correctly set. 78 | */ 79 | public static void checkAndroidSdkHome() throws AndroidLocationException { 80 | Global.ANDROID_SDK_HOME.validatePath(false); 81 | } 82 | 83 | /** 84 | * Returns the folder where the users AVDs are stored. 85 | * 86 | * @return An OS-specific path, terminated by a separator. 87 | * @throws AndroidLocationException If an error occurs while obtaining the AVD folder path. 88 | */ 89 | public static String getAvdFolder() throws AndroidLocationException { 90 | if (sAvdLocation == null) { 91 | sAvdLocation = findValidPath(Global.ANDROID_AVD_HOME); 92 | if (!sAvdLocation.endsWith(File.separator)) 93 | sAvdLocation += File.separator; 94 | } 95 | return sAvdLocation; 96 | } 97 | 98 | /** 99 | * Returns the user's home folder. 100 | * 101 | * @return An OS-specific path, terminated by a separator. 102 | * @throws AndroidLocationException If an error occurs while obtaining the user's home folder path. 103 | */ 104 | public static @NotNull String getUserHomeFolder() throws AndroidLocationException { 105 | return findValidPath(Global.TEST_TMPDIR, Global.USER_HOME, Global.HOME); 106 | } 107 | 108 | private static @NotNull String findHomeFolder() throws AndroidLocationException { 109 | String home = findValidPath(Global.ANDROID_SDK_HOME, Global.TEST_TMPDIR, Global.USER_HOME, Global.HOME); 110 | // If the above failed, we throw an exception. 111 | if (!home.endsWith(File.separator)) 112 | home += File.separator; 113 | return home + FOLDER_DOT_ANDROID + File.separator; 114 | } 115 | 116 | /** 117 | * Resets the folder used to store Android-related files. For testing. 118 | */ 119 | public static void resetFolder() { 120 | sPrefsLocation = null; 121 | sAvdLocation = null; 122 | } 123 | 124 | /** 125 | * Checks a list of system properties and/or system environment variables for validity 126 | * and returns the first one. 127 | * 128 | * @param vars The variables to check, Order does matter. 129 | * @return The content of the first property/variable that is a valid directory. 130 | * @throws AndroidLocationException If no valid path is found. 131 | */ 132 | private static @NotNull String findValidPath(Global @NotNull ... vars) throws AndroidLocationException { 133 | for (Global var : vars) { 134 | String path = var.validatePath(true); 135 | if (path != null) 136 | return path; 137 | } 138 | throw new AndroidLocationException("No valid path found."); 139 | } 140 | 141 | /** 142 | * Enum describing which variables to check and whether they should 143 | * be checked via {@link System#getProperty(String)} or {@link System#getenv()} or both. 144 | */ 145 | private enum Global { 146 | ANDROID_AVD_HOME("ANDROID_AVD_HOME", true, true), // both sys prop and env var 147 | ANDROID_SDK_HOME("ANDROID_SDK_HOME", true, true), // both sys prop and env var 148 | TEST_TMPDIR("TEST_TMPDIR", false, true), // Bazel kludge 149 | USER_HOME("user.home", true, false), // sys prop only 150 | HOME("HOME", false, true); // env var only 151 | 152 | final String mName; 153 | final boolean mIsSysProp; 154 | final boolean mIsEnvVar; 155 | 156 | Global(String name, boolean isSysProp, boolean isEnvVar) { 157 | mName = name; 158 | mIsSysProp = isSysProp; 159 | mIsEnvVar = isEnvVar; 160 | } 161 | 162 | private static boolean isSdkRootWithoutDotAndroid(File folder) { 163 | return subFolderExist(folder, "platforms") && 164 | subFolderExist(folder, "platform-tools") && 165 | !subFolderExist(folder, FOLDER_DOT_ANDROID); 166 | } 167 | 168 | private static boolean subFolderExist(File folder, String subFolder) { 169 | return new File(folder, subFolder).isDirectory(); 170 | } 171 | 172 | public @Nullable String validatePath(boolean silent) throws AndroidLocationException { 173 | String path; 174 | if (mIsSysProp) { 175 | path = checkPath(System.getProperty(mName), silent); 176 | if (path != null) 177 | return path; 178 | } 179 | if (mIsEnvVar) { 180 | path = checkPath(System.getenv(mName), silent); 181 | return path; 182 | } 183 | return null; 184 | } 185 | 186 | private String checkPath(String path, boolean silent) throws AndroidLocationException { 187 | if (path == null) 188 | return null; 189 | File file = new File(path); 190 | if (!file.isDirectory()) 191 | return null; 192 | if (!(this == ANDROID_SDK_HOME && isSdkRootWithoutDotAndroid(file))) 193 | return path; 194 | if (!silent) 195 | throw new AndroidLocationException(String.format( 196 | """ 197 | ANDROID_SDK_HOME is set to the root of your SDK: %1$s 198 | This is the path of the preference folder expected by the Android tools. 199 | It should NOT be set to the same as the root of your SDK. 200 | Please set it to a different folder or do not set it at all. 201 | If this is not set we default to: %2$s""", 202 | path, findValidPath(TEST_TMPDIR, USER_HOME, HOME))); 203 | return null; 204 | } 205 | } 206 | 207 | /** 208 | * Exception thrown when the location of the Android folder couldn't be found. 209 | */ 210 | public static final class AndroidLocationException extends Exception { 211 | @Serial 212 | private static final long serialVersionUID = 1L; 213 | 214 | public AndroidLocationException(String string) { 215 | super(string); 216 | } 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/android/JarSigner.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.android; 2 | 3 | import com.android.tools.build.bundletool.flags.Flag; 4 | import com.android.tools.build.bundletool.model.exceptions.CommandExecutionException; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.nio.file.Path; 9 | import java.util.Optional; 10 | 11 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 12 | 13 | /** 14 | * This class provides functionality for signing JAR files in an Android context. 15 | */ 16 | public class JarSigner { 17 | 18 | /** 19 | * Signs the specified file using the provided signature information. 20 | * 21 | * @param toBeSigned The file to be signed. 22 | * @param signature The signature information. 23 | * @throws IOException If an I/O error occurs while signing the file. 24 | * @throws InterruptedException If the signing process is interrupted. 25 | */ 26 | public void sign(File toBeSigned, Signature signature) throws IOException, InterruptedException { 27 | new OpenJDKJarSigner().sign(toBeSigned, signature); 28 | } 29 | 30 | /** 31 | * Represents the signature information for signing JAR files. 32 | */ 33 | public record Signature(Path storeFile, String storePassword, String keyAlias, String keyPassword) { 34 | /** 35 | * A constant representing the default debug signature configuration. 36 | */ 37 | public static final Signature DEBUG_SIGNATURE = AndroidDebugKeyStoreHelper.debugSigningConfig(); 38 | 39 | /** 40 | * Constructs a Signature object with the provided information. 41 | * 42 | * @param storeFile The path to the keystore file. 43 | * @param storePassword The password for the keystore. 44 | * @param keyAlias The alias for the key. 45 | * @param keyPassword The password for the key. 46 | */ 47 | public Signature(Path storeFile, String storePassword, String keyAlias, String keyPassword) { 48 | this.storeFile = storeFile; 49 | this.storePassword = storePassword; 50 | this.keyAlias = keyAlias; 51 | this.keyPassword = keyPassword; 52 | checkFileExistsAndReadable(storeFile); 53 | checkStringIsEmpty(storePassword, "storePassword"); 54 | checkStringIsEmpty(keyAlias, "keyAlias"); 55 | checkStringIsEmpty(keyPassword, "keyPassword"); 56 | } 57 | } 58 | 59 | /** 60 | * Checks if the specified flag is present (not null) and throws an exception if it's not. 61 | * 62 | * @param object The object to check for presence. 63 | * @param flag The flag being checked. 64 | * @throws CommandExecutionException If the flag is not present. 65 | */ 66 | public static void checkFlagPresent(Object object, Flag flag) { 67 | Optional.ofNullable(object) 68 | .orElseThrow(() -> CommandExecutionException.builder() 69 | .withInternalMessage("Wrong properties: %s can not be empty", flag) 70 | .build()); 71 | } 72 | 73 | /** 74 | * Checks if the specified string value is empty (null or consists only of whitespace) and throws an exception if it is. 75 | * 76 | * @param value The string value to check. 77 | * @param name The name of the property being checked. 78 | * @throws IllegalArgumentException If the string value is empty. 79 | */ 80 | public static void checkStringIsEmpty(String value, String name) { 81 | if (value == null || value.trim().isEmpty()) 82 | throw new IllegalArgumentException(String.format("Wrong properties: %s can not be empty", name)); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/android/OpenJDKJarSigner.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.android; 2 | 3 | import com.google.common.base.Joiner; 4 | import io.github.goldfish07.reschiper.plugin.utils.FileUtils; 5 | import org.jetbrains.annotations.Contract; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.logging.Logger; 14 | 15 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 16 | 17 | public class OpenJDKJarSigner { 18 | 19 | private static final String jarSignerExec = PlatformDetector.currentPlatform() == PlatformDetector.PLATFORM_WINDOWS 20 | ? "jarsigner.exe" : "jarsigner"; 21 | private static final Logger logger = Logger.getLogger(OpenJDKJarSigner.class.getName()); 22 | 23 | public void sign(@NotNull File toBeSigned, JarSigner.@NotNull Signature signature) throws IOException, InterruptedException { 24 | checkFileExistsAndReadable(toBeSigned.toPath()); 25 | checkFileExistsAndReadable(signature.storeFile()); 26 | File jarSigner = locatedJarSigner(); 27 | List args = new ArrayList<>(); 28 | if (jarSigner != null) 29 | args.add(jarSigner.getAbsolutePath()); 30 | else 31 | args.add(jarSignerExec); 32 | args.add("-keystore"); 33 | args.add(signature.storeFile().toFile().getAbsolutePath()); 34 | File keyStorePasswordFile = null; 35 | File aliasPasswordFile = null; 36 | // write passwords to a file, so it cannot be spied on. 37 | if (signature.storePassword() != null) { 38 | keyStorePasswordFile = File.createTempFile("store", "prv"); 39 | FileUtils.writeToFile(keyStorePasswordFile, signature.storePassword()); 40 | args.add("-storepass:file"); 41 | args.add(keyStorePasswordFile.getAbsolutePath()); 42 | } 43 | if (signature.keyPassword() != null) { 44 | aliasPasswordFile = File.createTempFile("alias", "prv"); 45 | FileUtils.writeToFile(aliasPasswordFile, signature.keyPassword()); 46 | args.add("--keypass:file"); 47 | args.add(aliasPasswordFile.getAbsolutePath()); 48 | } 49 | args.add(toBeSigned.getAbsolutePath()); 50 | if (signature.keyAlias() != null) 51 | args.add(signature.keyAlias()); 52 | File errorLog = File.createTempFile("error", ".log"); 53 | File outputLog = File.createTempFile("output", ".log"); 54 | logger.fine("Invoking " + Joiner.on(" ").join(args)); 55 | Process process = start(new ProcessBuilder(args).redirectError(errorLog).redirectOutput(outputLog)); 56 | int exitCode = process.waitFor(); 57 | if (exitCode != 0) { 58 | String errors = FileUtils.loadFileWithUnixLineSeparators(errorLog); 59 | String output = FileUtils.loadFileWithUnixLineSeparators(outputLog); 60 | throw new RuntimeException( 61 | String.format("%s failed with exit code %d: \n %s", 62 | jarSignerExec, exitCode, 63 | errors.trim().isEmpty() ? output : errors 64 | ) 65 | ); 66 | } 67 | if (keyStorePasswordFile != null) 68 | keyStorePasswordFile.delete(); 69 | if (aliasPasswordFile != null) 70 | aliasPasswordFile.delete(); 71 | } 72 | 73 | @Contract("_ -> new") 74 | private Process start(@NotNull ProcessBuilder builder) throws IOException { 75 | return builder.start(); 76 | } 77 | 78 | /** 79 | * Return the "jarsigner" tool location or null if it cannot be determined. 80 | */ 81 | private @Nullable File locatedJarSigner() { 82 | // Look in the java.home bin folder, on jdk installations or Mac OS X, this is where the 83 | // jarsigner will be located. 84 | File javaHome = new File(System.getProperty("java.home")); 85 | File jarSigner = getJarSigner(javaHome); 86 | if (jarSigner.exists()) 87 | return jarSigner; 88 | else { 89 | // if not in java.home bin, it's probable that the java.home points to a JRE 90 | // installation, we should then look one folder up and in the bin folder. 91 | jarSigner = getJarSigner(javaHome.getParentFile()); 92 | // if still can't find it, give up. 93 | return jarSigner.exists() ? jarSigner : null; 94 | } 95 | } 96 | 97 | /** 98 | * Returns the jarsigner tool location with the bin folder. 99 | */ 100 | @Contract("_ -> new") 101 | private @NotNull File getJarSigner(File parentDir) { 102 | return new File(new File(parentDir, "bin"), jarSignerExec); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/android/PlatformDetector.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.android; 2 | 3 | /** 4 | * Utility class for detecting the current platform/operating system. 5 | */ 6 | public class PlatformDetector { 7 | 8 | /** 9 | * Constant representing an unknown platform. 10 | */ 11 | public static final int PLATFORM_UNKNOWN = 0; 12 | 13 | /** 14 | * Constant representing the Linux platform. 15 | */ 16 | public static final int PLATFORM_LINUX = 1; 17 | 18 | /** 19 | * Constant representing the Windows platform. 20 | */ 21 | public static final int PLATFORM_WINDOWS = 2; 22 | 23 | /** 24 | * Constant representing the macOS (Darwin) platform. 25 | */ 26 | public static final int PLATFORM_DARWIN = 3; 27 | 28 | /** 29 | * Detects and returns the current platform/operating system. 30 | * 31 | * @return An integer representing the current platform: 32 | * - {@link #PLATFORM_UNKNOWN} if the platform cannot be determined. 33 | * - {@link #PLATFORM_LINUX} if the platform is Linux. 34 | * - {@link #PLATFORM_WINDOWS} if the platform is Windows. 35 | * - {@link #PLATFORM_DARWIN} if the platform is macOS (Darwin). 36 | */ 37 | public static int currentPlatform() { 38 | String os = System.getProperty("os.name"); 39 | if (os.startsWith("Mac OS")) 40 | return PLATFORM_DARWIN; 41 | else if (os.startsWith("Windows")) 42 | return PLATFORM_WINDOWS; 43 | else if (os.startsWith("Linux")) 44 | return PLATFORM_LINUX; 45 | return PLATFORM_UNKNOWN; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/AppBundleAnalyzer.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import com.android.tools.build.bundletool.model.AppBundle; 4 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 5 | 6 | import java.io.IOException; 7 | import java.nio.file.Path; 8 | import java.util.zip.ZipFile; 9 | 10 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 11 | 12 | /** 13 | * Utility class for analyzing Android App Bundles (AABs). 14 | */ 15 | public class AppBundleAnalyzer { 16 | 17 | private final Path bundlePath; 18 | 19 | /** 20 | * Constructs an AppBundleAnalyzer with the provided AAB file path. 21 | * 22 | * @param bundlePath The path to the Android App Bundle (AAB) file. 23 | * @throws IllegalArgumentException If the provided file path does not exist or is not readable. 24 | */ 25 | public AppBundleAnalyzer(Path bundlePath) { 26 | checkFileExistsAndReadable(bundlePath); 27 | this.bundlePath = bundlePath; 28 | } 29 | 30 | /** 31 | * Analyzes the Android App Bundle (AAB) file and returns the parsed AppBundle. 32 | * 33 | * @return The parsed AppBundle. 34 | * @throws IOException If an I/O error occurs while analyzing the AAB file. 35 | */ 36 | public AppBundle analyze() throws IOException { 37 | TimeClock timeClock = new TimeClock(); 38 | ZipFile bundleZip = new ZipFile(bundlePath.toFile()); 39 | AppBundle appBundle = AppBundle.buildFromZip(bundleZip); 40 | System.out.printf("Analysis of the bundle file completed, took %s%n", timeClock.getElapsedTime()); 41 | return appBundle; 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/AppBundlePackager.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import com.android.tools.build.bundletool.io.AppBundleSerializer; 4 | import com.android.tools.build.bundletool.model.AppBundle; 5 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 6 | 7 | import java.io.IOException; 8 | import java.nio.file.Path; 9 | 10 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileDoesNotExist; 11 | 12 | /** 13 | * Utility class for packaging an Android App Bundle (AAB) and writing it to an output file. 14 | */ 15 | public class AppBundlePackager { 16 | private final Path output; 17 | private final AppBundle appBundle; 18 | 19 | /** 20 | * Constructs an AppBundlePackager with the provided AppBundle and output path. 21 | * 22 | * @param appBundle The Android App Bundle (AAB) to package and write. 23 | * @param output The path to the output file where the packaged AAB will be written. 24 | * @throws IllegalArgumentException If the output file already exists. 25 | */ 26 | public AppBundlePackager(AppBundle appBundle, Path output) { 27 | this.output = output; 28 | this.appBundle = appBundle; 29 | checkFileDoesNotExist(output); 30 | } 31 | 32 | /** 33 | * Executes the packaging of the Android App Bundle (AAB) and writes it to the output file. 34 | * 35 | * @throws IOException If an I/O error occurs during packaging or writing. 36 | */ 37 | public void execute() throws IOException { 38 | System.out.println( 39 | """ 40 | ---------------------------------------- 41 | Resource Packaging: 42 | ---------------------------------------- 43 | - Packaging the bundle..."""); 44 | TimeClock timeClock = new TimeClock(); 45 | AppBundleSerializer appBundleSerializer = new AppBundleSerializer(); 46 | appBundleSerializer.writeToDisk(appBundle, output); 47 | System.out.printf("- Packaging completed in: %s%n\n", timeClock.getElapsedTime()); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/AppBundleSigner.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import io.github.goldfish07.reschiper.plugin.android.JarSigner; 4 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 5 | 6 | import java.io.IOException; 7 | import java.nio.file.Path; 8 | 9 | /** 10 | * Utility class for signing an Android App Bundle (AAB) using a JarSigner. 11 | */ 12 | public class AppBundleSigner { 13 | 14 | private final Path bundleFile; 15 | private JarSigner.Signature bundleSignature = JarSigner.Signature.DEBUG_SIGNATURE; 16 | 17 | /** 18 | * Constructs an AppBundleSigner with the provided AAB file path and signature. 19 | * 20 | * @param bundleFile The path to the Android App Bundle (AAB) file to sign. 21 | * @param signature The signature to use for signing the AAB. 22 | */ 23 | public AppBundleSigner(Path bundleFile, JarSigner.Signature signature) { 24 | this.bundleFile = bundleFile; 25 | this.bundleSignature = signature; 26 | } 27 | 28 | /** 29 | * Constructs an AppBundleSigner with the provided AAB file path. 30 | * 31 | * @param bundleFile The path to the Android App Bundle (AAB) file to sign. 32 | */ 33 | public AppBundleSigner(Path bundleFile) { 34 | this.bundleFile = bundleFile; 35 | } 36 | 37 | /** 38 | * Sets the signature to use for signing the AAB. 39 | * 40 | * @param bundleSignature The signature to use for signing the AAB. 41 | */ 42 | public void setBundleSignature(JarSigner.Signature bundleSignature) { 43 | this.bundleSignature = bundleSignature; 44 | } 45 | 46 | /** 47 | * Executes the signing of the Android App Bundle (AAB) using the specified JarSigner signature. 48 | * 49 | * @throws IOException If an I/O error occurs during the signing process. 50 | * @throws InterruptedException If the signing process is interrupted. 51 | */ 52 | public void execute() throws IOException, InterruptedException { 53 | if (bundleSignature == null) 54 | return; 55 | System.out.println( 56 | """ 57 | ---------------------------------------- 58 | Signing: 59 | ---------------------------------------- 60 | - Signing the bundle..."""); 61 | TimeClock timeClock = new TimeClock(); 62 | JarSigner.Signature signature = new JarSigner.Signature( 63 | bundleSignature.storeFile(), 64 | bundleSignature.storePassword(), 65 | bundleSignature.keyAlias(), 66 | bundleSignature.keyPassword() 67 | ); 68 | new JarSigner().sign(bundleFile.toFile(), signature); 69 | System.out.printf("- Signing completed in %s%n\n", timeClock.getElapsedTime()); 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/AppBundleUtils.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import com.android.tools.build.bundletool.model.BundleModule; 4 | import com.android.tools.build.bundletool.model.ModuleEntry; 5 | import com.android.tools.build.bundletool.model.ResourceTableEntry; 6 | import com.android.tools.build.bundletool.model.ZipPath; 7 | import com.android.tools.build.bundletool.model.utils.ZipUtils; 8 | import io.github.goldfish07.reschiper.plugin.operations.FileOperation; 9 | import org.apache.commons.codec.digest.DigestUtils; 10 | import org.jetbrains.annotations.NotNull; 11 | 12 | import java.io.IOException; 13 | import java.util.zip.ZipEntry; 14 | import java.util.zip.ZipFile; 15 | 16 | /** 17 | * Utility methods for working with Android App Bundles (AABs). 18 | */ 19 | public class AppBundleUtils { 20 | 21 | /** 22 | * Get the size of a specific entry within the AAB. 23 | * 24 | * @param bundleZipFile The AAB as a ZipFile. 25 | * @param entry The ModuleEntry for the entry. 26 | * @param bundleModule The BundleModule containing the entry. 27 | * @return The size of the entry in bytes. 28 | */ 29 | public static long getZipEntrySize(@NotNull ZipFile bundleZipFile, @NotNull ModuleEntry entry, @NotNull BundleModule bundleModule) { 30 | String path = String.format("%s/%s", bundleModule.getName().getName(), entry.getPath().toString()); 31 | ZipEntry bundleConfigEntry = bundleZipFile.getEntry(path); 32 | return FileOperation.getZipPathFileSize(bundleZipFile, bundleConfigEntry); 33 | } 34 | 35 | /** 36 | * Get the size of a specific entry within the AAB. 37 | * 38 | * @param bundleZipFile The AAB as a ZipFile. 39 | * @param zipPath The ZipPath of the entry. 40 | * @return The size of the entry in bytes. 41 | */ 42 | public static long getZipEntrySize(@NotNull ZipFile bundleZipFile, @NotNull ZipPath zipPath) { 43 | String path = zipPath.toString(); 44 | ZipEntry bundleConfigEntry = bundleZipFile.getEntry(path); 45 | return FileOperation.getZipPathFileSize(bundleZipFile, bundleConfigEntry); 46 | } 47 | 48 | /** 49 | * Get the MD5 hash of a specific entry within the AAB. 50 | * 51 | * @param bundleZipFile The AAB as a ZipFile. 52 | * @param entry The ModuleEntry for the entry. 53 | * @param bundleModule The BundleModule containing the entry. 54 | * @return The MD5 hash as a hexadecimal string. 55 | */ 56 | public static @NotNull String getEntryMd5(@NotNull ZipFile bundleZipFile, @NotNull ModuleEntry entry, @NotNull BundleModule bundleModule) { 57 | String path = String.format("%s/%s", bundleModule.getName().getName(), entry.getPath().toString()); 58 | ZipEntry bundleConfigEntry = bundleZipFile.getEntry(path); 59 | try { 60 | byte[] bs = ZipUtils.asByteSource(bundleZipFile, bundleConfigEntry).read(); 61 | return bytesToHexString(DigestUtils.md5(bs)); 62 | } catch (IOException e) { 63 | throw new RuntimeException(e); 64 | } 65 | } 66 | 67 | /** 68 | * Read the content of a specific entry within the AAB as bytes. 69 | * 70 | * @param bundleZipFile The AAB as a ZipFile. 71 | * @param entry The ModuleEntry for the entry. 72 | * @param bundleModule The BundleModule containing the entry. 73 | * @return The content of the entry as bytes. 74 | * @throws IOException If an I/O error occurs. 75 | */ 76 | public static byte[] readByte(@NotNull ZipFile bundleZipFile, @NotNull ModuleEntry entry, @NotNull BundleModule bundleModule) throws IOException { 77 | String path = String.format("%s/%s", bundleModule.getName().getName(), entry.getPath().toString()); 78 | ZipEntry bundleConfigEntry = bundleZipFile.getEntry(path); 79 | return ZipUtils.asByteSource(bundleZipFile, bundleConfigEntry).read(); 80 | } 81 | 82 | /** 83 | * Convert a byte array to a hexadecimal string. 84 | * 85 | * @param src The byte array to convert. 86 | * @return The hexadecimal string. 87 | */ 88 | public static @NotNull String bytesToHexString(byte @NotNull [] src) { 89 | if (src.length == 0) 90 | return ""; 91 | StringBuilder stringBuilder = new StringBuilder(src.length); 92 | for (byte b : src) { 93 | int v = b & 0xFF; 94 | String hv = Integer.toHexString(v); 95 | if (hv.length() < 2) 96 | stringBuilder.append(0); 97 | stringBuilder.append(hv); 98 | } 99 | return stringBuilder.toString(); 100 | } 101 | 102 | /** 103 | * Get the entry name from a resource name in the format "package.type.entry". 104 | * 105 | * @param resourceName The resource name. 106 | * @return The entry name. 107 | */ 108 | public static String getEntryNameByResourceName(@NotNull String resourceName) { 109 | int index = resourceName.indexOf(".R."); 110 | String value = resourceName.substring(index + 3); 111 | String[] values = value.replace(".", "/").split("/"); 112 | if (values.length != 2) 113 | throw new RuntimeException("Invalid resource format, it should be package.type.entry, yours: " + resourceName); 114 | return values[values.length - 1]; 115 | } 116 | 117 | /** 118 | * Get the type name from a resource name in the format "package.type.entry". 119 | * 120 | * @param resourceName The resource name. 121 | * @return The type name. 122 | */ 123 | public static String getTypeNameByResourceName(@NotNull String resourceName) { 124 | int index = resourceName.indexOf(".R."); 125 | String value = resourceName.substring(index + 3); 126 | String[] values = value.replace(".", "/").split("/"); 127 | if (values.length != 2) 128 | throw new RuntimeException("Invalid resource format, it should be package.type.entry, yours: " + resourceName); 129 | return values[0]; 130 | } 131 | 132 | /** 133 | * Get the full resource name from a ResourceTableEntry. 134 | * 135 | * @param entry The ResourceTableEntry. 136 | * @return The full resource name. 137 | */ 138 | public static String getResourceFullName(@NotNull ResourceTableEntry entry) { 139 | return getResourceFullName(entry.getPackage().getPackageName(), entry.getType().getName(), entry.getEntry().getName()); 140 | } 141 | 142 | /** 143 | * Get the full resource name from individual components. 144 | * 145 | * @param packageName The package name. 146 | * @param typeName The type name. 147 | * @param entryName The entry name. 148 | * @return The full resource name. 149 | */ 150 | public static String getResourceFullName(String packageName, String typeName, String entryName) { 151 | return String.format("%s.R.%s.%s", packageName, typeName, entryName); 152 | } 153 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/ResourceMapping.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import org.jetbrains.annotations.Contract; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.io.BufferedWriter; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.io.Writer; 10 | import java.nio.file.Path; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.stream.Collectors; 15 | 16 | /** 17 | * The ResourceMapping class represents a mapping of resources, directories, and entry files 18 | * used for obfuscating resource-related data within Android apps. 19 | * It provides methods to manage and write these mapping rules to a file. 20 | */ 21 | public class ResourceMapping { 22 | 23 | private final Map dirMapping = new HashMap<>(); 24 | private final Map resourceMapping = new HashMap<>(); 25 | private final Map entryFilesMapping = new HashMap<>(); 26 | private final Map resourceNameToIdMapping = new HashMap<>(); 27 | private final Map resourcePathToIdMapping = new HashMap<>(); 28 | 29 | /** 30 | * Constructs an empty ResourceMapping object. 31 | */ 32 | public ResourceMapping() { 33 | } 34 | 35 | /** 36 | * Extracts the simple name from a resource path. 37 | * 38 | * @param resourceName The resource name containing the path. 39 | * @return The simple name of the resource. 40 | */ 41 | @Contract(pure = true) 42 | public static String getResourceSimpleName(@NotNull String resourceName) { 43 | String[] values = resourceName.split("/"); 44 | return values[values.length - 1]; 45 | } 46 | 47 | /** 48 | * Gets the directory mapping. 49 | * 50 | * @return A map of raw directory paths to obfuscate directory paths. 51 | */ 52 | public Map getDirMapping() { 53 | return dirMapping; 54 | } 55 | 56 | /** 57 | * Gets the resource mapping. 58 | * 59 | * @return A map of raw resource names to obfuscate resource names. 60 | */ 61 | public Map getResourceMapping() { 62 | return resourceMapping; 63 | } 64 | 65 | /** 66 | * Gets the entry files mapping. 67 | * 68 | * @return A map of raw entry file paths to obfuscated entry file paths. 69 | */ 70 | public Map getEntryFilesMapping() { 71 | return entryFilesMapping; 72 | } 73 | 74 | /** 75 | * Adds a directory mapping to the resource mapping. 76 | * 77 | * @param rawPath The raw directory path. 78 | * @param obfuscatePath The obfuscated directory path. 79 | */ 80 | public void putDirMapping(String rawPath, String obfuscatePath) { 81 | dirMapping.put(rawPath, obfuscatePath); 82 | } 83 | 84 | /** 85 | * Adds a resource mapping to the resource mapping. 86 | * 87 | * @param rawResource The raw resource name. 88 | * @param obfuscateResource The obfuscated resource name. 89 | * @throws IllegalArgumentException if the obfuscateResource already exists in the mapping. 90 | */ 91 | public void putResourceMapping(String rawResource, String obfuscateResource) { 92 | if (resourceMapping.containsValue(obfuscateResource)) 93 | throw new IllegalArgumentException(String.format("Multiple entries: %s -> %s", rawResource, obfuscateResource)); 94 | resourceMapping.put(rawResource, obfuscateResource); 95 | } 96 | 97 | /** 98 | * Adds an entry file mapping to the entry files mapping. 99 | * 100 | * @param rawPath The raw entry file path. 101 | * @param obfuscatedPath The obfuscated entry file path. 102 | */ 103 | public void putEntryFileMapping(String rawPath, String obfuscatedPath) { 104 | entryFilesMapping.put(rawPath, obfuscatedPath); 105 | } 106 | 107 | /** 108 | * Gets a list of simple names from the directory mapping. 109 | * 110 | * @return A list of simple names extracted from obfuscated directory paths. 111 | */ 112 | public List getPathMappingNameList() { 113 | return dirMapping.values().stream() 114 | .map(value -> { 115 | String[] values = value.split("/"); 116 | if (value.isEmpty()) 117 | return value; 118 | return values[values.length - 1]; 119 | }) 120 | .collect(Collectors.toList()); 121 | } 122 | 123 | /** 124 | * Adds a resource name and its corresponding ID to the mapping. 125 | * 126 | * @param name The resource name. 127 | * @param id The ID associated with the resource name. 128 | */ 129 | public void addResourceNameAndId(String name, String id) { 130 | resourceNameToIdMapping.put(name, id); 131 | } 132 | 133 | /** 134 | * Adds a resource path and its corresponding ID to the mapping. 135 | * 136 | * @param path The resource path. 137 | * @param id The ID associated with the resource path. 138 | */ 139 | public void addResourcePathAndId(String path, String id) { 140 | resourcePathToIdMapping.put(path, id); 141 | } 142 | 143 | /** 144 | * Writes the mapping rules to a file at the specified path. 145 | * 146 | * @param mappingPath The path to the mapping file. 147 | * @throws IOException If there is an issue with file I/O. 148 | */ 149 | public void writeMappingToFile(@NotNull Path mappingPath) throws IOException { 150 | Writer writer = new BufferedWriter(new FileWriter(mappingPath.toFile(), false)); 151 | // Write resource directory mapping 152 | writer.write("res dir mapping:\n"); 153 | for (Map.Entry entry : dirMapping.entrySet()) 154 | writer.write(String.format("\t%s -> %s\n", entry.getKey(), entry.getValue())); 155 | writer.write("\n\n"); 156 | writer.flush(); 157 | // Write resource ID mapping 158 | writer.write("res id mapping:\n"); 159 | for (Map.Entry entry : resourceMapping.entrySet()) 160 | writer.write(String.format( 161 | "\t%s : %s -> %s\n", 162 | resourceNameToIdMapping.get(entry.getKey()), 163 | entry.getKey(), 164 | entry.getValue() 165 | )); 166 | writer.write("\n\n"); 167 | writer.flush(); 168 | // Write resource entries path mapping 169 | writer.write("res entries path mapping:\n"); 170 | for (Map.Entry entry : entryFilesMapping.entrySet()) 171 | writer.write(String.format( 172 | "\t%s : %s -> %s\n", 173 | resourcePathToIdMapping.get(entry.getKey()), 174 | entry.getKey(), 175 | entry.getValue() 176 | )); 177 | writer.write("\n\n"); 178 | writer.flush(); 179 | writer.close(); 180 | } 181 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/bundle/ResourceTableBuilder.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.bundle; 2 | 3 | import com.android.aapt.Resources; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import static com.google.common.base.Preconditions.checkArgument; 10 | import static com.google.common.base.Preconditions.checkState; 11 | 12 | /** 13 | * Builder for generating {@link com.android.aapt.Resources.ResourceTable}. 14 | */ 15 | public class ResourceTableBuilder { 16 | 17 | private final Resources.ResourceTable.Builder table; 18 | private final Map resPackageMap; 19 | 20 | /** 21 | * Constructs a new ResourceTableBuilder. 22 | */ 23 | public ResourceTableBuilder() { 24 | table = Resources.ResourceTable.newBuilder(); 25 | resPackageMap = new HashMap<>(); 26 | } 27 | 28 | /** 29 | * Adds a package to the resource table builder. 30 | * 31 | * @param resPackage The package to add. 32 | * @return The package builder. 33 | */ 34 | public PackageBuilder addPackage(Resources.@NotNull Package resPackage) { 35 | if (resPackageMap.containsKey(resPackage.getPackageName())) 36 | return resPackageMap.get(resPackage.getPackageName()); 37 | PackageBuilder packageBuilder = new PackageBuilder(resPackage); 38 | resPackageMap.put(resPackage.getPackageName(), packageBuilder); 39 | return packageBuilder; 40 | } 41 | 42 | /** 43 | * Generates the ResourceTable. 44 | * 45 | * @return The generated ResourceTable. 46 | */ 47 | public Resources.ResourceTable build() { 48 | resPackageMap.forEach((key, value) -> table.addPackage(value.resPackageBuilder.build())); 49 | return table.build(); 50 | } 51 | 52 | /** 53 | * Builder for generating packages within the ResourceTable. 54 | */ 55 | public class PackageBuilder { 56 | Resources.Package.Builder resPackageBuilder; 57 | 58 | private PackageBuilder(Resources.Package resPackage) { 59 | addPackage(resPackage); 60 | } 61 | 62 | /** 63 | * Builds the package and returns to the ResourceTableBuilder. 64 | * 65 | * @return The ResourceTableBuilder. 66 | */ 67 | public ResourceTableBuilder build() { 68 | return ResourceTableBuilder.this; 69 | } 70 | 71 | /** 72 | * Adds a package to the builder. 73 | * 74 | * @param resPackage The package to add. 75 | */ 76 | private void addPackage(Resources.@NotNull Package resPackage) { 77 | int id = resPackage.getPackageId().getId(); 78 | checkArgument( 79 | table.getPackageList().stream().noneMatch(pkg -> pkg.getPackageId().getId() == id), 80 | "Package ID %s already in use.", id); 81 | resPackageBuilder = Resources.Package.newBuilder() 82 | .setPackageId(resPackage.getPackageId()) 83 | .setPackageName(resPackage.getPackageName()); 84 | } 85 | 86 | /** 87 | * Gets a resource type from the package builder. 88 | * 89 | * @param resType The resource type to retrieve. 90 | * @return The resource type builder. 91 | */ 92 | Resources.Type.Builder getResourceType(Resources.Type resType) { 93 | return resPackageBuilder.getTypeBuilderList().stream() 94 | .filter(type -> type.getTypeId().getId() == resType.getTypeId().getId()) 95 | .findFirst() 96 | .orElseGet(() -> addResourceType(resType)); 97 | } 98 | 99 | /** 100 | * Adds a resource type to the package builder. 101 | * 102 | * @param resType The resource type to add. 103 | * @return The resource type builder. 104 | */ 105 | Resources.Type.Builder addResourceType(Resources.@NotNull Type resType) { 106 | Resources.Type.Builder typeBuilder = Resources.Type.newBuilder() 107 | .setName(resType.getName()) 108 | .setTypeId(resType.getTypeId()); 109 | resPackageBuilder.addType(typeBuilder); 110 | return getResourceType(resType); 111 | } 112 | 113 | /** 114 | * Adds a resource entry to the package builder. 115 | * 116 | * @param resType The resource type for the entry. 117 | * @param resEntry The resource entry to add. 118 | * @return The package builder. 119 | */ 120 | public PackageBuilder addResource(Resources.Type resType, Resources.@NotNull Entry resEntry) { 121 | Resources.Type.Builder type = getResourceType(resType); 122 | checkState(resPackageBuilder != null, "A package must be created before a resource can be added."); 123 | if (!resEntry.getEntryId().isInitialized()) 124 | resEntry = resEntry.toBuilder().setEntryId( 125 | resEntry.getEntryId().toBuilder().setId(0).build() 126 | ).build(); 127 | type.addEntry(resEntry.toBuilder()); 128 | return this; 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/extensions/BundleFileFilter.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.extensions; 2 | 3 | import com.android.bundle.Files; 4 | import com.android.tools.build.bundletool.model.*; 5 | import com.google.common.collect.ImmutableMap; 6 | import com.google.common.collect.ImmutableSet; 7 | import io.github.goldfish07.reschiper.plugin.bundle.AppBundleUtils; 8 | import io.github.goldfish07.reschiper.plugin.operations.NativeLibrariesOperation; 9 | import io.github.goldfish07.reschiper.plugin.operations.FileOperation; 10 | import io.github.goldfish07.reschiper.plugin.utils.Utils; 11 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 12 | import org.jetbrains.annotations.NotNull; 13 | import org.jetbrains.annotations.Nullable; 14 | 15 | import java.io.IOException; 16 | import java.nio.file.Path; 17 | import java.rmi.UnexpectedException; 18 | import java.util.*; 19 | import java.util.regex.Pattern; 20 | import java.util.stream.Collectors; 21 | import java.util.stream.Stream; 22 | import java.util.zip.ZipFile; 23 | 24 | import static com.android.tools.build.bundletool.model.AppBundle.METADATA_DIRECTORY; 25 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 26 | 27 | /** 28 | * The `BundleFileFilter` class is responsible for filtering files and metadata within an Android App Bundle (AAB). 29 | * It allows users to specify rules for filtering files within the bundle and removes the specified files according to 30 | * the defined rules. Additionally, it filters metadata files and updates the bundle accordingly. 31 | */ 32 | public class BundleFileFilter { 33 | private static final Set FILE_SIGN = new HashSet<>( 34 | ImmutableSet.of( 35 | "META-INF/*.RSA", 36 | "META-INF/*.SF", 37 | "META-INF/*.MF" 38 | ) 39 | ); 40 | private final ZipFile bundleZipFile; 41 | private final AppBundle rawAppBundle; 42 | private final Set filterRules; 43 | private int filterTotalSize = 0; 44 | private int filterTotalCount = 0; 45 | 46 | /** 47 | * Constructs a new `BundleFileFilter` instance. 48 | * 49 | * @param bundlePath The path to the AAB file to filter. 50 | * @param rawAppBundle The raw AppBundle to be filtered. 51 | * @param filterRules The set of filter rules specifying which files to exclude. 52 | * @throws IOException If there is an error accessing the AAB file. 53 | */ 54 | public BundleFileFilter(Path bundlePath, AppBundle rawAppBundle, Set filterRules) throws IOException { 55 | checkFileExistsAndReadable(bundlePath); 56 | this.bundleZipFile = new ZipFile(bundlePath.toFile()); 57 | this.rawAppBundle = rawAppBundle; 58 | if (filterRules == null) 59 | filterRules = new HashSet<>(); 60 | this.filterRules = filterRules; 61 | filterRules.addAll(FILE_SIGN); 62 | } 63 | 64 | /** 65 | * Filters the AppBundle based on the provided rules and returns the filtered AppBundle. 66 | * 67 | * @return The filtered AppBundle. 68 | * @throws IOException If there is an error during the filtering process. 69 | */ 70 | public AppBundle filter() throws IOException { 71 | System.out.println("----------------------------------------"); 72 | System.out.println(" Resource File Filter:"); 73 | System.out.println("----------------------------------------"); 74 | TimeClock timeClock = new TimeClock(); 75 | // filter bundle module file 76 | Map bundleModules = new HashMap<>(); 77 | for (Map.Entry entry : rawAppBundle.getModules().entrySet()) 78 | bundleModules.put(entry.getKey(), filterBundleModule(entry.getValue())); 79 | AppBundle appBundle = rawAppBundle.toBuilder() 80 | .setBundleMetadata(filterMetaData()) 81 | .setModules(ImmutableMap.copyOf(bundleModules)) 82 | .build(); 83 | System.out.printf( 84 | """ 85 | \n Filtering completed in %s 86 | ----------------------------------------- 87 | Reduced file count: %s 88 | Reduced file size: %s 89 | ----------------------------------------- 90 | %n""", timeClock.getElapsedTime(), filterTotalCount, FileOperation.getNetFileSizeDescription(filterTotalSize) 91 | ); 92 | return appBundle; 93 | } 94 | 95 | /** 96 | * Filters the given bundle module by removing files that match filter rules. 97 | * 98 | * @param bundleModule The bundle module to filter. 99 | * @return The filtered bundle module. 100 | * @throws IOException If there is an error during the filtering process. 101 | */ 102 | private BundleModule filterBundleModule(@NotNull BundleModule bundleModule) throws IOException { 103 | BundleModule.Builder builder = bundleModule.toBuilder(); 104 | List filteredModuleEntries = new ArrayList<>(); 105 | List entries = bundleModule.getEntries().stream() 106 | .filter(entry -> { 107 | String filterRule = getMatchedFilterRule(entry.getPath()); 108 | if (filterRule != null) { 109 | checkFilteredEntry(entry, filterRule); 110 | System.out.printf(" - %s%n", entry.getPath()); 111 | filteredModuleEntries.add(entry); 112 | filterTotalSize += (int) AppBundleUtils.getZipEntrySize(bundleZipFile, entry, bundleModule); 113 | return false; 114 | } 115 | return true; 116 | }) 117 | .collect(Collectors.toList()); 118 | builder.setRawEntries(entries); 119 | filterTotalCount += filteredModuleEntries.size(); 120 | // update pb 121 | Files.NativeLibraries nativeLibraries = updateLibDirectory(bundleModule, filteredModuleEntries); 122 | if (nativeLibraries != null) 123 | builder.setNativeConfig(nativeLibraries); 124 | return builder.build(); 125 | } 126 | 127 | /** 128 | * Updates the native libraries directory in the bundle module. 129 | * 130 | * @param bundleModule The bundle module to update. 131 | * @param entries The list of filtered module entries. 132 | * @return The updated native libraries configuration. 133 | * @throws UnexpectedException If there is an unexpected error. 134 | */ 135 | private Files.NativeLibraries updateLibDirectory(@NotNull BundleModule bundleModule, @NotNull List entries) throws UnexpectedException { 136 | List libEntries = entries.stream() 137 | .filter(entry -> entry.getPath().startsWith(BundleModule.LIB_DIRECTORY)) 138 | .toList(); 139 | Files.NativeLibraries nativeLibraries = bundleModule.getNativeConfig().orElse(null); 140 | if (libEntries.isEmpty()) 141 | return nativeLibraries; 142 | if (nativeLibraries == null) 143 | throw new UnexpectedException(String.format("can not find nativeLibraries file `native.pb` in %s module", bundleModule.getName().getName())); 144 | Files.NativeLibraries filteredNativeLibraries = nativeLibraries; 145 | for (Files.TargetedNativeDirectory directory : nativeLibraries.getDirectoryList()) { 146 | int directoryNativeSize = libEntries.stream() 147 | .filter(entry -> entry.getPath().startsWith(directory.getPath())) 148 | .toList().size(); 149 | if (directoryNativeSize > 0) { 150 | int moduleNativeSize = bundleModule.getEntries().stream() 151 | .filter(entry -> entry.getPath().startsWith(directory.getPath())) 152 | .toList().size(); 153 | if (directoryNativeSize == moduleNativeSize) 154 | filteredNativeLibraries = NativeLibrariesOperation.removeDirectory(filteredNativeLibraries, directory.getPath()); 155 | } 156 | } 157 | return filteredNativeLibraries; 158 | } 159 | 160 | /** 161 | * Filter metadata directory and return filtered list. 162 | * 163 | * @return The filtered metadata. 164 | */ 165 | private BundleMetadata filterMetaData() { 166 | BundleMetadata.Builder builder = BundleMetadata.builder(); 167 | Stream.of(rawAppBundle.getBundleMetadata()) 168 | .map(BundleMetadata::getFileContentMap) 169 | .map(ImmutableMap::entrySet) 170 | .flatMap(Collection::stream) 171 | .filter(entry -> { 172 | ZipPath entryZipPath = ZipPath.create(AppBundle.METADATA_DIRECTORY + "/" + entry.getKey()); 173 | if (getMatchedFilterRule(entryZipPath) != null) { 174 | System.out.printf(" - %s%n", entryZipPath); 175 | filterTotalCount += 1; 176 | filterTotalSize += (int) AppBundleUtils.getZipEntrySize(bundleZipFile, entryZipPath); 177 | return false; 178 | } 179 | return true; 180 | }).forEach(entry -> builder.addFile(entry.getKey(), entry.getValue())); 181 | return builder.build(); 182 | } 183 | 184 | /** 185 | * Checks if the filtered entry is valid and can be filtered. 186 | * 187 | * @param entry The module entry to be checked. 188 | * @param filterRule The filter rule applied to the entry. 189 | */ 190 | private void checkFilteredEntry(@org.jetbrains.annotations.NotNull ModuleEntry entry, String filterRule) { 191 | if (!entry.getPath().startsWith(BundleModule.LIB_DIRECTORY) && !entry.getPath().startsWith(METADATA_DIRECTORY.toString())) 192 | throw new UnsupportedOperationException(String.format("%s entry can not be filtered, please check the filter rule [%s].", entry.getPath(), filterRule)); 193 | } 194 | 195 | /** 196 | * Get the filter rule that matches the given ZipPath. 197 | * 198 | * @param zipPath The ZipPath to match against filter rules. 199 | * @return The matched filter rule, or null if no rule matches. 200 | */ 201 | private @Nullable String getMatchedFilterRule(ZipPath zipPath) { 202 | for (String rule : filterRules) { 203 | Pattern filterPattern = Pattern.compile(Utils.convertToPatternString(rule)); 204 | if (filterPattern.matcher(zipPath.toString()).matches()) 205 | return rule; 206 | } 207 | return null; 208 | } 209 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/extensions/BundleStringFilter.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.extensions; 2 | 3 | import com.android.aapt.Resources; 4 | import com.android.tools.build.bundletool.model.AppBundle; 5 | import com.android.tools.build.bundletool.model.BundleModule; 6 | import com.android.tools.build.bundletool.model.BundleModuleName; 7 | import com.google.common.collect.ImmutableMap; 8 | import io.github.goldfish07.reschiper.plugin.bundle.ResourceTableBuilder; 9 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 10 | import org.jetbrains.annotations.NotNull; 11 | import org.jetbrains.annotations.Nullable; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.nio.file.Paths; 18 | import java.util.*; 19 | import java.util.stream.Collectors; 20 | 21 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 22 | 23 | /** 24 | * The `BundleStringFilter` class is responsible for filtering strings in an Android App Bundle (AAB) based on specific criteria. 25 | * It can remove unused strings and, optionally, specific languages from the resource table in each module of the bundle. 26 | *

27 | * This class provides methods for filtering strings in the App Bundle and obfuscates the resource tables in each module 28 | * while respecting white-listed languages and a list of unused string names. 29 | */ 30 | public class BundleStringFilter { 31 | private static final String replaceValue = "[value removed]"; 32 | private final AppBundle rawAppBundle; 33 | private final String unusedStrPath; 34 | private final Set languageWhiteList; 35 | private final Set unUsedNameSet = new HashSet<>(5000); 36 | 37 | /** 38 | * Constructs a `BundleStringFilter` instance with the provided parameters. 39 | * 40 | * @param bundlePath The path to the input AAB file. 41 | * @param rawAppBundle The original unfiltered App Bundle. 42 | * @param unusedStrPath The path to a file containing a list of unused string names (one per line). 43 | * @param languageWhiteList A set of language codes to be preserved (optional). 44 | */ 45 | public BundleStringFilter(Path bundlePath, AppBundle rawAppBundle, String unusedStrPath, Set languageWhiteList) { 46 | checkFileExistsAndReadable(bundlePath); 47 | this.rawAppBundle = rawAppBundle; 48 | this.unusedStrPath = unusedStrPath; 49 | this.languageWhiteList = languageWhiteList; 50 | } 51 | 52 | /** 53 | * Filters the strings in the App Bundle based on the provided criteria. 54 | * 55 | * @return An AppBundle with filtered strings, or the original AppBundle if no filtering is applied. 56 | * @throws IOException If there is an issue with reading files or bundle contents. 57 | */ 58 | public AppBundle filter() throws IOException { 59 | TimeClock timeClock = new TimeClock(); 60 | File unusedStrFile = new File(unusedStrPath); 61 | Map obfuscatedModules = new HashMap<>(); 62 | if (unusedStrFile.exists()) { 63 | //shrink-results 64 | unUsedNameSet.addAll(Files.readAllLines(Paths.get(unusedStrPath))); 65 | System.out.println("unused string : " + unUsedNameSet.size()); 66 | } 67 | if (!unUsedNameSet.isEmpty() || !languageWhiteList.isEmpty()) 68 | for (Map.Entry entry : rawAppBundle.getModules().entrySet()) { 69 | BundleModule bundleModule = entry.getValue(); 70 | BundleModuleName bundleModuleName = entry.getKey(); 71 | // obfuscate bundle module 72 | BundleModule obfuscatedModule = obfuscateBundleModule(bundleModule); 73 | obfuscatedModules.put(bundleModuleName, obfuscatedModule); 74 | } 75 | else 76 | return rawAppBundle; 77 | AppBundle appBundle = rawAppBundle.toBuilder() 78 | .setModules(ImmutableMap.copyOf(obfuscatedModules)) 79 | .build(); 80 | System.out.printf("filtering strings completed in %s\n%n", timeClock.getElapsedTime()); 81 | return appBundle; 82 | } 83 | 84 | /** 85 | * Obfuscates the resource table of a bundle module based on the specified criteria. 86 | * 87 | * @param bundleModule The bundle module to obfuscate. 88 | * @return The obfuscated bundle module. 89 | */ 90 | private BundleModule obfuscateBundleModule(@NotNull BundleModule bundleModule) { 91 | BundleModule.Builder builder = bundleModule.toBuilder(); 92 | // obfuscate resourceTable 93 | Resources.ResourceTable obfuscatedResTable = obfuscateResourceTable(bundleModule); 94 | if (obfuscatedResTable != null) 95 | builder.setResourceTable(obfuscatedResTable); 96 | return builder.build(); 97 | } 98 | 99 | /** 100 | * Obfuscates the resource table of a bundle module by removing unused strings and languages. 101 | * 102 | * @param bundleModule The bundle module containing the resource table to obfuscate. 103 | * @return The obfuscated resource table, or null if it's empty. 104 | */ 105 | private Resources.@Nullable ResourceTable obfuscateResourceTable(@NotNull BundleModule bundleModule) { 106 | if (bundleModule.getResourceTable().isEmpty()) { 107 | return null; 108 | } 109 | Resources.ResourceTable rawTable = bundleModule.getResourceTable().get(); 110 | ResourceTableBuilder tableBuilder = new ResourceTableBuilder(); 111 | List packageList = rawTable.getPackageList(); 112 | if (packageList.isEmpty()) 113 | return tableBuilder.build(); 114 | for (Resources.Package resPackage : packageList) { 115 | if (resPackage == null) 116 | continue; 117 | ResourceTableBuilder.PackageBuilder packageBuilder = tableBuilder.addPackage(resPackage); 118 | List typeList = resPackage.getTypeList(); 119 | Set languageFilterSet = new HashSet<>(100); 120 | List nameFilterList = new ArrayList<>(3000); 121 | for (Resources.Type resType : typeList) { 122 | if (resType == null) 123 | continue; 124 | List entryList = resType.getEntryList(); 125 | for (Resources.Entry resEntry : entryList) { 126 | if (resEntry == null) 127 | continue; 128 | if (resPackage.getPackageId().getId() == 127 && resType.getName().equals("string") && 129 | languageWhiteList != null && !languageWhiteList.isEmpty()) { 130 | //delete language 131 | List languageValue = resEntry.getConfigValueList().stream() 132 | .filter(Objects::nonNull) 133 | .filter(configValue -> { 134 | String locale = configValue.getConfig().getLocale(); 135 | if (keepLanguage(locale)) 136 | return true; 137 | languageFilterSet.add(locale); 138 | return false; 139 | }).collect(Collectors.toList()); 140 | resEntry = resEntry.toBuilder().clearConfigValue().addAllConfigValue(languageValue).build(); 141 | } 142 | // delete unused strings identified by the shrink process 143 | if (resPackage.getPackageId().getId() == 127 && resType.getName().equals("string") 144 | && !unUsedNameSet.isEmpty() && unUsedNameSet.contains(resEntry.getName())) { 145 | List proguardConfigValue = resEntry.getConfigValueList().stream() 146 | .filter(Objects::nonNull) 147 | .map(configValue -> { 148 | Resources.ConfigValue.Builder rcb = configValue.toBuilder(); 149 | Resources.Value.Builder rvb = rcb.getValueBuilder(); 150 | Resources.Item.Builder rib = rvb.getItemBuilder(); 151 | Resources.String.Builder rfb = rib.getStrBuilder(); 152 | return rcb.setValue( 153 | rvb.setItem( 154 | rib.setStr( 155 | rfb.setValue(replaceValue).build() 156 | ).build() 157 | ).build() 158 | ).build(); 159 | }).collect(Collectors.toList()); 160 | nameFilterList.add(resEntry.getName()); 161 | resEntry = resEntry.toBuilder().clearConfigValue().addAllConfigValue(proguardConfigValue).build(); 162 | } 163 | packageBuilder.addResource(resType, resEntry); 164 | } 165 | } 166 | System.out.println("filtering " + resPackage.getPackageName() + " id:" + resPackage.getPackageId().getId()); 167 | StringBuilder l = new StringBuilder(); 168 | for (String lan : languageFilterSet) 169 | l.append("[remove language] : ").append(lan).append("\n"); 170 | System.out.println(l); 171 | l = new StringBuilder(); 172 | for (String name : nameFilterList) 173 | l.append("[delete name] ").append(name).append("\n"); 174 | System.out.println(l); 175 | System.out.println("-----------"); 176 | packageBuilder.build(); 177 | } 178 | return tableBuilder.build(); 179 | } 180 | 181 | /** 182 | * Determines whether a language should be preserved based on the language white list. 183 | * 184 | * @param lan The language code to check. 185 | * @return True if the language should be preserved, false otherwise. 186 | */ 187 | private boolean keepLanguage(String lan) { 188 | if (lan == null || lan.equals(" ") || lan.isEmpty()) 189 | return true; 190 | if (lan.contains("-")) { 191 | int index = lan.indexOf("-"); 192 | if (index != -1) { 193 | String language = lan.substring(0, index); 194 | return languageWhiteList.contains(language); 195 | } 196 | } else 197 | return languageWhiteList.contains(lan); 198 | return false; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/extensions/DuplicateResourceMerger.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.extensions; 2 | 3 | import com.android.aapt.Resources; 4 | import com.android.tools.build.bundletool.model.*; 5 | import com.android.tools.build.bundletool.model.utils.ResourcesUtils; 6 | import io.github.goldfish07.reschiper.plugin.bundle.AppBundleUtils; 7 | import io.github.goldfish07.reschiper.plugin.bundle.ResourceTableBuilder; 8 | import io.github.goldfish07.reschiper.plugin.operations.ResourceTableOperation; 9 | import io.github.goldfish07.reschiper.plugin.operations.FileOperation; 10 | import io.github.goldfish07.reschiper.plugin.utils.TimeClock; 11 | import org.jetbrains.annotations.NotNull; 12 | 13 | import java.io.*; 14 | import java.nio.file.Files; 15 | import java.nio.file.Path; 16 | import java.util.*; 17 | import java.util.logging.Logger; 18 | import java.util.stream.Collectors; 19 | import java.util.stream.Stream; 20 | import java.util.zip.ZipFile; 21 | 22 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileDoesNotExist; 23 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 24 | import static com.google.common.collect.ImmutableList.toImmutableList; 25 | 26 | /** 27 | * The `DuplicateResourceMerger` class is responsible for merging and removing duplicated resources 28 | * in an Android App Bundle (AAB). It identifies duplicated resources by their MD5 hash values and 29 | * merges them to reduce the size of the bundle. 30 | *

31 | * This class processes each module in the App Bundle, identifies duplicated resources, and generates 32 | * a log file with information about the merged resources and their original paths. 33 | */ 34 | public class DuplicateResourceMerger { 35 | private static final Logger logger = Logger.getLogger(DuplicateResourceMerger.class.getName()); 36 | public static final String DUPLICATE_LOGGER_FILE_SUFFIX = "-duplicate.txt"; 37 | private final Path outputLogLocationDir; 38 | private final ZipFile bundleZipFile; 39 | private final AppBundle rawAppBundle; 40 | private final Map md5FileList = new HashMap<>(); 41 | private final Map duplicatedFileList = new HashMap<>(); 42 | private int mergeDuplicatedTotalSize = 0; 43 | private int mergeDuplicatedTotalCount = 0; 44 | 45 | /** 46 | * Constructs a `DuplicateResourceMerger` instance with the provided parameters. 47 | * 48 | * @param bundlePath The path to the input AAB file. 49 | * @param appBundle The original unfiltered App Bundle. 50 | * @param outputLogLocationDir The directory where log files containing information about duplicated resources will be stored. 51 | * @throws IOException If there is an issue with reading files or bundle contents. 52 | */ 53 | public DuplicateResourceMerger(Path bundlePath, AppBundle appBundle, Path outputLogLocationDir) throws IOException { 54 | checkFileExistsAndReadable(bundlePath); 55 | this.outputLogLocationDir = outputLogLocationDir; 56 | bundleZipFile = new ZipFile(bundlePath.toFile()); 57 | rawAppBundle = appBundle; 58 | } 59 | 60 | /** 61 | * Merges duplicated resources in all modules of the App Bundle, removing duplicates based on their MD5 hash values. 62 | * Generates log files containing information about the merged resources and their original paths. 63 | * 64 | * @return An AppBundle with duplicated resources removed. 65 | * @throws IOException If there is an issue with reading files or bundle contents. 66 | */ 67 | public AppBundle merge() throws IOException { 68 | TimeClock timeClock = new TimeClock(); 69 | List mergedBundleModuleList = new ArrayList<>(); 70 | for (Map.Entry moduleEntry : rawAppBundle.getModules().entrySet()) 71 | mergedBundleModuleList.add(mergeBundleModule(moduleEntry.getValue())); 72 | AppBundle mergedAppBundle = AppBundle.buildFromModules( 73 | mergedBundleModuleList.stream().collect(toImmutableList()), 74 | rawAppBundle.getBundleConfig(), 75 | rawAppBundle.getBundleMetadata() 76 | ); 77 | System.out.printf( 78 | """ 79 | removed duplicate resources done, took %s 80 | ----------------------------------------- 81 | Reduce file count: %s 82 | Reduce file size: %s 83 | -----------------------------------------%n""", 84 | timeClock.getElapsedTime(), mergeDuplicatedTotalCount, 85 | FileOperation.getNetFileSizeDescription(mergeDuplicatedTotalSize) 86 | ); 87 | return mergedAppBundle; 88 | } 89 | 90 | /** 91 | * Merges duplicated resources within a single module of the App Bundle, removing duplicates based on their MD5 hash values. 92 | * Generates a log file containing information about the merged resources and their original paths for the module. 93 | * 94 | * @param bundleModule The bundle module to process. 95 | * @return A modified bundle module with duplicated resources removed. 96 | * @throws IOException If there is an issue with reading files or bundle contents. 97 | */ 98 | private BundleModule mergeBundleModule(@NotNull BundleModule bundleModule) throws IOException { 99 | File logFile = new File(outputLogLocationDir.toFile(), bundleModule.getName().getName() + DUPLICATE_LOGGER_FILE_SUFFIX); 100 | if (Files.exists(logFile.toPath())) { 101 | System.out.println("Log File Cleanup:"); 102 | logger.warning("- Deleted existing log file: " + logFile.toPath()); 103 | Files.delete(logFile.toPath()); 104 | } 105 | Resources.ResourceTable table = bundleModule.getResourceTable().orElse(Resources.ResourceTable.getDefaultInstance()); 106 | if (table.getPackageList().isEmpty() || bundleModule.getEntries().isEmpty()) 107 | return bundleModule; 108 | md5FileList.clear(); 109 | duplicatedFileList.clear(); 110 | List mergedModuleEntry = new ArrayList<>(); 111 | for (ModuleEntry entry : bundleModule.getEntries()) { 112 | if (!entry.getPath().startsWith(BundleModule.RESOURCES_DIRECTORY)) { 113 | mergedModuleEntry.add(entry); 114 | continue; 115 | } 116 | String md5 = AppBundleUtils.getEntryMd5(bundleZipFile, entry, bundleModule); 117 | if (md5FileList.containsKey(md5)) 118 | duplicatedFileList.put(entry.getPath(), md5); 119 | else { 120 | md5FileList.put(md5, entry.getPath()); 121 | mergedModuleEntry.add(entry); 122 | } 123 | } 124 | generateDuplicatedLog(logFile, bundleModule); 125 | Resources.ResourceTable mergedTable = mergeResourceTable(table); 126 | return bundleModule.toBuilder() 127 | .setResourceTable(mergedTable) 128 | .setRawEntries(mergedModuleEntry) 129 | .build(); 130 | } 131 | 132 | /** 133 | * Merges the resource table of a module, removing duplicated resources based on their MD5 hash values. 134 | * 135 | * @param resourceTable The original resource table to be modified. 136 | * @return A modified resource table with duplicated resources removed. 137 | */ 138 | private Resources.ResourceTable mergeResourceTable(Resources.ResourceTable resourceTable) { 139 | ResourceTableBuilder resourceTableBuilder = new ResourceTableBuilder(); 140 | ResourcesUtils.entries(resourceTable).forEach(entry -> { 141 | ResourceTableBuilder.PackageBuilder packageBuilder = resourceTableBuilder.addPackage(entry.getPackage()); 142 | // replace the duplicated path 143 | List configValues = getDuplicatedMergedConfigValues(entry.getEntry()); 144 | Resources.Entry mergedEntry = ResourceTableOperation.updateEntryConfigValueList(entry.getEntry(), configValues); 145 | packageBuilder.addResource(entry.getType(), mergedEntry); 146 | }); 147 | return resourceTableBuilder.build(); 148 | } 149 | 150 | /** 151 | * Modifies the configuration values of duplicated resources within an entry, updating file paths if necessary. 152 | * 153 | * @param entry The entry containing configuration values to be modified. 154 | * @return A list of modified configuration values with updated file paths for duplicated resources. 155 | */ 156 | private List getDuplicatedMergedConfigValues(Resources.@NotNull Entry entry) { 157 | return Stream.of(entry.getConfigValueList()) 158 | .flatMap(Collection::stream) 159 | .map(configValue -> { 160 | if (!configValue.getValue().getItem().hasFile()) 161 | return configValue; 162 | ZipPath zipPath = ZipPath.create(configValue.getValue().getItem().getFile().getPath()); 163 | if (duplicatedFileList.containsKey(zipPath)) 164 | zipPath = md5FileList.get(duplicatedFileList.get(zipPath)); 165 | return ResourceTableOperation.replaceEntryPath(configValue, zipPath.toString()); 166 | }).collect(Collectors.toList()); 167 | } 168 | 169 | /** 170 | * Generates a log file containing information about duplicated resources and their original paths. 171 | * 172 | * @param logFile The file where the log information will be written. 173 | * @param bundleModule The bundle module containing the duplicated resources. 174 | * @throws IOException If there is an issue with writing the log file. 175 | */ 176 | private void generateDuplicatedLog(@NotNull File logFile, BundleModule bundleModule) throws IOException { 177 | int duplicatedSize = 0; 178 | checkFileDoesNotExist(logFile.toPath()); 179 | Writer writer = new BufferedWriter(new FileWriter(logFile, false)); 180 | writer.write("res filter path mapping:\n"); 181 | writer.flush(); 182 | System.out.println("----------------------------------------"); 183 | System.out.println(" Resource Duplication Detected:"); 184 | System.out.println("----------------------------------------"); 185 | 186 | for (Map.Entry entry : duplicatedFileList.entrySet()) { 187 | ModuleEntry moduleEntry = bundleModule.getEntry(entry.getKey()).get(); 188 | long fileSize = AppBundleUtils.getZipEntrySize(bundleZipFile, moduleEntry, bundleModule); 189 | duplicatedSize += (int) fileSize; 190 | } 191 | 192 | System.out.printf("Found duplicated resources (Count: %d, Total Size: %s):\n%n", duplicatedFileList.size(), FileOperation.getNetFileSizeDescription(duplicatedSize)); 193 | duplicatedSize = 0; 194 | for (Map.Entry entry : duplicatedFileList.entrySet()) { 195 | ZipPath keepPath = md5FileList.get(entry.getValue()); 196 | ModuleEntry moduleEntry = bundleModule.getEntry(entry.getKey()).get(); 197 | long fileSize = AppBundleUtils.getZipEntrySize(bundleZipFile, moduleEntry, bundleModule); 198 | duplicatedSize += (int) fileSize; 199 | System.out.printf("- %s (size %s)%n", entry.getKey().toString(), FileOperation.getNetFileSizeDescription(duplicatedSize)); 200 | writer.write("\t" + entry.getKey().toString() 201 | + " -> " 202 | + keepPath.toString() 203 | + " (size " + FileOperation.getNetFileSizeDescription(fileSize) + ")" 204 | + "\n" 205 | ); 206 | } 207 | writer.write("removed: count(" + duplicatedFileList.size() + "), totalSize(" + FileOperation.getNetFileSizeDescription(duplicatedSize) + ")"); 208 | writer.close(); 209 | mergeDuplicatedTotalSize += duplicatedSize; 210 | mergeDuplicatedTotalCount += duplicatedFileList.size(); 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/model/DuplicateResMergerCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.model; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import org.jetbrains.annotations.Contract; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.util.Optional; 8 | 9 | /** 10 | * A command to configure merging of duplicated resources in the bundle. 11 | */ 12 | @AutoValue 13 | public abstract class DuplicateResMergerCommand { 14 | 15 | /** 16 | * Create a new builder for configuring the DuplicateResMergerCommand. 17 | * 18 | * @return A new instance of the DuplicateResMergerCommand.Builder. 19 | */ 20 | @Contract(" -> new") 21 | public static @NotNull Builder builder() { 22 | return new AutoValue_DuplicateResMergerCommand.Builder(); 23 | } 24 | 25 | /** 26 | * Get the flag indicating whether to disable signing during resource merging. 27 | * 28 | * @return An optional boolean flag, which, if present, specifies whether signing should be disabled during resource merging. 29 | */ 30 | public abstract Optional getDisableSign(); 31 | 32 | /** 33 | * A builder for configuring the DuplicateResMergerCommand. 34 | */ 35 | @AutoValue.Builder 36 | public abstract static class Builder { 37 | 38 | /** 39 | * Set the flag to disable signing during resource merging. 40 | * 41 | * @param disableSign If true, signing during resource merging will be disabled. 42 | * @return The builder instance for method chaining. 43 | */ 44 | public abstract Builder setDisableSign(Boolean disableSign); 45 | 46 | /** 47 | * Build the DuplicateResMergerCommand instance with the configured options. 48 | * 49 | * @return The configured DuplicateResMergerCommand instance. 50 | */ 51 | public abstract DuplicateResMergerCommand build(); 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/model/FileFilterCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.model; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import org.jetbrains.annotations.Contract; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.util.Optional; 8 | import java.util.Set; 9 | 10 | /** 11 | * Represents a configuration command for file filtering in the ResChiper tool. 12 | * This class is immutable and uses the AutoValue library for code generation. 13 | */ 14 | @AutoValue 15 | public abstract class FileFilterCommand { 16 | 17 | /** 18 | * Creates a new {@link Builder} instance to construct a {@link FileFilterCommand}. 19 | * 20 | * @return A new {@link Builder} instance. 21 | */ 22 | @Contract(" -> new") 23 | public static @NotNull Builder builder() { 24 | return new AutoValue_FileFilterCommand.Builder(); 25 | } 26 | 27 | /** 28 | * Get the set of file filtering rules. 29 | * 30 | * @return The set of file filtering rules. 31 | */ 32 | public abstract Set getFileFilterRules(); 33 | 34 | /** 35 | * Get an optional flag indicating whether file signing is disabled. 36 | * 37 | * @return An optional flag indicating whether file signing is disabled. 38 | */ 39 | public abstract Optional getDisableSign(); 40 | 41 | /** 42 | * Builder pattern for constructing {@link FileFilterCommand} instances. 43 | */ 44 | @AutoValue.Builder 45 | public abstract static class Builder { 46 | 47 | /** 48 | * Set the file filtering rules for the command. 49 | * 50 | * @param fileFilterRules The set of file filtering rules. 51 | * @return This builder for method chaining. 52 | */ 53 | public abstract Builder setFileFilterRules(Set fileFilterRules); 54 | 55 | /** 56 | * Set the flag indicating whether file signing should be disabled for the command. 57 | * 58 | * @param disableSign An optional flag indicating whether file signing is disabled. 59 | * @return This builder for method chaining. 60 | */ 61 | public abstract Builder setDisableSign(Boolean disableSign); 62 | 63 | /** 64 | * Build a new {@link FileFilterCommand} instance with the configured properties. 65 | * 66 | * @return A new {@link FileFilterCommand} instance. 67 | */ 68 | public abstract FileFilterCommand build(); 69 | } 70 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/model/ObfuscateBundleCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.model; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import org.jetbrains.annotations.Contract; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.nio.file.Path; 8 | import java.util.Optional; 9 | import java.util.Set; 10 | 11 | /** 12 | * Represents a command responsible for obfuscating resources in an App Bundle. 13 | * This class is immutable and uses the AutoValue library for code generation. 14 | */ 15 | @AutoValue 16 | public abstract class ObfuscateBundleCommand { 17 | 18 | /** 19 | * Creates a new {@link Builder} instance to construct an {@link ObfuscateBundleCommand}. 20 | * 21 | * @return A new {@link Builder} instance. 22 | */ 23 | @Contract(" -> new") 24 | public static @NotNull Builder builder() { 25 | return new AutoValue_ObfuscateBundleCommand.Builder(); 26 | } 27 | 28 | /** 29 | * Get the flag indicating whether obfuscation is enabled. 30 | * 31 | * @return A boolean flag indicating whether obfuscation is enabled. 32 | */ 33 | public abstract Boolean getEnableObfuscate(); 34 | 35 | /** 36 | * Get the resource obfuscation mode. 37 | * 38 | * @return A resource obfuscation mode, Mode are [dir, file, default]. 39 | */ 40 | public abstract String getObfuscationMode(); 41 | 42 | /** 43 | * Get an optional path to the obfuscation mapping file. 44 | * 45 | * @return An optional path to the obfuscation mapping file. 46 | */ 47 | public abstract Optional getMappingPath(); 48 | 49 | /** 50 | * Get an optional flag indicating whether duplicated resources should be merged. 51 | * 52 | * @return An optional flag indicating whether duplicated resources should be merged. 53 | */ 54 | public abstract Optional getMergeDuplicatedResources(); 55 | 56 | /** 57 | * Get an optional flag indicating whether resource signing is disabled. 58 | * 59 | * @return An optional flag indicating whether resource signing is disabled. 60 | */ 61 | public abstract Optional getDisableSign(); 62 | 63 | /** 64 | * Get the set of white-listed resources that should not be obfuscated. 65 | * 66 | * @return The set of white-listed resources. 67 | */ 68 | public abstract Set getWhiteList(); 69 | 70 | /** 71 | * Get an optional set of file filtering rules. 72 | * 73 | * @return An optional set of file filtering rules. 74 | */ 75 | public abstract Optional> getFileFilterRules(); 76 | 77 | /** 78 | * Get an optional flag indicating whether file filtering is enabled. 79 | * 80 | * @return An optional flag indicating whether file filtering is enabled. 81 | */ 82 | public abstract Optional getFilterFile(); 83 | 84 | /** 85 | * Get an optional flag indicating whether string removal is enabled. 86 | * 87 | * @return An optional flag indicating whether string removal is enabled. 88 | */ 89 | public abstract Optional getRemoveStr(); 90 | 91 | /** 92 | * Get an optional path to the unused string resources file. 93 | * 94 | * @return An optional path to the unused string resources file. 95 | */ 96 | public abstract Optional getUnusedStrPath(); 97 | 98 | /** 99 | * Get an optional set of language white-lists for string filtering. 100 | * 101 | * @return An optional set of language white-lists. 102 | */ 103 | public abstract Optional> getLanguageWhiteList(); 104 | 105 | /** 106 | * Builder pattern for constructing {@link ObfuscateBundleCommand} instances. 107 | */ 108 | @AutoValue.Builder 109 | public abstract static class Builder { 110 | 111 | /** 112 | * Set the flag indicating whether obfuscation is enabled. 113 | * 114 | * @param enable A boolean flag indicating whether obfuscation is enabled. 115 | * @return This builder instance for method chaining. 116 | */ 117 | public abstract Builder setEnableObfuscate(Boolean enable); 118 | 119 | /** 120 | * Set the resource obfuscation mode. 121 | * 122 | * @param mode flag indicating to toggle resource obfuscation mode [dir, file, default]. 123 | * @return This builder instance for method chaining. 124 | */ 125 | public abstract Builder setObfuscationMode(String mode); 126 | 127 | /** 128 | * Set the set of white-listed resources that should not be obfuscated. 129 | * 130 | * @param whiteList The set of white-listed resources. 131 | * @return This builder instance for method chaining. 132 | */ 133 | public abstract Builder setWhiteList(Set whiteList); 134 | 135 | /** 136 | * Set the flag indicating whether string removal is enabled. 137 | * 138 | * @param removeStr A boolean flag indicating whether string removal is enabled. 139 | * @return This builder instance for method chaining. 140 | */ 141 | public abstract Builder setRemoveStr(Boolean removeStr); 142 | 143 | /** 144 | * Set the path to the unused string resources file. 145 | * 146 | * @param unusedStrPath The path to the unused string resources file. 147 | * @return This builder instance for method chaining. 148 | */ 149 | public abstract Builder setUnusedStrPath(String unusedStrPath); 150 | 151 | /** 152 | * Set the set of language white-lists for string filtering. 153 | * 154 | * @param languageWhiteList The set of language white-lists. 155 | * @return This builder instance for method chaining. 156 | */ 157 | public abstract Builder setLanguageWhiteList(Set languageWhiteList); 158 | 159 | /** 160 | * Set the flag indicating whether file filtering is enabled. 161 | * 162 | * @param filterFile A boolean flag indicating whether file filtering is enabled. 163 | * @return This builder instance for method chaining. 164 | */ 165 | public abstract Builder setFilterFile(Boolean filterFile); 166 | 167 | /** 168 | * Set the set of file filtering rules. 169 | * 170 | * @param fileFilterRules The set of file filtering rules. 171 | * @return This builder instance for method chaining. 172 | */ 173 | public abstract Builder setFileFilterRules(Set fileFilterRules); 174 | 175 | /** 176 | * Set the path to the obfuscation mapping file. 177 | * 178 | * @param mappingPath The path to the obfuscation mapping file. 179 | * @return This builder instance for method chaining. 180 | */ 181 | public abstract Builder setMappingPath(Path mappingPath); 182 | 183 | /** 184 | * Set the flag indicating whether duplicated resources should be merged. 185 | * 186 | * @param mergeDuplicatedResources A boolean flag indicating whether duplicated resources should be merged. 187 | * @return This builder instance for method chaining. 188 | */ 189 | public abstract Builder setMergeDuplicatedResources(Boolean mergeDuplicatedResources); 190 | 191 | /** 192 | * Set the flag indicating whether resource signing is disabled. 193 | * 194 | * @param disableSign A boolean flag indicating whether resource signing is disabled. 195 | * @return This builder instance for method chaining. 196 | */ 197 | public abstract Builder setDisableSign(Boolean disableSign); 198 | 199 | /** 200 | * Build a new {@link ObfuscateBundleCommand} instance with the configured properties. 201 | * 202 | * @return A new {@link ObfuscateBundleCommand} instance. 203 | */ 204 | public abstract ObfuscateBundleCommand build(); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/command/model/StringFilterCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.command.model; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import org.jetbrains.annotations.Contract; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.nio.file.Path; 8 | import java.util.Optional; 9 | 10 | /** 11 | * Represents a command responsible for filtering and processing string resources in an App Bundle. 12 | * This class is immutable and uses the AutoValue library for code generation. 13 | */ 14 | @AutoValue 15 | public abstract class StringFilterCommand { 16 | 17 | /** 18 | * Creates a new {@link Builder} instance to construct a {@link StringFilterCommand}. 19 | * 20 | * @return A new {@link Builder} instance. 21 | */ 22 | @Contract(" -> new") 23 | public static @NotNull Builder builder() { 24 | return new AutoValue_StringFilterCommand.Builder(); 25 | } 26 | 27 | /** 28 | * Get an optional path to the configuration file for string filtering. 29 | * 30 | * @return An optional path to the configuration file for string filtering. 31 | */ 32 | public abstract Optional getConfigPath(); 33 | 34 | /** 35 | * Builder pattern for constructing {@link StringFilterCommand} instances. 36 | */ 37 | @AutoValue.Builder 38 | public abstract static class Builder { 39 | 40 | /** 41 | * Set the path to the configuration file for string filtering. 42 | * 43 | * @param configPath The path to the configuration file. 44 | * @return This builder instance for method chaining. 45 | */ 46 | public abstract Builder setConfigPath(Path configPath); 47 | 48 | /** 49 | * Build a new {@link StringFilterCommand} instance with the configured properties. 50 | * 51 | * @return A new {@link StringFilterCommand} instance. 52 | */ 53 | public abstract StringFilterCommand build(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/internal/AGP.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.internal; 2 | 3 | import org.gradle.api.GradleException; 4 | import org.gradle.api.Project; 5 | import org.gradle.api.initialization.dsl.ScriptHandler; 6 | import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | public class AGP { 10 | public static @NotNull String getAGPVersion(@NotNull Project project) { 11 | String agpVersion = null; 12 | for (org.gradle.api.artifacts.ResolvedArtifact artifact : project.getRootProject().getBuildscript().getConfigurations().getByName(ScriptHandler.CLASSPATH_CONFIGURATION) 13 | .getResolvedConfiguration().getResolvedArtifacts()) { 14 | DefaultModuleComponentIdentifier identifier = (DefaultModuleComponentIdentifier) artifact.getId().getComponentIdentifier(); 15 | if ("com.android.tools.build".equals(identifier.getGroup()) || 432891823 == identifier.getGroup().hashCode()) 16 | if ("gradle".equals(identifier.getModule())) 17 | agpVersion = identifier.getVersion(); 18 | } 19 | if (agpVersion == null) 20 | throw new GradleException("Failed to get AGP version"); 21 | return agpVersion; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/internal/Bundle.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.internal; 2 | 3 | import com.android.build.gradle.api.ApplicationVariant; 4 | import org.gradle.api.Project; 5 | import org.gradle.api.Task; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.io.File; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.nio.file.Path; 12 | 13 | public class Bundle { 14 | public static @NotNull Path getBundleFilePath(Project project, @NotNull ApplicationVariant variant) { 15 | String flavor = variant.getName(); 16 | return getBundleFileForAGP(project, flavor).toPath(); 17 | } 18 | 19 | public static @Nullable File getBundleFileForAGP(@NotNull Project project, String flavor) { 20 | Task finalizeBundleTask = project.getTasks().getByName("sign" + capitalize(flavor) + "Bundle"); 21 | Object bundleFile = finalizeBundleTask.property("finalBundleFile"); 22 | Object regularFile; 23 | try { 24 | if (bundleFile != null) { 25 | regularFile = bundleFile.getClass().getMethod("get").invoke(bundleFile); 26 | return (File) regularFile.getClass().getMethod("getAsFile").invoke(regularFile); 27 | } else 28 | return null; 29 | } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { 30 | throw new RuntimeException(e); 31 | } 32 | } 33 | 34 | private static @NotNull String capitalize(@NotNull String str) { 35 | return Character.toUpperCase(str.charAt(0)) + str.substring(1); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/internal/SigningConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.internal; 2 | 3 | import com.android.build.gradle.api.ApplicationVariant; 4 | import io.github.goldfish07.reschiper.plugin.model.KeyStore; 5 | import org.jetbrains.annotations.Contract; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public class SigningConfig { 9 | @Contract("_ -> new") 10 | public static @NotNull KeyStore getSigningConfig(@NotNull ApplicationVariant variant) { 11 | return new KeyStore( 12 | variant.getSigningConfig().getStoreFile(), 13 | variant.getSigningConfig().getStorePassword(), 14 | variant.getSigningConfig().getKeyAlias(), 15 | variant.getSigningConfig().getKeyPassword() 16 | ); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/model/KeyStore.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.model; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * Represents a keystore containing a cryptographic key pair for signing purposes. 7 | */ 8 | public record KeyStore(File storeFile, String storePassword, String keyAlias, String keyPassword) { 9 | /** 10 | * Constructs a new KeyStore with the provided parameters. 11 | * 12 | * @param storeFile The keystore file. 13 | * @param storePassword The password for the keystore. 14 | * @param keyAlias The alias for the key within the keystore. 15 | * @param keyPassword The password for the key. 16 | */ 17 | public KeyStore(File storeFile, String storePassword, String keyAlias, String keyPassword) { 18 | this.storeFile = storeFile; 19 | this.storePassword = storePassword; 20 | this.keyAlias = keyAlias; 21 | this.keyPassword = keyPassword; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/obfuscation/StringObfuscator.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.obfuscation; 2 | 3 | import io.github.goldfish07.reschiper.plugin.utils.Utils; 4 | 5 | import java.util.*; 6 | import java.util.regex.Pattern; 7 | 8 | /** 9 | * A utility class for generating obfuscated replacement strings. 10 | */ 11 | public class StringObfuscator { 12 | 13 | private final List replaceStringBuffer; 14 | private final Set isReplaced; 15 | private final Set isWhiteList; 16 | 17 | private static final String[] A_TO_Z = { 18 | "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 19 | "w", "x", "y", "z" 20 | }; 21 | private static final String[] A_TO_ALL = { 22 | "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 23 | "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" 24 | }; 25 | private static final Set FILE_NAME_BLACKLIST = new HashSet<>(Arrays.asList("con", "prn", "aux", "nul")); 26 | private static final int MAX_OBFUSCATION_LIMIT = 35594; 27 | 28 | /** 29 | * Initializes a new instance of the StringObfuscator class. 30 | */ 31 | public StringObfuscator() { 32 | replaceStringBuffer = new ArrayList<>(); 33 | isReplaced = new HashSet<>(); 34 | isWhiteList = new HashSet<>(); 35 | } 36 | 37 | /** 38 | * Resets the state of the StringObfuscator with the provided blacklist patterns. 39 | * 40 | * @param blacklistPatterns A set of regular expression patterns for blacklisted strings. 41 | */ 42 | public void reset(HashSet blacklistPatterns) { 43 | replaceStringBuffer.clear(); 44 | isReplaced.clear(); 45 | isWhiteList.clear(); 46 | 47 | for (String str : A_TO_Z) 48 | if (Utils.match(str, blacklistPatterns)) 49 | replaceStringBuffer.add(str); 50 | 51 | for (String first : A_TO_Z) 52 | for (String aMAToAll : A_TO_ALL) { 53 | String str = first + aMAToAll; 54 | if (Utils.match(str, blacklistPatterns)) 55 | replaceStringBuffer.add(str); 56 | } 57 | 58 | for (String first : A_TO_Z) 59 | for (String second : A_TO_ALL) 60 | for (String third : A_TO_ALL) { 61 | String str = first + second + third; 62 | if (!FILE_NAME_BLACKLIST.contains(str) && Utils.match(str, blacklistPatterns)) 63 | replaceStringBuffer.add(str); 64 | } 65 | } 66 | 67 | /** 68 | * Removes a collection of strings from the replacement buffer. 69 | * 70 | * @param collection The collection of strings to remove. 71 | */ 72 | public void removeStrings(Collection collection) { 73 | if (collection == null) 74 | return; 75 | replaceStringBuffer.removeAll(collection); 76 | } 77 | 78 | /** 79 | * Checks if a specific identifier has been replaced. 80 | * 81 | * @param id The identifier to check. 82 | * @return True if the identifier has been replaced; otherwise, false. 83 | */ 84 | public boolean isReplaced(int id) { 85 | return isReplaced.contains(id); 86 | } 87 | 88 | /** 89 | * Checks if a specific identifier is in the white list. 90 | * 91 | * @param id The identifier to check. 92 | * @return True if the identifier is in the white list; otherwise, false. 93 | */ 94 | public boolean isInWhiteList(int id) { 95 | return isWhiteList.contains(id); 96 | } 97 | 98 | /** 99 | * Adds an identifier to the white list. 100 | * 101 | * @param id The identifier to add to the white list. 102 | */ 103 | public void setInWhiteList(int id) { 104 | isWhiteList.add(id); 105 | } 106 | 107 | /** 108 | * Adds an identifier to the replacement list. 109 | * 110 | * @param id The identifier to add to the replacement list. 111 | */ 112 | public void setInReplaceList(int id) { 113 | isReplaced.add(id); 114 | } 115 | 116 | /** 117 | * Gets a replacement string from the buffer based on the provided names. 118 | * 119 | * @param names A collection of names to exclude from the replacements. 120 | * @return The replacement string. 121 | * @throws IllegalArgumentException If the replacement buffer is empty. 122 | */ 123 | public String getReplaceString(Collection names) throws IllegalArgumentException { 124 | if (replaceStringBuffer.isEmpty()) 125 | throw new IllegalArgumentException("Now can only obfuscate up to " + MAX_OBFUSCATION_LIMIT + " in a single type"); 126 | if (names != null) 127 | for (int i = 0; i < replaceStringBuffer.size(); i++) { 128 | String name = replaceStringBuffer.get(i); 129 | if (names.contains(name)) 130 | continue; 131 | return replaceStringBuffer.remove(i); 132 | } 133 | return replaceStringBuffer.remove(0); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/operations/FileOperation.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.operations; 2 | 3 | import com.android.tools.build.bundletool.model.ZipPath; 4 | import com.android.tools.build.bundletool.model.utils.ZipUtils; 5 | import com.android.tools.build.bundletool.model.utils.files.FileUtils; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | import java.io.*; 9 | import java.nio.file.Files; 10 | import java.nio.file.Path; 11 | import java.text.DecimalFormat; 12 | import java.util.Enumeration; 13 | import java.util.logging.Level; 14 | import java.util.logging.Logger; 15 | import java.util.zip.ZipEntry; 16 | import java.util.zip.ZipFile; 17 | 18 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 19 | 20 | /** 21 | * Utility class for various file operations. 22 | */ 23 | public class FileOperation { 24 | private static final Logger logger = Logger.getLogger(FileOperation.class.getName()); 25 | private static final int BUFFER = 8192; 26 | 27 | /** 28 | * Recursively deletes a directory and its contents. 29 | * 30 | * @param file The directory to delete. 31 | * @return true if the directory was successfully deleted, false otherwise. 32 | */ 33 | public static boolean deleteDir(File file) { 34 | if (file == null || (!file.exists())) { 35 | return false; 36 | } 37 | if (file.isFile()) { 38 | file.delete(); 39 | } else if (file.isDirectory()) { 40 | File[] files = file.listFiles(); 41 | if (files != null) { 42 | for (File value : files) { 43 | deleteDir(value); 44 | } 45 | } 46 | } 47 | file.delete(); 48 | return true; 49 | } 50 | 51 | /** 52 | * Uncompressed a ZIP file to a target directory. 53 | * 54 | * @param uncompressedFile The ZIP file to uncompress. 55 | * @param targetDir The target directory to extract the contents. 56 | * @throws IOException If an I/O error occurs during the uncompressed. 57 | */ 58 | public static void uncompress(Path uncompressedFile, Path targetDir) throws IOException { 59 | checkFileExistsAndReadable(uncompressedFile); 60 | if (Files.exists(targetDir)) { 61 | targetDir.toFile().delete(); 62 | } else { 63 | FileUtils.createDirectories(targetDir); 64 | } 65 | ZipFile zipFile = new ZipFile(uncompressedFile.toFile()); 66 | try (zipFile) { 67 | Enumeration emu = zipFile.entries(); 68 | while (emu.hasMoreElements()) { 69 | ZipEntry entry = emu.nextElement(); 70 | if (entry.isDirectory()) { 71 | FileUtils.createDirectories(new File(targetDir.toFile(), entry.getName()).toPath()); 72 | continue; 73 | } 74 | BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); 75 | File file = new File(targetDir.toFile() + File.separator + entry.getName()); 76 | File parent = file.getParentFile(); 77 | if (parent != null && (!parent.exists())) { 78 | FileUtils.createDirectories(parent.toPath()); 79 | } 80 | FileOutputStream fos = new FileOutputStream(file); 81 | BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); 82 | byte[] buf = new byte[BUFFER]; 83 | int len; 84 | while ((len = bis.read(buf, 0, BUFFER)) != -1) { 85 | fos.write(buf, 0, len); 86 | } 87 | bos.flush(); 88 | bos.close(); 89 | bis.close(); 90 | } 91 | } 92 | } 93 | 94 | /** 95 | * Gets a human-readable file size description from a file size in bytes. 96 | * 97 | * @param size The file size in bytes. 98 | * @return A string representing the file size with appropriate units (B, KB, MB, GB). 99 | */ 100 | public static @NotNull String getNetFileSizeDescription(long size) { 101 | StringBuilder bytes = new StringBuilder(); 102 | DecimalFormat format = new DecimalFormat("###.0"); 103 | if (size >= 1024 * 1024 * 1024) { 104 | double i = (size / (1024.0 * 1024.0 * 1024.0)); 105 | bytes.append(format.format(i)).append("GB"); 106 | } else if (size >= 1024 * 1024) { 107 | double i = (size / (1024.0 * 1024.0)); 108 | bytes.append(format.format(i)).append("MB"); 109 | } else if (size >= 1024) { 110 | double i = (size / (1024.0)); 111 | bytes.append(format.format(i)).append("KB"); 112 | } else { 113 | if (size <= 0) { 114 | bytes.append("0B"); 115 | } else { 116 | bytes.append((int) size).append("B"); 117 | } 118 | } 119 | return bytes.toString(); 120 | } 121 | 122 | /** 123 | * Gets the size of a file in bytes. 124 | * 125 | * @param f The file to get the size of. 126 | * @return The file size in bytes. 127 | */ 128 | public static long getFileSizes(@NotNull File f) { 129 | long size = 0; 130 | if (f.exists() && f.isFile()) { 131 | FileInputStream fis = null; 132 | try { 133 | fis = new FileInputStream(f); 134 | size = fis.available(); 135 | } catch (IOException e) { 136 | logger.log(Level.WARNING, "Unable to get FileSize", e); 137 | } finally { 138 | try { 139 | if (fis != null) { 140 | fis.close(); 141 | } 142 | } catch (IOException e) { 143 | logger.log(Level.WARNING, "Unable to get file size", e); 144 | } 145 | } 146 | } 147 | return size; 148 | } 149 | 150 | /** 151 | * Gets the size of a file within a ZIP archive. 152 | * 153 | * @param zipFile The ZIP file. 154 | * @param zipEntry The ZIP entry representing the file. 155 | * @return The size of the file in bytes. 156 | */ 157 | public static long getZipPathFileSize(ZipFile zipFile, ZipEntry zipEntry) { 158 | long size = 0; 159 | //todo changed 160 | try { 161 | InputStream is = ZipUtils.asByteSource(zipFile, zipEntry).openStream(); 162 | size = is.available(); 163 | is.close(); 164 | } catch (IOException e) { 165 | logger.log(Level.WARNING, "Unable to get ZipPath file size", e); 166 | } 167 | return size; 168 | } 169 | 170 | /** 171 | * Copies a file from a source location to a destination location using streams. 172 | * 173 | * @param source The source file to copy. 174 | * @param dest The destination file. 175 | * @throws IOException If an I/O error occurs during the copying process. 176 | */ 177 | public static void copyFileUsingStream(File source, @NotNull File dest) throws IOException { 178 | FileInputStream is = null; 179 | FileOutputStream os = null; 180 | File parent = dest.getParentFile(); 181 | if (parent != null && (!parent.exists())) { 182 | parent.mkdirs(); 183 | } 184 | try { 185 | is = new FileInputStream(source); 186 | os = new FileOutputStream(dest, false); 187 | 188 | byte[] buffer = new byte[BUFFER]; 189 | int length; 190 | while ((length = is.read(buffer)) > 0) { 191 | os.write(buffer, 0, length); 192 | } 193 | } finally { 194 | if (is != null) { 195 | is.close(); 196 | } 197 | if (os != null) { 198 | os.close(); 199 | } 200 | } 201 | } 202 | 203 | /** 204 | * Gets the simple name of a file from a ZipPath. 205 | * 206 | * @param zipPath The ZipPath representing the file. 207 | * @return The simple name of the file. 208 | */ 209 | public static @NotNull String getFileSimpleName(@NotNull ZipPath zipPath) { 210 | return zipPath.getFileName().toString(); 211 | } 212 | 213 | /** 214 | * Gets the file suffix (extension) from a ZipPath. 215 | * 216 | * @param zipPath The ZipPath representing the file. 217 | * @return The file suffix (extension). 218 | */ 219 | public static @NotNull String getFileSuffix(@NotNull ZipPath zipPath) { 220 | String fileName = zipPath.getName(zipPath.getNameCount() - 1).toString(); 221 | if (!fileName.contains(".")) { 222 | return fileName; 223 | } 224 | String[] values = fileName.replace(".", "/").split("/"); 225 | return fileName.substring(values[0].length()); 226 | } 227 | 228 | /** 229 | * Gets the parent directory path from a Zip file path. 230 | * 231 | * @param zipPath The Zip file path. 232 | * @return The parent directory path. 233 | */ 234 | public static @NotNull String getParentFromZipFilePath(@NotNull String zipPath) { 235 | if (!zipPath.contains("/")) { 236 | throw new IllegalArgumentException("invalid zipPath: " + zipPath); 237 | } 238 | String[] values = zipPath.split("/"); 239 | return zipPath.substring(0, zipPath.indexOf(values[values.length - 1]) - 1); 240 | } 241 | 242 | /** 243 | * Gets the name of a file from a Zip file path. 244 | * 245 | * @param zipPath The Zip file path. 246 | * @return The file name. 247 | */ 248 | public static String getNameFromZipFilePath(@NotNull String zipPath) { 249 | if (!zipPath.contains("/")) { 250 | throw new IllegalArgumentException("invalid zipPath: " + zipPath); 251 | } 252 | String[] values = zipPath.split("/"); 253 | return values[values.length - 1]; 254 | } 255 | 256 | /** 257 | * Gets the file prefix (name without extension) from a file name. 258 | * 259 | * @param fileName The file name. 260 | * @return The file prefix. 261 | */ 262 | public static String getFilePrefixByFileName(@NotNull String fileName) { 263 | if (!fileName.contains(".")) { 264 | throw new IllegalArgumentException("invalid file name: " + fileName); 265 | } 266 | String[] values = fileName.replace(".", "/").split("/"); 267 | return values[0]; 268 | } 269 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/operations/NativeLibrariesOperation.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.operations; 2 | 3 | import com.android.bundle.Files; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | /** 7 | * Utility class for working with Native Libraries in Android App Bundles. 8 | */ 9 | public class NativeLibrariesOperation { 10 | 11 | /** 12 | * Removes a directory from Native Libraries if it exists. 13 | * 14 | * @param nativeLibraries The NativeLibraries object to modify. 15 | * @param zipPath The path of the directory to remove. 16 | * @return The modified NativeLibraries object. 17 | */ 18 | public static Files.NativeLibraries removeDirectory(Files.@NotNull NativeLibraries nativeLibraries, String zipPath) { 19 | int index = -1; 20 | for (int i = 0; i < nativeLibraries.getDirectoryList().size(); i++) { 21 | Files.TargetedNativeDirectory directory = nativeLibraries.getDirectoryList().get(i); 22 | if (directory.getPath().equals(zipPath)) { 23 | index = i; 24 | break; 25 | } 26 | } 27 | if (index == -1) 28 | return nativeLibraries; 29 | return nativeLibraries.toBuilder().removeDirectory(index).build(); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/operations/ResourceTableOperation.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.operations; 2 | 3 | import com.android.aapt.Resources; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | /** 11 | * Utility class for operations on Android resource tables. 12 | */ 13 | public class ResourceTableOperation { 14 | 15 | /** 16 | * Replaces the entry path in a ConfigValue. 17 | * 18 | * @param configValue The ConfigValue to update. 19 | * @param path The new path to set. 20 | * @return The updated ConfigValue. 21 | */ 22 | public static Resources.@NotNull ConfigValue replaceEntryPath(Resources.@NotNull ConfigValue configValue, String path) { 23 | Resources.ConfigValue.Builder entryBuilder = configValue.toBuilder(); 24 | entryBuilder.setValue( 25 | configValue.getValue().toBuilder().setItem( 26 | configValue.getValue().getItem().toBuilder().setFile( 27 | configValue.getValue().getItem().getFile().toBuilder().setPath(path).build() 28 | ).build() 29 | ).build() 30 | ); 31 | return entryBuilder.build(); 32 | } 33 | 34 | /** 35 | * Updates the configuration values list for an Entry. 36 | * 37 | * @param entry The Entry to update. 38 | * @param configValueList The new list of ConfigValues. 39 | * @return The updated Entry. 40 | */ 41 | public static Resources.@NotNull Entry updateEntryConfigValueList(Resources.@NotNull Entry entry, List configValueList) { 42 | Resources.Entry.Builder entryBuilder = entry.toBuilder(); 43 | entryBuilder.clearConfigValue(); 44 | entryBuilder.addAllConfigValue(configValueList); 45 | return entryBuilder.build(); 46 | } 47 | 48 | /** 49 | * Updates the name of an Entry. 50 | * 51 | * @param entry The Entry to update. 52 | * @param name The new name to set. 53 | * @return The updated Entry. 54 | */ 55 | public static Resources.@NotNull Entry updateEntryName(Resources.@NotNull Entry entry, String name) { 56 | Resources.Entry.Builder builder = entry.toBuilder(); 57 | builder.setName(name); 58 | return builder.build(); 59 | } 60 | 61 | /** 62 | * Checks for duplicate configurations in an Entry. 63 | * 64 | * @param entry The Entry to check. 65 | * @throws IllegalArgumentException if duplicate configurations are found. 66 | */ 67 | public static void checkConfiguration(Resources.@NotNull Entry entry) { 68 | if (entry.getConfigValueCount() == 0) 69 | return; 70 | Set configValues = new HashSet<>(); 71 | for (Resources.ConfigValue configValue : entry.getConfigValueList()) { 72 | if (configValues.contains(configValue)) 73 | throw new IllegalArgumentException("Duplicate configuration for entry: " + entry.getName()); 74 | configValues.add(configValue); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/parser/Parser.java: -------------------------------------------------------------------------------- 1 | 2 | package io.github.goldfish07.reschiper.plugin.parser; 3 | 4 | import io.github.goldfish07.reschiper.plugin.parser.xml.FileFilterConfig; 5 | import io.github.goldfish07.reschiper.plugin.parser.xml.ResChiperConfig; 6 | import io.github.goldfish07.reschiper.plugin.parser.xml.StringFilterConfig; 7 | import org.dom4j.Document; 8 | import org.dom4j.DocumentException; 9 | import org.dom4j.Element; 10 | import org.dom4j.io.SAXReader; 11 | 12 | import java.nio.file.Path; 13 | import java.util.Iterator; 14 | 15 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 16 | 17 | /** 18 | * The Parser class provides methods for parsing configuration files and extracting specific settings. 19 | */ 20 | public class Parser { 21 | 22 | /** 23 | * The XML class provides methods to parse XML configuration files and extract specific settings. 24 | */ 25 | public static class XML { 26 | 27 | private final Path configPath; 28 | 29 | /** 30 | * Constructs an XML parser with the specified configuration file path. 31 | * 32 | * @param configPath The path to the XML configuration files to be parsed. 33 | */ 34 | public XML(Path configPath) { 35 | checkFileExistsAndReadable(configPath); 36 | this.configPath = configPath; 37 | } 38 | 39 | /** 40 | * Parses a file filter configuration from the XML document. 41 | * 42 | * @return A FileFilterConfig object containing file filter settings. 43 | * @throws DocumentException If there is an issue parsing the XML document. 44 | */ 45 | public FileFilterConfig fileFilterParse() throws DocumentException { 46 | FileFilterConfig fileFilter = new FileFilterConfig(); 47 | SAXReader reader = new SAXReader(); 48 | Document doc = reader.read(configPath.toFile()); 49 | Element root = doc.getRootElement(); 50 | for (Iterator i = root.elementIterator("filter"); i.hasNext(); ) { 51 | Element element = i.next(); 52 | String isActiveValue = element.attributeValue("isactive"); 53 | if (isActiveValue != null && isActiveValue.equals("true")) 54 | fileFilter.setActive(true); 55 | for (Iterator rules = element.elementIterator("rule"); rules.hasNext(); ) { 56 | Element ruleElement = rules.next(); 57 | String rule = ruleElement.attributeValue("value"); 58 | if (rule != null) 59 | fileFilter.addRule(rule); 60 | } 61 | } 62 | return fileFilter; 63 | } 64 | 65 | /** 66 | * Parses a ResChiper configuration from the XML document. 67 | * 68 | * @return A ResChiperConfig object containing ResChiper settings. 69 | * @throws DocumentException If there is an issue parsing the XML document. 70 | */ 71 | public ResChiperConfig resChiperParse() throws DocumentException { 72 | ResChiperConfig resChiperConfig = new ResChiperConfig(); 73 | SAXReader reader = new SAXReader(); 74 | Document doc = reader.read(configPath.toFile()); 75 | Element root = doc.getRootElement(); 76 | for (Iterator i = root.elementIterator("issue"); i.hasNext(); ) { 77 | Element element = i.next(); 78 | String id = element.attributeValue("id"); 79 | if (id == null || !id.equals("whitelist")) 80 | continue; 81 | String isActive = element.attributeValue("isactive"); 82 | if (isActive != null && isActive.equals("true")) 83 | resChiperConfig.setUseWhiteList(true); 84 | for (Iterator rules = element.elementIterator("path"); rules.hasNext(); ) { 85 | Element ruleElement = rules.next(); 86 | String rule = ruleElement.attributeValue("value"); 87 | if (rule != null) 88 | resChiperConfig.addWhiteList(rule); 89 | } 90 | } 91 | // File filter 92 | resChiperConfig.setFileFilter(fileFilterParse()); 93 | // String filter 94 | resChiperConfig.setStringFilterConfig(stringFilterParse()); 95 | return resChiperConfig; 96 | } 97 | 98 | /** 99 | * Parses a StringFilterConfig from the XML document. 100 | * 101 | * @return A StringFilterConfig object containing string filter settings. 102 | * @throws DocumentException If there is an issue parsing the XML document. 103 | */ 104 | public StringFilterConfig stringFilterParse() throws DocumentException { 105 | StringFilterConfig config = new StringFilterConfig(); 106 | SAXReader reader = new SAXReader(); 107 | Document doc = reader.read(configPath.toFile()); 108 | Element root = doc.getRootElement(); 109 | for (Iterator i = root.elementIterator("filter-str"); i.hasNext(); ) { 110 | Element element = i.next(); 111 | String isActive = element.attributeValue("isactive"); 112 | if (isActive != null && isActive.equalsIgnoreCase("true")) 113 | config.setActive(true); 114 | for (Iterator rules = element.elementIterator("path"); rules.hasNext(); ) { 115 | Element ruleElement = rules.next(); 116 | String path = ruleElement.attributeValue("value"); 117 | config.setPath(path); 118 | } 119 | for (Iterator rules = element.elementIterator("language"); rules.hasNext(); ) { 120 | Element ruleElement = rules.next(); 121 | String path = ruleElement.attributeValue("value"); 122 | config.getLanguageWhiteList().add(path); 123 | } 124 | } 125 | return config; 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/parser/ResourcesMappingParser.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.parser; 2 | 3 | import io.github.goldfish07.reschiper.plugin.bundle.ResourceMapping; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | import java.nio.file.Path; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | import static com.android.tools.build.bundletool.model.utils.files.FilePreconditions.checkFileExistsAndReadable; 13 | 14 | /** 15 | * This class is responsible for parsing a resource mapping file used for resource obfuscation 16 | * in Android development and populating a {@link ResourceMapping} object with the mappings. 17 | */ 18 | public class ResourcesMappingParser { 19 | private static final Pattern MAP_DIR_PATTERN = Pattern.compile("^\\s+(.*)->(.*)"); 20 | private static final Pattern MAP_RES_PATTERN = Pattern.compile("^\\s+(.*):(.*)->(.*)"); 21 | private final Path mappingPath; 22 | 23 | /** 24 | * Constructs a new ResourcesMappingParser with the specified mapping file path. 25 | * 26 | * @param mappingPath The path to the resource mapping file. 27 | * @throws IllegalArgumentException If the mapping file does not exist or is not readable. 28 | */ 29 | public ResourcesMappingParser(Path mappingPath) { 30 | checkFileExistsAndReadable(mappingPath); 31 | this.mappingPath = mappingPath; 32 | } 33 | 34 | /** 35 | * Parses the resource mapping file and returns a populated {@link ResourceMapping} object. 36 | * 37 | * @return A {@link ResourceMapping} object containing the parsed resource mappings. 38 | * @throws IOException If an I/O error occurs while reading the mapping file. 39 | */ 40 | public ResourceMapping parse() throws IOException { 41 | ResourceMapping mapping = new ResourceMapping(); 42 | FileReader fr = new FileReader(mappingPath.toFile()); 43 | BufferedReader br = new BufferedReader(fr); 44 | String line = br.readLine(); 45 | while (line != null) { 46 | if (line.isEmpty()) { 47 | line = br.readLine(); 48 | continue; 49 | } 50 | System.out.println("Res: " + line); 51 | if (!line.contains(":")) { 52 | Matcher mat = MAP_DIR_PATTERN.matcher(line); 53 | if (mat.find()) { 54 | String rawName = mat.group(1).trim(); 55 | String obfuscateName = mat.group(2).trim(); 56 | if (!line.contains("/") || line.contains(".")) 57 | throw new IllegalArgumentException("Unexpected resource dir: " + line); 58 | mapping.putDirMapping(rawName, obfuscateName); 59 | } 60 | } else { 61 | Matcher mat = MAP_RES_PATTERN.matcher(line); 62 | if (mat.find()) { 63 | String rawName = mat.group(2).trim(); 64 | String obfuscateName = mat.group(3).trim(); 65 | if (line.contains("/")) 66 | mapping.putEntryFileMapping(rawName, obfuscateName); 67 | else { 68 | int packagePos = rawName.indexOf(".R."); 69 | if (packagePos == -1) 70 | throw new IllegalArgumentException(String.format("the mapping file packageName is malformed, " 71 | + "it should be like com.github.goldfish07.ugc.R.attr.test, yours %s\n", rawName)); 72 | mapping.putResourceMapping(rawName, obfuscateName); 73 | } 74 | } 75 | } 76 | line = br.readLine(); 77 | } 78 | br.close(); 79 | fr.close(); 80 | return mapping; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/parser/xml/FileFilterConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.parser.xml; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * The `FileFilterConfig` class represents a configuration for filtering files based on a set of rules. 8 | * It allows specifying whether the filter is active and maintains a set of rules for file filtering. 9 | */ 10 | public class FileFilterConfig { 11 | private final Set rules = new HashSet<>(); 12 | private boolean isActive; 13 | 14 | /** 15 | * Checks if the file filter is active. 16 | * 17 | * @return `true` if the filter is active, `false` otherwise. 18 | */ 19 | public boolean isActive() { 20 | return isActive; 21 | } 22 | 23 | /** 24 | * Sets the activity status of the file filter. 25 | * 26 | * @param active `true` to activate the filter, `false` to deactivate it. 27 | */ 28 | public void setActive(boolean active) { 29 | isActive = active; 30 | } 31 | 32 | /** 33 | * Gets the set of rules used for file filtering. 34 | * 35 | * @return The set of rules for file filtering. 36 | */ 37 | public Set getRules() { 38 | return rules; 39 | } 40 | 41 | /** 42 | * Adds a rule to the set of rules for file filtering. 43 | * 44 | * @param rule The rule to add. 45 | */ 46 | public void addRule(String rule) { 47 | rules.add(rule); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/parser/xml/ResChiperConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.parser.xml; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * The `ResChiperConfig` class represents the configuration for the Resource Chiper tool. 8 | * It includes settings related to file filtering, string filtering, and a whitelist of rules. 9 | */ 10 | public class ResChiperConfig { 11 | private final Set whiteList = new HashSet<>(); 12 | private FileFilterConfig fileFilter; 13 | private StringFilterConfig stringFilterConfig; 14 | private boolean useWhiteList; 15 | 16 | /** 17 | * Gets the file filter configuration for the Resource Chiper tool. 18 | * 19 | * @return The file filter configuration. 20 | */ 21 | public FileFilterConfig getFileFilter() { 22 | return fileFilter; 23 | } 24 | 25 | /** 26 | * Sets the file filter configuration for the Resource Chiper tool. 27 | * 28 | * @param fileFilter The file filter configuration to set. 29 | */ 30 | public void setFileFilter(FileFilterConfig fileFilter) { 31 | this.fileFilter = fileFilter; 32 | } 33 | 34 | /** 35 | * Checks if the whitelist is active for the Resource Chiper tool. 36 | * 37 | * @return `true` if the whitelist is active, `false` otherwise. 38 | */ 39 | public boolean isUseWhiteList() { 40 | return useWhiteList; 41 | } 42 | 43 | /** 44 | * Sets the whitelist activity status for the Resource Chiper tool. 45 | * 46 | * @param useWhiteList `true` to activate the whitelist, `false` to deactivate it. 47 | */ 48 | public void setUseWhiteList(boolean useWhiteList) { 49 | this.useWhiteList = useWhiteList; 50 | } 51 | 52 | /** 53 | * Gets the whitelist of rules used for resource filtering. 54 | * 55 | * @return The set of whitelist rules. 56 | */ 57 | public Set getWhiteList() { 58 | return whiteList; 59 | } 60 | 61 | /** 62 | * Adds a rule to the whitelist for resource filtering. 63 | * 64 | * @param whiteRule The rule to add to the whitelist. 65 | */ 66 | public void addWhiteList(String whiteRule) { 67 | this.whiteList.add(whiteRule); 68 | } 69 | 70 | /** 71 | * Gets the string filter configuration for the Resource Chiper tool. 72 | * 73 | * @return The string filter configuration. 74 | */ 75 | public StringFilterConfig getStringFilterConfig() { 76 | return stringFilterConfig; 77 | } 78 | 79 | /** 80 | * Sets the string filter configuration for the Resource Chiper tool. 81 | * 82 | * @param stringFilterConfig The string filter configuration to set. 83 | */ 84 | public void setStringFilterConfig(StringFilterConfig stringFilterConfig) { 85 | this.stringFilterConfig = stringFilterConfig; 86 | } 87 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/parser/xml/StringFilterConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.parser.xml; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * The `StringFilterConfig` class represents the configuration for filtering strings in resources. 8 | * It allows specifying whether the string filter is active, a custom path, and a whitelist of languages. 9 | */ 10 | public class StringFilterConfig { 11 | private final Set languageWhiteList = new HashSet<>(); 12 | private boolean isActive; 13 | private String path = ""; 14 | 15 | /** 16 | * Checks if the string filter is active. 17 | * 18 | * @return `true` if the filter is active, `false` otherwise. 19 | */ 20 | public boolean isActive() { 21 | return isActive; 22 | } 23 | 24 | /** 25 | * Sets the activity status of the string filter. 26 | * 27 | * @param active `true` to activate the filter, `false` to deactivate it. 28 | */ 29 | public void setActive(boolean active) { 30 | isActive = active; 31 | } 32 | 33 | /** 34 | * Gets the custom path used for filtering strings. 35 | * 36 | * @return The custom path for string filtering. 37 | */ 38 | public String getPath() { 39 | return path; 40 | } 41 | 42 | /** 43 | * Sets the custom path for filtering strings. 44 | * 45 | * @param path The custom path to set. 46 | */ 47 | public void setPath(String path) { 48 | this.path = path; 49 | } 50 | 51 | /** 52 | * Gets the whitelist of languages used for string filtering. 53 | * 54 | * @return The set of whitelisted languages for string filtering. 55 | */ 56 | public Set getLanguageWhiteList() { 57 | return languageWhiteList; 58 | } 59 | 60 | /** 61 | * Returns a string representation of the `StringFilterConfig` object. 62 | * 63 | * @return A string representation of the object's properties. 64 | */ 65 | @Override 66 | public String toString() { 67 | return "StringFilterConfig{" + 68 | "isActive=" + isActive + 69 | ", path='" + path + '\'' + 70 | ", languageWhiteList=" + languageWhiteList + 71 | '}'; 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/tasks/ResChiperTask.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.tasks; 2 | 3 | import com.android.build.gradle.api.ApplicationVariant; 4 | import io.github.goldfish07.reschiper.plugin.command.Command; 5 | import io.github.goldfish07.reschiper.plugin.command.model.DuplicateResMergerCommand; 6 | import io.github.goldfish07.reschiper.plugin.command.model.FileFilterCommand; 7 | import io.github.goldfish07.reschiper.plugin.command.model.ObfuscateBundleCommand; 8 | import io.github.goldfish07.reschiper.plugin.command.model.StringFilterCommand; 9 | import io.github.goldfish07.reschiper.plugin.Extension; 10 | import io.github.goldfish07.reschiper.plugin.model.KeyStore; 11 | import io.github.goldfish07.reschiper.plugin.internal.Bundle; 12 | import io.github.goldfish07.reschiper.plugin.internal.SigningConfig; 13 | import org.gradle.api.DefaultTask; 14 | import org.gradle.api.tasks.TaskAction; 15 | import org.jetbrains.annotations.NotNull; 16 | 17 | import java.io.File; 18 | import java.nio.file.Path; 19 | import java.util.logging.Level; 20 | import java.util.logging.Logger; 21 | 22 | /** 23 | * Custom Gradle task for running ResChiper. 24 | */ 25 | public class ResChiperTask extends DefaultTask { 26 | 27 | private static final Logger logger = Logger.getLogger(ResChiperTask.class.getName()); 28 | private final Extension resChiperExtension = (Extension) getProject().getExtensions().getByName("resChiper"); 29 | private ApplicationVariant variant; 30 | private KeyStore keyStore; 31 | private Path bundlePath; 32 | private Path obfuscatedBundlePath; 33 | 34 | /** 35 | * Constructor for the ResChiperTask. 36 | */ 37 | public ResChiperTask() { 38 | setDescription("Assemble resource proguard for bundle file"); 39 | setGroup("bundle"); 40 | getOutputs().upToDateWhen(task -> false); 41 | } 42 | 43 | /** 44 | * Sets the variant scope for the task. 45 | * 46 | * @param variant The ApplicationVariant for the Android application. 47 | */ 48 | public void setVariantScope(ApplicationVariant variant) { 49 | this.variant = variant; 50 | bundlePath = Bundle.getBundleFilePath(getProject(), variant); 51 | obfuscatedBundlePath = new File(bundlePath.toFile().getParentFile(), resChiperExtension.getObfuscatedBundleName()).toPath(); 52 | } 53 | 54 | /** 55 | * Executes the ResChiperTask. 56 | * 57 | * @throws Exception If an error occurs during execution. 58 | */ 59 | @TaskAction 60 | public void execute() throws Exception { 61 | logger.log(Level.INFO, resChiperExtension.toString()); 62 | keyStore = SigningConfig.getSigningConfig(variant); 63 | printSignConfiguration(); 64 | printOutputFileLocation(); 65 | prepareUnusedFile(); 66 | Command.Builder builder = Command.builder(); 67 | builder.setBundlePath(bundlePath); 68 | builder.setOutputPath(obfuscatedBundlePath); 69 | 70 | ObfuscateBundleCommand.Builder obfuscateBuilder = ObfuscateBundleCommand.builder() 71 | .setEnableObfuscate(resChiperExtension.getEnableObfuscation()) 72 | .setObfuscationMode(resChiperExtension.getObfuscationMode()) 73 | .setMergeDuplicatedResources(resChiperExtension.getMergeDuplicateResources()) 74 | .setWhiteList(resChiperExtension.getWhiteList()) 75 | .setFilterFile(resChiperExtension.getEnableFileFiltering()) 76 | .setFileFilterRules(resChiperExtension.getFileFilterList()) 77 | .setRemoveStr(resChiperExtension.getEnableFilterStrings()) 78 | .setUnusedStrPath(resChiperExtension.getUnusedStringFile()) 79 | .setLanguageWhiteList(resChiperExtension.getLocaleWhiteList()); 80 | if (resChiperExtension.getMappingFile() != null) 81 | obfuscateBuilder.setMappingPath(resChiperExtension.getMappingFile()); 82 | 83 | if (keyStore.storeFile() != null && keyStore.storeFile().exists()) 84 | builder.setStoreFile(keyStore.storeFile().toPath()) 85 | .setKeyAlias(keyStore.keyAlias()) 86 | .setKeyPassword(keyStore.keyPassword()) 87 | .setStorePassword(keyStore.storePassword()); 88 | 89 | builder.setObfuscateBundleBuilder(obfuscateBuilder.build()); 90 | 91 | FileFilterCommand.Builder fileFilterBuilder = FileFilterCommand.builder(); 92 | fileFilterBuilder.setFileFilterRules(resChiperExtension.getFileFilterList()); 93 | builder.setFileFilterBuilder(fileFilterBuilder.build()); 94 | 95 | StringFilterCommand.Builder stringFilterBuilder = StringFilterCommand.builder(); 96 | builder.setStringFilterBuilder(stringFilterBuilder.build()); 97 | 98 | DuplicateResMergerCommand.Builder duplicateResMergeBuilder = DuplicateResMergerCommand.builder(); 99 | builder.setDuplicateResMergeBuilder(duplicateResMergeBuilder.build()); 100 | 101 | Command command = builder.build(builder.build(), Command.TYPE.OBFUSCATE_BUNDLE); 102 | command.execute(Command.TYPE.OBFUSCATE_BUNDLE); 103 | } 104 | 105 | /** 106 | * Prepares the unused file for filtering. 107 | */ 108 | private void prepareUnusedFile() { 109 | String simpleName = variant.getName().replace("Release", ""); 110 | String name = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1); 111 | String resourcePath = getProject().getBuildDir() + "/outputs/mapping/" + name + "/release/unused_strings.txt"; 112 | File usedFile = new File(resourcePath); 113 | 114 | if (usedFile.exists()) { 115 | System.out.println("find unused_strings.txt: " + usedFile.getAbsolutePath()); 116 | if (resChiperExtension.getEnableFilterStrings()) 117 | if (resChiperExtension.getUnusedStringFile() == null || resChiperExtension.getUnusedStringFile().isBlank()) { 118 | resChiperExtension.setUnusedStringFile(usedFile.getAbsolutePath()); 119 | logger.log(Level.SEVERE, "replace unused_strings.txt!"); 120 | } 121 | } else 122 | logger.log(Level.SEVERE, "not exists unused_strings.txt: " + usedFile.getAbsolutePath() 123 | + "\nuse default path: " + resChiperExtension.getUnusedStringFile()); 124 | } 125 | 126 | /** 127 | * Prints the signing configuration. 128 | */ 129 | private void printSignConfiguration() { 130 | System.out.println("----------------------------------------"); 131 | System.out.println(" Signing Configuration"); 132 | System.out.println("----------------------------------------"); 133 | System.out.println("\tKeyStoreFile:\t\t" + keyStore.storeFile()); 134 | System.out.println("\tKeyPassword:\t" + encrypt(keyStore.keyPassword())); 135 | System.out.println("\tAlias:\t\t\t" + encrypt(keyStore.keyAlias())); 136 | System.out.println("\tStorePassword:\t" + encrypt(keyStore.storePassword())); 137 | } 138 | 139 | /** 140 | * Prints the output file location. 141 | */ 142 | private void printOutputFileLocation() { 143 | System.out.println("----------------------------------------"); 144 | System.out.println(" Output configuration"); 145 | System.out.println("----------------------------------------"); 146 | System.out.println("\tFolder:\t\t" + obfuscatedBundlePath.getParent()); 147 | System.out.println("\tFile:\t\t" + obfuscatedBundlePath.getFileName()); 148 | System.out.println("----------------------------------------"); 149 | } 150 | 151 | /** 152 | * Encrypts a value for printing (partially). 153 | * 154 | * @param value The value to encrypt. 155 | * @return The encrypted value. 156 | */ 157 | private @NotNull String encrypt(String value) { 158 | if (value == null) 159 | return "/"; 160 | if (value.length() > 2) 161 | return value.substring(0, value.length() / 2) + "****"; 162 | return "****"; 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.utils; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.io.*; 6 | import java.nio.charset.StandardCharsets; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import static com.google.common.base.Preconditions.checkArgument; 11 | import static com.google.common.base.Preconditions.checkNotNull; 12 | 13 | public class FileUtils { 14 | private static final String UNIX_LINE_SEPARATOR = "\n"; 15 | 16 | /** 17 | * Loads a text file, forcing the line separator to be Unix-style '\n'. 18 | * 19 | * @param file the file to read from 20 | * @return the content of the file with Unix-style line separators 21 | * @throws IOException if an I/O error occurs or the file does not exist 22 | */ 23 | public static @NotNull String loadFileWithUnixLineSeparators(@NotNull File file) throws IOException { 24 | checkNotNull(file, "File must not be null"); 25 | checkArgument(file.exists(), "File does not exist"); 26 | checkArgument(file.isFile(), "File is not a regular file"); 27 | try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) { 28 | List lines = new ArrayList<>(); 29 | String line; 30 | while ((line = reader.readLine()) != null) 31 | lines.add(line); 32 | return String.join(UNIX_LINE_SEPARATOR, lines); 33 | } 34 | } 35 | 36 | /** 37 | * Creates a new text file or replaces the content of an existing file. 38 | * 39 | * @param file the file to write to 40 | * @param content the new content of the file 41 | * @throws IOException if an I/O error occurs 42 | */ 43 | public static void writeToFile(@NotNull File file, @NotNull String content) throws IOException { 44 | checkNotNull(file, "File must not be null"); 45 | checkNotNull(content, "Content must not be null"); 46 | try (FileWriter writer = new FileWriter(file, StandardCharsets.UTF_8)) { 47 | writer.write(content); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/utils/TimeClock.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.utils; 2 | 3 | /** 4 | * A utility class for measuring elapsed time. 5 | */ 6 | public class TimeClock { 7 | 8 | private final long startTime; 9 | 10 | /** 11 | * Constructs a TimeClock and starts the timer. 12 | */ 13 | public TimeClock() { 14 | startTime = System.currentTimeMillis(); 15 | } 16 | 17 | /** 18 | * Gets the elapsed time since the TimeClock was constructed. 19 | * 20 | * @return A string representing the elapsed time in a human-readable format (e.g., "1min 30s", "45s", "500ms"). 21 | */ 22 | public String getElapsedTime() { 23 | long elapsedTimeMillis = System.currentTimeMillis() - startTime; 24 | if (elapsedTimeMillis >= 60000) { 25 | long elapsedMinutes = elapsedTimeMillis / 60000; 26 | long remainingSeconds = (elapsedTimeMillis % 60000) / 1000; 27 | if (remainingSeconds > 0) 28 | return elapsedMinutes + "min " + remainingSeconds + "s"; 29 | else 30 | return elapsedMinutes + "min"; 31 | } else if (elapsedTimeMillis >= 1000) 32 | return elapsedTimeMillis / 1000 + "s"; 33 | else 34 | return elapsedTimeMillis + "ms"; 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/io/github/goldfish07/reschiper/plugin/utils/Utils.java: -------------------------------------------------------------------------------- 1 | package io.github.goldfish07.reschiper.plugin.utils; 2 | 3 | import io.github.goldfish07.reschiper.plugin.operations.FileOperation; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.io.*; 7 | import java.nio.charset.StandardCharsets; 8 | import java.util.*; 9 | import java.util.regex.Pattern; 10 | 11 | public class Utils { 12 | public static boolean isPresent(String str) { 13 | return str != null && !str.isEmpty(); 14 | } 15 | 16 | public static boolean isBlank(String str) { 17 | return !isPresent(str); 18 | } 19 | 20 | public static boolean isPresent(Iterator iterator) { 21 | return iterator != null && iterator.hasNext(); 22 | } 23 | 24 | public static boolean isBlank(Iterator iterator) { 25 | return !isPresent(iterator); 26 | } 27 | 28 | public static String convertToPatternString(String input) { 29 | // ? Zero or one character 30 | // * Zero or more of character 31 | // + One or more of characters 32 | final String[] searchList = new String[]{".", "?", "*", "+"}; 33 | final String[] replacementList = new String[]{"\\.", ".?", ".*", ".+"}; 34 | return replaceEach(input, searchList, replacementList); 35 | } 36 | 37 | public static boolean match(String str, HashSet patterns) { 38 | if (patterns == null) 39 | return true; 40 | for (Pattern p : patterns) { 41 | boolean isMatch = p.matcher(str).matches(); 42 | if (isMatch) 43 | return false; 44 | } 45 | return true; 46 | } 47 | 48 | public static void cleanDir(@NotNull File dir) { 49 | if (dir.exists()) { 50 | FileOperation.deleteDir(dir); 51 | dir.mkdirs(); 52 | } 53 | } 54 | 55 | public static String readInputStream(@NotNull InputStream inputStream) throws IOException { 56 | ByteArrayOutputStream result = new ByteArrayOutputStream(); 57 | byte[] buffer = new byte[4096]; 58 | int length; 59 | while ((length = inputStream.read(buffer)) != -1) 60 | result.write(buffer, 0, length); 61 | return result.toString(StandardCharsets.UTF_8); 62 | } 63 | 64 | public static String runCmd(String... cmd) throws IOException, InterruptedException { 65 | String output; 66 | Process process = null; 67 | try { 68 | process = new ProcessBuilder(cmd).start(); 69 | output = readInputStream(process.getInputStream()); 70 | process.waitFor(); 71 | if (process.exitValue() != 0) { 72 | System.err.printf("%s Failed! Please check your signature file.\n%n", cmd[0]); 73 | throw new RuntimeException(readInputStream(process.getErrorStream())); 74 | } 75 | } finally { 76 | if (process != null) 77 | process.destroy(); 78 | } 79 | return output; 80 | } 81 | 82 | public static String runExec(String[] argv) throws IOException, InterruptedException { 83 | Process process = null; 84 | String output; 85 | try { 86 | process = Runtime.getRuntime().exec(argv); 87 | output = readInputStream(process.getInputStream()); 88 | process.waitFor(); 89 | if (process.exitValue() != 0) { 90 | System.err.printf("%s Failed! Please check your signature file.\n%n", argv[0]); 91 | throw new RuntimeException(readInputStream(process.getErrorStream())); 92 | } 93 | } finally { 94 | if (process != null) 95 | process.destroy(); 96 | } 97 | return output; 98 | } 99 | 100 | private static void processOutputStreamInThread(@NotNull Process process) throws IOException { 101 | InputStreamReader ir = new InputStreamReader(process.getInputStream()); 102 | LineNumberReader input = new LineNumberReader(ir); 103 | // If not read, there may be issues; it is blocked. 104 | while (input.readLine() != null) { 105 | } 106 | } 107 | 108 | private static String replaceEach(String text, String[] searchList, String[] replacementList) { 109 | // TODO: throw new IllegalArgumentException() if any param doesn't make sense 110 | //validateParams(text, searchList, replacementList); 111 | 112 | SearchTracker tracker = new SearchTracker(text, searchList, replacementList); 113 | if (!tracker.hasNextMatch(0)) 114 | return text; 115 | StringBuilder buf = new StringBuilder(text.length() * 2); 116 | int start = 0; 117 | do { 118 | SearchTracker.MatchInfo matchInfo = tracker.matchInfo; 119 | int textIndex = matchInfo.textIndex; 120 | String pattern = matchInfo.pattern; 121 | String replacement = matchInfo.replacement; 122 | buf.append(text, start, textIndex); 123 | buf.append(replacement); 124 | start = textIndex + pattern.length(); 125 | } while (tracker.hasNextMatch(start)); 126 | return buf.append(text.substring(start)).toString(); 127 | } 128 | 129 | static class SearchTracker { 130 | final String text; 131 | final Map patternToReplacement = new HashMap<>(); 132 | final Set pendingPatterns = new HashSet<>(); 133 | MatchInfo matchInfo = null; 134 | 135 | SearchTracker(String text, String @NotNull [] searchList, String[] replacementList) { 136 | this.text = text; 137 | for (int i = 0; i < searchList.length; ++i) { 138 | String pattern = searchList[i]; 139 | patternToReplacement.put(pattern, replacementList[i]); 140 | pendingPatterns.add(pattern); 141 | } 142 | } 143 | 144 | boolean hasNextMatch(int start) { 145 | int textIndex = -1; 146 | String nextPattern = null; 147 | for (String pattern : new ArrayList<>(pendingPatterns)) { 148 | int matchIndex = text.indexOf(pattern, start); 149 | if (matchIndex == -1) 150 | pendingPatterns.remove(pattern); 151 | else { 152 | if (textIndex == -1 || matchIndex < textIndex) { 153 | textIndex = matchIndex; 154 | nextPattern = pattern; 155 | } 156 | } 157 | } 158 | if (nextPattern != null) { 159 | matchInfo = new MatchInfo(nextPattern, patternToReplacement.get(nextPattern), textIndex); 160 | return true; 161 | } 162 | return false; 163 | } 164 | 165 | private record MatchInfo(String pattern, String replacement, int textIndex) { 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/io.github.goldfish07.reschiper.properties: -------------------------------------------------------------------------------- 1 | implementation-class=io.github.goldfish07.reschiper.plugin.ResChiperPlugin --------------------------------------------------------------------------------