Repository: taamarin/box.manager Branch: main Commit: 09f5683086e7 Files: 125 Total size: 301.3 KB Directory structure: gitextract_dh8n5je7/ ├── .github/ │ ├── taamarinbot.py │ └── workflows/ │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ ├── release.keystore │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── xyz/ │ │ └── chz/ │ │ └── bfm/ │ │ └── ExampleInstrumentedTest.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── xyz/ │ │ │ └── chz/ │ │ │ └── bfm/ │ │ │ ├── BFRApp.kt │ │ │ ├── adapter/ │ │ │ │ └── AppListAdapter.kt │ │ │ ├── data/ │ │ │ │ ├── AppInfo.kt │ │ │ │ └── AppManager.kt │ │ │ ├── dialog/ │ │ │ │ ├── IMakeDialog.kt │ │ │ │ ├── ISettingDialog.kt │ │ │ │ ├── MakeDialog.kt │ │ │ │ ├── MaterialDialogFragment.kt │ │ │ │ └── SettingDialog.kt │ │ │ ├── enm/ │ │ │ │ └── StatusConnection.kt │ │ │ ├── service/ │ │ │ │ └── TileBox.kt │ │ │ ├── ui/ │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── base/ │ │ │ │ │ └── BaseActivity.kt │ │ │ │ ├── converter/ │ │ │ │ │ ├── ConfigManager.kt │ │ │ │ │ ├── ConverterActivity.kt │ │ │ │ │ └── config/ │ │ │ │ │ ├── ClashData.kt │ │ │ │ │ ├── ConfigType.kt │ │ │ │ │ ├── ConfigUtil.kt │ │ │ │ │ └── SingBoxData.kt │ │ │ │ ├── core/ │ │ │ │ │ ├── CoreActivity.kt │ │ │ │ │ └── util/ │ │ │ │ │ ├── CoreUtil.kt │ │ │ │ │ ├── DownloaderCore.kt │ │ │ │ │ └── IDownloadCore.kt │ │ │ │ ├── fragment/ │ │ │ │ │ ├── AppListFragment.kt │ │ │ │ │ ├── ConfigHelperFragment.kt │ │ │ │ │ ├── DashboardFragment.kt │ │ │ │ │ └── MainFragment.kt │ │ │ │ └── model/ │ │ │ │ └── MainViewModel.kt │ │ │ └── util/ │ │ │ ├── Constant.kt │ │ │ ├── OkHttpHelper.kt │ │ │ ├── Util.kt │ │ │ ├── ViewUtils.kt │ │ │ ├── command/ │ │ │ │ ├── CoreCmd.kt │ │ │ │ ├── SettingCmd.kt │ │ │ │ └── TermCmd.kt │ │ │ ├── modul/ │ │ │ │ └── ModuleManager.kt │ │ │ └── terminal/ │ │ │ └── TerminalHelper.kt │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── ic_app.xml │ │ │ ├── ic_commit.xml │ │ │ ├── ic_config.xml │ │ │ ├── ic_converter.xml │ │ │ ├── ic_dashboard.xml │ │ │ ├── ic_disabled.xml │ │ │ ├── ic_done.xml │ │ │ ├── ic_download.xml │ │ │ ├── ic_enabled.xml │ │ │ ├── ic_error.xml │ │ │ ├── ic_home.xml │ │ │ ├── ic_info.xml │ │ │ ├── ic_loading.xml │ │ │ ├── ic_log.xml │ │ │ ├── ic_modul.xml │ │ │ ├── ic_save.xml │ │ │ ├── ic_search.xml │ │ │ ├── ic_select_all.xml │ │ │ └── ic_setting.xml │ │ ├── layout/ │ │ │ ├── activity_converter.xml │ │ │ ├── activity_core.xml │ │ │ ├── activity_main.xml │ │ │ ├── custom_dialog.xml │ │ │ ├── fragment_app_list.xml │ │ │ ├── fragment_config_helper.xml │ │ │ ├── fragment_dashboard.xml │ │ │ ├── fragment_main.xml │ │ │ ├── item_applist.xml │ │ │ └── setting_dialog.xml │ │ ├── menu/ │ │ │ └── bottom_nav_menu.xml │ │ ├── navigation/ │ │ │ └── nav_main.xml │ │ ├── raw/ │ │ │ ├── clashtemplate │ │ │ └── singboxtemplate │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ ├── styles.xml │ │ │ └── themes.xml │ │ ├── values-night/ │ │ │ ├── colors.xml │ │ │ └── themes.xml │ │ └── xml/ │ │ ├── backup_rules.xml │ │ ├── data_extraction_rules.xml │ │ └── network_security_config.xml │ └── test/ │ └── java/ │ └── xyz/ │ └── chz/ │ └── bfm/ │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── ke/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── de/ │ │ └── markusressel/ │ │ └── kodeeditor/ │ │ └── library/ │ │ ├── extensions/ │ │ │ └── Extensions.kt │ │ └── view/ │ │ ├── CodeEditText.kt │ │ ├── CodeEditorLayout.kt │ │ ├── CodeEditorView.kt │ │ ├── CodeTextView.kt │ │ └── SelectionChangedListener.kt │ └── res/ │ ├── drawable/ │ │ ├── ic_launcher_background.xml │ │ └── ic_launcher_foreground.xml │ ├── layout/ │ │ ├── layout_code_editor__main_layout.xml │ │ ├── view_code_editor__divider.xml │ │ ├── view_code_editor__inner_layout.xml │ │ ├── view_code_editor__linenumbers.xml │ │ └── view_code_editor__minimap.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ ├── values/ │ │ ├── attributes.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── library_kodeeditor_strings.xml │ │ ├── strings.xml │ │ └── themes.xml │ └── values-night/ │ └── themes.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/taamarinbot.py ================================================ import asyncio import os import sys from telethon import TelegramClient from telethon.tl.functions.messages import GetMessagesRequest API_ID = os.environ.get("API_ID") API_HASH = os.environ.get("API_HASH") CHAT_ID = int(os.environ.get("CHAT_ID")) MESSAGE_THREAD_ID = int(os.environ.get("MESSAGE_THREAD_ID")) BOT_TOKEN = os.environ.get("BOT_TOKEN") VERSION = os.environ.get("VERSION") COMMIT = os.environ.get("COMMIT") # TAGS = os.environ.get("TAGS") MSG_TEMPLATE = """ {version} Commit: {commit} [source](https://github.com/taamarin/box.manager) [module](https://github.com/taamarin/box_for_magisk) #apk #manager #BFR #root """.strip() def get_caption(): msg = MSG_TEMPLATE.format( version=VERSION, # tags=TAGS, commit=COMMIT ) if len(msg) > 1024: return COMMIT return msg def check_environ(): if BOT_TOKEN is None: print("[-] Invalid BOT_TOKEN") exit(1) if CHAT_ID is None: print("[-] Invalid CHAT_ID") exit(1) if MESSAGE_THREAD_ID is None: print("[-] Invalid MESSAGE_THREAD_ID") exit(1) if VERSION is None: print("[-] Invalid VERSION") exit(1) if COMMIT is None: print("[-] Invalid COMMIT") exit(1) # if TAGS is None: # print("[-] Invalid TAGS") # exit(1) async def main(): print("[+] Uploading to telegram") check_environ() files = sys.argv[1:] print("[+] Files:", files) if len(files) <= 0: print("[-] No files to upload") exit(1) print("[+] Logging in Telegram with bot") script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) session_dir = os.path.join(script_dir, "bot.session") async with await TelegramClient(session=session_dir, api_id=API_ID, api_hash=API_HASH).start(bot_token=BOT_TOKEN) as bot: caption = [""] * len(files) caption[-1] = get_caption() print("[+] Caption: ") print("---") print(caption) print("---") print("[+] Sending") sent_messages = await bot.send_file(entity=CHAT_ID, file=files, caption=caption, reply_to=MESSAGE_THREAD_ID, parse_mode="markdown") # Pin the last sent message if sent_messages: last_message_id = sent_messages[-1].id await bot.pin_message(entity=CHAT_ID, message=last_message_id) print("[+] Done!") if __name__ == "__main__": try: asyncio.run(main()) except Exception as e: print(f"[-] An error occurred: {e}") ================================================ FILE: .github/workflows/build.yml ================================================ name: build android apps on: workflow_dispatch: push: paths-ignore: - "docs/**" - "README.md" - ".github/ISSUE_TEMPLATE/**" branches: - main jobs: build: permissions: write-all runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/setup-node@v3 with: node-version: '16.x' - uses: actions/setup-java@v3 with: java-version: '17' distribution: 'zulu' - name: update version run: | sed -i "s|versionCode .*|versionCode $(date +%Y%m%d)|g" app/build.gradle sed -i "s|versionName .*|versionName \"1.14-$(git rev-parse --short HEAD)\"|g" app/build.gradle - name: Build with Gradle run: | chmod +x gradlew ./gradlew --no-daemon --no-configuration-cache -q app:assembleRelease - name: checking release version id: version run: | echo ::set-output name=release_version::$(cat app/build.gradle | grep -o "versionName \"[0-9.]*-[a-z,0-9]*\"" | grep -o "[0-9.]*-[a-z,0-9]*") - name: rename apks run: | APK="Box4Root-Manager_v${{ steps.version.outputs.release_version }}.apk" mv -f ./app/build/outputs/apk/release/*.apk ./app/build/outputs/apk/release/$APK - name: upload artifact uses: actions/upload-artifact@v3 if: ${{ success() }} with: name: b4r_manager path: ./app/build/outputs/apk/release/*.apk - uses: andreaswilli/delete-release-assets-action@v2.0.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} tag: Prerelease deleteOnlyFromDrafts: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - uses: richardsimko/update-tag@v1.0.7 with: tag_name: Prerelease env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - uses: softprops/action-gh-release@v1 with: tag_name: Prerelease files: ${{ github.workspace }}/app/build/outputs/apk/release/*.apk draft: false prerelease: true generate_release_notes: true - name: upload to telegram if: ${{ success() }} env: CHAT_ID: "-1001597117128" MESSAGE_THREAD_ID: "282263" API_ID: ${{ secrets.API_ID }} API_HASH: ${{ secrets.API_HASH }} BOT_TOKEN: ${{ secrets.BOT_TOKEN }} run: | if [ ! -z "${{ secrets.BOT_TOKEN }}" ]; then export VERSION="v${{ steps.version.outputs.release_version }}" export COMMIT=$(git log --oneline -n 10 --no-decorate | sed 's/^[0-9a-f]* //' | sed 's/^/— /') FILE=$(find app/build/outputs/apk/release -name "*.apk") pip3 install telethon==1.31.1 python3 $GITHUB_WORKSPACE/.github/taamarinbot.py $FILE fi ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea/caches /.idea/libraries /.idea/modules.xml /.idea/workspace.xml /.idea/navEditor.xml /.idea/assetWizardSettings.xml .DS_Store /build /captures .externalNativeBuild .cxx local.properties .idea .gitmessage ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # BFR Manager

BOX
BOX

BFR Manager

[![ANDROID](https://img.shields.io/badge/Android-3DDC84?logo=android&logoColor=white)]() [![BUILD APK](https://github.com/taamarin/box.manager/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/taamarin/box/actions/workflows/debug.yml) [![TELEGRAM CHANNEL](https://img.shields.io/badge/Telegram-2CA5E0?logo=telegram&logoColor=white)](https://t.me/nothing_taamarin) [![TELEGRAM](https://img.shields.io/badge/Telegram%20-Grups%20-blue?)](https://t.me/taamarin)
================================================ FILE: app/.gitignore ================================================ /build /libs ================================================ FILE: app/build.gradle ================================================ plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-parcelize' id 'kotlin-kapt' id 'dagger.hilt.android.plugin' id 'androidx.navigation.safeargs' } android { namespace 'xyz.chz.bfm' compileSdk 33 defaultConfig { applicationId "xyz.chz.bfm" minSdk 24 targetSdk 33 versionCode 20241205 versionName "1.14" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } signingConfigs { release { storeFile file('release.keystore') storePassword 'qwerty' keyAlias 'key.alias' keyPassword 'qwerty' } } buildTypes { release { signingConfig signingConfigs.release minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { viewBinding true } } dependencies { implementation project(':ke') implementation 'androidx.core:core-ktx:1.9.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3' implementation 'androidx.navigation:navigation-ui-ktx:2.5.3' implementation 'com.google.dagger:hilt-android:2.43.2' kapt 'com.google.dagger:hilt-compiler:2.43.2' implementation 'io.reactivex:rxjava:1.3.8' implementation 'io.reactivex:rxandroid:1.2.1' implementation 'androidx.preference:preference-ktx:1.2.1' implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1' implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.1' } ================================================ FILE: app/proguard-rules.pro ================================================ -keep class xyz.chz.bfm.data.** { *; } -keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* { long producerIndex; long consumerIndex; } ================================================ FILE: app/src/androidTest/java/xyz/chz/bfm/ExampleInstrumentedTest.kt ================================================ package xyz.chz.bfm import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("xyz.chz.bfm", appContext.packageName) } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/xyz/chz/bfm/BFRApp.kt ================================================ package xyz.chz.bfm import android.app.Application import android.os.StrictMode import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class BFRApp : Application() { override fun onCreate() { super.onCreate() val policy = StrictMode.ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(policy) } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/adapter/AppListAdapter.kt ================================================ package xyz.chz.bfm.adapter import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import xyz.chz.bfm.R import xyz.chz.bfm.data.AppInfo import xyz.chz.bfm.databinding.ItemApplistBinding class AppListAdapter( val activity: Activity, val apps: List, blacklist: MutableSet? ) : RecyclerView.Adapter() { companion object { private const val VIEW_TYPE_HEADER = 0 private const val VIEW_TYPE_ITEM = 1 } val blacklist = if (blacklist == null) HashSet() else HashSet(blacklist) override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { if (holder is AppViewHolder) { val appInfo = apps[position - 1] holder.bind(appInfo) } } override fun getItemCount() = apps.size + 1 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { val ctx = parent.context return when (viewType) { VIEW_TYPE_HEADER -> { val view = View(ctx) view.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ctx.resources.getDimensionPixelSize(R.dimen.list_header_height) * 0 ) BaseViewHolder(view) } else -> AppViewHolder( ItemApplistBinding.inflate( LayoutInflater.from(ctx), parent, false ) ) } } override fun getItemViewType(position: Int) = if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) inner class AppViewHolder(private val item: ItemApplistBinding) : BaseViewHolder(item.root), View.OnClickListener { private lateinit var appInfo: AppInfo private val inBlacklist: Boolean get() = blacklist.contains(appInfo.packageName) fun bind(appInfo: AppInfo) { this.appInfo = appInfo with(item) { icon.setImageDrawable(appInfo.appIcon) checkBox.isChecked = inBlacklist item.packageName.text = appInfo.packageName if (appInfo.isSystemApp) { item.name.text = String.format("** %1s", appInfo.appName) } else { item.name.text = appInfo.appName } } itemView.setOnClickListener(this) } override fun onClick(v: View?) { if (inBlacklist) { blacklist.remove(appInfo.packageName) item.checkBox.isChecked = false } else { blacklist.add(appInfo.packageName) item.checkBox.isChecked = true } } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/data/AppInfo.kt ================================================ package xyz.chz.bfm.data import android.graphics.drawable.Drawable data class AppInfo( val appName: String, val packageName: String, val appIcon: Drawable, val isSystemApp: Boolean, var isSelected: Int ) ================================================ FILE: app/src/main/java/xyz/chz/bfm/data/AppManager.kt ================================================ package xyz.chz.bfm.data import android.Manifest import android.content.Context import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import android.content.pm.PackageManager import rx.Observable object AppManager { fun loadNetworkAppList(ctx: Context): ArrayList { val packageManager = ctx.packageManager val packages = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS) val apps = ArrayList() for (pkg in packages) { if (!pkg.hasInternetPermission && pkg.packageName != "android") continue val applicationInfo = pkg.applicationInfo val appName = applicationInfo.loadLabel(packageManager).toString() val appIcon = applicationInfo.loadIcon(packageManager) val isSystemApp = (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) > 0 val appInfo = AppInfo(appName, pkg.packageName, appIcon, isSystemApp, 0) apps.add(appInfo) } return apps } fun rxLoadNetworkAppList(ctx: Context): Observable> = Observable.unsafeCreate { it.onNext(loadNetworkAppList(ctx)) } val PackageInfo.hasInternetPermission: Boolean get() { val permissions = requestedPermissions return permissions?.any { it == Manifest.permission.INTERNET } ?: false } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/dialog/IMakeDialog.kt ================================================ package xyz.chz.bfm.dialog import androidx.fragment.app.DialogFragment interface IMakeDialog { fun onDialogPositiveButton(dialog: DialogFragment) } ================================================ FILE: app/src/main/java/xyz/chz/bfm/dialog/ISettingDialog.kt ================================================ package xyz.chz.bfm.dialog import androidx.fragment.app.DialogFragment interface ISettingDialog { fun onLoading(dialog: DialogFragment) fun onAbout(dialog: DialogFragment) fun onUpdate(dialog: DialogFragment) fun onCheckIP(dialog: DialogFragment) } ================================================ FILE: app/src/main/java/xyz/chz/bfm/dialog/MakeDialog.kt ================================================ package xyz.chz.bfm.dialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import xyz.chz.bfm.databinding.CustomDialogBinding class MakeDialog( private val strTitle: String? = "", private val strMsg: String? = "", private val isClick: Boolean? = false, private val canCancel: Boolean? = true ) : MaterialDialogFragment() { private lateinit var binding: CustomDialogBinding lateinit var listener: IMakeDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = CustomDialogBinding.inflate(layoutInflater, container, false) return binding.root } @Deprecated("Deprecated in Java") override fun onAttachFragment(childFragment: Fragment) { super.onAttachFragment(childFragment) try { listener = context as IMakeDialog } catch (e: ClassCastException) { throw ClassCastException("not cast") } } override fun onAttach(context: Context) { super.onAttach(context) try { listener = context as IMakeDialog } catch (e: ClassCastException) { throw ClassCastException("not cast") } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { isCancelable = canCancel!! tvTitle.text = strTitle tvMessage.text = strMsg btnOk.setOnClickListener { if (isClick!!) listener.onDialogPositiveButton(this@MakeDialog) this@MakeDialog.dismiss() } } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/dialog/MaterialDialogFragment.kt ================================================ package xyz.chz.bfm.dialog import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import xyz.chz.bfm.R open class MaterialDialogFragment : DialogFragment() { private var dialogView: View? = null @SuppressLint("UseGetLayoutInflater") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return MaterialAlertDialogBuilder( requireContext(), R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_background ).apply { dialogView = onCreateView(LayoutInflater.from(requireContext()), null, savedInstanceState) dialogView?.let { onViewCreated(it, savedInstanceState) } setView(dialogView) }.create() } override fun getView(): View? { return dialogView } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/dialog/SettingDialog.kt ================================================ package xyz.chz.bfm.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.Spinner import androidx.fragment.app.Fragment import xyz.chz.bfm.R import xyz.chz.bfm.databinding.SettingDialogBinding import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.SettingCmd class SettingDialog : MaterialDialogFragment() { private lateinit var binding: SettingDialogBinding lateinit var listener: ISettingDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { super.onCreateView(inflater, container, savedInstanceState) binding = SettingDialogBinding.inflate(layoutInflater, container, false) return binding.root } @Deprecated("Deprecated in Java") override fun onAttachFragment(childFragment: Fragment) { super.onAttachFragment(childFragment) try { listener = context as ISettingDialog } catch (e: ClassCastException) { throw ClassCastException("not cast") } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) enableDisable(!Util.isProxyed) binding.apply { with(SettingCmd) { coreSelector.apply { buildSpinner(resources.getStringArray(R.array.core_array), this) setSelection( when (core) { "clash" -> 0 "sing-box" -> 1 "xray" -> 2 "hysteria" -> 3 else -> 4 } ) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val isClashSelected = position == 0 val visibility = if (isClashSelected) View.VISIBLE else View.GONE clash1.visibility = visibility clash2.visibility = visibility clash4.visibility = visibility clash5.visibility = visibility clash6.visibility = visibility clash7.visibility = visibility clash8.visibility = visibility setCore = when (position) { 0 -> "clash" 1 -> "sing-box" 2 -> "xray" 3 -> "hysteria" else -> "v2fly" } } override fun onNothingSelected(parent: AdapterView<*>?) { } } } spFindProc.apply { buildSpinner(resources.getStringArray(R.array.proc_array), this) when (findProc) { "off" -> setSelection(0) "strict" -> setSelection(1) else -> setSelection(2) } onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long ) { when (p2) { 1 -> setFindProc("strict") 2 -> setFindProc("always") else -> setFindProc("off") } } override fun onNothingSelected(p0: AdapterView<*>?) {} } } spFindConf.apply { buildSpinner(resources.getStringArray(R.array.conf_array), this) when (findConf) { "config.yaml" -> setSelection(0) "config2.yaml" -> setSelection(1) else -> setSelection(2) } onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long ) { when (p2) { 1 -> setFindConf("config2.yaml") 2 -> setFindConf("config3.yaml") else -> setFindConf("config.yaml") } } override fun onNothingSelected(p0: AdapterView<*>?) {} } } spClashType.apply { buildSpinner(resources.getStringArray(R.array.clash_core_array), this) setSelection(if (clashType == "premium") 0 else 1) onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long ) { setClashType(if (p2 == 0) "premium" else "mihomo") } override fun onNothingSelected(p0: AdapterView<*>?) { } } } spNetworkMode.apply { buildSpinner(resources.getStringArray(R.array.network_array), this) when (networkMode) { "tproxy" -> setSelection(0) "redirect" -> setSelection(1) "enhance" -> setSelection(2) "mixed" -> setSelection(3) else -> setSelection(4) } onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long ) { when (p2) { 1 -> setNetworkMode("redirect") 2 -> setNetworkMode("enhance") 3 -> setNetworkMode("mixed") 4 -> setNetworkMode("tun") else -> setNetworkMode("tproxy") } } override fun onNothingSelected(p0: AdapterView<*>?) {} } } spProxyMode.apply { buildSpinner(resources.getStringArray(R.array.proxy_array), this) when (proxyMode) { "whitelist" -> setSelection(0) else -> setSelection(1) } onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long ) { when (p2) { 1 -> setProxyMode("blacklist") else -> setProxyMode("whitelist") } } override fun onNothingSelected(p0: AdapterView<*>?) {} } } cbunifiedDelay.apply { isChecked = unified setOnCheckedChangeListener { _, b -> if (b) setUnified("true") else setUnified("false") } } cbsnifferrs.apply { isChecked = sniffer setOnCheckedChangeListener { _, b -> if (b) setSniffer("true") else setSniffer("false") } } cbredirHost.apply { isChecked = redirHost setOnCheckedChangeListener { _, b -> if (b) setRedirHost("redir-host") else setRedirHost("fake-ip") } } cbgeodataMod.apply { isChecked = geodata setOnCheckedChangeListener { _, b -> if (b) setGeodata("true") else setGeodata("false") } } cbsubs.apply { isChecked = subs.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setSubs("true") else setSubs("false") } } cbgeo.apply { isChecked = geo.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setGeo("true") else setGeo("false") } } cbmemcg.apply { isChecked = memcg.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setMemcg("true") else setMemcg("false") } } cbblkio.apply { isChecked = blkio.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setBlkio("true") else setBlkio("false") } } cbcpuset.apply { isChecked = cpuset.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setCpuset("true") else setCpuset("false") } } cbquic.apply { isChecked = quic setOnCheckedChangeListener { _, b -> if (b) setQuic("enable") else setQuic("disable") } } cbipv6.apply { isChecked = ipv6 setOnCheckedChangeListener { _, b -> if (b) setIpv6("true") else setIpv6("false") } } cbcron.apply { isChecked = cron.toBoolean() setOnCheckedChangeListener { _, b -> if (b) setCron("true") else setCron("false") } } aboutApp.setOnClickListener { listener.onAbout(this@SettingDialog) } checkIp.setOnClickListener { listener.onCheckIP(this@SettingDialog) this@SettingDialog.dismiss() } checkModule.setOnClickListener { listener.onUpdate(this@SettingDialog) this@SettingDialog.dismiss() } } } listener.onLoading(this@SettingDialog) } private fun buildSpinner(arr: Array, spin: Spinner) { val aa = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, arr) aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spin.adapter = aa } private fun enableDisable(bo: Boolean) = with(binding) { cbunifiedDelay.isEnabled = bo cbsnifferrs.isEnabled = bo cbcron.isEnabled = bo cbipv6.isEnabled = bo cbquic.isEnabled = bo cbmemcg.isEnabled = bo cbblkio.isEnabled = bo cbcpuset.isEnabled = bo cbgeo.isEnabled = bo cbsubs.isEnabled = bo cbgeodataMod.isEnabled = bo cbredirHost.isEnabled = bo coreSelector.isEnabled = bo spProxyMode.isEnabled = bo spNetworkMode.isEnabled = bo spClashType.isEnabled = bo spFindProc.isEnabled = bo spFindConf.isEnabled = bo } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/enm/StatusConnection.kt ================================================ package xyz.chz.bfm.enm enum class StatusConnection(val str: String) { Enabled("Enabled"), Error("Error"), Disabled("Disabled"), Loading("Loading"), Unknown("Unknown") } ================================================ FILE: app/src/main/java/xyz/chz/bfm/service/TileBox.kt ================================================ package xyz.chz.bfm.service import android.service.quicksettings.Tile import android.service.quicksettings.TileService import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.TermCmd class TileBox : TileService() { override fun onClick() { super.onClick() when (qsTile.state) { Tile.STATE_INACTIVE -> { qsTile.state = Tile.STATE_ACTIVE qsTile.updateTile() TermCmd.start { Util.isProxyed = if (it) { qsTile.state = Tile.STATE_ACTIVE qsTile.updateTile() true } else { qsTile.state = Tile.STATE_INACTIVE qsTile.updateTile() false } } } else -> { qsTile.state = Tile.STATE_INACTIVE qsTile.updateTile() TermCmd.stop { Util.isProxyed = if (it) { qsTile.state = Tile.STATE_INACTIVE qsTile.updateTile() false } else { qsTile.state = Tile.STATE_ACTIVE qsTile.updateTile() true } } } } } override fun onStartListening() { super.onStartListening() if (Util.isProxyed) qsTile.state = Tile.STATE_ACTIVE else qsTile.state = Tile.STATE_INACTIVE qsTile.updateTile() } override fun onStopListening() { super.onStopListening() qsTile.updateTile() } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/MainActivity.kt ================================================ package xyz.chz.bfm.ui import android.os.Bundle import android.view.View import android.view.WindowManager import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.bottomnavigation.BottomNavigationView import dagger.hilt.android.AndroidEntryPoint import xyz.chz.bfm.R import xyz.chz.bfm.databinding.ActivityMainBinding import xyz.chz.bfm.ui.base.BaseActivity @AndroidEntryPoint class MainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navBottom val navController = findNavController(R.id.nav_host_fragment_container) navView.setupWithNavController(navController) navController.addOnDestinationChangedListener { _, dest, _ -> if (dest.id == R.id.nav_dashboard) this.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) if (dest.id == R.id.configHelperFragment) navView.visibility = View.GONE else navView.visibility = View.VISIBLE } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/base/BaseActivity.kt ================================================ package xyz.chz.bfm.ui.base import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import dagger.hilt.android.AndroidEntryPoint import xyz.chz.bfm.R import xyz.chz.bfm.dialog.IMakeDialog import xyz.chz.bfm.dialog.MakeDialog import xyz.chz.bfm.enm.StatusConnection import xyz.chz.bfm.util.modul.ModuleManager @AndroidEntryPoint open class BaseActivity : AppCompatActivity(), IMakeDialog { private var state: Int? = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ModuleManager.moduleVersionCode == "") { val df = MakeDialog( StatusConnection.Error.str, getString(R.string.module_not_found), true, false ) df.listener = this df.show(supportFragmentManager, "") } else { if (ModuleManager.moduleVersionCode.toInt() < getString(R.string.min_module_vrsion).toInt()) { val df = MakeDialog( StatusConnection.Loading.str, String.format( getString(R.string.update_module), ModuleManager.moduleVersionCode.toInt() ), true, false ) df.listener = this df.show(supportFragmentManager, "") state = 1 } } } override fun onDialogPositiveButton(dialog: DialogFragment) { when (state) { 1 -> { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.release_repo_url))) startActivity(intent) finish() } else -> { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.module_repo_url))) startActivity(intent) finish() } } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/ConfigManager.kt ================================================ package xyz.chz.bfm.ui.converter import org.json.JSONObject import xyz.chz.bfm.ui.converter.config.ClashData import xyz.chz.bfm.ui.converter.config.ConfigType import xyz.chz.bfm.ui.converter.config.ConfigUtil import xyz.chz.bfm.ui.converter.config.SingBoxData import java.util.regex.Pattern object ConfigManager { fun importConfig(config: String, isClash: Boolean, useIndent: Boolean = false): String { try { if (config.startsWith(ConfigType.VMESS.scheme)) { var result = config.replace(ConfigType.VMESS.scheme, "") result = ConfigUtil.decode(result) if (result.isEmpty()) { return "failed decode vms" } return if (isClash) ClashData(result, useIndent).newVmessConfig() else SingBoxData( result ).vmessSing() } else if (config.startsWith(ConfigType.VLESS.scheme)) { return if (isClash) ClashData(config, useIndent).newVlessConfig() else SingBoxData( config ).vlessSing() } else if (config.startsWith(ConfigType.TROJAN.scheme) || config.startsWith(ConfigType.TROJANGO.scheme)) { return if (isClash) ClashData(config, useIndent).newTrojanConfig() else SingBoxData( config ).trojanSing() } else { return "" } } catch (_: Exception) { } return "" } fun fullClashSimple(config: String, strRaw: String): String { val name = "match" val p = Pattern.compile("- name:(.*)") val m = p.matcher(config) val sb = StringBuilder() while (m.find()) { sb.appendLine(" - ${m.group(1)?.trim()}") } return String.format( strRaw, config, ClashData().proxyGroupBuilder(name, sb.toString()), name ) } fun fullSingSimple(config: String, strRaw: String): String { val s = ArrayList() val p = Pattern.compile("\"tag\":(.*)") val m = p.matcher(config) val sb = StringBuilder() while (m.find()) { s.add(m.group(1)?.trim()!!.replace("\"|,", "")) } sb.appendLine(SingBoxData().buildHeaderSlector(s)) sb.appendLine(SingBoxData().buildHeaderBestUrl(s)) sb.append(config) sb.appendLine(SingBoxData().buildFooter()) val strResult = String.format(strRaw, sb.toString()) return JSONObject(strResult).toString(2).replace("\\", "").replace("null,", "") } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/ConverterActivity.kt ================================================ package xyz.chz.bfm.ui.converter import android.os.Bundle import androidx.annotation.RawRes import androidx.appcompat.app.AppCompatActivity import dagger.hilt.android.AndroidEntryPoint import xyz.chz.bfm.R import xyz.chz.bfm.databinding.ActivityConverterBinding import xyz.chz.bfm.util.copyToClipboard import xyz.chz.bfm.util.isValidCheck import xyz.chz.bfm.util.removeEmptyLines import xyz.chz.bfm.util.toast @AndroidEntryPoint class ConverterActivity : AppCompatActivity() { private lateinit var binding: ActivityConverterBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityConverterBinding.inflate(layoutInflater) setContentView(binding.root) setupConfig() } private fun setupConfig() = with(binding) { var isFull = false var isSing = false fullClashConfig.setOnCheckedChangeListener { _, b -> isFull = b isSing = false fullSingConfig.isChecked = false } fullSingConfig.setOnCheckedChangeListener { _, b -> if (b) { isSing = true isFull = false fullClashConfig.isChecked = false } } btnConvert.setOnClickListener { if (textInput.isValidCheck()) { val str = textInput.removeEmptyLines() val spltStr = str.split("\n") val result = StringBuilder() for (x in spltStr) { result.appendLine( if (isSing) ConfigManager.importConfig( x, false ) + "," else ConfigManager.importConfig(x, true) ) } if (isFull) tvResult.text = ConfigManager.fullClashSimple( result.toString(), readRawFile(R.raw.clashtemplate) ) else tvResult.text = if (isSing) ConfigManager.fullSingSimple( result.toString(), readRawFile(R.raw.singboxtemplate) ) else result tvResult.apply { setOnClickListener { toast("Copied to Clipboard!", this@ConverterActivity) copyToClipboard(this@ConverterActivity) } } toast("Click result for copy config", this@ConverterActivity) } else toast("???????????", this@ConverterActivity) } } private fun readRawFile(@RawRes id: Int): String { return resources.openRawResource(id).bufferedReader().readText() } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/config/ClashData.kt ================================================ package xyz.chz.bfm.ui.converter.config import android.net.Uri import org.json.JSONObject import java.net.URLDecoder import kotlin.random.Random class ClashData(private val masuk: String = "", private val indent: Boolean = false) { fun proxyGroupBuilder(nameProxy: String, listProxy: String): String { val sb = StringBuilder() sb.appendLine("- name: $nameProxy") sb.appendLine(" type: select") sb.appendLine(" proxies:") sb.appendLine(" - urltest") sb.appendLine(" - loadbalance") sb.appendLine(" - fallback") sb.append(listProxy) sb.appendLine("- name: urltest") sb.appendLine(" type: url-test") sb.appendLine(" url: 'http://www.gstatic.com/generate_204'") sb.appendLine(" interval: 300") sb.appendLine(" proxies:") sb.append(listProxy) sb.appendLine("- name: loadbalance") sb.appendLine(" type: load-balance") sb.appendLine(" url: 'http://www.gstatic.com/generate_204'") sb.appendLine(" interval: 300") sb.appendLine(" # strategy: consistent-hashing # 可选 round-robin 和 sticky-sessions") sb.appendLine(" proxies:") sb.append(listProxy) sb.appendLine("- name: fallback") sb.appendLine(" type: fallback") sb.appendLine(" url: 'http://www.gstatic.com/generate_204'") sb.appendLine(" interval: 300") sb.appendLine(" proxies:") sb.append(listProxy) return sb.toString() } fun newVmessConfig(): String { val jo = JSONObject(masuk) val sb = StringBuilder() val idnt: String = if (indent) " " else "" sb.appendLine( "${idnt}- name: ${ jo.optString( "ps", jo.optString("add", "new") ) }_vmess_${Random.nextInt(0, 7000)}" ) sb.appendLine("$idnt server: ${jo.optString("add", jo.optString("host", ""))}") sb.appendLine("$idnt port: ${jo.getString("port")}") sb.appendLine("$idnt type: vmess") sb.appendLine("$idnt uuid: ${jo.getString("id")}") sb.appendLine("$idnt alterId: ${jo.optString("aid", "0")}") sb.appendLine("$idnt cipher: ${jo.optString("scy", "auto")}") sb.appendLine("$idnt tls: ${jo.optString("tls", "") == "tls"}") sb.appendLine("$idnt servername: ${jo.optString("sni", jo.optString("add", ""))}") sb.appendLine("$idnt skip-cert-verify: true") sb.appendLine("$idnt udp: true") when (jo.optString("net", "tcp")) { "ws" -> { sb.appendLine("$idnt network: ws") sb.appendLine("$idnt ws-opts:") sb.appendLine("$idnt path: ${jo.optString("path", "/")}") sb.appendLine("$idnt headers:") sb.append("$idnt Host: ${jo.getString("host")}") } "grpc" -> { sb.appendLine("$idnt network: grpc") sb.appendLine("$idnt grpc-opts:") sb.append("$idnt grpc-service-name: ${jo.getString("path")}") } "h2" -> { sb.appendLine("$idnt network: h2") sb.appendLine("$idnt h2-opts:") sb.append("$idnt path: ${jo.optString("path", "/")}") } "tcp" -> { if (jo.optString("type", "") == "http") { sb.appendLine("$idnt network: http") sb.appendLine("$idnt http-opts:") sb.append("$idnt path: ${jo.optString("path", "/")}") } } else -> throw Exception("${jo.getString("net")} not supported") } return sb.toString() } fun newVlessConfig(): String { val sb = StringBuilder() val idnt: String = if (indent) " " else "" var url = masuk if (!url.contains("@")) url = ConfigUtil.safeDecodeURLB64(url) val uri = Uri.parse(url) sb.appendLine( "${idnt}- name: ${uri.fragment ?: "new"}_${uri.scheme}_${ Random.nextInt( 0, 7000 ) }" ) sb.appendLine("$idnt server: ${uri.host ?: ""}") sb.appendLine("$idnt port: ${uri.port}") sb.appendLine("$idnt type: vless") if (uri.userInfo == null || uri.userInfo!!.isEmpty()) throw Exception("no user info") sb.appendLine("$idnt uuid: ${uri.userInfo}") sb.appendLine( "$idnt tls: ${ (ConfigUtil.getQueryParams( uri, "security" ) ?: "") == "tls" }" ) sb.appendLine( "$idnt servername: ${ ConfigUtil.getQueryParams( uri, "sni" ) ?: ConfigUtil.getQueryParams(uri, "host") ?: uri.host!! }" ) sb.appendLine("$idnt skip-cert-verify: true") sb.appendLine("$idnt udp: true") if (ConfigUtil.getQueryParams( uri, "flow" ) != null ) sb.appendLine("$idnt flow: ${ConfigUtil.getQueryParams(uri, "flow")!!}") val type = ConfigUtil.getQueryParams(uri, "type") ?: "tcp" val decodePath = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "path") ?: "", "UTF-8") val decodeHost = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "host") ?: "", "UTF-8") when (type) { "ws" -> { sb.appendLine("$idnt network: ws") sb.appendLine("$idnt ws-opts:") sb.appendLine("$idnt path: $decodePath") sb.appendLine("$idnt headers:") sb.append("$idnt Host: $decodeHost") } "tcp" -> {} "http" -> {} "grpc" -> { sb.appendLine("$idnt network: grpc") sb.appendLine("$idnt grpc-opts:") sb.append( "$idnt grpc-service-name: ${ ConfigUtil.getQueryParams( uri, "serviceName" ) ?: "" }" ) } else -> throw Exception("$type not supported") } return sb.toString() } fun newTrojanConfig(): String { val sb = StringBuilder() val idnt: String = if (indent) " " else "" var url = masuk if (!url.contains("@")) url = ConfigUtil.safeDecodeURLB64(url) val uri = Uri.parse(url) sb.appendLine( "${idnt}- name: ${uri.fragment ?: "new"}_${uri.scheme}_${ Random.nextInt( 0, 7000 ) }" ) sb.appendLine("$idnt server: ${uri.host ?: ""}") sb.appendLine("$idnt port: ${uri.port}") sb.appendLine("$idnt type: trojan") if (uri.userInfo == null || uri.userInfo!!.isEmpty()) throw Exception("no user info") sb.appendLine("$idnt password: ${uri.userInfo}") sb.appendLine( "$idnt sni: ${ ConfigUtil.getQueryParams( uri, "sni" ) ?: ConfigUtil.getQueryParams(uri, "host") ?: uri.host!! }" ) sb.appendLine("$idnt skip-cert-verify: true") sb.appendLine("$idnt udp: true") if (ConfigUtil.getQueryParams( uri, "flow" ) != null ) sb.appendLine("$idnt flow: ${ConfigUtil.getQueryParams(uri, "flow")!!}") val alpnStr = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "alpn") ?: "", "UTF-8") if (alpnStr != "") sb.appendLine("$idnt alpn: ${alpnStr.split(",")}") val type = ConfigUtil.getQueryParams(uri, "type") ?: "tcp" val decodePath = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "path") ?: "", "UTF-8") val decodeHost = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "host") ?: "", "UTF-8") when (type) { "ws" -> { sb.appendLine("$idnt network: ws") sb.appendLine("$idnt ws-opts:") sb.appendLine("$idnt path: $decodePath") sb.appendLine("$idnt headers:") sb.append("$idnt Host: $decodeHost") } "tcp" -> {} "http" -> {} "grpc" -> { sb.appendLine("$idnt network: grpc") sb.appendLine("$idnt grpc-opts:") sb.append( "$idnt grpc-service-name: ${ ConfigUtil.getQueryParams( uri, "serviceName" ) ?: "" }" ) } else -> throw Exception("$type not supported") } return sb.toString() } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/config/ConfigType.kt ================================================ package xyz.chz.bfm.ui.converter.config enum class ConfigType(val scheme: String) { VMESS("vmess://"), VLESS("vless://"), TROJAN("trojan://"), TROJANGO("trojan-go://") } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/config/ConfigUtil.kt ================================================ package xyz.chz.bfm.ui.converter.config import android.net.Uri import android.util.Base64 object ConfigUtil { fun safeDecodeURLB64(url: String): String { val split = url.split("://").toTypedArray() val schema = split[0] val result = split[1].substring(5) .replace(' ', '-') .replace('/', '_') .replace('+', '-') return "$schema://$result" } fun getQueryParams(uri: Uri, param: String): String? { for (p in uri.queryParameterNames) { if (param.equals(p, ignoreCase = true)) return uri.getQueryParameter(p) } return null } fun decode(text: String): String { tryDecodeBase64(text)?.let { return it } if (text.endsWith('=')) { // try again for some loosely formatted base64 tryDecodeBase64(text.trimEnd('='))?.let { return it } } return "" } private fun tryDecodeBase64(text: String): String? { try { return Base64.decode(text, Base64.NO_WRAP).toString(charset("UTF-8")) } catch (e: Exception) { e.printStackTrace() } try { return Base64.decode(text, Base64.NO_WRAP.or(Base64.URL_SAFE)) .toString(charset("UTF-8")) } catch (e: Exception) { e.printStackTrace() } return null } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/converter/config/SingBoxData.kt ================================================ package xyz.chz.bfm.ui.converter.config import android.net.Uri import org.json.JSONObject import xyz.chz.bfm.util.Util import java.net.URLDecoder import kotlin.random.Random //Template sing-box copied from singribet.deno.dev class SingBoxData(private val masuk: String = "") { fun vmessSing(): String { val jo = JSONObject(masuk) val json = Util.json { "tag" to "${jo.optString("ps", jo.optString("add", "new"))}_vmess_${ Random.nextInt( 0, 7000 ) }" "type" to "vmess" "server" to jo.optString("add", jo.optString("host", "")) "server_port" to jo.getString("port").toInt() "uuid" to jo.getString("id") "security" to jo.optString("scy", "auto") "alter_id" to jo.optString("aid", "0").toInt() "multiplex" to { "enabled" to false "protocol" to "smux" "max_streams" to 32 } if (jo.optString("tls", "") == "tls") { "tls" to { "enabled" to true "server_name" to jo.optString("sni", jo.optString("add", "")) "insecure" to true "disable_sni" to false } } val type = jo.optString("net", "tcp") when (type) { "ws" -> { "transport" to { "type" to "ws" "path" to jo.optString("path", "/") "headers" to { "Host" to jo.optString("host", jo.optString("add", "")) } } } "grpc" -> { "transport" to { "type" to "grpc" "service_name" to jo.optString("path", "/") } } "tcp" -> {} "h2" -> {} else -> throw Exception("$type not supported") } } return json.toString(2) } fun vlessSing(): String { var url = masuk if (!url.contains("@")) url = ConfigUtil.safeDecodeURLB64(url) val uri = Uri.parse(url) val json = Util.json { "tag" to "${uri.fragment ?: "new"}_${uri.scheme}_${ Random.nextInt( 0, 7000 ) }" "type" to "vless" ("server" to uri.host) "server_port" to uri.port.toInt() if (uri.userInfo == null || uri.userInfo!!.isEmpty()) throw Exception("no user info") "uuid" to uri.userInfo if (ConfigUtil.getQueryParams( uri, "flow" ) != null ) "flow" to ConfigUtil.getQueryParams(uri, "flow")!! else "flow" to "" "packet_encoding" to "xudp" "multiplex" to { "enabled" to false "protocol" to "smux" "max_streams" to 32 } if ((ConfigUtil.getQueryParams(uri, "security") ?: "") == "tls") { "tls" to { "enabled" to true "server_name" to (ConfigUtil.getQueryParams(uri, "sni") ?: ConfigUtil.getQueryParams(uri, "host") ?: uri.host!!) "insecure" to true "disable_sni" to false } } val decodePath = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "path") ?: "", "UTF-8") val decodeHost = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "host") ?: "", "UTF-8") val type = ConfigUtil.getQueryParams(uri, "type") ?: "tcp" when (type) { "ws" -> { "transport" to { "type" to "ws" "path" to decodePath "headers" to { "Host" to decodeHost } } } "grpc" -> { "transport" to { "type" to "grpc" ("service_name" to ConfigUtil.getQueryParams(uri, "serviceName")) "idle_timeout" to "15s" "ping_timeout" to "15s" "permit_without_stream" to false } } "tcp" -> {} "http" -> {} else -> throw Exception("$type not supported") } } return json.toString(2) } fun trojanSing(): String { var url = masuk if (!url.contains("@")) url = ConfigUtil.safeDecodeURLB64(url) val uri = Uri.parse(url) val json = Util.json { "tag" to "${uri.fragment ?: "new"}_${uri.scheme}_${ Random.nextInt( 0, 7000 ) }" "type" to "trojan" ("server" to uri.host) "server_port" to uri.port.toInt() if (uri.userInfo == null || uri.userInfo!!.isEmpty()) throw Exception("no user info") "password" to uri.userInfo "multiplex" to { "enabled" to false "protocol" to "smux" "max_streams" to 32 } if ((ConfigUtil.getQueryParams(uri, "security") ?: "") == "tls") { "tls" to { "enabled" to true "server_name" to (ConfigUtil.getQueryParams(uri, "sni") ?: ConfigUtil.getQueryParams(uri, "host") ?: uri.host!!) "insecure" to true "disable_sni" to false } } val decodePath = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "path") ?: "", "UTF-8") val decodeHost = URLDecoder.decode(ConfigUtil.getQueryParams(uri, "host") ?: "", "UTF-8") val type = ConfigUtil.getQueryParams(uri, "type") ?: "tcp" when (type) { "ws" -> { "transport" to { "type" to "ws" "path" to decodePath "headers" to { "Host" to decodeHost } } } "grpc" -> { "transport" to { "type" to "grpc" ("service_name" to ConfigUtil.getQueryParams(uri, "serviceName")) "idle_timeout" to "15s" "ping_timeout" to "15s" "permit_without_stream" to false } } "tcp" -> {} "http" -> {} else -> throw Exception("$type not supported") } } return json.toString(2) } fun buildHeaderSlector(arrName: ArrayList): String { val sb = StringBuilder() sb.append("{\"type\": \"selector\",\"tag\": \"match\",") sb.append("\"outbounds\": [\"urltest\",") for (x in arrName) sb.append(x) sb.append("]},") return sb.toString().replace(",]", "]") } fun buildHeaderBestUrl(arrName: ArrayList): String { val sb = StringBuilder() sb.append("{\"type\": \"urltest\",\"tag\": \"urltest\",\"url\": \"http://www.gstatic.com/generate_204\",\"interval\": \"1m\",\"tolerance\": 50,\"interrupt_exist_connections\": false,") sb.append("\"outbounds\": [") for (x in arrName) sb.append(x) sb.append("]},") sb.append("{\"type\": \"selector\",\"tag\": \"ads-all\",") sb.append("\"outbounds\": [\"direct\",\"block\",\"match\"") sb.append("]},") return sb.toString().replace(",]", "]") } fun buildFooter(): String { val json = Util.json { "type" to "direct" "tag" to "direct" } val json2 = Util.json { "type" to "block" "tag" to "block" } val json3 = Util.json { "type" to "dns" "tag" to "dns-out" } return "${json.toString(2)},\n${json2.toString(2)},\n${json3.toString(2)}" } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/core/CoreActivity.kt ================================================ package xyz.chz.bfm.ui.core import android.annotation.SuppressLint import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import dagger.hilt.android.AndroidEntryPoint import okhttp3.Call import okhttp3.Callback import okhttp3.Response import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import xyz.chz.bfm.databinding.ActivityCoreBinding import xyz.chz.bfm.ui.core.util.CoreUtil import xyz.chz.bfm.ui.core.util.DownloaderCore import xyz.chz.bfm.ui.core.util.IDownloadCore import xyz.chz.bfm.util.META_DOWNLOAD import xyz.chz.bfm.util.META_REPO import xyz.chz.bfm.util.OkHttpHelper import xyz.chz.bfm.util.SING_DOWNLOAD import xyz.chz.bfm.util.SING_REPO import xyz.chz.bfm.util.command.CoreCmd import xyz.chz.bfm.util.toast import xyz.chz.bfm.util.urlText import java.io.IOException @AndroidEntryPoint @SuppressLint("SetTextI18n") class CoreActivity : AppCompatActivity() { private lateinit var binding: ActivityCoreBinding private lateinit var dCore: DownloaderCore private var urlClash = "" private var urlSing = "" private var tagNameClash = "" private var tagNameSing = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCoreBinding.inflate(layoutInflater) setContentView(binding.root) dCore = DownloaderCore(this) checkClash() buttonUp() } private fun checkClash() = with(binding) { tvClash.text = "Checking for mihomo" prgClash.isVisible = true OkHttpHelper().reqGithub(META_REPO, object : Callback { override fun onFailure(call: Call, e: IOException) { runOnUiThread { tvClash.text = "Failed to get repo clash, check ur internet connection" prgClash.isVisible = false } } override fun onResponse(call: Call, response: Response) { val respom = response.body!!.string() runOnUiThread { urlClash = parseClash(respom) if (parseVersionClashMeta() != CoreCmd.checkVerClashMeta) { tvClash.text = "Update available mihomo" btnClash.isVisible = true } else { tvClash.text = "mihomo has Latest Version" imgDoneClash.isVisible = true btnClash.isVisible = false } prgClash.isVisible = false } } }) } private fun parseClash(str: String): String { return try { val jo = JSONObject(str) tagNameClash = jo.getString("tag_name") if (CoreUtil.getAbis().contains("arm64")) { "$META_DOWNLOAD/$tagNameClash/mihomo-android-arm64-v8-$tagNameClash.gz" } else { "$META_DOWNLOAD/$tagNameClash/mihomo-android-armv7-$tagNameClash.gz" } } catch (e: JSONException) { e.message!!.toString() } } private fun parseVersionClashMeta(): String { return try { "$META_DOWNLOAD/$tagNameClash/version.txt".urlText() } catch (e: Exception) { e.message.toString() } } private fun buttonUp() = with(binding) { btnClash.apply { setOnClickListener { dCore.downloadFile( urlClash, "clash_meta.gz", "/data/adb/box/bin/xclash/mihomo", object : IDownloadCore { override fun onDownloadingStart() { prgHrzClash.isVisible = true btnClash.isVisible = false } override fun onDownloadingProgress(progress: Int) { prgHrzClash.progress = progress } override fun onDownloadingComplete() { btnClash.isVisible = false prgHrzClash.isVisible = false imgDoneClash.isVisible = true tvClash.text = "mihomo has Latest Version" } override fun onDownloadingFailed(e: Exception?) { toast("failed downloading clash", this@CoreActivity) btnClash.isVisible = true prgHrzClash.progress = 0 prgHrzClash.isVisible = false } }) } } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/core/util/CoreUtil.kt ================================================ package xyz.chz.bfm.ui.core.util import xyz.chz.bfm.util.terminal.TerminalHelper import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.util.zip.GZIPInputStream object CoreUtil { fun gZipExtractor(gzipIn: String, gzipOut: String) { try { val fis = FileInputStream(gzipIn) val gis = GZIPInputStream(fis) val fos = FileOutputStream(gzipOut) val buff = ByteArray(1024) var len: Int while (gis.read(buff).also { len = it } != -1) { fos.write(buff, 0, len) } fos.close() gis.close() } catch (e: IOException) { e.printStackTrace() } } fun tarExtractUsingRoot(tarIn: String, tarOut: String) { TerminalHelper.execRootCmdSilent("tar xfz $tarIn -C $tarOut && mv -f $tarOut/sing-box-v* $tarOut/sing-box && chmod 755 $tarOut/sing-box && chown root:net_admin $tarOut/sing-box") } fun getAbis(): String { for (abis in android.os.Build.SUPPORTED_ABIS) { when (abis) { "arm64-v8a" -> return "arm64" "armeabi-v7a" -> return "armv7" } } return throw RuntimeException("unable get abis") } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/core/util/DownloaderCore.kt ================================================ package xyz.chz.bfm.ui.core.util import android.content.Context import android.os.Handler import android.os.Looper import xyz.chz.bfm.util.command.CoreCmd import java.io.BufferedInputStream import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.net.URL import java.util.concurrent.ExecutorService import java.util.concurrent.Executors open class DownloaderCore(private val ctx: Context) { private var exFile: File? = null fun downloadFile( stringUrl: String, nameFile: String, path: String, callback: IDownloadCore ) { val executor: ExecutorService = Executors.newSingleThreadExecutor() val handler = Handler(Looper.getMainLooper()) executor.execute { handler.post { callback.onDownloadingStart() } try { val url = URL(stringUrl) val conection = url.openConnection() conection.connect() val lenghtOfFile = conection.contentLength val input: InputStream = BufferedInputStream(url.openStream(), 8192) exFile = File(ctx.getExternalFilesDir(null), nameFile) if (exFile!!.exists()) exFile!!.delete() val output = FileOutputStream(exFile) val data = ByteArray(1024) var total: Long = 0 while (true) { val read = input.read(data) if (read == -1) { break } output.write(data, 0, read) val j2 = total + read.toLong() if (lenghtOfFile > 0) { val progress = ((100 * j2 / lenghtOfFile.toLong()).toInt()) callback.onDownloadingProgress(progress) } total = j2 } output.flush() output.close() input.close() handler.post { callback.onDownloadingComplete() } if (nameFile.contains("clash")) { val x = exFile.toString().replace(".gz", "") CoreUtil.gZipExtractor( exFile.toString(), x ) CoreCmd.moveResult(x, path) } else { CoreUtil.tarExtractUsingRoot(exFile.toString(), path) } exFile!!.delete() } catch (e: Exception) { handler.post { exFile!!.delete() callback.onDownloadingFailed(e) } } } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/core/util/IDownloadCore.kt ================================================ package xyz.chz.bfm.ui.core.util interface IDownloadCore { fun onDownloadingStart() fun onDownloadingProgress(progress: Int) fun onDownloadingComplete() fun onDownloadingFailed(e: Exception?) } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/fragment/AppListFragment.kt ================================================ package xyz.chz.bfm.ui.fragment import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.widget.doOnTextChanged import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import dagger.hilt.android.AndroidEntryPoint import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import xyz.chz.bfm.R import xyz.chz.bfm.adapter.AppListAdapter import xyz.chz.bfm.data.AppInfo import xyz.chz.bfm.data.AppManager import xyz.chz.bfm.databinding.FragmentAppListBinding import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.TermCmd import xyz.chz.bfm.util.setMyFab import xyz.chz.bfm.util.showKeyboard import java.text.Collator @AndroidEntryPoint class AppListFragment : Fragment() { private lateinit var binding: FragmentAppListBinding private var adapter: AppListAdapter? = null private var appsAll: List? = null private val defaultsSharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences( requireActivity() ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentAppListBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { val dividerItemDecoration = DividerItemDecoration(requireActivity(), LinearLayoutManager.VERTICAL) rvApps.addItemDecoration(dividerItemDecoration) val applist = TermCmd.appidList AppManager.rxLoadNetworkAppList(requireActivity()) .subscribeOn(Schedulers.io()) .map { if (applist != null) { it.forEach { one -> if ((applist.contains(one.packageName))) { one.isSelected = 1 } else { one.isSelected = 0 } } val comparator = Comparator { p1, p2 -> when { p1.isSelected > p2.isSelected -> -1 p1.isSelected == p2.isSelected -> 0 else -> 1 } } it.sortedWith(comparator) } else { val comparator = object : Comparator { val collator = Collator.getInstance() override fun compare(o1: AppInfo, o2: AppInfo) = collator.compare(o1.appName, o2.appName) } it.sortedWith(comparator) } } .observeOn(AndroidSchedulers.mainThread()) .subscribe { appsAll = it adapter = AppListAdapter(requireActivity(), it, applist) rvApps.adapter = adapter prgWaiting.visibility = View.GONE } with(fbSave) { setOnClickListener { setMyFab("#888F96", R.drawable.ic_commit) if (Util.isProxyed) { TermCmd.renewBox { Util.runOnUiThread { if (it) { setMyFab("#6fa251", R.drawable.ic_done) } else { setMyFab("#EC7474", R.drawable.ic_error) } } } } adapter?.let { TermCmd.setAppidList(it.blacklist) } } } } setupSearchApp() setupSelect() } @SuppressLint("NotifyDataSetChanged") private fun setupSelect() = with(binding) { selectAll.setOnClickListener { adapter?.let { if (it.blacklist.containsAll(it.apps.map { it.packageName })) { it.apps.forEach { adapter?.blacklist!!.remove(it.packageName) } } else { it.apps.forEach { adapter?.blacklist!!.add(it.packageName) } } it.notifyDataSetChanged() } } } private fun setupSearchApp() = with(binding) { searchBtn.setOnClickListener { tvInfoApps.visibility = View.GONE edSearch.visibility = View.VISIBLE edSearch.doOnTextChanged { text, _, _, _ -> search(text.toString()) } edSearch.showKeyboard() } } @SuppressLint("NotifyDataSetChanged") private fun search(str: String) { val apps = ArrayList() val key = str.uppercase() if (key.isNotEmpty()) { appsAll?.forEach { if (it.appName.uppercase().indexOf(key) >= 0 || it.packageName.uppercase().indexOf(key) >= 0 ) { apps.add(it) } } } else { appsAll?.forEach { apps.add(it) } } adapter = AppListAdapter(requireActivity(), apps, adapter?.blacklist) binding.rvApps.adapter = adapter adapter?.notifyDataSetChanged() } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/fragment/ConfigHelperFragment.kt ================================================ package xyz.chz.bfm.ui.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import xyz.chz.bfm.R import xyz.chz.bfm.databinding.FragmentConfigHelperBinding import xyz.chz.bfm.ui.converter.ConverterActivity import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.TermCmd import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmd import xyz.chz.bfm.util.toast class ConfigHelperFragment : Fragment() { private lateinit var binding: FragmentConfigHelperBinding private var statePath: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentConfigHelperBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupEditor() initEditor() editorApply() } private fun setupEditor() = with(binding.myEditor) { languageRuleBook = null lineNumberGenerator = { l -> (1..l).map { " $it " } } editable = true showDivider = false showMinimap = false } private fun initEditor() = with(binding) { dialogConfig() } private fun editorApply() = with(binding) { fbSave.apply { setOnClickListener { dialogSave() } } fbConverter.apply { setOnClickListener { val intent = Intent(context, ConverterActivity::class.java) startActivity(intent) } } } private fun dialogConfig() { val builder = AlertDialog.Builder( requireActivity(), R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_background ) builder.setCancelable(false) val items = TermCmd.proxyProviderPath.toTypedArray() builder.setItems(items) { _, w -> val configSlected = execRootCmd("cat ${items[w]}") if (configSlected.isNotEmpty()) { binding.myEditor.text = configSlected } else { toast("Empty file", requireActivity()) } statePath = items[w] } val dialog = builder.create() dialog.show() } private fun dialogSave() { val builder = AlertDialog.Builder( requireActivity(), R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_background ) builder.setTitle("Save") builder.setMessage("Do you want save config now ?") builder.setPositiveButton("yes") { _, _ -> val input = binding.myEditor.text TermCmd.saveConfig(requireActivity(), input, statePath!!) { Util.runOnUiThread { if (it) toast(requireActivity().getString(R.string.success), requireActivity()) else toast(requireActivity().getString(R.string.failed), requireActivity()) } } } builder.setNegativeButton("cancel") { d, _ -> d.dismiss() } val dialog = builder.create() dialog.show() } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/fragment/DashboardFragment.kt ================================================ package xyz.chz.bfm.ui.fragment import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebSettings import android.webkit.WebViewClient import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint import xyz.chz.bfm.databinding.FragmentDashboardBinding import xyz.chz.bfm.dialog.IMakeDialog import xyz.chz.bfm.dialog.MakeDialog import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.SettingCmd import xyz.chz.bfm.util.command.TermCmd @AndroidEntryPoint class DashboardFragment : Fragment(), IMakeDialog { private lateinit var binding: FragmentDashboardBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentDashboardBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (Util.isClashOrSing) { showRes() } else { MakeDialog( "Wowo :( ", "Your core is not clash or sing-box so dashboard not available", false, false ).show(requireActivity().supportFragmentManager, "") } } @SuppressLint("SetJavaScriptEnabled") private fun showRes() = with(binding) { val linkDB: String = if (SettingCmd.core == "clash") { TermCmd.linkDBClash } else { TermCmd.linkDBSing } dbWebview.loadUrl("${linkDB}/ui/#/proxies") with(dbWebview.settings) { domStorageEnabled = true databaseEnabled = true allowContentAccess = true javaScriptEnabled = true cacheMode = WebSettings.LOAD_NO_CACHE dbWebview.webViewClient = WebViewClient() } } override fun onDialogPositiveButton(dialog: DialogFragment) { } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/fragment/MainFragment.kt ================================================ package xyz.chz.bfm.ui.fragment import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import okhttp3.Call import okhttp3.Callback import okhttp3.Response import org.json.JSONException import org.json.JSONObject import xyz.chz.bfm.R import xyz.chz.bfm.databinding.FragmentMainBinding import xyz.chz.bfm.dialog.IMakeDialog import xyz.chz.bfm.dialog.ISettingDialog import xyz.chz.bfm.dialog.MakeDialog import xyz.chz.bfm.dialog.SettingDialog import xyz.chz.bfm.enm.StatusConnection import xyz.chz.bfm.ui.core.CoreActivity import xyz.chz.bfm.ui.model.MainViewModel import xyz.chz.bfm.util.OkHttpHelper import xyz.chz.bfm.util.Util import xyz.chz.bfm.util.command.SettingCmd import xyz.chz.bfm.util.command.TermCmd import xyz.chz.bfm.util.modul.ModuleManager import xyz.chz.bfm.util.moduleVer import xyz.chz.bfm.util.setColorBackground import xyz.chz.bfm.util.setImage import xyz.chz.bfm.util.setTextHtml import xyz.chz.bfm.util.toast import java.io.IOException @AndroidEntryPoint class MainFragment : Fragment(), ISettingDialog, IMakeDialog { private lateinit var binding: FragmentMainBinding private val viewModel: MainViewModel by viewModels() private var state: Int? = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMainBinding.inflate(layoutInflater, container, false) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.dataLog() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (Util.isProxyed) { setProxyCard(StatusConnection.Enabled.str) } else { setProxyCard(StatusConnection.Disabled.str) } binding.apply { proxy.setOnClickListener { v -> setProxyCard(StatusConnection.Loading.str) v.isClickable = false if (Util.isProxyed) { TermCmd.stop { Util.runOnUiThread { Util.isProxyed = if (it) { setProxyCard(StatusConnection.Disabled.str) false } else { setProxyCard(StatusConnection.Error.str) true } v.isClickable = true } } } else { TermCmd.start { Util.runOnUiThread { Util.isProxyed = if (it) { setProxyCard(StatusConnection.Enabled.str) true } else { setProxyCard(StatusConnection.Error.str) false } v.isClickable = true } } } } } setupLog() settings() configEditor() checkCore() } private fun setProxyCard(status: String) = with(binding) { val strapps: String = if (TermCmd.appidList.size == 0) String.format( getString(R.string.no_apps_count_list), SettingCmd.proxyMode ) else String.format( getString(R.string.apps_count_list), TermCmd.appidList.size, SettingCmd.proxyMode ) when (status) { StatusConnection.Enabled.str -> { statusTitle.text = StatusConnection.Enabled.str tvApps.text = strapps proxy.setColorBackground("#6fa251") statusIcon.setImage(R.drawable.ic_enabled) statusSummary.moduleVer() } StatusConnection.Disabled.str -> { statusTitle.text = StatusConnection.Disabled.str tvApps.text = strapps proxy.setColorBackground("#87afc7") statusIcon.setImage(R.drawable.ic_disabled) statusSummary.moduleVer() } StatusConnection.Loading.str -> { statusTitle.text = StatusConnection.Loading.str tvApps.text = strapps proxy.setColorBackground("#478fec") statusIcon.setImage(R.drawable.ic_loading) statusSummary.moduleVer() } StatusConnection.Error.str -> { statusTitle.text = StatusConnection.Error.str tvApps.text = strapps proxy.setColorBackground("#f35e5e") statusIcon.setImage(R.drawable.ic_error) statusSummary.moduleVer() } else -> { statusTitle.text = StatusConnection.Unknown.str tvApps.text = strapps proxy.setColorBackground("#26b545") statusIcon.setImage(R.drawable.ic_app) statusSummary.moduleVer() } } } private fun settings() = with(binding) { with(fbSetting) { setOnClickListener { visibility = View.GONE prgLoading.visibility = View.VISIBLE val sd = SettingDialog() sd.listener = this@MainFragment sd.show(requireActivity().supportFragmentManager, "") } } } private fun setupLog() = with(binding) { viewModel.log.observe(viewLifecycleOwner) { tvLog.text = setTextHtml(it) } } private fun configEditor() = with(binding.fbConfig) { setOnClickListener { findNavController().navigate(R.id.action_nav_home_to_configHelperFragment) } } private fun checkCore() = with(binding.imgModule) { setOnClickListener { startActivity(Intent(context, CoreActivity::class.java)) } } override fun onLoading(dialog: DialogFragment) { binding.fbSetting.visibility = View.VISIBLE binding.prgLoading.visibility = View.GONE } override fun onAbout(dialog: DialogFragment) { // dont remove this :) val df = MakeDialog("About", "App: t.me/chetoosz\nModule: t.me/taamarin") df.listener = this@MainFragment df.show(requireActivity().supportFragmentManager, "") } override fun onUpdate(dialog: DialogFragment) { binding.prgLoadingTop.visibility = View.GONE showRes( "https://raw.githubusercontent.com/taamarin/box_for_magisk/master/update.json", "Updater", 0 ) state = 0 } override fun onCheckIP(dialog: DialogFragment) { binding.prgLoadingTop.visibility = View.VISIBLE showRes("http://ip-api.com/json", "MyIP", 1) state = 1 } override fun onDialogPositiveButton(dialog: DialogFragment) = when (state) { 1 -> {} else -> {} } private fun showRes(url: String, title: String, state: Int) { binding.prgLoadingTop.visibility = View.VISIBLE val request = OkHttpHelper() request.getRawTextFromURL(url, object : Callback { override fun onFailure(call: Call, e: IOException) { Util.runOnUiThread { toast(e.message!!, requireActivity()) binding.prgLoadingTop.visibility = View.GONE } } override fun onResponse(call: Call, response: Response) { try { val jo = JSONObject(response.body!!.string()) var res: String? = "" res = if (state == 1) { "IP: ${jo.getString("query")}\n" + "ISP: ${jo.getString("isp")}\n" + "TZ: ${jo.getString("timezone")}\n" + "C: ${jo.getString("country")}\n" + "City: ${jo.getString("city")}\n" } else { if (jo.getString("versionCode") .toInt() > ModuleManager.moduleVersionCode.toInt() ) { "Update available\nDo you want update now?" } else { "No update found" } } val df = MakeDialog(title, res) df.listener = this@MainFragment df.show(requireActivity().supportFragmentManager, "") } catch (e: JSONException) { Log.d(MainFragment().tag, e.message!!) } Util.runOnUiThread { binding.prgLoadingTop.visibility = View.GONE } } }) } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/ui/model/MainViewModel.kt ================================================ package xyz.chz.bfm.ui.model import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import okhttp3.Call import okhttp3.Callback import okhttp3.Response import xyz.chz.bfm.util.OkHttpHelper import xyz.chz.bfm.util.command.TermCmd import xyz.chz.bfm.util.myReplacer import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor() : ViewModel() { private val _log = MutableLiveData() val log: LiveData get() = _log private val _theresult = MutableLiveData() val theresult: LiveData = _theresult fun dataLog(): Job { return CoroutineScope(Dispatchers.IO).launch { while (isActive) { _log.postValue( TermCmd.readLog().myReplacer( "\\[Info\\]".toRegex() to "[Info] ", "\\[Debug\\]".toRegex() to "[Debug] ", "\\[Error\\]".toRegex() to "[Error] ", "\\[Warning\\]".toRegex() to "[Warning] ", "\n".toRegex() to "
" ) ) delay(1500) } } } fun getTextFromUrl(url: String) { OkHttpHelper().getRawTextFromURL(url, object : Callback { override fun onFailure(call: Call, e: java.io.IOException) { _theresult.value = e.message!! } override fun onResponse(call: Call, response: Response) { _theresult.postValue(response.body!!.string()) } }) } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/Constant.kt ================================================ package xyz.chz.bfm.util // bcs yq yaml cant get emojis // dont make this to regex const val EXTRACTOR = "sed 's/\\[//g' | sed 's/\\]//g' | sed 's/\"//g' | sed 's/,//g' | sed 's/ //g' | awk 'NF'" const val QUOTES = "sed 's/\"//g'" const val META_REPO = "https://api.github.com/repos/MetaCubeX/mihomo/releases/latest" const val META_DOWNLOAD = "https://github.com/MetaCubeX/mihomo/releases/download" const val SING_REPO = "https://api.github.com/repos/shioeri/sing-box/releases" const val SING_DOWNLOAD = "https://github.com/shioeri/sing-box/releases/download" ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/OkHttpHelper.kt ================================================ package xyz.chz.bfm.util import okhttp3.Call import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request class OkHttpHelper { fun getRawTextFromURL(url: String, callback: Callback): Call { val client = OkHttpClient() val request = Request.Builder() .url(url) .build() val call = client.newCall(request) call.enqueue(callback) return call } fun reqGithub(url: String, callback: Callback): Call { val client = OkHttpClient() val request = Request.Builder() .url(url) .addHeader("Accept", "application/vnd.github+json") .addHeader("X-GitHub-Api-Version", "2022-11-28") .build() val call = client.newCall(request) call.enqueue(callback) return call } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/Util.kt ================================================ package xyz.chz.bfm.util import android.os.Handler import android.os.Looper import org.json.JSONArray import org.json.JSONObject import xyz.chz.bfm.util.command.SettingCmd import xyz.chz.bfm.util.command.TermCmd import java.util.ArrayDeque import java.util.Deque object Util { var isProxyed = TermCmd.isProxying() private val handler = Handler(Looper.getMainLooper()) fun runOnUiThread(action: () -> Unit) { if (Looper.myLooper() != Looper.getMainLooper()) { handler.post(action) } else { action.invoke() } } val isClashOrSing: Boolean get() { if (SettingCmd.core.contains("clash") or SettingCmd.core.contains("sing-box")) return true return false } fun json(build: JsonObjectBuilder.() -> Unit): JSONObject { return JsonObjectBuilder().json(build) } class JsonObjectBuilder { private val deque: Deque = ArrayDeque() fun json(build: JsonObjectBuilder.() -> Unit): JSONObject { deque.push(JSONObject()) this.build() return deque.pop() } infix fun String.to(value: T) { val wrapped = when (value) { is Function0<*> -> json { value.invoke() } is Array<*> -> JSONArray().apply { value.forEach { put(it) } } else -> value } deque.peek().put(this, wrapped) } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/ViewUtils.kt ================================================ package xyz.chz.bfm.util import android.annotation.SuppressLint import android.app.Activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.os.Build import android.text.Html import android.text.Spanned import android.util.TypedValue import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.google.android.material.card.MaterialCardView import com.google.android.material.floatingactionbutton.FloatingActionButton import xyz.chz.bfm.ui.converter.config.ConfigType import xyz.chz.bfm.util.modul.ModuleManager import java.net.HttpURLConnection import java.net.URL fun MaterialCardView.setColorBackground(str: String) { this.setCardBackgroundColor(Color.parseColor(str)) this.radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8f, context.resources.displayMetrics) } fun ImageView.setImage(res: Int) { this.setImageResource(res) } fun TextView.moduleVer() { this.text = ModuleManager.moduleVersion } fun FloatingActionButton.setMyFab(color: String, res: Int) { this.backgroundTintList = ColorStateList.valueOf(Color.parseColor(color)) this.setImageResource(res) } fun toast(str: String, ctx: Context) { Toast.makeText(ctx, str, Toast.LENGTH_SHORT).show() } fun String.myReplacer(vararg replacements: Pair): String = replacements.fold(this) { acc, (old, new) -> acc.replace(old, new) } @SuppressLint("ObsoleteSdkInt") fun setTextHtml(text: String): Spanned { val res: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(text) } return res } fun EditText.hideKeyboard(): Boolean { return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(windowToken, 0) } fun EditText.showKeyboard(): Boolean { return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .showSoftInput(this, 0) } fun EditText.removeEmptyLines(): String { //val regex = Regex() return this.text.replace("(?m)^[ \t]*\r?\n".toRegex(), "") } fun TextView.copyToClipboard(context: Context) { (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager) .setPrimaryClip(ClipData.newPlainText("copied", this.text.toString())) } fun EditText.isValidCheck(): Boolean { if (this.text.toString().isNotEmpty() || this.text.toString() .startsWith(ConfigType.VMESS.scheme) || this.text.toString().startsWith( ConfigType.VLESS.scheme ) || this.text.toString().startsWith(ConfigType.TROJAN.scheme) || this.text.toString() .startsWith(ConfigType.TROJANGO.scheme) ) { return true } return false } fun String.urlText(): String { return URL(this).run { openConnection().run { this as HttpURLConnection inputStream.bufferedReader().readText().trim() } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/command/CoreCmd.kt ================================================ package xyz.chz.bfm.util.command import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmd import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmdSilent object CoreCmd { private const val path = "/data/adb/box" val checkVerSing: String get() { val cmd = "$path/bin/sing-box version | awk '{print $3}' | awk '{print $1; exit}'" return execRootCmd(cmd) } val checkVerClashMeta: String get() { val cmd = "$path/bin/xclash/mihomo -v | awk '{print $3}' | awk '{print $1; exit}'" return execRootCmd(cmd) } fun moveResult(pathOut: String, pathDir: String) { val cmd = "mv -f $pathOut $pathDir && chmod 755 $pathDir && chown root:net_admin $pathDir" execRootCmdSilent(cmd) } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/command/SettingCmd.kt ================================================ package xyz.chz.bfm.util.command import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmd object SettingCmd { val networkMode: String get() = execRootCmd("grep 'network_mode=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setNetworkMode(mode: String): String { return execRootCmd("sed -i 's/network_mode=.*/network_mode=\"$mode\"/;' /data/adb/box/settings.ini") } val proxyMode: String get() = execRootCmd("sed -n 's/^mode:\\([^ ]*\\).*/\\1/p' /data/adb/box/package.list.cfg") fun setProxyMode(mode: String): String { return execRootCmd("sed -i 's/^mode:[^ ]*/mode:$mode/' /data/adb/box/package.list.cfg") } val cron: String get() = execRootCmd("grep 'run_crontab=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setCron(mode: String): String { return execRootCmd("sed -i 's/run_crontab=.*/run_crontab=\"$mode\"/;' /data/adb/box/settings.ini") } val geo: String get() = execRootCmd("grep 'update_geo=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setGeo(mode: String): String { return execRootCmd("sed -i 's/update_geo=.*/update_geo=\"$mode\"/;' /data/adb/box/settings.ini") } val memcg: String get() = execRootCmd("grep 'cgroup_memcg=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setMemcg(mode: String): String { return execRootCmd("sed -i 's/cgroup_memcg=.*/cgroup_memcg=\"$mode\"/;' /data/adb/box/settings.ini") } val blkio: String get() = execRootCmd("grep 'cgroup_blkio=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setBlkio(mode: String): String { return execRootCmd("sed -i 's/cgroup_blkio=.*/cgroup_blkio=\"$mode\"/;' /data/adb/box/settings.ini") } val cpuset: String get() = execRootCmd("grep 'cgroup_cpuset=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setCpuset(mode: String): String { return execRootCmd("sed -i 's/cgroup_cpuset=.*/cgroup_cpuset=\"$mode\"/;' /data/adb/box/settings.ini") } val subs: String get() = execRootCmd("grep 'update_subscription=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setSubs(mode: String): String { return execRootCmd("sed -i 's/update_subscription=.*/update_subscription=\"$mode\"/;' /data/adb/box/settings.ini") } val redirHost: Boolean get() = "redir-host" == execRootCmd("grep 'enhanced-mode:' /data/adb/box/clash/config.yaml | awk '{print $2}'") fun setRedirHost(mode: String): String { return execRootCmd("sed -i 's/enhanced-mode:.*/enhanced-mode: $mode/;' /data/adb/box/clash/config.yaml") } val quic: Boolean get() = "enable" == execRootCmd("grep 'quic=' /data/adb/box/scripts/box.iptables | sed 's/^.*=//' | sed 's/\"//g'") fun setQuic(mode: String): String { return execRootCmd("sed -i 's/quic=.*/quic=\"$mode\"/;' /data/adb/box/scripts/box.iptables") } val unified: Boolean get() = "true" == execRootCmd("grep 'unified-delay:' /data/adb/box/clash/config.yaml | awk '{print $2}'") fun setUnified(mode: String): String { return execRootCmd("sed -i 's/unified-delay:.*/unified-delay: $mode/;' /data/adb/box/clash/config.yaml") } val geodata: Boolean get() = "true" == execRootCmd("grep 'geodata-mode:' /data/adb/box/clash/config.yaml | awk '{print $2}'") fun setGeodata(mode: String): String { return execRootCmd("sed -i 's/geodata-mode:.*/geodata-mode: $mode/;' /data/adb/box/clash/config.yaml") } val tcpCon: Boolean get() = "true" == execRootCmd("grep 'tcp-concurrent:' /data/adb/box/clash/config.yaml | awk '{print $2}'") fun setTcpCon(mode: String): String { return execRootCmd("sed -i 's/tcp-concurrent:.*/tcp-concurrent: $mode/;' /data/adb/box/clash/config.yaml") } val sniffer: Boolean get() = "true" == execRootCmd("grep -C 1 'sniffer:' /data/adb/box/clash/config.yaml | grep 'enable:' | awk '{print $2}'") fun setSniffer(mode: String): String { return execRootCmd("sed -i '/^sniffer:/{n;s/enable:.*/enable: $mode/;}' /data/adb/box/clash/config.yaml") } val ipv6: Boolean get() = "true" == execRootCmd("grep 'ipv6=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setIpv6(mode: String): String { return execRootCmd("sed -i 's/ipv6=.*/ipv6=\"$mode\"/;' /data/adb/box/settings.ini") } val findProc: String get() = execRootCmd("grep 'find-process-mode:' /data/adb/box/clash/config.yaml | awk '{print $2}'") fun setFindProc(mode: String): String { return execRootCmd("sed -i 's/find-process-mode:.*/find-process-mode: $mode/;' /data/adb/box/clash/config.yaml") } val findConf: String get() = execRootCmd("grep 'name_clash_config=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setFindConf(mode: String): String { return execRootCmd("sed -i 's/name_clash_config=.*/name_clash_config=\"$mode\"/;' /data/adb/box/settings.ini") } val clashType: String get() = execRootCmd("grep 'xclash_option=' /data/adb/box/settings.ini | sed 's/^.*=//' | sed 's/\"//g'") fun setClashType(mode: String): String { return execRootCmd("sed -i 's/xclash_option=.*/xclash_option=\"$mode\"/;' /data/adb/box/settings.ini") } val core: String get() = execRootCmd("grep 'bin_name=' /data/adb/box/settings.ini | sed 's/^.*=//g' | sed 's/\"//g'") // fun setCore(x: String): Boolean { // return execRootCmdSilent("sed -i 's/bin_name=.*/bin_name=$x/;' /data/adb/box/settings.ini") != -1 // } var setCore: String = "" set(value) { field = value execRootCmd("sed -i 's/bin_name=.*/bin_name=$field/;' /data/adb/box/settings.ini") } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/command/TermCmd.kt ================================================ package xyz.chz.bfm.util.command import android.annotation.SuppressLint import android.content.Context import xyz.chz.bfm.util.EXTRACTOR import xyz.chz.bfm.util.QUOTES import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmd import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmdSilent import xyz.chz.bfm.util.terminal.TerminalHelper.execRootCmdVoid import java.io.File import java.io.FileOutputStream import kotlin.concurrent.thread object TermCmd { private const val path = "/data/adb/box" private const val yq = "${path}/bin/yq" fun isProxying(): Boolean { return execRootCmdSilent("if [ -f ${path}/run/box.pid ] ; then exit 1;fi") == 1 } fun renewBox(callback: (Boolean) -> Unit) { thread { val cmd = "${path}/scripts/box.iptables renew" execRootCmdVoid(cmd, callback) } } fun start(callback: (Boolean) -> Unit) { thread { val cmd = "${path}/scripts/box.service start && ${path}/scripts/box.iptables enable" execRootCmdVoid(cmd, callback) } } fun stop(callback: (Boolean) -> Unit) { thread { val cmd = "${path}/scripts/box.iptables disable && ${path}/scripts/box.service stop" execRootCmdVoid(cmd, callback) } } fun readLog(): String { return execRootCmd("cat ${path}/run/runs.log") } val linkDBClash: String get() { return execRootCmd("grep 'external-controller:' ${path}/clash/config.yaml | awk '{print $2}'") } val linkDBSing: String get() { val cmd = "grep -w 'external_controller' ${path}/sing-box/config.json | awk '{print $2}' | sed 's/\"//g' | sed 's/,//g'" return execRootCmd(cmd) } private val proxyProviderJsonKey: HashSet get() { val s = HashSet() val cmd = "$yq -oj '.proxy-providers | keys' $path/clash/config.yaml | $EXTRACTOR" val result = execRootCmd(cmd) if (result.isEmpty()) return s val list = result.split("\n") for (x in list) { s.add(x) } return s } val proxyProviderPath: HashSet @SuppressLint("SuspiciousIndentation") get() { val s = HashSet() val ppKey = proxyProviderJsonKey for (xs in ppKey) { if (SettingCmd.core == "clash") { val pth = execRootCmd("exp=$xs $yq -oj '.proxy-providers.[env(exp)].path' $getPathOnly | $QUOTES") if (pth.contains("./")) { s.add(pth.replace("./", "$path/clash/")) } else { s.add(pth) } } } s.add(getPathOnly) return s } val appidList: HashSet get() { val s = HashSet() val modeCommand = "sed -n 's/^\\(mode:[^ ]*\\).*/\\1/p' ${path}/package.list.cfg" val packageCommand = "sed -n '/^[^#]/s/^\\([^ ]*\\.[^ ]*\\).*/\\1/p' ${path}/package.list.cfg" val gidCommand = "sed -n '/^[^#]/s/^\\([0-9]\\{1,8\\}\\).*/\\1/p' ${path}/package.list.cfg" val modeResult = execRootCmd(modeCommand) val packageResult = execRootCmd(packageCommand) val gidResult = execRootCmd(gidCommand) val result = """ $modeResult $packageResult $gidResult """.trimIndent() if (result.isEmpty()) { return s } val appIds = result.split("\n") for (i in appIds) { if (i.isNotEmpty() && !i.startsWith("alook")) { s.add(i.trim()) } } return s } fun setAppidList(s: HashSet): Boolean { val content = s.filterNotNull() .filter { it.isNotEmpty() } .joinToString(" ") val command = """ echo "$content" > "$path/package.list.cfg" && sed -i '/^#/!s/ /\'$'\n/g' "${path}/package.list.cfg" sed -i '/alook\\|999_alook/s/^/#/' "${path}/package.list.cfg" """.trimIndent() return execRootCmdSilent(command) != -1 } private fun getNameConfig(what: String, isClash: Boolean): String { val m = if (isClash) "yaml" else "json" return execRootCmd("find ${path}/$what/ -maxdepth 1 -name 'config.$m' -type f -exec basename {} \\;") } val getPathOnly: String get() { val what = SettingCmd.core val isClash = what == "clash" val name = getNameConfig(what, isClash) return "$path/$what/$name" } fun saveConfig(ctx: Context, str: String, pth: String, callback: (Boolean) -> Unit) { thread { val exFile = File(ctx.getExternalFilesDir(null), "out.txt") val fos = FileOutputStream(exFile) fos.write(str.toByteArray()) val cmd = "mv -f $exFile $pth" execRootCmdVoid(cmd, callback) } } private fun yqParser(dir: String, config: String, isClash: Boolean): String { return if (isClash) { val yamlToJson = "$yq -oj ${path}/${dir}/${config} > ${path}/${dir}/xtemp.json" execRootCmd("$yamlToJson && $yq -oy ${path}/${dir}/xtemp.json > ${path}/${dir}/${config} && rm -f ${path}/${dir}/xtemp.json && cat ${path}/${dir}/${config}") } else { execRootCmd("$yq -oj ${path}/${dir}/${config} > ${path}/${dir}/xtemp.json && mv -f ${path}/${dir}/xtemp.json ${path}/${dir}/${config} && cat ${path}/${dir}/${config}") } } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/modul/ModuleManager.kt ================================================ package xyz.chz.bfm.util.modul import xyz.chz.bfm.util.terminal.TerminalHelper object ModuleManager { val moduleVersionCode: String get() { val cmd = "cat /data/adb/modules/box_for_root/module.prop | grep '^versionCode='" val result = TerminalHelper.execRootCmd(cmd) return if (result.isEmpty()) "" else result.split("=")[1] } val moduleVersion: String get() { val cmd = "cat /data/adb/modules/box_for_root/module.prop | grep '^version='" val result = TerminalHelper.execRootCmd(cmd) return if (result.isEmpty()) "" else result.split("=")[1] } } ================================================ FILE: app/src/main/java/xyz/chz/bfm/util/terminal/TerminalHelper.kt ================================================ package xyz.chz.bfm.util.terminal import android.util.Log import xyz.chz.bfm.BuildConfig object TerminalHelper { private const val TAG = "BoxForRoot.Terminal" fun execRootCmd(cmd: String): String { return try { val process: Process = Runtime.getRuntime().exec("su -c $cmd") process.waitFor() val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n") if (BuildConfig.DEBUG) Log.d(TAG, output) output } catch (e: Exception) { "" } } fun execRootCmdSilent(cmd: String): Int { return try { val process: Process = Runtime.getRuntime().exec("su -c $cmd") process.waitFor() process.exitValue() } catch (e: Exception) { -1 } } fun execRootCmdVoid(cmd: String, callback: (Boolean) -> Unit) { try { val process = Runtime.getRuntime().exec("su -c $cmd") process.waitFor() callback(process.exitValue() == 0) } catch (e: Exception) { e.printStackTrace() callback(false) } } } ================================================ FILE: app/src/main/res/drawable/ic_app.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_commit.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_config.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_converter.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_dashboard.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_disabled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_done.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_download.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_enabled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_error.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_home.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_info.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_loading.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_log.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_modul.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_save.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_search.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_select_all.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_setting.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_converter.xml ================================================