Repository: 4o3F/Ascent Branch: v2 Commit: 5aa4a12d7a4a Files: 64 Total size: 200.7 KB Directory structure: gitextract_v3z9eq9s/ ├── .github/ │ ├── release.yaml │ └── workflows/ │ └── github-releases-to-discord.yml ├── .gitignore ├── .metadata ├── LICENSE ├── README.md ├── analysis_options.yaml ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ ├── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin/ │ │ │ │ └── cafe/ │ │ │ │ └── f403/ │ │ │ │ └── ascent/ │ │ │ │ └── MainActivity.kt │ │ │ └── res/ │ │ │ ├── drawable/ │ │ │ │ └── launch_background.xml │ │ │ ├── drawable-v21/ │ │ │ │ └── launch_background.xml │ │ │ ├── values/ │ │ │ │ └── styles.xml │ │ │ └── values-night/ │ │ │ └── styles.xml │ │ └── profile/ │ │ └── AndroidManifest.xml │ ├── ascent_android.iml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ └── settings.gradle ├── ascent.iml ├── assets/ │ └── translations/ │ ├── en-US.json │ ├── en.json │ ├── ru-RU.json │ ├── ru.json │ ├── zh-CN.json │ └── zh.json ├── flutter_rust_bridge.yaml ├── integration_test/ │ └── simple_test.dart ├── lib/ │ ├── components/ │ │ └── bottom_navigation_bar/ │ │ └── view.dart │ ├── foreground/ │ │ ├── connect.dart │ │ ├── pair.dart │ │ ├── root_connect.dart │ │ └── shizuku_connect.dart │ ├── global_state.dart │ ├── main.dart │ ├── native/ │ │ ├── api/ │ │ │ └── api.dart │ │ ├── frb_generated.dart │ │ ├── frb_generated.io.dart │ │ └── frb_generated.web.dart │ ├── pages/ │ │ ├── connect/ │ │ │ ├── logic.dart │ │ │ └── view.dart │ │ ├── home/ │ │ │ ├── logic.dart │ │ │ └── view.dart │ │ ├── info/ │ │ │ ├── logic.dart │ │ │ └── view.dart │ │ └── pair/ │ │ ├── logic.dart │ │ └── view.dart │ └── routes.dart ├── pubspec.yaml ├── rust/ │ ├── .cargo/ │ │ └── config.toml │ ├── .gitignore │ ├── Cargo.toml │ └── src/ │ ├── api/ │ │ ├── api.rs │ │ └── mod.rs │ ├── connect.rs │ ├── frb_generated.io.rs │ ├── frb_generated.rs │ ├── frb_generated.web.rs │ ├── lib.rs │ └── pair.rs └── test_driver/ └── integration_test.dart ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/release.yaml ================================================ changelog: exclude: labels: - ignore-for-release categories: - title: '🔥 Breaking Changes' labels: - 'breaking' - title: '🏕 Features' labels: - 'feat' - title: '🐛 Bug Fixes' labels: - 'fix' - title: '📄 Docs' labels: - 'docs' - title: '📦 Dependencies & Build' labels: - 'chore' - title: 'Other Changes' labels: - "*" ================================================ FILE: .github/workflows/github-releases-to-discord.yml ================================================ name: Push release to Discord on: release: types: [ published,edited ] jobs: github-releases-to-discord: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Github Releases To Discord uses: SethCohen/github-releases-to-discord@v1.13.1 with: webhook_url: ${{ secrets.WEBHOOK_URL }} username: "Ascent Release" footer_title: "Changelog" footer_timestamp: true ================================================ FILE: .gitignore ================================================ .flutter-plugins .flutter-plugins-dependencies .idea/ build/ .dart_tool/ rust_builder logs android/key.properties ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "db7ef5bf9f59442b0e200a90587e8fa5e0c6336a" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: android create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: ios create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: linux create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: macos create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: web create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a - platform: windows create_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a base_revision: db7ef5bf9f59442b0e200a90587e8fa5e0c6336a # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj' ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see . ================================================ FILE: README.md ================================================ # Ascent ![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/4o3F/Ascent/total) ![Discord](https://img.shields.io/discord/1180781478951530537?color=5865F2&label=403F%E2%80%99s%20Cafe&logo=discord&logoColor=white") A tool for retrieving wish link from Mihoyo games on Android with single device, no Root or PC required. **Please give me a star if you like this tool** Thanks to @Mirai0009 for the excellent [guide](https://gist.github.com/Mirai0009/8615e52e09083de9c0ea2dc00dc62ea8). Thanks Dark_St4lker for Russian translation. If you still have problems, please raise a issue or join our [Discord](https://discord.com/invite/6v6HEUaRWk) for support. Supported: + Xiaomi + Honor + Samsung + Vivo/iQOO (Only Android 14, other versions need interaction with customer service) + ....mostly all brands Not supported: + ~~Vivo/iQOO~~ + ~~Samsung~~(Fixed by V2) + Huawei/Honor(No wireless debug available, requires PC to enable) Ascent mainly simulates the ADB wireless debug pairing and connect protocol, thus filtering out the wish history URL from the WebView log of Unity. For tech details, please refer to [my blog post](https://403f.cafe/p/adb-tls-protocol/). ## Build 1. Make sure you have Flutter and Rust installed 2. Simply run `flutter build apk`, it should auto configure everything [![Stargazers over time](https://starchart.cc/4o3F/Ascent.svg?variant=adaptive)](https://starchart.cc/4o3F/Ascent) ================================================ FILE: analysis_options.yaml ================================================ # This file configures the analyzer, which statically analyzes Dart code to # check for errors, warnings, and lints. # # The issues identified by the analyzer are surfaced in the UI of Dart-enabled # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be # invoked from the command line by running `flutter analyze`. # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` # included above or to enable additional rules. A list of all available lints # and their documentation is published at https://dart.dev/lints. # # Instead of disabling a lint rule for the entire project in the # section below, it can also be suppressed for a single line of code # or a specific dart file by using the `// ignore: name_of_lint` and # `// ignore_for_file: name_of_lint` syntax on the line or in the file # producing the lint. rules: # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # Additional information about this file can be found at # https://dart.dev/guides/language/analysis-options ================================================ FILE: android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties **/*.keystore **/*.jks ================================================ FILE: android/app/build.gradle ================================================ import com.android.build.OutputFile plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin" } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } android { namespace "cafe.f403.ascent" compileSdkVersion localProperties.getProperty('flutter.compileSdkVersion').toInteger() ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "cafe.f403.ascent" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. // signingConfig signingConfigs.release applicationVariants.all { variant -> variant.outputs.all { output -> if (variant.buildType.name.equals('release')) { output.outputFileName = "ascent_${flutterVersionName}${getFilter(OutputFile.ABI) ? "_${getFilter(OutputFile.ABI)}" : ""}.apk" } else if (variant.buildType.name.equals('debug')) { outputFileName = "ascent_${flutterVersionName}${getFilter(OutputFile.ABI) ? "_${getFilter(OutputFile.ABI)}" : ""}_debug.apk" } } } } } splits { abi { enable true reset() include "armeabi-v7a", "arm64-v8a", "x86_64" universalApk true } } } flutter { source '../..' } dependencies {} ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/kotlin/cafe/f403/ascent/MainActivity.kt ================================================ package cafe.f403.ascent import androidx.annotation.NonNull import android.provider.Settings import android.content.Context import android.os.Build import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "cafe.f403.ascent/main" override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getDeveloperOptionEnabled") { result.success(isDevMode(this)) } else { result.notImplemented() } } } fun isDevMode(context: Context): Boolean { return when { Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN -> { Settings.Secure.getInt( context.contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0 ) != 0 } Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN -> { @Suppress("DEPRECATION") Settings.Secure.getInt( context.contentResolver, Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, 0 ) != 0 } else -> false } } } ================================================ FILE: android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: android/ascent_android.iml ================================================ ================================================ FILE: android/build.gradle ================================================ buildscript { ext.kotlin_version = '2.1.0' repositories { google() mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } subprojects { afterEvaluate { project -> if (project.hasProperty('android')) { project.android { if (namespace == null) { namespace project.group } compileSdkVersion 36 } } } } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir } tasks.withType(JavaCompile) { options.encoding = "UTF-8" } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip ================================================ FILE: android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true ================================================ FILE: android/settings.gradle ================================================ pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath } settings.ext.flutterSdkPath = flutterSdkPath() includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") repositories { google() mavenCentral() gradlePluginPortal() } plugins { id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false } } plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "8.9.1" apply false } include ":app" ================================================ FILE: ascent.iml ================================================ ================================================ FILE: assets/translations/en-US.json ================================================ { "title": "Ascent", "navigation": { "home": "Home", "pair": "Pair", "connect": "Connect", "info": "Info" }, "home": { "star": "If you like Ascent, Star it ;D", "support": "Get Support", "developer_option": { "status": "Developer Option Status: ", "enabled": "Enabled", "disabled": "Disabled" }, "root": { "name": "Get Link", "enabled": "Root Enabled!", "direct_connect": "You can directly tap connect" }, "shizuku": { "name": "Get Link", "enabled": "Shizuku Enabled!", "direct_connect": "You can directly tap connect" }, "pairing": { "name": "Pair", "status": "ADB Pair Status: ", "paired": "Paired", "wait_pairing": "Wait Pairing" }, "connect": { "name": "Connect", "status": "ADB Connect Status: ", "connected": "Connected", "wait_connect": "Wait Connecting" } }, "pair": { "guide": { "prepare_guide": "Please follow the guide in notification for following ADB pairing process", "pair": "Start Pairing", "reset": "Reset Pair Cert" }, "notification_title": "Ascent Pairing", "notification_description": { "guide_port": "Open wireless debugging and click 'Pair device with pairing code'\nEnter the pairing port by clicking the following button", "guide_code": "Please enter the pairing code (6 bit) below the button", "error_init": "Foreground service start failed, please contact developer", "pair_port": "Port: ", "pair_code": "Code: ", "pair_success": "Pairing success, please return to Ascent", "pair_fail": "Pair failed, please check pair code\n" }, "notification_reply_button": "Enter data here" }, "connect": { "guide": { "prepare_guide": "Open game after connect\nYou'll be notified on success", "connect": "Connect!", "in_progress": "Waiting...", "reset": "Reset Process", "root_connect": "Root Connect!", "shizuku_connect": "Shizuku Connect!" }, "notification_title": "Ascent Connect", "notification_description": { "connecting": "Port undetected, enter 5 digit port number behind IP address", "waiting": "Please open game, waiting for link", "success": "Success, please return to Ascent", "fail": "Failed, please check port\n", "repair": "Cert invalid, please redo pairing" }, "notification_reply_button": "Enter data here", "link_action": { "title": "Wish history link", "copy_button": "Copy", "copied": "Copied" } }, "root_connect": { "notification_title": "Ascent Root Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "update": { "title": "New version ", "ok": "Update", "cancel": "Not now" }, "error": { "title": "Please contact support", "copy": "Copy", "copied": "Copied" }, "settings": { "disable_auto_detect_port": "Disable auto detect port" } } ================================================ FILE: assets/translations/en.json ================================================ { "title": "Ascent", "navigation": { "home": "Home", "pair": "Pair", "connect": "Connect", "info": "Info" }, "home": { "star": "If you like Ascent, Star it ;D", "support": "Get Support", "developer_option": { "status": "Developer Option Status: ", "enabled": "Enabled", "disabled": "Disabled" }, "root": { "name": "Get Link", "enabled": "Root Enabled!", "direct_connect": "You can directly tap connect" }, "shizuku": { "name": "Get Link", "enabled": "Shizuku Enabled!", "direct_connect": "You can directly tap connect" }, "pairing": { "name": "Pair", "status": "ADB Pair Status: ", "paired": "Paired", "wait_pairing": "Wait Pairing" }, "connect": { "name": "Connect", "status": "ADB Connect Status: ", "connected": "Connected", "wait_connect": "Wait Connecting" } }, "pair": { "guide": { "prepare_guide": "Please follow the guide in notification for following ADB pairing process", "pair": "Start Pairing", "reset": "Reset Pair Cert" }, "notification_title": "Ascent Pairing", "notification_description": { "guide_port": "Open wireless debugging and click 'Pair device with pairing code'\nEnter the pairing port by clicking the following button", "guide_code": "Please enter the pairing code (6 bit) below the button", "error_init": "Foreground service start failed, please contact developer", "pair_port": "Port: ", "pair_code": "Code: ", "pair_success": "Pairing success, please return to Ascent", "pair_fail": "Pair failed, please check pair code\n" }, "notification_reply_button": "Enter data here" }, "connect": { "guide": { "prepare_guide": "Open game after connect\nYou'll be notified on success", "connect": "Connect!", "in_progress": "Waiting...", "reset": "Reset Process", "root_connect": "Root Connect!", "shizuku_connect": "Shizuku Connect!" }, "notification_title": "Ascent Connect", "notification_description": { "connecting": "Port undetected, enter 5 digit port number behind IP address", "waiting": "Please open game, waiting for link", "success": "Success, please return to Ascent", "fail": "Failed, please check port\n", "repair": "Cert invalid, please redo pairing" }, "notification_reply_button": "Enter data here", "link_action": { "title": "Wish history link", "copy_button": "Copy", "copied": "Copied" } }, "root_connect": { "notification_title": "Ascent Root Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "update": { "title": "New version ", "ok": "Update", "cancel": "Not now" }, "error": { "title": "Please contact support", "copy": "Copy", "copied": "Copied" }, "settings": { "disable_auto_detect_port": "Disable auto detect port" } } ================================================ FILE: assets/translations/ru-RU.json ================================================ { "title": "Ascent", "navigation": { "home": "Главная", "pair": "Соедините", "connect": "Подключение", "info": "Информация" }, "home": { "star": "Если вам нравится Ascent, поставьте ему звездочку ;D", "support": "Возникли вопросы", "developer_option": { "status": "Статус опции разработчика: ", "enabled": "Вкл", "disabled": "Выкл" }, "root": { "name": "Получить ссылку", "enabled": "Root-доступ вкл!", "direct_connect": "Вы можете напрямую нажать «Подключиться»" }, "shizuku": { "name": "Get Link", "enabled": "Shizuku Enabled!", "direct_connect": "You can directly tap connect" }, "pairing": { "name": "Соедините", "status": "Статус подключение ADB: ", "paired": "Подключен", "wait_pairing": "Подождите подключение" }, "connect": { "name": "Подключение", "status": "Статус подключения ADB: ", "connected": "Подключен", "wait_connect": "Подождите, идет подключение" } }, "pair": { "guide": { "prepare_guide": "Пожалуйста, следуйте инструкциям в уведомлении для последующего процесса сопряжения с ADB.", "pair": "Начать подключение", "reset": "Сброс соединение сертификатов" }, "notification_title": "Ascent Подключается", "notification_description": { "guide_port": "Откройте отладку по беспроводной сети и нажмите «Связать устройство с кодом сопряжения».\n Введите порт сопряжения, нажав следующую кнопку.", "guide_code": "Введите код сопряжения (6 цифр) под кнопкой.", "error_init": "Не удалось запустить службу, обратитесь к разработчику", "pair_port": "Порт: ", "pair_code": "Код: ", "pair_success": "Сопряжение прошло успешно, пожалуйста, вернитесь к Ascent", "pair_fail": "Соединение не удалась, проверьте код соединение\n" }, "notification_reply_button": "Введите данные здесь" }, "connect": { "guide": { "prepare_guide": "Откройте игру после подключения\nВы будете уведомлены об успешный подключение", "connect": "Соединять!", "in_progress": "Ожидание...", "reset": "Начать заново", "root_connect": "Подключитесь как root!", "shizuku_connect": "Shizuku Connect!" }, "notification_title": "Ascent Подключение", "notification_description": { "connecting": "Порт не обнаружен, введите 5-значный номер порта за IP-адресом", "waiting": "Пожалуйста, откройте игру, ждите ссылку", "success": "Успешно, пожалуйста, вернитесь в программу Ascent", "fail": "Ошибка, проверьте порт\n", "repair": "Сертификат недействителен, пожалуйста, повторите подключение" }, "notification_reply_button": "Введите данные здесь", "link_action": { "title": "Ссылка на историю пожеланий", "copy_button": "Копировать", "copied": "Скопировано" } }, "root_connect": { "notification_title": "Ascent Root Connect", "notification_description": { "waiting": "Ожидание ссылки", "success": "Успешно, пожалуйста, вернитесь в программу Ascent" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "update": { "title": "Новая версия", "ok": "Обновить", "cancel": "Не сейчас" }, "error": { "title": "Пожалуйста, свяжитесь со службой поддержки.", "copy": "Копировать", "copied": "Скопировано" }, "settings": { "disable_auto_detect_port": "Отключить автоматическое определение порта" } } ================================================ FILE: assets/translations/ru.json ================================================ { "title": "Ascent", "navigation": { "home": "Главная", "pair": "Соедините", "connect": "Подключение", "info": "Информация" }, "home": { "star": "Если вам нравится Ascent, поставьте ему звездочку ;D", "support": "Возникли вопросы", "developer_option": { "status": "Статус опции разработчика: ", "enabled": "Вкл", "disabled": "Выкл" }, "root": { "name": "Получить ссылку", "enabled": "Root-доступ вкл!", "direct_connect": "Вы можете напрямую нажать «Подключиться»" }, "shizuku": { "name": "Get Link", "enabled": "Shizuku Enabled!", "direct_connect": "You can directly tap connect" }, "pairing": { "name": "Соедините", "status": "Статус подключение ADB: ", "paired": "Подключен", "wait_pairing": "Подождите подключение" }, "connect": { "name": "Подключение", "status": "Статус подключения ADB: ", "connected": "Подключен", "wait_connect": "Подождите, идет подключение" } }, "pair": { "guide": { "prepare_guide": "Пожалуйста, следуйте инструкциям в уведомлении для последующего процесса сопряжения с ADB.", "pair": "Начать подключение", "reset": "Сброс соединение сертификатов" }, "notification_title": "Ascent Подключается", "notification_description": { "guide_port": "Откройте отладку по беспроводной сети и нажмите «Связать устройство с кодом сопряжения».\n Введите порт сопряжения, нажав следующую кнопку.", "guide_code": "Введите код сопряжения (6 цифр) под кнопкой.", "error_init": "Не удалось запустить службу, обратитесь к разработчику", "pair_port": "Порт: ", "pair_code": "Код: ", "pair_success": "Сопряжение прошло успешно, пожалуйста, вернитесь к Ascent", "pair_fail": "Соединение не удалась, проверьте код соединение\n" }, "notification_reply_button": "Введите данные здесь" }, "connect": { "guide": { "prepare_guide": "Откройте игру после подключения\nВы будете уведомлены об успешный подключение", "connect": "Соединять!", "in_progress": "Ожидание...", "reset": "Начать заново", "root_connect": "Подключитесь как root!", "shizuku_connect": "Shizuku Connect!" }, "notification_title": "Ascent Подключение", "notification_description": { "connecting": "Порт не обнаружен, введите 5-значный номер порта за IP-адресом", "waiting": "Пожалуйста, откройте игру, ждите ссылку", "success": "Успешно, пожалуйста, вернитесь в программу Ascent", "fail": "Ошибка, проверьте порт\n", "repair": "Сертификат недействителен, пожалуйста, повторите подключение" }, "notification_reply_button": "Введите данные здесь", "link_action": { "title": "Ссылка на историю пожеланий", "copy_button": "Копировать", "copied": "Скопировано" } }, "root_connect": { "notification_title": "Ascent Root Connect", "notification_description": { "waiting": "Ожидание ссылки", "success": "Успешно, пожалуйста, вернитесь в программу Ascent" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku Connect", "notification_description": { "waiting": "Waiting for link", "success": "Success, please return to Ascent" } }, "update": { "title": "Новая версия", "ok": "Обновить", "cancel": "Не сейчас" }, "error": { "title": "Пожалуйста, свяжитесь со службой поддержки.", "copy": "Копировать", "copied": "Скопировано" }, "settings": { "disable_auto_detect_port": "Отключить автоматическое определение порта" } } ================================================ FILE: assets/translations/zh-CN.json ================================================ { "title": "Ascent", "navigation": { "home": "主页", "pair": "配对", "connect": "连接", "info": "关于" }, "home": { "star": "如果你喜欢Ascent 请给个Star吧 ;D", "support": "技术支持", "developer_option": { "status": "开发者选项状态: ", "enabled": "已启用", "disabled": "未启用" }, "root": { "name": "获取链接", "enabled": "Root已开启!", "direct_connect": "你可以直接点击连接" }, "shizuku": { "name": "获取链接", "enabled": "Shizuku已开启!", "direct_connect": "你可以直接点击连接" }, "pairing": { "name": "配对", "status": "无线调试配对状态: ", "paired": "已配对", "wait_pairing": "未配对" }, "connect": { "name": "连接", "status": "无线调试连接状态: ", "connected": "已连接", "wait_connect": "等待连接" } }, "pair": { "guide": { "prepare_guide": "接下来的无线调试配对过程请跟随通知栏中的提示进行", "pair": "开始配对", "reset": "重置配对状态" }, "notification_title": "Ascent配对", "notification_description": { "guide_port": "打开无线调试并点击使用配对码配对设备\n通过下面的按钮输入无线调试配对端口", "guide_code": "请通过下面的按钮输入无线调试配对码", "error_init": "前台服务启动失败,请联系开发者", "pair_port": "端口: ", "pair_code": "配对码: ", "pair_success": "配对成功,请返回Ascent主程序", "pair_fail": "配对失败,请确认配对码" }, "notification_reply_button": "点此输入数据" }, "connect": { "guide": { "prepare_guide": "连接后请直接打开游戏\n成功获得链接后将在通知中提示", "connect": "开始连接!", "in_progress": "请打开游戏,等待中...", "reset": "重置状态", "root_connect": "开始Root连接!", "shizuku_connect": "开始Shizuku连接!" }, "notification_title": "Ascent连接", "notification_description": { "connecting": "连接无线调试中,请点击按钮输入无线调试端口", "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序", "fail": "失败,请检查端口\n", "repair": "证书失效,请重新配对" }, "notification_reply_button": "点此输入数据", "link_action": { "title": "抽卡链接", "copy_button": "复制", "copied": "已复制" } }, "root_connect": { "notification_title": "Ascent Root连接", "notification_description": { "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku连接", "notification_description": { "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序" } }, "update": { "title": "新版本 ", "ok": "更新", "cancel": "暂不更新" }, "error" : { "title": "请联系技术支持", "copy": "复制", "copied": "已复制" }, "settings": { "disable_auto_detect_port": "关闭端口自动检测" } } ================================================ FILE: assets/translations/zh.json ================================================ { "title": "Ascent", "navigation": { "home": "主页", "pair": "配对", "connect": "连接", "info": "关于" }, "home": { "star": "如果你喜欢Ascent 请给个Star吧 ;D", "support": "技术支持", "developer_option": { "status": "开发者选项状态: ", "enabled": "已启用", "disabled": "未启用" }, "root": { "name": "获取链接", "enabled": "Root已开启!", "direct_connect": "你可以直接点击连接" }, "shizuku": { "name": "获取链接", "enabled": "Shizuku已开启!", "direct_connect": "你可以直接点击连接" }, "pairing": { "name": "配对", "status": "无线调试配对状态: ", "paired": "已配对", "wait_pairing": "未配对" }, "connect": { "name": "连接", "status": "无线调试连接状态: ", "connected": "已连接", "wait_connect": "等待连接" } }, "pair": { "guide": { "prepare_guide": "接下来的无线调试配对过程请跟随通知栏中的提示进行", "pair": "开始配对", "reset": "重置配对状态" }, "notification_title": "Ascent配对", "notification_description": { "guide_port": "打开无线调试并点击使用配对码配对设备\n通过下面的按钮输入无线调试配对端口", "guide_code": "请通过下面的按钮输入无线调试配对码", "error_init": "前台服务启动失败,请联系开发者", "pair_port": "端口: ", "pair_code": "配对码: ", "pair_success": "配对成功,请返回Ascent主程序", "pair_fail": "配对失败,请确认配对码" }, "notification_reply_button": "点此输入数据" }, "connect": { "guide": { "prepare_guide": "连接后请直接打开游戏\n成功获得链接后将在通知中提示", "connect": "开始连接!", "in_progress": "请打开游戏,等待中...", "reset": "重置状态", "root_connect": "开始Root连接!", "shizuku_connect": "开始Shizuku连接!" }, "notification_title": "Ascent连接", "notification_description": { "connecting": "连接无线调试中,请点击按钮输入无线调试端口", "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序", "fail": "失败,请检查端口\n", "repair": "证书失效,请重新配对" }, "notification_reply_button": "点此输入数据", "link_action": { "title": "抽卡链接", "copy_button": "复制", "copied": "已复制" } }, "root_connect": { "notification_title": "Ascent Root连接", "notification_description": { "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序" } }, "shizuku_connect": { "notification_title": "Ascent Shizuku连接", "notification_description": { "waiting": "等待链接中", "success": "获取成功,请返回Ascent主程序" } }, "update": { "title": "新版本 ", "ok": "更新", "cancel": "暂不更新" }, "error" : { "title": "请联系技术支持", "copy": "复制", "copied": "已复制" }, "settings": { "disable_auto_detect_port": "关闭端口自动检测" } } ================================================ FILE: flutter_rust_bridge.yaml ================================================ rust_input: crate::api rust_root: rust/ dart_output: lib/native ================================================ FILE: integration_test/simple_test.dart ================================================ import 'package:flutter_test/flutter_test.dart'; import 'package:ascent/main.dart'; import 'package:ascent/src/rust/frb_generated.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async => await RustLib.init()); testWidgets('Can call rust function', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); expect(find.textContaining('Result: `Hello, Tom!`'), findsOneWidget); }); } ================================================ FILE: lib/components/bottom_navigation_bar/view.dart ================================================ import 'package:ascent/global_state.dart'; import 'package:ascent/routes.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart' as easy_localization; import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:get/get.dart'; class BottomNavigationBarComponent extends StatelessWidget { const BottomNavigationBarComponent({super.key}); @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Obx(() => BrnBottomTabBar( currentIndex: Routes.route2index(GlobalState.currentRoute.value), onTap: (index) { GlobalState.currentRoute.value = Routes.index2route(index); FlutterForegroundTask.isRunningService.then((value) => { if (value) {FlutterForegroundTask.stopService()} }); Get.toNamed(GlobalState.currentRoute.value); }, fixedColor: Colors.blueAccent, isInkResponse: true, items: [ BrnBottomTabBarItem( icon: const Icon(Icons.home), title: const Text('navigation.home').tr(), ), BrnBottomTabBarItem( icon: const Icon(Icons.key), title: const Text('navigation.pair').tr(), ), BrnBottomTabBarItem( icon: const Icon(Icons.link), title: const Text('navigation.connect').tr(), ), BrnBottomTabBarItem( icon: const Icon(Icons.info), title: const Text('navigation.info').tr(), ) ], ))); } } ================================================ FILE: lib/foreground/connect.dart ================================================ import 'dart:io'; import 'package:ascent/native/api/api.dart' as api; import 'package:ascent/global_state.dart'; import 'package:ascent/native/frb_generated.dart'; import 'package:ascent/pages/connect/logic.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge.dart'; import 'package:get/get.dart'; import 'package:multicast_dns/multicast_dns.dart'; @pragma('vm:entry-point') void startCallback() { // The setTaskHandler function must be called to handle the task in the background. FlutterForegroundTask.setTaskHandler(ConnectTaskHandler()); } enum ConnectStatus { WAIT_PORT, WAIT_LINK } class ConnectTaskHandler extends TaskHandler { String port = ""; String link = ""; static late MDnsClient mDnsClient; ConnectStatus status = ConnectStatus.WAIT_PORT; Future loadTranslations() async { //this will only set EasyLocalizationController.savedLocale await EasyLocalizationController.initEasyLocation(); final controller = EasyLocalizationController( saveLocale: true, //mandatory to use EasyLocalizationController.savedLocale fallbackLocale: GlobalState.supportedLocale[0], supportedLocales: GlobalState.supportedLocale, assetLoader: const RootBundleAssetLoader(), useOnlyLangCode: false, useFallbackTranslations: true, path: GlobalState.localizationAssetPath, onLoadError: (FlutterError e) {}, ); //Load translations from assets await controller.loadTranslations(); //load translations into exploitable data, kept in memory Localization.load(controller.locale, translations: controller.translations, fallbackTranslations: controller.fallbackTranslations); } Future startMDNS() async { print("Start listening to mDNS"); await mDnsClient.start(); while (status == ConnectStatus.WAIT_PORT) { await for (final PtrResourceRecord ptr in mDnsClient.lookup( ResourceRecordQuery.serverPointer('_adb-tls-connect._tcp'))) { await for (final SrvResourceRecord srv in mDnsClient.lookup( ResourceRecordQuery.service(ptr.domainName))) { port = srv.port.toString(); status = ConnectStatus.WAIT_LINK; waitLink(); } } await Future.delayed(const Duration(milliseconds: 500)); } } Future waitLink() async { mDnsClient.stop(); FlutterForegroundTask.updateService( notificationText: tr('connect.notification_description.waiting'), ); await RustLib.init(); String errorMessage = ""; api .doConnect(port: port, dataFolder: GlobalState.dataDir.path) .catchError((error) { if (error is AnyhowException) { errorMessage = error.message; } else { errorMessage = error.toString(); } if (errorMessage.contains("error.pair_cert_invalid")) { FlutterForegroundTask.sendDataToMain( "error.pair_cert_invalid#$errorMessage"); return "error.pair_cert_invalid"; } else { FlutterForegroundTask.sendDataToMain("error.other#$errorMessage"); return "error.other"; } }).then((value) { if (!value.startsWith("error")) { link = value; FlutterForegroundTask.updateService( notificationText: tr('connect.notification_description.success'), ); FlutterForegroundTask.sendDataToMain(link); } else { if (value == "error.pair_cert_invalid") { FlutterForegroundTask.updateService( notificationText: tr('connect.notification_description.repair'), ); } else { FlutterForegroundTask.updateService( notificationText: tr('connect.notification_description.fail') + errorMessage, ); } } }); } @override Future onDestroy(DateTime timestamp) async { mDnsClient.stop(); } @override void onRepeatEvent(DateTime timestamp) {} @override Future onStart(DateTime timestamp, TaskStarter starter) async { await loadTranslations(); await GlobalState.init(); mDnsClient = MDnsClient(rawDatagramSocketFactory: (dynamic host, int port, {bool reuseAddress = true, bool reusePort = true, int ttl = 1}) { return RawDatagramSocket.bind(host, port, reuseAddress: true, reusePort: false, ttl: ttl); }); if (!GlobalState.disableAutoDetectPort.value) { startMDNS(); } } @override void onNotificationReplied(String id, String reply) { if (status == ConnectStatus.WAIT_PORT) { if (reply.length > 5) { FlutterForegroundTask.updateService( notificationText: tr('connect.notification_description.fail'), ); return; } if (int.tryParse(reply) != null) { port = reply; status = ConnectStatus.WAIT_LINK; waitLink(); } } } } class ConnectForegroundTask { Future requestPermission() async { // Android 12 or higher, there are restrictions on starting a foreground service. // // To restart the service on device reboot or unexpected problem, you need to allow below permission. if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) { // This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission. await FlutterForegroundTask.requestIgnoreBatteryOptimization(); } // Android 13 and higher, you need to allow notification permission to expose foreground service notification. final NotificationPermission notificationPermissionStatus = await FlutterForegroundTask.checkNotificationPermission(); if (notificationPermissionStatus != NotificationPermission.granted) { await FlutterForegroundTask.requestNotificationPermission(); } } Future startConnectForegroundTask(ConnectLogic logic) async { GlobalState.mixpanel.track("Connect Begin"); GlobalState.mixpanel.flush(); await requestPermission(); if (await FlutterForegroundTask.isRunningService) { await FlutterForegroundTask.stopService(); } FlutterForegroundTask.dataCallbacks.clear(); FlutterForegroundTask.addTaskDataCallback((dynamic data) { if (data is String) { if (data.startsWith("error.other#")) { logic.inProgress.value = false; String errorMessage = data.replaceFirst("error.other#", ""); Get.dialog(BrnScrollableTextDialog( title: tr("error.title"), contentText: errorMessage, submitText: tr("error.copy"), submitBgColor: Colors.orangeAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: errorMessage)); BrnToast.showInCenter( text: tr("error.copied"), context: Get.context!, ); }, )); } else if (data.startsWith("error.pair_cert_invalid#")) { logic.inProgress.value = false; File("${GlobalState.dataDir.path}/cert.pem").deleteSync(); File("${GlobalState.dataDir.path}/pkey.pem").deleteSync(); GlobalState.hasCert.value = false; } else { RegExp regex = RegExp(r'https://(.+)'); Match? match = regex.firstMatch(data); if (match != null) { logic.link.value = match.group(0)!; logic.inProgress.value = false; Get.dialog(BrnScrollableTextDialog( title: tr("connect.link_action.title"), contentText: logic.link.value, submitText: tr("connect.link_action.copy_button"), submitBgColor: Colors.greenAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: logic.link.value)); BrnToast.showInCenter( text: tr("connect.link_action.copied"), context: Get.context!, ); }, )); GlobalState.mixpanel.track("Connect Complete", properties: { 'Game': logic.link.value.contains('hkrpg') ? 'hkrpg' : 'gs', }); GlobalState.mixpanel.flush(); FlutterForegroundTask.stopService(); } } } }); FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'ascent_foreground_service', channelName: 'Ascent Foreground Service', channelImportance: NotificationChannelImportance.HIGH, priority: NotificationPriority.HIGH, ), iosNotificationOptions: const IOSNotificationOptions( showNotification: false, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, autoRunOnBoot: false, allowWifiLock: true, eventAction: ForegroundTaskEventAction.repeat(5000), ), ); await FlutterForegroundTask.startService( notificationTitle: tr('connect.notification_title'), notificationText: tr('connect.notification_description.connecting'), callback: startCallback, notificationButtons: [ NotificationButton( id: 'replyButton', text: tr("pair.notification_reply_button"), isReply: true, ) ], ); return true; } } ================================================ FILE: lib/foreground/pair.dart ================================================ import 'dart:io'; import 'package:ascent/native/api/api.dart' as api; import 'package:ascent/global_state.dart'; import 'package:ascent/native/frb_generated.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge.dart'; import 'package:get/get.dart'; import 'package:multicast_dns/multicast_dns.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; // Top level callback function, will run in isolated @pragma('vm:entry-point') void startCallback() { // The setTaskHandler function must be called to handle the task in the background. FlutterForegroundTask.setTaskHandler(PairTaskHandler()); } enum PairStatus { WAIT_PORT, WAIT_CODE } // This will run in the foreground service isolated class PairTaskHandler extends TaskHandler { PairStatus status = PairStatus.WAIT_PORT; String port = ""; String code = ""; static late MDnsClient mDnsClient; Future loadTranslations() async { //this will only set EasyLocalizationController.savedLocale await EasyLocalizationController.initEasyLocation(); final controller = EasyLocalizationController( saveLocale: true, //mandatory to use EasyLocalizationController.savedLocale fallbackLocale: GlobalState.supportedLocale[0], supportedLocales: GlobalState.supportedLocale, assetLoader: const RootBundleAssetLoader(), useOnlyLangCode: false, useFallbackTranslations: true, path: GlobalState.localizationAssetPath, onLoadError: (FlutterError e) {}, ); //Load translations from assets await controller.loadTranslations(); //load translations into exploitable data, kept in memory Localization.load(controller.locale, translations: controller.translations, fallbackTranslations: controller.fallbackTranslations); } Future startMDNS() async { print("Start listening to mDNS"); await mDnsClient.start(); while (status == PairStatus.WAIT_PORT) { await for (final PtrResourceRecord ptr in mDnsClient.lookup( ResourceRecordQuery.serverPointer('_adb-tls-pairing._tcp'))) { await for (final SrvResourceRecord srv in mDnsClient.lookup( ResourceRecordQuery.service(ptr.domainName))) { port = srv.port.toString(); status = PairStatus.WAIT_CODE; waitCode(); } } await Future.delayed(const Duration(milliseconds: 500)); } } // This is called when pairing port has been set already Future waitCode() async { // Stop mDnsClient for it has no use mDnsClient.stop(); FlutterForegroundTask.updateService( notificationTitle: "${tr('pair.notification_title')} ${tr('pair.notification_description.pair_port')} $port", notificationText: tr('pair.notification_description.guide_code'), ); } Future doPair() async { await RustLib.init(); String errorMessage = ""; api .doPair(port: port, code: code, dataFolder: GlobalState.dataDir.path) .catchError((error) { if (error is AnyhowException) { errorMessage = error.message; } else { errorMessage = error.toString(); } FlutterForegroundTask.sendDataToMain("error#$errorMessage"); return false; }).then((value) { if (value) { FlutterForegroundTask.updateService( notificationTitle: tr('pair.notification_title'), notificationText: tr('pair.notification_description.pair_success'), ); FlutterForegroundTask.sendDataToMain('pair_complete'); } else { FlutterForegroundTask.updateService( notificationTitle: tr('pair.notification_title'), notificationText: tr('pair.notification_description.pair_fail') + errorMessage, ); File("${GlobalState.dataDir.path}/cert.pem").deleteSync(); File("${GlobalState.dataDir.path}/pkey.pem").deleteSync(); } }); } @override Future onDestroy(DateTime timestamp) async { mDnsClient.stop(); } @override void onRepeatEvent(DateTime timestamp) {} @override Future onStart(DateTime timestamp, TaskStarter starter) async { loadTranslations(); await GlobalState.init(); mDnsClient = MDnsClient(rawDatagramSocketFactory: (dynamic host, int port, {bool reuseAddress = true, bool reusePort = true, int ttl = 1}) { return RawDatagramSocket.bind(host, port, reuseAddress: true, reusePort: false, ttl: ttl); }); // Start mdns listener if (!GlobalState.disableAutoDetectPort.value) { startMDNS(); } } @override void onNotificationReplied(String id, String reply) { switch (status) { case PairStatus.WAIT_PORT: if (int.tryParse(reply) != null) { port = reply; status = PairStatus.WAIT_CODE; waitCode(); } break; case PairStatus.WAIT_CODE: code = reply; doPair(); break; } } } class PairForegroundTask { Future requestPermission() async { // Android 12 or higher, there are restrictions on starting a foreground service. // // To restart the service on device reboot or unexpected problem, you need to allow below permission. if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) { // This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission. await FlutterForegroundTask.requestIgnoreBatteryOptimization(); } // Android 13 and higher, you need to allow notification permission to expose foreground service notification. final NotificationPermission notificationPermissionStatus = await FlutterForegroundTask.checkNotificationPermission(); if (notificationPermissionStatus != NotificationPermission.granted) { await FlutterForegroundTask.requestNotificationPermission(); } } void pairCallback(Object data) { if (data is String) { if (data == "pair_complete") { WidgetsBinding.instance.addPostFrameCallback((_) { GlobalState.hasCert.value = true; GlobalState.mixpanel.track("Pair Complete"); GlobalState.mixpanel.flush(); FlutterForegroundTask.stopService(); }); } else if (data.startsWith("error#")) { String errorMessage = data.replaceFirst("error#", ""); Get.dialog(BrnScrollableTextDialog( title: tr("error.title"), contentText: errorMessage, submitText: tr("error.copy"), submitBgColor: Colors.orangeAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: errorMessage)); BrnToast.showInCenter( text: tr("error.copied"), context: Get.context!, ); }, )); } } } Future startPairForegroundTask() async { GlobalState.mixpanel.track("Pair Begin"); GlobalState.mixpanel.flush(); // Request permission await requestPermission(); // Stop any foreground service still running if (await FlutterForegroundTask.isRunningService) { await FlutterForegroundTask.stopService(); } FlutterForegroundTask.addTaskDataCallback(pairCallback); // Init foreground task FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'ascent_foreground_service', channelName: 'Ascent Foreground Service', channelImportance: NotificationChannelImportance.HIGH, priority: NotificationPriority.HIGH, ), iosNotificationOptions: const IOSNotificationOptions( showNotification: false, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( eventAction: ForegroundTaskEventAction.repeat(5000), allowWakeLock: true, autoRunOnBoot: false, allowWifiLock: true, ), ); // Start task await FlutterForegroundTask.startService( notificationTitle: tr('pair.notification_title'), notificationText: tr('pair.notification_description.guide_port'), callback: startCallback, notificationButtons: [ NotificationButton( id: 'replyButton', text: tr("pair.notification_reply_button"), isReply: true, ) ]); return true; } } ================================================ FILE: lib/foreground/root_connect.dart ================================================ import 'package:ascent/global_state.dart'; import 'package:ascent/pages/connect/logic.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:get/get.dart'; import 'package:root/root.dart'; @pragma('vm:entry-point') void startCallback() { // The setTaskHandler function must be called to handle the task in the background. FlutterForegroundTask.setTaskHandler(RootConnectTaskHandler()); } class RootConnectTaskHandler extends TaskHandler { String link = ""; Future loadTranslations() async { //this will only set EasyLocalizationController.savedLocale await EasyLocalizationController.initEasyLocation(); final controller = EasyLocalizationController( saveLocale: true, //mandatory to use EasyLocalizationController.savedLocale fallbackLocale: GlobalState.supportedLocale[0], supportedLocales: GlobalState.supportedLocale, assetLoader: const RootBundleAssetLoader(), useOnlyLangCode: false, useFallbackTranslations: true, path: GlobalState.localizationAssetPath, onLoadError: (FlutterError e) {}, ); //Load translations from assets await controller.loadTranslations(); //load translations into exploitable data, kept in memory Localization.load(controller.locale, translations: controller.translations, fallbackTranslations: controller.fallbackTranslations); } Future waitLink() async { FlutterForegroundTask.updateService( notificationText: tr('root_connect.notification_description.waiting'), ); while (link.isEmpty) { String? data = await Root.exec( cmd: "logcat -d | grep -E 'https://(webstatic|hk4e-api|webstatic-sea|hk4e-api-os|api-takumi|api-os-takumi|gs|aki-gm-resources-oversea).(mihoyo\\.com|hoyoverse\\.com|aki-game\\.net|aki-game\\.com)' | grep -i 'gacha' | tail -n 1"); if (data != null) { link = data; FlutterForegroundTask.sendDataToMain(link); } Future.delayed(const Duration(milliseconds: 500)); } } @override Future onDestroy(DateTime timestamp) async {} @override void onRepeatEvent(DateTime timestamp) {} @override Future onStart(DateTime timestamp, TaskStarter starter) async { await loadTranslations(); await GlobalState.init(); waitLink(); } } class RootConnectForegroundTask { Future requestPermission() async { // Android 12 or higher, there are restrictions on starting a foreground service. // // To restart the service on device reboot or unexpected problem, you need to allow below permission. if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) { // This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission. await FlutterForegroundTask.requestIgnoreBatteryOptimization(); } // Android 13 and higher, you need to allow notification permission to expose foreground service notification. final NotificationPermission notificationPermissionStatus = await FlutterForegroundTask.checkNotificationPermission(); if (notificationPermissionStatus != NotificationPermission.granted) { await FlutterForegroundTask.requestNotificationPermission(); } } Future startRootConnectForegroundTask(ConnectLogic logic) async { GlobalState.mixpanel.track("Root Connect Begin"); GlobalState.mixpanel.flush(); await requestPermission(); if (await FlutterForegroundTask.isRunningService) { await FlutterForegroundTask.stopService(); } FlutterForegroundTask.dataCallbacks.clear(); FlutterForegroundTask.addTaskDataCallback((dynamic data) { if (data is String) { if (data.startsWith("error.other#")) { logic.inProgress.value = false; String errorMessage = data.replaceFirst("error.other#", ""); Get.dialog(BrnScrollableTextDialog( title: tr("error.title"), contentText: errorMessage, submitText: tr("error.copy"), submitBgColor: Colors.orangeAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: errorMessage)); BrnToast.showInCenter( text: tr("error.copied"), context: Get.context!, ); }, )); } else { RegExp regex = RegExp(r'https://(.+)'); Match? match = regex.firstMatch(data); if (match != null) { logic.link.value = match.group(0)!; logic.inProgress.value = false; Get.dialog(BrnScrollableTextDialog( title: tr("connect.link_action.title"), contentText: logic.link.value, submitText: tr("connect.link_action.copy_button"), submitBgColor: Colors.greenAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: logic.link.value)); BrnToast.showInCenter( text: tr("connect.link_action.copied"), context: Get.context!, ); }, )); GlobalState.mixpanel.track("Connect Complete", properties: { 'Game': logic.link.value.contains('hkrpg') ? 'hkrpg' : 'gs', }); GlobalState.mixpanel.flush(); FlutterForegroundTask.stopService(); } } } }); FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'ascent_foreground_service', channelName: 'Ascent Foreground Service', channelImportance: NotificationChannelImportance.HIGH, priority: NotificationPriority.HIGH, ), iosNotificationOptions: const IOSNotificationOptions( showNotification: false, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( eventAction: ForegroundTaskEventAction.repeat(5000), allowWakeLock: true, autoRunOnBoot: false, allowWifiLock: true, ), ); await FlutterForegroundTask.startService( notificationTitle: tr('root_connect.notification_title'), notificationText: tr('root_connect.notification_description.waiting'), callback: startCallback, ); return true; } } ================================================ FILE: lib/foreground/shizuku_connect.dart ================================================ import 'package:ascent/global_state.dart'; import 'package:ascent/pages/connect/logic.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:get/get.dart'; import 'package:shizuku_api/shizuku_api.dart'; @pragma('vm:entry-point') void startCallback() { // The setTaskHandler function must be called to handle the task in the background. FlutterForegroundTask.setTaskHandler(ShizukuConnectTaskHandler()); } class ShizukuConnectTaskHandler extends TaskHandler { String link = ""; Future loadTranslations() async { //this will only set EasyLocalizationController.savedLocale await EasyLocalizationController.initEasyLocation(); final controller = EasyLocalizationController( saveLocale: true, //mandatory to use EasyLocalizationController.savedLocale fallbackLocale: GlobalState.supportedLocale[0], supportedLocales: GlobalState.supportedLocale, assetLoader: const RootBundleAssetLoader(), useOnlyLangCode: false, useFallbackTranslations: true, path: GlobalState.localizationAssetPath, onLoadError: (FlutterError e) {}, ); //Load translations from assets await controller.loadTranslations(); //load translations into exploitable data, kept in memory Localization.load(controller.locale, translations: controller.translations, fallbackTranslations: controller.fallbackTranslations); } Future waitLink() async { FlutterForegroundTask.updateService( notificationText: tr('shizuku_connect.notification_description.waiting'), ); final _shizukuApiPlugin = ShizukuApi(); while (link.isEmpty) { String? data = await _shizukuApiPlugin.runCommand( "logcat -d | grep -E 'https://(webstatic|hk4e-api|webstatic-sea|hk4e-api-os|api-takumi|api-os-takumi|gs|aki-gm-resources-oversea).(mihoyo\\.com|hoyoverse\\.com|aki-game\\.net|aki-game\\.com)' | grep -i 'gacha' | tail -n 1"); if (data != null) { link = data; FlutterForegroundTask.sendDataToMain(link); } Future.delayed(const Duration(milliseconds: 500)); } } @override Future onDestroy(DateTime timestamp) async {} @override void onRepeatEvent(DateTime timestamp) {} @override Future onStart(DateTime timestamp, TaskStarter starter) async { await loadTranslations(); await GlobalState.init(); waitLink(); } } class ShizukuConnectForegroundTask { Future requestPermission() async { // Android 12 or higher, there are restrictions on starting a foreground service. // // To restart the service on device reboot or unexpected problem, you need to allow below permission. if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) { // This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission. await FlutterForegroundTask.requestIgnoreBatteryOptimization(); } // Android 13 and higher, you need to allow notification permission to expose foreground service notification. final NotificationPermission notificationPermissionStatus = await FlutterForegroundTask.checkNotificationPermission(); if (notificationPermissionStatus != NotificationPermission.granted) { await FlutterForegroundTask.requestNotificationPermission(); } } Future startShizukuConnectForegroundTask(ConnectLogic logic) async { GlobalState.mixpanel.track("Shizuku Connect Begin"); GlobalState.mixpanel.flush(); await requestPermission(); if (await FlutterForegroundTask.isRunningService) { await FlutterForegroundTask.stopService(); } FlutterForegroundTask.dataCallbacks.clear(); FlutterForegroundTask.addTaskDataCallback((dynamic data) { if (data is String) { if (data.startsWith("error.other#")) { logic.inProgress.value = false; String errorMessage = data.replaceFirst("error.other#", ""); Get.dialog(BrnScrollableTextDialog( title: tr("error.title"), contentText: errorMessage, submitText: tr("error.copy"), submitBgColor: Colors.orangeAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: errorMessage)); BrnToast.showInCenter( text: tr("error.copied"), context: Get.context!, ); }, )); } else { RegExp regex = RegExp(r'https://(.+)'); Match? match = regex.firstMatch(data); if (match != null) { logic.link.value = match.group(0)!; logic.inProgress.value = false; Get.dialog(BrnScrollableTextDialog( title: tr("connect.link_action.title"), contentText: logic.link.value, submitText: tr("connect.link_action.copy_button"), submitBgColor: Colors.greenAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: logic.link.value)); BrnToast.showInCenter( text: tr("connect.link_action.copied"), context: Get.context!, ); }, )); GlobalState.mixpanel.track("Connect Complete", properties: { 'Game': logic.link.value.contains('hkrpg') ? 'hkrpg' : 'gs', }); GlobalState.mixpanel.flush(); FlutterForegroundTask.stopService(); } } } }); FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'ascent_foreground_service', channelName: 'Ascent Foreground Service', channelImportance: NotificationChannelImportance.HIGH, priority: NotificationPriority.HIGH, ), iosNotificationOptions: const IOSNotificationOptions( showNotification: false, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( eventAction: ForegroundTaskEventAction.repeat(5000), allowWakeLock: true, autoRunOnBoot: false, allowWifiLock: true, ), ); await FlutterForegroundTask.startService( notificationTitle: tr('shizuku_connect.notification_title'), notificationText: tr('shizuku_connect.notification_description.waiting'), callback: startCallback, ); return true; } } ================================================ FILE: lib/global_state.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:mixpanel_flutter/mixpanel_flutter.dart'; import 'package:path_provider/path_provider.dart'; import 'package:root/root.dart'; import 'package:shizuku_api/shizuku_api.dart'; class GlobalState { static const version = "2.4.0"; static String discord = "https://discord.gg/6v6HEUaRWk"; static const platform = MethodChannel('cafe.f403.ascent/main'); static Rx currentRoute = "/home".obs; static late final Directory dataDir; static const String localizationAssetPath = "assets/translations"; static Rx hasCert = false.obs; static Rx rootEnabled = false.obs; static Rx shizukuEnabled = false.obs; static late Mixpanel mixpanel; static StreamSubscription? intentSubscription; static String? locale; static Rx disableAutoDetectPort = false.obs; static const List supportedLocale = [ Locale('en', 'US'), Locale('zh', 'CN'), Locale('ru', 'RU'), ]; static Future init() async { dataDir = await getApplicationDocumentsDirectory(); hasCert.value = File("${dataDir.path}/cert.pem").existsSync(); if (kDebugMode) { print("Data directory: ${dataDir.path}"); } disableAutoDetectPort.value = File("${dataDir.path}/disableAutoDetectPort").existsSync(); mixpanel = await Mixpanel.init("1bad86a59f59ee1d395c31b61bf9202a", trackAutomaticEvents: true); rootEnabled.value = await Root.isRooted() ?? false; final _shizukuApiPlugin = ShizukuApi(); if ((await _shizukuApiPlugin.pingBinder() ?? false) && (await _shizukuApiPlugin.checkPermission() ?? false) && (await _shizukuApiPlugin.requestPermission() ?? false)) { shizukuEnabled.value = true; } } } ================================================ FILE: lib/main.dart ================================================ import 'dart:convert'; import 'dart:io'; import 'package:ascent/global_state.dart'; import 'package:ascent/native/frb_generated.dart'; import 'package:ascent/routes.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:get/get.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:receive_intent/receive_intent.dart' as intent; import 'package:uri_to_file/uri_to_file.dart'; import 'package:url_launcher/url_launcher.dart'; import 'components/bottom_navigation_bar/view.dart'; import 'package:http/http.dart' as http; import 'native/api/api.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Load localizations await EasyLocalization.ensureInitialized(); await RustLib.init(); // Set some final global data await GlobalState.init(); FlutterForegroundTask.initCommunicationPort(); runApp( WithForegroundTask( child: EasyLocalization( supportedLocales: GlobalState.supportedLocale, path: GlobalState.localizationAssetPath, fallbackLocale: GlobalState.supportedLocale[0], child: const AscentApp(), ), ), ); } Future checkUpdate() async { String url = GlobalState.locale == "zh_CN" ? "https://gist.gitmirror.com/4o3F/d44252ab04227a81b8270fe85a50691a/raw" : "https://gist.github.com/4o3F/d44252ab04227a81b8270fe85a50691a/raw"; http.Response response = await http.get(Uri.parse(url)); Map parsed = json.decode(response.body); String version = parsed['version']; String discord = parsed['discord']; GlobalState.discord = discord; Version newVersion = Version.parse(version); Version currentVersion = Version.parse(GlobalState.version); if (newVersion > currentVersion) { String updateInfo = parsed['info'][GlobalState.locale] ?? parsed['info']['en_US']; Uri url = Uri.parse(GlobalState.locale == "zh_CN" ? parsed['url']['backup'] : parsed['url']['main']); BrnEnhanceOperationDialog dialog = BrnEnhanceOperationDialog( context: Get.context!, titleText: tr('update.title') + version, descText: updateInfo, mainButtonText: tr('update.ok'), secondaryButtonText: tr('update.cancel'), onMainButtonClick: () async { if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { await launchUrl(url); } }, onSecondaryButtonClick: () { Get.back(closeOverlays: true); }, ); dialog.show(); } } class AscentApp extends StatelessWidget { const AscentApp({super.key}); Future initReceiveIntent() async { try { final receivedIntent = await intent.ReceiveIntent.getInitialIntent(); if (receivedIntent != null && receivedIntent.action != null) { if (receivedIntent.action == "android.intent.action.SEND" && receivedIntent.extra != null) { File file = await toFile( receivedIntent.extra?["android.intent.extra.STREAM"]); String path = file.path; String link = await doFilter(filePath: path); file.deleteSync(); GlobalState.mixpanel.track("System Trace Complete", properties: { 'Game': link.contains('hkrpg') ? 'hkrpg' : 'gs', }); Get.dialog(BrnScrollableTextDialog( title: tr("connect.link_action.title"), contentText: link, submitText: tr("connect.link_action.copy_button"), submitBgColor: Colors.greenAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: link)); BrnToast.showInCenter( text: tr("connect.link_action.copied"), context: Get.context!, ); }, )); GlobalState.mixpanel.flush(); } } } on PlatformException catch (_, e) { GlobalState.mixpanel .track('Platform error', properties: {'error': e.toString()}); } GlobalState.intentSubscription ??= intent.ReceiveIntent.receivedIntentStream .listen((intent.Intent? receivedIntent) async { if (receivedIntent != null && receivedIntent.action != null) { if (receivedIntent.action == "android.intent.action.SEND" && receivedIntent.extra != null) { File file = await toFile( receivedIntent.extra?["android.intent.extra.STREAM"]); String path = file.path; String link = await doFilter(filePath: path); file.deleteSync(); GlobalState.mixpanel.track("System Trace Complete", properties: { 'Game': link.contains('hkrpg') ? 'hkrpg' : 'gs', }); Get.dialog(BrnScrollableTextDialog( title: tr("connect.link_action.title"), contentText: link, submitText: tr("connect.link_action.copy_button"), submitBgColor: Colors.greenAccent, onSubmitClick: () { Clipboard.setData(ClipboardData(text: link)); BrnToast.showInCenter( text: tr("connect.link_action.copied"), context: Get.context!, ); }, )); GlobalState.mixpanel.flush(); } } }, onError: (err) { GlobalState.mixpanel .track('Platform error', properties: {'error': err.toString()}); }); } @override Widget build(BuildContext context) { initReceiveIntent(); GlobalState.locale = context.deviceLocale.toString(); checkUpdate(); initLogger(); return MaterialApp( localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: context.locale, debugShowCheckedModeBanner: false, home: Column( children: [ Expanded( child: Scaffold( body: GetMaterialApp( initialRoute: Routes.defaultRoute, getPages: Routes.routes, defaultTransition: Transition.fade, debugShowCheckedModeBanner: false, routingCallback: (routing) { // Switch current route, mainly used for updating bottom navigation tab GlobalState.currentRoute.value = routing!.current; }, ), ), ), BottomNavigationBarComponent() ], )); } } ================================================ FILE: lib/native/api/api.dart ================================================ // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import import '../frb_generated.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; Future doPair( {required String port, required String code, required String dataFolder}) => RustLib.instance.api .crateApiApiDoPair(port: port, code: code, dataFolder: dataFolder); Future doConnect({required String port, required String dataFolder}) => RustLib.instance.api .crateApiApiDoConnect(port: port, dataFolder: dataFolder); Future doFilter({required String filePath}) => RustLib.instance.api.crateApiApiDoFilter(filePath: filePath); Future initLogger() => RustLib.instance.api.crateApiApiInitLogger(); ================================================ FILE: lib/native/frb_generated.dart ================================================ // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field import 'api/api.dart'; import 'dart:async'; import 'dart:convert'; import 'frb_generated.dart'; import 'frb_generated.io.dart' if (dart.library.js_interop) 'frb_generated.web.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; /// Main entrypoint of the Rust API class RustLib extends BaseEntrypoint { @internal static final instance = RustLib._(); RustLib._(); /// Initialize flutter_rust_bridge static Future init({ RustLibApi? api, BaseHandler? handler, ExternalLibrary? externalLibrary, bool forceSameCodegenVersion = true, }) async { await instance.initImpl( api: api, handler: handler, externalLibrary: externalLibrary, forceSameCodegenVersion: forceSameCodegenVersion, ); } /// Initialize flutter_rust_bridge in mock mode. /// No libraries for FFI are loaded. static void initMock({ required RustLibApi api, }) { instance.initMockImpl( api: api, ); } /// Dispose flutter_rust_bridge /// /// The call to this function is optional, since flutter_rust_bridge (and everything else) /// is automatically disposed when the app stops. static void dispose() => instance.disposeImpl(); @override ApiImplConstructor get apiImplConstructor => RustLibApiImpl.new; @override WireConstructor get wireConstructor => RustLibWire.fromExternalLibrary; @override Future executeRustInitializers() async {} @override ExternalLibraryLoaderConfig get defaultExternalLibraryLoaderConfig => kDefaultExternalLibraryLoaderConfig; @override String get codegenVersion => '2.11.1'; @override int get rustContentHash => -637951497; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( stem: 'rust_lib_ascent', ioDirectory: 'rust/target/release/', webPrefix: 'pkg/', ); } abstract class RustLibApi extends BaseApi { Future crateApiApiDoConnect( {required String port, required String dataFolder}); Future crateApiApiDoFilter({required String filePath}); Future crateApiApiDoPair( {required String port, required String code, required String dataFolder}); Future crateApiApiInitLogger(); } class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { RustLibApiImpl({ required super.handler, required super.wire, required super.generalizedFrbRustBinding, required super.portManager, }); @override Future crateApiApiDoConnect( {required String port, required String dataFolder}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(port, serializer); sse_encode_String(dataFolder, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 1, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_String, decodeErrorData: sse_decode_AnyhowException, ), constMeta: kCrateApiApiDoConnectConstMeta, argValues: [port, dataFolder], apiImpl: this, )); } TaskConstMeta get kCrateApiApiDoConnectConstMeta => const TaskConstMeta( debugName: "do_connect", argNames: ["port", "dataFolder"], ); @override Future crateApiApiDoFilter({required String filePath}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(filePath, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 2, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_String, decodeErrorData: sse_decode_AnyhowException, ), constMeta: kCrateApiApiDoFilterConstMeta, argValues: [filePath], apiImpl: this, )); } TaskConstMeta get kCrateApiApiDoFilterConstMeta => const TaskConstMeta( debugName: "do_filter", argNames: ["filePath"], ); @override Future crateApiApiDoPair( {required String port, required String code, required String dataFolder}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); sse_encode_String(port, serializer); sse_encode_String(code, serializer); sse_encode_String(dataFolder, serializer); pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 3, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_bool, decodeErrorData: sse_decode_AnyhowException, ), constMeta: kCrateApiApiDoPairConstMeta, argValues: [port, code, dataFolder], apiImpl: this, )); } TaskConstMeta get kCrateApiApiDoPairConstMeta => const TaskConstMeta( debugName: "do_pair", argNames: ["port", "code", "dataFolder"], ); @override Future crateApiApiInitLogger() { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), constMeta: kCrateApiApiInitLoggerConstMeta, argValues: [], apiImpl: this, )); } TaskConstMeta get kCrateApiApiInitLoggerConstMeta => const TaskConstMeta( debugName: "init_logger", argNames: [], ); @protected AnyhowException dco_decode_AnyhowException(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return AnyhowException(raw as String); } @protected String dco_decode_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return raw as String; } @protected bool dco_decode_bool(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return raw as bool; } @protected Uint8List dco_decode_list_prim_u_8_strict(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return raw as Uint8List; } @protected int dco_decode_u_8(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return raw as int; } @protected void dco_decode_unit(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs return; } @protected AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs var inner = sse_decode_String(deserializer); return AnyhowException(inner); } @protected String sse_decode_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs var inner = sse_decode_list_prim_u_8_strict(deserializer); return utf8.decoder.convert(inner); } @protected bool sse_decode_bool(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs return deserializer.buffer.getUint8() != 0; } @protected Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs var len_ = sse_decode_i_32(deserializer); return deserializer.buffer.getUint8List(len_); } @protected int sse_decode_u_8(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs return deserializer.buffer.getUint8(); } @protected void sse_decode_unit(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs } @protected int sse_decode_i_32(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs return deserializer.buffer.getInt32(); } @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_String(self.message, serializer); } @protected void sse_encode_String(String self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_list_prim_u_8_strict(utf8.encoder.convert(self), serializer); } @protected void sse_encode_bool(bool self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs serializer.buffer.putUint8(self ? 1 : 0); } @protected void sse_encode_list_prim_u_8_strict( Uint8List self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_i_32(self.length, serializer); serializer.buffer.putUint8List(self); } @protected void sse_encode_u_8(int self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs serializer.buffer.putUint8(self); } @protected void sse_encode_unit(void self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs } @protected void sse_encode_i_32(int self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs serializer.buffer.putInt32(self); } } ================================================ FILE: lib/native/frb_generated.io.dart ================================================ // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field import 'api/api.dart'; import 'dart:async'; import 'dart:convert'; import 'dart:ffi' as ffi; import 'frb_generated.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart'; abstract class RustLibApiImplPlatform extends BaseApiImpl { RustLibApiImplPlatform({ required super.handler, required super.wire, required super.generalizedFrbRustBinding, required super.portManager, }); @protected AnyhowException dco_decode_AnyhowException(dynamic raw); @protected String dco_decode_String(dynamic raw); @protected bool dco_decode_bool(dynamic raw); @protected Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); @protected int dco_decode_u_8(dynamic raw); @protected void dco_decode_unit(dynamic raw); @protected AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer); @protected String sse_decode_String(SseDeserializer deserializer); @protected bool sse_decode_bool(SseDeserializer deserializer); @protected Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); @protected int sse_decode_u_8(SseDeserializer deserializer); @protected void sse_decode_unit(SseDeserializer deserializer); @protected int sse_decode_i_32(SseDeserializer deserializer); @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer); @protected void sse_encode_String(String self, SseSerializer serializer); @protected void sse_encode_bool(bool self, SseSerializer serializer); @protected void sse_encode_list_prim_u_8_strict( Uint8List self, SseSerializer serializer); @protected void sse_encode_u_8(int self, SseSerializer serializer); @protected void sse_encode_unit(void self, SseSerializer serializer); @protected void sse_encode_i_32(int self, SseSerializer serializer); } // Section: wire_class class RustLibWire implements BaseWire { factory RustLibWire.fromExternalLibrary(ExternalLibrary lib) => RustLibWire(lib.ffiDynamicLibrary); /// Holds the symbol lookup function. final ffi.Pointer Function(String symbolName) _lookup; /// The symbols are looked up in [dynamicLibrary]. RustLibWire(ffi.DynamicLibrary dynamicLibrary) : _lookup = dynamicLibrary.lookup; } ================================================ FILE: lib/native/frb_generated.web.dart ================================================ // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field // Static analysis wrongly picks the IO variant, thus ignore this // ignore_for_file: argument_type_not_assignable import 'api/api.dart'; import 'dart:async'; import 'dart:convert'; import 'frb_generated.dart'; import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart'; abstract class RustLibApiImplPlatform extends BaseApiImpl { RustLibApiImplPlatform({ required super.handler, required super.wire, required super.generalizedFrbRustBinding, required super.portManager, }); @protected AnyhowException dco_decode_AnyhowException(dynamic raw); @protected String dco_decode_String(dynamic raw); @protected bool dco_decode_bool(dynamic raw); @protected Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); @protected int dco_decode_u_8(dynamic raw); @protected void dco_decode_unit(dynamic raw); @protected AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer); @protected String sse_decode_String(SseDeserializer deserializer); @protected bool sse_decode_bool(SseDeserializer deserializer); @protected Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); @protected int sse_decode_u_8(SseDeserializer deserializer); @protected void sse_decode_unit(SseDeserializer deserializer); @protected int sse_decode_i_32(SseDeserializer deserializer); @protected void sse_encode_AnyhowException( AnyhowException self, SseSerializer serializer); @protected void sse_encode_String(String self, SseSerializer serializer); @protected void sse_encode_bool(bool self, SseSerializer serializer); @protected void sse_encode_list_prim_u_8_strict( Uint8List self, SseSerializer serializer); @protected void sse_encode_u_8(int self, SseSerializer serializer); @protected void sse_encode_unit(void self, SseSerializer serializer); @protected void sse_encode_i_32(int self, SseSerializer serializer); } // Section: wire_class class RustLibWire implements BaseWire { RustLibWire.fromExternalLibrary(ExternalLibrary lib); } @JS('wasm_bindgen') external RustLibWasmModule get wasmModule; @JS() @anonymous extension type RustLibWasmModule._(JSObject _) implements JSObject {} ================================================ FILE: lib/pages/connect/logic.dart ================================================ import 'package:get/get.dart'; class ConnectLogic extends GetxController { Rx developerOptionEnabled = false.obs; Rx link = "".obs; Rx inProgress = false.obs; } ================================================ FILE: lib/pages/connect/view.dart ================================================ import 'package:ascent/foreground/connect.dart'; import 'package:ascent/foreground/root_connect.dart'; import 'package:ascent/foreground/shizuku_connect.dart'; import 'package:ascent/global_state.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:get/get.dart'; import 'logic.dart'; class ConnectPage extends StatelessWidget { ConnectPage({super.key}); final logic = Get.put(ConnectLogic()); ConnectForegroundTask connectForegroundTask = ConnectForegroundTask(); RootConnectForegroundTask rootConnectForegroundTask = RootConnectForegroundTask(); ShizukuConnectForegroundTask shizukuConnectForegroundTask = ShizukuConnectForegroundTask(); Future doConnect() async { logic.inProgress.value = true; await connectForegroundTask.startConnectForegroundTask(logic); } Future doRootConnect() async { logic.inProgress.value = true; await rootConnectForegroundTask.startRootConnectForegroundTask(logic); } Future doShizukuConnect() async { logic.inProgress.value = true; await shizukuConnectForegroundTask.startShizukuConnectForegroundTask(logic); } Future doResetProcess() async { logic.inProgress.value = false; logic.link.value = ""; await FlutterForegroundTask.stopService(); } @override Widget build(BuildContext context) { GlobalState.platform.invokeMethod('getDeveloperOptionEnabled').then( (value) => logic.developerOptionEnabled.value = (value.toString() == "true")); FlutterForegroundTask.isRunningService.then((value) => { if (!value) {logic.inProgress.value = false, logic.link.value = ""} }); return Material( child: Padding( padding: const EdgeInsets.only(left: 20, right: 20), child: Obx( () => Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'connect.guide.prepare_guide', style: TextStyle(fontSize: 20), ).tr(), const SizedBox(height: 20), BrnBigMainButton( title: logic.inProgress.value ? tr('connect.guide.in_progress') : tr('connect.guide.connect'), bgColor: Colors.blueAccent.withOpacity(0.8), isEnable: ((logic.developerOptionEnabled.value && GlobalState.hasCert.value) && !logic.inProgress.value), onTap: () { doConnect(); }, ), const SizedBox(height: 20), BrnBigMainButton( title: tr('connect.guide.reset'), bgColor: Colors.orangeAccent.withOpacity(0.8), onTap: () { doResetProcess(); }, ), const SizedBox(height: 20), Visibility( visible: GlobalState.rootEnabled.value, child: BrnBigMainButton( title: logic.inProgress.value ? tr('connect.guide.in_progress') : tr('connect.guide.root_connect'), bgColor: Colors.blueAccent.withOpacity(0.8), isEnable: (GlobalState.rootEnabled.value && !logic.inProgress.value), onTap: () { doRootConnect(); }, ), ), Visibility( visible: GlobalState.shizukuEnabled.value, child: BrnBigMainButton( title: logic.inProgress.value ? tr('connect.guide.in_progress') : tr('connect.guide.shizuku_connect'), bgColor: Colors.blueAccent.withOpacity(0.8), isEnable: (GlobalState.shizukuEnabled.value && !logic.inProgress.value), onTap: () { doShizukuConnect(); }, ), ) ], ), )), ); } } ================================================ FILE: lib/pages/home/logic.dart ================================================ import 'package:get/get.dart'; class HomeLogic extends GetxController { Rx developerOptionEnabled = false.obs; } ================================================ FILE: lib/pages/home/view.dart ================================================ import 'package:ascent/global_state.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:url_launcher/url_launcher.dart'; import 'logic.dart'; class HomePage extends StatelessWidget { HomePage({super.key}); final logic = Get.put(HomeLogic()); @override Widget build(BuildContext context) { GlobalState.platform.invokeMethod('getDeveloperOptionEnabled').then( (value) => logic.developerOptionEnabled.value = (value.toString() == "true")); return Material( child: Padding( padding: const EdgeInsets.only(left: 20, right: 20), child: Obx(() => Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.developer_option.status", style: TextStyle(fontSize: 20), ).tr(), logic.developerOptionEnabled.value ? const Text( "home.developer_option.enabled", style: TextStyle( color: Colors.lightGreenAccent, fontSize: 20), ).tr() : const Text( "home.developer_option.disabled", style: TextStyle( color: Colors.redAccent, fontSize: 20), ).tr(), ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.pairing.status", style: TextStyle(fontSize: 20), ).tr(), GlobalState.hasCert.value ? const Text( "home.pairing.paired", style: TextStyle( color: Colors.lightGreenAccent, fontSize: 20), ).tr() : const Text( "home.pairing.wait_pairing", style: TextStyle( color: Colors.redAccent, fontSize: 20), ).tr(), ], ), const SizedBox( height: 20, ), Visibility( visible: GlobalState.rootEnabled.value, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.root.enabled", style: TextStyle( fontSize: 20, color: Colors.lightGreenAccent, fontWeight: FontWeight.w500, ), ).tr(), ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.root.direct_connect", style: TextStyle( fontSize: 20, color: Colors.deepOrangeAccent, fontWeight: FontWeight.w500, ), ).tr(), ], ), const SizedBox( height: 20, ), ], )), Visibility( visible: GlobalState.shizukuEnabled.value, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.shizuku.enabled", style: TextStyle( fontSize: 20, color: Colors.lightGreenAccent, fontWeight: FontWeight.w500, ), ).tr(), ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "home.shizuku.direct_connect", style: TextStyle( fontSize: 20, color: Colors.deepOrangeAccent, fontWeight: FontWeight.w500, ), ).tr(), ], ), const SizedBox( height: 20, ), ], )), BrnBigMainButton( title: tr('home.pairing.name'), bgColor: Colors.cyan.withOpacity(0.8), isEnable: (logic.developerOptionEnabled.value && !GlobalState.hasCert.value), onTap: () { Get.toNamed("/pair"); }, ), const SizedBox( height: 20, ), BrnBigMainButton( title: tr('home.connect.name'), bgColor: Colors.indigoAccent.withOpacity(0.8), isEnable: ((logic.developerOptionEnabled.value && GlobalState.hasCert.value) || GlobalState.rootEnabled.value || GlobalState.shizukuEnabled.value), onTap: () { Get.toNamed("/connect"); }, ), const SizedBox( height: 40, ), BrnBigGhostButton( title: tr('home.star'), onTap: () async { final Uri url = Uri.parse("https://github.com/4o3F"); if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { await launchUrl(url); } }, ), const SizedBox( height: 20, ), BrnBigGhostButton( bgColor: Colors.orangeAccent.withOpacity(0.8), titleColor: Colors.white, title: tr('home.support'), onTap: () async { final Uri url = Uri.parse(GlobalState.discord); if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { await launchUrl(url); } }, ), ], )), ), ); } } ================================================ FILE: lib/pages/info/logic.dart ================================================ import 'package:get/get.dart'; class InfoLogic extends GetxController {} ================================================ FILE: lib/pages/info/view.dart ================================================ import 'dart:io'; import 'package:ascent/global_state.dart'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:get/get.dart'; import 'package:path_provider/path_provider.dart'; import 'logic.dart'; class InfoPage extends StatelessWidget { InfoPage({super.key}); final logic = Get.put(InfoLogic()); @override Widget build(BuildContext context) { return Material( child: Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 100, height: 100, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( borderRadius: BorderRadius.circular(50), ), child: Image.network( "https://0.gravatar.com/avatar/3915902215ca977d6e1e82f82540cf1aab004717f087e996cb5ffaab43a8c681?size=1024", fit: BoxFit.cover, ), ), const SizedBox( width: 20, ), const Text( "403F", style: TextStyle(fontSize: 30), ), ], ), const SizedBox( height: 20, ), const Text( "Source code at ", style: TextStyle(fontSize: 15), ), const Text( "https://github.com/4o3F/Ascent", style: TextStyle(fontSize: 15, color: Colors.indigoAccent), ), const SizedBox( height: 20, ), const Text( "Version: ${GlobalState.version}", style: TextStyle(fontSize: 15, color: Colors.orangeAccent), ), const SizedBox( height: 20, ), const Text( "Contact me", style: TextStyle(fontSize: 15), ), const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("Email: "), Text("4o3f@proton.me", style: TextStyle(color: Colors.blueAccent)), ], ), const SizedBox( height: 10, ), const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("Discord: "), Text("403F", style: TextStyle(color: Colors.blueAccent)), ], ), const SizedBox( height: 10, ), const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("QQ: "), Text("855857816", style: TextStyle(color: Colors.blueAccent)), ], ), const SizedBox( height: 10, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("settings.disable_auto_detect_port").tr(), Obx(() => Switch( value: GlobalState.disableAutoDetectPort.value, onChanged: (bool value) async { var dataDir = await getApplicationDocumentsDirectory(); GlobalState.disableAutoDetectPort.value = value; if (value) { File("${dataDir.path}/disableAutoDetectPort") .createSync(); } else { File("${dataDir.path}/disableAutoDetectPort").deleteSync(); } })) ], ) ], ), )); } } ================================================ FILE: lib/pages/pair/logic.dart ================================================ import 'package:get/get.dart'; class PairLogic extends GetxController { Rx developerOptionEnabled = false.obs; Rx foregroundServiceStartResult = true.obs; } ================================================ FILE: lib/pages/pair/view.dart ================================================ import 'dart:io'; import 'package:android_intent_plus/android_intent.dart'; import 'package:ascent/global_state.dart'; import 'package:bruno/bruno.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../foreground/pair.dart'; import 'logic.dart'; class PairPage extends StatelessWidget { PairPage({super.key}); final logic = Get.put(PairLogic()); PairForegroundTask pairForegroundTask = PairForegroundTask(); Future doPair() async { // Call out developer option intent AndroidIntent intent = const AndroidIntent( action: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS', ); bool result = await pairForegroundTask.startPairForegroundTask(); if (!result) { logic.foregroundServiceStartResult.value = false; } await intent.launch(); } Future resetPair() async { File("${GlobalState.dataDir.path}/cert.pem").deleteSync(); File("${GlobalState.dataDir.path}/pkey.pem").deleteSync(); GlobalState.hasCert.value = false; } @override Widget build(BuildContext context) { // GlobalState.hasCert.value = // File("${GlobalState.dataDir.path}/cert.pem").existsSync(); GlobalState.platform.invokeMethod('getDeveloperOptionEnabled').then( (value) => logic.developerOptionEnabled.value = (value.toString() == "true")); logic.foregroundServiceStartResult.listen((result) { if (!result) { BrnToast.showInCenter( text: tr('pair.notification_description.error_init'), context: context); } }); return Material( child: Padding( padding: const EdgeInsets.only(left: 20, right: 20), child: Obx( () => Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ const Text( 'pair.guide.prepare_guide', style: TextStyle(fontSize: 20), ).tr(), const SizedBox( height: 20, ), BrnBigMainButton( title: tr('pair.guide.pair'), bgColor: Colors.indigoAccent.withOpacity(0.8), isEnable: (logic.developerOptionEnabled.value && !GlobalState.hasCert.value), onTap: () { doPair(); }, ), const SizedBox( height: 20, ), BrnBigMainButton( title: tr('pair.guide.reset'), bgColor: Colors.orangeAccent.withOpacity(0.8), isEnable: (logic.developerOptionEnabled.value && GlobalState.hasCert.value), onTap: () { resetPair(); }, ), ], ), ), ), ); } } ================================================ FILE: lib/routes.dart ================================================ import 'package:ascent/pages/connect/view.dart'; import 'package:ascent/pages/home/view.dart'; import 'package:ascent/pages/info/view.dart'; import 'package:ascent/pages/pair/view.dart'; import 'package:get/get.dart'; class Routes { static const String defaultRoute = "/home"; static final List routes = [ GetPage(name: '/home', page: () => HomePage()), GetPage(name: '/pair', page: () => PairPage()), GetPage(name: '/connect', page: () => ConnectPage()), GetPage(name: '/info', page: () => InfoPage()), ]; static int route2index(String route) { switch (route) { case '/home': return 0; case '/pair': return 1; case '/connect': return 2; case '/info': return 3; default: return 0; } } static String index2route(int index) { switch (index) { case 0: return '/home'; case 1: return '/pair'; case 2: return '/connect'; case 3: return '/info'; default: return '/home'; } } } ================================================ FILE: pubspec.yaml ================================================ name: ascent description: Tool for mihoyo game gacha link retrival # The following line prevents the package from being accidentally published to # pub.dev using `flutter pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. version: 2.4.0 environment: sdk: '>=3.3.0 <4.0.0' # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions # consider running `flutter pub upgrade --major-versions`. Alternatively, # dependencies can be manually updated by changing the version numbers below to # the latest version available on pub.dev. To see which dependencies have newer # versions available, run `flutter pub outdated`. dependencies: flutter: sdk: flutter bruno: 3.4.3 get: ^4.6.6 path_provider: ^2.1.1 easy_localization: ^3.0.3 flutter_foreground_task: git: url: https://github.com/4o3F/flutter_foreground_task # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 freezed_annotation: ^2.4.1 multicast_dns: ^0.3.2+5 android_intent_plus: ^5.2.2 mixpanel_flutter: ^2.2.0 url_launcher: ^6.2.1 uri_to_file: ^1.0.0 receive_intent: git: url: https://github.com/daadu/receive_intent ref: master http: ^1.1.0 pub_semver: ^2.1.4 root: ^2.0.4 rust_lib_ascent: path: rust_builder flutter_rust_bridge: 2.11.1 shizuku_api: ^1.2.1 dev_dependencies: flutter_test: sdk: flutter # The "flutter_lints" package below contains a set of recommended lints to # encourage good coding practices. The lint set provided by the package is # activated in the `analysis_options.yaml` file located at the root of your # package. See that file for information about deactivating specific lint # rules and activating additional ones. flutter_lints: ^5.0.0 build_runner: ^2.4.6 freezed: ^2.4.5 integration_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter packages. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg assets: - assets/translations/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages dependency_overrides: intl: 0.19.0 shared_preferences_android: 2.4.10 ================================================ FILE: rust/.cargo/config.toml ================================================ #[env] #CC = { value = "D:\\Applications\\LLVM\\bin\\clang-cl.exe", force = true } #CMAKE_CXX_COMPILER = { value = "D:\\Applications\\LLVM\\bin\\clang-cl.exe", force = true } #CMAKE_C_COMPILER = { value = "D:\\Applications\\LLVM\\bin\\clang-cl.exe", force = true } #CMAKE_GENERATOR = { value = "Ninja", force = true } #CXX = { value = "D:\\Applications\\LLVM\\bin\\clang-cl.exe", force = true } ================================================ FILE: rust/.gitignore ================================================ /target ================================================ FILE: rust/Cargo.toml ================================================ [package] name = "rust_lib_ascent" version = "2.4.0" edition = "2021" [dependencies] flutter_rust_bridge = "=2.11.1" anyhow = { version = "1.0.75" } bytebuffer = "2.2.0" hex = "0.4.3" hkdf = "0.12.3" spake2 = "0.4.0" tokio = { version = "1.34.0", features = ["full"] } sha2 = "0.10.8" boring = { git = "https://github.com/4o3F/boring.git" } tokio-boring = { git = "https://github.com/4o3F/boring.git" } log = "0.4.20" regex = { version = "1.10.2", features = [] } android_logger = "0.13.3" [lib] crate-type = ["cdylib", "staticlib"] [profile.release] lto = true opt-level = "z" codegen-units = 1 ================================================ FILE: rust/src/api/api.rs ================================================ use std::{env, fs}; use android_logger::Config; use anyhow::Result; use log::{debug, LevelFilter}; use regex::Regex; use tokio::runtime::Runtime; use crate::{connect, pair}; pub fn do_pair(port: String, code: String, data_folder: String) -> Result { debug!("Do pair native called"); let rt = Runtime::new().unwrap(); rt.block_on(async { pair::pair(port, code, data_folder).await }) } pub fn do_connect(port: String, data_folder: String) -> Result { debug!("Do connect native called"); let rt = Runtime::new().unwrap(); rt.block_on(async { connect::connect(port, data_folder).await }) } pub fn do_filter(file_path: String) -> Result { let rt = Runtime::new().unwrap(); rt.block_on(async { let bytes = fs::read(file_path).unwrap(); let data = String::from_utf8_lossy(bytes.as_slice()).to_string(); let re = Regex::new(r"https://(webstatic|hk4e-api|webstatic-sea|hk4e-api-os|api-takumi|api-os-takumi|gs|public-operation-hk4e).(mihoyo\.com|hoyoverse\.com).*authkey=.*\s*.*game_biz.*(plat_type|#/log)").unwrap(); let matches = re.find(data.as_str()).unwrap(); let data = String::from(matches.as_str()); let mut front_half: String = String::new(); let mut back_half: String = String::new(); for (_, c) in data.chars().enumerate() { if !c.is_ascii_alphanumeric() && !c.is_ascii_punctuation() { break; } front_half.push(c); } for (_, c) in data.chars().rev().enumerate() { if !c.is_ascii_alphanumeric() && !c.is_ascii_punctuation() { break; } back_half.push(c); } //reverse back_half back_half = back_half.chars().rev().collect(); let result = front_half + back_half.as_str(); Ok(result) }) } pub fn init_logger() { env::set_var("RUST_BACKTRACE", "1"); if cfg!(debug_assertions) { android_logger::init_once( Config::default().with_max_level(LevelFilter::Trace).with_tag("flutter_native"), ); } else { android_logger::init_once( Config::default().with_max_level(LevelFilter::Error).with_tag("flutter_native"), ); } } ================================================ FILE: rust/src/api/mod.rs ================================================ pub mod api; ================================================ FILE: rust/src/connect.rs ================================================ use std::io::Read; use anyhow::{anyhow, Context, Result}; use log::debug; use tokio::io::{AsyncReadExt, AsyncWriteExt}; const ADB_HEADER_LENGTH: usize = 24; const SYSTEM_IDENTITY_STRING_HOST: &str = "host::\u{0}"; const A_CNXN: i32 = 0x4e584e43; const A_OPEN: i32 = 0x4e45504f; const A_OKAY: i32 = 0x59414b4f; const A_WRTE: i32 = 0x45545257; const A_STLS: i32 = 0x534c5453; // wireless debug introduced in Android 11, so must use TLS const A_VERSION: i32 = 0x01000001; const MAX_PAYLOAD: i32 = 1024 * 1024; const A_STLS_VERSION: i32 = 0x01000000; struct Message { command: u32, _arg0: u32, _arg1: u32, data_length: u32, _data_check: u32, _magic: u32, } impl Message { fn parse(buffer: &mut bytebuffer::ByteBuffer) -> Message { Message { command: buffer.read_u32().unwrap(), _arg0: buffer.read_u32().unwrap(), _arg1: buffer.read_u32().unwrap(), data_length: buffer.read_u32().unwrap(), _data_check: buffer.read_u32().unwrap(), _magic: buffer.read_u32().unwrap(), } } } fn get_payload_checksum(data: Vec, offset: i32, length: i32) -> i32 { let mut checksum: i32 = 0; for i in offset..(offset + length) { checksum += (data[i as usize] & 0xFF) as i32; } checksum } fn generate_message(command: i32, arg0: i32, arg1: i32, data: Vec) -> bytebuffer::ByteBuffer { let mut message = bytebuffer::ByteBuffer::new(); message.resize(ADB_HEADER_LENGTH + data.len()); message.set_endian(bytebuffer::Endian::LittleEndian); message.write_i32(command); message.write_i32(arg0); message.write_i32(arg1); if data.len() != 0 { message.write_i32(data.len() as i32); message.write_i32(get_payload_checksum(data.clone(), 0, data.len() as i32)); } else { message.write_i32(0); message.write_i32(0); } message.write_i32(!command); if data.len() != 0 { message.write_bytes(data.as_slice()); } message } pub async fn connect(port: String, data_folder: String) -> Result { let host = String::from("127.0.0.1:") + port.as_str(); let host = host.as_str(); debug!("Connecting {}",host); let mut stream = tokio::net::TcpStream::connect(host).await.with_context(|| format!("TCP connection to {} failed", host))?; let link: String; // Send CNXN first { let cnxn_message = generate_message( A_CNXN, A_VERSION, MAX_PAYLOAD, Vec::from(SYSTEM_IDENTITY_STRING_HOST.as_bytes()), ); stream.write_all(cnxn_message.as_bytes()).await.with_context(|| format!("Send CNXN"))?; debug!("CNXN Sent"); } // Read STLS command { let mut message_raw = vec![0u8; ADB_HEADER_LENGTH]; stream.read_exact(message_raw.as_mut_slice()).await.with_context(|| format!("Read STLS"))?; let mut header = bytebuffer::ByteBuffer::from_vec(message_raw); // CNXN header header.resize(ADB_HEADER_LENGTH); header.set_endian(bytebuffer::Endian::LittleEndian); let message = Message::parse(&mut header); if message.command != A_STLS as u32 { return Err(anyhow!("Not STLS command")); } debug!("STLS Received") } // Send STLS packet { let stls_message = generate_message(A_STLS, A_STLS_VERSION, 0, Vec::new()); stream.write_all(stls_message.as_bytes()).await.with_context(|| format!("Send STLS"))?; debug!("STLS Sent") } debug!("TLS Handshake begin"); let data_folder = data_folder; let cert_path = data_folder.clone() + "/cert.pem"; let pkey_path = data_folder.clone() + "/pkey.pem"; let cert_path = std::path::Path::new(cert_path.as_str()); let pkey_path = std::path::Path::new(pkey_path.as_str()); // Load cert and pkey from file let cert_file = std::fs::File::open(cert_path)?; let pkey_file = std::fs::File::open(pkey_path)?; let x509_raw: Vec = cert_file.bytes().map(|x| x.unwrap()).collect(); let x509_raw = x509_raw.as_slice(); let pkey_raw: Vec = pkey_file.bytes().map(|x| x.unwrap()).collect(); let pkey_raw = pkey_raw.as_slice(); let x509 = Some(boring::x509::X509::from_pem(x509_raw).unwrap()); let pkey = Some(boring::pkey::PKey::private_key_from_pem(pkey_raw).unwrap()); let method = boring::ssl::SslMethod::tls(); let mut connector = boring::ssl::SslConnector::builder(method).unwrap(); connector.set_verify(boring::ssl::SslVerifyMode::PEER); connector.set_certificate(x509.clone().unwrap().as_ref()).unwrap(); connector.set_private_key(pkey.clone().unwrap().as_ref()).unwrap(); connector.set_options(boring::ssl::SslOptions::NO_TLSV1); connector.set_options(boring::ssl::SslOptions::NO_TLSV1_2); connector.set_options(boring::ssl::SslOptions::NO_TLSV1_1); connector.set_keylog_callback(move |_, line| { debug!("{}", line); }); let mut config = connector.build().configure().unwrap(); //config.set_verify_hostname(false); config.set_use_server_name_indication(false); config.set_verify_callback(boring::ssl::SslVerifyMode::PEER, |_, _| { return true; }); let mut stream = tokio_boring::connect(config, host, stream).await.with_context(|| format!("Open TLS stream"))?; debug!("TLS Handshake success"); // Read CNXN { let mut message_raw = vec![0u8; ADB_HEADER_LENGTH]; match stream.read_exact(message_raw.as_mut_slice()).await.with_context(|| format!("Read CNXN header")) { Ok(_) => {} Err(e) => { debug!("Read CNXN header failed: {:?}", e.source().unwrap().to_string()); if e.source().unwrap().to_string().contains("SSLV3_ALERT_CERTIFICATE_UNKNOWN") { return Err(anyhow!("error.pair_cert_invalid")); } return Err(anyhow!("Read CNXN header failed \n {}", e.root_cause())); } } let mut header = bytebuffer::ByteBuffer::from_vec(message_raw); // CNXN header header.resize(ADB_HEADER_LENGTH); header.set_endian(bytebuffer::Endian::LittleEndian); let message = Message::parse(&mut header); debug!("CNXN Received"); let mut data_raw = vec![0u8; message.data_length as usize]; stream.read_exact(data_raw.as_mut_slice()).await.with_context(|| format!("Read CNXN"))?; let data = String::from_utf8(data_raw).with_context(|| format!("Parse CNXN data"))?; debug!("CNXN data: {}", data) } // Send OPEN { let shell_cmd = "shell:setprop log.tag I && logcat -b all -c && logcat | grep -E 'https://(webstatic|hk4e-api|webstatic-sea|hk4e-api-os|api-takumi|api-os-takumi|gs|public-operation-hk4e|aki-gm-resources-oversea).(mihoyo\\.com|hoyoverse\\.com|aki-game\\.net|aki-game\\.com)' | grep -i 'gacha'\u{0}"; let open_message = generate_message(A_OPEN, 233, 0, Vec::from(shell_cmd.as_bytes())); stream.write_all(open_message.as_bytes()).await.with_context(|| format!("Send OPEN"))?; debug!("OPEN Sent"); } // Read OKAY { let mut message_raw = vec![0u8; ADB_HEADER_LENGTH]; stream.read_exact(message_raw.as_mut_slice()).await.with_context(|| format!("Read OKAY"))?; let mut header = bytebuffer::ByteBuffer::from_vec(message_raw); header.resize(ADB_HEADER_LENGTH); header.set_endian(bytebuffer::Endian::LittleEndian); let message = Message::parse(&mut header); if message.command != A_OKAY as u32 { return Err(anyhow!("Not OKAY command")); } debug!("OKAY Received"); } // Read WRTE { let mut message_raw = vec![0u8; ADB_HEADER_LENGTH]; stream.read_exact(message_raw.as_mut_slice()).await.with_context(|| format!("Read WRTE header"))?; let mut header = bytebuffer::ByteBuffer::from_vec(message_raw); header.resize(ADB_HEADER_LENGTH); header.set_endian(bytebuffer::Endian::LittleEndian); let message = Message::parse(&mut header); if message.command != A_WRTE as u32 { return Err(anyhow!("Not WRTE command")); } debug!("WRTE Received"); let mut data_raw = vec![0u8; message.data_length as usize]; stream.read_exact(data_raw.as_mut_slice()).await.with_context(|| format!("Read WRTE"))?; link = String::from_utf8(data_raw).with_context(|| format!("Parse WRTE string"))?; debug!("WRTE data: {}", link) } // Send OKAY { let okay_message = generate_message(A_OKAY, 233, 0, Vec::new()); stream.write_all(okay_message.as_bytes()).await.with_context(|| format!("Send OKAY"))?; debug!("OKAY Sent"); } stream.flush().await.with_context(|| format!("Flush stream"))?; stream.shutdown().await.with_context(|| format!("Shutdown stream"))?; Ok(link) } ================================================ FILE: rust/src/frb_generated.io.rs ================================================ // This file is automatically generated, so please do not edit it. // Generated by `flutter_rust_bridge`@ 2.0.0-dev.32. // Section: imports use super::*; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use flutter_rust_bridge::for_generated::transform_result_dco; use flutter_rust_bridge::{Handler, IntoIntoDart}; // Section: boilerplate flutter_rust_bridge::frb_generated_boilerplate_io!(); ================================================ FILE: rust/src/frb_generated.rs ================================================ // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. #![allow( non_camel_case_types, unused, non_snake_case, clippy::needless_return, clippy::redundant_closure_call, clippy::redundant_closure, clippy::useless_conversion, clippy::unit_arg, clippy::unused_unit, clippy::double_parens, clippy::let_and_return, clippy::too_many_arguments, clippy::match_single_binding, clippy::clone_on_copy, clippy::let_unit_value, clippy::deref_addrof, clippy::explicit_auto_deref, clippy::borrow_deref_ref, clippy::needless_borrow )] // Section: imports use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; use flutter_rust_bridge::{Handler, IntoIntoDart}; // Section: boilerplate flutter_rust_bridge::frb_generated_boilerplate!( default_stream_sink_codec = SseCodec, default_rust_opaque = RustOpaqueMoi, default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.11.1"; pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -637951497; // Section: executor flutter_rust_bridge::frb_generated_default_handler!(); // Section: wire_funcs fn wire__crate__api__api__do_connect_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { debug_name: "do_connect", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( ptr_, rust_vec_len_, data_len_, ) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_port = ::sse_decode(&mut deserializer); let api_data_folder = ::sse_decode(&mut deserializer); deserializer.end(); move |context| { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || { let output_ok = crate::api::api::do_connect(api_port, api_data_folder)?; Ok(output_ok) })(), ) } }, ) } fn wire__crate__api__api__do_filter_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { debug_name: "do_filter", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( ptr_, rust_vec_len_, data_len_, ) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_file_path = ::sse_decode(&mut deserializer); deserializer.end(); move |context| { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || { let output_ok = crate::api::api::do_filter(api_file_path)?; Ok(output_ok) })(), ) } }, ) } fn wire__crate__api__api__do_pair_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { debug_name: "do_pair", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( ptr_, rust_vec_len_, data_len_, ) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_port = ::sse_decode(&mut deserializer); let api_code = ::sse_decode(&mut deserializer); let api_data_folder = ::sse_decode(&mut deserializer); deserializer.end(); move |context| { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || { let output_ok = crate::api::api::do_pair(api_port, api_code, api_data_folder)?; Ok(output_ok) })(), ) } }, ) } fn wire__crate__api__api__init_logger_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { debug_name: "init_logger", port: Some(port_), mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( ptr_, rust_vec_len_, data_len_, ) }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); deserializer.end(); move |context| { transform_result_sse::<_, ()>((move || { let output_ok = Result::<_, ()>::Ok({ crate::api::api::init_logger(); })?; Ok(output_ok) })()) } }, ) } // Section: dart2rust impl SseDecode for flutter_rust_bridge::for_generated::anyhow::Error { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut inner = ::sse_decode(deserializer); return flutter_rust_bridge::for_generated::anyhow::anyhow!("{}", inner); } } impl SseDecode for String { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut inner = >::sse_decode(deserializer); return String::from_utf8(inner).unwrap(); } } impl SseDecode for bool { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { deserializer.cursor.read_u8().unwrap() != 0 } } impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut len_ = ::sse_decode(deserializer); let mut ans_ = vec![]; for idx_ in 0..len_ { ans_.push(::sse_decode(deserializer)); } return ans_; } } impl SseDecode for u8 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { deserializer.cursor.read_u8().unwrap() } } impl SseDecode for () { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {} } impl SseDecode for i32 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { deserializer.cursor.read_i32::().unwrap() } } fn pde_ffi_dispatcher_primary_impl( func_id: i32, port: flutter_rust_bridge::for_generated::MessagePort, ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len: i32, data_len: i32, ) { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { 1 => wire__crate__api__api__do_connect_impl(port, ptr, rust_vec_len, data_len), 2 => wire__crate__api__api__do_filter_impl(port, ptr, rust_vec_len, data_len), 3 => wire__crate__api__api__do_pair_impl(port, ptr, rust_vec_len, data_len), 4 => wire__crate__api__api__init_logger_impl(port, ptr, rust_vec_len, data_len), _ => unreachable!(), } } fn pde_ffi_dispatcher_sync_impl( func_id: i32, ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len: i32, data_len: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { _ => unreachable!(), } } // Section: rust2dart impl SseEncode for flutter_rust_bridge::for_generated::anyhow::Error { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(format!("{:?}", self), serializer); } } impl SseEncode for String { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { >::sse_encode(self.into_bytes(), serializer); } } impl SseEncode for bool { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { serializer.cursor.write_u8(self as _).unwrap(); } } impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.len() as _, serializer); for item in self { ::sse_encode(item, serializer); } } } impl SseEncode for u8 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { serializer.cursor.write_u8(self).unwrap(); } } impl SseEncode for () { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {} } impl SseEncode for i32 { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { serializer.cursor.write_i32::(self).unwrap(); } } #[cfg(not(target_family = "wasm"))] mod io { // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // Section: imports use super::*; use flutter_rust_bridge::for_generated::byteorder::{ NativeEndian, ReadBytesExt, WriteBytesExt, }; use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; use flutter_rust_bridge::{Handler, IntoIntoDart}; // Section: boilerplate flutter_rust_bridge::frb_generated_boilerplate_io!(); } #[cfg(not(target_family = "wasm"))] pub use io::*; /// cbindgen:ignore #[cfg(target_family = "wasm")] mod web { // This file is automatically generated, so please do not edit it. // @generated by `flutter_rust_bridge`@ 2.11.1. // Section: imports use super::*; use flutter_rust_bridge::for_generated::byteorder::{ NativeEndian, ReadBytesExt, WriteBytesExt, }; use flutter_rust_bridge::for_generated::wasm_bindgen; use flutter_rust_bridge::for_generated::wasm_bindgen::prelude::*; use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; use flutter_rust_bridge::{Handler, IntoIntoDart}; // Section: boilerplate flutter_rust_bridge::frb_generated_boilerplate_web!(); } #[cfg(target_family = "wasm")] pub use web::*; ================================================ FILE: rust/src/frb_generated.web.rs ================================================ // This file is automatically generated, so please do not edit it. // Generated by `flutter_rust_bridge`@ 2.0.0-dev.32. // Section: imports use super::*; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use flutter_rust_bridge::for_generated::transform_result_dco; use flutter_rust_bridge::for_generated::wasm_bindgen; use flutter_rust_bridge::for_generated::wasm_bindgen::prelude::*; use flutter_rust_bridge::{Handler, IntoIntoDart}; // Section: boilerplate flutter_rust_bridge::frb_generated_boilerplate_web!(); ================================================ FILE: rust/src/lib.rs ================================================ pub mod api; pub mod pair; pub mod connect; mod frb_generated; /* AUTO INJECTED BY flutter_rust_bridge. This line may not be accurate, and you can change it according to your needs. */ ================================================ FILE: rust/src/pair.rs ================================================ use std::io::Write; use anyhow::{anyhow, bail, Context, Result}; use log::debug; use tokio::io::{AsyncReadExt, AsyncWriteExt}; const EXPORTED_KEY_LABEL: &str = "adb-label\u{0}"; pub const CLIENT_NAME: &str = "adb pair client\u{0}"; pub const SERVER_NAME: &str = "adb pair server\u{0}"; pub const MAX_PEER_INFO_SIZE: i32 = 1 << 13; const ANDROID_PUBKEY_MODULUS_SIZE: i32 = 2048 / 8; const ANDROID_PUBKEY_ENCODED_SIZE: i32 = 3 * 4 + 2 * ANDROID_PUBKEY_MODULUS_SIZE; const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: i32 = ANDROID_PUBKEY_MODULUS_SIZE / 4; fn generate_cert() -> Result<(boring::x509::X509, boring::pkey::PKey)> { let rsa = boring::rsa::Rsa::generate(2048).with_context(|| format!("failed to generate rsa keypair"))?; // put it into the pkey struct let pkey = boring::pkey::PKey::from_rsa(rsa).with_context(|| format!("failed to create pkey struct from rsa keypair"))?; // make a new x509 certificate with the pkey we generated let mut x509builder = boring::x509::X509::builder().with_context(|| format!("failed to make x509 builder"))?; x509builder .set_version(2) .with_context(|| format!("failed to set x509 version"))?; // set the serial number to some big random positive integer let mut serial = boring::bn::BigNum::new().with_context(|| format!("failed to make new bignum"))?; serial .rand(32, boring::bn::MsbOption::ONE, false) .with_context(|| format!("failed to generate random bignum"))?; let serial = serial .to_asn1_integer() .with_context(|| format!("failed to get asn1 integer from bignum"))?; x509builder .set_serial_number(&serial) .with_context(|| format!("failed to set x509 serial number"))?; // call fails without expiration dates // I guess they are important anyway, but still let not_before = boring::asn1::Asn1Time::days_from_now(0).with_context(|| format!("failed to parse 'notBefore' timestamp"))?; let not_after = boring::asn1::Asn1Time::days_from_now(360) .with_context(|| format!("failed to parse 'notAfter' timestamp"))?; x509builder .set_not_before(¬_before) .with_context(|| format!("failed to set x509 start date"))?; x509builder .set_not_after(¬_after) .with_context(|| format!("failed to set x509 expiration date"))?; // add the issuer and subject name // it's set to "/CN=LinuxTransport" // if we want we can make that configurable later let mut x509namebuilder = boring::x509::X509Name::builder().with_context(|| format!("failed to get x509name builder"))?; x509namebuilder .append_entry_by_text("CN", "LinuxTransport") .with_context(|| format!("failed to append /CN=LinuxTransport to x509name builder"))?; let x509name = x509namebuilder.build(); x509builder .set_issuer_name(&x509name) .with_context(|| format!("failed to set x509 issuer name"))?; x509builder .set_subject_name(&x509name) .with_context(|| format!("failed to set x509 subject name"))?; // set the public key x509builder .set_pubkey(&pkey) .with_context(|| format!("failed to set x509 pubkey"))?; // it also needs several extensions // in the openssl configuration file, these are set when generating certs // basicConstraints=CA:true // subjectKeyIdentifier=hash // authorityKeyIdentifier=keyid:always,issuer // that means these extensions get added to certs generated using the // command line tool automatically. but since we are constructing it, we // need to add them manually. // we need to do them one at a time, and they need to be in this order // let conf = boring::conf::Conf::new(boring::conf::ConfMethod::).with_context(|| format!("failed to make new conf struct"))?; // it seems like everything depends on the basic constraints, so let's do // that first. let bc = boring::x509::extension::BasicConstraints::new() .ca() .build() .with_context(|| format!("failed to build BasicConstraints extension"))?; x509builder .append_extension(bc) .with_context(|| format!("failed to append BasicConstraints extension"))?; // the akid depends on the skid. I guess it copies the skid when the cert is // self-signed or something, I'm not really sure. let skid = { // we need to wrap these in a block because the builder gets borrowed away // from us let ext_con = x509builder.x509v3_context(None, None); boring::x509::extension::SubjectKeyIdentifier::new() .build(&ext_con) .with_context(|| format!("failed to build SubjectKeyIdentifier extention"))? }; x509builder .append_extension(skid) .with_context(|| format!("failed to append SubjectKeyIdentifier extention"))?; // now that the skid is added we can add the akid let akid = { let ext_con = x509builder.x509v3_context(None, None); boring::x509::extension::AuthorityKeyIdentifier::new() .keyid(true) .issuer(false) .build(&ext_con) .with_context(|| format!("failed to build AuthorityKeyIdentifier extention"))? }; x509builder .append_extension(akid) .with_context(|| format!("failed to append AuthorityKeyIdentifier extention"))?; // self-sign the certificate x509builder .sign(&pkey, boring::hash::MessageDigest::sha256()) .with_context(|| format!("failed to self-sign x509 cert"))?; let x509 = x509builder.build(); Ok((x509, pkey)) } fn big_endian_to_little_endian_padded(len: usize, num: boring::bn::BigNum) -> Result, anyhow::Error> { let mut out = vec![0u8; len]; let bytes = swap_endianness(num.to_vec()); let mut num_bytes = bytes.len(); if len < num_bytes { if !fit_in_bytes(bytes.as_ref(), num_bytes, len) { return Err(anyhow!("Can't fit in bytes")); } num_bytes = len; } out[..num_bytes].copy_from_slice(&bytes[..num_bytes]); return Ok(out); } fn fit_in_bytes(bytes: &Vec, num_bytes: usize, len: usize) -> bool { let mut mask = 0u8; for i in len..num_bytes { mask |= bytes[i]; } return mask == 0; } fn swap_endianness(bytes: Vec) -> Vec { bytes.into_iter().rev().collect() } pub fn encode_rsa_publickey(public_key: boring::rsa::Rsa) -> Result, anyhow::Error> { let mut r32: boring::bn::BigNum; let mut n0inv: boring::bn::BigNum; let mut rr: boring::bn::BigNum; let mut tmp: boring::bn::BigNum; let mut ctx = boring::bn::BigNumContext::new()?; if (public_key.n().to_vec().len() as i32) < ANDROID_PUBKEY_MODULUS_SIZE { return Err(anyhow!(String::from("Invalid key length ") + public_key.n().to_vec().len().to_string().as_str())); } let mut key_struct = bytebuffer::ByteBuffer::new(); key_struct.resize(ANDROID_PUBKEY_ENCODED_SIZE as usize); key_struct.set_endian(bytebuffer::Endian::LittleEndian); key_struct.write_i32(ANDROID_PUBKEY_MODULUS_SIZE_WORDS); // Compute and store n0inv = -1 / N[0] mod 2 ^ 32 r32 = boring::bn::BigNum::new()?; r32.set_bit(32)?; n0inv = public_key.n().to_owned()?; tmp = n0inv.to_owned()?; // do n0inv mod r32 n0inv.checked_rem(tmp.as_mut(), r32.as_ref(), ctx.as_mut())?; tmp = n0inv.to_owned()?; n0inv.mod_inverse(tmp.as_mut(), r32.as_ref(), ctx.as_mut())?; tmp = n0inv.to_owned()?; n0inv.checked_sub(r32.as_ref(), tmp.as_mut())?; // This is hacky..... key_struct.write_u32(n0inv.to_dec_str().unwrap().parse::().unwrap()); key_struct.write(big_endian_to_little_endian_padded( ANDROID_PUBKEY_MODULUS_SIZE as usize, public_key.n().to_owned().unwrap()) .unwrap().as_slice())?; rr = boring::bn::BigNum::new()?; rr.set_bit(ANDROID_PUBKEY_MODULUS_SIZE * 8)?; tmp = rr.to_owned()?; rr.mod_sqr(tmp.as_ref(), public_key.n().to_owned().unwrap().as_ref(), ctx.as_mut())?; key_struct.write(big_endian_to_little_endian_padded( ANDROID_PUBKEY_MODULUS_SIZE as usize, rr.to_owned().unwrap()) .unwrap().as_slice())?; println!("{:?}", public_key.e().to_string().parse::().unwrap()); key_struct.write_i32(public_key.e().to_string().parse::().unwrap()); Ok(key_struct.into_vec()) } fn encode_rsa_publickey_with_name(public_key: boring::rsa::Rsa) -> Result, anyhow::Error> { let name = " Ascent@Antagonism\u{0}"; let pkey_size = 4 * (f64::from(ANDROID_PUBKEY_ENCODED_SIZE) / 3.0).ceil() as usize; let mut bos = bytebuffer::ByteBuffer::new(); bos.resize(pkey_size + name.len()); let base64 = boring::base64::encode_block(encode_rsa_publickey(public_key).unwrap().as_slice()); bos.write(base64.as_bytes())?; bos.write(name.as_bytes())?; Ok(bos.into_vec()) } // TODO: Rewrite this to FSM pub async fn pair(port: String, code: String, data_folder: String) -> Result { let host = "127.0.0.1".to_string(); debug!("Pair starting"); // Check cert file existance let data_folder = data_folder; debug!("Cert load begin"); let cert_path = data_folder.clone() + "/cert.pem"; let pkey_path = data_folder.clone() + "/pkey.pem"; let cert_path = std::path::Path::new(cert_path.as_str()); let pkey_path = std::path::Path::new(pkey_path.as_str()); let x509: Option; let pkey: Option>; if !cert_path.exists() || !pkey_path.exists() { debug!("Cert file don't exist"); let (x509_raw, pkey_raw) = generate_cert().with_context(|| format!("Generate cert"))?; x509 = Some(x509_raw.clone()); pkey = Some(pkey_raw.clone()); let mut cert_file = std::fs::File::create(cert_path)?; let mut pkey_file = std::fs::File::create(pkey_path)?; cert_file.write_all(x509_raw.to_pem().unwrap().as_slice())?; pkey_file.write_all(pkey_raw.private_key_to_pem_pkcs8().unwrap().as_slice())?; } else { return Ok(true); } debug!("Cert load end"); debug!("TLS connect begin"); debug!("Building TLS connector"); let domain = host.clone() + ":" + port.as_str(); let method = boring::ssl::SslMethod::tls(); let mut connector = boring::ssl::SslConnector::builder(method)?; connector.set_verify(boring::ssl::SslVerifyMode::PEER); // The following two line is critical for ADB client auth, without them system_server will throw out "No peer certificate" error. connector.set_certificate(x509.clone().unwrap().as_ref())?; connector.set_private_key(pkey.clone().unwrap().as_ref())?; let mut config = connector.build().configure()?; config.set_verify_callback(boring::ssl::SslVerifyMode::PEER, |_, _| true); debug!("TLS connector build"); debug!("TCP connecting at {}", domain); let stream = tokio::net::TcpStream::connect(domain.as_str()).await.with_context(|| format!("TCP stream connect"))?; debug!("TLS connecting"); let mut stream = tokio_boring::connect(config, host.as_str(), stream).await.with_context(|| format!("TLS stream connect"))?; // To ensure the connection is not stolen while we do the PAKE, append the exported key material from the // tls connection to the password. let mut exported_key_material = [0; 64]; stream.ssl().export_keying_material(&mut exported_key_material, EXPORTED_KEY_LABEL, None).with_context(|| format!("Export key material"))?; debug!("exported_key_material: {:?}\n", exported_key_material); let mut password = vec![0u8; code.as_bytes().len() + exported_key_material.len()]; password[..code.as_bytes().len()].copy_from_slice(code.as_bytes()); password[code.as_bytes().len()..].copy_from_slice(&exported_key_material); let spake2_context = boring::curve25519::Spake2Context::new( boring::curve25519::Spake2Role::Alice, CLIENT_NAME, SERVER_NAME, ).with_context(|| format!("SPAKE2 context generation"))?; let mut outbound_msg = vec![0u8; 32]; spake2_context.generate_message(outbound_msg.as_mut_slice(), 32, password.as_ref()).with_context(|| format!("SPAKE2 message generation"))?; // Set header let mut header = bytebuffer::ByteBuffer::new(); header.resize(6); header.set_endian(bytebuffer::Endian::BigEndian); // Write in data // Write version header.write_u8(1); // Write message type header.write_u8(0); // Write message length header.write_i32(outbound_msg.len() as i32); // Send data stream.write_all(header.as_bytes()).await.with_context(|| format!("Send SPAKE2 header"))?; stream.write_all(outbound_msg.as_slice()).await.with_context(|| format!("Send SPAKE2 message"))?; debug!("SPAKE2 Send"); // Read header data stream.read_u8().await.with_context(|| format!("Read SPAKE2 header"))?; let msg_type = stream.read_u8().await.with_context(|| format!("Read SPAKE2 header msg_type"))?; let payload_length = stream.read_i32().await.with_context(|| format!("Read SPAKE2 header payload_length"))?; if msg_type != 0u8 { debug!("Message type miss match"); return Err(anyhow!("Message type miss match")); } let mut payload_raw = vec![0u8; payload_length as usize]; stream.read_exact(payload_raw.as_mut_slice()).await.with_context(|| format!("Read SPAKE2 message"))?; let mut bob_key = vec![0u8; 64]; spake2_context.process_message(bob_key.as_mut_slice(), 64, payload_raw.as_mut_slice()).with_context(|| format!("Process SPAKE2"))?; // Has checked the hkdf generation process is correct let mut secret_key = [0u8; 16]; match hkdf::Hkdf::::new(None, bob_key.as_ref()).expand("adb pairing_auth aes-128-gcm key".as_bytes(), &mut secret_key) { Ok(_) => {} Err(err) => { bail!(err) } }; let encrypt_iv: i64 = 0; let mut iv_bytes = bytebuffer::ByteBuffer::new(); iv_bytes.resize(12); iv_bytes.set_endian(bytebuffer::Endian::LittleEndian); iv_bytes.write_i64(encrypt_iv); let iv = iv_bytes.as_bytes(); debug!("Create encrypt crypter"); let mut crypter = boring::symm::Crypter::new( boring::symm::Cipher::aes_128_gcm(), boring::symm::Mode::Encrypt, secret_key.as_ref(), Some(iv)).with_context(|| format!("Create encrypt crypter"))?; debug!("Encrypt crypter created"); debug!("Generate PeerInfo"); let mut peerinfo = bytebuffer::ByteBuffer::new(); peerinfo.resize(MAX_PEER_INFO_SIZE as usize); peerinfo.set_endian(bytebuffer::Endian::BigEndian); peerinfo.write_u8(0); peerinfo.write(encode_rsa_publickey_with_name(x509.unwrap().public_key().unwrap().rsa().unwrap()).unwrap().as_slice()).with_context(|| format!("Write peerinfo data"))?; debug!("PeerInfo Generated"); debug!("Update Crypter"); let mut encrypted = vec![0u8; peerinfo.as_bytes().len()]; crypter.update(peerinfo.as_bytes(), encrypted.as_mut_slice()).with_context(|| format!("Update encrypt crypter"))?; debug!("Crypter Updated"); let fin = crypter.finalize(encrypted.as_mut_slice()).with_context(|| format!("Finalize encrypt crypter"))?; if fin != 0 { debug!("Finalize error"); return Err(anyhow!("Finalize error")); } let mut encryption_tag = vec![0u8; 16]; crypter.get_tag(encryption_tag.as_mut_slice()).with_context(|| format!("Get encrypt tag"))?; encrypted.append(encryption_tag.as_mut()); // Set header // Write version let mut header = bytebuffer::ByteBuffer::new(); header.resize(6); header.set_endian(bytebuffer::Endian::BigEndian); // Write in data header.write_u8(1); // Write message type header.write_u8(1); // Write message length header.write_i32(encrypted.len() as i32); stream.write_all(header.as_bytes()).await.with_context(|| format!("Send KeyExchange header"))?; stream.write_all(encrypted.as_slice()).await.with_context(|| format!("Send KeyExchange data"))?; // Read peer info header stream.read_u8().await.with_context(|| format!("Read KeyExchange header"))?; let msg_type = stream.read_u8().await.with_context(|| format!("Read KeyExchange header msg_type"))?; let payload_length = stream.read_i32().await.with_context(|| format!("Read KeyExchange header payload_length"))?; if msg_type != 1u8 { debug!("Message type miss match"); return Err(anyhow!("Message type miss match")); } let mut payload_raw = vec![0u8; payload_length as usize]; stream.read_exact(payload_raw.as_mut_slice()).await.with_context(|| format!("Read KeyExchange payload"))?; let encrypted = payload_raw[0..payload_length as usize - 16].to_vec(); let encrypted_tag = payload_raw[payload_length as usize - 16..payload_length as usize].to_vec(); let decrypt_iv: i64 = 0; let mut iv_bytes = bytebuffer::ByteBuffer::new(); iv_bytes.resize(12); iv_bytes.set_endian(bytebuffer::Endian::LittleEndian); iv_bytes.write_i64(decrypt_iv); let iv = iv_bytes.as_bytes(); debug!("Create decrypt crypter"); let mut crypter = boring::symm::Crypter::new( boring::symm::Cipher::aes_128_gcm(), boring::symm::Mode::Decrypt, secret_key.as_ref(), Some(iv)).with_context(|| format!("Create decrypt crypter"))?; debug!("Decrypt crypter created"); // debug!("Encrypted: {:?}",boring::base64::encode_block(encrypted.as_slice())); // debug!("Tag: {:?}",boring::base64::encode_block(encrypted_tag.as_slice())); // debug!("Key: {:?}", boring::base64::encode_block(secret_key.as_ref())); // debug!("IV: {:?}", boring::base64::encode_block(iv)); debug!("Update crypter"); let mut decrypted = vec![0u8; (payload_length - 16) as usize]; crypter.set_tag(encrypted_tag.as_ref()).with_context(|| format!("Set decrypt tag"))?; crypter.update((encrypted).as_slice(), decrypted.as_mut_slice()).with_context(|| format!("Update decrypt crypter"))?; debug!("Crypter updated"); let fin = crypter.finalize(decrypted.as_mut_slice()).with_context(|| format!("Finalize decrypt crypter"))?; if fin != 0 { debug!("Finalize error"); return Err(anyhow!("Finalize error")); } debug!("All process done, peerinfo is {:?}", String::from_utf8(decrypted)?.trim_matches(char::from(0))); Ok(true) } ================================================ FILE: test_driver/integration_test.dart ================================================ import 'package:integration_test/integration_test_driver.dart'; Future main() => integrationDriver();