Browse Source

Add Android app example

pull/14/head
switch_st 7 years ago
parent
commit
2dd3f8e878
  1. 15
      android/Hin2n/.gitignore
  2. 674
      android/Hin2n/LICENSE
  3. 67
      android/Hin2n/README.md
  4. 67
      android/Hin2n/README_zh.md
  5. 15
      android/Hin2n/android_studio_gradle_4.4/.gitignore
  6. 1
      android/Hin2n/android_studio_gradle_4.4/app/.gitignore
  7. 160
      android/Hin2n/android_studio_gradle_4.4/app/build.gradle
  8. 17
      android/Hin2n/android_studio_gradle_4.4/app/proguard-rules.pro
  9. 27
      android/Hin2n/android_studio_gradle_4.4/build.gradle
  10. 19
      android/Hin2n/android_studio_gradle_4.4/gradle.properties
  11. BIN
      android/Hin2n/android_studio_gradle_4.4/gradle/wrapper/gradle-wrapper.jar
  12. 6
      android/Hin2n/android_studio_gradle_4.4/gradle/wrapper/gradle-wrapper.properties
  13. 160
      android/Hin2n/android_studio_gradle_4.4/gradlew
  14. 90
      android/Hin2n/android_studio_gradle_4.4/gradlew.bat
  15. 1
      android/Hin2n/android_studio_gradle_4.4/settings.gradle
  16. 1
      android/Hin2n/app/.gitignore
  17. 56
      android/Hin2n/app/CMakeLists.txt
  18. 160
      android/Hin2n/app/build.gradle
  19. 17
      android/Hin2n/app/proguard-rules.pro
  20. 26
      android/Hin2n/app/src/androidTest/java/wang/switchy/hin2n/ExampleInstrumentedTest.java
  21. 36
      android/Hin2n/app/src/main/AndroidManifest.xml
  22. 1
      android/Hin2n/app/src/main/cpp/n2n
  23. 1
      android/Hin2n/app/src/main/cpp/tun2tap
  24. 1
      android/Hin2n/app/src/main/cpp/uip
  25. 56
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/Hin2nApplication.java
  26. 59
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/BaseActivity.java
  27. 166
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/ListActivity.java
  28. 187
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/MainActivity.java
  29. 543
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/SettingDetailsActivity.java
  30. 89
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/adapter/SettingItemAdapter.java
  31. 51
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/entity/SettingItemEntity.java
  32. 8
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/ErrorEvent.java
  33. 8
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/StartEvent.java
  34. 8
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/StopEvent.java
  35. 152
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/EdgeCmd.java
  36. 9
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/EdgeStatus.java
  37. 254
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/N2NSettingInfo.java
  38. 187
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/service/N2NService.java
  39. 96
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/DaoMaster.java
  40. 48
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/DaoSession.java
  41. 275
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/N2NSettingModelDao.java
  42. 222
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/model/N2NSettingModel.java
  43. 21
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/BaseTemplate.java
  44. 60
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/CommonTitleTemplate.java
  45. 26
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/EmptyTemplate.java
  46. 53
      android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/MainTitleTemplate.java
  47. 11
      android/Hin2n/app/src/main/res/drawable/titlebar_icon_return_selector.xml
  48. 328
      android/Hin2n/app/src/main/res/layout/activity_add_item.xml
  49. 65
      android/Hin2n/app/src/main/res/layout/activity_main.xml
  50. 10
      android/Hin2n/app/src/main/res/layout/activity_setting_list.xml
  51. 42
      android/Hin2n/app/src/main/res/layout/layout_setting_item.xml
  52. 44
      android/Hin2n/app/src/main/res/layout/main_template_view.xml
  53. BIN
      android/Hin2n/app/src/main/res/mipmap-hdpi/ic_launcher.png
  54. BIN
      android/Hin2n/app/src/main/res/mipmap-mdpi/ic_launcher.png
  55. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_launcher.png
  56. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_setting_dark.png
  57. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_setting_light.png
  58. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/img_add.png
  59. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/img_change.png
  60. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/img_icon_selected.png
  61. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/img_more.png
  62. BIN
      android/Hin2n/app/src/main/res/mipmap-xhdpi/title_back_normal.png
  63. BIN
      android/Hin2n/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
  64. BIN
      android/Hin2n/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
  65. 6
      android/Hin2n/app/src/main/res/values-w820dp/dimens.xml
  66. 6
      android/Hin2n/app/src/main/res/values/colors.xml
  67. 5
      android/Hin2n/app/src/main/res/values/dimens.xml
  68. 3
      android/Hin2n/app/src/main/res/values/strings.xml
  69. 11
      android/Hin2n/app/src/main/res/values/styles.xml
  70. 17
      android/Hin2n/app/src/test/java/wang/switchy/hin2n/ExampleUnitTest.java
  71. 25
      android/Hin2n/build.gradle
  72. 19
      android/Hin2n/gradle.properties
  73. BIN
      android/Hin2n/gradle/wrapper/gradle-wrapper.jar
  74. 6
      android/Hin2n/gradle/wrapper/gradle-wrapper.properties
  75. 160
      android/Hin2n/gradlew
  76. 90
      android/Hin2n/gradlew.bat
  77. 1
      android/Hin2n/settings.gradle

15
android/Hin2n/.gitignore

@ -0,0 +1,15 @@
.idea
*.iml
*.ipr
*.iws
/.idea/workspace.xml
/.idea/libraries
.gradle
/local.properties
reports
/captures
jacoco.exec
.DS_Store
/build
.externalNativeBuild
/app/Hin2n.jks

674
android/Hin2n/LICENSE

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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 General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

67
android/Hin2n/README.md

@ -0,0 +1,67 @@
# n2n_vLTS
[README](README.md) | [中文文档](README_zh.md)
N2N is a VPN project that supports p2p. It was originally developed and open sourced by `Luca Deri` <deri@ntop.org>, `Richard Andrews` <andrews@ntop.org> of ntop.org, and `Meyerd` <https://github.com/meyerd> continues to do optimization work. Our goal is to continuously optimize n2n based on several masters and provide `mobile version` support.
## Hin2n
The original n2n supports many platforms, including windows, linux, osx, bsd, openwrt, raspberry pie, etc., except for mobile phones(non-root). Therefore, we have developed the Hin2n project.
### What is Hin2n
- Hin2n is a mobile VPN app that supports the n2n protocol
- Hin2n does not need a rooted phone
- Hin2n only supports Android phones for now, IPhone version will be developed in the future
- Hin2n is currently in continuous development and will gradually provide more complete versions
- Hin2n only supports [n2n_v2s](#About v2s version) protocol now, other versions of n2n protocol are under development
### Hin2n latest version [CHANGELOG](Hin2n_android/CHANGELOG)
The latest version of Hin2n is available for download at [release link](https://github.com/switch-iot/n2n_vLTS/releases).
### Hin2n Development Plan
View the development plan at [`Projects`](https://github.com/switch-iot/n2n_vLTS/projects).
If you have new features and ideas, you can submit them in [`issues`](https://github.com/switch-iot/n2n_vLTS/issues), and we will arrange development plans as appropriate. Your concern is our motivation.
### Technical principle
- VPNService
> Hin2n is based on Android's native VPNService. It builds a tun virtual network card through VPNService and communicates with supernode and edges.
- tun2tap
> Android only supports tun virtual network card, only support network layer, and n2n requires tap virtual network card, which needs data link layer support. So we simulated the data link layer and ARP protocol.
- n2n protocol
> Hin2n supports the n2n protocol by using the native method of jni to reuse the code of the original n2n project as far as possible.
## N2N protocol version
There are three popular versions of the n2n project
- Version v1 developed by the great masters of ntop.org. Project address:https://github.com/meyerd/n2n.git(n2n_v1)
- Version v2 developed by the great masters of ntop.org. Project address:https://github.com/ntop/n2n.git
- Version [v2s](#About v2s version) developed by the master Meyerd. Project address:https://github.com/meyerd/n2n.git(n2n_v2)
### About v2s version
The v2s is the renaming of the v2 (also known as v2.1) developed by master Meyerd in the QQ group(256572040), that is, the v2 upgrade version. The v2s version is not compatible with the v2 version developed by the ntop.org masters. To avoid confusion, the QQ group friends named the project separately.
## Development and compilation
### Hin2n
- git clone https://github.com/switch-iot/n2n_vLTS.git `--recurse-submodules`
- The windows environment needs to execute `link.bat` in the project folder to replace symbolic links under Linux.
- Hin2n_android directory is the Hin2n project Android source directory
- Execute `gradlew assemble` in Hin2n_android directory to compile Hin2n
- The gradle version of the Hin2n_android project is 2.14.1. If you want to upgrade the gradle version to 4.4, copy the file under the branch `dev_android_gradle4.4` to the branch `marster`/`dev_android` to overwrite the corresponding files.
### About open source agreement
The project is open sourced under the [`GPLv3`](LICENSE) agreement, and is consistent with the original open source agreement of n2n. We also hope that everyone will support and comply with the open source agreement of this project.
## Contribute to Hin2n
Hin2n is a free and open source n2n project, and we welcome anyone to contribute to it.
- Any problems in use can be fed back through ['issues'](https://github.com/switch-iot/n2n_vLTS/issues)
- Bug fixes can submit `Pull Request` to `android_dev` branch
- If you want to add a new feature, please create an [`issues`](https://github.com/switch-iot/n2n_vLTS/issues) first to describe the new feature, as well as the implementation approach. Once a proposal is accepted, create an implementation of the new features and submit it as a pull request.
- Sorry for my poor english and improvement for this document is welcome even some typo fix.
- Welcome to pay attention to the project and give the project a `Star`
### Contributors
- [`lucktu`](https://github.com/lucktu) is the initiator of the Hin2n project and plays a crucial role in the project. We thank [`lucktu`](https://github.com/lucktu) for organizing, promoting and testing for the project.
- [`zhangbz`](https://github.com/zhangbz) is mainly responsible for the development of the Android level, and has given strong support in the most difficult time of the project. The participation of [`zhangbz`](https://github.com/zhangbz) has enabled the project to continue.
- At the same time, thank all the friends for their support
## QQ group
- Hin2n QQ group: 769731491
- N2N QQ group: 256572040

67
android/Hin2n/README_zh.md

@ -0,0 +1,67 @@
# n2n_vLTS
[README](README.md) | [中文文档](README_zh.md)
n2n是一个支持内网穿透p2p的VPN项目,最初由ntop.org大神`Luca Deri` <deri@ntop.org>, `Richard Andrews` <andrews@ntop.org>开发并开源的项目,后由`meyerd`大神 <https://github.com/meyerd>继续做优化工作。我们的目的是在几位大神的基础上做持续优化并提供`手机版本`的支持。
## Hin2n
原版的n2n支持很多平台,包括windows,linux,osx,bsd,openwrt,raspberry pie等,唯独缺少对手机(非root)的支持。因此,我们开发了Hin2n项目。
### Hin2n是什么
- Hin2n是支持n2n协议的手机VPN软件
- 该APP不需要root手机
- 该APP暂时只支持安卓手机,后续会发开IPhone版本
- 该项目现处于持续开发阶段,仅支持基本的配置连接功能,后续会提供更完善的功能
- 该项目现只支持[n2n_v2s](#关于v2s版本)协议,其他版本的n2n协议正在开发中
### Hin2n最新版本 [CHANGELOG](Hin2n_android/CHANGELOG_zh)
Hin2n最新版本可在[release地址](https://github.com/switch-iot/n2n_vLTS/releases)查看下载。
### Hin2n开发计划
详细开发计划请见[`Projects`](https://github.com/switch-iot/n2n_vLTS/projects)。
大家如果有新需求和想法,任何意见建议均可提交在[`issues`](https://github.com/switch-iot/n2n_vLTS/issues)中,我们将会酌情安排开发计划。您的关注就是我们的动力。
### 技术原理
- VPNService
> Hin2n基于安卓原生提供的VPNService,通过VPNService建立tun虚拟网卡,与supernode和edge通讯。
- tun2tap
> 安卓上层仅支持建立tun虚拟网卡,仅是TCP/IP网络层,而n2n协议依赖tap虚拟网卡,需要对数据链路层的支持,因此我们模拟了数据链路层,并实现了ARP协议。
- n2n protocol
> Hin2n对n2n协议的支持是采用jni的方式,native方法可以尽量复用原n2n项目的代码。
## n2n协议版本
n2n项目现有三个主流版本
- ntop.org大神们维护的v1版本,项目地址:https://github.com/meyerd/n2n.git(n2n_v1)
- ntop.org大神们维护的v2版本,项目地址:https://github.com/ntop/n2n.git
- meyerd大神维护的[v2s版本](#关于v2s版本),项目地址:https://github.com/meyerd/n2n.git(n2n_v2)
### 关于v2s版本
v2s版本是N2N交流QQ群(256572040)中对meyerd大神维护的v2版本(又称v2.1)的命名,即v2升级版,该版本与ntop.org大神们维护的v2版本并不互通,为避免混淆,群友们对该项目另行命名。
## 项目开发/编译说明
### Hin2n
- git clone https://github.com/switch-iot/n2n_vLTS.git `--recurse-submodules`
- windows环境下需要在项目文件夹下执行`link.bat`,用于替换linux下的符号链接
- Hin2n_android目录即是Hin2n项目安卓源码目录
- Hin2n_android目录下执行`gradlew assemble`编译
- Hin2n_android项目的gradle是2.14.1版本,如需4.4版本的gradle,请将分支`dev_android_gradle4.4`下的文件拷贝至分支`marster`/`dev_android`下,覆盖相应的文件
### 关于开源协议
该项目以[`GPLv3`](LICENSE)协议进行开源,与n2n原有开源协议保持一致,也希望大家支持并遵守本项目的开源协议。
## 为Hin2n做贡献
Hin2n是一个免费且开源的n2n项目,我们欢迎任何人为其开发和进步贡献力量。
- 在使用过程中出现任何问题,可以通过[`issues`](https://github.com/switch-iot/n2n_vLTS/issues) 来反馈
- Bug的修复可以直接提交`Pull Request`到`android_dev`分支
- 如果是增加新的功能特性,请先创建一个[`issues`](https://github.com/switch-iot/n2n_vLTS/issues)并做简单描述以及大致的实现方法,提议被采纳后,就可以创建一个实现新特性的 Pull Request
- 欢迎对说明文档做出改善,帮助更多的人使用`Hin2n`,特别是英文文档
- 如果您觉得Hin2n对您有帮助,欢迎您关注该项目,并给项目点个`Star`
### 贡献者
- [`lucktu`](https://github.com/lucktu)是Hin2n项目的发起人,对该项目起到至关重要的作用,感谢[`lucktu`](https://github.com/lucktu)对该项目的组织、推广、测试等工作
- [`zhangbz`](https://github.com/zhangbz)主要负责Android层面的开发,在项目最困难的时候,给予了强有力的支持,[`zhangbz`](https://github.com/zhangbz)的参与,使得该项目得以继续
- 同时也感谢广大群友对我们的支持
## 交流群
- Hin2n交流群: 769731491(QQ群号)
- N2N交流群: 256572040(QQ群号)

15
android/Hin2n/android_studio_gradle_4.4/.gitignore

@ -0,0 +1,15 @@
.idea
*.iml
*.ipr
*.iws
/.idea/workspace.xml
/.idea/libraries
.gradle
/local.properties
reports
/captures
jacoco.exec
.DS_Store
/build
.externalNativeBuild
/app/Hin2n.jks

1
android/Hin2n/android_studio_gradle_4.4/app/.gitignore

@ -0,0 +1 @@
/build

160
android/Hin2n/android_studio_gradle_4.4/app/build.gradle

@ -0,0 +1,160 @@
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.android.application'
def getVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--all', '--count'
standardOutput = stdout
}
return Integer.parseInt(stdout.toString().trim())
}
catch (ignored) {
return -1;
}
}
def getVersionName = { ->
def ver = 'v0.5.2'
return ver;
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--always', '--dirty', '--match', 'hin2n_v*'
standardOutput = stdout
}
return stdout.toString().trim()
}
catch (ignored) {
return null;
}
}
def getEnvOrConsole = { env, prompt ->
def val = null
try {
val = System.getenv(env)
if (val == null || val == "") {
if (System.console() != null) {
val = System.console().readLine("\n" + prompt + ": ")
}
}
} catch (ignored) {
return null
}
return val
}
android {
compileSdkVersion 25
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "wang.switchy.hin2n"
minSdkVersion 14
targetSdkVersion 25
versionCode getVersionCode()
versionName getVersionName()
multiDexEnabled true
manifestPlaceholders = [CHANNEL_VALUE: "normal", ARCH: "all"]
resConfigs "en", "zh-rCN", "zh-rTW"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
signingConfigs {
debug {}
release {
storeFile file("Hin2n.jks")
storePassword getEnvOrConsole("HIN2N_KSTOREPWD", "Keystore password")
keyAlias "Hin2n"
keyPassword getEnvOrConsole("HIN2N_KEYPWD", "Key password")
}
}
buildTypes {
debug {
buildConfigField("boolean", "API_DEBUG", "true")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
buildConfigField("boolean", "API_DEBUG", "false")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.all { output ->
def outputFile = output.outputFile
def fileName = null
if (outputFile != null && outputFile.name.endsWith('.apk')) {
variant.mergedFlavor.versionName = getVersionName()
def channel = variant.mergedFlavor.manifestPlaceholders.CHANNEL_VALUE
def arch = variant.mergedFlavor.manifestPlaceholders.ARCH
fileName = "hin2n_${variant.mergedFlavor.versionName}_${channel}_${arch}_${variant.buildType.name}.apk"
outputFileName = fileName
}
}
}
flavorDimensions "channel", "arch"
productFlavors {
normal {
dimension "channel"
manifestPlaceholders += [CHANNEL_VALUE: "normal"]
}
arm {
dimension "arch"
ndk {
abiFilters "armeabi-v7a", "arm64-v8a"
manifestPlaceholders += [ARCH: "arm"]
}
}
x86 {
dimension "arch"
ndk {
abiFilters "x86", "x86_64"
manifestPlaceholders += [ARCH: "x86"]
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
greendao {
schemaVersion 1
daoPackage 'wang.switchy.hin2n.storage.db.base'
targetGenDir 'src/main/java'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:design:25.4.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:25.+'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'org.greenrobot:greendao:3.2.0'
}

17
android/Hin2n/android_studio_gradle_4.4/app/proguard-rules.pro

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\Users\janiszhang\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

27
android/Hin2n/android_studio_gradle_4.4/build.gradle

@ -0,0 +1,27 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

19
android/Hin2n/android_studio_gradle_4.4/gradle.properties

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.daemon=true

BIN
android/Hin2n/android_studio_gradle_4.4/gradle/wrapper/gradle-wrapper.jar

Binary file not shown.

6
android/Hin2n/android_studio_gradle_4.4/gradle/wrapper/gradle-wrapper.properties

@ -0,0 +1,6 @@
#Wed Apr 18 23:44:31 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

160
android/Hin2n/android_studio_gradle_4.4/gradlew

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
android/Hin2n/android_studio_gradle_4.4/gradlew.bat

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
android/Hin2n/android_studio_gradle_4.4/settings.gradle

@ -0,0 +1 @@
include ':app'

1
android/Hin2n/app/.gitignore

@ -0,0 +1 @@
/build

56
android/Hin2n/app/CMakeLists.txt

@ -0,0 +1,56 @@
project(Hin2n)
cmake_minimum_required(VERSION 3.4.1)
# N2n information
set(N2N_VERSION 2.1.0)
set(N2N_OSNAME ${CMAKE_SYSTEM})
INCLUDE(TestBigEndian)
TEST_BIG_ENDIAN(UIP_CONF_BYTE_ORDER)
if(${UIP_CONF_BYTE_ORDER} EQUAL 1)
set(UIP_CONF_BYTE_ORDER UIP_BIG_ENDIAN)
else(${UIP_CONF_BYTE_ORDER} EQUAL 1)
set(UIP_CONF_BYTE_ORDER UIP_LITTLE_ENDIAN)
endif(${UIP_CONF_BYTE_ORDER} EQUAL 1)
if(CMAKE_BUILD_TYPE)
if(NOT ${CMAKE_BUILD_TYPE} STREQUAL Debug)
set(CMAKE_BUILD_TYPE Release)
endif(NOT ${CMAKE_BUILD_TYPE} STREQUAL Debug)
else(CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif(CMAKE_BUILD_TYPE)
add_definitions(-DN2N_VERSION=\"${N2N_VERSION}\" -DN2N_OSNAME=\"${N2N_OSNAME}\" -DUIP_CONF_BYTE_ORDER=\"${UIP_CONF_BYTE_ORDER}\")
include_directories(src/main/cpp src/main/cpp/tun2tap src/main/cpp/uip)
add_library(edge SHARED
src/main/cpp/n2n/android/edge_jni.c
src/main/cpp/n2n/android/edge_android.c
)
target_link_libraries(edge n2n)
target_link_libraries(edge log)
add_library(n2n SHARED
src/main/cpp/n2n/n2n.c
src/main/cpp/n2n/n2n_keyfile.c
src/main/cpp/n2n/wire.c
src/main/cpp/n2n/minilzo.c
src/main/cpp/n2n/twofish.c
src/main/cpp/n2n/edge_utils.c
src/main/cpp/n2n/transform_null.c
src/main/cpp/n2n/transform_tf.c
src/main/cpp/n2n/transform_aes.c
src/main/cpp/n2n/android/tuntap_android.c
src/main/cpp/n2n/version.c
)
target_link_libraries(n2n uip)
target_link_libraries(n2n log)
add_library(uip SHARED
src/main/cpp/uip/uip.c
src/main/cpp/uip/uip_arp.c
src/main/cpp/tun2tap/tun2tap.c
)

160
android/Hin2n/app/build.gradle

@ -0,0 +1,160 @@
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.android.application'
def getVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--all', '--count'
standardOutput = stdout
}
return Integer.parseInt(stdout.toString().trim())
}
catch (ignored) {
return -1;
}
}
def getVersionName = { ->
def ver = 'v0.5.2'
return ver
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--always', '--dirty', '--match', 'hin2n_v*'
standardOutput = stdout
}
return stdout.toString().trim()
}
catch (ignored) {
return null
}
}
def getEnvOrConsole = { env, prompt ->
def val = null
try {
val = System.getenv(env)
if (val == null || val == "") {
if (System.console() != null) {
val = System.console().readLine("\n" + prompt + ": ")
}
}
} catch (ignored) {
return null
}
return val
}
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "wang.switchy.hin2n"
minSdkVersion 14
targetSdkVersion 25
versionCode getVersionCode()
versionName getVersionName()
multiDexEnabled true
manifestPlaceholders = [CHANNEL_VALUE: "normal", ARCH: "all"]
resConfigs "en", "zh-rCN", "zh-rTW"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
signingConfigs {
debug {}
release {
storeFile file("Hin2n.jks")
storePassword getEnvOrConsole("HIN2N_KSTOREPWD", "Keystore password")
keyAlias "Hin2n"
keyPassword getEnvOrConsole("HIN2N_KEYPWD", "Key password")
}
}
buildTypes {
debug {
buildConfigField("boolean", "API_DEBUG", "true")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
buildConfigField("boolean", "API_DEBUG", "false")
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
def fileName = null
if (outputFile != null && outputFile.name.endsWith('.apk')) {
variant.mergedFlavor.versionName = getVersionName()
def channel = variant.mergedFlavor.manifestPlaceholders.CHANNEL_VALUE
def arch = variant.mergedFlavor.manifestPlaceholders.ARCH
fileName = "hin2n_${variant.mergedFlavor.versionName}_${channel}_${arch}_${variant.buildType.name}.apk"
output.outputFile = new File(output.outputFile.parent, fileName)
}
}
}
flavorDimensions "channel", "arch"
productFlavors {
normal {
dimension "channel"
manifestPlaceholders += [CHANNEL_VALUE: "normal"]
}
arm {
dimension "arch"
ndk {
abiFilters "armeabi-v7a", "arm64-v8a"
manifestPlaceholders += [ARCH: "arm"]
}
}
x86 {
dimension "arch"
ndk {
abiFilters "x86", "x86_64"
manifestPlaceholders += [ARCH: "x86"]
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
greendao {
schemaVersion 1
daoPackage 'wang.switchy.hin2n.storage.db.base'
targetGenDir 'src/main/java'
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.+'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'org.greenrobot:greendao:3.2.0'
}

17
android/Hin2n/app/proguard-rules.pro

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\Users\janiszhang\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

26
android/Hin2n/app/src/androidTest/java/wang/switchy/hin2n/ExampleInstrumentedTest.java

@ -0,0 +1,26 @@
package wang.switchy.hin2n;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.n2n.hin2n", appContext.getPackageName());
}
}

36
android/Hin2n/app/src/main/AndroidManifest.xml

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wang.switchy.hin2n">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".Hin2nApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.ListActivity"
android:screenOrientation="portrait"/>
<activity android:name=".activity.SettingDetailsActivity"
android:screenOrientation="portrait"/>
<service android:name=".service.N2NService"
android:permission="android.permission.BIND_VPN_SERVICE">
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
</service>
</application>
</manifest>

1
android/Hin2n/app/src/main/cpp/n2n

@ -0,0 +1 @@
../../../../../..

1
android/Hin2n/app/src/main/cpp/tun2tap

@ -0,0 +1 @@
../../../../../tun2tap

1
android/Hin2n/app/src/main/cpp/uip

@ -0,0 +1 @@
../../../../../uip/uip

56
android/Hin2n/app/src/main/java/wang/switchy/hin2n/Hin2nApplication.java

@ -0,0 +1,56 @@
package wang.switchy.hin2n;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDexApplication;
import wang.switchy.hin2n.storage.db.base.DaoMaster;
import wang.switchy.hin2n.storage.db.base.DaoSession;
/**
* Created by janiszhang on 2018/4/19.
*/
public class Hin2nApplication extends MultiDexApplication {
public Context AppContext;
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static Hin2nApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
AppContext = this;
setDatabase();
}
public static Hin2nApplication getInstance(){
return instance;
}
private void setDatabase() {
mHelper = new DaoMaster.DevOpenHelper(this, "N2N-db", null);
db = mHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}

59
android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/BaseActivity.java

@ -0,0 +1,59 @@
package wang.switchy.hin2n.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import wang.switchy.hin2n.template.BaseTemplate;
/**
* Created by janiszhang on 2018/4/13.
*/
public abstract class BaseActivity extends AppCompatActivity {
protected Activity mContext;
protected View mContentView;
protected BaseTemplate mTemplate;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
mContext = this;
mTemplate = createTemplate();
if (mTemplate != null) {
if (getContentLayout() != 0) {
mContentView = LayoutInflater.from(mContext).inflate(getContentLayout(), null);
mTemplate.setContentView(mContentView);
}
setContentView(mTemplate.getPageView());
}
doOnCreate(savedInstanceState);
}
protected abstract BaseTemplate createTemplate();
protected abstract void doOnCreate(Bundle savedInstanceState);
protected abstract int getContentLayout();
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}

166
android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/ListActivity.java

@ -0,0 +1,166 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.adapter.SettingItemAdapter;
import wang.switchy.hin2n.entity.SettingItemEntity;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
/**
* Created by janiszhang on 2018/5/4.
*/
public class ListActivity extends BaseActivity {
private ListView mSettingsListView;
private SettingItemAdapter mSettingItemAdapter;
private ArrayList<SettingItemEntity> mSettingItemEntities;
private SharedPreferences mHin2nSp;
private SharedPreferences.Editor mHin2nEdit;
private TextView mMoreInfo;
private N2NSettingModel mN2NSettingModel;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(mContext, "Setting List");
titleTemplate.mRightImg.setVisibility(View.VISIBLE);
titleTemplate.mRightImg.setImageResource(R.mipmap.img_add);
titleTemplate.mRightImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ListActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_ADD);
startActivity(intent);
}
});
titleTemplate.mLeftImg.setVisibility(View.VISIBLE);
titleTemplate.mLeftImg.setImageResource(R.drawable.titlebar_icon_return_selector);
titleTemplate.mLeftImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
mHin2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
mHin2nEdit = mHin2nSp.edit();
mSettingsListView = (ListView) findViewById(R.id.lv_setting_item);
mSettingItemEntities = new ArrayList<>();
mSettingItemAdapter = new SettingItemAdapter(this, mSettingItemEntities);
mSettingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
for (int i = 0; i < mSettingItemEntities.size(); i++) {
mSettingItemEntities.get(i).setSelected(false);
}
mSettingItemAdapter.notifyDataSetChanged();
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
mN2NSettingModel = n2NSettingModelDao.load(mSettingItemEntities.get(position).getSaveId());
mN2NSettingModel.setIsSelcected(true);
n2NSettingModelDao.update(mN2NSettingModel);
mHin2nEdit.putLong("current_setting_id", mN2NSettingModel.getId());
mHin2nEdit.commit();
mSettingItemEntities.get(position).setSelected(true);
mSettingItemAdapter.notifyDataSetChanged();
}
});
mSettingsListView.setAdapter(mSettingItemAdapter);
}
@Override
protected void onResume() {
super.onResume();
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
List<N2NSettingModel> n2NSettingModels = n2NSettingModelDao.loadAll();
N2NSettingModel n2NSettingModel;
mSettingItemEntities.clear();
for (int i = 0; i < n2NSettingModels.size(); i++) {
n2NSettingModel = n2NSettingModels.get(i);
final SettingItemEntity settingItemEntity = new SettingItemEntity(n2NSettingModel.getName(),
n2NSettingModel.getId(), n2NSettingModel.getIsSelcected());
settingItemEntity.setOnMoreBtnClickListener(new SettingItemEntity.OnMoreBtnClickListener() {
@Override
public void onClick() {
Intent intent = new Intent(ListActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_MODIFY);
intent.putExtra("saveId", settingItemEntity.getSaveId());
startActivity(intent);
}
});
mSettingItemEntities.add(settingItemEntity);
}
mSettingItemAdapter.notifyDataSetChanged();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Intent intent = new Intent(ListActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mN2NSettingModel);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
protected int getContentLayout() {
return R.layout.activity_setting_list;
}
}

187
android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/MainActivity.java

@ -0,0 +1,187 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.event.ErrorEvent;
import wang.switchy.hin2n.event.StartEvent;
import wang.switchy.hin2n.event.StopEvent;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
public class MainActivity extends BaseActivity {
private Button mActionBtn;
static {
System.loadLibrary("uip");
System.loadLibrary("n2n");
System.loadLibrary("edge");
}
private N2NSettingModel mCurrentSettingInfo;
private RelativeLayout mCurrentSettingItem;
private TextView mCurrentSettingName;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(this, "Hin2n");
titleTemplate.mRightImg.setImageResource(R.mipmap.img_add);
titleTemplate.mRightImg.setVisibility(View.VISIBLE);
titleTemplate.mRightImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SettingDetailsActivity.class);
intent.putExtra("type", SettingDetailsActivity.TYPE_SETTING_ADD);
startActivity(intent);
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
mCurrentSettingItem = (RelativeLayout) findViewById(R.id.rl_current_setting_item);
mCurrentSettingItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
Toast.makeText(mContext, "~Running~", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, ListActivity.class));
}
}
});
mCurrentSettingName = (TextView) findViewById(R.id.tv_current_setting_name);
mActionBtn = (Button) findViewById(R.id.btn_action);
if (N2NService.INSTANCE == null) {
mActionBtn.setText("start");
} else {
if (N2NService.INSTANCE.getEdgeStatus().isRunning) {
mActionBtn.setText("stop");
} else {
mActionBtn.setText("start");
}
}
mActionBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentSettingName.getText().equals("--null--")) {
Toast.makeText(mContext, "null setting", Toast.LENGTH_SHORT).show();
return;
}
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
} else {
Intent vpnPrepareIntent = VpnService.prepare(MainActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
}
}
});
}
@Override
protected int getContentLayout() {
return R.layout.activity_main;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Intent intent = new Intent(MainActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mCurrentSettingInfo);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences n2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
Long currentSettingId = n2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
mCurrentSettingInfo = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (mCurrentSettingInfo != null) {
mCurrentSettingName.setText(mCurrentSettingInfo.getName());
} else {
mCurrentSettingName.setText("--null--");
}
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onStartEvent(StartEvent event) {
mActionBtn.setText("stop");
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onStopEvent(StopEvent event) {
mActionBtn.setText("start");
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onErrorEvent(ErrorEvent event) {
mActionBtn.setText("start");
Toast.makeText(mContext, "~_~Error~_~", Toast.LENGTH_SHORT).show();
}
}

543
android/Hin2n/app/src/main/java/wang/switchy/hin2n/activity/SettingDetailsActivity.java

@ -0,0 +1,543 @@
package wang.switchy.hin2n.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import wang.switchy.hin2n.Hin2nApplication;
import wang.switchy.hin2n.service.N2NService;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.model.EdgeCmd;
import wang.switchy.hin2n.model.N2NSettingInfo;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.template.BaseTemplate;
import wang.switchy.hin2n.template.CommonTitleTemplate;
/**
* Created by janiszhang on 2018/5/4.
*/
public class SettingDetailsActivity extends BaseActivity implements View.OnClickListener {
public static int TYPE_SETTING_ADD = 0;
public static int TYPE_SETTING_MODIFY = 1;
private int type = TYPE_SETTING_ADD;
private TextInputLayout mIpAddressTIL;
private TextInputLayout mNetMaskTIL;
private TextInputLayout mCommunityTIL;
private TextInputLayout mEncryptTIL;
private TextInputLayout mSuperNodeTIL;
private Button mSaveBtn;
private SharedPreferences mHin2nSp;
private SharedPreferences.Editor mHin2nEdit;
private TextInputLayout mSettingName;
private CheckBox mSaveAndSetCheckBox;
private TextInputLayout mSuperNodeBackup;
private TextInputLayout mMacAddr;
private TextInputLayout mMtu;
private CheckBox mResoveSupernodeIPCheckBox;
private TextInputLayout mLocalPort;
private CheckBox mAllowRoutinCheckBox;
private CheckBox mDropMuticastCheckBox;
private Spinner mTraceLevelSpinner;
private CheckBox mMoreSettingCheckBox;
private RelativeLayout mMoreSettingView;
private N2NSettingModel mN2NSettingModel;
private Button mModifyBtn;
private LinearLayout mButtons;
private Button mDeleteBtn;
private long mSaveId;
private ArrayList<String> mTraceLevelList;
@Override
protected BaseTemplate createTemplate() {
CommonTitleTemplate titleTemplate = new CommonTitleTemplate(mContext, "Add New Setting");
titleTemplate.mLeftImg.setVisibility(View.VISIBLE);
titleTemplate.mLeftImg.setImageResource(R.drawable.titlebar_icon_return_selector);
titleTemplate.mLeftImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
return titleTemplate;
}
@Override
protected void doOnCreate(Bundle savedInstanceState) {
mHin2nSp = getSharedPreferences("Hin2n", MODE_PRIVATE);
mHin2nEdit = mHin2nSp.edit();
mSettingName = (TextInputLayout) findViewById(R.id.til_setting_name);
mIpAddressTIL = (TextInputLayout) findViewById(R.id.til_ip_address);
mNetMaskTIL = (TextInputLayout) findViewById(R.id.til_net_mask);
mCommunityTIL = (TextInputLayout) findViewById(R.id.til_community);
mEncryptTIL = (TextInputLayout) findViewById(R.id.til_encrypt);
mEncryptTIL.getEditText().setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏
mSuperNodeTIL = (TextInputLayout) findViewById(R.id.til_super_node);
mMoreSettingView = (RelativeLayout) findViewById(R.id.rl_more_setting);
mMoreSettingCheckBox = (CheckBox) findViewById(R.id.more_setting_check_box);
mMoreSettingCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
mMoreSettingView.setVisibility(View.VISIBLE);
} else {
mMoreSettingView.setVisibility(View.GONE);
}
}
});
mSuperNodeBackup = (TextInputLayout) findViewById(R.id.til_super_node_2);
mMacAddr = (TextInputLayout) findViewById(R.id.til_mac_addr);
mMtu = (TextInputLayout) findViewById(R.id.til_mtu);
mResoveSupernodeIPCheckBox = (CheckBox) findViewById(R.id.resove_super_node_ip_check_box);
mLocalPort = (TextInputLayout) findViewById(R.id.til_local_port);
mAllowRoutinCheckBox = (CheckBox) findViewById(R.id.allow_routing_check_box);
mDropMuticastCheckBox = (CheckBox) findViewById(R.id.drop_muticast_check_box);
mTraceLevelSpinner = (Spinner) findViewById(R.id.spinner_trace_level);
mTraceLevelList = new ArrayList<>();
// 0:ERROR, 1: WARNING, 2: NORMAL, 3: INFO, 4: DEBUG
mTraceLevelList.add("ERROR");
mTraceLevelList.add("WARNING");
mTraceLevelList.add("NORMAL");
mTraceLevelList.add("INFO");
mTraceLevelList.add("DEBUG");
final ArrayAdapter<String> traceLevelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mTraceLevelList);
traceLevelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mTraceLevelSpinner.setAdapter(traceLevelAdapter);
mTraceLevelSpinner.setSelection(1);
mTraceLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = traceLevelAdapter.getItem(position);
int selectedItemPosition = mTraceLevelSpinner.getSelectedItemPosition();
String traceLevel = mTraceLevelList.get(selectedItemPosition);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mSaveAndSetCheckBox = (CheckBox) findViewById(R.id.check_box);
mSaveBtn = (Button) findViewById(R.id.btn_save);
mSaveBtn.setOnClickListener(this);
mButtons = (LinearLayout) findViewById(R.id.ll_buttons);
mModifyBtn = (Button) findViewById(R.id.btn_modify);
mModifyBtn.setOnClickListener(this);
mDeleteBtn = (Button) findViewById(R.id.btn_delete);
mDeleteBtn.setOnClickListener(this);
Intent intent = getIntent();
type = intent.getIntExtra("type", 0);
if (type == TYPE_SETTING_ADD) {
mMtu.getEditText().setText("1400");
mDropMuticastCheckBox.setChecked(true);
mTraceLevelSpinner.setSelection(1);
mSaveBtn.setVisibility(View.VISIBLE);
mButtons.setVisibility(View.GONE);
} else if (type == TYPE_SETTING_MODIFY) {
mSaveId = intent.getLongExtra("saveId", 0);
mN2NSettingModel = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load(mSaveId);
mSettingName.getEditText().setText(mN2NSettingModel.getName());
mIpAddressTIL.getEditText().setText(mN2NSettingModel.getIp());
mNetMaskTIL.getEditText().setText(mN2NSettingModel.getNetmask());
mCommunityTIL.getEditText().setText(mN2NSettingModel.getCommunity());
mEncryptTIL.getEditText().setText(mN2NSettingModel.getPassword());
mSuperNodeTIL.getEditText().setText(mN2NSettingModel.getSuperNode());
mSuperNodeBackup.getEditText().setText(mN2NSettingModel.getSuperNodeBackup());
mMacAddr.getEditText().setText(mN2NSettingModel.getMacAddr());
mMtu.getEditText().setText(String.valueOf(mN2NSettingModel.getMtu()));
mResoveSupernodeIPCheckBox.setChecked(mN2NSettingModel.getResoveSupernodeIP());
mLocalPort.getEditText().setText(String.valueOf(mN2NSettingModel.getLocalPort()));
mAllowRoutinCheckBox.setChecked(mN2NSettingModel.getAllowRouting());
mDropMuticastCheckBox.setChecked(mN2NSettingModel.getDropMuticast());
mTraceLevelSpinner.setSelection(Integer.valueOf(mN2NSettingModel.getTraceLevel()));
if (mN2NSettingModel.getMoreSettings()) {
mMoreSettingCheckBox.setChecked(true);
mMoreSettingView.setVisibility(View.VISIBLE);
} else {
mMoreSettingCheckBox.setChecked(false);
}
mButtons.setVisibility(View.VISIBLE);
mSaveBtn.setVisibility(View.GONE);
}
}
@Override
protected int getContentLayout() {
return R.layout.activity_add_item;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == -RESULT_OK) {
Intent intent = new Intent(SettingDetailsActivity.this, N2NService.class);
Bundle bundle = new Bundle();
N2NSettingInfo n2NSettingInfo = new N2NSettingInfo(mN2NSettingModel);
bundle.putParcelable("n2nSettingInfo", n2NSettingInfo);
intent.putExtra("Setting", bundle);
startService(intent);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_save:
if (!checkValues()) {
return;
}
if (mSaveAndSetCheckBox.isChecked()) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName = mSettingName.getEditText().getText().toString();
String setingNameTmp = settingName;
int i = 0;
while (n2NSettingModelDao.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName)).unique() != null) {
i++;
settingName = setingNameTmp + "(" + i + ")";
}
long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), true);
id = n2NSettingModelDao.insert(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, true);
id = n2NSettingModelDao.insert(mN2NSettingModel);
}
mHin2nEdit.putLong("current_setting_id", id);
mHin2nEdit.commit();
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
}
Intent vpnPrepareIntent = VpnService.prepare(SettingDetailsActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
} else {
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName = mSettingName.getEditText().getText().toString();
String setingNameTmp = settingName;
int i = 0;
while (n2NSettingModelDao.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName)).unique() != null) {
i++;
settingName = setingNameTmp + "(" + i + ")";
}
Long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), false);
id = n2NSettingModelDao.insert(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(null, settingName, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, false);
id = n2NSettingModelDao.insert(mN2NSettingModel);
}
}
Toast.makeText(mContext, "Add Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.btn_modify:
if (!checkValues()) {
return;
}
if (mSaveAndSetCheckBox.isChecked()) {
Long currentSettingId = mHin2nSp.getLong("current_setting_id", -1);
if (currentSettingId != -1) {
N2NSettingModel currentSettingItem = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().load((long) currentSettingId);
if (currentSettingItem != null) {
currentSettingItem.setIsSelcected(false);
Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao().update(currentSettingItem);
}
}
N2NSettingModelDao n2NSettingModelDao1 = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName1 = mSettingName.getEditText().getText().toString();
String setingNameTmp1 = settingName1;
int i1 = 0;
N2NSettingModel n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
while (n2NSettingModelTmp != null) {
if (n2NSettingModelTmp.getId() == mSaveId) {
break;
}
i1++;
settingName1 = setingNameTmp1 + "(" + i1 + ")";
n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
}
long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), true);
n2NSettingModelDao1.update(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, true);
n2NSettingModelDao1.update(mN2NSettingModel);
}
mHin2nEdit.putLong("current_setting_id", mSaveId);
mHin2nEdit.commit();
if (N2NService.INSTANCE != null && N2NService.INSTANCE.getEdgeStatus().isRunning) {
N2NService.INSTANCE.stop();
}
Intent vpnPrepareIntent = VpnService.prepare(SettingDetailsActivity.this);
if (vpnPrepareIntent != null) {
startActivityForResult(vpnPrepareIntent, 100);
} else {
onActivityResult(100, RESULT_OK, null);
}
} else {
N2NSettingModelDao n2NSettingModelDao1 = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
String settingName1 = mSettingName.getEditText().getText().toString();
String setingNameTmp1 = settingName1;
int i1 = 0;
N2NSettingModel n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
while (n2NSettingModelTmp != null) {
if (n2NSettingModelTmp.getId() == mSaveId) {
break;
}
i1++;
settingName1 = setingNameTmp1 + "(" + i1 + ")";
n2NSettingModelTmp = n2NSettingModelDao1.queryBuilder().where(N2NSettingModelDao.Properties.Name.eq(settingName1)).unique();
}
Long id;
if (mMoreSettingCheckBox.isChecked()) {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), true, mSuperNodeBackup.getEditText().getText().toString(),
TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) ? EdgeCmd.getRandomMac() : mMacAddr.getEditText().getText().toString(),
TextUtils.isEmpty(mMtu.getEditText().getText().toString()) ? 1400 : Integer.valueOf(mMtu.getEditText().getText().toString()),
mResoveSupernodeIPCheckBox.isChecked(), TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) ? 0 : Integer.valueOf(mLocalPort.getEditText().getText().toString()),
mAllowRoutinCheckBox.isChecked(), mDropMuticastCheckBox.isChecked(), mTraceLevelSpinner.getSelectedItemPosition(), mN2NSettingModel.getIsSelcected());
n2NSettingModelDao1.update(mN2NSettingModel);
} else {
mN2NSettingModel = new N2NSettingModel(mSaveId, settingName1, mIpAddressTIL.getEditText().getText().toString(),
TextUtils.isEmpty(mNetMaskTIL.getEditText().getText()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString(),
mCommunityTIL.getEditText().getText().toString(), mEncryptTIL.getEditText().getText().toString(),
mSuperNodeTIL.getEditText().getText().toString(), false, "", EdgeCmd.getRandomMac(), 1400, false, 0, false, true, 1, mN2NSettingModel.getIsSelcected());
n2NSettingModelDao1.update(mN2NSettingModel);
}
}
Toast.makeText(mContext, "Update Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.btn_delete:
N2NSettingModelDao n2NSettingModelDao = Hin2nApplication.getInstance().getDaoSession().getN2NSettingModelDao();
n2NSettingModelDao.deleteByKey(mSaveId);
Toast.makeText(mContext, "Delete Succeed", Toast.LENGTH_SHORT).show();
finish();
break;
default:
break;
}
}
private boolean checkValues() {
if (TextUtils.isEmpty(mSettingName.getEditText().getText())
|| TextUtils.isEmpty(mIpAddressTIL.getEditText().getText())
|| TextUtils.isEmpty(mCommunityTIL.getEditText().getText())
|| TextUtils.isEmpty(mSuperNodeTIL.getEditText().getText())) {
if (TextUtils.isEmpty(mSuperNodeTIL.getEditText().getText())) {
mSuperNodeTIL.setError("Required");
mSuperNodeTIL.getEditText().requestFocus();
} else {
mSuperNodeTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mCommunityTIL.getEditText().getText())) {
mCommunityTIL.setError("Required");
mCommunityTIL.getEditText().requestFocus();
} else {
mCommunityTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mIpAddressTIL.getEditText().getText())) {
mIpAddressTIL.setError("Required");
mIpAddressTIL.getEditText().requestFocus();
} else {
mIpAddressTIL.setErrorEnabled(false);
}
if (TextUtils.isEmpty(mSettingName.getEditText().getText())) {
mSettingName.setError("Required");
mSettingName.getEditText().requestFocus();
} else {
mSettingName.setErrorEnabled(false);
}
return false;
}
if (!EdgeCmd.checkIPV4(mIpAddressTIL.getEditText().getText().toString())) {
mIpAddressTIL.setError("IP Address Error!");
mIpAddressTIL.getEditText().requestFocus();
return false;
} else {
mIpAddressTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkIPV4Mask(TextUtils.isEmpty(mNetMaskTIL.getEditText().getText().toString()) ? "255.255.255.0" : mNetMaskTIL.getEditText().getText().toString())) {
mNetMaskTIL.setError("NetMask Error!");
mNetMaskTIL.getEditText().requestFocus();
return false;
} else {
mNetMaskTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkCommunity(mCommunityTIL.getEditText().getText().toString())) {
mCommunityTIL.setError("Community Error!");
mCommunityTIL.getEditText().requestFocus();
return false;
} else {
mCommunityTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkEncKey(mEncryptTIL.getEditText().getText().toString())) {
mEncryptTIL.setError("Password Error!");
mEncryptTIL.getEditText().requestFocus();
return false;
} else {
mEncryptTIL.setErrorEnabled(false);
}
if (!EdgeCmd.checkSupernode(mSuperNodeTIL.getEditText().getText().toString())) {
mSuperNodeTIL.setError("Supernode Error!");
mSuperNodeTIL.getEditText().requestFocus();
return false;
} else {
mSuperNodeTIL.setErrorEnabled(false);
}
if (mMoreSettingCheckBox.isChecked()) {
if (!TextUtils.isEmpty(mSuperNodeBackup.getEditText().getText().toString()) && !EdgeCmd.checkSupernode(mSuperNodeBackup.getEditText().getText().toString())) {
mSuperNodeBackup.setError("Supernode Back Error!");
mSuperNodeBackup.getEditText().requestFocus();
return false;
} else {
mSuperNodeBackup.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mMacAddr.getEditText().getText().toString()) && !EdgeCmd.checkMacAddr(mMacAddr.getEditText().getText().toString())) {
mMacAddr.setError("Mac Address Error!");
mMacAddr.getEditText().requestFocus();
return false;
} else {
mMacAddr.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mMtu.getEditText().getText().toString()) && !EdgeCmd.checkInt(Integer.valueOf(mMtu.getEditText().getText().toString()), 46, 1500)) {
mMtu.setError("Mtu Error!");
mMtu.getEditText().requestFocus();
return false;
} else {
mMtu.setErrorEnabled(false);
}
if (!TextUtils.isEmpty(mLocalPort.getEditText().getText().toString()) && !EdgeCmd.checkInt(Integer.valueOf(mLocalPort.getEditText().getText().toString()), 0, 65535)) {
mLocalPort.setError("Local Port Error!");
mLocalPort.getEditText().requestFocus();
return false;
} else {
mLocalPort.setErrorEnabled(false);
}
}
return true;
}
}

89
android/Hin2n/app/src/main/java/wang/switchy/hin2n/adapter/SettingItemAdapter.java

@ -0,0 +1,89 @@
package wang.switchy.hin2n.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
import wang.switchy.hin2n.R;
import wang.switchy.hin2n.entity.SettingItemEntity;
/**
* Created by janiszhang on 2018/5/6.
*/
public class SettingItemAdapter extends BaseAdapter {
private Context mContext;
private List<SettingItemEntity> mSettingItemEntities;
private final LayoutInflater mLayoutInflater;
public SettingItemAdapter(Context context, List<SettingItemEntity> settingItemEntities) {
mContext = context;
mSettingItemEntities = settingItemEntities;
mLayoutInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mSettingItemEntities.size();
}
@Override
public Object getItem(int i) {
return mSettingItemEntities.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final SettingItemEntity settingItemEntity = mSettingItemEntities.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.layout_setting_item, null);
viewHolder = new ViewHolder();
viewHolder.settingName = (TextView) convertView.findViewById(R.id.tv_setting_name);
viewHolder.imgIsSelected = (ImageView) convertView.findViewById(R.id.iv_selected);
viewHolder.moreInfo = (TextView) convertView.findViewById(R.id.tv_more);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.settingName.setText(settingItemEntity.getSettingName());
if (settingItemEntity.isSelected()) {
viewHolder.imgIsSelected.setVisibility(View.VISIBLE);
} else {
viewHolder.imgIsSelected.setVisibility(View.INVISIBLE);
}
viewHolder.moreInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
settingItemEntity.mOnMoreBtnClickListener.onClick();
}
});
return convertView;
}
class ViewHolder {
TextView settingName;
ImageView imgIsSelected;
TextView moreInfo;
}
}

51
android/Hin2n/app/src/main/java/wang/switchy/hin2n/entity/SettingItemEntity.java

@ -0,0 +1,51 @@
package wang.switchy.hin2n.entity;
/**
* Created by janiszhang on 2018/5/5.
*/
public class SettingItemEntity {
private String mSettingName;
private Long mSaveId;
private boolean isSelected;
public SettingItemEntity(String settingName, Long saveId, boolean isSelected) {
mSettingName = settingName;
mSaveId = saveId;
this.isSelected = isSelected;
}
public String getSettingName() {
return mSettingName;
}
public void setSettingName(String settingName) {
mSettingName = settingName;
}
public Long getSaveId() {
return mSaveId;
}
public void setSaveId(Long saveId) {
mSaveId = saveId;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public OnMoreBtnClickListener mOnMoreBtnClickListener;
public void setOnMoreBtnClickListener(OnMoreBtnClickListener onMoreBtnClickListener) {
mOnMoreBtnClickListener = onMoreBtnClickListener;
}
public interface OnMoreBtnClickListener {
void onClick();
}
}

8
android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/ErrorEvent.java

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class ErrorEvent {
}

8
android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/StartEvent.java

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class StartEvent {
}

8
android/Hin2n/app/src/main/java/wang/switchy/hin2n/event/StopEvent.java

@ -0,0 +1,8 @@
package wang.switchy.hin2n.event;
/**
* Created by janiszhang on 2018/4/21.
*/
public class StopEvent {
}

152
android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/EdgeCmd.java

@ -0,0 +1,152 @@
package wang.switchy.hin2n.model;
import android.util.Log;
import java.util.Random;
import java.util.Vector;
public class EdgeCmd {
public String ipAddr;
public String ipNetmask;
public String[] supernodes;
public String community;
public String encKey;
public String encKeyFile;
public String macAddr;
public int mtu;
public boolean reResoveSupernodeIP;
public int localPort;
public boolean allowRouting;
public boolean dropMuticast;
public int traceLevel;
public int vpnFd;
public static boolean checkIPV4(String ip) {
if (ip == null || ip.length() < 7 || ip.length() > 15) {
return false;
}
String[] split = ip.split("\\.");
if (split == null || split.length != 4) {
return false;
}
try {
for (int i = 0; i < split.length; ++i) {
int n = Integer.parseInt(split[i]);
if (n < 0 || n > 255 || !String.valueOf(n).equals(split[i])) {
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static boolean checkIPV4Mask(String netmask) {
int[] arr = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF};
if (netmask == null || netmask.length() < 7 || netmask.length() > 15) {
return false;
}
String[] split = netmask.split("\\.");
if (split == null || split.length != 4) {
return false;
}
try {
for (int i = 0; i < split.length; ++i) {
int n = Integer.parseInt(split[i]);
boolean flag = false;
for (int j = 0; j < arr.length; ++j) {
if (n == arr[j]) {
flag = true;
break;
}
}
if (!flag || !String.valueOf(n).equals(split[i])) {
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static boolean checkSupernode(String supernode) {
if (supernode == null || supernode.isEmpty() || supernode.length() > 47) {
return false;
}
String[] split = supernode.split(":");
if (split == null || split.length != 2 || split[0].isEmpty()) {
return false;
}
int n = Integer.parseInt(split[1]);
if (n < 0 || n > 65535 || !String.valueOf(n).equals(split[1])) {
return false;
}
return true;
}
public static boolean checkCommunity(String community) {
if (community == null || community.isEmpty() || community.length() > 15) {
return false;
}
return true;
}
public static boolean checkEncKey(String encKey) {
return true;
}
public static boolean checkEncKeyFile(String encKeyFile) {
return true;
}
public static boolean checkMacAddr(String mac) {
String hex = "0123456789abcdef";
if (mac == null || mac.length() != 17) {
return false;
}
for (int i = 0; i < mac.length(); ++i) {
char c = mac.charAt(i);
if ((i + 1) % 3 == 0) {
if (c != ':') {
return false;
}
continue;
}
if (!hex.contains(String.valueOf(c))) {
return false;
}
}
return true;
}
public static boolean checkInt(int n, int min, int max) {
if (n < min || n > max) {
return false;
}
return true;
}
public static String getRandomMac() {
String mac = "", hex="0123456789abcdef";
Random rand = new Random();
for (int i = 0; i < 17; ++i)
{
if ((i + 1) % 3 == 0) {
mac += ':';
continue;
}
mac += hex.charAt(rand.nextInt(16));
}
return mac;
}
}

9
android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/EdgeStatus.java

@ -0,0 +1,9 @@
package wang.switchy.hin2n.model;
//
// Created by switchwang(https://github.com/switch-st) on 2018-04-28.
//
public class EdgeStatus {
public boolean isRunning;
}

254
android/Hin2n/app/src/main/java/wang/switchy/hin2n/model/N2NSettingInfo.java

@ -0,0 +1,254 @@
package wang.switchy.hin2n.model;
import android.os.Parcel;
import android.os.Parcelable;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
/**
* Created by janiszhang on 2018/5/11.
*/
public class N2NSettingInfo implements Parcelable {
Long id;
String name;
String ip;
String netmask;
String community;
String password;
String superNode;
boolean moreSettings;
String superNodeBackup;
String macAddr;
int mtu;
boolean resoveSupernodeIP;
int localPort;
boolean allowRouting;
boolean dropMuticast;
int traceLevel;
public N2NSettingInfo(N2NSettingModel n2NSettingModel) {
this.id = n2NSettingModel.getId();
this.name = n2NSettingModel.getName();
this.ip = n2NSettingModel.getIp();
this.netmask = n2NSettingModel.getNetmask();
this.community = n2NSettingModel.getCommunity();
this.password = n2NSettingModel.getPassword();
this.superNode = n2NSettingModel.getSuperNode();
this.moreSettings = n2NSettingModel.getMoreSettings();
this.superNodeBackup = n2NSettingModel.getSuperNodeBackup();
this.macAddr = n2NSettingModel.getMacAddr();
this.mtu = n2NSettingModel.getMtu();
this.resoveSupernodeIP = n2NSettingModel.getResoveSupernodeIP();
this.localPort = n2NSettingModel.getLocalPort();
this.allowRouting = n2NSettingModel.getAllowRouting();
this.dropMuticast = n2NSettingModel.getDropMuticast();
this.traceLevel = n2NSettingModel.getTraceLevel();
}
protected N2NSettingInfo(Parcel in) {
name = in.readString();
ip = in.readString();
netmask = in.readString();
community = in.readString();
password = in.readString();
superNode = in.readString();
moreSettings = in.readByte() != 0;
superNodeBackup = in.readString();
macAddr = in.readString();
mtu = in.readInt();
resoveSupernodeIP = in.readByte() != 0;
localPort = in.readInt();
allowRouting = in.readByte() != 0;
dropMuticast = in.readByte() != 0;
traceLevel = in.readInt();
}
public static final Creator<N2NSettingInfo> CREATOR = new Creator<N2NSettingInfo>() {
@Override
public N2NSettingInfo createFromParcel(Parcel in) {
return new N2NSettingInfo(in);
}
@Override
public N2NSettingInfo[] newArray(int size) {
return new N2NSettingInfo[size];
}
};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getCommunity() {
return community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSuperNode() {
return superNode;
}
public void setSuperNode(String superNode) {
this.superNode = superNode;
}
public boolean isMoreSettings() {
return moreSettings;
}
public void setMoreSettings(boolean moreSettings) {
this.moreSettings = moreSettings;
}
public String getSuperNodeBackup() {
return superNodeBackup;
}
public void setSuperNodeBackup(String superNodeBackup) {
this.superNodeBackup = superNodeBackup;
}
public String getMacAddr() {
return macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public int getMtu() {
return mtu;
}
public void setMtu(int mtu) {
this.mtu = mtu;
}
public boolean isResoveSupernodeIP() {
return resoveSupernodeIP;
}
public void setResoveSupernodeIP(boolean resoveSupernodeIP) {
this.resoveSupernodeIP = resoveSupernodeIP;
}
public int getLocalPort() {
return localPort;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public boolean isAllowRouting() {
return allowRouting;
}
public void setAllowRouting(boolean allowRouting) {
this.allowRouting = allowRouting;
}
public boolean isDropMuticast() {
return dropMuticast;
}
public void setDropMuticast(boolean dropMuticast) {
this.dropMuticast = dropMuticast;
}
public int getTraceLevel() {
return traceLevel;
}
public void setTraceLevel(int traceLevel) {
this.traceLevel = traceLevel;
}
@Override
public String toString() {
return "N2NSettingInfo{" +
"id=" + id +
", name='" + name + '\'' +
", ip='" + ip + '\'' +
", netmask='" + netmask + '\'' +
", community='" + community + '\'' +
", password='" + password + '\'' +
", superNode='" + superNode + '\'' +
", moreSettings=" + moreSettings +
", superNodeBackup='" + superNodeBackup + '\'' +
", macAddr='" + macAddr + '\'' +
", mtu=" + mtu +
", resoveSupernodeIP=" + resoveSupernodeIP +
", localPort=" + localPort +
", allowRouting=" + allowRouting +
", dropMuticast=" + dropMuticast +
", traceLevel=" + traceLevel +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(ip);
parcel.writeString(netmask);
parcel.writeString(community);
parcel.writeString(password);
parcel.writeString(superNode);
parcel.writeByte((byte) (moreSettings ? 1 : 0));
parcel.writeString(superNodeBackup);
parcel.writeString(macAddr);
parcel.writeInt(mtu);
parcel.writeByte((byte) (resoveSupernodeIP ? 1 : 0));
parcel.writeInt(localPort);
parcel.writeByte((byte) (allowRouting ? 1 : 0));
parcel.writeByte((byte) (dropMuticast ? 1 : 0));
parcel.writeInt(traceLevel);
}
}

187
android/Hin2n/app/src/main/java/wang/switchy/hin2n/service/N2NService.java

@ -0,0 +1,187 @@
package wang.switchy.hin2n.service;
import android.content.Intent;
import android.net.VpnService;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.net.InetAddress;
import wang.switchy.hin2n.event.ErrorEvent;
import wang.switchy.hin2n.event.StartEvent;
import wang.switchy.hin2n.event.StopEvent;
import wang.switchy.hin2n.model.EdgeCmd;
import wang.switchy.hin2n.model.EdgeStatus;
import wang.switchy.hin2n.model.N2NSettingInfo;
import static wang.switchy.hin2n.model.EdgeCmd.getRandomMac;
/**
* Created by janiszhang on 2018/4/15.
*/
public class N2NService extends VpnService {
public static N2NService INSTANCE;
private ParcelFileDescriptor mParcelFileDescriptor = null;
private EdgeCmd cmd;
private boolean mStartResult;
@Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle setting = intent.getBundleExtra("Setting");
N2NSettingInfo n2nSettingInfo = setting.getParcelable("n2nSettingInfo");
Builder b = new Builder();
b.setMtu(n2nSettingInfo.getMtu());
String ipAddress = n2nSettingInfo.getIp();
b.addAddress(ipAddress, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
String route = getRoute(ipAddress, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
b.addRoute(route, getIpAddrPrefixLength(n2nSettingInfo.getNetmask()));
try {
mParcelFileDescriptor = b.setSession("N2N").establish();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Toast.makeText(INSTANCE, "Parameter is not accepted by the operating system.", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
} catch (IllegalStateException e) {
e.printStackTrace();
Toast.makeText(INSTANCE, "Parameter cannot be applied by the operating system.", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
if (mParcelFileDescriptor == null) {
Toast.makeText(INSTANCE, "~error~", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
cmd = new EdgeCmd();
cmd.ipAddr = n2nSettingInfo.getIp();
cmd.ipNetmask = n2nSettingInfo.getNetmask();
cmd.supernodes = new String[2];
cmd.supernodes[0] = n2nSettingInfo.getSuperNode();
cmd.supernodes[1] = n2nSettingInfo.getSuperNodeBackup();
cmd.community = n2nSettingInfo.getCommunity();
cmd.encKey = n2nSettingInfo.getPassword();
cmd.encKeyFile = null;
cmd.macAddr = n2nSettingInfo.getMacAddr();
cmd.mtu = n2nSettingInfo.getMtu();
cmd.reResoveSupernodeIP = n2nSettingInfo.isResoveSupernodeIP();
cmd.localPort = n2nSettingInfo.getLocalPort();
cmd.allowRouting = n2nSettingInfo.isAllowRouting();
cmd.dropMuticast = n2nSettingInfo.isDropMuticast();
cmd.traceLevel = n2nSettingInfo.getTraceLevel();
cmd.vpnFd = mParcelFileDescriptor.detachFd();
try {
mStartResult = startEdge(cmd);
if (!mStartResult) {
EventBus.getDefault().post(new ErrorEvent());
}
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
public void stop() {
stopEdge();
try {
if (mParcelFileDescriptor != null) {
mParcelFileDescriptor.close();
mParcelFileDescriptor = null;
}
} catch (IOException e) {
e.printStackTrace();
}
EventBus.getDefault().post(new StopEvent());
}
@Override
public void onRevoke() {
super.onRevoke();
stop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
public native boolean startEdge(EdgeCmd cmd);
public native void stopEdge();
public native EdgeStatus getEdgeStatus();
public void reportEdgeStatus(EdgeStatus status) {
if (status != null) {
if (status.isRunning) {
EventBus.getDefault().post(new StartEvent());
} else {
EventBus.getDefault().post(new StopEvent());
}
}
}
private int getIpAddrPrefixLength(String netmask) {
try {
byte[] byteAddr = InetAddress.getByName(netmask).getAddress();
int prefixLength = 0;
for (int i = 0; i < byteAddr.length; i++) {
for (int j = 0; j < 8; j++) {
if ((byteAddr[i] << j & 0xFF) != 0) {
prefixLength++;
} else {
return prefixLength;
}
}
}
return prefixLength;
} catch (Exception e) {
return -1;
}
}
private String getRoute(String ipAddr, int prefixLength) {
byte[] arr = {(byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE, (byte) 0xFF};
if (prefixLength > 32 || prefixLength < 0) {
return "";
}
try {
byte[] byteAddr = InetAddress.getByName(ipAddr).getAddress();
int idx = 0;
while (prefixLength >= 8) {
idx++;
prefixLength -= 8;
}
if (idx < byteAddr.length) {
byteAddr[idx++] &= arr[prefixLength];
}
for (; idx < byteAddr.length; idx++) {
byteAddr[idx] = (byte) 0x00;
}
return InetAddress.getByAddress(byteAddr).getHostAddress();
} catch (Exception e) {
return "";
}
}
}

96
android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/DaoMaster.java

@ -0,0 +1,96 @@
package wang.switchy.hin2n.storage.db.base;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
N2NSettingModelDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
N2NSettingModelDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(N2NSettingModelDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}

48
android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/DaoSession.java

@ -0,0 +1,48 @@
package wang.switchy.hin2n.storage.db.base;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
import wang.switchy.hin2n.storage.db.base.N2NSettingModelDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig n2NSettingModelDaoConfig;
private final N2NSettingModelDao n2NSettingModelDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
n2NSettingModelDaoConfig = daoConfigMap.get(N2NSettingModelDao.class).clone();
n2NSettingModelDaoConfig.initIdentityScope(type);
n2NSettingModelDao = new N2NSettingModelDao(n2NSettingModelDaoConfig, this);
registerDao(N2NSettingModel.class, n2NSettingModelDao);
}
public void clear() {
n2NSettingModelDaoConfig.clearIdentityScope();
}
public N2NSettingModelDao getN2NSettingModelDao() {
return n2NSettingModelDao;
}
}

275
android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/N2NSettingModelDao.java

@ -0,0 +1,275 @@
package wang.switchy.hin2n.storage.db.base;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import wang.switchy.hin2n.storage.db.base.model.N2NSettingModel;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "N2NSettingList".
*/
public class N2NSettingModelDao extends AbstractDao<N2NSettingModel, Long> {
public static final String TABLENAME = "N2NSettingList";
/**
* Properties of entity N2NSettingModel.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Ip = new Property(2, String.class, "ip", false, "IP");
public final static Property Netmask = new Property(3, String.class, "netmask", false, "NETMASK");
public final static Property Community = new Property(4, String.class, "community", false, "COMMUNITY");
public final static Property Password = new Property(5, String.class, "password", false, "PASSWORD");
public final static Property SuperNode = new Property(6, String.class, "superNode", false, "SUPER_NODE");
public final static Property MoreSettings = new Property(7, boolean.class, "moreSettings", false, "MORE_SETTINGS");
public final static Property SuperNodeBackup = new Property(8, String.class, "superNodeBackup", false, "SUPER_NODE_BACKUP");
public final static Property MacAddr = new Property(9, String.class, "macAddr", false, "MAC_ADDR");
public final static Property Mtu = new Property(10, int.class, "mtu", false, "MTU");
public final static Property ResoveSupernodeIP = new Property(11, boolean.class, "resoveSupernodeIP", false, "RESOVE_SUPERNODE_IP");
public final static Property LocalPort = new Property(12, int.class, "localPort", false, "LOCAL_PORT");
public final static Property AllowRouting = new Property(13, boolean.class, "allowRouting", false, "ALLOW_ROUTING");
public final static Property DropMuticast = new Property(14, boolean.class, "dropMuticast", false, "DROP_MUTICAST");
public final static Property TraceLevel = new Property(15, int.class, "traceLevel", false, "TRACE_LEVEL");
public final static Property IsSelcected = new Property(16, boolean.class, "isSelcected", false, "IS_SELCECTED");
}
public N2NSettingModelDao(DaoConfig config) {
super(config);
}
public N2NSettingModelDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"N2NSettingList\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"NAME\" TEXT," + // 1: name
"\"IP\" TEXT," + // 2: ip
"\"NETMASK\" TEXT," + // 3: netmask
"\"COMMUNITY\" TEXT," + // 4: community
"\"PASSWORD\" TEXT," + // 5: password
"\"SUPER_NODE\" TEXT," + // 6: superNode
"\"MORE_SETTINGS\" INTEGER NOT NULL ," + // 7: moreSettings
"\"SUPER_NODE_BACKUP\" TEXT," + // 8: superNodeBackup
"\"MAC_ADDR\" TEXT," + // 9: macAddr
"\"MTU\" INTEGER NOT NULL ," + // 10: mtu
"\"RESOVE_SUPERNODE_IP\" INTEGER NOT NULL ," + // 11: resoveSupernodeIP
"\"LOCAL_PORT\" INTEGER NOT NULL ," + // 12: localPort
"\"ALLOW_ROUTING\" INTEGER NOT NULL ," + // 13: allowRouting
"\"DROP_MUTICAST\" INTEGER NOT NULL ," + // 14: dropMuticast
"\"TRACE_LEVEL\" INTEGER NOT NULL ," + // 15: traceLevel
"\"IS_SELCECTED\" INTEGER NOT NULL );"); // 16: isSelcected
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"N2NSettingList\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, N2NSettingModel entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String ip = entity.getIp();
if (ip != null) {
stmt.bindString(3, ip);
}
String netmask = entity.getNetmask();
if (netmask != null) {
stmt.bindString(4, netmask);
}
String community = entity.getCommunity();
if (community != null) {
stmt.bindString(5, community);
}
String password = entity.getPassword();
if (password != null) {
stmt.bindString(6, password);
}
String superNode = entity.getSuperNode();
if (superNode != null) {
stmt.bindString(7, superNode);
}
stmt.bindLong(8, entity.getMoreSettings() ? 1L: 0L);
String superNodeBackup = entity.getSuperNodeBackup();
if (superNodeBackup != null) {
stmt.bindString(9, superNodeBackup);
}
String macAddr = entity.getMacAddr();
if (macAddr != null) {
stmt.bindString(10, macAddr);
}
stmt.bindLong(11, entity.getMtu());
stmt.bindLong(12, entity.getResoveSupernodeIP() ? 1L: 0L);
stmt.bindLong(13, entity.getLocalPort());
stmt.bindLong(14, entity.getAllowRouting() ? 1L: 0L);
stmt.bindLong(15, entity.getDropMuticast() ? 1L: 0L);
stmt.bindLong(16, entity.getTraceLevel());
stmt.bindLong(17, entity.getIsSelcected() ? 1L: 0L);
}
@Override
protected final void bindValues(SQLiteStatement stmt, N2NSettingModel entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String ip = entity.getIp();
if (ip != null) {
stmt.bindString(3, ip);
}
String netmask = entity.getNetmask();
if (netmask != null) {
stmt.bindString(4, netmask);
}
String community = entity.getCommunity();
if (community != null) {
stmt.bindString(5, community);
}
String password = entity.getPassword();
if (password != null) {
stmt.bindString(6, password);
}
String superNode = entity.getSuperNode();
if (superNode != null) {
stmt.bindString(7, superNode);
}
stmt.bindLong(8, entity.getMoreSettings() ? 1L: 0L);
String superNodeBackup = entity.getSuperNodeBackup();
if (superNodeBackup != null) {
stmt.bindString(9, superNodeBackup);
}
String macAddr = entity.getMacAddr();
if (macAddr != null) {
stmt.bindString(10, macAddr);
}
stmt.bindLong(11, entity.getMtu());
stmt.bindLong(12, entity.getResoveSupernodeIP() ? 1L: 0L);
stmt.bindLong(13, entity.getLocalPort());
stmt.bindLong(14, entity.getAllowRouting() ? 1L: 0L);
stmt.bindLong(15, entity.getDropMuticast() ? 1L: 0L);
stmt.bindLong(16, entity.getTraceLevel());
stmt.bindLong(17, entity.getIsSelcected() ? 1L: 0L);
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public N2NSettingModel readEntity(Cursor cursor, int offset) {
N2NSettingModel entity = new N2NSettingModel( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // ip
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // netmask
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // community
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // password
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // superNode
cursor.getShort(offset + 7) != 0, // moreSettings
cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // superNodeBackup
cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9), // macAddr
cursor.getInt(offset + 10), // mtu
cursor.getShort(offset + 11) != 0, // resoveSupernodeIP
cursor.getInt(offset + 12), // localPort
cursor.getShort(offset + 13) != 0, // allowRouting
cursor.getShort(offset + 14) != 0, // dropMuticast
cursor.getInt(offset + 15), // traceLevel
cursor.getShort(offset + 16) != 0 // isSelcected
);
return entity;
}
@Override
public void readEntity(Cursor cursor, N2NSettingModel entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setIp(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setNetmask(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setCommunity(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setPassword(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setSuperNode(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setMoreSettings(cursor.getShort(offset + 7) != 0);
entity.setSuperNodeBackup(cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8));
entity.setMacAddr(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9));
entity.setMtu(cursor.getInt(offset + 10));
entity.setResoveSupernodeIP(cursor.getShort(offset + 11) != 0);
entity.setLocalPort(cursor.getInt(offset + 12));
entity.setAllowRouting(cursor.getShort(offset + 13) != 0);
entity.setDropMuticast(cursor.getShort(offset + 14) != 0);
entity.setTraceLevel(cursor.getInt(offset + 15));
entity.setIsSelcected(cursor.getShort(offset + 16) != 0);
}
@Override
protected final Long updateKeyAfterInsert(N2NSettingModel entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(N2NSettingModel entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(N2NSettingModel entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}

222
android/Hin2n/app/src/main/java/wang/switchy/hin2n/storage/db/base/model/N2NSettingModel.java

@ -0,0 +1,222 @@
package wang.switchy.hin2n.storage.db.base.model;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
/**
* Created by janiszhang on 2018/5/4.
*/
@Entity(
nameInDb = "N2NSettingList"
)
public class N2NSettingModel /*implements Parcelable*/ {
@Id(autoincrement = true)
Long id;
String name;
String ip;
String netmask;
String community;
String password;
String superNode;
boolean moreSettings;
String superNodeBackup;
String macAddr;
int mtu;
boolean resoveSupernodeIP;
int localPort;
boolean allowRouting;
boolean dropMuticast;
int traceLevel;
boolean isSelcected;
@Generated(hash = 1390425120)
public N2NSettingModel(Long id, String name, String ip, String netmask,
String community, String password, String superNode,
boolean moreSettings, String superNodeBackup, String macAddr, int mtu,
boolean resoveSupernodeIP, int localPort, boolean allowRouting,
boolean dropMuticast, int traceLevel, boolean isSelcected) {
this.id = id;
this.name = name;
this.ip = ip;
this.netmask = netmask;
this.community = community;
this.password = password;
this.superNode = superNode;
this.moreSettings = moreSettings;
this.superNodeBackup = superNodeBackup;
this.macAddr = macAddr;
this.mtu = mtu;
this.resoveSupernodeIP = resoveSupernodeIP;
this.localPort = localPort;
this.allowRouting = allowRouting;
this.dropMuticast = dropMuticast;
this.traceLevel = traceLevel;
this.isSelcected = isSelcected;
}
@Generated(hash = 998225630)
public N2NSettingModel() {
}
public String getSuperNode() {
return this.superNode;
}
public void setSuperNode(String superNode) {
this.superNode = superNode;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCommunity() {
return this.community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getNetmask() {
return this.netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean getIsSelcected() {
return this.isSelcected;
}
public void setIsSelcected(boolean isSelcected) {
this.isSelcected = isSelcected;
}
public int getTraceLevel() {
return this.traceLevel;
}
public void setTraceLevel(int traceLevel) {
this.traceLevel = traceLevel;
}
public boolean getDropMuticast() {
return this.dropMuticast;
}
public void setDropMuticast(boolean dropMuticast) {
this.dropMuticast = dropMuticast;
}
public boolean getAllowRouting() {
return this.allowRouting;
}
public void setAllowRouting(boolean allowRouting) {
this.allowRouting = allowRouting;
}
public int getLocalPort() {
return this.localPort;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public boolean getResoveSupernodeIP() {
return this.resoveSupernodeIP;
}
public void setResoveSupernodeIP(boolean resoveSupernodeIP) {
this.resoveSupernodeIP = resoveSupernodeIP;
}
public int getMtu() {
return this.mtu;
}
public void setMtu(int mtu) {
this.mtu = mtu;
}
public String getMacAddr() {
return this.macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public String getSuperNodeBackup() {
return this.superNodeBackup;
}
public void setSuperNodeBackup(String superNodeBackup) {
this.superNodeBackup = superNodeBackup;
}
public boolean getMoreSettings() {
return this.moreSettings;
}
public void setMoreSettings(boolean moreSettings) {
this.moreSettings = moreSettings;
}
@Override
public String toString() {
return "N2NSettingModel{" +
"id=" + id +
", name='" + name + '\'' +
", ip='" + ip + '\'' +
", netmask='" + netmask + '\'' +
", community='" + community + '\'' +
", password='" + password + '\'' +
", superNode='" + superNode + '\'' +
", moreSettings=" + moreSettings +
", superNodeBackup='" + superNodeBackup + '\'' +
", macAddr='" + macAddr + '\'' +
", mtu=" + mtu +
", resoveSupernodeIP=" + resoveSupernodeIP +
", localPort=" + localPort +
", allowRouting=" + allowRouting +
", dropMuticast=" + dropMuticast +
", traceLevel=" + traceLevel +
", isSelcected=" + isSelcected +
'}';
}
}

21
android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/BaseTemplate.java

@ -0,0 +1,21 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.View;
/**
* Created by janiszhang on 2018/4/13.
*/
public abstract class BaseTemplate {
protected Context mContext;
public BaseTemplate(Context context) {
this.mContext = context;
}
public abstract void setContentView(View contentView);
public abstract View getPageView();
}

60
android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/CommonTitleTemplate.java

@ -0,0 +1,60 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import wang.switchy.hin2n.R;
/**
* Created by janiszhang on 2018/4/13.
*/
public class CommonTitleTemplate extends BaseTemplate {
private Context mContext;
private LinearLayout mPageView;
private RelativeLayout mTitleLayout;
private FrameLayout mContainerLayout;
public final ImageView mLeftImg;
public final ImageView mRightImg;
public CommonTitleTemplate(Context context, String title) {
super(context);
this.mContext = context;
mPageView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.main_template_view, null);
mTitleLayout = (RelativeLayout) mPageView.findViewById(R.id.rl_title);
mContainerLayout = (FrameLayout) mPageView.findViewById(R.id.fl_container);
TextView titleText = (TextView) mPageView.findViewById(R.id.tv_title);
mLeftImg = (ImageView) mPageView.findViewById(R.id.iv_left_img);
mRightImg = (ImageView) mPageView.findViewById(R.id.iv_right_img);
titleText.setText(title);
}
@Override
public void setContentView(View contentView) {
RelativeLayout.LayoutParams contentViewLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
mContainerLayout.addView(contentView, contentViewLayoutParams);
}
@Override
public View getPageView() {
return mPageView;
}
}

26
android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/EmptyTemplate.java

@ -0,0 +1,26 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.View;
/**
* Created by janiszhang on 2018/4/13.
*/
public class EmptyTemplate extends BaseTemplate {
private View mContentView;
public EmptyTemplate(Context context) {
super(context);
}
@Override
public void setContentView(View contentView) {
this.mContentView = contentView;
}
@Override
public View getPageView() {
return mContentView;
}
}

53
android/Hin2n/app/src/main/java/wang/switchy/hin2n/template/MainTitleTemplate.java

@ -0,0 +1,53 @@
package wang.switchy.hin2n.template;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import wang.switchy.hin2n.R;
/**
* Created by janiszhang on 2018/4/13.
*/
public class MainTitleTemplate extends BaseTemplate {
private Context mContext;
private LinearLayout mPageView;
private RelativeLayout mTitleLayout;
private FrameLayout mContainerLayout;
public MainTitleTemplate(Context context, String title) {
super(context);
this.mContext = context;
mPageView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.main_template_view, null);
mTitleLayout = (RelativeLayout) mPageView.findViewById(R.id.rl_title);
mContainerLayout = (FrameLayout) mPageView.findViewById(R.id.fl_container);
TextView titleText = (TextView) mPageView.findViewById(R.id.tv_title);
titleText.setText(title);
}
@Override
public void setContentView(View contentView) {
RelativeLayout.LayoutParams contentViewLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
mContainerLayout.addView(contentView, contentViewLayoutParams);
}
@Override
public View getPageView() {
return mPageView;
}
}

11
android/Hin2n/app/src/main/res/drawable/titlebar_icon_return_selector.xml

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<layer-list>
<item><shape android:shape="oval">
<solid android:color="#33FFFFFF" />
</shape></item>
<item android:drawable="@mipmap/title_back_normal"/>
</layer-list></item>
<item android:drawable="@mipmap/title_back_normal" android:state_pressed="false"/>
</selector>

328
android/Hin2n/app/src/main/res/layout/activity_add_item.xml

@ -0,0 +1,328 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.design.widget.TextInputLayout
android:id="@+id/til_setting_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_setting_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_ip_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_setting_name">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_ip_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="IP address"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_net_mask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_ip_address">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_net_mask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Netmask"
android:text="255.255.255.0"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_community"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_net_mask">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_community"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Community"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_community">
<!--app:passwordToggleEnabled="true"-->
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"/>
<!--android:inputType="textPassword"-->
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_super_node"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_encrypt">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_super_node"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Supernode"
android:text="n2n.switchy.wang:10086"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rl_more_setting_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_super_node">
<CheckBox
android:id="@+id/more_setting_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/more_setting_check_box"
android:text="more setting"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_more_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl_more_setting_check_box"
android:visibility="gone">
<android.support.design.widget.TextInputLayout
android:id="@+id/til_super_node_2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_super_node_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Supernode Backup"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_mac_addr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_super_node_2">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_mac_addr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Mac Address"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_mtu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/til_mac_addr">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_mtu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="mtu"/>
</android.support.design.widget.TextInputLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_resove_super_node_ip_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_mtu">
<CheckBox
android:id="@+id/resove_super_node_ip_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/resove_super_node_ip_check_box"
android:text="Resove Supernode IP"/>
</RelativeLayout>
<android.support.design.widget.TextInputLayout
android:layout_below="@id/rl_resove_super_node_ip_check_box"
android:id="@+id/til_local_port"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/tie_local_port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="localPort"/>
</android.support.design.widget.TextInputLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_allow_routing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/til_local_port">
<CheckBox
android:id="@+id/allow_routing_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/allow_routing_check_box"
android:text="Allow Routing"/>
</RelativeLayout>
<!--boolean-->
<RelativeLayout
android:id="@+id/rl_drop_muticast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rl_allow_routing">
<CheckBox
android:id="@+id/drop_muticast_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/drop_muticast_check_box"
android:text="Drop Muticast"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="@id/rl_drop_muticast"
android:id="@+id/rl_trace_level"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_trace_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trace Level : "/>
<Spinner
android:layout_toRightOf="@id/tv_trace_level"
android:id="@+id/spinner_trace_level"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_buttons"
android:layout_below="@id/rl_more_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:visibility="gone"
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"/>
<LinearLayout
android:id="@+id/ll_buttons"
android:weightSum="1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_weight="0.5"
android:id="@+id/btn_modify"
android:text="modify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_weight="0.5"
android:id="@+id/btn_delete"
android:text="delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rl_buttons"
android:visibility="gone">
<CheckBox
android:id="@+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/check_box"
android:text="with immediate effect"/>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>

65
android/Hin2n/app/src/main/res/layout/activity_main.xml

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/rl_current_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:layout_centerVertical="true"
android:id="@+id/tv_current_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="Current Setting : "/>
<RelativeLayout
android:layout_toRightOf="@id/tv_current_setting"
android:id="@+id/rl_current_setting_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:id="@+id/tv_current_setting_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="--null--"/>
<ImageView
android:layout_alignParentRight="true"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@mipmap/img_more"/>
</RelativeLayout>
</RelativeLayout>
<Button
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:id="@+id/btn_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl_current_setting"
android:text="Start"/>
</RelativeLayout>
</RelativeLayout>

10
android/Hin2n/app/src/main/res/layout/activity_setting_list.xml

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lv_setting_item"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

42
android/Hin2n/app/src/main/res/layout/layout_setting_item.xml

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
>
<ImageView
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:id="@+id/iv_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:src="@mipmap/img_icon_selected"/>
<TextView
android:layout_toRightOf="@id/iv_selected"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:id="@+id/tv_setting_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="SettingName"/>
<TextView
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:layout_alignParentRight="true"
android:id="@+id/tv_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="Edit"
android:padding="10dp"
/>
</RelativeLayout>
</RelativeLayout>

44
android/Hin2n/app/src/main/res/layout/main_template_view.xml

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/rl_title"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary">
<ImageView
android:id="@+id/iv_left_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"/>
<TextView
android:id="@+id/tv_title"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hin2n"
android:textSize="20dp"
android:textColor="@android:color/white"/>
<ImageView
android:id="@+id/iv_right_img"
android:layout_alignParentRight="true"
android:layout_width="30dp"
android:layout_height="30dp"
android:visibility="visible"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"/>
</RelativeLayout>
<FrameLayout
android:id="@+id/fl_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>

BIN
android/Hin2n/app/src/main/res/mipmap-hdpi/ic_launcher.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

BIN
android/Hin2n/app/src/main/res/mipmap-mdpi/ic_launcher.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_launcher.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_setting_dark.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/ic_setting_light.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 557 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/img_add.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/img_change.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 496 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/img_icon_selected.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 629 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/img_more.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 910 B

BIN
android/Hin2n/app/src/main/res/mipmap-xhdpi/title_back_normal.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 B

BIN
android/Hin2n/app/src/main/res/mipmap-xxhdpi/ic_launcher.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

BIN
android/Hin2n/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

6
android/Hin2n/app/src/main/res/values-w820dp/dimens.xml

@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

6
android/Hin2n/app/src/main/res/values/colors.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

5
android/Hin2n/app/src/main/res/values/dimens.xml

@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>

3
android/Hin2n/app/src/main/res/values/strings.xml

@ -0,0 +1,3 @@
<resources>
<string name="app_name">Hin2n</string>
</resources>

11
android/Hin2n/app/src/main/res/values/styles.xml

@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

17
android/Hin2n/app/src/test/java/wang/switchy/hin2n/ExampleUnitTest.java

@ -0,0 +1,17 @@
package wang.switchy.hin2n;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

25
android/Hin2n/build.gradle

@ -0,0 +1,25 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

19
android/Hin2n/gradle.properties

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.daemon=true

BIN
android/Hin2n/gradle/wrapper/gradle-wrapper.jar

Binary file not shown.

6
android/Hin2n/gradle/wrapper/gradle-wrapper.properties

@ -0,0 +1,6 @@
#Tue Apr 17 00:25:58 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

160
android/Hin2n/gradlew

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
android/Hin2n/gradlew.bat

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
android/Hin2n/settings.gradle

@ -0,0 +1 @@
include ':app'
Loading…
Cancel
Save