Repository: romanvht/ByeByeDPI Branch: master Commit: 0dd7a98b0184 Files: 161 Total size: 441.4 KB Directory structure: gitextract_b_bxmhtu/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── bug.yml │ ├── config.yml │ └── feature.yml ├── .gitignore ├── .gitmodules ├── LICENSE ├── README-en.md ├── README-tr.md ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── io/ │ │ └── github/ │ │ └── romanvht/ │ │ └── byedpi/ │ │ └── ExampleInstrumentedTest.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── assets/ │ │ │ ├── proxytest_cloudflare.sites │ │ │ ├── proxytest_discord.sites │ │ │ ├── proxytest_general.sites │ │ │ ├── proxytest_googlevideo.sites │ │ │ ├── proxytest_social.sites │ │ │ ├── proxytest_strategies.list │ │ │ └── proxytest_youtube.sites │ │ ├── cpp/ │ │ │ ├── CMakeLists.txt │ │ │ ├── main.h │ │ │ └── native-lib.c │ │ ├── java/ │ │ │ └── io/ │ │ │ └── github/ │ │ │ └── romanvht/ │ │ │ └── byedpi/ │ │ │ ├── activities/ │ │ │ │ ├── BaseActivity.kt │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── SettingsActivity.kt │ │ │ │ ├── TestActivity.kt │ │ │ │ ├── TestSettingsActivity.kt │ │ │ │ └── ToggleActivity.kt │ │ │ ├── adapters/ │ │ │ │ ├── AppSelectionAdapter.kt │ │ │ │ ├── DomainListAdapter.kt │ │ │ │ ├── SiteResultAdapter.kt │ │ │ │ └── StrategyResultAdapter.kt │ │ │ ├── core/ │ │ │ │ ├── ByeDpiProxy.kt │ │ │ │ ├── ByeDpiProxyPreferences.kt │ │ │ │ └── TProxyService.kt │ │ │ ├── data/ │ │ │ │ ├── Actions.kt │ │ │ │ ├── AppInfo.kt │ │ │ │ ├── AppSettings.kt │ │ │ │ ├── AppStatus.kt │ │ │ │ ├── Broadcasts.kt │ │ │ │ ├── Command.kt │ │ │ │ ├── DomainList.kt │ │ │ │ ├── ServiceStatus.kt │ │ │ │ ├── TestResult.kt │ │ │ │ └── UISettings.kt │ │ │ ├── fragments/ │ │ │ │ ├── AppSelectionFragment.kt │ │ │ │ ├── ByeDpiCMDSettingsFragment.kt │ │ │ │ ├── ByeDpiUISettingsFragment.kt │ │ │ │ ├── DomainListsFragment.kt │ │ │ │ ├── MainSettingsFragment.kt │ │ │ │ └── ProxyTestSettingsFragment.kt │ │ │ ├── receiver/ │ │ │ │ └── BootReceiver.kt │ │ │ ├── services/ │ │ │ │ ├── ByeDpiProxyService.kt │ │ │ │ ├── ByeDpiStatus.kt │ │ │ │ ├── ByeDpiVpnService.kt │ │ │ │ ├── LifecycleVpnService.kt │ │ │ │ ├── QuickTileService.kt │ │ │ │ └── ServiceManager.kt │ │ │ └── utility/ │ │ │ ├── ArgumentsUtils.kt │ │ │ ├── BatteryUtils.kt │ │ │ ├── ClipboardUtils.kt │ │ │ ├── DomainListUtils.kt │ │ │ ├── HistoryUtils.kt │ │ │ ├── NotificationUtils.kt │ │ │ ├── PreferencesUtils.kt │ │ │ ├── SettingsUtils.kt │ │ │ ├── ShortcutUtils.kt │ │ │ ├── SiteCheckUtils.kt │ │ │ ├── StorageUtils.kt │ │ │ └── ValidateUtils.kt │ │ ├── jni/ │ │ │ ├── Android.mk │ │ │ └── Application.mk │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── baseline_settings_24.xml │ │ │ ├── ic_apps.xml │ │ │ ├── ic_arrow_down.xml │ │ │ ├── ic_autorenew.xml │ │ │ ├── ic_battery.xml │ │ │ ├── ic_check.xml │ │ │ ├── ic_code.xml │ │ │ ├── ic_computer.xml │ │ │ ├── ic_description.xml │ │ │ ├── ic_dns.xml │ │ │ ├── ic_documentation.xml │ │ │ ├── ic_filter_list.xml │ │ │ ├── ic_folder.xml │ │ │ ├── ic_github.xml │ │ │ ├── ic_http.xml │ │ │ ├── ic_info.xml │ │ │ ├── ic_language.xml │ │ │ ├── ic_launcher_monochrome.xml │ │ │ ├── ic_network.xml │ │ │ ├── ic_notification.xml │ │ │ ├── ic_palette.xml │ │ │ ├── ic_pin.xml │ │ │ ├── ic_pinned.xml │ │ │ ├── ic_port.xml │ │ │ ├── ic_power.xml │ │ │ ├── ic_speed.xml │ │ │ ├── ic_telegram.xml │ │ │ ├── ic_terminal.xml │ │ │ ├── ic_toggle.xml │ │ │ ├── ic_tune.xml │ │ │ ├── ic_vpn_key.xml │ │ │ └── material_alert.xml │ │ ├── layout/ │ │ │ ├── activity_main.xml │ │ │ ├── activity_proxy_test.xml │ │ │ ├── activity_settings.xml │ │ │ ├── activity_test_settings.xml │ │ │ ├── app_selection_item.xml │ │ │ ├── app_selection_layout.xml │ │ │ ├── cmd_editor_buttons.xml │ │ │ ├── domain_lists.xml │ │ │ ├── history_category.xml │ │ │ ├── history_item.xml │ │ │ ├── item_domain_list.xml │ │ │ ├── item_site_result.xml │ │ │ ├── item_strategy_result.xml │ │ │ └── material_switch.xml │ │ ├── layout-land/ │ │ │ └── activity_main.xml │ │ ├── menu/ │ │ │ ├── menu_main.xml │ │ │ ├── menu_settings.xml │ │ │ └── menu_test.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── values/ │ │ │ ├── arrays.xml │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── themes.xml │ │ ├── values-en/ │ │ │ ├── arrays.xml │ │ │ └── strings.xml │ │ ├── values-kk/ │ │ │ ├── arrays.xml │ │ │ └── strings.xml │ │ ├── values-night/ │ │ │ └── themes.xml │ │ ├── values-night-v31/ │ │ │ └── themes.xml │ │ ├── values-tr/ │ │ │ ├── arrays.xml │ │ │ └── strings.xml │ │ ├── values-v31/ │ │ │ └── themes.xml │ │ ├── values-vi/ │ │ │ ├── arrays.xml │ │ │ └── strings.xml │ │ └── xml/ │ │ ├── backup_rules.xml │ │ ├── byedpi_cmd_settings.xml │ │ ├── byedpi_ui_settings.xml │ │ ├── data_extraction_rules.xml │ │ ├── main_settings.xml │ │ └── proxy_test_settings.xml │ └── test/ │ └── java/ │ └── io/ │ └── github/ │ └── romanvht/ │ └── byedpi/ │ └── ExampleUnitTest.kt ├── build.gradle.kts ├── fastlane/ │ └── metadata/ │ └── android/ │ ├── en-US/ │ │ ├── full_description.txt │ │ └── short_description.txt │ └── ru-RU/ │ ├── full_description.txt │ └── short_description.txt ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── sbox.md ├── scripts/ │ └── update_readmes.sh └── settings.gradle.kts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug.yml ================================================ name: Bug Report / Сообщение об ошибке description: File a bug report / Сообщить об ошибке в программе labels: [ bug ] assignees: romanvht body: - type: markdown attributes: value: | ### If you have trouble with specific websites or or can't configure the app, please use the [discussions section](https://github.com/dovecoteescapee/ByeDPIAndroid/discussions) to discuss it. This template is only for reporting bugs in the ByeDPI program. ### Если у вас не работают какие-то сайты или не получается настроить приложение, используйте [раздел дискуссий](https://github.com/dovecoteescapee/ByeDPIAndroid/discussions) для обсуждения этого. Этот шаблон предназначен только для сообщений об ошибках в программе ByeDPI. - type: textarea id: bug attributes: label: Describe the bug / Описание ошибки description: A clear and concise description of what the bug is / Четкое и краткое описание ошибки validations: required: true - type: textarea id: reproduce attributes: label: To Reproduce / Как воспроизвести description: Steps to reproduce the behavior / Шаги для воспроизведения проблемы value: | 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error validations: required: true - type: textarea id: expected attributes: label: Expected behavior / Ожидаемое поведение description: A clear and concise description of what you expected to happen / Четкое и краткое описание ожидаемого поведения validations: required: true - type: textarea id: screenshots attributes: label: Screenshots / Скриншоты description: If applicable, add screenshots to help explain your problem / При необходимости добавьте скриншоты, чтобы объяснить вашу проблему - type: textarea id: environment attributes: label: Environment / Окружение description: Please complete the following information / Пожалуйста, заполните следующую информацию value: | **Smartphone / Смартфон:** - Device: [e.g. Pixel Fold, Samsung Galaxy S24] - Android version: [e.g. 10] - ByeDPI version: [e.g. 1.0.2] validations: required: true - type: textarea id: context attributes: label: Additional context / Дополнительная информация description: Add any other context about the problem here / Добавьте любую другую информацию о проблеме здесь - type: checkboxes id: checklist attributes: label: Before you submit / Прежде чем отправить options: - label: I have searched the open and closed issues for duplicates / Я искал(а) открытые и закрытые задачи на предмет дубликатов required: true - label: This is not a question, feature request, or general feedback / Это не вопрос, предложение новой функциональности или общий отзыв required: true ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Questions about the program on Github / Вопросы по програме на Github url: https://github.com/dovecoteescapee/ByeDPIAndroid/discussions about: Please do not ask questions in the issue tracker / Пожалуйста, не задавайте вопросы в трекере задач - name: Questions about the program on NTC.party / Вопросы по програме на NTC.party url: https://ntc.party/c/community-software/byedpi/39 about: Please do not ask questions in the issue tracker / Пожалуйста, не задавайте вопросы в трекере задач ================================================ FILE: .github/ISSUE_TEMPLATE/feature.yml ================================================ name: Feature request / Предложить новую функциональность description: Suggest an idea for this project / Предложить идею для проекта labels: [ enhancement ] assignees: romanvht body: - type: textarea id: problem attributes: label: What problem does your proposal solve? / Какую проблему решает ваше предложение? description: A clear and concise description of what the problem is / Четкое и краткое описание проблемы validations: required: true - type: textarea id: solution attributes: label: Describe the solution you'd like / Опишите решение, которое вы предлагаете description: A clear and concise description of what you want to happen / Четкое и краткое описание того, что вы хотите, чтобы произошло validations: required: true - type: textarea id: alternatives attributes: label: Describe alternatives you've considered / Опишите альтернативные варианты, которые вы рассматривали description: A clear and concise description of any alternative solutions or features you've considered / Четкое и краткое описание любых альтернативных решений или функций, которые вы рассматривали validations: required: true - type: checkboxes id: checklist attributes: label: Before you submit / Прежде чем отправить options: - label: I have searched the open and closed issues for duplicates / Я искал(а) открытые и закрытые задачи на предмет дубликатов required: true - label: I have verified that this feature does not already exist / Я убедился(ась), что эта функция еще не существует required: true ================================================ FILE: .gitignore ================================================ # OS .DS_Store # IDE .idea/ .kotlin/ *.iml # Gradle .gradle/ build/ # Local config local.properties # Android /captures .externalNativeBuild .cxx # JNI app/src/main/jniLibs/ ================================================ FILE: .gitmodules ================================================ [submodule "hev-socks5-tunnel"] path = app/src/main/jni/hev-socks5-tunnel url = https://github.com/heiher/hev-socks5-tunnel.git [submodule "byedpi"] path = app/src/main/cpp/byedpi url = https://github.com/hufrea/byedpi.git ================================================ 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-en.md ================================================

Логотип ByeDPI

ByeByeDPI Android

Русский | English | Türkçe

Latest Release Downloads License GitHub code size in bytes

An Android application that locally runs ByeDPI and routes all traffic through it. For stable operation, you may need to adjust the settings. You can read more about different settings in the [ByeDPI documentation](https://github.com/hufrea/byedpi/blob/v0.13/README.md). This application is **not** a VPN. It uses Android's VPN mode to route traffic but does not transmit anything to a remote server. It does not encrypt traffic or hide your IP address. This application is a fork of [ByeDPIAndroid](https://github.com/dovecoteescapee/ByeDPIAndroid). --- ### Features * Autostart service on device boot * Saving lists of command-line parameters * Improved compatibility with Android TV/BOX * Per-app split tunneling * Import/export settings ### Usage * To enable auto-start, activate the option in settings. * It is recommended to connect to the VPN once to accept the request. * After that, upon device startup, the application will automatically launch the service based on settings (VPN/Proxy). * Comprehensive instruction from the community [ByeByeDPI-Manual (En)](https://github.com/BDManual/ByeByeDPI-Manual) ### How to use ByeByeDPI with AdGuard? * Start ByeByeDPI in proxy mode. * Add ByeByeDPI to AdGuard exclusions on the "App Management" tab. * In AdGuard settings, specify the proxy: ```plaintext Proxy Type: SOCKS5 Host: 127.0.0.1 Port: 1080 (default) ``` ### Building 1. Clone the repository with submodules: ```bash git clone --recurse-submodules ``` 2. Run the build script from the root of the repository: ```bash ./gradlew assembleRelease ``` 3. The APK will be in `app/build/outputs/apk/release/` > P.S.: hev_socks5_tunnel will not build under Windows, you will need to use WSL ### Signature Hash SHA-256: `77:45:10:75:AC:EA:40:64:06:47:5D:74:D4:59:88:3A:49:A6:40:51:FA:F3:2E:42:F7:18:F3:F9:77:7A:8D:FB` ### Dependencies - [ByeDPI](https://github.com/hufrea/byedpi) - [hev-socks5-tunnel](https://github.com/heiher/hev-socks5-tunnel) ================================================ FILE: README-tr.md ================================================

Логотип ByeDPI

ByeByeDPI Android

Русский | English | Türkçe

Latest Release Downloads License GitHub code size in bytes

ByeDPI'yi yerel olarak çalıştıran ve tüm trafiği bunun üzerinden yönlendiren bir Android uygulaması. Kararlı bir çalışma için ayarları yapmanız gerekebilir. Farklı ayarlar hakkında daha fazla bilgiye [ByeDPI dökümantasyonundan](https://github.com/hufrea/byedpi/blob/v0.13/README.md) ulaşabilirsiniz. Bu uygulama **VPN** değildir. Trafiği yönlendirmek için Android'in VPN modunu kullanır ancak herhangi bir veriyi uzak bir sunucuya iletmez. Trafiği şifrelemez veya IP adresinizi gizlemez. Bu uygulama, [ByeDPIAndroid](https://github.com/dovecoteescapee/ByeDPIAndroid) uygulamasının bir çatallamasıdır. --- ### Özellikler * Cihaz başlatıldığında hizmetin otomatik başlatılması * Komut satırı parametrelerinin listelerinin kaydedilmesi * Android TV/BOX ile geliştirilmiş uyumluluk * Uygulama başına bölünmüş tünelleme * Ayarları içe/dışa aktarma ### Kullanım * Otomatik başlatmayı etkinleştirmek için ayarlarda seçeneği aktifleştirin. * İlk başta VPN'e bağlanarak isteği kabul etmeniz önerilir. * Bundan sonra, cihaz başlatıldığında, uygulama ayarlara göre (VPN/Proxy) hizmeti otomatik olarak başlatacaktır. * Topluluktan kapsamlı talimatlar [ByeByeDPI-Manual (İngilizce)](https://github.com/BDManual/ByeByeDPI-Manual) ### Türkiye İle İlgili * Uygulama Türkiyede uygulanan DPI'ı aşmak için şuanlık yeterlidir. İlk başta çalıştırdığınızda uygulama DPI'ı aşamayabilir. UI editöründen rastgele taktikler deneyebilirsiniz veya şuan Deneysel özellik olan proxy modundan bazı argümanlar alıp onları Komut satırı editöründe deneyebilirsiniz. * Türkiye ile alakalı destek için Discord: [nyaex](https://github.com/nyaexx) ### ByeByeDPI'yi AdGuard ile nasıl kullanırım? * ByeByeDPI'yi proxy modunda başlatın. * ByeByeDPI'yi AdGuard dışlamalarına "Uygulama Yönetimi" sekmesinde ekleyin. * AdGuard ayarlarında, proxy'i belirtin: ```plaintext Proxy Türü: SOCKS5 Host: 127.0.0.1 Port: 1080 (varsayılan) ``` ### Oluşturma 1. Depoyu alt modüllerle klonlayın: ```bash git clone --recurse-submodules ``` 2. Depo kökünden derleme betiğini çalıştırın: ```bash ./gradlew assemblyRelease ``` 3. APK `app/build/outputs/apk/release/` dizininde olacaktır > Not: hev_socks5_tunnel Windows altında derlenmeyecektir, WSL kullanmanız gerekecektir ### İmza Özeti SHA-256: `77:45:10:75:AC:EA:40:64:06:47:5D:74:D4:59:88:3A:49:A6:40:51:FA:F3:2E:42:F7:18:F3:F9:77:7A:8D:FB` ### Bağımlılıklar - [ByeDPI](https://github.com/hufrea/byedpi) - [hev-socks5-tunnel](https://github.com/heiher/hev-socks5-tunnel) ================================================ FILE: README.md ================================================

Логотип ByeDPI

ByeByeDPI Android

Русский | English | Türkçe

Latest Release Downloads License GitHub code size in bytes

Приложение для Android, которое локально запускает ByeDPI и перенаправляет весь трафик через него. Для стабильной работы может потребоваться изменить настройки. Подробнее о различных настройках можно прочитать в [документации ByeDPI](https://github.com/hufrea/byedpi/blob/v0.13/README.md). Приложение не является VPN. Оно использует VPN-режим на Android для перенаправления трафика, но не передает ничего на удаленный сервер. Оно не шифрует трафик и не скрывает ваш IP-адрес. Приложения является форком [ByeDPIAndroid](https://github.com/dovecoteescapee/ByeDPIAndroid) --- ### Возможности * Автозапуск сервиса при старте устройства * Сохранение списков параметров командной строки * Улучшена совместимость с Android TV/BOX * Раздельное туннелирование приложений * Импорт/экспорт настроек ### Использование * Для работы автозапуска активируйте пункт в настройках. * Рекомендуется подключится один раз к VPN, чтобы принять запрос. * После этого, при загрузке устройства, приложение автоматически запустит сервис в зависимости от настроек (VPN/Proxy) * Комплексная инструкция от комьюнити [ByeByeDPI-Manual](https://github.com/BDManual/ByeByeDPI-Manual) ### Как использовать ByeByeDPI вместе с AdGuard? * Запустите ByeByeDPI в режиме прокси. * Добавьте ByeByeDPI в исключения AdGuard на вкладке "Управление приложениями". * В настройках AdGuard укажите прокси: ```plaintext Тип прокси: SOCKS5 Хост: 127.0.0.1 Порт: 1080 (по умолчанию) ``` ### Сборка 1. Клонируйте репозиторий с сабмодулями: ```bash git clone --recurse-submodules ``` 2. Запустите скрипт сборки из корня репозитория: ```bash ./gradlew assembleRelease ``` 3. APK будет в `app/build/outputs/apk/release/` > P.S.: hev_socks5_tunnel не соберется под Windows, вам нужно будет использовать WSL ### Хеш подписи SHA-256: `77:45:10:75:AC:EA:40:64:06:47:5D:74:D4:59:88:3A:49:A6:40:51:FA:F3:2E:42:F7:18:F3:F9:77:7A:8D:FB` ### Зависимости - [ByeDPI](https://github.com/hufrea/byedpi) - [hev-socks5-tunnel](https://github.com/heiher/hev-socks5-tunnel) ================================================ FILE: app/.gitignore ================================================ /build /debug /release *.aar *.jar ================================================ FILE: app/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { id("com.android.application") id("org.jetbrains.kotlin.android") } val abis = setOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64") android { namespace = "io.github.romanvht.byedpi" compileSdk = 36 defaultConfig { applicationId = "io.github.romanvht.byedpi" minSdk = 21 //noinspection OldTargetApi targetSdk = 34 versionCode = 1730 versionName = "1.7.3" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { abiFilters.addAll(abis) } } buildFeatures { buildConfig = true viewBinding = true } buildTypes { release { buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"") proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") isMinifyEnabled = true isShrinkResources = true } debug { buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}-debug\"") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_1_8) } } externalNativeBuild { cmake { path = file("src/main/cpp/CMakeLists.txt") version = "3.22.1" } } // https://android.izzysoft.de/articles/named/iod-scan-apkchecks?lang=en#blobs dependenciesInfo { // Disables dependency metadata when building APKs. includeInApk = false // Disables dependency metadata when building Android App Bundles. includeInBundle = false } splits { abi { isEnable = true reset() include(*abis.toTypedArray()) isUniversalApk = true } } } dependencies { implementation("androidx.fragment:fragment-ktx:1.8.9") implementation("androidx.core:core-ktx:1.17.0") implementation("androidx.appcompat:appcompat:1.7.1") implementation("androidx.preference:preference-ktx:1.2.1") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.4") implementation("androidx.lifecycle:lifecycle-service:2.9.4") implementation("com.google.android.material:material:1.13.0") implementation("com.google.code.gson:gson:2.13.2") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.3.0") androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") } tasks.register("runNdkBuild") { group = "build" val ndkDir = android.ndkDirectory executable = if (System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) { "$ndkDir\\ndk-build.cmd" } else { "$ndkDir/ndk-build" } setArgs(listOf( "NDK_PROJECT_PATH=build/intermediates/ndkBuild", "NDK_LIBS_OUT=src/main/jniLibs", "APP_BUILD_SCRIPT=src/main/jni/Android.mk", "NDK_APPLICATION_MK=src/main/jni/Application.mk" )) println("Command: $commandLine") } tasks.preBuild { dependsOn("runNdkBuild") } ================================================ FILE: app/proguard-rules.pro ================================================ # Keep JNI methods -keepclasseswithmembernames class * { native ; } -keep class io.github.romanvht.byedpi.core.ByeDpiProxy { *; } -keep,allowoptimization class io.github.romanvht.byedpi.core.TProxyService { *; } -keep,allowoptimization class io.github.romanvht.byedpi.activities.** { *; } -keep,allowoptimization class io.github.romanvht.byedpi.services.** { *; } -keep,allowoptimization class io.github.romanvht.byedpi.receiver.** { *; } -keep class io.github.romanvht.byedpi.fragments.** { (); } -keep,allowoptimization class io.github.romanvht.byedpi.data.** { ; } -keepattributes Signature -keepattributes *Annotation* -repackageclasses 'ru.romanvht' -renamesourcefileattribute '' -keepattributes SourceFile,InnerClasses,EnclosingMethod,Signature,RuntimeVisibleAnnotations,*Annotation*,*Parcelable* -allowaccessmodification -overloadaggressively -optimizationpasses 5 -verbose -dontusemixedcaseclassnames -adaptclassstrings -adaptresourcefilecontents **.xml,**.json -adaptresourcefilenames **.xml,**.json ================================================ FILE: app/src/androidTest/java/io/github/romanvht/byedpi/ExampleInstrumentedTest.kt ================================================ package io.github.romanvht.byedpi import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * 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("io.github.romanvht.byedpi", appContext.packageName) } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/proxytest_cloudflare.sites ================================================ cloudflare.net cloudflare.com cloudflarecn.net cloudflare-ech.com ================================================ FILE: app/src/main/assets/proxytest_discord.sites ================================================ dis.gd discord.co discord.gg discord.app discord.com discord.dev discord.new discord.gift discord.gifts discord.media discord.store discord.design discordapp.com discordcdn.com discordsez.com discordsays.com discordmerch.com discordpartygames.com discordactivities.com stable.dl2.discordapp.net discord-attachments-uploads-prd.storage.googleapis.com ================================================ FILE: app/src/main/assets/proxytest_general.sites ================================================ rutracker.org nyaa.si rutor.org nnmclub.to speedtest.net ookla.com ================================================ FILE: app/src/main/assets/proxytest_googlevideo.sites ================================================ rr1---sn-4axm-n8vs.googlevideo.com rr1---sn-gvnuxaxjvh-o8ge.googlevideo.com rr1---sn-ug5onuxaxjvh-p3ul.googlevideo.com rr1---sn-ug5onuxaxjvh-n8v6.googlevideo.com rr4---sn-q4flrnsl.googlevideo.com rr10---sn-gvnuxaxjvh-304z.googlevideo.com rr14---sn-n8v7kn7r.googlevideo.com rr16---sn-axq7sn76.googlevideo.com rr1---sn-8ph2xajvh-5xge.googlevideo.com rr1---sn-gvnuxaxjvh-5gie.googlevideo.com rr12---sn-gvnuxaxjvh-bvwz.googlevideo.com rr5---sn-n8v7knez.googlevideo.com rr1---sn-u5uuxaxjvhg0-ocje.googlevideo.com rr2---sn-q4fl6ndl.googlevideo.com rr5---sn-gvnuxaxjvh-n8vk.googlevideo.com rr4---sn-jvhnu5g-c35d.googlevideo.com rr1---sn-q4fl6n6y.googlevideo.com rr2---sn-hgn7ynek.googlevideo.com rr1---sn-xguxaxjvh-gufl.googlevideo.com ================================================ FILE: app/src/main/assets/proxytest_social.sites ================================================ snapchat.com snap.com linkedin.com facebook.com fb.com fb.me fbcdn.net messenger.com meta.com instagram.com static.cdninstagram.com proton.me medium.com x.com twitter.com soundcloud.com telegram.org whatsapp.com ================================================ FILE: app/src/main/assets/proxytest_strategies.list ================================================ -f-200 -Qr -s3:5+sm -a1 -As -d1 -s4+sm -s8+sh -f-300 -d6+sh -a1 -At,r,s -o2 -f-30 -As -r5 -Mh -r6+sh -f-250 -s2:7+s -s3:6+sm -a1 -At,r,s -s3:5+sm -s6+s -s7:9+s -q30+sm -a1 -d1 -d3+s -s6+s -d9+s -s12+s -d15+s -s20+s -d25+s -s30+s -d35+s -r1+s -S -a1 -As -d1 -d3+s -s6+s -d9+s -s12+s -d15+s -s20+s -d25+s -s30+s -d35+s -S -a1 -q2 -s2 -s3+s -r3 -s4 -r4 -s5+s -r5+s -s6 -s7+s -r8 -s9+s -Qr -Mh,d,r -a1 -At,r -s2+s -r2 -d2 -s3 -r3 -r4 -s4 -d5+s -r5 -d6 -s7+s -d7 -a1 -o1 -d1 -a1 -At,r,s -s1 -d1 -s5+s -s10+s -s15+s -s20+s -r1+s -S -a1 -As -s1 -d1 -s5+s -s10+s -s15+s -s20+s -S -a1 -n {sni} -Qr -f-204 -s1:5+sm -a1 -As -d1 -s3+s -s5+s -q7 -a1 -As -o2 -f-43 -a1 -As -r5 -Mh -s1:5+s -s3:7+sm -a1 -n {sni} -Qr -f-205 -a1 -As -s1:3+sm -a1 -As -s5:8+sm -a1 -As -d3 -q7 -o2 -f-43 -f-85 -f-165 -r5 -Mh -a1 -d1+s -s50+s -a1 -As -f20 -r2+s -a1 -At -d2 -s1+s -s5+s -s10+s -s15+s -s25+s -s35+s -s50+s -s60+s -a1 -o1 -a1 -At,r,s -f-1 -a1 -At,r,s -d1:11+sm -S -a1 -At,r,s -n {sni} -Qr -f1 -d1:11+sm -s1:11+sm -S -a1 -d1 -s1 -q1 -Y -a1 -Ar -s5 -o1+s -d3+s -s6+s -d9+s -s12+s -d15+s -s20+s -d25+s -s30+s -d35+s -a1 -f1+nme -t6 -a1 -As -n {sni} -Qr -s1:6+sm -a1 -As -s5:12+sm -a1 -As -d3 -q7 -r6 -Mh -a1 -s1 -o1 -a1 -Y -Ar -s5 -o1+s -a1 -At -f-1 -r1+s -a1 -As -s1 -o1+s -s-1 -a1 -s1 -d1 -a1 -Y -Ar -d5 -o1+s -a1 -At -f-1 -r1+s -a1 -As -d1 -o1+s -s-1 -a1 -d1 -s1+s -d3+s -s6+s -d9+s -s12+s -d15+s -s20+s -d25+s -s30+s -d35+s -a1 -s1 -q1 -a1 -Y -Ar -a1 -s5 -o2 -At -f-1 -r1+s -a1 -As -s1 -o1+s -s-1 -a1 -s1 -q1 -a1 -Ar -s5 -o1+s -a1 -At -f-1 -d1+s -a1 -As -s1 -o1+s -s-1 -a1 -s1 -q1 -a1 -Ar -s5 -o2 -a1 -At -f-1 -r1+s -a1 -As -s1 -o1+s -s-1 -a1 -d1 -s1+s -d1+s -s3+s -d6+s -s12+s -d14+s -s20+s -d24+s -s30+s -a1 -s1 -q1 -a1 -Y -At -a1 -S -f-1 -r1+s -a1 -As -d1+s -O1 -s29+s -a1 -o1 -a1 -At,r,s -f-1 -a1 -Ar,s -o1 -a1 -At -r1+s -f-1 -t6 -a1 -d1 -s1+s -s3+s -s6+s -s9+s -s12+s -s15+s -s20+s -s30+s -a1 -f1 -t5 -n {sni} -q3+h -Qr -f2 -q1 -r1+s -t15 -q1 -o2 -a1 -n {sni} -d2:5:2+h -f-3 -r2+sm -o2 -o50+s -r2+s -f-4 -a1 -r-1+s -o20+sm -s3:7+sm -d5:3+sm -f300+s -Qr -Y -f-1 -a1 -f-1 -Qr -s1+sm -d3+s -s5+sm -o2 -a1 -As -r1+s -d8+s -a1 -s25 -r5+s -s25+s -a1 -At,r,s -s50 -r5+s -s50+s -a1 -o1 -r-5+se -a1 -At,r,s -d1 -n {sni} -Qr -f-1 -a1 -s1 -d1 -r1+s -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -s1 -q1 -r1+s -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -s1 -o1 -r1+s -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -n {sni} -Qr -f6+nr -d2 -d11 -f9+hm -o3 -t7 -a1 -s1 -d1 -o1 -a1 -Ar -o3 -a1 -At -f-1 -r1+s -a1 -d9+s -q20+s -s25+s -t5 -a1 -At,r,s -r1+h -a1 -q1+s -s29+s -s30+s -s14+s -o5+s -f-1 -S -a1 -d1 -s1+s -r1+s -e1 -m1 -o1+s -f-1 -t2 -a1 -d9+s -q20+s -s 25+s -t5 -At,r,s -r1+h -a1 -s1 -o1 -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -d1 -o1 -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -d1 -s4 -d8 -s1+s -d5+s -s10+s -d20+s -a1 -n {sni} -Qr -d5+sm -f3+sm -o2 -t4 -a1 -o1 -a1 -Ar -q1 -a1 -At -f-1 -r1+s -a1 -q1 -a1 -Ar -o1 -a1 -At -f-1 -r1+s -a1 -s1 -q1 -Y -a1 -At,r,s -f-1 -r1+s -a1 -s1 -o1 -Y -a1 -At,r,s -f-1 -r1+s -a1 -s1 -d1 -Y -a1 -At,r,s -f-1 -r1+s -a1 -n {sni} -Qr -f209 -s1+sm -R1-3 -a1 -s1 -q1 -a1 -At,r,s -f-1 -r1+s -a1 -s1 -o1 -a1 -At,r,s -f-1 -r1+s -a1 -s1 -d1 -a1 -At,r,s -f-1 -r1+s -a1 -s4+sn -r9+s -Qr -n {sni} -S -a1 -n {sni} -Qr -m0x02 -f-1 -d7 -a1 -o1 -d1 -r1+s -S -s1+s -d3+s -a1 -d1 -r1+s -f-1 -S -t8 -o3+s -a1 -q1+s -s29+s -o5+s -f-1 -S -a1 -d1 -s1+s -r1+s -f-1 -t8 -a1 -o1 -a1 -An -f1+nme -t6 -a1 -n {sni} -Qr -f-1 -r1+s -a1 -n {sni} -Qr -d1:3 -f-1 -a1 -s1 -d3+s -a1 -At -r1+s -a1 -o1 -a1 -At,r,s -d1 -a1 -q1 -a1 -At,r,s -d1 -a1 -n {sni} -Qr -d1 -f-1 -d1+s -o2 -s5 -r5 -a1 -r8 -o2 -s7 -q4+s -a1 -d6+s -q4+hm -o2 -a1 -s1+s -d3+s -a1 -s1 -f-1 -S -a1 -o1+s -d3+s -a1 -o1 -s4 -s6 -a1 -q1 -r25+s -a1 -d1 -s3+s -a1 -o3 -d7 -a1 -d7 -s2 -a1 ================================================ FILE: app/src/main/assets/proxytest_youtube.sites ================================================ youtu.be youtube.com i.ytimg.com i9.ytimg.com yt3.ggpht.com yt4.ggpht.com googleapis.com jnn-pa.googleapis.com googleusercontent.com signaler-pa.youtube.com youtubei.googleapis.com manifest.googlevideo.com yt3.googleusercontent.com ================================================ FILE: app/src/main/cpp/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.22.1) project(byedpi_native) file(GLOB BYE_DPI_SRC byedpi/*.c) list(REMOVE_ITEM BYE_DPI_SRC ${CMAKE_CURRENT_SOURCE_DIR}/byedpi/win_service.c) add_library(byedpi SHARED ${BYE_DPI_SRC} native-lib.c) target_include_directories(byedpi PRIVATE byedpi) target_compile_options(byedpi PRIVATE -std=c99 -O2 -Wall -Wno-unused -Wextra -Wno-unused-parameter -pedantic) target_compile_definitions(byedpi PRIVATE ANDROID_APP) target_link_libraries(byedpi PRIVATE android log) ================================================ FILE: app/src/main/cpp/main.h ================================================ void clear_params(char *line, char **argv); int main(int argc, char **argv); ================================================ FILE: app/src/main/cpp/native-lib.c ================================================ #include #include #include #include #include #include #include "byedpi/error.h" #include "main.h" extern int server_fd; static int g_proxy_running = 0; struct params default_params = { .await_int = 10, .ipv6 = 1, .resolve = 1, .udp = 1, .max_open = 512, .bfsize = 16384, .baddr = { .in6 = { .sin6_family = AF_INET6 } }, .laddr = { .in = { .sin_family = AF_INET } }, .debug = 0 }; void reset_params(void) { clear_params(NULL, NULL); params = default_params; } JNIEXPORT jint JNICALL Java_io_github_romanvht_byedpi_core_ByeDpiProxy_jniStartProxy(JNIEnv *env, __attribute__((unused)) jobject thiz, jobjectArray args) { if (g_proxy_running) { LOG(LOG_S, "proxy already running"); return -1; } int argc = (*env)->GetArrayLength(env, args); char **argv = calloc(argc, sizeof(char *)); if (!argv) { LOG(LOG_S, "failed to allocate memory for argv"); return -1; } for (int i = 0; i < argc; i++) { jstring arg = (jstring) (*env)->GetObjectArrayElement(env, args, i); if (!arg) { argv[i] = NULL; continue; } const char *arg_str = (*env)->GetStringUTFChars(env, arg, 0); argv[i] = arg_str ? strdup(arg_str) : NULL; if (arg_str) (*env)->ReleaseStringUTFChars(env, arg, arg_str); (*env)->DeleteLocalRef(env, arg); } LOG(LOG_S, "starting proxy with %d args", argc); reset_params(); g_proxy_running = 1; optind = 1; int result = main(argc, argv); LOG(LOG_S, "proxy return code %d", result); g_proxy_running = 0; for (int i = 0; i < argc; i++) free(argv[i]); free(argv); return result; } JNIEXPORT jint JNICALL Java_io_github_romanvht_byedpi_core_ByeDpiProxy_jniStopProxy(__attribute__((unused)) JNIEnv *env, __attribute__((unused)) jobject thiz) { LOG(LOG_S, "send shutdown to proxy"); if (!g_proxy_running) { LOG(LOG_S, "proxy is not running"); return -1; } shutdown(server_fd, SHUT_RDWR); g_proxy_running = 0; return 0; } JNIEXPORT jint JNICALL Java_io_github_romanvht_byedpi_core_ByeDpiProxy_jniForceClose(__attribute__((unused)) JNIEnv *env, __attribute__((unused)) jobject thiz) { LOG(LOG_S, "closing server socket (fd: %d)", server_fd); if (close(server_fd) == -1) { LOG(LOG_S, "failed to close server socket (fd: %d)", server_fd); return -1; } LOG(LOG_S, "proxy socket force close"); g_proxy_running = 0; return 0; } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/BaseActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.material.color.DynamicColors import io.github.romanvht.byedpi.utility.SettingsUtils import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.getStringNotNull abstract class BaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { val prefs = getPreferences() val lang = prefs.getStringNotNull("language", "system") SettingsUtils.setLang(lang) val theme = prefs.getStringNotNull("app_theme", "system") SettingsUtils.setTheme(theme) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { DynamicColors.applyToActivityIfAvailable(this) } super.onCreate(savedInstanceState) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/MainActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.Manifest import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.net.VpnService import android.os.Build import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.* import io.github.romanvht.byedpi.databinding.ActivityMainBinding import io.github.romanvht.byedpi.services.ServiceManager import io.github.romanvht.byedpi.services.appStatus import io.github.romanvht.byedpi.utility.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.io.IOException import kotlin.system.exitProcess import androidx.core.content.edit class MainActivity : BaseActivity() { private lateinit var binding: ActivityMainBinding companion object { private val TAG: String = MainActivity::class.java.simpleName private const val BATTERY_OPTIMIZATION_REQUESTED = "battery_optimization_requested" private fun collectLogs(): String? = try { Runtime.getRuntime() .exec("logcat *:D -d") .inputStream.bufferedReader() .use { it.readText() } } catch (e: Exception) { Log.e(TAG, "Failed to collect logs", e) null } } private val vpnRegister = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == RESULT_OK) { ServiceManager.start(this, Mode.VPN) } else { Toast.makeText(this, R.string.vpn_permission_denied, Toast.LENGTH_SHORT).show() updateStatus() } } private val logsRegister = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { log -> lifecycleScope.launch(Dispatchers.IO) { val logs = collectLogs() if (logs == null) { Toast.makeText( this@MainActivity, R.string.logs_failed, Toast.LENGTH_SHORT ).show() } else { val uri = log.data?.data ?: run { Log.e(TAG, "No data in result") return@launch } contentResolver.openOutputStream(uri)?.use { try { it.write(logs.toByteArray()) } catch (e: IOException) { Log.e(TAG, "Failed to save logs", e) } } ?: run { Log.e(TAG, "Failed to open output stream") } } } } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.d(TAG, "Received intent: ${intent?.action}") if (intent == null) { Log.w(TAG, "Received null intent") return } val senderOrd = intent.getIntExtra(SENDER, -1) val sender = Sender.entries.getOrNull(senderOrd) if (sender == null) { Log.w(TAG, "Received intent with unknown sender: $senderOrd") return } when (val action = intent.action) { STARTED_BROADCAST, STOPPED_BROADCAST -> updateStatus() FAILED_BROADCAST -> { Toast.makeText( context, getString(R.string.failed_to_start, sender.name), Toast.LENGTH_SHORT, ).show() updateStatus() } else -> Log.w(TAG, "Unknown action: $action") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val intentFilter = IntentFilter().apply { addAction(STARTED_BROADCAST) addAction(STOPPED_BROADCAST) addAction(FAILED_BROADCAST) } @SuppressLint("UnspecifiedRegisterReceiverFlag") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { registerReceiver(receiver, intentFilter, RECEIVER_EXPORTED) } else { registerReceiver(receiver, intentFilter) } binding.statusButtonCard.setOnClickListener { binding.statusButtonCard.isClickable = false val (status, _) = appStatus when (status) { AppStatus.Halted -> start() AppStatus.Running -> stop() } binding.statusButtonCard.postDelayed({ binding.statusButtonCard.isClickable = true }, 1000) } binding.statusButtonCard.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { binding.statusButtonCard.strokeWidth = 10 binding.statusButtonCard.strokeColor = android.graphics.Color.argb(100, 0, 0, 0) } else { binding.statusButtonCard.strokeWidth = 0 } } binding.settingsButton.setOnClickListener { val (status, _) = appStatus if (status == AppStatus.Halted) { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } else { Toast.makeText(this, R.string.settings_unavailable, Toast.LENGTH_SHORT).show() } } binding.editorButton.setOnClickListener { val useCmdSettings = getPreferences().getBoolean("byedpi_enable_cmd_settings", false) if (!useCmdSettings && appStatus.first == AppStatus.Running) { Toast.makeText(this, R.string.settings_unavailable, Toast.LENGTH_SHORT).show() return@setOnClickListener } val intent = Intent(this, SettingsActivity::class.java) intent.putExtra("open_fragment", if (useCmdSettings) "cmd" else "ui") startActivity(intent) } binding.testProxyButton.setOnClickListener { startActivity(Intent(this, TestActivity::class.java)) } binding.domainListsButton.setOnClickListener { val intent = Intent(this, TestSettingsActivity::class.java) intent.putExtra("open_fragment", "domain_lists") startActivity(intent) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1) } else { requestBatteryOptimization() } if (getPreferences().getBoolean("auto_connect", false) && appStatus.first != AppStatus.Running) { this.start() } ShortcutUtils.update(this) } override fun onResume() { super.onResume() updateStatus() updateButtonsVisibility() } override fun onDestroy() { super.onDestroy() unregisterReceiver(receiver) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 1) { requestBatteryOptimization() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val (status, _) = appStatus return when (item.itemId) { R.id.action_save_logs -> { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "text/plain" putExtra(Intent.EXTRA_TITLE, "byedpi.log") } logsRegister.launch(intent) true } R.id.action_close_app -> { if (status == AppStatus.Running) stop() finishAffinity() android.os.Process.killProcess(android.os.Process.myPid()) exitProcess(0) } else -> super.onOptionsItemSelected(item) } } private fun start() { when (getPreferences().mode()) { Mode.VPN -> { val intentPrepare = VpnService.prepare(this) if (intentPrepare != null) { vpnRegister.launch(intentPrepare) } else { ServiceManager.start(this, Mode.VPN) } } Mode.Proxy -> ServiceManager.start(this, Mode.Proxy) } } private fun stop() { ServiceManager.stop(this) } private fun updateStatus() { val (status, mode) = appStatus Log.i(TAG, "Updating status: $status, $mode") val preferences = getPreferences() val (ip, port) = preferences.getProxyIpAndPort() binding.proxyAddress.text = getString(R.string.proxy_address, ip, port) when (status) { AppStatus.Halted -> { val typedValue = android.util.TypedValue() theme.resolveAttribute(android.R.attr.colorPrimary, typedValue,true) binding.statusButtonCard.setCardBackgroundColor(typedValue.data) binding.statusButtonIcon.clearColorFilter() when (preferences.mode()) { Mode.VPN -> { binding.statusText.setText(R.string.vpn_disconnected) } Mode.Proxy -> { binding.statusText.setText(R.string.proxy_down) } } } AppStatus.Running -> { binding.statusButtonCard.setCardBackgroundColor(ContextCompat.getColor(this, R.color.green_active)) binding.statusButtonIcon.setColorFilter(ContextCompat.getColor(this, android.R.color.white)) when (mode) { Mode.VPN -> { binding.statusText.setText(R.string.vpn_connected) } Mode.Proxy -> { binding.statusText.setText(R.string.proxy_up) } } } } } private fun updateButtonsVisibility() { val useCmdSettings = getPreferences().getBoolean("byedpi_enable_cmd_settings", false) val visibility = if (useCmdSettings) View.VISIBLE else View.GONE binding.cmdButtonsRow.visibility = visibility } private fun requestBatteryOptimization() { val preferences = getPreferences() val alreadyRequested = preferences.getBoolean(BATTERY_OPTIMIZATION_REQUESTED, false) if (!alreadyRequested && !BatteryUtils.isOptimizationDisabled(this)) { BatteryUtils.requestBatteryOptimization(this) preferences.edit { putBoolean(BATTERY_OPTIMIZATION_REQUESTED, true) } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/SettingsActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.result.contract.ActivityResultContracts import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.fragments.ByeDpiCMDSettingsFragment import io.github.romanvht.byedpi.fragments.ByeDpiUISettingsFragment import io.github.romanvht.byedpi.fragments.MainSettingsFragment import io.github.romanvht.byedpi.utility.SettingsUtils import io.github.romanvht.byedpi.utility.getPreferences import androidx.core.content.edit class SettingsActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) val openFragment = intent.getStringExtra("open_fragment") when (openFragment) { "cmd" -> { supportFragmentManager .beginTransaction() .replace(R.id.settings, ByeDpiCMDSettingsFragment()) .commit() } "ui" -> { supportFragmentManager .beginTransaction() .replace(R.id.settings, ByeDpiUISettingsFragment()) .commit() } else -> { supportFragmentManager .beginTransaction() .replace(R.id.settings, MainSettingsFragment()) .commit() } } supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_settings, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> { onBackPressedDispatcher.onBackPressed() true } R.id.action_reset_settings -> { val prefs = getPreferences() prefs.edit { clear() } recreate() true } R.id.action_export_settings -> { val fileName = "bbd_${System.currentTimeMillis().toReadableDateTime()}.json" exportSettingsLauncher.launch(fileName) true } R.id.action_import_settings -> { importSettingsLauncher.launch(arrayOf("application/json")) true } else -> super.onOptionsItemSelected(item) } private val exportSettingsLauncher = registerForActivityResult( ActivityResultContracts.CreateDocument("application/json") ) { uri -> uri?.let { SettingsUtils.exportSettings(this, it) } } private val importSettingsLauncher = registerForActivityResult( ActivityResultContracts.OpenDocument() ) { uri -> uri?.let { SettingsUtils.importSettings(this, it) { recreate() } } } private fun Long.toReadableDateTime(): String { val format = java.text.SimpleDateFormat("yyyyMMdd_HHmm", java.util.Locale.getDefault()) return format.format(this) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/TestActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.content.Intent import android.net.VpnService import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.adapters.StrategyResultAdapter import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.data.AppStatus import io.github.romanvht.byedpi.data.SiteResult import io.github.romanvht.byedpi.data.StrategyResult import io.github.romanvht.byedpi.services.appStatus import io.github.romanvht.byedpi.services.ServiceManager import io.github.romanvht.byedpi.utility.HistoryUtils import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.SiteCheckUtils import io.github.romanvht.byedpi.utility.getIntStringNotNull import io.github.romanvht.byedpi.utility.getLongStringNotNull import androidx.core.content.edit import io.github.romanvht.byedpi.utility.getStringNotNull import com.google.gson.Gson import com.google.gson.reflect.TypeToken import io.github.romanvht.byedpi.utility.DomainListUtils import io.github.romanvht.byedpi.utility.mode import kotlinx.coroutines.* import java.io.File class TestActivity : BaseActivity() { private lateinit var strategiesRecyclerView: RecyclerView private lateinit var progressTextView: TextView private lateinit var disclaimerTextView: TextView private lateinit var startStopButton: Button private lateinit var strategyAdapter: StrategyResultAdapter private lateinit var siteChecker: SiteCheckUtils private lateinit var cmdHistoryUtils: HistoryUtils private lateinit var sites: List private lateinit var cmds: List private var savedCmd: String = "" private var testJob: Job? = null private val strategies = mutableListOf() private val gson = Gson() private var isTesting: Boolean get() = prefs.getBoolean("is_test_running", false) set(value) { prefs.edit(commit = true) { putBoolean("is_test_running", value) } } private val prefs by lazy { getPreferences() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_proxy_test) val ip = prefs.getStringNotNull("byedpi_proxy_ip", "127.0.0.1") val port = prefs.getIntStringNotNull("byedpi_proxy_port", 1080) siteChecker = SiteCheckUtils(ip, port) cmdHistoryUtils = HistoryUtils(this) strategiesRecyclerView = findViewById(R.id.strategiesRecyclerView) startStopButton = findViewById(R.id.startStopButton) progressTextView = findViewById(R.id.progressTextView) disclaimerTextView = findViewById(R.id.disclaimerTextView) strategyAdapter = StrategyResultAdapter(this, onApply = { command -> addToHistory(command) } ) strategiesRecyclerView.layoutManager = LinearLayoutManager(this) strategiesRecyclerView.adapter = strategyAdapter lifecycleScope.launch { val previousResults = loadResults() if (previousResults.isNotEmpty()) { progressTextView.text = getString(R.string.test_complete) disclaimerTextView.visibility = View.GONE strategies.clear() strategies.addAll(previousResults) strategyAdapter.updateStrategies(strategies) } if (isTesting) { progressTextView.text = getString(R.string.test_proxy_error) disclaimerTextView.text = getString(R.string.test_crash) disclaimerTextView.visibility = View.VISIBLE isTesting = false } } startStopButton.setOnClickListener { startStopButton.isClickable = false if (isTesting) { stopTesting() } else { startTesting() } startStopButton.postDelayed({ startStopButton.isClickable = true }, 1000) } onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (isTesting) { stopTesting() } else { if (appStatus.first == AppStatus.Running) { val intent = Intent(this@TestActivity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) } } finish() } }) supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_test, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> { if (!isTesting) { val intent = Intent(this, TestSettingsActivity::class.java) startActivity(intent) } else { Toast.makeText(this, R.string.settings_unavailable, Toast.LENGTH_SHORT).show() } true } android.R.id.home -> { onBackPressedDispatcher.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } private suspend fun waitForProxyStatus(statusNeeded: AppStatus): Boolean { val startTime = System.currentTimeMillis() while (System.currentTimeMillis() - startTime < 3000) { if (appStatus.first == statusNeeded) { delay(500) return true } delay(100) } return false } private suspend fun isProxyRunning(): Boolean = withContext(Dispatchers.IO) { appStatus.first == AppStatus.Running } private fun updateCmdArgs(cmd: String) { prefs.edit(commit = true) { putString("byedpi_cmd_args", cmd) } } private fun startTesting() { sites = loadSites() cmds = loadCmds() if (sites.isEmpty()) { Toast.makeText(this, R.string.test_settings_domain_empty, Toast.LENGTH_LONG).show() return } testJob = lifecycleScope.launch(Dispatchers.IO) { isTesting = true savedCmd = prefs.getString("byedpi_cmd_args", "").orEmpty() strategies.clear() strategies.addAll(cmds.map { StrategyResult(command = it) }) withContext(Dispatchers.Main) { disclaimerTextView.visibility = View.GONE window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) startStopButton.text = getString(R.string.test_stop) progressTextView.text = "" strategyAdapter.setTestingState(true) strategyAdapter.updateStrategies(strategies, sortByPercentage = false) } if (isProxyRunning()) { ServiceManager.stop(this@TestActivity) waitForProxyStatus(AppStatus.Halted) } val delaySec = prefs.getIntStringNotNull("byedpi_proxytest_delay", 1) val requestsCount = prefs.getIntStringNotNull("byedpi_proxytest_requests", 1) val requestTimeout = prefs.getLongStringNotNull("byedpi_proxytest_timeout", 5) val requestLimit = prefs.getIntStringNotNull("byedpi_proxytest_limit", 20) for (strategyIndex in strategies.indices) { if (!isActive) break val strategy = strategies[strategyIndex] val cmdIndex = strategyIndex + 1 withContext(Dispatchers.Main) { progressTextView.text = getString(R.string.test_process, cmdIndex, cmds.size) } updateCmdArgs(strategy.command) if (isProxyRunning()) stopTesting() else ServiceManager.start(this@TestActivity, Mode.Proxy) if (!waitForProxyStatus(AppStatus.Running)) { stopTesting() } delay(delaySec * 500L) val totalRequests = sites.size * requestsCount strategy.totalRequests = totalRequests withContext(Dispatchers.Main) { strategyAdapter.notifyItemChanged(strategyIndex) } siteChecker.checkSitesAsync( sites = sites, requestsCount = requestsCount, requestTimeout = requestTimeout, concurrentRequests = requestLimit, fullLog = true, onSiteChecked = { site, successCount, countRequests -> lifecycleScope.launch(Dispatchers.Main) { strategy.currentProgress += countRequests strategy.successCount += successCount strategy.siteResults.add(SiteResult(site, successCount, countRequests)) strategyAdapter.notifyItemChanged(strategyIndex, "progress") } } ) strategy.isCompleted = true withContext(Dispatchers.Main) { strategyAdapter.updateStrategies(strategies, sortByPercentage = true) saveResults(strategies) } if (isProxyRunning()) ServiceManager.stop(this@TestActivity) else stopTesting() if (!waitForProxyStatus(AppStatus.Halted)) { stopTesting() } delay(delaySec * 500L) } stopTesting() } } private fun stopTesting() { if (!isTesting) { return } lifecycleScope.launch(Dispatchers.IO) { isTesting = false updateCmdArgs(savedCmd) testJob?.cancel() testJob = null if (isProxyRunning()) { ServiceManager.stop(this@TestActivity) } withContext(Dispatchers.Main) { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) startStopButton.text = getString(R.string.test_start) progressTextView.text = getString(R.string.test_complete) strategyAdapter.setTestingState(false) strategyAdapter.updateStrategies(strategies, sortByPercentage = true) saveResults(strategies) } } } private fun addToHistory(command: String) { lifecycleScope.launch(Dispatchers.IO) { updateCmdArgs(command) cmdHistoryUtils.addCommand(command) val mode = prefs.mode() if (mode == Mode.VPN && VpnService.prepare(this@TestActivity) != null) return@launch val toastText = if (appStatus.first == AppStatus.Running) { ServiceManager.restart(this@TestActivity, mode) R.string.service_restart } else { R.string.cmd_history_applied } withContext(Dispatchers.Main) { Toast.makeText(this@TestActivity, toastText, Toast.LENGTH_SHORT).show() } } } private fun saveResults(results: List) { val file = File(filesDir, "proxy_test_results.json") val json = gson.toJson(results) file.writeText(json) } private fun loadResults(): List { val file = File(filesDir, "proxy_test_results.json") return if (file.exists()) { try { val json = file.readText() val type = object : TypeToken>() {}.type gson.fromJson>(json, type) ?: emptyList() } catch (e: Exception) { emptyList() } } else { emptyList() } } private fun loadSites(): List { DomainListUtils.initializeDefaultLists(this) return DomainListUtils.getActiveDomains(this) } private fun loadCmds(): List { val userCommands = prefs.getBoolean("byedpi_proxytest_usercommands", false) val sniValue = prefs.getStringNotNull("byedpi_proxytest_sni", "google.com") return if (userCommands) { val content = prefs.getStringNotNull("byedpi_proxytest_commands", "") content.replace("{sni}", sniValue).lines().map { it.trim() }.filter { it.isNotEmpty() } } else { val content = assets.open("proxytest_strategies.list").bufferedReader().readText() content.replace("{sni}", sniValue).lines().map { it.trim() }.filter { it.isNotEmpty() } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/TestSettingsActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.os.Bundle import android.view.MenuItem import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.fragments.DomainListsFragment import io.github.romanvht.byedpi.fragments.ProxyTestSettingsFragment class TestSettingsActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test_settings) val openFragment = intent.getStringExtra("open_fragment") when (openFragment) { "domain_lists" -> { supportFragmentManager .beginTransaction() .replace(R.id.test_settings, DomainListsFragment()) .commit() } else -> { supportFragmentManager .beginTransaction() .replace(R.id.test_settings, ProxyTestSettingsFragment()) .commit() } } supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> { onBackPressedDispatcher.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/activities/ToggleActivity.kt ================================================ package io.github.romanvht.byedpi.activities import android.app.Activity import android.content.SharedPreferences import android.net.VpnService import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import androidx.core.content.edit import io.github.romanvht.byedpi.data.AppStatus import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.services.ServiceManager import io.github.romanvht.byedpi.services.appStatus import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.mode class ToggleActivity : Activity() { companion object { private const val TAG = "ToggleServiceActivity" } private lateinit var prefs: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) prefs = getPreferences() val strategy = intent.getStringExtra("strategy") val updated = updateStrategy(strategy) val onlyUpdate = intent.getBooleanExtra("only_update", false) val onlyStart = intent.getBooleanExtra("only_start", false) val onlyStop = intent.getBooleanExtra("only_stop", false) when { onlyUpdate -> { Log.i(TAG, "Only update strategy") } onlyStart -> { val (status) = appStatus if (status == AppStatus.Halted) { startService() } else { Log.i(TAG, "Service already running") } } onlyStop -> { val (status) = appStatus if (status == AppStatus.Running) { stopService() } else { Log.i(TAG, "Service already stopped") } } else -> { toggleService(updated) } } finish() } private fun startService() { val mode = prefs.mode() if (mode == Mode.VPN && VpnService.prepare(this) != null) { return } ServiceManager.start(this, mode) Log.i(TAG, "Toggle service start") } private fun restartService() { val mode = prefs.mode() if (mode == Mode.VPN && VpnService.prepare(this) != null) { return } ServiceManager.restart(this, mode) Log.i(TAG, "Toggle service start") } private fun stopService() { ServiceManager.stop(this) Log.i(TAG, "Toggle service stop") } private fun toggleService(restart: Boolean) { val (status) = appStatus when (status) { AppStatus.Halted -> { startService() } AppStatus.Running -> { if (restart) { restartService() } else { stopService() } } } } private fun updateStrategy(strategy: String?): Boolean { val current = prefs.getString("byedpi_cmd_args", null) if (strategy != null && strategy != current) { prefs.edit(commit = true) { putString("byedpi_cmd_args", strategy) } Log.i(TAG, "Strategy updated to: $strategy") return true } return false } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/adapters/AppSelectionAdapter.kt ================================================ package io.github.romanvht.byedpi.adapters import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.Filter import android.widget.Filterable import android.widget.ImageView import android.widget.TextView import androidx.core.content.edit import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.AppInfo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class AppSelectionAdapter( context: Context, allApps: List ) : RecyclerView.Adapter(), Filterable { private val context = context.applicationContext private val pm = context.packageManager private val originalApps: List = allApps private val filteredApps: MutableList = allApps.toMutableList() private val adapterScope = CoroutineScope(Dispatchers.Main + Job()) class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val appIcon: ImageView = view.findViewById(R.id.appIcon) val appName: TextView = view.findViewById(R.id.appName) val appPackageName: TextView = view.findViewById(R.id.appPackageName) val appCheckBox: CheckBox = view.findViewById(R.id.appCheckBox) var iconLoadJob: Job? = null } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.app_selection_item, parent, false) val holder = ViewHolder(view) holder.itemView.setOnClickListener { val position = holder.bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { val app = filteredApps[position] app.isSelected = !app.isSelected notifyItemChanged(position) updateSelectedApps() } } return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = filteredApps[position] if (app.appName == app.packageName) { holder.appName.text = app.packageName holder.appPackageName.visibility = View.GONE } else { holder.appName.text = app.appName holder.appPackageName.text = app.packageName holder.appPackageName.visibility = View.VISIBLE } holder.appCheckBox.isChecked = app.isSelected holder.iconLoadJob?.cancel() if (app.icon != null) { holder.appIcon.setImageDrawable(app.icon) } else { holder.appIcon.setImageDrawable(pm.defaultActivityIcon) holder.iconLoadJob = adapterScope.launch { val icon = withContext(Dispatchers.IO) { try { pm.getApplicationIcon(app.packageName) } catch (_: Exception) { null } } if (icon != null) { app.icon = icon holder.appIcon.setImageDrawable(icon) } } } } override fun getItemCount(): Int { return filteredApps.size } override fun onViewRecycled(holder: ViewHolder) { super.onViewRecycled(holder) holder.iconLoadJob?.cancel() } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(constraint: CharSequence?): FilterResults { val query = constraint?.toString()?.lowercase().orEmpty() var filteredList = originalApps if (query.isNotEmpty()) { filteredList = originalApps.filter { it.appName.lowercase().contains(query) || it.packageName.lowercase().contains(query) } } return FilterResults().apply { values = filteredList } } @SuppressLint("NotifyDataSetChanged") override fun publishResults(constraint: CharSequence, results: FilterResults) { val newList = (results.values as List<*>).filterIsInstance() filteredApps.clear() filteredApps.addAll(newList) notifyDataSetChanged() } } } private fun getAllSelectedPackages(): Set { return originalApps.filter { it.isSelected }.map { it.packageName }.toSet() } private fun updateSelectedApps() { val prefs = PreferenceManager.getDefaultSharedPreferences(context) val selectedApps = getAllSelectedPackages() prefs.edit { putStringSet("selected_apps", selectedApps) } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/adapters/DomainListAdapter.kt ================================================ package io.github.romanvht.byedpi.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.DomainList class DomainListAdapter( private val onStateChanged: (DomainList) -> Unit, private val onEdit: (DomainList) -> Unit, private val onDelete: (DomainList) -> Unit, private val onCopy: (DomainList) -> Unit ) : ListAdapter(DiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DomainListViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_domain_list, parent, false) val holder = DomainListViewHolder(view) holder.checkbox.setOnClickListener { val position = holder.bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { onStateChanged(getItem(position)) } } holder.contentLayout.setOnClickListener { val position = holder.bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { holder.showActionDialog(getItem(position), onEdit, onCopy, onDelete) } } return holder } override fun onBindViewHolder(holder: DomainListViewHolder, position: Int) { holder.bind(getItem(position)) } class DomainListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val nameText: TextView = itemView.findViewById(R.id.list_name) private val countText: TextView = itemView.findViewById(R.id.list_count) val checkbox: CheckBox = itemView.findViewById(R.id.list_checkbox) val contentLayout: LinearLayout = itemView.findViewById(R.id.list_content) fun bind(domainList: DomainList) { nameText.text = domainList.name val domains = domainList.domains.take(5).joinToString("\n") val summary = if (domainList.domains.size > 5) "$domains\n..." else domains countText.text = summary checkbox.isChecked = domainList.isActive } fun showActionDialog( domainList: DomainList, onEdit: (DomainList) -> Unit, onCopy: (DomainList) -> Unit, onDelete: (DomainList) -> Unit ) { val context = itemView.context val options = arrayOf( context.getString(R.string.domain_list_edit), context.getString(R.string.cmd_history_copy), context.getString(R.string.domain_list_delete) ) AlertDialog.Builder(context, R.style.CustomAlertDialog) .setTitle(domainList.name) .setItems(options) { _, which -> when (which) { 0 -> onEdit(domainList) 1 -> onCopy(domainList) 2 -> onDelete(domainList) } } .setNegativeButton(android.R.string.cancel, null) .show() } } private class DiffCallback : DiffUtil.ItemCallback() { override fun areItemsTheSame(oldItem: DomainList, newItem: DomainList): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: DomainList, newItem: DomainList): Boolean { return oldItem == newItem } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/adapters/SiteResultAdapter.kt ================================================ package io.github.romanvht.byedpi.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.SiteResult class SiteResultAdapter : RecyclerView.Adapter() { private val sites = mutableListOf() class SiteViewHolder(view: View) : RecyclerView.ViewHolder(view) { val siteTextView: TextView = view.findViewById(R.id.siteTextView) val resultTextView: TextView = view.findViewById(R.id.siteResultTextView) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SiteViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_site_result, parent, false) return SiteViewHolder(view) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: SiteViewHolder, position: Int) { val site = sites[position] holder.siteTextView.text = site.site holder.resultTextView.text = "${site.successCount}/${site.totalCount}" } override fun getItemCount(): Int { return sites.size } @SuppressLint("NotifyDataSetChanged") fun updateSites(newSites: List) { sites.clear() sites.addAll(newSites) notifyDataSetChanged() } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/adapters/StrategyResultAdapter.kt ================================================ package io.github.romanvht.byedpi.adapters import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.StrategyResult import androidx.core.view.isGone import androidx.core.view.isVisible import io.github.romanvht.byedpi.utility.ClipboardUtils class StrategyResultAdapter( private val context: Context, private val onApply: (String) -> Unit ) : RecyclerView.Adapter() { private var isTesting = false private val strategies = mutableListOf() class StrategyViewHolder(view: View) : RecyclerView.ViewHolder(view) { val commandTextView: TextView = view.findViewById(R.id.commandTextView) val progressLayout: LinearLayout = view.findViewById(R.id.progressLayout) val progressBar: ProgressBar = view.findViewById(R.id.progressBar) val progressTextView: TextView = view.findViewById(R.id.progressTextView) val expandButton: LinearLayout = view.findViewById(R.id.expandButton) val expandTextView: TextView = view.findViewById(R.id.expandTextView) val expandIcon: ImageView = view.findViewById(R.id.expandIcon) val sitesRecyclerView: RecyclerView = view.findViewById(R.id.sitesRecyclerView) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StrategyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_strategy_result, parent, false) val holder = StrategyViewHolder(view) holder.commandTextView.setOnClickListener { val position = holder.bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { showCommandMenu(strategies[position].command) } } holder.expandButton.setOnClickListener { val position = holder.bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { strategies[position].isExpanded = !strategies[position].isExpanded notifyItemChanged(position) } } return holder } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: StrategyViewHolder, position: Int) { val strategy = strategies[position] holder.commandTextView.text = strategy.command if (strategy.totalRequests > 0) { holder.progressLayout.visibility = View.VISIBLE holder.progressTextView.visibility = View.VISIBLE val isProgress = isTesting && !strategy.isCompleted if (isProgress) { holder.progressBar.isIndeterminate = true holder.progressTextView.text = "${strategy.successCount}/${strategy.totalRequests}" } else { holder.progressBar.isIndeterminate = false holder.progressBar.max = strategy.totalRequests holder.progressBar.progress = strategy.successCount holder.progressTextView.text = "${strategy.successCount}/${strategy.totalRequests}" } } else { holder.progressLayout.visibility = View.GONE } if (strategy.siteResults.isNotEmpty()) { holder.expandButton.visibility = View.VISIBLE if (strategy.isExpanded) { holder.expandTextView.text = context.getString(R.string.test_hide_details) holder.expandIcon.rotation = 180f holder.sitesRecyclerView.visibility = View.VISIBLE val siteAdapter = SiteResultAdapter() holder.sitesRecyclerView.layoutManager = LinearLayoutManager(context) holder.sitesRecyclerView.adapter = siteAdapter siteAdapter.updateSites(strategy.siteResults) } else { holder.expandTextView.text = context.getString(R.string.test_show_details) holder.expandIcon.rotation = 0f holder.sitesRecyclerView.visibility = View.GONE } } else { holder.expandButton.visibility = View.GONE holder.sitesRecyclerView.visibility = View.GONE } } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: StrategyViewHolder, position: Int, payloads: MutableList) { if (payloads.isEmpty()) { super.onBindViewHolder(holder, position, payloads) } else { val strategy = strategies[position] if (strategy.totalRequests > 0) { val isProgress = isTesting && !strategy.isCompleted if (isProgress) { holder.progressBar.isIndeterminate = true holder.progressTextView.text = "${strategy.successCount}/${strategy.totalRequests}" } else { holder.progressBar.isIndeterminate = false holder.progressBar.max = strategy.totalRequests holder.progressBar.progress = strategy.successCount holder.progressTextView.text = "${strategy.successCount}/${strategy.totalRequests}" } } if (strategy.siteResults.isNotEmpty() && holder.expandButton.isGone) { holder.expandButton.visibility = View.VISIBLE } if (strategy.isExpanded && holder.sitesRecyclerView.isVisible) { val adapter = holder.sitesRecyclerView.adapter if (adapter is SiteResultAdapter) { adapter.updateSites(strategy.siteResults) } } } } override fun getItemCount(): Int { return strategies.size } @SuppressLint("NotifyDataSetChanged") fun setTestingState(testing: Boolean) { isTesting = testing notifyDataSetChanged() } @SuppressLint("NotifyDataSetChanged") fun updateStrategies(newStrategies: List, sortByPercentage: Boolean = true) { strategies.clear() val sorted = if (sortByPercentage) { newStrategies.sortedWith(compareByDescending { it.isCompleted } .thenByDescending { it.successPercentage } .thenByDescending { it.successCount }) } else { newStrategies } strategies.addAll(sorted) notifyDataSetChanged() } private fun showCommandMenu(command: String) { val menuItems = arrayOf( context.getString(R.string.cmd_history_apply), context.getString(R.string.cmd_history_copy) ) AlertDialog.Builder(context) .setTitle(context.getString(R.string.cmd_history_menu)) .setItems(menuItems) { _, which -> when (which) { 0 -> onApply(command) 1 -> ClipboardUtils.copy(context, command, "command") } } .show() } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/core/ByeDpiProxy.kt ================================================ package io.github.romanvht.byedpi.core class ByeDpiProxy { companion object { init { System.loadLibrary("byedpi") } } fun startProxy(preferences: ByeDpiProxyPreferences): Int { val args = prepareArgs(preferences) return jniStartProxy(args) } fun stopProxy(): Int { return jniStopProxy() } private fun prepareArgs(preferences: ByeDpiProxyPreferences): Array = when (preferences) { is ByeDpiProxyCmdPreferences -> preferences.args is ByeDpiProxyUIPreferences -> preferences.uiargs } private external fun jniStartProxy(args: Array): Int private external fun jniStopProxy(): Int external fun jniForceClose(): Int } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/core/ByeDpiProxyPreferences.kt ================================================ package io.github.romanvht.byedpi.core import android.content.Context import android.content.SharedPreferences import android.util.Log import io.github.romanvht.byedpi.data.UISettings import io.github.romanvht.byedpi.utility.DomainListUtils import io.github.romanvht.byedpi.utility.checkIpAndPortInCmd import io.github.romanvht.byedpi.utility.getStringNotNull import io.github.romanvht.byedpi.utility.shellSplit sealed interface ByeDpiProxyPreferences { companion object { fun fromSharedPreferences(preferences: SharedPreferences, context: Context): ByeDpiProxyPreferences = when (preferences.getBoolean("byedpi_enable_cmd_settings", false)) { true -> ByeDpiProxyCmdPreferences(preferences, context) false -> ByeDpiProxyUIPreferences(preferences) } } } class ByeDpiProxyCmdPreferences(val args: Array) : ByeDpiProxyPreferences { constructor(preferences: SharedPreferences, context: Context) : this( parseCmdToArguments(preferences, context) ) companion object { private fun parseCmdToArguments(preferences: SharedPreferences, context: Context): Array { val cmd = preferences.getStringNotNull("byedpi_cmd_args", "-Ku -a1 -An -o1 -At,r,s -d1") val preparedCmd = getLists(cmd, context) val firstArgIndex = preparedCmd.indexOf("-") val args = (if (firstArgIndex > 0) preparedCmd.substring(firstArgIndex) else preparedCmd).trim() Log.d("ProxyPref", "CMD: $args") val (cmdIp, cmdPort) = preferences.checkIpAndPortInCmd() val ip = preferences.getStringNotNull("byedpi_proxy_ip", "127.0.0.1") val port = preferences.getStringNotNull("byedpi_proxy_port", "1080") val enableHttp = preferences.getBoolean("byedpi_http_connect", false) val hasHttp = args.contains("-G") || args.contains("--http-connect") val prefix = buildString { if (cmdIp == null) append("--ip $ip ") if (cmdPort == null) append("--port $port ") if (enableHttp && !hasHttp) append("--http-connect ") } Log.d("ProxyPref", "Added from settings: $prefix") return if (prefix.isNotEmpty()) { arrayOf("ciadpi") + shellSplit("$prefix$args") } else { arrayOf("ciadpi") + shellSplit(args) } } private fun getLists(cmd: String, context: Context): String { return Regex("""\{list:([^}]+)\}""").replace(cmd) { matchResult -> val listName = matchResult.groupValues[1].trim() val lists = DomainListUtils.getLists(context) val domainList = lists.find { it.name.equals(listName, ignoreCase = true) } if (domainList != null && domainList.domains.isNotEmpty()) { domainList.domains.joinToString(" ") } else { Log.w("ProxyPref", "List '$listName' not found or empty") "" } } } } } class ByeDpiProxyUIPreferences(val settings: UISettings = UISettings()) : ByeDpiProxyPreferences { constructor(preferences: SharedPreferences) : this( UISettings.fromSharedPreferences(preferences) ) val uiargs: Array get() { val args = mutableListOf("ciadpi") if (settings.ip.isNotEmpty()) args.add("-i${settings.ip}") if (settings.port != 0) args.add("-p${settings.port}") if (settings.maxConnections != 0) args.add("-c${settings.maxConnections}") if (settings.bufferSize != 0) args.add("-b${settings.bufferSize}") if (settings.httpConnect) args.add("-G") val protocols = buildList { if (settings.desyncHttps) add("t") if (settings.desyncHttp) add("h") } if (!settings.hosts.isNullOrBlank()) { val hostStr = ":${settings.hosts.replace("\n", " ")}" when (settings.hostsMode) { UISettings.HostsMode.Blacklist -> { args.add("-H$hostStr") args.add("-An") if (protocols.isNotEmpty()) args.add("-K${protocols.joinToString(",")}") } UISettings.HostsMode.Whitelist -> { if (protocols.isNotEmpty()) args.add("-K${protocols.joinToString(",")}") args.add("-H$hostStr") } else -> {} } } else { if (protocols.isNotEmpty()) args.add("-K${protocols.joinToString(",")}") } if (settings.defaultTtl != 0) args.add("-g${settings.defaultTtl}") if (settings.noDomain) args.add("-N") if (settings.splitPosition != 0) { val posArg = settings.splitPosition.toString() + if (settings.splitAtHost) "+h" else "" val option = when (settings.desyncMethod) { UISettings.DesyncMethod.Split -> "-s" UISettings.DesyncMethod.Disorder -> "-d" UISettings.DesyncMethod.OOB -> "-o" UISettings.DesyncMethod.DISOOB -> "-q" UISettings.DesyncMethod.Fake -> "-f" UISettings.DesyncMethod.None -> "" } if (option.isNotEmpty()) args.add("$option$posArg") } if (settings.desyncMethod == UISettings.DesyncMethod.Fake) { if (settings.fakeTtl != 0) args.add("-t${settings.fakeTtl}") if (settings.fakeSni.isNotEmpty()) args.add("-n${settings.fakeSni}") if (settings.fakeOffset != 0) args.add("-O${settings.fakeOffset}") } if (settings.desyncMethod == UISettings.DesyncMethod.OOB || settings.desyncMethod == UISettings.DesyncMethod.DISOOB) { args.add("-e${settings.oobChar[0].code.toByte()}") } val modHttpFlags = buildList { if (settings.hostMixedCase) add("h") if (settings.domainMixedCase) add("d") if (settings.hostRemoveSpaces) add("r") } if (modHttpFlags.isNotEmpty()) args.add("-M${modHttpFlags.joinToString(",")}") if (settings.tlsRecordSplit && settings.tlsRecordSplitPosition != 0) { val tlsRecArg = settings.tlsRecordSplitPosition.toString() + if (settings.tlsRecordSplitAtSni) "+s" else "" args.add("-r$tlsRecArg") } if (settings.tcpFastOpen) args.add("-F") if (settings.dropSack) args.add("-Y") args.add("-An") if (settings.desyncUdp) { args.add("-Ku") if (settings.udpFakeCount != 0) args.add("-a${settings.udpFakeCount}") args.add("-An") } Log.d("ProxyPref", "UI to cmd: ${args.joinToString(" ")}") return args.toTypedArray() } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/core/TProxyService.kt ================================================ package io.github.romanvht.byedpi.core object TProxyService { init { System.loadLibrary("hev-socks5-tunnel") } @JvmStatic external fun TProxyStartService(configPath: String, fd: Int) @JvmStatic external fun TProxyStopService() @JvmStatic @Suppress("unused") external fun TProxyGetStats(): LongArray } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/Actions.kt ================================================ package io.github.romanvht.byedpi.data const val START_ACTION = "start" const val STOP_ACTION = "stop" const val RESUME_ACTION = "resume" const val PAUSE_ACTION = "pause" ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/AppInfo.kt ================================================ package io.github.romanvht.byedpi.data import android.graphics.drawable.Drawable data class AppInfo( val appName: String, val packageName: String, var isSelected: Boolean, var icon: Drawable? = null ) ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/AppSettings.kt ================================================ package io.github.romanvht.byedpi.data data class AppSettings( val app: String, val version: String, val history: List?, val apps: List?, val domainLists: List?, val settings: Map ) ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/AppStatus.kt ================================================ package io.github.romanvht.byedpi.data enum class AppStatus { Halted, Running, } enum class Mode { Proxy, VPN; companion object { fun fromSender(sender: Sender): Mode = when (sender) { Sender.Proxy -> Proxy Sender.VPN -> VPN } fun fromString(name: String): Mode = when (name) { "proxy" -> Proxy "vpn" -> VPN else -> throw IllegalArgumentException("Invalid mode: $name") } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/Broadcasts.kt ================================================ package io.github.romanvht.byedpi.data import io.github.romanvht.byedpi.BuildConfig const val STARTED_BROADCAST = "${BuildConfig.APPLICATION_ID}.STARTED" const val STOPPED_BROADCAST = "${BuildConfig.APPLICATION_ID}.STOPPED" const val FAILED_BROADCAST = "${BuildConfig.APPLICATION_ID}.FAILED" const val SENDER = "sender" enum class Sender(val senderName: String) { Proxy("Proxy"), VPN("VPN") } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/Command.kt ================================================ package io.github.romanvht.byedpi.data data class Command( var text: String, var pinned: Boolean = false, var name: String? = null ) ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/DomainList.kt ================================================ package io.github.romanvht.byedpi.data data class DomainList( val id: String, val name: String, val domains: List, val isActive: Boolean = true, val isBuiltIn: Boolean = false ) ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/ServiceStatus.kt ================================================ package io.github.romanvht.byedpi.data enum class ServiceStatus { Disconnected, Connected, Failed, } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/TestResult.kt ================================================ package io.github.romanvht.byedpi.data data class StrategyResult( val command: String, var successCount: Int = 0, var totalRequests: Int = 0, var currentProgress: Int = 0, var isCompleted: Boolean = false, val siteResults: MutableList = mutableListOf(), var isExpanded: Boolean = false ) { val successPercentage: Int get() = if (totalRequests > 0) (successCount * 100) / totalRequests else 0 } data class SiteResult( val site: String, val successCount: Int, val totalCount: Int ) ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/data/UISettings.kt ================================================ package io.github.romanvht.byedpi.data import android.content.SharedPreferences data class UISettings( val ip: String = "127.0.0.1", val port: Int = 1080, val httpConnect: Boolean = false, val maxConnections: Int = 512, val bufferSize: Int = 16384, val defaultTtl: Int = 0, val noDomain: Boolean = false, val desyncHttp: Boolean = true, val desyncHttps: Boolean = true, val desyncUdp: Boolean = true, val desyncMethod: DesyncMethod = DesyncMethod.OOB, val splitPosition: Int = 1, val splitAtHost: Boolean = false, val fakeTtl: Int = 8, val fakeSni: String = "www.iana.org", val oobChar: String = "a", val hostMixedCase: Boolean = false, val domainMixedCase: Boolean = false, val hostRemoveSpaces: Boolean = false, val tlsRecordSplit: Boolean = false, val tlsRecordSplitPosition: Int = 0, val tlsRecordSplitAtSni: Boolean = false, val hostsMode: HostsMode = HostsMode.Disable, val hosts: String? = null, val tcpFastOpen: Boolean = false, val udpFakeCount: Int = 1, val dropSack: Boolean = false, val fakeOffset: Int = 0, ) { enum class DesyncMethod { None, Split, Disorder, Fake, OOB, DISOOB; companion object { fun fromName(name: String): DesyncMethod = when (name) { "none" -> None "split" -> Split "disorder" -> Disorder "fake" -> Fake "oob" -> OOB "disoob" -> DISOOB else -> throw IllegalArgumentException("Unknown desync method: $name") } } } enum class HostsMode { Disable, Blacklist, Whitelist; companion object { fun fromName(name: String): HostsMode = when (name) { "disable" -> Disable "blacklist" -> Blacklist "whitelist" -> Whitelist else -> throw IllegalArgumentException("Unknown hosts mode: $name") } } } companion object { fun fromSharedPreferences(preferences: SharedPreferences): UISettings { val hostsMode = preferences.getString("byedpi_hosts_mode", null) ?.let { HostsMode.fromName(it) } ?: HostsMode.Disable val hosts = when (hostsMode) { HostsMode.Blacklist -> preferences.getString("byedpi_hosts_blacklist", null) HostsMode.Whitelist -> preferences.getString("byedpi_hosts_whitelist", null) else -> null } return UISettings( ip = preferences.getString("byedpi_proxy_ip", null) ?: "127.0.0.1", port = preferences.getString("byedpi_proxy_port", null)?.toIntOrNull() ?: 1080, httpConnect = preferences.getBoolean("byedpi_http_connect", false), maxConnections = preferences.getString("byedpi_max_connections", null)?.toIntOrNull() ?: 512, bufferSize = preferences.getString("byedpi_buffer_size", null)?.toIntOrNull() ?: 16384, defaultTtl = preferences.getString("byedpi_default_ttl", null)?.toIntOrNull() ?: 0, noDomain = preferences.getBoolean("byedpi_no_domain", false), desyncHttp = preferences.getBoolean("byedpi_desync_http", true), desyncHttps = preferences.getBoolean("byedpi_desync_https", true), desyncUdp = preferences.getBoolean("byedpi_desync_udp", true), desyncMethod = preferences.getString("byedpi_desync_method", null) ?.let { DesyncMethod.fromName(it) } ?: DesyncMethod.OOB, splitPosition = preferences.getString("byedpi_split_position", null)?.toIntOrNull() ?: 1, splitAtHost = preferences.getBoolean("byedpi_split_at_host", false), fakeTtl = preferences.getString("byedpi_fake_ttl", null)?.toIntOrNull() ?: 8, fakeSni = preferences.getString("byedpi_fake_sni", null) ?: "www.iana.org", oobChar = preferences.getString("byedpi_oob_data", null) ?: "a", hostMixedCase = preferences.getBoolean("byedpi_host_mixed_case", false), domainMixedCase = preferences.getBoolean("byedpi_domain_mixed_case", false), hostRemoveSpaces = preferences.getBoolean("byedpi_host_remove_spaces", false), tlsRecordSplit = preferences.getBoolean("byedpi_tlsrec_enabled", false), tlsRecordSplitPosition = preferences.getString("byedpi_tlsrec_position", null)?.toIntOrNull() ?: 0, tlsRecordSplitAtSni = preferences.getBoolean("byedpi_tlsrec_at_sni", false), tcpFastOpen = preferences.getBoolean("byedpi_tcp_fast_open", false), udpFakeCount = preferences.getString("byedpi_udp_fake_count", null)?.toIntOrNull() ?: 1, dropSack = preferences.getBoolean("byedpi_drop_sack", false), fakeOffset = preferences.getString("byedpi_fake_offset", null)?.toIntOrNull() ?: 0, hostsMode = hostsMode, hosts = hosts, ) } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/AppSelectionFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.SearchView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.adapters.AppSelectionAdapter import io.github.romanvht.byedpi.data.AppInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class AppSelectionFragment : Fragment() { private lateinit var recyclerView: RecyclerView private lateinit var searchView: SearchView private lateinit var progressBar: ProgressBar private lateinit var adapter: AppSelectionAdapter private lateinit var prefs: SharedPreferences override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.app_selection_layout, container, false) prefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) recyclerView = view.findViewById(R.id.recyclerView) searchView = view.findViewById(R.id.searchView) progressBar = view.findViewById(R.id.progressBar) setupRecyclerView() setupSearchView() loadApps() return view } override fun onDestroyView() { super.onDestroyView() recyclerView.adapter = null searchView.setOnQueryTextListener(null) } private fun setupRecyclerView() { recyclerView.layoutManager = LinearLayoutManager(context) } private fun setupSearchView() { searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean = false override fun onQueryTextChange(newText: String?): Boolean { adapter.filter.filter(newText) return true } }) } private fun loadApps() { progressBar.visibility = View.VISIBLE searchView.visibility = View.GONE lifecycleScope.launch { val apps = withContext(Dispatchers.IO) { getInstalledAppsAsync() } adapter = AppSelectionAdapter(requireContext(), apps) recyclerView.adapter = adapter progressBar.visibility = View.GONE searchView.visibility = View.VISIBLE } } private suspend fun getInstalledAppsAsync(): List { val pm = requireContext().packageManager val installedApps = pm.getInstalledApplications(0) val selectedApps = prefs.getStringSet("selected_apps", setOf()) ?: setOf() return installedApps .filter { it.packageName != requireContext().packageName } .map { appInfo -> lifecycleScope.async(Dispatchers.IO) { createAppInfo(appInfo, pm, selectedApps) } } .awaitAll() .sortedWith(compareBy({ !it.isSelected }, { it.appName.lowercase() })) } private fun createAppInfo( appInfo: ApplicationInfo, pm: PackageManager, selectedApps: Set ): AppInfo { val appName = try { pm.getApplicationLabel(appInfo).toString() } catch (_: Exception) { appInfo.packageName } return AppInfo( appName, appInfo.packageName, selectedApps.contains(appInfo.packageName), icon = null ) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/ByeDpiCMDSettingsFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.net.VpnService import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.preference.* import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.utility.findPreferenceNotNull import androidx.appcompat.app.AlertDialog import io.github.romanvht.byedpi.data.AppStatus import io.github.romanvht.byedpi.data.Command import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.services.ServiceManager import io.github.romanvht.byedpi.services.appStatus import io.github.romanvht.byedpi.utility.ClipboardUtils import io.github.romanvht.byedpi.utility.HistoryUtils import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.mode class ByeDpiCMDSettingsFragment : PreferenceFragmentCompat() { private lateinit var cmdHistoryUtils: HistoryUtils private lateinit var editTextPreference: EditTextPreference private lateinit var historyHeader: Preference private val historyPreferences = mutableListOf() override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.byedpi_cmd_settings, rootKey) cmdHistoryUtils = HistoryUtils(requireContext()) editTextPreference = findPreferenceNotNull("byedpi_cmd_args") historyHeader = findPreferenceNotNull("cmd_history_header") editTextPreference.setOnPreferenceChangeListener { _, newValue -> val newCommand = newValue.toString() if (newCommand.isNotBlank()) { cmdHistoryUtils.addCommand(newCommand) restartService() } updateHistoryItems() true } historyHeader.setOnPreferenceClickListener { showHistoryClearDialog() true } updateHistoryItems() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.post { view.findViewById(R.id.btn_clear)?.setOnClickListener { editTextPreference.text = "" updateHistoryItems() } view.findViewById(R.id.btn_paste)?.setOnClickListener { val text = ClipboardUtils.paste(requireContext()) if (!text.isNullOrBlank()) { editTextPreference.text = text cmdHistoryUtils.addCommand(text) updateHistoryItems() } } } } private fun updateHistoryItems() { if (listView !== null) { listView.itemAnimator = null } historyPreferences.forEach { preference -> preferenceScreen.removePreference(preference) } historyPreferences.clear() val history = cmdHistoryUtils.getHistory() historyHeader.isVisible = history.isNotEmpty() if (history.isNotEmpty()) { history.sortedWith(compareByDescending { it.pinned }.thenBy { history.indexOf(it) }) .forEachIndexed { _, command -> val preference = createPreference(command) historyPreferences.add(preference) preferenceScreen.addPreference(preference) } } } private fun createPreference(command: Command) = object : Preference(requireContext()) { override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) val nameView = holder.itemView.findViewById(R.id.command_name) val summaryView = holder.itemView.findViewById(android.R.id.summary) val pinIcon = holder.itemView.findViewById(R.id.pin_icon) val commandName = command.name if (!commandName.isNullOrBlank()) { nameView.visibility = View.VISIBLE nameView.text = command.name } else { nameView.visibility = View.GONE } val summaryText = buildSummary(command) if (summaryText.isNotBlank()) { summaryView.visibility = View.VISIBLE summaryView.text = summaryText } else { summaryView.visibility = View.GONE } pinIcon.visibility = if (command.pinned) View.VISIBLE else View.GONE } }.apply { title = command.text layoutResource = R.layout.history_item setOnPreferenceClickListener { showActionDialog(command) true } } private fun buildSummary(command: Command): String { val parts = mutableListOf() if (command.text == editTextPreference.text) { parts.add(getString(R.string.cmd_history_applied)) } return parts.joinToString(" • ") } private fun showHistoryClearDialog() { val options = arrayOf( getString(R.string.cmd_history_delete_unpinned), getString(R.string.cmd_history_delete_all), ) AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cmd_history_menu)) .setItems(options) { _, which -> when (which) { 0 -> deleteUnpinnedHistory() 1 -> deleteAllHistory() } } .setNegativeButton(getString(android.R.string.cancel), null) .show() } private fun deleteAllHistory() { cmdHistoryUtils.clearAllHistory() updateHistoryItems() } private fun deleteUnpinnedHistory() { cmdHistoryUtils.clearUnpinnedHistory() updateHistoryItems() } private fun showActionDialog(command: Command) { val options = arrayOf( getString(R.string.cmd_history_apply), if (command.pinned) getString(R.string.cmd_history_unpin) else getString(R.string.cmd_history_pin), getString(R.string.cmd_history_rename), getString(R.string.cmd_history_edit), getString(R.string.cmd_history_copy), getString(R.string.cmd_history_delete) ) AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cmd_history_menu)) .setItems(options) { _, which -> when (which) { 0 -> applyCommand(command.text) 1 -> if (command.pinned) unpinCommand(command.text) else pinCommand(command.text) 2 -> showRenameDialog(command) 3 -> showEditDialog(command) 4 -> ClipboardUtils.copy(requireContext(), command.text, "command") 5 -> deleteCommand(command.text) } } .show() } private fun showRenameDialog(command: Command) { val input = EditText(requireContext()).apply { setText(command.name) } val container = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL setPadding(50, 20, 50, 20) addView(input) } AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cmd_history_rename)) .setView(container) .setPositiveButton(getString(android.R.string.ok)) { _, _ -> val newName = input.text.toString() if (newName != command.name) { cmdHistoryUtils.renameCommand(command.text, newName) updateHistoryItems() } } .setNegativeButton(getString(android.R.string.cancel), null) .show() } private fun showEditDialog(command: Command) { val input = EditText(requireContext()).apply { setText(command.text) } val container = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL setPadding(50, 20, 50, 20) addView(input) } AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cmd_history_edit)) .setView(container) .setPositiveButton(getString(android.R.string.ok)) { _, _ -> val newText = input.text.toString() if (newText.isNotBlank() && newText != command.text) { cmdHistoryUtils.editCommand(command.text, newText) if (editTextPreference.text == command.text) applyCommand(newText) updateHistoryItems() } } .setNegativeButton(getString(android.R.string.cancel), null) .show() } private fun applyCommand(command: String) { editTextPreference.text = command updateHistoryItems() restartService() } private fun pinCommand(command: String) { cmdHistoryUtils.pinCommand(command) updateHistoryItems() } private fun unpinCommand(command: String) { cmdHistoryUtils.unpinCommand(command) updateHistoryItems() } private fun deleteCommand(command: String) { cmdHistoryUtils.deleteCommand(command) updateHistoryItems() } private fun restartService() { if (appStatus.first == AppStatus.Running) { val ctx = context ?: return val mode = ctx.getPreferences().mode() if (mode == Mode.VPN && VpnService.prepare(ctx) != null) return ServiceManager.restart(ctx, mode) Toast.makeText(ctx, R.string.service_restart, Toast.LENGTH_SHORT).show() } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/ByeDpiUISettingsFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.content.SharedPreferences import android.os.Bundle import androidx.preference.* import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.UISettings import io.github.romanvht.byedpi.data.UISettings.DesyncMethod.* import io.github.romanvht.byedpi.data.UISettings.HostsMode.* import io.github.romanvht.byedpi.utility.* class ByeDpiUISettingsFragment : PreferenceFragmentCompat() { private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> updatePreferences() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.byedpi_ui_settings, rootKey) setEditTestPreferenceListenerInt( "byedpi_max_connections", 1, Short.MAX_VALUE.toInt() ) setEditTestPreferenceListenerInt( "byedpi_buffer_size", 1, Int.MAX_VALUE / 4 ) setEditTestPreferenceListenerInt("byedpi_default_ttl", 0, 255) setEditTestPreferenceListenerInt( "byedpi_split_position", Int.MIN_VALUE, Int.MAX_VALUE ) setEditTestPreferenceListenerInt("byedpi_fake_ttl", 1, 255) setEditTestPreferenceListenerInt( "byedpi_tlsrec_position", 2 * Short.MIN_VALUE, 2 * Short.MAX_VALUE, ) findPreferenceNotNull("byedpi_oob_data") .setOnBindEditTextListener { it.filters = arrayOf(android.text.InputFilter.LengthFilter(1)) } updatePreferences() } override fun onResume() { super.onResume() sharedPreferences?.registerOnSharedPreferenceChangeListener(preferenceListener) } override fun onPause() { super.onPause() sharedPreferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener) } private fun updatePreferences() { val desyncMethod = findPreferenceNotNull("byedpi_desync_method").value.let { UISettings.DesyncMethod.fromName(it) } val hostsMode = findPreferenceNotNull("byedpi_hosts_mode").value.let { UISettings.HostsMode.fromName(it) } val hostsBlacklist = findPreferenceNotNull("byedpi_hosts_blacklist") val hostsWhitelist = findPreferenceNotNull("byedpi_hosts_whitelist") val desyncHttp = findPreferenceNotNull("byedpi_desync_http") val desyncHttps = findPreferenceNotNull("byedpi_desync_https") val desyncUdp = findPreferenceNotNull("byedpi_desync_udp") val splitPosition = findPreferenceNotNull("byedpi_split_position") val splitAtHost = findPreferenceNotNull("byedpi_split_at_host") val ttlFake = findPreferenceNotNull("byedpi_fake_ttl") val fakeSni = findPreferenceNotNull("byedpi_fake_sni") val fakeOffset = findPreferenceNotNull("byedpi_fake_offset") val oobChar = findPreferenceNotNull("byedpi_oob_data") val udpFakeCount = findPreferenceNotNull("byedpi_udp_fake_count") val hostMixedCase = findPreferenceNotNull("byedpi_host_mixed_case") val domainMixedCase = findPreferenceNotNull("byedpi_domain_mixed_case") val hostRemoveSpaces = findPreferenceNotNull("byedpi_host_remove_spaces") val splitTlsRec = findPreferenceNotNull("byedpi_tlsrec_enabled") val splitTlsRecPosition = findPreferenceNotNull("byedpi_tlsrec_position") val splitTlsRecAtSni = findPreferenceNotNull("byedpi_tlsrec_at_sni") hostsBlacklist.isVisible = hostsMode == Blacklist hostsWhitelist.isVisible = hostsMode == Whitelist val desyncEnabled = desyncMethod != None splitPosition.isVisible = desyncEnabled splitAtHost.isVisible = desyncEnabled val isFake = desyncMethod == Fake ttlFake.isVisible = isFake fakeSni.isVisible = isFake fakeOffset.isVisible = isFake val isOob = desyncMethod == OOB || desyncMethod == DISOOB oobChar.isVisible = isOob val desyncAllProtocols = !desyncHttp.isChecked && !desyncHttps.isChecked && !desyncUdp.isChecked val desyncHttpEnabled = desyncAllProtocols || desyncHttp.isChecked hostMixedCase.isEnabled = desyncHttpEnabled domainMixedCase.isEnabled = desyncHttpEnabled hostRemoveSpaces.isEnabled = desyncHttpEnabled val desyncUdpEnabled = desyncAllProtocols || desyncUdp.isChecked udpFakeCount.isEnabled = desyncUdpEnabled val desyncHttpsEnabled = desyncAllProtocols || desyncHttps.isChecked splitTlsRec.isEnabled = desyncHttpsEnabled val tlsRecEnabled = desyncHttpsEnabled && splitTlsRec.isChecked splitTlsRecPosition.isEnabled = tlsRecEnabled splitTlsRecAtSni.isEnabled = tlsRecEnabled } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/DomainListsFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.adapters.DomainListAdapter import io.github.romanvht.byedpi.data.DomainList import io.github.romanvht.byedpi.utility.ClipboardUtils import io.github.romanvht.byedpi.utility.DomainListUtils class DomainListsFragment : Fragment() { private lateinit var recyclerView: RecyclerView private lateinit var adapter: DomainListAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.domain_lists, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) DomainListUtils.initializeDefaultLists(requireContext()) recyclerView = view.findViewById(R.id.domain_lists_recycler) view.findViewById(R.id.add_new_list_button).setOnClickListener { showAddDialog() } adapter = DomainListAdapter( onStateChanged = { domainList -> DomainListUtils.toggleListActive(requireContext(), domainList.id) refreshLists() }, onEdit = { domainList -> showEditDialog(domainList) }, onDelete = { domainList -> DomainListUtils.deleteList(requireContext(), domainList.id) refreshLists() }, onCopy = { domainList -> copyDomainsToClipboard(domainList) } ) recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.adapter = adapter refreshLists() } private fun refreshLists() { val lists = DomainListUtils.getLists(requireContext()) adapter.submitList(lists.sortedBy { it.name.lowercase() }) } private fun copyDomainsToClipboard(domainList: DomainList) { val domainsText = domainList.domains.joinToString("\n") ClipboardUtils.copy(requireContext(), domainsText, domainList.name, showToast = false) Toast.makeText(requireContext(), R.string.toast_copied, Toast.LENGTH_SHORT).show() } private fun showAddDialog() { val context = requireContext() val layout = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL setPadding(50, 40, 50, 10) } val nameInput = EditText(context).apply { hint = getString(R.string.domain_list_name_hint) } val domainsInput = EditText(context).apply { hint = getString(R.string.domain_list_domains_hint) minLines = 5 gravity = android.view.Gravity.BOTTOM } layout.addView(nameInput) layout.addView(domainsInput) AlertDialog.Builder(context, R.style.CustomAlertDialog) .setTitle(R.string.domain_list_add_new) .setView(layout) .setPositiveButton(android.R.string.ok) { _, _ -> val name = nameInput.text.toString().trim() val domainsText = domainsInput.text.toString() val domains = domainsText.lines() .map { it.trim() } .filter { it.isNotEmpty() } if (name.isEmpty()) { Toast.makeText(context, R.string.domain_list_name_empty, Toast.LENGTH_SHORT).show() return@setPositiveButton } if (domains.isEmpty()) { Toast.makeText(context, R.string.domain_list_domains_empty, Toast.LENGTH_SHORT).show() return@setPositiveButton } if (DomainListUtils.addList(context, name, domains)) { Toast.makeText(context, R.string.domain_list_added, Toast.LENGTH_SHORT).show() refreshLists() } else { Toast.makeText(context, R.string.domain_list_already_exists, Toast.LENGTH_SHORT).show() } } .setNegativeButton(android.R.string.cancel, null) .show() } private fun showEditDialog(domainList: DomainList) { val context = requireContext() val layout = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL setPadding(50, 40, 50, 10) } val nameInput = EditText(context).apply { hint = getString(R.string.domain_list_name_hint) setText(domainList.name) } val domainsInput = EditText(context).apply { hint = getString(R.string.domain_list_domains_hint) minLines = 5 gravity = android.view.Gravity.BOTTOM setText(domainList.domains.joinToString("\n")) } layout.addView(nameInput) layout.addView(domainsInput) AlertDialog.Builder(context, R.style.CustomAlertDialog) .setTitle(R.string.domain_list_edit) .setView(layout) .setPositiveButton(android.R.string.ok) { _, _ -> val name = nameInput.text.toString().trim() val domainsText = domainsInput.text.toString() val domains = domainsText.lines() .map { it.trim() } .filter { it.isNotEmpty() } if (name.isEmpty()) { Toast.makeText(context, R.string.domain_list_name_empty, Toast.LENGTH_SHORT).show() return@setPositiveButton } if (domains.isEmpty()) { Toast.makeText(context, R.string.domain_list_domains_empty, Toast.LENGTH_SHORT).show() return@setPositiveButton } if (DomainListUtils.updateList(context, domainList.id, name, domains)) { Toast.makeText(context, R.string.domain_list_updated, Toast.LENGTH_SHORT).show() refreshLists() } else { Toast.makeText(context, R.string.domain_list_update_failed, Toast.LENGTH_SHORT).show() } } .setNegativeButton(android.R.string.cancel, null) .show() } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/MainSettingsFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import androidx.preference.* import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.BuildConfig import io.github.romanvht.byedpi.activities.TestActivity import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.utility.* class MainSettingsFragment : PreferenceFragmentCompat() { companion object { private val TAG: String = MainSettingsFragment::class.java.simpleName } private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> updatePreferences() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.main_settings, rootKey) setEditTextPreferenceListener("byedpi_proxy_ip") { checkIp(it) } setEditTestPreferenceListenerPort("byedpi_proxy_port") setEditTextPreferenceListener("dns_ip") { it.isBlank() || checkNotLocalIp(it) } findPreferenceNotNull("language") .setOnPreferenceChangeListener { _, newValue -> SettingsUtils.setLang(newValue as String) true } findPreferenceNotNull("app_theme") .setOnPreferenceChangeListener { _, newValue -> SettingsUtils.setTheme(newValue as String) true } findPreferenceNotNull("proxy_test") .setOnPreferenceClickListener { val intent = Intent(context, TestActivity::class.java) startActivity(intent) true } findPreferenceNotNull("battery_optimization") .setOnPreferenceClickListener { BatteryUtils.requestBatteryOptimization(requireContext()) true } findPreferenceNotNull("storage_access") .setOnPreferenceClickListener { StorageUtils.requestStoragePermission(this) true } findPreferenceNotNull("version").summary = BuildConfig.VERSION_NAME findPreferenceNotNull("byedpi_version").summary = "0.17.3" updatePreferences() } override fun onResume() { super.onResume() sharedPreferences?.registerOnSharedPreferenceChangeListener(preferenceListener) updatePreferences() } override fun onPause() { super.onPause() sharedPreferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener) } private fun updatePreferences() { val cmdEnable = findPreferenceNotNull("byedpi_enable_cmd_settings").isChecked val mode = findPreferenceNotNull("byedpi_mode").value.let { Mode.fromString(it) } val dns = findPreferenceNotNull("dns_ip") val ipv6 = findPreferenceNotNull("ipv6_enable") val proxy = findPreferenceNotNull("byedpi_proxy_category") val applistType = findPreferenceNotNull("applist_type") val selectedApps = findPreferenceNotNull("selected_apps") val batteryOptimization = findPreferenceNotNull("battery_optimization") val storageAccess = findPreferenceNotNull("storage_access") val uiSettings = findPreferenceNotNull("byedpi_ui_settings") val cmdSettings = findPreferenceNotNull("byedpi_cmd_settings") val proxyTest = findPreferenceNotNull("proxy_test") if (cmdEnable) { val (cmdIp, cmdPort) = sharedPreferences?.checkIpAndPortInCmd() ?: Pair(null, null) proxy.isVisible = cmdIp == null && cmdPort == null } else { proxy.isVisible = true } uiSettings.isEnabled = !cmdEnable cmdSettings.isEnabled = cmdEnable proxyTest.isEnabled = cmdEnable when (mode) { Mode.VPN -> { dns.isVisible = true ipv6.isVisible = true when (applistType.value) { "disable" -> { applistType.isVisible = true selectedApps.isVisible = false } "blacklist", "whitelist" -> { applistType.isVisible = true selectedApps.isVisible = true } else -> { applistType.isVisible = true selectedApps.isVisible = false Log.w(TAG, "Unexpected applistType value: ${applistType.value}") } } } Mode.Proxy -> { dns.isVisible = false ipv6.isVisible = false applistType.isVisible = false selectedApps.isVisible = false } } if (BatteryUtils.isOptimizationDisabled(requireContext())) { batteryOptimization.summary = getString(R.string.battery_optimization_disabled_summary) } else { batteryOptimization.summary = getString(R.string.battery_optimization_summary) } if (StorageUtils.hasStoragePermission(requireContext())) { storageAccess.summary = getString(R.string.storage_access_allowed_summary) } else { storageAccess.summary = getString(R.string.storage_access_summary) } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/fragments/ProxyTestSettingsFragment.kt ================================================ package io.github.romanvht.byedpi.fragments import android.content.SharedPreferences import android.os.Bundle import androidx.preference.* import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.utility.* class ProxyTestSettingsFragment : PreferenceFragmentCompat() { private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> updatePreferences() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.proxy_test_settings, rootKey) setupNumberSummary("byedpi_proxytest_delay", R.string.proxytest_delay_desc) setupNumberSummary("byedpi_proxytest_requests", R.string.proxytest_requests_desc) setupNumberSummary("byedpi_proxytest_limit", R.string.proxytest_limit_desc) setupNumberSummary("byedpi_proxytest_timeout", R.string.proxytest_timeout_desc) setEditTestPreferenceListenerInt("byedpi_proxytest_delay", 0, 10) setEditTestPreferenceListenerInt("byedpi_proxytest_requests", 1, 20) setEditTestPreferenceListenerInt("byedpi_proxytest_timeout", 1, 15) setEditTestPreferenceListenerInt("byedpi_proxytest_limit", 1, 50) setEditTestPreferenceListenerDomain("byedpi_proxytest_sni") updatePreferences() } override fun onResume() { super.onResume() sharedPreferences?.registerOnSharedPreferenceChangeListener(preferenceListener) } override fun onPause() { super.onPause() sharedPreferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener) } private fun updatePreferences() { val switchUserCommands = findPreferenceNotNull("byedpi_proxytest_usercommands") val textUserCommands = findPreferenceNotNull("byedpi_proxytest_commands") val manageDomainLists = findPreferenceNotNull("manage_domain_lists") val activeLists = DomainListUtils.getLists(requireContext()).filter { it.isActive } manageDomainLists.summary = if (activeLists.isEmpty()) { getString(R.string.domain_lists_summary) } else { activeLists.joinToString(", ") { it.name } } textUserCommands.isEnabled = switchUserCommands.isChecked } private fun setupNumberSummary(key: String, descriptionResId: Int) { val pref = findPreference(key) ?: return pref.summaryProvider = Preference.SummaryProvider { p -> val value = p.text ?: "—" val description = getString(descriptionResId) "$value - $description" } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/receiver/BootReceiver.kt ================================================ package io.github.romanvht.byedpi.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.VpnService import android.os.SystemClock import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.services.ServiceManager import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.mode class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_BOOT_COMPLETED || intent.action == Intent.ACTION_REBOOT || intent.action == "android.intent.action.QUICKBOOT_POWERON") { // for A15, todo: use wasForceStopped if (SystemClock.elapsedRealtime() > 5 * 60 * 1000) { return } val preferences = context.getPreferences() val autorunEnabled = preferences.getBoolean("autostart", false) if(autorunEnabled) { when (preferences.mode()) { Mode.VPN -> { if (VpnService.prepare(context) == null) { ServiceManager.start(context, Mode.VPN) } } Mode.Proxy -> ServiceManager.start(context, Mode.Proxy) } } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/ByeDpiProxyService.kt ================================================ package io.github.romanvht.byedpi.services import android.app.Notification import android.app.NotificationManager import android.content.Intent import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE import android.os.Build import android.util.Log import androidx.lifecycle.LifecycleService import androidx.lifecycle.lifecycleScope import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.core.ByeDpiProxy import io.github.romanvht.byedpi.core.ByeDpiProxyPreferences import io.github.romanvht.byedpi.data.* import io.github.romanvht.byedpi.utility.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull class ByeDpiProxyService : LifecycleService() { private var proxy = ByeDpiProxy() private var proxyJob: Job? = null private val mutex = Mutex() companion object { private val TAG: String = ByeDpiProxyService::class.java.simpleName private const val FOREGROUND_SERVICE_ID: Int = 2 private const val PAUSE_NOTIFICATION_ID: Int = 3 private const val NOTIFICATION_CHANNEL_ID: String = "ByeDPI Proxy" private var status: ServiceStatus = ServiceStatus.Disconnected } override fun onCreate() { super.onCreate() registerNotificationChannel( this, NOTIFICATION_CHANNEL_ID, R.string.proxy_channel_name, ) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) startForeground() return when (val action = intent?.action) { START_ACTION -> { lifecycleScope.launch { start() } START_STICKY } STOP_ACTION -> { lifecycleScope.launch { stop() } START_NOT_STICKY } RESUME_ACTION -> { lifecycleScope.launch { start() } START_STICKY } PAUSE_ACTION -> { lifecycleScope.launch { stop() createNotificationPause() } START_NOT_STICKY } else -> { Log.w(TAG, "Unknown action: $action") START_NOT_STICKY } } } private suspend fun start() { Log.i(TAG, "Starting") val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(PAUSE_NOTIFICATION_ID) if (status == ServiceStatus.Connected) { Log.w(TAG, "Proxy already connected") return } try { mutex.withLock { if (status == ServiceStatus.Connected) { Log.w(TAG, "Proxy already connected") return@withLock } startProxy() updateStatus(ServiceStatus.Connected) } } catch (e: Exception) { Log.e(TAG, "Failed to start proxy", e) updateStatus(ServiceStatus.Failed) stop() } } private fun startForeground() { val notification: Notification = createNotification() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startForeground( FOREGROUND_SERVICE_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE, ) } else { startForeground(FOREGROUND_SERVICE_ID, notification) } } private suspend fun stop() { Log.i(TAG, "Stopping") mutex.withLock { withContext(Dispatchers.IO) { stopProxy() } updateStatus(ServiceStatus.Disconnected) } stopSelf() } private fun startProxy() { Log.i(TAG, "Starting proxy") if (proxyJob != null) { Log.w(TAG, "Proxy fields not null") throw IllegalStateException("Proxy fields not null") } proxy = ByeDpiProxy() val preferences = getByeDpiPreferences() proxyJob = lifecycleScope.launch(Dispatchers.IO) { val code = proxy.startProxy(preferences) delay(500) if (code != 0) { Log.e(TAG, "Proxy stopped with code $code") updateStatus(ServiceStatus.Failed) } else { updateStatus(ServiceStatus.Disconnected) } stopSelf() } Log.i(TAG, "Proxy started") } private suspend fun stopProxy() { Log.i(TAG, "Stopping proxy") if (status == ServiceStatus.Disconnected) { Log.w(TAG, "Proxy already disconnected") return } try { proxy.stopProxy() proxyJob?.cancel() val completed = withTimeoutOrNull(2000) { proxyJob?.join() true } if (completed == null) { Log.w(TAG, "proxy not finish in time, cancelling...") proxy.jniForceClose() } proxyJob = null } catch (e: Exception) { Log.e(TAG, "Failed to close proxyJob", e) } Log.i(TAG, "Proxy stopped") } private fun getByeDpiPreferences(): ByeDpiProxyPreferences = ByeDpiProxyPreferences.fromSharedPreferences(getPreferences(), this) private fun updateStatus(newStatus: ServiceStatus) { Log.d(TAG, "Proxy status changed from $status to $newStatus") status = newStatus setStatus( when (newStatus) { ServiceStatus.Connected -> AppStatus.Running ServiceStatus.Disconnected, ServiceStatus.Failed -> { proxyJob = null AppStatus.Halted } }, Mode.Proxy ) val intent = Intent( when (newStatus) { ServiceStatus.Connected -> STARTED_BROADCAST ServiceStatus.Disconnected -> STOPPED_BROADCAST ServiceStatus.Failed -> FAILED_BROADCAST } ) intent.putExtra(SENDER, Sender.Proxy.ordinal) sendBroadcast(intent) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { QuickTileService.updateTile() } } private fun createNotification(): Notification = createConnectionNotification( this, NOTIFICATION_CHANNEL_ID, R.string.notification_title, R.string.proxy_notification_content, ByeDpiProxyService::class.java, ) private fun createNotificationPause() { val notification = createPauseNotification( this, NOTIFICATION_CHANNEL_ID, R.string.notification_title, R.string.service_paused_text, ByeDpiProxyService::class.java, ) val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(PAUSE_NOTIFICATION_ID, notification) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/ByeDpiStatus.kt ================================================ package io.github.romanvht.byedpi.services import io.github.romanvht.byedpi.data.AppStatus import io.github.romanvht.byedpi.data.Mode var appStatus = AppStatus.Halted to Mode.VPN private set fun setStatus(status: AppStatus, mode: Mode) { appStatus = status to mode } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/ByeDpiVpnService.kt ================================================ package io.github.romanvht.byedpi.services import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.content.pm.ServiceInfo import android.os.Build import android.os.ParcelFileDescriptor import android.util.Log import androidx.lifecycle.lifecycleScope import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.activities.MainActivity import io.github.romanvht.byedpi.core.ByeDpiProxy import io.github.romanvht.byedpi.core.ByeDpiProxyPreferences import io.github.romanvht.byedpi.core.TProxyService import io.github.romanvht.byedpi.data.* import io.github.romanvht.byedpi.utility.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import java.io.File class ByeDpiVpnService : LifecycleVpnService() { private val byeDpiProxy = ByeDpiProxy() private var proxyJob: Job? = null private var tunFd: ParcelFileDescriptor? = null private val mutex = Mutex() companion object { private val TAG: String = ByeDpiVpnService::class.java.simpleName private const val FOREGROUND_SERVICE_ID: Int = 1 private const val PAUSE_NOTIFICATION_ID: Int = 3 private const val NOTIFICATION_CHANNEL_ID: String = "ByeDPIVpn" private var status: ServiceStatus = ServiceStatus.Disconnected } override fun onCreate() { super.onCreate() registerNotificationChannel( this, NOTIFICATION_CHANNEL_ID, R.string.vpn_channel_name, ) } override fun onDestroy() { super.onDestroy() tunFd?.close() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) startForeground() return when (val action = intent?.action) { START_ACTION -> { lifecycleScope.launch { start() } START_STICKY } STOP_ACTION -> { lifecycleScope.launch { stop() } START_NOT_STICKY } RESUME_ACTION -> { lifecycleScope.launch { if (prepare(this@ByeDpiVpnService) == null) { start() } } START_STICKY } PAUSE_ACTION -> { lifecycleScope.launch { stop() createNotificationPause() } START_NOT_STICKY } else -> { Log.w(TAG, "Unknown action: $action") START_NOT_STICKY } } } override fun onRevoke() { Log.i(TAG, "VPN revoked") lifecycleScope.launch { stop() } } private suspend fun start() { Log.i(TAG, "Starting") val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(PAUSE_NOTIFICATION_ID) if (status == ServiceStatus.Connected) { Log.w(TAG, "VPN already connected") return } try { mutex.withLock { if (status == ServiceStatus.Connected) { Log.w(TAG, "VPN already connected") return@withLock } startProxy() startTun2Socks() updateStatus(ServiceStatus.Connected) } } catch (e: Exception) { Log.e(TAG, "Failed to start VPN", e) updateStatus(ServiceStatus.Failed) stop() } } private fun startForeground() { val notification: Notification = createNotification() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startForeground( FOREGROUND_SERVICE_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE, ) } else { startForeground(FOREGROUND_SERVICE_ID, notification) } } private suspend fun stop() { Log.i(TAG, "Stopping") mutex.withLock { try { withContext(Dispatchers.IO) { stopProxy() stopTun2Socks() } } catch (e: Exception) { Log.e(TAG, "Failed to stop VPN", e) } updateStatus(ServiceStatus.Disconnected) } stopSelf() } private fun startProxy() { Log.i(TAG, "Starting proxy") if (proxyJob != null) { Log.w(TAG, "Proxy fields not null") throw IllegalStateException("Proxy fields not null") } val preferences = getByeDpiPreferences() proxyJob = lifecycleScope.launch(Dispatchers.IO) { val code = byeDpiProxy.startProxy(preferences) delay(500) if (code != 0) { Log.e(TAG, "Proxy stopped with code $code") updateStatus(ServiceStatus.Failed) } else { updateStatus(ServiceStatus.Disconnected) } stopTun2Socks() stopSelf() } Log.i(TAG, "Proxy started") } private suspend fun stopProxy() { Log.i(TAG, "Stopping proxy") if (status == ServiceStatus.Disconnected) { Log.w(TAG, "Proxy already disconnected") return } try { byeDpiProxy.stopProxy() proxyJob?.cancel() val completed = withTimeoutOrNull(2000) { proxyJob?.join() true } if (completed == null) { Log.w(TAG, "proxy not finish in time, cancelling...") byeDpiProxy.jniForceClose() } proxyJob = null } catch (e: Exception) { Log.e(TAG, "Failed to close proxyJob", e) } Log.i(TAG, "Proxy stopped") } private fun startTun2Socks() { Log.i(TAG, "Starting tun2socks") if (tunFd != null) { throw IllegalStateException("VPN field not null") } val sharedPreferences = getPreferences() val (ip, port) = sharedPreferences.getProxyIpAndPort() val dns = sharedPreferences.getStringNotNull("dns_ip", "8.8.8.8") val ipv6 = sharedPreferences.getBoolean("ipv6_enable", false) val tun2socksConfig = buildString { appendLine("tunnel:") appendLine(" mtu: 8500") appendLine("misc:") appendLine(" task-stack-size: 81920") appendLine("socks5:") appendLine(" address: $ip") appendLine(" port: $port") appendLine(" udp: udp") } val configPath = try { File.createTempFile("config", "tmp", cacheDir).apply { writeText(tun2socksConfig) } } catch (e: Exception) { Log.e(TAG, "Failed to create config file", e) throw e } val fd = createBuilder(dns, ipv6).establish() ?: throw IllegalStateException("VPN connection failed") this.tunFd = fd TProxyService.TProxyStartService(configPath.absolutePath, fd.fd) Log.i(TAG, "Tun2Socks started. ip: $ip port: $port") } private fun stopTun2Socks() { Log.i(TAG, "Stopping tun2socks") try { TProxyService.TProxyStopService() } catch (e: Exception) { Log.e(TAG, "Failed to stop TProxyService", e) } try { File(cacheDir, "config.tmp").delete() } catch (e: SecurityException) { Log.e(TAG, "Failed to delete config file", e) } try { tunFd?.close() } catch (e: Exception) { Log.e(TAG, "Failed to close tunFd", e) } finally { tunFd = null } Log.i(TAG, "Tun2socks stopped") } private fun getByeDpiPreferences(): ByeDpiProxyPreferences = ByeDpiProxyPreferences.fromSharedPreferences(getPreferences(), this) private fun updateStatus(newStatus: ServiceStatus) { Log.d(TAG, "VPN status changed from $status to $newStatus") status = newStatus setStatus( when (newStatus) { ServiceStatus.Connected -> AppStatus.Running ServiceStatus.Disconnected, ServiceStatus.Failed -> { proxyJob = null AppStatus.Halted } }, Mode.VPN ) val intent = Intent( when (newStatus) { ServiceStatus.Connected -> STARTED_BROADCAST ServiceStatus.Disconnected -> STOPPED_BROADCAST ServiceStatus.Failed -> FAILED_BROADCAST } ) intent.putExtra(SENDER, Sender.VPN.ordinal) sendBroadcast(intent) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { QuickTileService.updateTile() } } private fun createNotification(): Notification = createConnectionNotification( this, NOTIFICATION_CHANNEL_ID, R.string.notification_title, R.string.vpn_notification_content, ByeDpiVpnService::class.java, ) private fun createNotificationPause() { val notification = createPauseNotification( this, NOTIFICATION_CHANNEL_ID, R.string.notification_title, R.string.service_paused_text, ByeDpiVpnService::class.java, ) val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(PAUSE_NOTIFICATION_ID, notification) } private fun createBuilder(dns: String, ipv6: Boolean): Builder { Log.d(TAG, "DNS: $dns") val builder = Builder() builder.setSession("ByeDPI") builder.setConfigureIntent( PendingIntent.getActivity( this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE, ) ) builder.addAddress("10.10.10.10", 32) .addRoute("0.0.0.0", 0) if (ipv6) { builder.addAddress("fd00::1", 128) .addRoute("::", 0) } if (dns.isNotBlank()) { builder.addDnsServer(dns) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { builder.setMetered(false) } val preferences = getPreferences() val listType = preferences.getStringNotNull("applist_type", "disable") val listedApps = preferences.getSelectedApps() when (listType) { "blacklist" -> { for (packageName in listedApps) { try { builder.addDisallowedApplication(packageName) } catch (e: Exception) { Log.e(TAG, "Не удалось добавить приложение $packageName в черный список", e) } } builder.addDisallowedApplication(applicationContext.packageName) } "whitelist" -> { for (packageName in listedApps) { try { builder.addAllowedApplication(packageName) } catch (e: Exception) { Log.e(TAG, "Не удалось добавить приложение $packageName в белый список", e) } } } "disable" -> { builder.addDisallowedApplication(applicationContext.packageName) } } return builder } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/LifecycleVpnService.kt ================================================ package io.github.romanvht.byedpi.services import android.content.Intent import android.net.VpnService import android.os.IBinder import androidx.annotation.CallSuper import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ServiceLifecycleDispatcher /** * Based on [androidx.lifecycle.LifecycleService] */ open class LifecycleVpnService : VpnService(), LifecycleOwner { @Suppress("LeakingThis") private val dispatcher = ServiceLifecycleDispatcher(this) @CallSuper override fun onCreate() { dispatcher.onServicePreSuperOnCreate() super.onCreate() } @CallSuper override fun onBind(intent: Intent): IBinder? { dispatcher.onServicePreSuperOnBind() return super.onBind(intent) } @Deprecated("Deprecated in Java") @CallSuper override fun onStart(intent: Intent?, startId: Int) { dispatcher.onServicePreSuperOnStart() @Suppress("DEPRECATION") super.onStart(intent, startId) } // this method is added only to annotate it with @CallSuper. // In usual Service, super.onStartCommand is no-op, but in LifecycleService // it results in dispatcher.onServicePreSuperOnStart() call, because // super.onStartCommand calls onStart(). @CallSuper override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return super.onStartCommand(intent, flags, startId) } @CallSuper override fun onDestroy() { dispatcher.onServicePreSuperOnDestroy() super.onDestroy() } override val lifecycle: Lifecycle get() = dispatcher.lifecycle } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/QuickTileService.kt ================================================ package io.github.romanvht.byedpi.services import android.net.VpnService import android.os.Build import android.service.quicksettings.Tile import android.service.quicksettings.TileService import android.util.Log import androidx.annotation.RequiresApi import io.github.romanvht.byedpi.data.* import io.github.romanvht.byedpi.utility.getPreferences import io.github.romanvht.byedpi.utility.mode @RequiresApi(Build.VERSION_CODES.N) class QuickTileService : TileService() { companion object { private const val TAG = "QuickTileService" private var instance: QuickTileService? = null fun updateTile() { instance?.updateStatus() } } private var appTile: Tile? = null override fun onStartListening() { super.onStartListening() instance = this appTile = qsTile updateStatus() } override fun onStopListening() { super.onStopListening() instance = null appTile = null } override fun onClick() { super.onClick() handleClick() } private fun handleClick() { val (status) = appStatus val mode = getPreferences().mode() when (status) { AppStatus.Halted -> startService(mode) AppStatus.Running -> stopService() } Log.i(TAG, "Tile clicked") } private fun startService(mode: Mode) { if (mode == Mode.VPN && VpnService.prepare(this) != null) { return } ServiceManager.start(this, mode) setState(Tile.STATE_ACTIVE) } private fun stopService() { ServiceManager.stop(this) setState(Tile.STATE_INACTIVE) } private fun updateStatus() { val (status) = appStatus val newState = when (status) { AppStatus.Running -> Tile.STATE_ACTIVE AppStatus.Halted -> Tile.STATE_INACTIVE } setState(newState) } private fun setState(state: Int) { appTile?.apply { this.state = state updateTile() } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/services/ServiceManager.kt ================================================ package io.github.romanvht.byedpi.services import android.content.Context import android.content.Intent import android.util.Log import androidx.core.content.ContextCompat import io.github.romanvht.byedpi.data.AppStatus import io.github.romanvht.byedpi.data.Mode import io.github.romanvht.byedpi.data.START_ACTION import io.github.romanvht.byedpi.data.STOP_ACTION import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch object ServiceManager { private val TAG: String = ServiceManager::class.java.simpleName private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) fun start(context: Context, mode: Mode) { when (mode) { Mode.VPN -> { Log.i(TAG, "Starting VPN") val intent = Intent(context, ByeDpiVpnService::class.java) intent.action = START_ACTION ContextCompat.startForegroundService(context, intent) } Mode.Proxy -> { Log.i(TAG, "Starting proxy") val intent = Intent(context, ByeDpiProxyService::class.java) intent.action = START_ACTION ContextCompat.startForegroundService(context, intent) } } } fun stop(context: Context) { val (_, mode) = appStatus when (mode) { Mode.VPN -> { Log.i(TAG, "Stopping VPN") val intent = Intent(context, ByeDpiVpnService::class.java) intent.action = STOP_ACTION ContextCompat.startForegroundService(context, intent) } Mode.Proxy -> { Log.i(TAG, "Stopping proxy") val intent = Intent(context, ByeDpiProxyService::class.java) intent.action = STOP_ACTION ContextCompat.startForegroundService(context, intent) } } } fun restart(context: Context, mode: Mode) { if (appStatus.first == AppStatus.Running) { stop(context) scope.launch { val startTime = System.currentTimeMillis() while (System.currentTimeMillis() - startTime < 3000L) { if (appStatus.first == AppStatus.Halted) break delay(100) } start(context, mode) } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/ArgumentsUtils.kt ================================================ package io.github.romanvht.byedpi.utility // Based on https://gist.github.com/raymyers/8077031 fun shellSplit(string: CharSequence): List { val tokens: MutableList = ArrayList() var quoteChar = ' ' var escaping = false var quoting = false var lastCloseQuoteIndex = Int.MIN_VALUE var current = StringBuilder() for (i in string.indices) { val c = string[i] if (escaping) { current.append(c) escaping = false } else if (c == '\\' && quoting) { if (i + 1 < string.length && string[i + 1] == quoteChar) { escaping = true } else { current.append(c) } } else if (quoting && c == quoteChar) { quoting = false lastCloseQuoteIndex = i } else if (!quoting && (c == '\'' || c == '"')) { quoting = true quoteChar = c } else if (!quoting && Character.isWhitespace(c)) { if (current.isNotEmpty() || lastCloseQuoteIndex == i - 1) { tokens.add(current.toString()) current = StringBuilder() } } else { current.append(c) } } if (current.isNotEmpty() || lastCloseQuoteIndex == string.length - 1) { tokens.add(current.toString()) } return tokens } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/BatteryUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.annotation.SuppressLint import android.provider.Settings import android.content.Context import android.content.Intent import android.os.Build import android.os.PowerManager import android.util.Log import androidx.core.net.toUri object BatteryUtils { private const val TAG = "BatteryUtils" fun isOptimizationDisabled(context: Context): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager powerManager.isIgnoringBatteryOptimizations(context.packageName) } else { true } } @SuppressLint("BatteryLife") fun requestBatteryOptimization(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply { data = "package:${context.packageName}".toUri() flags = Intent.FLAG_ACTIVITY_NEW_TASK } context.startActivity(intent) } catch (e: Exception) { Log.e(TAG, "Failed to request ignore battery optimizations", e) try { val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) context.startActivity(intent) } catch (e2: Exception) { Log.e(TAG, "Failed to open battery optimization settings", e2) } } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/ClipboardUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.widget.Toast import io.github.romanvht.byedpi.R object ClipboardUtils { fun copy(context: Context, text: String, label: String = "text", showToast: Boolean = true) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager val clip = ClipData.newPlainText(label, text) clipboard?.setPrimaryClip(clip) if (showToast) { Toast.makeText(context, R.string.toast_copied, Toast.LENGTH_SHORT).show() } } fun paste(context: Context): String? { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager val clipData = clipboard?.primaryClip return if (clipData != null && clipData.itemCount > 0) { clipData.getItemAt(0).text?.toString() } else { null } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/DomainListUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import io.github.romanvht.byedpi.data.DomainList import java.io.File import androidx.core.content.edit object DomainListUtils { private const val DOMAIN_LISTS_FILE = "domain_lists.json" private const val KEY_INITIAL_LOADED = "domain_initial_loaded" private val gson = Gson() fun initializeDefaultLists(context: Context) { val prefs = context.getPreferences() val isInitialized = prefs.getBoolean(KEY_INITIAL_LOADED, false) if (isInitialized) return val defaultLists = mutableListOf() val assetFiles = context.assets.list("")?.filter { it.startsWith("proxytest_") && it.endsWith(".sites") } ?: emptyList() for (assetFile in assetFiles) { val listName = assetFile .removePrefix("proxytest_") .removeSuffix(".sites") val domains = context.assets.open(assetFile) .bufferedReader() .useLines { it.toList() } .map { it.trim() } .filter { it.isNotEmpty() } defaultLists.add( DomainList( id = listName, name = listName.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }, domains = domains, isActive = listName in setOf("youtube", "googlevideo"), isBuiltIn = true ) ) } saveLists(context, defaultLists) prefs.edit { putBoolean(KEY_INITIAL_LOADED, true) } } fun getLists(context: Context): List { val listsFile = File(context.filesDir, DOMAIN_LISTS_FILE) if (!listsFile.exists()) { return emptyList() } return try { val json = listsFile.readText() val type = object : TypeToken>() {}.type gson.fromJson(json, type) ?: emptyList() } catch (e: Exception) { emptyList() } } fun saveLists(context: Context, lists: List) { val listsFile = File(context.filesDir, DOMAIN_LISTS_FILE) val json = gson.toJson(lists) listsFile.writeText(json) } fun getActiveDomains(context: Context): List { return getLists(context) .filter { it.isActive } .flatMap { it.domains } .distinct() } fun addList(context: Context, name: String, domains: List): Boolean { val lists = getLists(context).toMutableList() val id = name.lowercase().replace(" ", "_") if (lists.any { it.id == id }) return false lists.add( DomainList( id = id, name = name, domains = domains, isActive = true, isBuiltIn = false ) ) saveLists(context, lists) return true } fun updateList(context: Context, id: String, name: String, domains: List): Boolean { val lists = getLists(context).toMutableList() val index = lists.indexOfFirst { it.id == id } if (index == -1) return false val oldList = lists[index] lists[index] = oldList.copy(name = name, domains = domains) saveLists(context, lists) return true } fun toggleListActive(context: Context, id: String): Boolean { val lists = getLists(context).toMutableList() val index = lists.indexOfFirst { it.id == id } if (index == -1) return false val list = lists[index] lists[index] = list.copy(isActive = !list.isActive) saveLists(context, lists) return true } fun deleteList(context: Context, id: String): Boolean { val lists = getLists(context).toMutableList() val iterator = lists.iterator() var removed = false while (iterator.hasNext()) { val list = iterator.next() if (list.id == id) { iterator.remove() removed = true } } if (removed) { saveLists(context, lists) } return removed } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/HistoryUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.Context import android.content.SharedPreferences import io.github.romanvht.byedpi.data.Command import com.google.gson.Gson import androidx.core.content.edit class HistoryUtils(context: Context) { private val context = context.applicationContext private val sharedPreferences: SharedPreferences = context.getPreferences() private val historyKey = "byedpi_command_history" private val maxHistorySize = 40 fun addCommand(command: String) { if (command.isBlank()) return val history = getHistory().toMutableList() val unpinned = history.filter { !it.pinned } val search = history.find { it.text == command } if (search == null) { history.add(0, Command(command)) if (history.size > maxHistorySize) { if (unpinned.isNotEmpty()) { history.remove(unpinned.last()) } } } saveHistory(history) } fun pinCommand(command: String) { val history = getHistory().toMutableList() history.find { it.text == command }?.pinned = true saveHistory(history) } fun unpinCommand(command: String) { val history = getHistory().toMutableList() history.find { it.text == command }?.pinned = false saveHistory(history) } fun deleteCommand(command: String) { val history = getHistory().toMutableList() history.removeAll { it.text == command } saveHistory(history) } fun renameCommand(command: String, newName: String) { val history = getHistory().toMutableList() history.find { it.text == command }?.name = newName saveHistory(history) } fun editCommand(command: String, newText: String) { val history = getHistory().toMutableList() history.find { it.text == command }?.text = newText saveHistory(history) } fun getHistory(): List { val historyJson = sharedPreferences.getString(historyKey, null) return if (historyJson != null) { Gson().fromJson(historyJson, Array::class.java).toList() } else { emptyList() } } fun saveHistory(history: List) { val historyJson = Gson().toJson(history) sharedPreferences.edit { putString(historyKey, historyJson) } ShortcutUtils.update(context) } fun clearAllHistory() { saveHistory(emptyList()) } fun clearUnpinnedHistory() { val history = getHistory().filter { it.pinned } saveHistory(history) } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/NotificationUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.activities.MainActivity import io.github.romanvht.byedpi.data.PAUSE_ACTION import io.github.romanvht.byedpi.data.RESUME_ACTION import io.github.romanvht.byedpi.data.STOP_ACTION fun registerNotificationChannel(context: Context, id: String, @StringRes name: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val manager = context.getSystemService(NotificationManager::class.java) ?: return val channel = NotificationChannel( id, context.getString(name), NotificationManager.IMPORTANCE_DEFAULT ) channel.enableLights(false) channel.enableVibration(false) channel.setShowBadge(false) manager.createNotificationChannel(channel) } } fun createConnectionNotification( context: Context, channelId: String, @StringRes title: Int, @StringRes content: Int, service: Class<*>, ): Notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setSilent(true) .setContentTitle(context.getString(title)) .setContentText(context.getString(content)) .addAction(0, context.getString(R.string.service_pause_btn), PendingIntent.getService( context, 0, Intent(context, service).setAction(PAUSE_ACTION), PendingIntent.FLAG_IMMUTABLE, ) ) .addAction(0, context.getString(R.string.service_stop_btn), PendingIntent.getService( context, 0, Intent(context, service).setAction(STOP_ACTION), PendingIntent.FLAG_IMMUTABLE, ) ) .setContentIntent( PendingIntent.getActivity( context, 0, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE, ) ) .build() fun createPauseNotification( context: Context, channelId: String, @StringRes title: Int, @StringRes content: Int, service: Class<*>, ): Notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setSilent(true) .setContentTitle(context.getString(title)) .setContentText(context.getString(content)) .addAction(0, context.getString(R.string.service_start_btn), PendingIntent.getService( context, 0, Intent(context, service).setAction(RESUME_ACTION), PendingIntent.FLAG_IMMUTABLE, ) ) .setContentIntent( PendingIntent.getActivity( context, 0, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE, ) ) .build() ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/PreferencesUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.Context import android.content.SharedPreferences import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import io.github.romanvht.byedpi.data.Mode val PreferenceFragmentCompat.sharedPreferences get() = preferenceScreen.sharedPreferences fun Context.getPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) fun SharedPreferences.getIntStringNotNull(key: String, defValue: Int): Int = getString(key, defValue.toString())?.toIntOrNull() ?: defValue fun SharedPreferences.getLongStringNotNull(key: String, defValue: Long): Long = getString(key, defValue.toString())?.toLongOrNull() ?: defValue fun SharedPreferences.getStringNotNull(key: String, defValue: String): String = getString(key, defValue) ?: defValue fun SharedPreferences.mode(): Mode = Mode.fromString(getStringNotNull("byedpi_mode", "vpn")) fun PreferenceFragmentCompat.findPreferenceNotNull(key: CharSequence): T = findPreference(key) ?: throw IllegalStateException("Preference $key not found") fun SharedPreferences.getSelectedApps(): List { return getStringSet("selected_apps", emptySet())?.toList() ?: emptyList() } fun SharedPreferences.checkIpAndPortInCmd(): Pair { val cmdEnable = getBoolean("byedpi_enable_cmd_settings", false) if (!cmdEnable) return Pair(null, null) val cmdArgs = getString("byedpi_cmd_args", "")?.let { shellSplit(it) } ?: emptyList() fun getArgValue(argsList: List, keys: List): String? { for (i in argsList.indices) { val arg = argsList[i] for (key in keys) { if (key.startsWith("--")) { if (arg == key && i + 1 < argsList.size) { return argsList[i + 1] } else if (arg.startsWith("$key=")) { return arg.substringAfter('=') } } else if (key.startsWith("-")) { if (arg.startsWith(key) && arg.length > key.length) { return arg.substring(key.length) } else if (arg == key && i + 1 < argsList.size) { return argsList[i + 1] } } } } return null } val cmdIp = getArgValue(cmdArgs, listOf("--ip", "-i")) val cmdPort = getArgValue(cmdArgs, listOf("--port", "-p")) return Pair(cmdIp, cmdPort) } fun SharedPreferences.getProxyIpAndPort(): Pair { val (cmdIp, cmdPort) = checkIpAndPortInCmd() val ip = cmdIp ?: getStringNotNull("byedpi_proxy_ip", "127.0.0.1") val port = cmdPort ?: getStringNotNull("byedpi_proxy_port", "1080") return Pair(ip, port) } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/SettingsUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.Context import android.net.Uri import android.os.Handler import android.os.Looper import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.edit import androidx.core.os.LocaleListCompat import com.google.gson.Gson import io.github.romanvht.byedpi.BuildConfig import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.data.AppSettings object SettingsUtils { private const val TAG = "SettingsUtils" fun setLang(lang: String) { val appLocale = localeByName(lang) ?: LocaleListCompat.getEmptyLocaleList() if (AppCompatDelegate.getApplicationLocales().toLanguageTags() != appLocale.toLanguageTags()) { AppCompatDelegate.setApplicationLocales(appLocale) } } private fun localeByName(lang: String): LocaleListCompat? = when (lang) { "system" -> LocaleListCompat.getEmptyLocaleList() "ru" -> LocaleListCompat.forLanguageTags("ru") "en" -> LocaleListCompat.forLanguageTags("en") "tr" -> LocaleListCompat.forLanguageTags("tr") "kk" -> LocaleListCompat.forLanguageTags("kk") "vi" -> LocaleListCompat.forLanguageTags("vi") else -> { Log.w(TAG, "Invalid value for language: $lang") null } } fun setTheme(name: String) { val appTheme = themeByName(name) ?: AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM if (AppCompatDelegate.getDefaultNightMode() != appTheme) { AppCompatDelegate.setDefaultNightMode(appTheme) } } private fun themeByName(name: String): Int? = when (name) { "system" -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM "light" -> AppCompatDelegate.MODE_NIGHT_NO "dark" -> AppCompatDelegate.MODE_NIGHT_YES else -> { Log.w(TAG, "Invalid value for app_theme: $name") null } } fun exportSettings(context: Context, uri: Uri) { try { val prefs = context.getPreferences() val history = HistoryUtils(context).getHistory() val apps = prefs.getSelectedApps() val settings = prefs.all.filterKeys { key -> key !in setOf("byedpi_command_history", "selected_apps") } val domainLists = DomainListUtils.getLists(context) val export = AppSettings( app = BuildConfig.APPLICATION_ID, version = BuildConfig.VERSION_NAME, history = history, apps = apps, domainLists = domainLists, settings = settings ) val json = Gson().toJson(export) context.contentResolver.openOutputStream(uri)?.use { outputStream -> outputStream.write(json.toByteArray()) } } catch (e: Exception) { Log.e(TAG, "Failed to export settings", e) Handler(Looper.getMainLooper()).post { Toast.makeText(context, "Failed to export settings", Toast.LENGTH_SHORT).show() } } } fun importSettings(context: Context, uri: Uri, onRestart: () -> Unit) { try { context.contentResolver.openInputStream(uri)?.use { inputStream -> val json = inputStream.bufferedReader().readText() val import = try { Gson().fromJson(json, AppSettings::class.java) } catch (e: Exception) { null } if (import == null || import.app != BuildConfig.APPLICATION_ID) { Handler(Looper.getMainLooper()).post { Toast.makeText(context, R.string.logs_failed, Toast.LENGTH_LONG).show() } return@use } val prefs = context.getPreferences() prefs.edit (commit = true) { clear() import.settings.forEach { (key, value) -> when (value) { is Int -> putInt(key, value) is Boolean -> putBoolean(key, value) is String -> putString(key, value) is Float -> putFloat(key, value) is Long -> putLong(key, value) is Double -> { when (value) { value.toInt().toDouble() -> { putInt(key, value.toInt()) } value.toLong().toDouble() -> { putLong(key, value.toLong()) } else -> { putFloat(key, value.toFloat()) } } } is Collection<*> -> { if (value.all { it is String }) { @Suppress("UNCHECKED_CAST") putStringSet(key, (value as Collection).toSet()) } } } } } if (import.apps !== null) { prefs.edit (commit = true) { putStringSet("selected_apps", import.apps.toSet()) } } if (import.history !== null) { HistoryUtils(context).saveHistory(import.history) } if (import.domainLists !== null) { DomainListUtils.saveLists(context, import.domainLists) } Handler(Looper.getMainLooper()).post { val newLang = prefs.getString("language", "system") ?: "system" val newTheme = prefs.getString("app_theme", "system") ?: "system" setLang(newLang) setTheme(newTheme) onRestart() } } } catch (e: Exception) { Log.e(TAG, "Failed to import settings", e) Handler(Looper.getMainLooper()).post { Toast.makeText(context, "Failed to import settings", Toast.LENGTH_SHORT).show() } } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/ShortcutUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.content.Context import android.content.Intent import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.drawable.Icon import android.os.Build import io.github.romanvht.byedpi.R import io.github.romanvht.byedpi.activities.ToggleActivity object ShortcutUtils { fun update(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { val shortcutManager = context.getSystemService(ShortcutManager::class.java) val shortcuts = mutableListOf() val toggleIntent = Intent(context, ToggleActivity::class.java).apply { action = Intent.ACTION_VIEW flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val toggleShortcut = ShortcutInfo.Builder(context, "toggle_service") .setShortLabel(context.getString(R.string.toggle_connect)) .setLongLabel(context.getString(R.string.toggle_connect)) .setIcon(Icon.createWithResource(context, R.drawable.ic_toggle)) .setIntent(toggleIntent) .build() shortcuts.add(toggleShortcut) if (context.getPreferences().getBoolean("byedpi_enable_cmd_settings", false)) { val history = HistoryUtils(context) val pinned = history.getHistory().filter { it.pinned }.take(3) pinned.forEachIndexed { index, strategy -> val strategyIntent = Intent(context, ToggleActivity::class.java).apply { action = Intent.ACTION_VIEW flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK putExtra("strategy", strategy.text) } val fullLabel = strategy.name?.takeIf { it.isNotBlank() } ?: strategy.text val shortLabel = if (fullLabel.length > 15) fullLabel.take(15) + "..." else fullLabel val longLabel = if (fullLabel.length > 30) fullLabel.take(30) + "..." else fullLabel val commandShortcut = ShortcutInfo.Builder(context, "strategy_$index") .setShortLabel(shortLabel) .setLongLabel(longLabel) .setIcon(Icon.createWithResource(context, R.drawable.ic_pin)) .setIntent(strategyIntent) .build() shortcuts.add(commandShortcut) } } shortcutManager.dynamicShortcuts = shortcuts } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/SiteCheckUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import java.io.IOException import java.net.HttpURLConnection import java.net.InetSocketAddress import java.net.Proxy import java.net.URL class SiteCheckUtils( private val proxyIp: String, private val proxyPort: Int ) { suspend fun checkSitesAsync( sites: List, requestsCount: Int, requestTimeout: Long, concurrentRequests: Int = 20, fullLog: Boolean, onSiteChecked: ((String, Int, Int) -> Unit)? = null ): List> { val semaphore = Semaphore(concurrentRequests) return withContext(Dispatchers.IO) { sites.map { site -> async { semaphore.withPermit { val successCount = checkSiteAccess(site, requestsCount, requestTimeout) if (fullLog) { onSiteChecked?.invoke(site, successCount, requestsCount) } site to successCount } } }.awaitAll() } } private suspend fun checkSiteAccess( site: String, requestsCount: Int, timeout: Long ): Int = withContext(Dispatchers.IO) { var responseCount = 0 val formattedUrl = if (site.startsWith("http://") || site.startsWith("https://")) site else "https://$site" val url = try { URL(formattedUrl) } catch (_: Exception) { Log.e("SiteChecker", "Invalid URL: $formattedUrl") return@withContext 0 } val proxy = Proxy(Proxy.Type.SOCKS, InetSocketAddress(proxyIp, proxyPort)) repeat(requestsCount) { attempt -> Log.i("SiteChecker", "Attempt ${attempt + 1}/$requestsCount for $site") var connection: HttpURLConnection? = null try { connection = url.openConnection(proxy) as HttpURLConnection connection.connectTimeout = (timeout * 1000).toInt() connection.readTimeout = (timeout * 1000).toInt() connection.instanceFollowRedirects = true connection.setRequestProperty("Connection", "close") val responseCode = connection.responseCode val declaredLength = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { connection.contentLengthLong } else { connection.contentLength.toLong() } var actualLength = 0L try { val inputStream = if (responseCode in 200..299) connection.inputStream else connection.errorStream if (inputStream != null) { val buffer = ByteArray(8192) var bytesRead: Int val limit = if (declaredLength > 0) declaredLength else 1024L * 1024 while (actualLength < limit) { val remaining = limit - actualLength val toRead = if (remaining > buffer.size) buffer.size else remaining.toInt() bytesRead = inputStream.read(buffer, 0, toRead) if (bytesRead == -1) break actualLength += bytesRead } } } catch (_: IOException) { // Stream reading failed } if (declaredLength <= 0L || actualLength >= declaredLength) { Log.i("SiteChecker", "Response for $site: $responseCode, Declared: $declaredLength, Actual: $actualLength") responseCount++ } else { Log.w("SiteChecker", "Block detected for $site, Declared: $declaredLength, Actual: $actualLength") } } catch (e: Exception) { Log.e("SiteChecker", "Error accessing $site: ${e.message}") } finally { connection?.disconnect() } } responseCount } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/StorageUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Environment import android.provider.Settings import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.fragment.app.Fragment object StorageUtils { private const val TAG = "StorageUtils" private const val STORAGE_PERMISSION_REQUEST = 1001 fun hasStoragePermission(context: Context): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Environment.isExternalStorageManager() } else { val readPermission = ContextCompat.checkSelfPermission( context, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED val writePermission = ContextCompat.checkSelfPermission( context, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED readPermission && writePermission } } fun requestStoragePermission(fragment: Fragment) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { try { val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { data = "package:${fragment.requireContext().packageName}".toUri() } fragment.startActivity(intent) } catch (e: Exception) { Log.e(TAG, "Failed to request storage permission", e) try { val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) fragment.startActivity(intent) } catch (e2: Exception) { Log.e(TAG, "Failed to open storage settings", e2) } } } else { Log.d(TAG, "Requesting storage permission for Android 10 and below") ActivityCompat.requestPermissions( fragment.requireActivity(), arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ), STORAGE_PERMISSION_REQUEST ) } } } ================================================ FILE: app/src/main/java/io/github/romanvht/byedpi/utility/ValidateUtils.kt ================================================ package io.github.romanvht.byedpi.utility import android.net.InetAddresses import android.os.Build import android.util.Log import android.widget.Toast import androidx.preference.EditTextPreference import androidx.preference.PreferenceFragmentCompat private const val TAG = "ValidateUtils" fun checkIp(ip: String): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { InetAddresses.isNumericAddress(ip) } else { // This pattern doesn't not support IPv6 // @Suppress("DEPRECATION") // Patterns.IP_ADDRESS.matcher(ip).matches() true } } fun checkNotLocalIp(ip: String): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { InetAddresses.isNumericAddress(ip) && InetAddresses.parseNumericAddress(ip).let { !it.isAnyLocalAddress && !it.isLoopbackAddress } } else { // This pattern doesn't not support IPv6 // @Suppress("DEPRECATION") // Patterns.IP_ADDRESS.matcher(ip).matches() true } } fun checkDomain(domain: String): Boolean { if (domain.isEmpty()) return false if (domain.length > 253) return false if (domain.startsWith(".") || domain.endsWith(".")) return false if (!domain.contains(".")) return false return true } fun PreferenceFragmentCompat.setEditTestPreferenceListenerDomain(key: String) { setEditTextPreferenceListener(key) { value -> value.isNotEmpty() && checkDomain(value) } } fun PreferenceFragmentCompat.setEditTestPreferenceListenerPort(key: String) { setEditTestPreferenceListenerInt(key, 1, 65535) } fun PreferenceFragmentCompat.setEditTestPreferenceListenerInt( key: String, min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE ) { setEditTextPreferenceListener(key) { value -> value.toIntOrNull()?.let { it in min..max } ?: false } } fun PreferenceFragmentCompat.setEditTextPreferenceListener( key: String, check: (String) -> Boolean ) { findPreferenceNotNull(key) .setOnPreferenceChangeListener { preference, newValue -> when (newValue) { is String -> { val valid = check(newValue) if (!valid) { Toast.makeText( requireContext(), "Invalid value for ${preference.title}: $newValue", Toast.LENGTH_SHORT ).show() } valid } else -> { Log.w( TAG, "Invalid type for ${preference.key}: " + "$newValue has type ${newValue::class.java}" ) false } } } } ================================================ FILE: app/src/main/jni/Android.mk ================================================ # Copyright (C) 2023 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include $(call all-subdir-makefiles) ================================================ FILE: app/src/main/jni/Application.mk ================================================ # Copyright (C) 2023 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # APP_OPTIM := release APP_PLATFORM := android-21 APP_ABI := armeabi-v7a arm64-v8a x86 x86_64 APP_CFLAGS := -O3 -DPKGNAME=io/github/romanvht/byedpi/core APP_CPPFLAGS := -O3 -std=c++11 NDK_TOOLCHAIN_VERSION := clang ================================================ FILE: app/src/main/res/drawable/baseline_settings_24.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_apps.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_arrow_down.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_autorenew.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_battery.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_check.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_code.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_computer.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_description.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_dns.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_documentation.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_filter_list.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_folder.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_github.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_http.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_info.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_language.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_monochrome.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_network.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_notification.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_palette.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_pin.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_pinned.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_port.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_power.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_speed.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_telegram.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_terminal.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_toggle.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_tune.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_vpn_key.xml ================================================ ================================================ FILE: app/src/main/res/drawable/material_alert.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_proxy_test.xml ================================================