Showing preview only (222K chars total). Download the full file or copy to clipboard to get everything.
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. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
# Ascent


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
[](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
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
================================================
FILE: android/app/src/main/AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- foregroundServiceType: dataSync -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
<!-- foregroundServiceType: remoteMessaging -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING"/>
<application
android:label="Ascent"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<provider
android:name="rikka.shizuku.ShizukuProvider"
android:authorities="${applicationId}.shizuku"
android:multiprocess="false"
android:enabled="true"
android:exported="true"
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleInstance"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.EnableImpeller"
android:value="false" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
</activity>
<service
android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
android:foregroundServiceType="dataSync|remoteMessaging"
android:exported="false"/>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2"/>
</application>
</manifest>
================================================
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
================================================
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
================================================
FILE: android/app/src/main/res/drawable-v21/launch_background.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
================================================
FILE: android/app/src/main/res/values/styles.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
================================================
FILE: android/app/src/main/res/values-night/styles.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
================================================
FILE: android/app/src/profile/AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
================================================
FILE: android/ascent_android.iml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="GEN_FOLDER_RELATIVE_PATH_APT" value="/gen" />
<option name="GEN_FOLDER_RELATIVE_PATH_AIDL" value="/gen" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/app/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/app/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/app/src/main/assets" />
<option name="LIBS_FOLDER_RELATIVE_PATH" value="/app/src/main/libs" />
<option name="PROGUARD_LOGS_FOLDER_RELATIVE_PATH" value="/app/src/main/proguard_logs" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/app/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/app/src/main/kotlin" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
</content>
<orderEntry type="jdk" jdkName="Android API 29 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Flutter for Android" level="project" />
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
</component>
</module>
================================================
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
</component>
</module>
================================================
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<void> 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<void> startMDNS() async {
print("Start listening to mDNS");
await mDnsClient.start();
while (status == ConnectStatus.WAIT_PORT) {
await for (final PtrResourceRecord ptr
in mDnsClient.lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer('_adb-tls-connect._tcp'))) {
await for (final SrvResourceRecord srv
in mDnsClient.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(ptr.domainName))) {
port = srv.port.toString();
status = ConnectStatus.WAIT_LINK;
waitLink();
}
}
await Future.delayed(const Duration(milliseconds: 500));
}
}
Future<void> 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<void> onDestroy(DateTime timestamp) async {
mDnsClient.stop();
}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
Future<void> 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<void> 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<bool> 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<void> 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<void> startMDNS() async {
print("Start listening to mDNS");
await mDnsClient.start();
while (status == PairStatus.WAIT_PORT) {
await for (final PtrResourceRecord ptr
in mDnsClient.lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer('_adb-tls-pairing._tcp'))) {
await for (final SrvResourceRecord srv
in mDnsClient.lookup<SrvResourceRecord>(
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<void> 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<void> 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<void> onDestroy(DateTime timestamp) async {
mDnsClient.stop();
}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
Future<void> 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<void> 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<bool> 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<void> 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<void> 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<void> onDestroy(DateTime timestamp) async {}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
await loadTranslations();
await GlobalState.init();
waitLink();
}
}
class RootConnectForegroundTask {
Future<void> 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<bool> 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<void> 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<void> 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<void> onDestroy(DateTime timestamp) async {}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
await loadTranslations();
await GlobalState.init();
waitLink();
}
}
class ShizukuConnectForegroundTask {
Future<void> 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<bool> 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<String> currentRoute = "/home".obs;
static late final Directory dataDir;
static const String localizationAssetPath = "assets/translations";
static Rx<bool> hasCert = false.obs;
static Rx<bool> rootEnabled = false.obs;
static Rx<bool> shizukuEnabled = false.obs;
static late Mixpanel mixpanel;
static StreamSubscription? intentSubscription;
static String? locale;
static Rx<bool> disableAutoDetectPort = false.obs;
static const List<Locale> supportedLocale = [
Locale('en', 'US'),
Locale('zh', 'CN'),
Locale('ru', 'RU'),
];
static Future<void> 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<void> 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<void> 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<bool> doPair(
{required String port,
required String code,
required String dataFolder}) =>
RustLib.instance.api
.crateApiApiDoPair(port: port, code: code, dataFolder: dataFolder);
Future<String> doConnect({required String port, required String dataFolder}) =>
RustLib.instance.api
.crateApiApiDoConnect(port: port, dataFolder: dataFolder);
Future<String> doFilter({required String filePath}) =>
RustLib.instance.api.crateApiApiDoFilter(filePath: filePath);
Future<void> 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<RustLibApi, RustLibApiImpl, RustLibWire> {
@internal
static final instance = RustLib._();
RustLib._();
/// Initialize flutter_rust_bridge
static Future<void> 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<RustLibApiImpl, RustLibWire> get apiImplConstructor =>
RustLibApiImpl.new;
@override
WireConstructor<RustLibWire> get wireConstructor =>
RustLibWire.fromExternalLibrary;
@override
Future<void> 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<String> crateApiApiDoConnect(
{required String port, required String dataFolder});
Future<String> crateApiApiDoFilter({required String filePath});
Future<bool> crateApiApiDoPair(
{required String port, required String code, required String dataFolder});
Future<void> crateApiApiInitLogger();
}
class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
RustLibApiImpl({
required super.handler,
required super.wire,
required super.generalizedFrbRustBinding,
required super.portManager,
});
@override
Future<String> 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<String> 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<bool> 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<void> 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<RustLibWire> {
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<T> Function<T extends ffi.NativeType>(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<RustLibWire> {
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<bool> developerOptionEnabled = false.obs;
Rx<String> link = "".obs;
Rx<bool> 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<void> doConnect() async {
logic.inProgress.value = true;
await connectForegroundTask.startConnectForegroundTask(logic);
}
Future<void> doRootConnect() async {
logic.inProgress.value = true;
await rootConnectForegroundTask.startRootConnectForegroundTask(logic);
}
Future<void> doShizukuConnect() async {
logic.inProgress.value = true;
await shizukuConnectForegroundTask.startShizukuConnectForegroundTask(logic);
}
Future<void> 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<bool> 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<bool> developerOptionEnabled = false.obs;
Rx<bool> 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<void> 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<void> 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<GetPage> 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<bool> {
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<String> {
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<String> {
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<u8>, 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<u8>) -> 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<String> {
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<u8> = cert_file.bytes().map(|x| x.unwrap()).collect();
let x509_raw = x509_raw.as_slice();
let pkey_raw: Vec<u8> = 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::SseCodec, _, _>(
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 = <String>::sse_decode(&mut deserializer);
let api_data_folder = <String>::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::SseCodec, _, _>(
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 = <String>::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::SseCodec, _, _>(
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 = <String>::sse_decode(&mut deserializer);
let api_code = <String>::sse_decode(&mut deserializer);
let api_data_folder = <String>::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::SseCodec, _, _>(
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 = <String>::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 = <Vec<u8>>::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<u8> {
// 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_ = <i32>::sse_decode(deserializer);
let mut ans_ = vec![];
for idx_ in 0..len_ {
ans_.push(<u8>::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::<NativeEndian>().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) {
<String>::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) {
<Vec<u8>>::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<u8> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
<i32>::sse_encode(self.len() as _, serializer);
for item in self {
<u8>::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::<NativeEndian>(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<boring::pkey::Private>)> {
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!
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
SYMBOL INDEX (218 symbols across 26 files)
FILE: integration_test/simple_test.dart
function main (line 6) | void main()
FILE: lib/components/bottom_navigation_bar/view.dart
class BottomNavigationBarComponent (line 9) | class BottomNavigationBarComponent extends StatelessWidget {
method build (line 13) | Widget build(BuildContext context)
FILE: lib/foreground/connect.dart
function startCallback (line 19) | void startCallback()
type ConnectStatus (line 24) | enum ConnectStatus { WAIT_PORT, WAIT_LINK }
class ConnectTaskHandler (line 26) | class ConnectTaskHandler extends TaskHandler {
method loadTranslations (line 32) | Future<void> loadTranslations()
method startMDNS (line 57) | Future<void> startMDNS()
method waitLink (line 76) | Future<void> waitLink()
method onDestroy (line 123) | Future<void> onDestroy(DateTime timestamp)
method onRepeatEvent (line 128) | void onRepeatEvent(DateTime timestamp)
method onStart (line 131) | Future<void> onStart(DateTime timestamp, TaskStarter starter)
method onNotificationReplied (line 145) | void onNotificationReplied(String id, String reply)
class ConnectForegroundTask (line 162) | class ConnectForegroundTask {
method requestPermission (line 163) | Future<void> requestPermission()
method startConnectForegroundTask (line 180) | Future<bool> startConnectForegroundTask(ConnectLogic logic)
FILE: lib/foreground/pair.dart
function startCallback (line 19) | void startCallback()
type PairStatus (line 24) | enum PairStatus { WAIT_PORT, WAIT_CODE }
class PairTaskHandler (line 27) | class PairTaskHandler extends TaskHandler {
method loadTranslations (line 33) | Future<void> loadTranslations()
method startMDNS (line 58) | Future<void> startMDNS()
method waitCode (line 78) | Future<void> waitCode()
method doPair (line 88) | Future<void> doPair()
method onDestroy (line 121) | Future<void> onDestroy(DateTime timestamp)
method onRepeatEvent (line 126) | void onRepeatEvent(DateTime timestamp)
method onStart (line 129) | Future<void> onStart(DateTime timestamp, TaskStarter starter)
method onNotificationReplied (line 144) | void onNotificationReplied(String id, String reply)
class PairForegroundTask (line 161) | class PairForegroundTask {
method requestPermission (line 162) | Future<void> requestPermission()
method pairCallback (line 179) | void pairCallback(Object data)
method startPairForegroundTask (line 207) | Future<bool> startPairForegroundTask()
FILE: lib/foreground/root_connect.dart
function startCallback (line 14) | void startCallback()
class RootConnectTaskHandler (line 19) | class RootConnectTaskHandler extends TaskHandler {
method loadTranslations (line 22) | Future<void> loadTranslations()
method waitLink (line 47) | Future<void> waitLink()
method onDestroy (line 65) | Future<void> onDestroy(DateTime timestamp)
method onRepeatEvent (line 68) | void onRepeatEvent(DateTime timestamp)
method onStart (line 71) | Future<void> onStart(DateTime timestamp, TaskStarter starter)
class RootConnectForegroundTask (line 78) | class RootConnectForegroundTask {
method requestPermission (line 79) | Future<void> requestPermission()
method startRootConnectForegroundTask (line 96) | Future<bool> startRootConnectForegroundTask(ConnectLogic logic)
FILE: lib/foreground/shizuku_connect.dart
function startCallback (line 14) | void startCallback()
class ShizukuConnectTaskHandler (line 19) | class ShizukuConnectTaskHandler extends TaskHandler {
method loadTranslations (line 22) | Future<void> loadTranslations()
method waitLink (line 47) | Future<void> waitLink()
method onDestroy (line 65) | Future<void> onDestroy(DateTime timestamp)
method onRepeatEvent (line 68) | void onRepeatEvent(DateTime timestamp)
method onStart (line 71) | Future<void> onStart(DateTime timestamp, TaskStarter starter)
class ShizukuConnectForegroundTask (line 78) | class ShizukuConnectForegroundTask {
method requestPermission (line 79) | Future<void> requestPermission()
method startShizukuConnectForegroundTask (line 96) | Future<bool> startShizukuConnectForegroundTask(ConnectLogic logic)
FILE: lib/global_state.dart
class GlobalState (line 13) | class GlobalState {
method init (line 35) | Future<void> init()
FILE: lib/main.dart
function main (line 22) | void main()
function checkUpdate (line 44) | Future<void> checkUpdate()
class AscentApp (line 80) | class AscentApp extends StatelessWidget {
method initReceiveIntent (line 83) | Future<void> initReceiveIntent()
method build (line 154) | Widget build(BuildContext context)
FILE: lib/native/api/api.dart
function doPair (line 9) | Future<bool> doPair(
function doConnect (line 16) | Future<String> doConnect({required String port, required String dataFold...
function doFilter (line 20) | Future<String> doFilter({required String filePath})
function initLogger (line 23) | Future<void> initLogger()
FILE: lib/native/frb_generated.dart
class RustLib (line 15) | class RustLib extends BaseEntrypoint<RustLibApi, RustLibApiImpl, RustLib...
method init (line 22) | Future<void> init({
method initMock (line 38) | void initMock({
method dispose (line 50) | void dispose()
method executeRustInitializers (line 61) | Future<void> executeRustInitializers()
class RustLibApi (line 81) | abstract class RustLibApi extends BaseApi {
method crateApiApiDoConnect (line 82) | Future<String> crateApiApiDoConnect(
method crateApiApiDoFilter (line 85) | Future<String> crateApiApiDoFilter({required String filePath})
method crateApiApiDoPair (line 87) | Future<bool> crateApiApiDoPair(
method crateApiApiInitLogger (line 90) | Future<void> crateApiApiInitLogger()
class RustLibApiImpl (line 93) | class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
method crateApiApiDoConnect (line 102) | Future<String> crateApiApiDoConnect(
method crateApiApiDoFilter (line 128) | Future<String> crateApiApiDoFilter({required String filePath})
method crateApiApiDoPair (line 152) | Future<bool> crateApiApiDoPair(
method crateApiApiInitLogger (line 181) | Future<void> crateApiApiInitLogger()
method dco_decode_AnyhowException (line 204) | AnyhowException dco_decode_AnyhowException(dynamic raw)
method dco_decode_String (line 210) | String dco_decode_String(dynamic raw)
method dco_decode_bool (line 216) | bool dco_decode_bool(dynamic raw)
method dco_decode_list_prim_u_8_strict (line 222) | Uint8List dco_decode_list_prim_u_8_strict(dynamic raw)
method dco_decode_u_8 (line 228) | int dco_decode_u_8(dynamic raw)
method dco_decode_unit (line 234) | void dco_decode_unit(dynamic raw)
method sse_decode_AnyhowException (line 240) | AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer)
method sse_decode_String (line 247) | String sse_decode_String(SseDeserializer deserializer)
method sse_decode_bool (line 254) | bool sse_decode_bool(SseDeserializer deserializer)
method sse_decode_list_prim_u_8_strict (line 260) | Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer)
method sse_decode_u_8 (line 267) | int sse_decode_u_8(SseDeserializer deserializer)
method sse_decode_unit (line 273) | void sse_decode_unit(SseDeserializer deserializer)
method sse_decode_i_32 (line 278) | int sse_decode_i_32(SseDeserializer deserializer)
method sse_encode_AnyhowException (line 284) | void sse_encode_AnyhowException(
method sse_encode_String (line 291) | void sse_encode_String(String self, SseSerializer serializer)
method sse_encode_bool (line 297) | void sse_encode_bool(bool self, SseSerializer serializer)
method sse_encode_list_prim_u_8_strict (line 303) | void sse_encode_list_prim_u_8_strict(
method sse_encode_u_8 (line 311) | void sse_encode_u_8(int self, SseSerializer serializer)
method sse_encode_unit (line 317) | void sse_encode_unit(void self, SseSerializer serializer)
method sse_encode_i_32 (line 322) | void sse_encode_i_32(int self, SseSerializer serializer)
FILE: lib/native/frb_generated.io.dart
class RustLibApiImplPlatform (line 13) | abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
method dco_decode_AnyhowException (line 22) | AnyhowException dco_decode_AnyhowException(dynamic raw)
method dco_decode_String (line 25) | String dco_decode_String(dynamic raw)
method dco_decode_bool (line 28) | bool dco_decode_bool(dynamic raw)
method dco_decode_list_prim_u_8_strict (line 31) | Uint8List dco_decode_list_prim_u_8_strict(dynamic raw)
method dco_decode_u_8 (line 34) | int dco_decode_u_8(dynamic raw)
method dco_decode_unit (line 37) | void dco_decode_unit(dynamic raw)
method sse_decode_AnyhowException (line 40) | AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer)
method sse_decode_String (line 43) | String sse_decode_String(SseDeserializer deserializer)
method sse_decode_bool (line 46) | bool sse_decode_bool(SseDeserializer deserializer)
method sse_decode_list_prim_u_8_strict (line 49) | Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer)
method sse_decode_u_8 (line 52) | int sse_decode_u_8(SseDeserializer deserializer)
method sse_decode_unit (line 55) | void sse_decode_unit(SseDeserializer deserializer)
method sse_decode_i_32 (line 58) | int sse_decode_i_32(SseDeserializer deserializer)
method sse_encode_AnyhowException (line 61) | void sse_encode_AnyhowException(
method sse_encode_String (line 65) | void sse_encode_String(String self, SseSerializer serializer)
method sse_encode_bool (line 68) | void sse_encode_bool(bool self, SseSerializer serializer)
method sse_encode_list_prim_u_8_strict (line 71) | void sse_encode_list_prim_u_8_strict(
method sse_encode_u_8 (line 75) | void sse_encode_u_8(int self, SseSerializer serializer)
method sse_encode_unit (line 78) | void sse_encode_unit(void self, SseSerializer serializer)
method sse_encode_i_32 (line 81) | void sse_encode_i_32(int self, SseSerializer serializer)
class RustLibWire (line 86) | class RustLibWire implements BaseWire {
FILE: lib/native/frb_generated.web.dart
class RustLibApiImplPlatform (line 15) | abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
method dco_decode_AnyhowException (line 24) | AnyhowException dco_decode_AnyhowException(dynamic raw)
method dco_decode_String (line 27) | String dco_decode_String(dynamic raw)
method dco_decode_bool (line 30) | bool dco_decode_bool(dynamic raw)
method dco_decode_list_prim_u_8_strict (line 33) | Uint8List dco_decode_list_prim_u_8_strict(dynamic raw)
method dco_decode_u_8 (line 36) | int dco_decode_u_8(dynamic raw)
method dco_decode_unit (line 39) | void dco_decode_unit(dynamic raw)
method sse_decode_AnyhowException (line 42) | AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer)
method sse_decode_String (line 45) | String sse_decode_String(SseDeserializer deserializer)
method sse_decode_bool (line 48) | bool sse_decode_bool(SseDeserializer deserializer)
method sse_decode_list_prim_u_8_strict (line 51) | Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer)
method sse_decode_u_8 (line 54) | int sse_decode_u_8(SseDeserializer deserializer)
method sse_decode_unit (line 57) | void sse_decode_unit(SseDeserializer deserializer)
method sse_decode_i_32 (line 60) | int sse_decode_i_32(SseDeserializer deserializer)
method sse_encode_AnyhowException (line 63) | void sse_encode_AnyhowException(
method sse_encode_String (line 67) | void sse_encode_String(String self, SseSerializer serializer)
method sse_encode_bool (line 70) | void sse_encode_bool(bool self, SseSerializer serializer)
method sse_encode_list_prim_u_8_strict (line 73) | void sse_encode_list_prim_u_8_strict(
method sse_encode_u_8 (line 77) | void sse_encode_u_8(int self, SseSerializer serializer)
method sse_encode_unit (line 80) | void sse_encode_unit(void self, SseSerializer serializer)
method sse_encode_i_32 (line 83) | void sse_encode_i_32(int self, SseSerializer serializer)
class RustLibWire (line 88) | class RustLibWire implements BaseWire {
FILE: lib/pages/connect/logic.dart
class ConnectLogic (line 3) | class ConnectLogic extends GetxController {
FILE: lib/pages/connect/view.dart
class ConnectPage (line 13) | class ConnectPage extends StatelessWidget {
method doConnect (line 22) | Future<void> doConnect()
method doRootConnect (line 27) | Future<void> doRootConnect()
method doShizukuConnect (line 32) | Future<void> doShizukuConnect()
method doResetProcess (line 37) | Future<void> doResetProcess()
method build (line 44) | Widget build(BuildContext context)
FILE: lib/pages/home/logic.dart
class HomeLogic (line 3) | class HomeLogic extends GetxController {
FILE: lib/pages/home/view.dart
class HomePage (line 10) | class HomePage extends StatelessWidget {
method build (line 16) | Widget build(BuildContext context)
FILE: lib/pages/info/logic.dart
class InfoLogic (line 3) | class InfoLogic extends GetxController {}
FILE: lib/pages/info/view.dart
class InfoPage (line 11) | class InfoPage extends StatelessWidget {
method build (line 17) | Widget build(BuildContext context)
FILE: lib/pages/pair/logic.dart
class PairLogic (line 3) | class PairLogic extends GetxController {
FILE: lib/pages/pair/view.dart
class PairPage (line 13) | class PairPage extends StatelessWidget {
method doPair (line 19) | Future<void> doPair()
method resetPair (line 31) | Future<void> resetPair()
method build (line 38) | Widget build(BuildContext context)
FILE: lib/routes.dart
class Routes (line 7) | class Routes {
method route2index (line 16) | int route2index(String route)
method index2route (line 31) | String index2route(int index)
FILE: rust/src/api/api.rs
function do_pair (line 11) | pub fn do_pair(port: String, code: String, data_folder: String) -> Resul...
function do_connect (line 19) | pub fn do_connect(port: String, data_folder: String) -> Result<String> {
function do_filter (line 27) | pub fn do_filter(file_path: String) -> Result<String> {
function init_logger (line 59) | pub fn init_logger() {
FILE: rust/src/connect.rs
constant ADB_HEADER_LENGTH (line 7) | const ADB_HEADER_LENGTH: usize = 24;
constant SYSTEM_IDENTITY_STRING_HOST (line 8) | const SYSTEM_IDENTITY_STRING_HOST: &str = "host::\u{0}";
constant A_CNXN (line 9) | const A_CNXN: i32 = 0x4e584e43;
constant A_OPEN (line 10) | const A_OPEN: i32 = 0x4e45504f;
constant A_OKAY (line 11) | const A_OKAY: i32 = 0x59414b4f;
constant A_WRTE (line 12) | const A_WRTE: i32 = 0x45545257;
constant A_STLS (line 13) | const A_STLS: i32 = 0x534c5453;
constant A_VERSION (line 15) | const A_VERSION: i32 = 0x01000001;
constant MAX_PAYLOAD (line 16) | const MAX_PAYLOAD: i32 = 1024 * 1024;
constant A_STLS_VERSION (line 17) | const A_STLS_VERSION: i32 = 0x01000000;
type Message (line 20) | struct Message {
method parse (line 30) | fn parse(buffer: &mut bytebuffer::ByteBuffer) -> Message {
function get_payload_checksum (line 42) | fn get_payload_checksum(data: Vec<u8>, offset: i32, length: i32) -> i32 {
function generate_message (line 50) | fn generate_message(command: i32, arg0: i32, arg1: i32, data: Vec<u8>) -...
function connect (line 71) | pub async fn connect(port: String, data_folder: String) -> Result<String> {
FILE: rust/src/frb_generated.rs
constant FLUTTER_RUST_BRIDGE_CODEGEN_VERSION (line 39) | pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.11.1";
constant FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH (line 40) | pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -637951...
function wire__crate__api__api__do_connect_impl (line 48) | fn wire__crate__api__api__do_connect_impl(
function wire__crate__api__api__do_filter_impl (line 84) | fn wire__crate__api__api__do_filter_impl(
function wire__crate__api__api__do_pair_impl (line 119) | fn wire__crate__api__api__do_pair_impl(
function wire__crate__api__api__init_logger_impl (line 157) | fn wire__crate__api__api__init_logger_impl(
method sse_decode (line 196) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 204) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 212) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 219) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 231) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 238) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
method sse_decode (line 243) | fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::Sse...
function pde_ffi_dispatcher_primary_impl (line 248) | fn pde_ffi_dispatcher_primary_impl(
function pde_ffi_dispatcher_sync_impl (line 265) | fn pde_ffi_dispatcher_sync_impl(
method sse_encode (line 281) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 288) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 295) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 302) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 312) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 319) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
method sse_encode (line 324) | fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated:...
FILE: rust/src/pair.rs
constant EXPORTED_KEY_LABEL (line 7) | const EXPORTED_KEY_LABEL: &str = "adb-label\u{0}";
constant CLIENT_NAME (line 8) | pub const CLIENT_NAME: &str = "adb pair client\u{0}";
constant SERVER_NAME (line 9) | pub const SERVER_NAME: &str = "adb pair server\u{0}";
constant MAX_PEER_INFO_SIZE (line 10) | pub const MAX_PEER_INFO_SIZE: i32 = 1 << 13;
constant ANDROID_PUBKEY_MODULUS_SIZE (line 12) | const ANDROID_PUBKEY_MODULUS_SIZE: i32 = 2048 / 8;
constant ANDROID_PUBKEY_ENCODED_SIZE (line 13) | const ANDROID_PUBKEY_ENCODED_SIZE: i32 = 3 * 4 + 2 * ANDROID_PUBKEY_MODU...
constant ANDROID_PUBKEY_MODULUS_SIZE_WORDS (line 14) | const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: i32 = ANDROID_PUBKEY_MODULUS_SI...
function generate_cert (line 16) | fn generate_cert() -> Result<(boring::x509::X509, boring::pkey::PKey<bor...
function big_endian_to_little_endian_padded (line 128) | fn big_endian_to_little_endian_padded(len: usize, num: boring::bn::BigNu...
function fit_in_bytes (line 142) | fn fit_in_bytes(bytes: &Vec<u8>, num_bytes: usize, len: usize) -> bool {
function swap_endianness (line 150) | fn swap_endianness(bytes: Vec<u8>) -> Vec<u8> {
function encode_rsa_publickey (line 154) | pub fn encode_rsa_publickey(public_key: boring::rsa::Rsa<boring::pkey::P...
function encode_rsa_publickey_with_name (line 208) | fn encode_rsa_publickey_with_name(public_key: boring::rsa::Rsa<boring::p...
function pair (line 220) | pub async fn pair(port: String, code: String, data_folder: String) -> Re...
FILE: test_driver/integration_test.dart
function main (line 3) | Future<void> main()
Condensed preview — 64 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (222K chars).
[
{
"path": ".github/release.yaml",
"chars": 438,
"preview": "changelog:\n exclude:\n labels:\n - ignore-for-release\n categories:\n - title: '🔥 Breaking Changes'\n label"
},
{
"path": ".github/workflows/github-releases-to-discord.yml",
"chars": 478,
"preview": "name: Push release to Discord\non:\n release:\n types: [ published,edited ]\n\njobs:\n github-releases-to-discord:\n ru"
},
{
"path": ".gitignore",
"chars": 113,
"preview": ".flutter-plugins\n.flutter-plugins-dependencies\n.idea/\nbuild/\n.dart_tool/\nrust_builder\nlogs\nandroid/key.properties"
},
{
"path": ".metadata",
"chars": 1706,
"preview": "# This file tracks properties of this Flutter project.\n# Used by Flutter tool to assess capabilities and perform upgrade"
},
{
"path": "LICENSE",
"chars": 34522,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 1457,
"preview": "# Ascent\n\n![Dis"
},
{
"path": "analysis_options.yaml",
"chars": 1420,
"preview": "# This file configures the analyzer, which statically analyzes Dart code to\n# check for errors, warnings, and lints.\n#\n#"
},
{
"path": "android/.gitignore",
"chars": 285,
"preview": "gradle-wrapper.jar\n/.gradle\n/captures/\n/gradlew\n/gradlew.bat\n/local.properties\nGeneratedPluginRegistrant.java\n\n# Remembe"
},
{
"path": "android/app/build.gradle",
"chars": 2758,
"preview": "import com.android.build.OutputFile\n\nplugins {\n id \"com.android.application\"\n id \"kotlin-android\"\n id \"dev.flut"
},
{
"path": "android/app/src/debug/AndroidManifest.xml",
"chars": 378,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <!-- The INTERNET permission is required for d"
},
{
"path": "android/app/src/main/AndroidManifest.xml",
"chars": 3181,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <uses-permission android:name=\"android.permiss"
},
{
"path": "android/app/src/main/kotlin/cafe/f403/ascent/MainActivity.kt",
"chars": 1520,
"preview": "package cafe.f403.ascent\n\nimport androidx.annotation.NonNull\nimport android.provider.Settings\nimport android.content.Con"
},
{
"path": "android/app/src/main/res/drawable/launch_background.xml",
"chars": 434,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Modify this file to customize your launch splash screen -->\n<layer-list xmln"
},
{
"path": "android/app/src/main/res/drawable-v21/launch_background.xml",
"chars": 438,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Modify this file to customize your launch splash screen -->\n<layer-list xmln"
},
{
"path": "android/app/src/main/res/values/styles.xml",
"chars": 996,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is sta"
},
{
"path": "android/app/src/main/res/values-night/styles.xml",
"chars": 995,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is sta"
},
{
"path": "android/app/src/profile/AndroidManifest.xml",
"chars": 378,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <!-- The INTERNET permission is required for d"
},
{
"path": "android/ascent_android.iml",
"chars": 1600,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n <component name=\"FacetManager\">\n <fa"
},
{
"path": "android/build.gradle",
"chars": 947,
"preview": "buildscript {\n ext.kotlin_version = '2.1.0'\n repositories {\n google()\n mavenCentral()\n }\n\n dep"
},
{
"path": "android/gradle/wrapper/gradle-wrapper.properties",
"chars": 203,
"preview": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dist"
},
{
"path": "android/gradle.properties",
"chars": 79,
"preview": "org.gradle.jvmargs=-Xmx4G\nandroid.useAndroidX=true\nandroid.enableJetifier=true\n"
},
{
"path": "android/settings.gradle",
"chars": 820,
"preview": "pluginManagement {\n def flutterSdkPath = {\n def properties = new Properties()\n file(\"local.properties\")"
},
{
"path": "ascent.iml",
"chars": 692,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">\n <component name=\"NewModuleRootManager\" "
},
{
"path": "assets/translations/en-US.json",
"chars": 3299,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"Home\",\n \"pair\": \"Pair\",\n \"connect\": \"Connect\",\n \"info\": \""
},
{
"path": "assets/translations/en.json",
"chars": 3299,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"Home\",\n \"pair\": \"Pair\",\n \"connect\": \"Connect\",\n \"info\": \""
},
{
"path": "assets/translations/ru-RU.json",
"chars": 3666,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"Главная\",\n \"pair\": \"Соедините\",\n \"connect\": \"Подключение\",\n "
},
{
"path": "assets/translations/ru.json",
"chars": 3666,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"Главная\",\n \"pair\": \"Соедините\",\n \"connect\": \"Подключение\",\n "
},
{
"path": "assets/translations/zh-CN.json",
"chars": 2526,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"主页\",\n \"pair\": \"配对\",\n \"connect\": \"连接\",\n \"info\": \"关于\"\n },\n"
},
{
"path": "assets/translations/zh.json",
"chars": 2526,
"preview": "{\n \"title\": \"Ascent\",\n \"navigation\": {\n \"home\": \"主页\",\n \"pair\": \"配对\",\n \"connect\": \"连接\",\n \"info\": \"关于\"\n },\n"
},
{
"path": "flutter_rust_bridge.yaml",
"chars": 63,
"preview": "rust_input: crate::api\nrust_root: rust/\ndart_output: lib/native"
},
{
"path": "integration_test/simple_test.dart",
"chars": 511,
"preview": "import 'package:flutter_test/flutter_test.dart';\nimport 'package:ascent/main.dart';\nimport 'package:ascent/src/rust/frb_"
},
{
"path": "lib/components/bottom_navigation_bar/view.dart",
"chars": 1850,
"preview": "import 'package:ascent/global_state.dart';\nimport 'package:ascent/routes.dart';\nimport 'package:bruno/bruno.dart';\nimpor"
},
{
"path": "lib/foreground/connect.dart",
"chars": 9798,
"preview": "import 'dart:io';\n\nimport 'package:ascent/native/api/api.dart' as api;\nimport 'package:ascent/global_state.dart';\nimport"
},
{
"path": "lib/foreground/pair.dart",
"chars": 8760,
"preview": "import 'dart:io';\n\nimport 'package:ascent/native/api/api.dart' as api;\nimport 'package:ascent/global_state.dart';\nimport"
},
{
"path": "lib/foreground/root_connect.dart",
"chars": 6674,
"preview": "import 'package:ascent/global_state.dart';\nimport 'package:ascent/pages/connect/logic.dart';\nimport 'package:bruno/bruno"
},
{
"path": "lib/foreground/shizuku_connect.dart",
"chars": 6756,
"preview": "import 'package:ascent/global_state.dart';\nimport 'package:ascent/pages/connect/logic.dart';\nimport 'package:bruno/bruno"
},
{
"path": "lib/global_state.dart",
"chars": 1896,
"preview": "import 'dart:async';\nimport 'dart:io';\nimport 'dart:ui';\n\nimport 'package:flutter/foundation.dart';\nimport 'package:flut"
},
{
"path": "lib/main.dart",
"chars": 6635,
"preview": "import 'dart:convert';\nimport 'dart:io';\n\nimport 'package:ascent/global_state.dart';\nimport 'package:ascent/native/frb_g"
},
{
"path": "lib/native/api/api.dart",
"chars": 907,
"preview": "// This file is automatically generated, so please do not edit it.\n// @generated by `flutter_rust_bridge`@ 2.11.1.\n\n// i"
},
{
"path": "lib/native/frb_generated.dart",
"chars": 9995,
"preview": "// This file is automatically generated, so please do not edit it.\n// @generated by `flutter_rust_bridge`@ 2.11.1.\n\n// i"
},
{
"path": "lib/native/frb_generated.io.dart",
"chars": 2735,
"preview": "// This file is automatically generated, so please do not edit it.\n// @generated by `flutter_rust_bridge`@ 2.11.1.\n\n// i"
},
{
"path": "lib/native/frb_generated.web.dart",
"chars": 2649,
"preview": "// This file is automatically generated, so please do not edit it.\n// @generated by `flutter_rust_bridge`@ 2.11.1.\n\n// i"
},
{
"path": "lib/pages/connect/logic.dart",
"chars": 188,
"preview": "import 'package:get/get.dart';\n\nclass ConnectLogic extends GetxController {\n Rx<bool> developerOptionEnabled = false.ob"
},
{
"path": "lib/pages/connect/view.dart",
"chars": 4423,
"preview": "import 'package:ascent/foreground/connect.dart';\nimport 'package:ascent/foreground/root_connect.dart';\nimport 'package:a"
},
{
"path": "lib/pages/home/logic.dart",
"chars": 122,
"preview": "import 'package:get/get.dart';\n\nclass HomeLogic extends GetxController {\n Rx<bool> developerOptionEnabled = false.obs;\n"
},
{
"path": "lib/pages/home/view.dart",
"chars": 8002,
"preview": "import 'package:ascent/global_state.dart';\nimport 'package:bruno/bruno.dart';\nimport 'package:easy_localization/easy_loc"
},
{
"path": "lib/pages/info/logic.dart",
"chars": 74,
"preview": "import 'package:get/get.dart';\n\nclass InfoLogic extends GetxController {}\n"
},
{
"path": "lib/pages/info/view.dart",
"chars": 4191,
"preview": "import 'dart:io';\n\nimport 'package:ascent/global_state.dart';\nimport 'package:flutter/material.dart';\nimport 'package:ea"
},
{
"path": "lib/pages/pair/logic.dart",
"chars": 175,
"preview": "import 'package:get/get.dart';\n\nclass PairLogic extends GetxController {\n Rx<bool> developerOptionEnabled = false.obs;\n"
},
{
"path": "lib/pages/pair/view.dart",
"chars": 2984,
"preview": "import 'dart:io';\n\nimport 'package:android_intent_plus/android_intent.dart';\nimport 'package:ascent/global_state.dart';\n"
},
{
"path": "lib/routes.dart",
"chars": 1069,
"preview": "import 'package:ascent/pages/connect/view.dart';\nimport 'package:ascent/pages/home/view.dart';\nimport 'package:ascent/pa"
},
{
"path": "pubspec.yaml",
"chars": 4648,
"preview": "name: ascent\ndescription: Tool for mihoyo game gacha link retrival\n# The following line prevents the package from being "
},
{
"path": "rust/.cargo/config.toml",
"chars": 395,
"preview": "#[env]\n#CC = { value = \"D:\\\\Applications\\\\LLVM\\\\bin\\\\clang-cl.exe\", force = true }\n#CMAKE_CXX_COMPILER = { value = \"D:\\\\"
},
{
"path": "rust/.gitignore",
"chars": 8,
"preview": "/target\n"
},
{
"path": "rust/Cargo.toml",
"chars": 599,
"preview": "[package]\nname = \"rust_lib_ascent\"\nversion = \"2.4.0\"\nedition = \"2021\"\n\n[dependencies]\nflutter_rust_bridge = \"=2.11.1\"\nan"
},
{
"path": "rust/src/api/api.rs",
"chars": 2294,
"preview": "use std::{env, fs};\n\nuse android_logger::Config;\nuse anyhow::Result;\nuse log::{debug, LevelFilter};\nuse regex::Regex;\nus"
},
{
"path": "rust/src/api/mod.rs",
"chars": 13,
"preview": "pub mod api;\n"
},
{
"path": "rust/src/connect.rs",
"chars": 8960,
"preview": "use std::io::Read;\n\nuse anyhow::{anyhow, Context, Result};\nuse log::debug;\nuse tokio::io::{AsyncReadExt, AsyncWriteExt};"
},
{
"path": "rust/src/frb_generated.io.rs",
"chars": 444,
"preview": "// This file is automatically generated, so please do not edit it.\n// Generated by `flutter_rust_bridge`@ 2.0.0-dev.32.\n"
},
{
"path": "rust/src/frb_generated.rs",
"chars": 13473,
"preview": "// This file is automatically generated, so please do not edit it.\n// @generated by `flutter_rust_bridge`@ 2.11.1.\n\n#![a"
},
{
"path": "rust/src/frb_generated.web.rs",
"chars": 565,
"preview": "// This file is automatically generated, so please do not edit it.\n// Generated by `flutter_rust_bridge`@ 2.0.0-dev.32.\n"
},
{
"path": "rust/src/lib.rs",
"chars": 185,
"preview": "pub mod api;\npub mod pair;\npub mod connect;\nmod frb_generated; /* AUTO INJECTED BY flutter_rust_bridge. This line may no"
},
{
"path": "rust/src/pair.rs",
"chars": 18559,
"preview": "use std::io::Write;\n\nuse anyhow::{anyhow, bail, Context, Result};\nuse log::debug;\nuse tokio::io::{AsyncReadExt, AsyncWri"
},
{
"path": "test_driver/integration_test.dart",
"chars": 109,
"preview": "import 'package:integration_test/integration_test_driver.dart';\n\nFuture<void> main() => integrationDriver();\n"
}
]
About this extraction
This page contains the full source code of the 4o3F/Ascent GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 64 files (200.7 KB), approximately 49.5k tokens, and a symbol index with 218 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.