[WIP] Migrating to XMPP, added XMPPConnectionService, LoginActivity

This commit is contained in:
ChronosX88 2019-05-19 15:29:02 +04:00
commit a66a83c0fd
93 changed files with 4743 additions and 0 deletions

8
.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild

18
.idea/gradle.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

44
.idea/misc.xml Normal file
View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="10">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
<item index="3" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="4" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
<item index="5" class="java.lang.String" itemvalue="androidx.annotation.Nullable" />
<item index="6" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNullable" />
<item index="7" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.qual.Nullable" />
<item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NullableDecl" />
<item index="9" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NullableType" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="9">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
<item index="4" class="java.lang.String" itemvalue="androidx.annotation.NonNull" />
<item index="5" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNonNull" />
<item index="6" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.qual.NonNull" />
<item index="7" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NonNullDecl" />
<item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NonNullType" />
</list>
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU 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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

69
README.md Normal file
View File

@ -0,0 +1,69 @@
<p align="center">
<h1 align="center">Influence</h1>
<p align="center">
This is a decentralized messenger for Android, which work on top of TomP2P DHT.
</p>
</p>
<!-- Used for the "back to top" links within the document -->
<div id="contents"></div>
## Table of Contents
- [Intro](#intro)
- [Getting started](#getting-started)
- [Features](#features)
- [Useful links](#useful-links)
- [License](#license)
- [Author](#author)
## Intro
*[Soon]*
## Getting started
1. Clone repo:
```bash
$ git clone https://github.com/ChronosX88/Influence-android
$ cd Influence-android
```
2. Simply open project in Android Studio.
(Also exists precompiled APKs - see Releases)
<sub>[⇧ back to top](#contents)</sub>
## Features
- 1:1 chats
- Decentralized message storage
- Username system
- Group chats [Soon]
- Encryption [Soon]
- Channels (like Telegram) [Soon]
- Profile pictures [Soon]
<sub>[⇧ back to top](#contents)</sub>
## Useful links
- [TomP2P GitHub](https://github.com/tomp2p/TomP2P)
<sub>[⇧ back to top](#contents)</sub>
## License
This project is licensed under the GNU GPLv3 License - see the [LICENSE](LICENSE) file for details.
<sub>[⇧ back to top](#contents)</sub>
## Author
```txt
Author : ChronosX88
Email : chronosx88@gmail.com
Github : https://github.com/ChronosX88/Influence-android.git
```
[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
<sub>[⇧ back to top](#contents)</sub>

1
app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

70
app/build.gradle Normal file
View File

@ -0,0 +1,70 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 28
defaultConfig {
applicationId "io.github.chronosx88.influence"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "0.1alpha4"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/INDEX.LIST'
exclude 'META-INF/io.netty.versions.properties'
exclude 'LICENSE-EPL-1.0.txt'
exclude 'LICENSE-EDL-1.0.txt'
exclude 'META-INF/atomicfu.kotlin_module'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
implementation "androidx.room:room-runtime:2.1.0-alpha04"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
annotationProcessor "androidx.room:room-compiler:2.1.0-alpha04"
implementation 'org.slf4j:slf4j-log4j12:1.7.26'
implementation('net.tomp2p:tomp2p-all:5.0-Beta8') {
exclude group: 'net.tomp2p', module: 'tomp2p-storage'
}
implementation 'com.google.android.material:material:1.1.0-alpha04'
implementation 'androidx.preference:preference:1.1.0-alpha03'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'de.hdodenhof:circleimageview:3.0.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'com.android.support:multidex:1.0.3'
implementation "org.jetbrains.anko:anko:0.10.8"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.0'
implementation 'com.esotericsoftware:kryo:5.0.0-RC1'
implementation 'com.github.instacart.truetime-android:library:3.4'
implementation 'org.igniterealtime.smack:smack-core:4.3.3'
implementation 'org.igniterealtime.smack:smack-tcp:4.3.3'
implementation 'org.igniterealtime.smack:smack-android:4.3.3'
implementation 'org.igniterealtime.smack:smack-extensions:4.3.3'
}
repositories {
mavenCentral()
}

Binary file not shown.

BIN
app/libs/trove.jar Normal file

Binary file not shown.

21
app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# 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 *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,132 @@
{
"formatVersion": 1,
"database": {
"version": 2,
"identityHash": "81501115d10a6dc46002667323359631",
"entities": [
{
"tableName": "messages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`messageID` TEXT NOT NULL, `type` INTEGER NOT NULL, `chatID` TEXT, `senderID` TEXT, `username` TEXT, `timestamp` INTEGER NOT NULL, `text` TEXT, `isSent` INTEGER NOT NULL, `isRead` INTEGER NOT NULL, PRIMARY KEY(`messageID`))",
"fields": [
{
"fieldPath": "messageID",
"columnName": "messageID",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "chatID",
"columnName": "chatID",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "senderID",
"columnName": "senderID",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "text",
"columnName": "text",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "isSent",
"columnName": "isSent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isRead",
"columnName": "isRead",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"messageID"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "chats",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatID` TEXT NOT NULL, `name` TEXT, `metadataRef` TEXT, `membersRef` TEXT, `bannedUsers` TEXT, `chunkCursor` INTEGER NOT NULL, PRIMARY KEY(`chatID`))",
"fields": [
{
"fieldPath": "chatID",
"columnName": "chatID",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "metadataRef",
"columnName": "metadataRef",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "membersRef",
"columnName": "membersRef",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "bannedUsers",
"columnName": "bannedUsers",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "chunkCursor",
"columnName": "chunkCursor",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"chatID"
],
"autoGenerate": false
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"81501115d10a6dc46002667323359631\")"
]
}
}

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="io.github.chronosx88.influence">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".helpers.AppHelper"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".views.LoginActivity"></activity>
<service
android:name=".XMPPConnectionService"
android:enabled="true"
android:exported="true" />
<activity android:name=".views.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".views.ChatActivity"
android:theme="@style/NoWindowActionBar" />
</application>
</manifest>

View File

@ -0,0 +1,24 @@
/*
* Copyright (C) 2019 ChronosX88
*
* 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 <https://www.gnu.org/licenses/>.
*/
package io.github.chronosx88.influence;
public class LoginCredentials {
String username = "";
String password = "";
String jabberHost = "";
}

View File

@ -0,0 +1,191 @@
/*
* Copyright (C) 2019 ChronosX88
*
* 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 <https://www.gnu.org/licenses/>.
*/
package io.github.chronosx88.influence;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.preference.PreferenceManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.ReconnectionManager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
import java.io.IOException;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.helpers.NetworkHandler;
public class XMPPConnection implements ConnectionListener {
private final static String LOG_TAG = "XMPPConnection";
private LoginCredentials credentials = new LoginCredentials();
private XMPPTCPConnection connection = null;
private SharedPreferences prefs;
private NetworkHandler networkHandler;
private BroadcastReceiver sendMessageReceiver = null;
private Context context;
public enum ConnectionState {
CONNECTED,
AUTHENTICATED,
CONNECTING,
DISCONNECTING,
DISCONNECTED
}
public enum SessionState {
LOGGED_IN,
LOGGED_OUT
}
public XMPPConnection(Context context) {
String jid = prefs.getString("jid", null);
String password = prefs.getString("pass", null);
if(jid != null && password != null) {
String username = jid.split("@")[0];
String jabberHost = jid.split("@")[1];
credentials.username = username;
credentials.jabberHost = jabberHost;
credentials.password = password;
}
networkHandler = new NetworkHandler(context);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.context = context;
}
public void connect() throws XMPPException, SmackException, IOException {
if(connection == null) {
XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(credentials.jabberHost)
.setHost(credentials.jabberHost)
.setResource(AppHelper.APP_NAME)
.setKeystoreType(null)
.setSecurityMode(ConnectionConfiguration.SecurityMode.required)
.setCompressionEnabled(true)
.build();
setupSendMessageReceiver();
connection = new XMPPTCPConnection(conf);
connection.addConnectionListener(this);
try {
connection.connect();
connection.login(credentials.username, credentials.password);
} catch (InterruptedException e) {
e.printStackTrace();
}
ChatManager.getInstanceFor(connection).addIncomingListener(networkHandler);
ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
ReconnectionManager.setEnabledPerDefault(true);
reconnectionManager.enableAutomaticReconnection();
}
}
public void disconnect() {
prefs.edit().putBoolean("logged_in", false).apply();
if(connection != null) {
connection.disconnect();
connection = null;
}
}
@Override
public void connected(org.jivesoftware.smack.XMPPConnection connection) {
XMPPConnectionService.connectionState = ConnectionState.CONNECTED;
}
@Override
public void authenticated(org.jivesoftware.smack.XMPPConnection connection, boolean resumed) {
XMPPConnectionService.sessionState = SessionState.LOGGED_IN;
prefs.edit().putBoolean("logged_in", true).apply();
}
@Override
public void connectionClosed() {
XMPPConnectionService.connectionState = ConnectionState.DISCONNECTED;
XMPPConnectionService.sessionState = SessionState.LOGGED_OUT;
prefs.edit().putBoolean("logged_in", false).apply();
}
@Override
public void connectionClosedOnError(Exception e) {
XMPPConnectionService.connectionState = ConnectionState.DISCONNECTED;
XMPPConnectionService.sessionState = SessionState.LOGGED_OUT;
prefs.edit().putBoolean("logged_in", false).apply();
Log.e(LOG_TAG, "Connection closed, exception occurred");
e.printStackTrace();
}
private void setupSendMessageReceiver() {
sendMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case XMPPConnectionService.INTENT_SEND_MESSAGE: {
String recipientJid = intent.getStringExtra(XMPPConnectionService.MESSAGE_RECIPIENT);
String messageText = intent.getStringExtra(XMPPConnectionService.MESSAGE_BODY);
sendMessage(recipientJid, messageText);
break;
}
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(XMPPConnectionService.INTENT_SEND_MESSAGE);
context.registerReceiver(sendMessageReceiver, intentFilter);
}
private void sendMessage(String recipientJid, String messageText) {
EntityBareJid jid = null;
try {
jid = JidCreate.entityBareFrom(recipientJid);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid);
try {
Message message = new Message(jid, Message.Type.chat);
message.setBody(messageText);
chat.send(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public XMPPTCPConnection getConnection() {
return connection;
}
}

View File

@ -0,0 +1,110 @@
/*
* Copyright (C) 2019 ChronosX88
*
* 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 <https://www.gnu.org/licenses/>.
*/
package io.github.chronosx88.influence;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import java.io.IOException;
public class XMPPConnectionService extends Service {
public static final String INTENT_NEW_MESSAGE = "io.github.chronosx88.intents.new_message";
public static final String INTENT_SEND_MESSAGE = "io.github.chronosx88.intents.send_message";
public static final String INTENT_AUTHENTICATED = "io.github.chronosx88.intents.authenticated";
public static final String INTENT_AUTHENTICATION_FAILED = "io.github.chronosx88.intents.authentication_failed";
public static final String MESSAGE_CHATID = "chat_jid";
public static final String MESSAGE_ID = "message_id";
public static final String MESSAGE_BODY = "message_body";
public static final String MESSAGE_RECIPIENT = "message_recipient";
public static XMPPConnection.ConnectionState connectionState = XMPPConnection.ConnectionState.DISCONNECTED;
public static XMPPConnection.SessionState sessionState = XMPPConnection.SessionState.LOGGED_OUT;
private Thread thread;
private Handler threadHandler;
private boolean isThreadAlive = false;
private XMPPConnection connection;
private Context context;
public XMPPConnectionService(Context context) {
this.context = context;
}
@Override
public IBinder onBind(Intent intent) { return null; }
public void onServiceStart() {
if(!isThreadAlive)
{
isThreadAlive = true;
if(thread == null || !thread.isAlive()) {
thread = new Thread(() -> {
Looper.prepare();
threadHandler = new Handler();
createConnection();
Looper.loop();
});
thread.start();
}
}
}
private void onServiceStop() {
isThreadAlive = false;
threadHandler.post(() -> {
if(connection != null) {
connection.disconnect();
}
});
}
private void createConnection() {
if(connection == null) {
connection = new XMPPConnection(this);
}
try {
connection.connect();
} catch (IOException | SmackException | XMPPException e) {
Intent intent = new Intent(INTENT_AUTHENTICATION_FAILED);
e.printStackTrace();
//Stop the service all together.
stopSelf();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onServiceStart();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
onServiceStop();
}
}

View File

@ -0,0 +1,89 @@
package io.github.chronosx88.influence.contracts
import android.content.Intent
import android.view.MenuItem
import io.github.chronosx88.influence.helpers.ChatListAdapter
import io.github.chronosx88.influence.models.roomEntities.ChatEntity
import io.github.chronosx88.influence.models.roomEntities.MessageEntity
interface CoreContracts {
interface ViewWithLoadingScreen {
fun loadingScreen(state: Boolean);
}
// -----ChatList-----
interface IChatListLogicContract {
fun loadAllChats(): List<ChatEntity>
}
interface IChatListPresenterContract {
fun updateChatList()
fun openChat(chatID: String)
fun onContextItemSelected(item: MenuItem)
}
interface IChatListViewContract {
fun setRecycleAdapter(adapter: ChatListAdapter)
fun startActivity(intent: Intent)
fun updateChatList(adapter: ChatListAdapter, chats: List<ChatEntity>)
}
// -----MainActivity-----
interface IMainLogicContract {
fun initPeer()
fun sendStartChatMessage(username: String)
fun shutdownPeer()
}
interface IMainPresenterContract {
fun initPeer()
fun startChatWithPeer(username: String)
fun onDestroy()
}
interface IMainViewContract {
fun showSnackbar(message: String)
fun showProgressBar(state: Boolean)
}
// -----ChatActivity-----
interface IChatLogicContract {
fun sendMessage(message: MessageEntity)
fun stopTrackingForNewMsgs()
}
interface IChatPresenterContract {
fun sendMessage(text: String)
fun updateAdapter()
fun onDestroy()
}
interface IChatViewContract {
fun updateMessageList(message: MessageEntity)
fun updateMessageList(messages: List<MessageEntity>)
}
// -----SettingsFragment-----
interface ISettingsLogic {
fun checkUsernameExists(username: String) : Boolean
}
interface ISettingsPresenter {
fun updateUsername(username: String)
}
interface ISettingsView {
fun loadingScreen(state: Boolean)
fun showMessage(message: String)
fun refreshScreen()
}
// -----LoginActivity-----
interface ILoginViewContract : ViewWithLoadingScreen
}

View File

@ -0,0 +1,7 @@
package io.github.chronosx88.influence.contracts;
import android.view.View;
public interface IItemClickListener {
void onItemClick(View view, int position);
}

View File

@ -0,0 +1,5 @@
package io.github.chronosx88.influence.contracts.observer;
public interface INetworkObserver {
void handleEvent(Object object);
}

View File

@ -0,0 +1,12 @@
package io.github.chronosx88.influence.contracts.observer;
import com.google.gson.JsonObject;
public interface IObservable {
void register(IObserver observer);
void register(INetworkObserver networkObserver);
void unregister(IObserver observer);
void unregister(INetworkObserver networkObserver);
void notifyUIObservers(JsonObject jsonObject);
void notifyNetworkObservers(Object object);
}

View File

@ -0,0 +1,7 @@
package io.github.chronosx88.influence.contracts.observer;
import com.google.gson.JsonObject;
public interface IObserver {
void handleEvent(JsonObject object);
}

View File

@ -0,0 +1,65 @@
package io.github.chronosx88.influence.helpers;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import net.tomp2p.dht.PeerDHT;
import androidx.multidex.MultiDexApplication;
import androidx.room.Room;
import com.instacart.library.truetime.TrueTime;
import java.io.IOException;
import io.github.chronosx88.influence.observable.MainObservable;
/**
* Extended Application class which designed for centralized getting various objects from anywhere in the application.
*/
public class AppHelper extends MultiDexApplication {
private static Application instance;
private static MainObservable observable;
public final static String APP_NAME = "Influence";
private static String jid;
private static RoomHelper chatDB;
private static SharedPreferences preferences;
@Override
public void onCreate() {
super.onCreate();
instance = this;
observable = new MainObservable();
chatDB = Room.databaseBuilder(getApplicationContext(), RoomHelper.class, "chatDB")
.allowMainThreadQueries()
.build();
preferences = PreferenceManager.getDefaultSharedPreferences(instance);
new Thread(() -> {
try {
TrueTime.build().initialize();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
public static Context getContext() {
return instance.getApplicationContext();
}
public static MainObservable getObservable() { return observable; }
public static String getJid() { return jid; }
public static void setJid(String jid1) { jid = jid1; }
public static RoomHelper getChatDB() { return chatDB; }
public static SharedPreferences getPreferences() {
return preferences;
}
}

View File

@ -0,0 +1,105 @@
package io.github.chronosx88.influence.helpers;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.github.chronosx88.influence.R;
import io.github.chronosx88.influence.models.roomEntities.MessageEntity;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private final static int RIGHT_ITEM = 0;
private final static int LEFT_ITEM = 1;
private final static int TECHNICAL_MESSAGE = 2; // TODO
private final Context context = AppHelper.getContext();
private ArrayList<MessageEntity> messages = new ArrayList<>();
private static Comparator<MessageEntity> comparator = ((o1, o2) -> Long.compare(o1.timestamp, o2.timestamp));
@NonNull
@Override
public ChatAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == RIGHT_ITEM) {
return new ChatAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.message_right_item, parent, false));
} else {
return new ChatAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.message_left_item, parent, false));
}
}
public void addMessage(MessageEntity message) {
if(message != null) {
for (MessageEntity messageEntity : messages) {
if(messageEntity.messageID.equals(message.messageID)) {
return;
}
}
messages.add(message);
Collections.sort(messages, comparator);
}
}
public void addMessages(List<MessageEntity> messages) {
this.messages.addAll(messages);
Collections.sort(messages, comparator);
}
@Override
public void onBindViewHolder(@NonNull ChatAdapter.ViewHolder holder, int position) {
// Setting message text
holder.messageText.setText(messages.get(position).text);
// Setting message time (HOUR:MINUTE)
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateFormat.setTimeZone(TimeZone.getDefault());
String time = dateFormat.format(new Date(messages.get(position).timestamp));
holder.messageTime.setText(time);
}
@Override
public int getItemCount() {
return messages.size();
}
@Override
public int getItemViewType(int position) {
if(messages.get(position).senderID.equals(AppHelper.getPeerID())) {
return RIGHT_ITEM;
} else {
return LEFT_ITEM;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView messageText;
CircleImageView profileImage;
TextView messageTime;
public ViewHolder(View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.message_text);
profileImage = itemView.findViewById(R.id.profile_image);
messageTime = itemView.findViewById(R.id.message_time);
}
}
}

View File

@ -0,0 +1,84 @@
package io.github.chronosx88.influence.helpers;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import io.github.chronosx88.influence.R;
import io.github.chronosx88.influence.contracts.IItemClickListener;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
public class ChatListAdapter extends RecyclerView.Adapter<ChatListAdapter.ChatListViewHolder> {
List<ChatEntity> chatList = new ArrayList<>();
public int onClickPosition = -1;
private IItemClickListener itemClickListener;
public ChatListAdapter(IItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@NonNull
@Override
public ChatListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item, parent, false);
return new ChatListViewHolder(view);
}
public void setChatList(List<ChatEntity> entities) {
chatList.clear();
chatList.addAll(entities);
}
public ChatEntity getItem(int position) {
return chatList.get(position);
}
@Override
public void onBindViewHolder(@NonNull ChatListViewHolder holder, int position) {
holder.chatName.setText(chatList.get(position).name);
holder.onLongClick(position);
}
public ChatEntity getChatEntity(int position) {
return chatList.get(position);
}
@Override
public int getItemCount() {
return chatList.size();
}
class ChatListViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
TextView chatName;
public ChatListViewHolder(View itemView) {
super(itemView);
chatName = itemView.findViewById(R.id.chat_name);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener((v) -> {
itemClickListener.onItemClick(v, getAdapterPosition());
});
}
public void onLongClick(int position) {
itemView.setOnLongClickListener((v) -> {
onClickPosition = position;
itemView.showContextMenu();
return true;
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0, 0, 0, "Remove chat");
}
}
}

View File

@ -0,0 +1,78 @@
package io.github.chronosx88.influence.helpers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class KeyPairManager {
private File keyPairDir;
private Serializer<KeyPair> serializer;
public KeyPairManager() {
this.keyPairDir = new File(AppHelper.getContext().getFilesDir().getAbsoluteFile(), "keyPairs");
if(!this.keyPairDir.exists()) {
this.keyPairDir.mkdir();
}
this.serializer = new Serializer<>();
}
public KeyPair openMainKeyPair() {
return getKeyPair("mainKeyPair");
}
public KeyPair getKeyPair(String keyPairName) {
keyPairName = keyPairName + ".kp";
File keyPairFile = new File(keyPairDir, keyPairName);
if (!keyPairFile.exists()) {
return createKeyPairFile(keyPairFile);
}
return openKeyPairFile(keyPairFile);
}
private synchronized KeyPair openKeyPairFile(File keyPairFile) {
KeyPair keyPair = null;
try {
FileInputStream inputStream = new FileInputStream(keyPairFile);
byte[] serializedKeyPair = new byte[(int) keyPairFile.length()];
inputStream.read(serializedKeyPair);
inputStream.close();
keyPair = serializer.deserialize(serializedKeyPair);
} catch (IOException e) {
e.printStackTrace();
}
return keyPair;
}
private synchronized KeyPair createKeyPairFile(File keyPairFile) {
KeyPair keyPair = null;
try {
keyPairFile.createNewFile();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyPair = keyPairGenerator.generateKeyPair();
FileOutputStream outputStream = new FileOutputStream(keyPairFile);
outputStream.write(serializer.serialize(keyPair));
outputStream.close();
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return keyPair;
}
public synchronized void saveKeyPair(String keyPairID, KeyPair keyPair) {
File keyPairFile = new File(keyPairDir, keyPairID + ".kp");
if(!keyPairFile.exists()) {
try {
FileOutputStream outputStream = new FileOutputStream(keyPairFile);
outputStream.write(serializer.serialize(keyPair));
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,61 @@
package io.github.chronosx88.influence.helpers;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
import io.github.chronosx88.influence.models.roomEntities.MessageEntity;
public class LocalDBWrapper {
private static final String LOG_TAG = "LocalDBWrapper";
private static RoomHelper dbInstance = AppHelper.getChatDB();
public static void createChatEntry(String jid, String chatName) {
dbInstance.chatDao().addChat(new ChatEntity(jid, chatName));
}
public static long createMessageEntry(String jid, String senderJid, long timestamp, String text, boolean isSent, boolean isRead) {
List<ChatEntity> chatEntities = AppHelper.getChatDB().chatDao().getChatByChatID(jid);
if(chatEntities.size() < 1) {
Log.e(LOG_TAG, "Failed to create message entry because chat " + jid + " doesn't exists!");
return -1;
}
MessageEntity message = new MessageEntity(jid, senderJid, timestamp, text, isSent, isRead);
long index = dbInstance.messageDao().insertMessage(message);
return index;
}
public static MessageEntity getMessageByID(long messageID) {
List<MessageEntity> messages = dbInstance.messageDao().getMessageByID(messageID);
if(messages.isEmpty()) {
return null;
}
return messages.get(0);
}
public static List<MessageEntity> getMessagesByChatID(String chatID) {
List<MessageEntity> messages = dbInstance.messageDao().getMessagesByChatID(chatID);
if(messages.isEmpty()) {
return null;
}
return messages;
}
public static ChatEntity getChatByChatID(String chatID) {
List<ChatEntity> chats = dbInstance.chatDao().getChatByChatID(chatID);
if(chats.isEmpty()) {
return null;
}
return chats.get(0);
}
public static void updateChatEntity(ChatEntity chatEntity) {
dbInstance.chatDao().updateChat(chatEntity);
}
public static void updateMessage(MessageEntity messageEntity) {
dbInstance.messageDao().updateMessage(messageEntity);
}
}

View File

@ -0,0 +1,35 @@
package io.github.chronosx88.influence.helpers;
import android.content.Context;
import android.content.Intent;
import com.instacart.library.truetime.TrueTime;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jxmpp.jid.EntityBareJid;
import io.github.chronosx88.influence.XMPPConnectionService;
public class NetworkHandler implements IncomingChatMessageListener {
private final static String LOG_TAG = "NetworkHandler";
private Context context;
public NetworkHandler(Context context) {
this.context = context;
}
@Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
if(LocalDBWrapper.getChatByChatID(from.asEntityBareJidString()) == null) {
LocalDBWrapper.createChatEntry(chat.getXmppAddressOfChatPartner().asUnescapedString(), chat.getXmppAddressOfChatPartner().asBareJid().asUnescapedString());
}
long messageID = LocalDBWrapper.createMessageEntry(chat.getXmppAddressOfChatPartner().asUnescapedString(), from.asUnescapedString(), TrueTime.now().getTime(), message.getBody(), true, false);
Intent intent = new Intent(XMPPConnectionService.INTENT_NEW_MESSAGE);
intent.setPackage(context.getPackageName());
intent.putExtra(XMPPConnectionService.MESSAGE_CHATID, chat.getXmppAddressOfChatPartner().toString());
intent.putExtra(XMPPConnectionService.MESSAGE_ID, messageID);
context.sendBroadcast(intent);
}
}

View File

@ -0,0 +1,30 @@
package io.github.chronosx88.influence.helpers;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class ObservableUtils {
public static void notifyUI(int action) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", action);
AppHelper.getObservable().notifyUIObservers(jsonObject);
}
public static void notifyUI(int action, String... additional) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", action);
JsonArray jsonArray = new JsonArray();
for(String info : additional) {
jsonArray.add(info);
}
jsonObject.add("additional", jsonArray);
AppHelper.getObservable().notifyUIObservers(jsonObject);
}
public static void notifyUI(int action, int additional) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", action);
jsonObject.addProperty("additional", additional);
AppHelper.getObservable().notifyUIObservers(jsonObject);
}
}

View File

@ -0,0 +1,17 @@
package io.github.chronosx88.influence.helpers;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import io.github.chronosx88.influence.models.daos.ChatDao;
import io.github.chronosx88.influence.models.daos.MessageDao;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
import io.github.chronosx88.influence.models.roomEntities.MessageEntity;
@Database(entities = { MessageEntity.class, ChatEntity.class }, version = 2)
@TypeConverters({RoomTypeConverter.class})
public abstract class RoomHelper extends RoomDatabase {
public abstract ChatDao chatDao();
public abstract MessageDao messageDao();
}

View File

@ -0,0 +1,25 @@
package io.github.chronosx88.influence.helpers;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import androidx.room.TypeConverter;
public class RoomTypeConverter {
@TypeConverter
public static ArrayList<String> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String fromArrayList(ArrayList<String> list) {
Gson gson = new Gson();
return gson.toJson(list);
}
}

View File

@ -0,0 +1,15 @@
package io.github.chronosx88.influence.logic;
import java.util.List;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
public class ChatListLogic implements CoreContracts.IChatListLogicContract {
@Override
public List<ChatEntity> loadAllChats() {
return AppHelper.getChatDB().chatDao().getAllChats();
}
}

View File

@ -0,0 +1,182 @@
package io.github.chronosx88.influence.logic;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.tomp2p.peers.Number640;
import net.tomp2p.storage.Data;
import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.helpers.KeyPairManager;
import io.github.chronosx88.influence.helpers.LocalDBWrapper;
import io.github.chronosx88.influence.helpers.ObservableUtils;
import io.github.chronosx88.influence.helpers.actions.NetworkActions;
import io.github.chronosx88.influence.helpers.actions.UIActions;
import io.github.chronosx88.influence.models.JoinChatMessage;
import io.github.chronosx88.influence.models.NextChunkReference;
import io.github.chronosx88.influence.models.TextMessage;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
import io.github.chronosx88.influence.models.roomEntities.MessageEntity;
public class ChatLogic implements CoreContracts.IChatLogicContract {
private static Gson gson = new Gson();
private String chatID;
private volatile String newMessage = "";
private ChatEntity chatEntity;
private Thread checkNewMessagesThread = null;
private KeyPairManager keyPairManager;
private Timer timer;
public ChatLogic(ChatEntity chatEntity) {
this.chatEntity = chatEntity;
this.chatID = chatEntity.chatID;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
checkForNewMessages();
}
};
this.timer = new Timer();
if(AppHelper.getPeerDHT() != null) {
timer.schedule(timerTask, 1, 1000);
}
this.keyPairManager = new KeyPairManager();
}
@Override
public void sendMessage(MessageEntity message) {
if(AppHelper.getPeerDHT() == null) {
ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE);
return;
}
new Thread(() -> {
Data data = null;
try {
data = new Data(gson.toJson(new TextMessage(message.senderID, message.messageID, message.chatID, message.username, message.timestamp, message.text, false)));
} catch (IOException e) {
e.printStackTrace();
}
data.protectEntry(keyPairManager.getKeyPair("mainKeyPair"));
P2PUtils.put(chatID + "_messages" + chatEntity.chunkCursor, message.messageID, data);
try {
P2PUtils.put(chatID + "_newMessage", null, new Data(message.messageID));
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
private void checkForNewMessages() {
if(checkNewMessagesThread == null) {
checkNewMessagesThread = new Thread(() -> {
Map<Number640, Data> data = P2PUtils.get(chatID + "_newMessage");
if(data != null) {
for(Map.Entry<Number640, Data> entry : data.entrySet()) {
String newMessage = null;
try {
newMessage = (String) entry.getValue().object();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(!newMessage.equals(this.newMessage)) {
handleNewMessages(chatEntity.chunkCursor);
this.newMessage = newMessage;
}
}
}
});
}
if(!checkNewMessagesThread.isAlive()) {
checkNewMessagesThread = new Thread(() -> {
Map<Number640, Data> data = P2PUtils.get(chatID + "_newMessage");
if(data != null) {
for(Map.Entry<Number640, Data> entry : data.entrySet()) {
String newMessage = null;
try {
newMessage = (String) entry.getValue().object();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(!newMessage.equals(this.newMessage)) {
handleNewMessages(chatEntity.chunkCursor);
this.newMessage = newMessage;
}
}
}
});
checkNewMessagesThread.start();
}
}
private void handleNewMessages(int chunkID) {
new Thread(() -> {
Map<Number640, Data> messages = P2PUtils.get(chatEntity.chatID + "_messages" + chunkID);
if (messages != null) {
for (Map.Entry<Number640, Data> message : messages.entrySet()) {
String json = null;
try {
json = (String) message.getValue().object();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
switch (getMessageAction(json)) {
case NetworkActions.TEXT_MESSAGE: {
TextMessage textMessage = gson.fromJson(json, TextMessage.class);
LocalDBWrapper.createMessageEntry(NetworkActions.TEXT_MESSAGE, textMessage.getMessageID(), textMessage.getChatID(), textMessage.getUsername(), textMessage.getSenderID(), textMessage.getTimestamp(), textMessage.getText(), true, false);
ObservableUtils.notifyUI(UIActions.MESSAGE_RECEIVED, chatID, textMessage.getMessageID());
break;
}
case NetworkActions.JOIN_CHAT: {
JoinChatMessage joinChatMessage = gson.fromJson(json, JoinChatMessage.class);
LocalDBWrapper.createMessageEntry(NetworkActions.JOIN_CHAT, joinChatMessage.getMessageID(), joinChatMessage.getChatID(), joinChatMessage.getUsername(), joinChatMessage.getSenderID(), joinChatMessage.getTimestamp(), null, true, false);
ObservableUtils.notifyUI(UIActions.MESSAGE_RECEIVED, chatID, joinChatMessage.getMessageID());
break;
}
case NetworkActions.NEXT_CHUNK_REF: {
NextChunkReference nextChunkReference = gson.fromJson(json, NextChunkReference.class);
chatEntity.chunkCursor = nextChunkReference.getNextChunkID();
LocalDBWrapper.updateChatEntity(chatEntity);
break;
}
}
}
if(messages.size() > 10) {
String messageID = UUID.randomUUID().toString();
try {
int nextChunkCursor = chatEntity.chunkCursor + 1;
P2PUtils.put(chatEntity.chatID + "_messages" + chunkID, messageID, new Data(gson.toJson(new NextChunkReference(messageID, AppHelper.getPeerID(), AppHelper.getPeerID(), System.currentTimeMillis(), nextChunkCursor))));
P2PUtils.put(chatEntity.chatID + "_newMessage", null, new Data(messageID));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
private int getMessageAction(String json) {
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject.get("action").getAsInt();
}
@Override
public void stopTrackingForNewMsgs() {
timer.cancel();
timer.purge();
}
}

View File

@ -0,0 +1,370 @@
package io.github.chronosx88.influence.logic;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import net.tomp2p.connection.Bindings;
import net.tomp2p.connection.ChannelClientConfiguration;
import net.tomp2p.connection.ChannelServerConfiguration;
import net.tomp2p.connection.Ports;
import net.tomp2p.connection.RSASignatureFactory;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.dht.Storage;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDiscover;
import net.tomp2p.nat.FutureRelayNAT;
import net.tomp2p.nat.PeerBuilderNAT;
import net.tomp2p.nat.PeerNAT;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number640;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.relay.tcp.TCPRelayClientConfig;
import net.tomp2p.replication.IndirectReplication;
import net.tomp2p.storage.Data;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.helpers.KeyPairManager;
import io.github.chronosx88.influence.helpers.LocalDBWrapper;
import io.github.chronosx88.influence.helpers.NetworkHandler;
import io.github.chronosx88.influence.helpers.ObservableUtils;
import io.github.chronosx88.influence.helpers.StorageBerkeleyDB;
import io.github.chronosx88.influence.helpers.actions.UIActions;
import io.github.chronosx88.influence.models.ChatMetadata;
import io.github.chronosx88.influence.models.NewChatRequestMessage;
import io.github.chronosx88.influence.models.PublicUserProfile;
public class MainLogic implements CoreContracts.IMainLogicContract {
private static final String LOG_TAG = MainLogic.class.getName();
private SharedPreferences preferences;
private Number160 peerID;
private PeerDHT peerDHT;
private Context context;
private InetAddress bootstrapAddress = null;
private PeerAddress bootstrapPeerAddress = null;
private Gson gson;
private IndirectReplication replication;
private KeyPairManager keyPairManager;
private Thread checkNewChatsThread = null;
private Storage storage;
public MainLogic() {
this.context = AppHelper.getContext();
this.preferences = context.getSharedPreferences("io.github.chronosx88.influence_preferences", context.MODE_PRIVATE);
gson = new Gson();
keyPairManager = new KeyPairManager();
}
@Override
public void initPeer() {
org.apache.log4j.BasicConfigurator.configure();
if(checkFirstRun()) {
SharedPreferences.Editor editor = preferences.edit();
String uuid = UUID.randomUUID().toString();
editor.putString("peerID", uuid);
editor.apply();
}
peerID = Number160.createHash(preferences.getString("peerID", null));
new Thread(() -> {
try {
File dhtDBEnv = new File(context.getFilesDir(), "dhtDBEnv");
if(!dhtDBEnv.exists())
dhtDBEnv.mkdirs();
Storage storage = new StorageBerkeleyDB(peerID, dhtDBEnv, new RSASignatureFactory());
this.storage = storage;
peerDHT = new PeerBuilderDHT(
new PeerBuilder(peerID)
.ports(7243)
.channelClientConfiguration(createChannelClientConfig())
.channelServerConfiguration(createChannelServerConfig())
.start()
)
.storage(storage)
.start();
Runtime.getRuntime().addShutdownHook(new JVMShutdownHook(storage));
try {
String bootstrapIP = this.preferences.getString("bootstrapAddress", null);
if(bootstrapIP == null) {
throw new NullPointerException();
}
bootstrapAddress = Inet4Address.getByName(bootstrapIP);
} catch (NullPointerException e) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", UIActions.BOOTSTRAP_NOT_SPECIFIED);
AppHelper.getObservable().notifyUIObservers(jsonObject);
peerDHT.shutdown();
return;
} catch (UnknownHostException e) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", UIActions.NETWORK_ERROR);
AppHelper.getObservable().notifyUIObservers(jsonObject);
peerDHT.shutdown();
return;
}
boolean discoveredExternalAddress = false;
if(discoverExternalAddress()) {
discoveredExternalAddress = true;
}
if(!discoveredExternalAddress) {
if(!setupConnectionToRelay()) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", UIActions.RELAY_CONNECTION_ERROR);
AppHelper.getObservable().notifyUIObservers(jsonObject);
return;
}
}
if(!bootstrapPeer()) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", UIActions.BOOTSTRAP_ERROR);
AppHelper.getObservable().notifyUIObservers(jsonObject);
return;
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", UIActions.BOOTSTRAP_SUCCESS);
AppHelper.getObservable().notifyUIObservers(jsonObject);
AppHelper.storePeerID(preferences.getString("peerID", null));
AppHelper.updateUsername(preferences.getString("username", null));
AppHelper.storePeerDHT(peerDHT);
AppHelper.initNetworkHandler();
//setReceiveHandler();
gson = new Gson();
publicProfileToDHT();
SettingsLogic.Companion.publishUsername(AppHelper.getUsername(), AppHelper.getUsername());
NetworkHandler.handlePendingChatRequests();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(checkNewChatsThread == null) {
checkNewChatsThread = new Thread(NetworkHandler::handlePendingChatRequests);
checkNewChatsThread.start();
}
if(!checkNewChatsThread.isAlive()) {
checkNewChatsThread = new Thread(NetworkHandler::handlePendingChatRequests);
checkNewChatsThread.start();
}
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 1, 5000);
replication = new IndirectReplication(peerDHT).start();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
private boolean bootstrapPeer() {
FutureBootstrap futureBootstrap = peerDHT.peer().bootstrap().inetAddress(bootstrapAddress).ports(7243).start();
futureBootstrap.awaitUninterruptibly();
if(futureBootstrap.isSuccess()) {
Log.i("MainLogic", "# Successfully bootstrapped to " + bootstrapAddress.toString());
return true;
} else {
Log.e("MainLogic", "# Cannot bootstrap to " + bootstrapAddress.toString() + ". Reason: " + futureBootstrap.failedReason());
return false;
}
}
private boolean discoverExternalAddress() {
FutureDiscover futureDiscover = peerDHT
.peer()
.discover()
.inetAddress(bootstrapAddress)
.ports(7243)
.start();
futureDiscover.awaitUninterruptibly();
bootstrapPeerAddress = futureDiscover.reporter();
if(futureDiscover.isSuccess()) {
Log.i(LOG_TAG, "# Success discover! Your external IP: " + futureDiscover.peerAddress().toString());
return true;
} else {
Log.e(LOG_TAG, "# Failed to discover my external IP. Reason: " + futureDiscover.failedReason());
return false;
}
}
private boolean setupConnectionToRelay() {
PeerNAT peerNat = new PeerBuilderNAT(peerDHT.peer()).start();
FutureRelayNAT futureRelayNAT = peerNat.startRelay(new TCPRelayClientConfig(), bootstrapPeerAddress).awaitUninterruptibly();
if (futureRelayNAT.isSuccess()) {
Log.i(LOG_TAG, "# Successfully connected to relay node.");
return true;
} else {
Log.e(LOG_TAG, "# Cannot connect to relay node. Reason: " + futureRelayNAT.failedReason());
return false;
}
}
private void setReceiveHandler() {
AppHelper.getPeerDHT().peer().objectDataReply((s, r) -> {
Log.i(LOG_TAG, "# Incoming message: " + r);
AppHelper.getObservable().notifyNetworkObservers(r);
return null;
});
}
@Override
public void shutdownPeer() {
new Thread(() -> {
if(replication != null) {
replication.shutdown();
}
if(peerDHT != null) {
peerDHT.peer().announceShutdown().start().awaitUninterruptibly();
peerDHT.peer().shutdown().awaitUninterruptibly();
}
storage.close();
System.exit(0);
}).start();
}
private boolean checkFirstRun() {
if (preferences.getBoolean("firstRun", true)) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstRun", false);
editor.apply();
return true;
}
return false;
}
private void publicProfileToDHT() {
KeyPair mainKeyPair = keyPairManager.openMainKeyPair();
PublicUserProfile userProfile = new PublicUserProfile(AppHelper.getUsername(), peerDHT.peerAddress());
Data serializedUserProfile = null;
try {
serializedUserProfile = new Data(gson.toJson(userProfile))
.protectEntry(mainKeyPair.getPrivate());
} catch (IOException e) {
e.printStackTrace();
}
Log.i(LOG_TAG, P2PUtils.put(AppHelper.getPeerID() + "_profile", null, serializedUserProfile, mainKeyPair) ? "# Profile successfully published!" : "# Profile publishing failed!");
}
private ChannelClientConfiguration createChannelClientConfig() {
ChannelClientConfiguration channelClientConfiguration = new ChannelClientConfiguration();
channelClientConfiguration.bindings(new Bindings());
channelClientConfiguration.maxPermitsPermanentTCP(250);
channelClientConfiguration.maxPermitsTCP(250);
channelClientConfiguration.maxPermitsUDP(250);
channelClientConfiguration.pipelineFilter(new PeerBuilder.DefaultPipelineFilter());
channelClientConfiguration.signatureFactory(new RSASignatureFactory());
channelClientConfiguration.senderTCP((new InetSocketAddress(0)).getAddress());
channelClientConfiguration.senderUDP((new InetSocketAddress(0)).getAddress());
channelClientConfiguration.byteBufPool(false);
return channelClientConfiguration;
}
private ChannelServerConfiguration createChannelServerConfig() {
ChannelServerConfiguration channelServerConfiguration = new ChannelServerConfiguration();
channelServerConfiguration.bindings(new Bindings());
//these two values may be overwritten in the peer builder
channelServerConfiguration.ports(new Ports(Ports.DEFAULT_PORT, Ports.DEFAULT_PORT));
channelServerConfiguration.portsForwarding(new Ports(Ports.DEFAULT_PORT, Ports.DEFAULT_PORT));
channelServerConfiguration.behindFirewall(false);
channelServerConfiguration.pipelineFilter(new PeerBuilder.DefaultPipelineFilter());
channelServerConfiguration.signatureFactory(new RSASignatureFactory());
channelServerConfiguration.byteBufPool(false);
return channelServerConfiguration;
}
@Override
public void sendStartChatMessage(@NotNull String username) {
if(AppHelper.getPeerDHT() == null) {
ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE);
return;
}
String companionPeerID = getPeerIDByUsername(username);
if(companionPeerID == null) {
ObservableUtils.notifyUI(UIActions.PEER_NOT_EXIST);
return;
}
PublicUserProfile recipientPublicProfile = getPublicProfile(companionPeerID);
if(recipientPublicProfile == null) {
ObservableUtils.notifyUI(UIActions.PEER_NOT_EXIST);
return;
}
NewChatRequestMessage newChatRequestMessage = new NewChatRequestMessage(UUID.randomUUID().toString(), UUID.randomUUID().toString(), AppHelper.getPeerID(), AppHelper.getUsername(), System.currentTimeMillis(), 0);
try {
if(P2PUtils.put(companionPeerID + "_pendingChats", newChatRequestMessage.getChatID(), new Data(gson.toJson(newChatRequestMessage)))) {
Log.i(LOG_TAG, "# Create new offline chat request is successful! ChatID: " + newChatRequestMessage.getChatID());
} else {
Log.e(LOG_TAG, "# Failed to create offline chat request. ChatID: " + newChatRequestMessage.getChatID());
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> admins = new ArrayList<>();
admins.add(AppHelper.getPeerID());
Data data = null;
try {
data = new Data(gson.toJson(new ChatMetadata(username, admins, new ArrayList<>())));
} catch (IOException e) {
e.printStackTrace();
}
data.protectEntry(keyPairManager.openMainKeyPair());
P2PUtils.put(newChatRequestMessage.getChatID() + "_metadata", null, data);
LocalDBWrapper.createChatEntry(newChatRequestMessage.getChatID(), username, newChatRequestMessage.getChatID() + "_metadata", newChatRequestMessage.getChatID() + "_members", 0);
ObservableUtils.notifyUI(UIActions.NEW_CHAT);
}
private PublicUserProfile getPublicProfile(String peerID) {
PublicUserProfile publicProfile = null;
Map<Number640, Data> data = P2PUtils.get(peerID + "_profile");
if (data != null && data.size() == 1) {
try {
publicProfile = gson.fromJson((String) data.values().iterator().next().object(), PublicUserProfile.class);
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return publicProfile;
}
return null;
}
private String getPeerIDByUsername(String username) {
Map<Number640, Data> usernameMap = P2PUtils.get(username);
if(usernameMap == null) {
return null;
}
try {
return (String) usernameMap.values().iterator().next().object();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,58 @@
package io.github.chronosx88.influence.logic
import android.util.Log
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.helpers.AppHelper
import io.github.chronosx88.influence.helpers.KeyPairManager
import io.github.chronosx88.influence.helpers.ObservableUtils
import io.github.chronosx88.influence.helpers.actions.UIActions
import net.tomp2p.peers.Number640
import net.tomp2p.storage.Data
import java.io.IOException
class SettingsLogic : CoreContracts.ISettingsLogic {
override fun checkUsernameExists(username: String) : Boolean {
if (AppHelper.getPeerDHT() == null) {
ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE)
return false
}
val usernameMap: MutableMap<Number640, Data>? = P2PUtils.get(username)
usernameMap ?: return false
return true
}
companion object {
private val LOG_TAG: String = "SettingsLogic"
private val keyPairManager = KeyPairManager()
fun publishUsername(oldUsername: String?, username: String?) {
if (AppHelper.getPeerDHT() == null) {
ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE)
return
}
val mainKeyPair = keyPairManager.openMainKeyPair()
oldUsername?.let {
if(!oldUsername.equals("")) {
P2PUtils.remove(oldUsername, null, mainKeyPair)
}
}
username?.let {
var data: Data? = null
try {
data = Data(AppHelper.getPeerID())
} catch (e: IOException) {
e.printStackTrace()
}
data!!.protectEntry(mainKeyPair)
val isSuccess = P2PUtils.put(username, null, data, mainKeyPair)
Log.i(LOG_TAG, if (isSuccess) "# Username $username is published!" else "# Username $username isn't published!")
} ?: run {
return
}
}
}
}

View File

@ -0,0 +1,28 @@
package io.github.chronosx88.influence.models.daos;
import java.util.List;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
@Dao
public interface ChatDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void addChat(ChatEntity chatEntity);
@Query("DELETE FROM chats WHERE jid = :jid")
void deleteChat(String jid);
@Query("SELECT * FROM chats")
List<ChatEntity> getAllChats();
@Query("SELECT * FROM chats WHERE jid = :jid")
List<ChatEntity> getChatByChatID(String jid);
@Update
void updateChat(ChatEntity chat);
}

View File

@ -0,0 +1,31 @@
package io.github.chronosx88.influence.models.daos;
import java.util.List;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import io.github.chronosx88.influence.models.roomEntities.MessageEntity;
@Dao
public interface MessageDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
long insertMessage(MessageEntity chatModel);
@Query("DELETE FROM messages WHERE messageID = :messageID")
void deleteMessage(String messageID);
@Query("DELETE FROM messages WHERE jid = :jid")
void deleteMessagesByChatID(String jid);
@Query("SELECT * FROM messages WHERE jid = :jid")
List<MessageEntity> getMessagesByChatID(String jid);
@Query("SELECT * FROM messages WHERE messageID = :messageID")
List<MessageEntity> getMessageByID(long messageID);
@Update
void updateMessage(MessageEntity message);
}

View File

@ -0,0 +1,17 @@
package io.github.chronosx88.influence.models.roomEntities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "chats")
public class ChatEntity {
@PrimaryKey @NonNull public String jid;
@ColumnInfo public String chatName;
public ChatEntity(@NonNull String jid, String chatName) {
this.jid = jid;
this.chatName = chatName;
}
}

View File

@ -0,0 +1,32 @@
package io.github.chronosx88.influence.models.roomEntities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "messages")
public class MessageEntity {
@PrimaryKey(autoGenerate = true) public long messageID; // Global message ID
@ColumnInfo public String jid; // Chat ID
@ColumnInfo public String senderJid;
@ColumnInfo public long timestamp; // Timestamp
@ColumnInfo public String text; // Message text
@ColumnInfo public boolean isSent; // Send status indicator
@ColumnInfo public boolean isRead; // Message Read Indicator
public MessageEntity(String jid, String senderJid, long timestamp, String text, boolean isSent, boolean isRead) {
this.jid = jid;
this.senderJid = senderJid;
this.timestamp = timestamp;
this.text = text;
this.isSent = isSent;
this.isRead = isRead;
}
@NonNull
@Override
public String toString() {
return text;
}
}

View File

@ -0,0 +1,56 @@
package io.github.chronosx88.influence.observable;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import io.github.chronosx88.influence.contracts.observer.INetworkObserver;
import io.github.chronosx88.influence.contracts.observer.IObservable;
import io.github.chronosx88.influence.contracts.observer.IObserver;
public class MainObservable implements IObservable {
public static final int UI_ACTIONS_CHANNEL = 0;
public static final int OTHER_ACTIONS_CHANNEL = 1;
private ArrayList<IObserver> uiObservers;
private ArrayList<INetworkObserver> networkObservers;
public MainObservable() {
this.uiObservers = new ArrayList<>();
this.networkObservers = new ArrayList<>();
}
@Override
public void register(IObserver observer) {
uiObservers.add(observer);
}
@Override
public void register(INetworkObserver observer) {
networkObservers.add(observer);
}
@Override
public void unregister(IObserver observer) {
uiObservers.remove(observer);
}
@Override
public void unregister(INetworkObserver observer) {
networkObservers.remove(observer);
}
@Override
public void notifyUIObservers(JsonObject jsonObject) {
for (IObserver observer : uiObservers) {
observer.handleEvent(jsonObject);
}
}
@Override
public void notifyNetworkObservers(Object object) {
for (INetworkObserver observer : networkObservers) {
observer.handleEvent(object);
}
}
}

View File

@ -0,0 +1,56 @@
package io.github.chronosx88.influence.presenters;
import android.content.Intent;
import android.view.MenuItem;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.helpers.ChatListAdapter;
import io.github.chronosx88.influence.helpers.LocalDBWrapper;
import io.github.chronosx88.influence.logic.ChatListLogic;
import io.github.chronosx88.influence.models.roomEntities.ChatEntity;
import io.github.chronosx88.influence.views.ChatActivity;
public class ChatListPresenter implements CoreContracts.IChatListPresenterContract {
private CoreContracts.IChatListViewContract view;
private CoreContracts.IChatListLogicContract logic;
private ChatListAdapter chatListAdapter;
public ChatListPresenter(CoreContracts.IChatListViewContract view) {
this.view = view;
chatListAdapter = new ChatListAdapter((v, p)-> {
openChat(chatListAdapter.getChatEntity(p).chatID);
});
this.logic = new ChatListLogic();
this.view.setRecycleAdapter(chatListAdapter);
}
@Override
public void updateChatList() {
view.updateChatList(chatListAdapter, logic.loadAllChats());
}
@Override
public void openChat(String chatID) {
Intent intent = new Intent(AppHelper.getContext(), ChatActivity.class);
intent.putExtra("chatID", chatID);
intent.putExtra("contactUsername", LocalDBWrapper.getChatByChatID(chatID).name);
view.startActivity(intent);
}
@Override
public void onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 0: {
if(chatListAdapter.onClickPosition != -1) {
new Thread(() -> {
ChatEntity chat = chatListAdapter.getItem(chatListAdapter.onClickPosition);
AppHelper.getChatDB().chatDao().deleteChat(chat.chatID);
AppHelper.getChatDB().messageDao().deleteMessagesByChatID(chat.chatID);
view.updateChatList(chatListAdapter, logic.loadAllChats());
}).start();
}
}
}
}
}

View File

@ -0,0 +1,70 @@
package io.github.chronosx88.influence.presenters
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.instacart.library.truetime.TrueTime
import java.io.IOException
import java.util.ArrayList
import java.util.UUID
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.contracts.observer.IObserver
import io.github.chronosx88.influence.helpers.AppHelper
import io.github.chronosx88.influence.helpers.LocalDBWrapper
import io.github.chronosx88.influence.helpers.actions.NetworkActions
import io.github.chronosx88.influence.helpers.actions.UIActions
import io.github.chronosx88.influence.logic.ChatLogic
import io.github.chronosx88.influence.models.roomEntities.ChatEntity
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.doAsyncResult
class ChatPresenter(private val view: CoreContracts.IChatViewContract, private val chatID: String) : CoreContracts.IChatPresenterContract, IObserver {
private val logic: CoreContracts.IChatLogicContract
private val chatEntity: ChatEntity?
private val gson: Gson
init {
this.logic = ChatLogic(LocalDBWrapper.getChatByChatID(chatID)!!)
this.chatEntity = LocalDBWrapper.getChatByChatID(chatID)
AppHelper.getObservable().register(this)
gson = Gson()
}
override fun sendMessage(text: String) {
doAsync {
val message = LocalDBWrapper.createMessageEntry(NetworkActions.TEXT_MESSAGE, UUID.randomUUID().toString(), chatID, AppHelper.getPeerID(), AppHelper.getPeerID(), TrueTime.now().time, text, false, false)
logic.sendMessage(message!!)
view.updateMessageList(message)
}
}
override fun handleEvent(obj: JsonObject) {
when (obj.get("action").asInt) {
UIActions.MESSAGE_RECEIVED -> {
val jsonArray = obj.getAsJsonArray("additional")
if (jsonArray.get(0).asString != chatID) {
return
}
val messageEntity = LocalDBWrapper.getMessageByID(jsonArray.get(1).asString)
view.updateMessageList(messageEntity!!)
}
UIActions.NODE_IS_OFFLINE -> {
Toast.makeText(AppHelper.getContext(), "Нода не запущена!", Toast.LENGTH_SHORT).show()
}
}
}
override fun updateAdapter() {
val entities = LocalDBWrapper.getMessagesByChatID(chatID)
view.updateMessageList(entities ?: ArrayList())
}
override fun onDestroy() {
logic.stopTrackingForNewMsgs()
}
}

View File

@ -0,0 +1,56 @@
package io.github.chronosx88.influence.presenters
import com.google.gson.JsonObject
import io.github.chronosx88.influence.R
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.contracts.observer.IObserver
import io.github.chronosx88.influence.helpers.AppHelper
import io.github.chronosx88.influence.helpers.actions.UIActions
import io.github.chronosx88.influence.logic.MainLogic
import org.jetbrains.anko.doAsync
class MainPresenter(private val view: CoreContracts.IMainViewContract) : CoreContracts.IMainPresenterContract, IObserver {
private val logic: CoreContracts.IMainLogicContract = MainLogic()
init {
AppHelper.getObservable().register(this)
}
override fun initPeer() {
if (AppHelper.getPeerDHT() == null) {
logic.initPeer()
} else {
view.showSnackbar(AppHelper.getContext().getString(R.string.node_already_running))
view.showProgressBar(false)
}
}
override fun startChatWithPeer(username: String) {
doAsync {
logic.sendStartChatMessage(username)
}
}
override fun handleEvent(obj: JsonObject) {
when(obj.get("action").asInt) {
UIActions.PEER_NOT_EXIST -> {
view.showProgressBar(false)
view.showSnackbar("Данный узел не существует!")
}
UIActions.NEW_CHAT -> {
view.showProgressBar(false)
view.showSnackbar("Чат успешно создан!")
}
UIActions.NODE_IS_OFFLINE -> {
view.showProgressBar(false)
view.showSnackbar("Нода не запущена!")
}
}
}
override fun onDestroy() {
logic.shutdownPeer()
}
}

View File

@ -0,0 +1,74 @@
package io.github.chronosx88.influence.presenters
import android.content.SharedPreferences
import android.os.Handler
import com.google.gson.JsonObject
import io.github.chronosx88.influence.R
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.contracts.observer.IObserver
import io.github.chronosx88.influence.helpers.AppHelper
import io.github.chronosx88.influence.helpers.ObservableUtils
import io.github.chronosx88.influence.helpers.actions.UIActions
import io.github.chronosx88.influence.logic.SettingsLogic
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class SettingsPresenter(private val view: CoreContracts.ISettingsView) : CoreContracts.ISettingsPresenter, IObserver {
private val mainThreadHandler: Handler = Handler(AppHelper.getContext().mainLooper)
private val logic: SettingsLogic = SettingsLogic()
init {
AppHelper.getObservable().register(this)
}
override fun updateUsername(username: String) {
view.loadingScreen(true)
val editor: SharedPreferences.Editor = AppHelper.getPreferences().edit()
GlobalScope.launch {
val oldUsername = AppHelper.getPreferences().getString("username", null)
if(username.equals("")) {
SettingsLogic.publishUsername(oldUsername, null)
editor.remove("username")
editor.apply()
AppHelper.updateUsername(null)
ObservableUtils.notifyUI(UIActions.USERNAME_AVAILABLE)
return@launch
}
if(!logic.checkUsernameExists(username)) {
// Save username in SharedPreferences
if(username.equals("")) {
editor.remove("username")
} else {
editor.putString("username", username)
}
editor.apply()
AppHelper.updateUsername(if (username.equals("")) null else username)
// Publish username on DHT network
SettingsLogic.publishUsername(oldUsername, username)
ObservableUtils.notifyUI(UIActions.USERNAME_AVAILABLE)
} else {
ObservableUtils.notifyUI(UIActions.USERNAME_ISNT_AVAILABLE)
}
}
}
override fun handleEvent(json: JsonObject) {
val post = {
when (json.get("action").asInt) {
UIActions.USERNAME_AVAILABLE -> {
view.loadingScreen(false)
view.showMessage(AppHelper.getContext().getString(R.string.username_saved))
view.refreshScreen()
}
UIActions.USERNAME_ISNT_AVAILABLE -> {
view.loadingScreen(false)
view.showMessage(AppHelper.getContext().getString(R.string.username_isnt_saved))
}
}
}
mainThreadHandler.post(post)
}
}

View File

@ -0,0 +1,87 @@
package io.github.chronosx88.influence.views
import android.os.Bundle
import android.view.MenuItem
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.github.chronosx88.influence.R
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.helpers.ChatAdapter
import io.github.chronosx88.influence.models.roomEntities.MessageEntity
import io.github.chronosx88.influence.presenters.ChatPresenter
class ChatActivity : AppCompatActivity(), CoreContracts.IChatViewContract {
private var chatAdapter: ChatAdapter? = null
private var messageList: RecyclerView? = null
private var sendMessageButton: ImageButton? = null
private var messageTextEdit: EditText? = null
private var contactUsernameTextView: TextView? = null
private var presenter: ChatPresenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
val intent = intent
presenter = ChatPresenter(this, intent.getStringExtra("chatID"))
val toolbar = findViewById<Toolbar>(R.id.toolbar_chat_activity)
setSupportActionBar(toolbar)
supportActionBar!!.setTitle("")
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
messageList = findViewById(R.id.message_list)
chatAdapter = ChatAdapter()
presenter!!.updateAdapter()
messageList!!.adapter = chatAdapter
messageList!!.layoutManager = LinearLayoutManager(this)
contactUsernameTextView = findViewById(R.id.appbar_username)
messageTextEdit = findViewById(R.id.message_input)
sendMessageButton = findViewById(R.id.send_button)
sendMessageButton!!.setOnClickListener sendMessageButton@{
if (messageTextEdit!!.text.toString() == "") {
return@sendMessageButton
}
presenter!!.sendMessage(messageTextEdit!!.text.toString())
messageTextEdit!!.setText("")
}
contactUsernameTextView!!.text = intent.getStringExtra("contactUsername")
messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1)
}
override fun updateMessageList(message: MessageEntity) {
runOnUiThread {
chatAdapter!!.addMessage(message)
messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1)
chatAdapter!!.notifyDataSetChanged()
}
}
override fun updateMessageList(messages: List<MessageEntity>) {
runOnUiThread {
chatAdapter!!.addMessages(messages)
messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1)
chatAdapter!!.notifyDataSetChanged()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
presenter!!.onDestroy()
}
}

View File

@ -0,0 +1,157 @@
/*
* Copyright (C) 2019 ChronosX88
*
* 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 <https://www.gnu.org/licenses/>.
*/
package io.github.chronosx88.influence.views;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import io.github.chronosx88.influence.R;
import io.github.chronosx88.influence.XMPPConnectionService;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
public class LoginActivity extends AppCompatActivity implements CoreContracts.ILoginViewContract {
private EditText jidEditText;
private EditText passwordEditText;
private Button signInButton;
private BroadcastReceiver broadcastReceiver;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jidEditText = findViewById(R.id.login_jid);
passwordEditText = findViewById(R.id.login_password);
signInButton = findViewById(R.id.sign_in_button);
progressDialog = new ProgressDialog(LoginActivity.this);
signInButton.setOnClickListener((v) -> {
if(checkLoginCredentials()) {
saveLoginCredentials();
doLogin();
}
});
}
@Override
public void loadingScreen(boolean state) {
if(state)
progressDialog.show();
else
progressDialog.dismiss();
}
@Override
protected void onResume() {
super.onResume();
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case XMPPConnectionService.INTENT_AUTHENTICATED: {
loadingScreen(false);
finish();
break;
}
case XMPPConnectionService.INTENT_AUTHENTICATION_FAILED: {
loadingScreen(false);
passwordEditText.setError("Invalid JID/Password");
break;
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(XMPPConnectionService.INTENT_AUTHENTICATED);
filter.addAction(XMPPConnectionService.INTENT_AUTHENTICATION_FAILED);
this.registerReceiver(broadcastReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(broadcastReceiver);
}
private boolean checkLoginCredentials() {
jidEditText.setError(null);
passwordEditText.setError(null);
String jid = jidEditText.getText().toString();
String password = passwordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
passwordEditText.setError("Invalid password");
focusView = passwordEditText;
cancel = true;
}
if (TextUtils.isEmpty(jid)) {
jidEditText.setError("Field is required!");
focusView = jidEditText;
cancel = true;
} else if (!isEmailValid(jid)) {
jidEditText.setError("Invalid JID");
focusView = jidEditText;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
return false;
} else {
return true;
}
}
private boolean isEmailValid(String email) {
return email.contains("@");
}
private boolean isPasswordValid(String password) {
return password.length() > 4;
}
private void saveLoginCredentials() {
AppHelper.getPreferences().edit()
.putString("jid", jidEditText.getText().toString())
.putString("pass", passwordEditText.getText().toString())
.putBoolean("logged_in", true)
.apply();
}
private void doLogin() {
loadingScreen(true);
startService(new Intent(this, XMPPConnectionService.class));
}
}

View File

@ -0,0 +1,152 @@
package io.github.chronosx88.influence.views;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.JsonObject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import org.jetbrains.annotations.NotNull;
import io.github.chronosx88.influence.R;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.contracts.observer.IObserver;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.helpers.actions.UIActions;
import io.github.chronosx88.influence.presenters.MainPresenter;
import io.github.chronosx88.influence.views.fragments.ChatListFragment;
import io.github.chronosx88.influence.views.fragments.SettingsFragment;
import kotlin.Pair;
public class MainActivity extends AppCompatActivity implements CoreContracts.IMainViewContract {
private CoreContracts.IMainPresenterContract presenter;
private ProgressDialog progressDialog;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_chats:
selectedFragment = new ChatListFragment();
break;
case R.id.action_settings:
selectedFragment = new SettingsFragment();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_fragment_container, selectedFragment);
transaction.commit();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.main_bottom_navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FloatingActionButton fab = findViewById(R.id.add_chat);
fab.setOnClickListener((v) -> {
Pair<AlertDialog.Builder, EditText> pair = ViewUtils.INSTANCE.setupEditTextDialog(MainActivity.this, getString(R.string.input_companion_username));
pair.getFirst().setPositiveButton(getString(R.string.ok), (dialog, which) -> {
progressDialog.show();
presenter.startChatWithPeer(pair.getSecond().getText().toString());
});
pair.getFirst().setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
dialog.cancel();
});
pair.getFirst().show();
});
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment_container, new ChatListFragment())
.commit();
presenter = new MainPresenter(this);
progressDialog = new ProgressDialog(MainActivity.this, R.style.AlertDialogTheme);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
progressDialog.show();
presenter.initPeer();
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_actionbar_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_reconnect_network) {
progressDialog.show();
presenter.initPeer();
}
return true;
}
@Override
public void showSnackbar(@NotNull String message) {
runOnUiThread(() -> {
Snackbar.make(getRootView(), message, Snackbar.LENGTH_LONG)
.show();
});
}
@Override
public void showProgressBar(boolean state) {
runOnUiThread(() -> {
if(state) {
progressDialog.show();
} else {
progressDialog.dismiss();
}
});
}
private View getRootView() {
final ViewGroup contentViewGroup = findViewById(android.R.id.content);
View rootView = null;
if(contentViewGroup != null)
rootView = contentViewGroup.getChildAt(0);
if(rootView == null)
rootView = getWindow().getDecorView().getRootView();
return rootView;
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (C) 2019 ChronosX88
*
* 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 <https://www.gnu.org/licenses/>.
*/
package io.github.chronosx88.influence.views
import android.content.Context
import android.widget.EditText
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import io.github.chronosx88.influence.R
object ViewUtils {
fun setupEditTextDialog(context: Context, message: String): Pair<AlertDialog.Builder, EditText> {
val alertDialog = AlertDialog.Builder(context)
alertDialog.setTitle(message)
val input = EditText(context)
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT)
input.setSingleLine()
input.layoutParams = lp
alertDialog.setView(input)
return Pair(alertDialog, input)
}
}

View File

@ -0,0 +1,76 @@
package io.github.chronosx88.influence.views.fragments
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.google.gson.JsonObject
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.github.chronosx88.influence.R
import io.github.chronosx88.influence.contracts.CoreContracts
import io.github.chronosx88.influence.contracts.observer.IObserver
import io.github.chronosx88.influence.helpers.AppHelper
import io.github.chronosx88.influence.helpers.ChatListAdapter
import io.github.chronosx88.influence.helpers.actions.UIActions
import io.github.chronosx88.influence.models.roomEntities.ChatEntity
import io.github.chronosx88.influence.presenters.ChatListPresenter
class ChatListFragment : Fragment(), CoreContracts.IChatListViewContract, IObserver {
private var presenter: CoreContracts.IChatListPresenterContract? = null
private var chatList: RecyclerView? = null
private var mainThreadHandler: Handler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppHelper.getObservable().register(this)
this.mainThreadHandler = Handler(context!!.mainLooper)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.chatlist_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
chatList = view.findViewById(R.id.chatlist_container)
chatList!!.layoutManager = LinearLayoutManager(context)
presenter = ChatListPresenter(this)
presenter!!.updateChatList()
registerForContextMenu(chatList!!)
}
override fun setRecycleAdapter(adapter: ChatListAdapter) {
chatList!!.adapter = adapter
}
override fun onResume() {
super.onResume()
presenter!!.updateChatList()
}
override fun handleEvent(`object`: JsonObject) {
when (`object`.get("action").asInt) {
UIActions.SUCCESSFUL_CREATE_CHAT, UIActions.NEW_CHAT -> {
presenter!!.updateChatList()
}
}
}
override fun updateChatList(adapter: ChatListAdapter, chats: List<ChatEntity>) {
mainThreadHandler!!.post {
adapter.setChatList(chats)
adapter.notifyDataSetChanged()
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
presenter!!.onContextItemSelected(item)
return super.onContextItemSelected(item)
}
}

View File

@ -0,0 +1,92 @@
package io.github.chronosx88.influence.views.fragments;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen;
import androidx.recyclerview.widget.RecyclerView;
import io.github.chronosx88.influence.R;
import io.github.chronosx88.influence.contracts.CoreContracts;
import io.github.chronosx88.influence.helpers.AppHelper;
import io.github.chronosx88.influence.presenters.SettingsPresenter;
public class SettingsFragment extends PreferenceFragmentCompat implements CoreContracts.ISettingsView {
private ProgressDialog progressDialog;
private SettingsPresenter presenter;
@Override
public void onCreatePreferences(Bundle bundle, String s) {
progressDialog = new ProgressDialog(getContext(), R.style.AlertDialogTheme);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
presenter = new SettingsPresenter(this);
// Load the Preferences from the XML file
addPreferencesFromResource(R.xml.main_settings);
getPreferenceScreen().getPreference(0).setSummary(AppHelper.getPeerID());
getPreferenceScreen().getPreference(0).setOnPreferenceClickListener((preference -> {
ClipboardManager clipboard = (ClipboardManager) AppHelper.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", AppHelper.getPeerID());
clipboard.setPrimaryClip(clip);
Toast.makeText(AppHelper.getContext(), "Скопировано в буфер обмена!", Toast.LENGTH_SHORT).show();
return false;
}));
getPreferenceScreen().getPreference(1).setSummary(AppHelper.getUsername());
getPreferenceScreen().getPreference(1).setOnPreferenceClickListener((v) -> {
setupUsernameEditDialog().show();
return true;
});
getPreferenceScreen().getPreference(1).setOnPreferenceChangeListener((p, nV) -> {
getPreferenceScreen().getPreference(1).setSummary((String) nV);
return true;
});
}
@Override
public void loadingScreen(boolean state) {
if(state)
progressDialog.show();
else
progressDialog.dismiss();
}
@Override
public void showMessage(@NotNull String message) {
Toast.makeText(AppHelper.getContext(), message, Toast.LENGTH_LONG).show();
}
private AlertDialog.Builder setupUsernameEditDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle(getContext().getString(R.string.username_settings));
final EditText input = new EditText(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setSingleLine();
input.setLayoutParams(lp);
input.setText(AppHelper.getPreferences().getString("username", null));
alertDialog.setView(input);
alertDialog.setPositiveButton(getContext().getString(R.string.ok), (dialog, which) -> presenter.updateUsername(input.getText().toString()));
alertDialog.setNegativeButton(getContext().getString(R.string.cancel), (dialog, which) -> dialog.cancel());
return alertDialog;
}
@Override
public void refreshScreen() {
getPreferenceScreen().getPreference(1).callChangeListener(AppHelper.getPreferences().getString("username", null));
}
}

View File

@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeWidth="1"
android:strokeColor="#00000000">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@ -0,0 +1,22 @@
<!--
~ Copyright (C) 2019 ChronosX88
~
~ 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 <https://www.gnu.org/licenses/>.
-->
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

View File

@ -0,0 +1,22 @@
<!--
~ Copyright (C) 2019 ChronosX88
~
~ 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 <https://www.gnu.org/licenses/>.
-->
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M12,6v3l4,-4 -4,-4v3c-4.42,0 -8,3.58 -8,8 0,1.57 0.46,3.03 1.24,4.26L6.7,14.8c-0.45,-0.83 -0.7,-1.79 -0.7,-2.8 0,-3.31 2.69,-6 6,-6zM18.76,7.74L17.3,9.2c0.44,0.84 0.7,1.79 0.7,2.8 0,3.31 -2.69,6 -6,6v-3l-4,4 4,4v-3c4.42,0 8,-3.58 8,-8 0,-1.57 -0.46,-3.03 -1.24,-4.26z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM6,9h12v2L6,11L6,9zM14,14L6,14v-2h8v2zM18,8L6,8L6,6h12v2z"/>
</vector>

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#008577"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10L6,7L4,7v3L1,10v2h3v3h2v-3h3v-2L6,10zM15,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#008577"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z"/>
</vector>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="10dp"
android:topLeftRadius="0dp"/>
<stroke
android:width="1dp"
android:color="#ababb2"/>
<solid android:color="@android:color/background_light"/>
</shape>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="10dp"
android:topRightRadius="0dp"/>
<solid android:color="@color/colorPrimary"/>
</shape>

View File

@ -0,0 +1,75 @@
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#e6e6e6">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_chat_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar_chat_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/MenuStyle">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/ic_launcher"
android:id="@+id/profile_image_chat_activity"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/appbar_username"
android:textSize="18sp"
android:layout_marginLeft="25dp"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:layout_marginStart="25dp" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/message_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/appbar_chat_activity"
android:layout_above="@+id/chat_activity_bottom_container"/>
<RelativeLayout
android:id="@+id/chat_activity_bottom_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FFFFFF"
android:orientation="horizontal"
android:padding="5dp">
<EditText
android:id="@+id/message_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/send_button"
android:background="@android:color/transparent"
android:hint="Type a message..." />
<ImageButton
android:id="@+id/send_button"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="@drawable/ic_send_green_24dp" />
</RelativeLayout>
</RelativeLayout>

View File

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 ChronosX88
~
~ 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 <https://www.gnu.org/licenses/>.
-->
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".views.LoginActivity">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/login_jid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="JabberID"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:imeActionLabel="SIGN IN"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="SIGN IN"
android:textStyle="bold" />
</LinearLayout>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".views.MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/main_fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/main_bottom_navigation"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@android:color/white"
app:menu="@menu/main_bottom_nav_menu"
android:layout_weight="1"
android:layout_gravity="bottom"/>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/add_chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="68dp"
android:layout_marginEnd="16dp"
android:src="@drawable/ic_add_white_24dp"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -0,0 +1,27 @@
<?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="wrap_content"
android:gravity="center_vertical"
android:background="?android:selectableItemBackground"
android:clickable="true">
<TextView
android:id="@+id/chat_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="null"
android:textSize="19sp"
android:layout_gravity="center_vertical"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="17dp"
android:textColor="@android:color/black"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
</LinearLayout>

View File

@ -0,0 +1,10 @@
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/chatlist_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/profile_image"
android:src="@mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/message_item_left_background"
android:layout_toRightOf="@id/profile_image"
android:text="Null"
android:paddingEnd="50dp"
android:layout_marginStart="4dp"
android:layout_marginTop="7dp"
android:id="@+id/message_text"
android:textColor="#000000"
android:textSize="18sp"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message_time"
android:layout_alignBottom="@+id/message_text"
android:layout_alignRight="@+id/message_text"
android:paddingBottom="3dp"
android:paddingRight="4dp"
android:textColor="#000000"
android:text="12:00"/>
</RelativeLayout>
</RelativeLayout>

View File

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/profile_image"
android:src="@mipmap/ic_launcher"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/message_item_right_background"
android:text="Null"
android:layout_toLeftOf="@id/profile_image"
android:layout_marginEnd="4dp"
android:layout_marginTop="7dp"
android:id="@+id/message_text"
android:textSize="18sp"
android:paddingEnd="50dp"
android:textColor="#ffffff"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message_time"
android:layout_alignBottom="@+id/message_text"
android:layout_alignRight="@+id/message_text"
android:paddingBottom="3dp"
android:textColor="#ffffff"
android:paddingRight="4dp"
android:text="12:00"/>
</RelativeLayout>
</RelativeLayout>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2019 ChronosX88
~
~ 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 <https://www.gnu.org/licenses/>.
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_reconnect_network"
app:showAsAction="always"
android:icon="@drawable/ic_autorenew_white_24dp"
android:title="@string/reconnect_network"/>
</menu>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_chats"
android:icon="@drawable/ic_chat_white"
android:title="Чаты"/>
<item
android:id="@+id/action_settings"
android:icon="@drawable/ic_settings_white"
android:title="Настройки" />
</menu>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Influence</string>
<string name="username_saved">Ваше имя пользователя успешно сохранено!</string>
<string name="username_isnt_saved">К сожалению, это имя пользователя занято.</string>
<string name="ok">OK</string>
<string name="cancel">Отмена</string>
<string name="username_settings">Ваше имя пользователя</string>
<string name="username_hint">Имя пользователя</string>
<string name="reconnect_network">Переподключиться к сети</string>
<string name="node_already_running">Узел уже запущен</string>
<string name="input_companion_username">Введите имя пользователя собеседника</string>
</resources>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>

View File

@ -0,0 +1,12 @@
<resources>
<string name="app_name">Influence</string>
<string name="username_saved">Your username saved successfully!</string>
<string name="username_isnt_saved">Sorry, this username is busy.</string>
<string name="ok">OK</string>
<string name="cancel">Cancel</string>
<string name="username_settings">Your username</string>
<string name="username_hint">Username</string>
<string name="reconnect_network">Reconnect to the network</string>
<string name="node_already_running">Node already running</string>
<string name="input_companion_username">Input interlocutor\'s username</string>
</resources>

View File

@ -0,0 +1,43 @@
<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>
<style name="AlertDialogTheme" parent="Base.Theme.AppCompat.Dialog">
<item name="alertDialogStyle">@style/CustomAlertStyle</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:textStyle">normal</item>
<item name="android:textSize">12sp</item>
</style>
<style name="CustomAlertStyle">
<item name="android:bottomBright">@android:color/transparent</item>
<item name="android:bottomDark">@android:color/transparent</item>
<item name="android:bottomMedium">@android:color/transparent</item>
<item name="android:centerBright">@android:color/transparent</item>
<item name="android:centerDark">@android:color/transparent</item>
<item name="android:centerMedium">@android:color/transparent</item>
<item name="android:fullBright">@android:color/transparent</item>
<item name="android:fullDark">@android:color/transparent</item>
<item name="android:topBright">@android:color/transparent</item>
<item name="android:topDark">@android:color/transparent</item>
</style>
<style name="MenuStyle" parent="Theme.AppCompat.Light">
<item name="android:background">@android:color/white</item>
</style>
<style name="NoWindowActionBar" parent="AppTheme">
<item name="windowNoTitle">true</item>
</style>
</resources>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="peerID"
android:title="Мой Peer ID"
android:summary=""/>
<Preference
android:key="username"
android:title="Мой username"
android:summary=""/>
<EditTextPreference
android:key="bootstrapAddress"
android:title="Адрес Bootstrap-ноды"
android:summary="Bootstrap-нода необходима для подключения к сети" />
<CheckBoxPreference
android:key="allowWorkBackground"
android:title="Работать в фоне (not implemented)"
android:summary="Позволять узлу работать в фоне (может повысить потребление трафика и батареи)"/>
<Preference
android:key="exportEncryptionKeys"
android:title="Экспортировать ключи шифрования (not implemented)" />
</PreferenceScreen>

35
build.gradle Normal file
View File

@ -0,0 +1,35 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.30'
repositories {
google()
jcenter()
maven {
url "http://tomp2p.net/dev/mvn/"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "http://tomp2p.net/dev/mvn/"
}
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

18
gradle.properties Normal file
View File

@ -0,0 +1,18 @@
# 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
android.useAndroidX=true
android.enableJetifier=true
android.enableD8=true

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Thu Apr 25 15:51:08 MSK 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip

172
gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# 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
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# 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
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
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" -a "$nonstop" = "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
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored Executable file
View File

@ -0,0 +1,84 @@
@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
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@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=
@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 Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_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=%*
: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
settings.gradle Normal file
View File

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