Genesis
18
.gitignore
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
.DS_Store
|
||||||
|
.Trashes
|
||||||
|
ehthumbs.db
|
||||||
|
Thumbs.db
|
||||||
|
build
|
||||||
|
.cxx
|
||||||
|
/app/release
|
||||||
|
.gradle
|
||||||
|
local.properties
|
||||||
|
.idea/
|
||||||
|
*.apk
|
||||||
|
*.ap_
|
||||||
|
*.dex
|
||||||
|
*.class
|
||||||
|
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.so
|
613
LICENSE
Normal file
@ -0,0 +1,613 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license
|
||||||
|
document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for software
|
||||||
|
and other kinds of works, specifically designed to ensure cooperation with
|
||||||
|
the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take
|
||||||
|
away your freedom to share and change the works. By contrast, our General
|
||||||
|
Public Licenses are intended to guarantee your freedom to share and change
|
||||||
|
all versions of a program--to make sure it remains free software for all its
|
||||||
|
users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our
|
||||||
|
General Public Licenses are designed to make sure that you have the freedom
|
||||||
|
to distribute copies of free software (and charge for them if you wish), that
|
||||||
|
you receive source code or can get it if you want it, that you can change
|
||||||
|
the software or use pieces of it in new free programs, and that you know you
|
||||||
|
can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights with two
|
||||||
|
steps: (1) assert copyright on the software, and (2) offer you this License
|
||||||
|
which gives you legal permission to copy, distribute and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that improvements made
|
||||||
|
in alternate versions of the program, if they receive widespread use, become
|
||||||
|
available for other developers to incorporate. Many developers of free software
|
||||||
|
are heartened and encouraged by the resulting cooperation. However, in the
|
||||||
|
case of software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and letting
|
||||||
|
the public access it on a server without ever releasing its source code to
|
||||||
|
the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to ensure that,
|
||||||
|
in such cases, the modified source code becomes available to the community.
|
||||||
|
It requires the operator of a network server to provide the source code of
|
||||||
|
the modified version running there to the users of that server. Therefore,
|
||||||
|
public use of a modified version, on a publicly accessible server, gives the
|
||||||
|
public access to the source code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and published by
|
||||||
|
Affero, was designed to accomplish similar goals. This is a different license,
|
||||||
|
not a version of the Affero GPL, but Affero has released a new version of
|
||||||
|
the Affero GPL which permits relicensing under this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification
|
||||||
|
follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of works,
|
||||||
|
such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this License.
|
||||||
|
Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals
|
||||||
|
or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work in
|
||||||
|
a fashion requiring copyright permission, other than the making of an exact
|
||||||
|
copy. The resulting work is called a "modified version" of the earlier work
|
||||||
|
or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based on the
|
||||||
|
Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without permission,
|
||||||
|
would make you directly or secondarily liable for infringement under applicable
|
||||||
|
copyright law, except executing it on a computer or modifying a private copy.
|
||||||
|
Propagation includes copying, distribution (with or without modification),
|
||||||
|
making available to the public, and in some countries other activities as
|
||||||
|
well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other parties
|
||||||
|
to make or receive copies. Mere interaction with a user through a computer
|
||||||
|
network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices" to the
|
||||||
|
extent that it includes a convenient and prominently visible feature that
|
||||||
|
(1) displays an appropriate copyright notice, and (2) tells the user that
|
||||||
|
there is no warranty for the work (except to the extent that warranties are
|
||||||
|
provided), that licensees may convey the work under this License, and how
|
||||||
|
to view a copy of this License. If the interface presents a list of user commands
|
||||||
|
or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work for making
|
||||||
|
modifications to it. "Object code" means any non-source form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official standard
|
||||||
|
defined by a recognized standards body, or, in the case of interfaces specified
|
||||||
|
for a particular programming language, one that is widely used among developers
|
||||||
|
working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other than
|
||||||
|
the work as a whole, that (a) is included in the normal form of packaging
|
||||||
|
a Major Component, but which is not part of that Major Component, and (b)
|
||||||
|
serves only to enable use of the work with that Major Component, or to implement
|
||||||
|
a Standard Interface for which an implementation is available to the public
|
||||||
|
in source code form. A "Major Component", in this context, means a major essential
|
||||||
|
component (kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to produce
|
||||||
|
the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all the source
|
||||||
|
code needed to generate, install, and (for an executable work) run the object
|
||||||
|
code and to modify the work, including scripts to control those activities.
|
||||||
|
However, it does not include the work's System Libraries, or general-purpose
|
||||||
|
tools or generally available free programs which are used unmodified in performing
|
||||||
|
those activities but which are not part of the work. For example, Corresponding
|
||||||
|
Source includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically linked
|
||||||
|
subprograms that the work is specifically designed to require, such as by
|
||||||
|
intimate data communication or control flow between those
|
||||||
|
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate
|
||||||
|
automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of copyright
|
||||||
|
on the Program, and are irrevocable provided the stated conditions are met.
|
||||||
|
This License explicitly affirms your unlimited permission to run the unmodified
|
||||||
|
Program. The output from running a covered work is covered by this License
|
||||||
|
only if the output, given its content, constitutes a covered work. This License
|
||||||
|
acknowledges your rights of fair use or other equivalent, as provided by copyright
|
||||||
|
law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without
|
||||||
|
conditions so long as your license otherwise remains in force. You may convey
|
||||||
|
covered works to others for the sole purpose of having them make modifications
|
||||||
|
exclusively for you, or provide you with facilities for running those works,
|
||||||
|
provided that you comply with the terms of this License in conveying all material
|
||||||
|
for which you do not control copyright. Those thus making or running the covered
|
||||||
|
works for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of your copyrighted
|
||||||
|
material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions
|
||||||
|
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological measure
|
||||||
|
under any applicable law fulfilling obligations under article 11 of the WIPO
|
||||||
|
copyright treaty adopted on 20 December 1996, or similar laws prohibiting
|
||||||
|
or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention
|
||||||
|
of technological measures to the extent such circumvention is effected by
|
||||||
|
exercising rights under this License with respect to the covered work, and
|
||||||
|
you disclaim any intention to limit operation or modification of the work
|
||||||
|
as a means of enforcing, against the work's users, your or third parties'
|
||||||
|
legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive
|
||||||
|
it, in any medium, provided that you conspicuously and appropriately publish
|
||||||
|
on each copy an appropriate copyright notice; keep intact all notices stating
|
||||||
|
that this License and any non-permissive terms added in accord with section
|
||||||
|
7 apply to the code; keep intact all notices of the absence of any warranty;
|
||||||
|
and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you
|
||||||
|
may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to produce
|
||||||
|
it from the Program, in the form of source code under the terms of section
|
||||||
|
4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and
|
||||||
|
giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under
|
||||||
|
this License and any conditions added under section 7. This requirement modifies
|
||||||
|
the requirement in section 4 to "keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone
|
||||||
|
who comes into possession of a copy. This License will therefore apply, along
|
||||||
|
with any applicable section 7 additional terms, to the whole of the work,
|
||||||
|
and all its parts, regardless of how they are packaged. This License gives
|
||||||
|
no permission to license the work in any other way, but it does not invalidate
|
||||||
|
such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate
|
||||||
|
Legal Notices; however, if the Program has interactive interfaces that do
|
||||||
|
not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works,
|
||||||
|
which are not by their nature extensions of the covered work, and which are
|
||||||
|
not combined with it such as to form a larger program, in or on a volume of
|
||||||
|
a storage or distribution medium, is called an "aggregate" if the compilation
|
||||||
|
and its resulting copyright are not used to limit the access or legal rights
|
||||||
|
of the compilation's users beyond what the individual works permit. Inclusion
|
||||||
|
of a covered work in an aggregate does not cause this License to apply to
|
||||||
|
the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms of sections
|
||||||
|
4 and 5, provided that you also convey the machine-readable Corresponding
|
||||||
|
Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including
|
||||||
|
a physical distribution medium), accompanied by the Corresponding Source fixed
|
||||||
|
on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including
|
||||||
|
a physical distribution medium), accompanied by a written offer, valid for
|
||||||
|
at least three years and valid for as long as you offer spare parts or customer
|
||||||
|
support for that product model, to give anyone who possesses the object code
|
||||||
|
either (1) a copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical medium customarily
|
||||||
|
used for software interchange, for a price no more than your reasonable cost
|
||||||
|
of physically performing this conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written
|
||||||
|
offer to provide the Corresponding Source. This alternative is allowed only
|
||||||
|
occasionally and noncommercially, and only if you received the object code
|
||||||
|
with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis
|
||||||
|
or for a charge), and offer equivalent access to the Corresponding Source
|
||||||
|
in the same way through the same place at no further charge. You need not
|
||||||
|
require recipients to copy the Corresponding Source along with the object
|
||||||
|
code. If the place to copy the object code is a network server, the Corresponding
|
||||||
|
Source may be on a different server (operated by you or a third party) that
|
||||||
|
supports equivalent copying facilities, provided you maintain clear directions
|
||||||
|
next to the object code saying where to find the Corresponding Source. Regardless
|
||||||
|
of what server hosts the Corresponding Source, you remain obligated to ensure
|
||||||
|
that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform
|
||||||
|
other peers where the object code and Corresponding Source of the work are
|
||||||
|
being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from
|
||||||
|
the Corresponding Source as a System Library, need not be included in conveying
|
||||||
|
the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any tangible
|
||||||
|
personal property which is normally used for personal, family, or household
|
||||||
|
purposes, or (2) anything designed or sold for incorporation into a dwelling.
|
||||||
|
In determining whether a product is a consumer product, doubtful cases shall
|
||||||
|
be resolved in favor of coverage. For a particular product received by a particular
|
||||||
|
user, "normally used" refers to a typical or common use of that class of product,
|
||||||
|
regardless of the status of the particular user or of the way in which the
|
||||||
|
particular user actually uses, or expects or is expected to use, the product.
|
||||||
|
A product is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent the
|
||||||
|
only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods, procedures,
|
||||||
|
authorization keys, or other information required to install and execute modified
|
||||||
|
versions of a covered work in that User Product from a modified version of
|
||||||
|
its Corresponding Source. The information must suffice to ensure that the
|
||||||
|
continued functioning of the modified object code is in no case prevented
|
||||||
|
or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically
|
||||||
|
for use in, a User Product, and the conveying occurs as part of a transaction
|
||||||
|
in which the right of possession and use of the User Product is transferred
|
||||||
|
to the recipient in perpetuity or for a fixed term (regardless of how the
|
||||||
|
transaction is characterized), the Corresponding Source conveyed under this
|
||||||
|
section must be accompanied by the Installation Information. But this requirement
|
||||||
|
does not apply if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has been installed
|
||||||
|
in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement
|
||||||
|
to continue to provide support service, warranty, or updates for a work that
|
||||||
|
has been modified or installed by the recipient, or for the User Product in
|
||||||
|
which it has been modified or installed. Access to a network may be denied
|
||||||
|
when the modification itself materially and adversely affects the operation
|
||||||
|
of the network or violates the rules and protocols for communication across
|
||||||
|
the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord
|
||||||
|
with this section must be in a format that is publicly documented (and with
|
||||||
|
an implementation available to the public in source code form), and must require
|
||||||
|
no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this License
|
||||||
|
by making exceptions from one or more of its conditions. Additional permissions
|
||||||
|
that are applicable to the entire Program shall be treated as though they
|
||||||
|
were included in this License, to the extent that they are valid under applicable
|
||||||
|
law. If additional permissions apply only to part of the Program, that part
|
||||||
|
may be used separately under those permissions, but the entire Program remains
|
||||||
|
governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any
|
||||||
|
additional permissions from that copy, or from any part of it. (Additional
|
||||||
|
permissions may be written to require their own removal in certain cases when
|
||||||
|
you modify the work.) You may place additional permissions on material, added
|
||||||
|
by you to a covered work, for which you have or can give appropriate copyright
|
||||||
|
permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add
|
||||||
|
to a covered work, you may (if authorized by the copyright holders of that
|
||||||
|
material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of
|
||||||
|
sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author
|
||||||
|
attributions in that material or in the Appropriate Legal Notices displayed
|
||||||
|
by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring
|
||||||
|
that modified versions of such material be marked in reasonable ways as different
|
||||||
|
from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors
|
||||||
|
of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names,
|
||||||
|
trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by
|
||||||
|
anyone who conveys the material (or modified versions of it) with contractual
|
||||||
|
assumptions of liability to the recipient, for any liability that these contractual
|
||||||
|
assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further restrictions"
|
||||||
|
within the meaning of section 10. If the Program as you received it, or any
|
||||||
|
part of it, contains a notice stating that it is governed by this License
|
||||||
|
along with a term that is a further restriction, you may remove that term.
|
||||||
|
If a license document contains a further restriction but permits relicensing
|
||||||
|
or conveying under this License, you may add to a covered work material governed
|
||||||
|
by the terms of that license document, provided that the further restriction
|
||||||
|
does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place,
|
||||||
|
in the relevant source files, a statement of the additional terms that apply
|
||||||
|
to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form
|
||||||
|
of a separately written license, or stated as exceptions; the above requirements
|
||||||
|
apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly provided
|
||||||
|
under this License. Any attempt otherwise to propagate or modify it is void,
|
||||||
|
and will automatically terminate your rights under this License (including
|
||||||
|
any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from
|
||||||
|
a particular copyright holder is reinstated (a) provisionally, unless and
|
||||||
|
until the copyright holder explicitly and finally terminates your license,
|
||||||
|
and (b) permanently, if the copyright holder fails to notify you of the violation
|
||||||
|
by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently
|
||||||
|
if the copyright holder notifies you of the violation by some reasonable means,
|
||||||
|
this is the first time you have received notice of violation of this License
|
||||||
|
(for any work) from that copyright holder, and you cure the violation prior
|
||||||
|
to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses
|
||||||
|
of parties who have received copies or rights from you under this License.
|
||||||
|
If your rights have been terminated and not permanently reinstated, you do
|
||||||
|
not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or run a copy
|
||||||
|
of the Program. Ancillary propagation of a covered work occurring solely as
|
||||||
|
a consequence of using peer-to-peer transmission to receive a copy likewise
|
||||||
|
does not require acceptance. However, nothing other than this License grants
|
||||||
|
you permission to propagate or modify any covered work. These actions infringe
|
||||||
|
copyright if you do not accept this License. Therefore, by modifying or propagating
|
||||||
|
a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically receives
|
||||||
|
a license from the original licensors, to run, modify and propagate that work,
|
||||||
|
subject to this License. You are not responsible for enforcing compliance
|
||||||
|
by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an organization,
|
||||||
|
or substantially all assets of one, or subdividing an organization, or merging
|
||||||
|
organizations. If propagation of a covered work results from an entity transaction,
|
||||||
|
each party to that transaction who receives a copy of the work also receives
|
||||||
|
whatever licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the Corresponding
|
||||||
|
Source of the work from the predecessor in interest, if the predecessor has
|
||||||
|
it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights
|
||||||
|
granted or affirmed under this License. For example, you may not impose a
|
||||||
|
license fee, royalty, or other charge for exercise of rights granted under
|
||||||
|
this License, and you may not initiate litigation (including a cross-claim
|
||||||
|
or counterclaim in a lawsuit) alleging that any patent claim is infringed
|
||||||
|
by making, using, selling, offering for sale, or importing the Program or
|
||||||
|
any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this License
|
||||||
|
of the Program or a work on which the Program is based. The work thus licensed
|
||||||
|
is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims owned or controlled
|
||||||
|
by the contributor, whether already acquired or hereafter acquired, that would
|
||||||
|
be infringed by some manner, permitted by this License, of making, using,
|
||||||
|
or selling its contributor version, but do not include claims that would be
|
||||||
|
infringed only as a consequence of further modification of the contributor
|
||||||
|
version. For purposes of this definition, "control" includes the right to
|
||||||
|
grant patent sublicenses in a manner consistent with the requirements of this
|
||||||
|
License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent
|
||||||
|
license under the contributor's essential patent claims, to make, use, sell,
|
||||||
|
offer for sale, import and otherwise run, modify and propagate the contents
|
||||||
|
of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express agreement
|
||||||
|
or commitment, however denominated, not to enforce a patent (such as an express
|
||||||
|
permission to practice a patent or covenant not to s ue for patent infringement).
|
||||||
|
To "grant" such a patent license to a party means to make such an agreement
|
||||||
|
or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the
|
||||||
|
Corresponding Source of the work is not available for anyone to copy, free
|
||||||
|
of charge and under the terms of this License, through a publicly available
|
||||||
|
network server or other readily accessible means, then you must either (1)
|
||||||
|
cause the Corresponding Source to be so available, or (2) arrange to deprive
|
||||||
|
yourself of the benefit of the patent license for this particular work, or
|
||||||
|
(3) arrange, in a manner consistent with the requirements of this License,
|
||||||
|
to extend the patent
|
||||||
|
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have actual
|
||||||
|
knowledge that, but for the patent license, your conveying the covered work
|
||||||
|
in a country, or your recipient's use of the covered work in a country, would
|
||||||
|
infringe one or more identifiable patents in that country that you have reason
|
||||||
|
to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement,
|
||||||
|
you convey, or propagate by procuring conveyance of, a covered work, and grant
|
||||||
|
a patent license to some of the parties receiving the covered work authorizing
|
||||||
|
them to use, propagate, modify or convey a specific copy of the covered work,
|
||||||
|
then the patent license you grant is automatically extended to all recipients
|
||||||
|
of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within the scope
|
||||||
|
of its coverage, prohibits the exercise of, or is conditioned on the non-exercise
|
||||||
|
of one or more of the rights that are specifically granted under this License.
|
||||||
|
You may not convey a covered work if you are a party to an arrangement with
|
||||||
|
a third party that is in the business of distributing software, under which
|
||||||
|
you make payment to the third party based on the extent of your activity of
|
||||||
|
conveying the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory patent
|
||||||
|
license (a) in connection with copies of the covered work conveyed by you
|
||||||
|
(or copies made from those copies), or (b) primarily for and in connection
|
||||||
|
with specific products or compilations that contain the covered work, unless
|
||||||
|
you entered into that arrangement, or that patent license was granted, prior
|
||||||
|
to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied
|
||||||
|
license or other defenses to infringement that may otherwise be available
|
||||||
|
to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise)
|
||||||
|
that contradict the conditions of this License, they do not excuse you from
|
||||||
|
the conditions of this License. If you cannot convey a covered work so as
|
||||||
|
to satisfy simultaneously your obligations under this License and any other
|
||||||
|
pertinent obligations, then as a consequence you may
|
||||||
|
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey the
|
||||||
|
Program, the only way you could satisfy both those terms and this License
|
||||||
|
would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the Program,
|
||||||
|
your modified version must prominently offer all users interacting with it
|
||||||
|
remotely through a computer network (if your version supports such interaction)
|
||||||
|
an opportunity to receive the Corresponding Source of your version by providing
|
||||||
|
access to the Corresponding Source from a network server at no charge, through
|
||||||
|
some standard or customary means of facilitating copying of software. This
|
||||||
|
Corresponding Source shall include the Corresponding Source for any work covered
|
||||||
|
by version 3 of the GNU General Public License that is incorporated pursuant
|
||||||
|
to the following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have permission to
|
||||||
|
link or combine any covered work with a work licensed under version 3 of the
|
||||||
|
GNU General Public License into a single combined work, and to convey the
|
||||||
|
resulting work. The terms of this License will continue to apply to the part
|
||||||
|
which is the covered work, but the work with which it is combined will remain
|
||||||
|
governed by version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the
|
||||||
|
GNU Affero General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to address
|
||||||
|
new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies
|
||||||
|
that a certain numbered version of the GNU Affero General Public License "or
|
||||||
|
any later version" applies to it, you have the option of following the terms
|
||||||
|
and conditions either of that numbered version or of any later version published
|
||||||
|
by the Free Software Foundation. If the Program does not specify a version
|
||||||
|
number of the GNU Affero General Public License, you may choose any version
|
||||||
|
ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of
|
||||||
|
the GNU Affero General Public License can be used, that proxy's public statement
|
||||||
|
of acceptance of a version permanently authorizes you to choose that version
|
||||||
|
for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However,
|
||||||
|
no additional obligations are imposed on any author or copyright holder as
|
||||||
|
a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
|
||||||
|
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||||
|
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
|
||||||
|
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||||
|
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||||
|
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM
|
||||||
|
PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
|
||||||
|
CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
|
||||||
|
ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM
|
||||||
|
AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
|
||||||
|
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO
|
||||||
|
USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
|
||||||
|
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
|
||||||
|
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
|
||||||
|
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot
|
||||||
|
be given local legal effect according to their terms, reviewing courts shall
|
||||||
|
apply local law that most closely approximates an absolute waiver of all civil
|
||||||
|
liability in connection with the Program, unless a warranty or assumption
|
||||||
|
of liability accompanies a copy of the Program in return for a fee. END OF
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible
|
||||||
|
use to the public, the best way to achieve this is to make it free software
|
||||||
|
which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach
|
||||||
|
them to the start of each source file to most effectively state the exclusion
|
||||||
|
of warranty; and each file should have at least the "copyright" line and a
|
||||||
|
pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under
|
||||||
|
the terms of the GNU Affero General Public License as published by the Free
|
||||||
|
Software Foundation, either version 3 of the License, or (at your option)
|
||||||
|
any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||||
|
details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License along
|
||||||
|
with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer network,
|
||||||
|
you should also make sure that it provides a way for users to get its source.
|
||||||
|
For example, if your program is a web application, its interface could display
|
||||||
|
a "Source" link that leads users to an archive of the code. There are many
|
||||||
|
ways you could offer source, and different solutions will be better for different
|
||||||
|
programs; see section 13 for the specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary. For
|
||||||
|
more information on this, and how to apply and follow the GNU AGPL, see <https://www.gnu.org/licenses/>.
|
64
README.md
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
# AIRA Android
|
||||||
|
AIRA is peer-to-peer encrypted communication tool for local networks built on the [PSEC protocol](https://forge.chapril.org/hardcoresushi/PSEC). It allows to securely send text messages and files without any server or Internet access.
|
||||||
|
|
||||||
|
Here is the Android version. You can find the original AIRA desktop version [here](https://forge.chapril.org/hardcoresushi/AIRA).
|
||||||
|
|
||||||
|
# Disclaimer
|
||||||
|
AIRA is still under developement and is not ready for production usage yet. Not all features have been implemented and bugs are expected. Neither the code or the PSEC protocol received any security audit and therefore shouldn't be considered fully secure. AIRA is provided "as is", without any warranty of any kind.
|
||||||
|
|
||||||
|
# Features
|
||||||
|
- End-to-End encryption using the [PSEC protocol](https://forge.chapril.org/hardcoresushi/PSEC)
|
||||||
|
- Automatic peer discovery using mDNS
|
||||||
|
- Manual peer connection
|
||||||
|
- File transferts
|
||||||
|
- Notifications
|
||||||
|
- Encrypted database
|
||||||
|
- Contact verification
|
||||||
|
- IPv4/v6 compatibility
|
||||||
|
- Free/Libre and Open Source
|
||||||
|
|
||||||
|
# Build
|
||||||
|
### Install Rust
|
||||||
|
AIRA android uses some code from the desktop version which is written in Rust. Therefore, you need to compile this Rust code first.
|
||||||
|
```
|
||||||
|
curl --proto '=https' --tlsv1.3 -sSf https://sh.rustup.rs | sh
|
||||||
|
rustup target add aarch64-linux-android armv7-linux-androideabi
|
||||||
|
```
|
||||||
|
### Install NDK
|
||||||
|
The Rust code uses a crate called "rusqlite" to store data in SQLite databases. This crates uses the original SQLite3 library written in C. Therefore, to compile it you need the Android NDK. You can find instructions to install the NDK here: https://developer.android.com/ndk/guides
|
||||||
|
|
||||||
|
Once installed, you need to define the $ANDROID_NDK_HOME environment variable (if not already set):
|
||||||
|
```
|
||||||
|
export ANDROID_NDK_HOME=/home/<user>/Android/SDK/ndk/<NDK version>"
|
||||||
|
```
|
||||||
|
### Download AIRA
|
||||||
|
```
|
||||||
|
git clone --depth=1 https://forge.chapril.org/hardcoresushi/AIRA-android.git && cd AIRA-android
|
||||||
|
```
|
||||||
|
### Verify commit
|
||||||
|
```
|
||||||
|
git verify-commit HEAD
|
||||||
|
```
|
||||||
|
### Build AIRA Rust code
|
||||||
|
```
|
||||||
|
cd app/src/main/native
|
||||||
|
./build.sh
|
||||||
|
```
|
||||||
|
### Build final APK
|
||||||
|
If you have AndroidStudio installed, you can just open the project directory and then start the build process. Otherwise, you can use Gradle from the command line:
|
||||||
|
|
||||||
|
Generate a signed APK with your keystore:
|
||||||
|
```
|
||||||
|
# From the project root directory:
|
||||||
|
./gradlew assembleRelease -Pandroid.injected.signing.store.file=<KEYFILE> -Pandroid.injected.signing.store.password=<STORE_PASSWORD> -Pandroid.injected.signing.key.alias=<KEY_ALIAS> -Pandroid.injected.signing.key.password=<KEY_PASSWORD>
|
||||||
|
```
|
||||||
|
Generate an unsigned APK:
|
||||||
|
```
|
||||||
|
./gradlew assembleRelease
|
||||||
|
```
|
||||||
|
Once completed, the APKs will be located under `app/build/outputs/apk/release/`.
|
||||||
|
|
||||||
|
If you generate an unsigned APK you won't be able to install it as-is on your device. You will need to force install it with ADB:
|
||||||
|
```
|
||||||
|
adb install app-release-unsigned.apk
|
||||||
|
```
|
1
app/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/build
|
54
app/build.gradle
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
plugins {
|
||||||
|
id 'com.android.application'
|
||||||
|
id 'kotlin-android'
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
compileSdkVersion 30
|
||||||
|
buildToolsVersion "30.0.3"
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId "sushi.hardcore.aira"
|
||||||
|
minSdkVersion 19
|
||||||
|
targetSdkVersion 30
|
||||||
|
versionCode 1
|
||||||
|
versionName "0.1"
|
||||||
|
|
||||||
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
viewBinding true
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
minifyEnabled false
|
||||||
|
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility JavaVersion.VERSION_1_8
|
||||||
|
}
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = '1.8'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||||
|
implementation 'androidx.core:core-ktx:1.3.2'
|
||||||
|
implementation 'androidx.appcompat:appcompat:1.2.0'
|
||||||
|
implementation "androidx.fragment:fragment-ktx:1.3.2"
|
||||||
|
implementation "androidx.preference:preference-ktx:1.1.1"
|
||||||
|
implementation 'com.google.android.material:material:1.3.0'
|
||||||
|
//implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
|
||||||
|
//implementation 'androidx.legacy:legacy-support-v4:1.0.0'
|
||||||
|
//testImplementation 'junit:junit:4.13.1'
|
||||||
|
|
||||||
|
implementation 'net.i2p.crypto:eddsa:0.3.0'
|
||||||
|
implementation "org.whispersystems:curve25519-android:0.5.0"
|
||||||
|
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
|
||||||
|
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
|
||||||
|
}
|
21
app/proguard-rules.pro
vendored
Normal 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
|
@ -0,0 +1,24 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instrumented test, which will execute on an Android device.
|
||||||
|
*
|
||||||
|
* See [testing documentation](http://d.android.com/tools/testing).
|
||||||
|
*/
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class ExampleInstrumentedTest {
|
||||||
|
@Test
|
||||||
|
fun useAppContext() {
|
||||||
|
// Context of the app under test.
|
||||||
|
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
assertEquals("sushi.hardcore.aira", appContext.packageName)
|
||||||
|
}
|
||||||
|
}
|
49
app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
<?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="sushi.hardcore.aira">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||||
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove"/>
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.AIRA"
|
||||||
|
android:allowBackup="true">
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".background_service.AIRAService"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="false"/>
|
||||||
|
|
||||||
|
<receiver android:name=".background_service.NotificationBroadcastReceiver" android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="mark_as_read"/>
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".ChatActivity"
|
||||||
|
android:windowSoftInputMode="adjustResize"/>
|
||||||
|
<activity android:name=".MainActivity">
|
||||||
|
<intent-filter android:label="@string/share_label">
|
||||||
|
<action android:name="android.intent.action.SEND"/>
|
||||||
|
<category android:name="android.intent.category.DEFAULT"/>
|
||||||
|
<data android:mimeType="*/*"/>
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<activity android:name=".LoginActivity">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN"/>
|
||||||
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<activity android:name=".SettingsActivity"/>
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
24
app/src/main/java/sushi/hardcore/aira/AIRADatabase.kt
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import sushi.hardcore.aira.background_service.Contact
|
||||||
|
|
||||||
|
object AIRADatabase {
|
||||||
|
external fun isIdentityProtected(databaseFolder: String): Boolean
|
||||||
|
external fun loadIdentity(databaseFolder: String, password: ByteArray?): Boolean
|
||||||
|
external fun addContact(name: String, publicKey: ByteArray): Contact?
|
||||||
|
external fun removeContact(uuid: String): Boolean
|
||||||
|
external fun loadContacts(): ArrayList<Contact>?
|
||||||
|
external fun setVerified(uuid: String): Boolean
|
||||||
|
external fun setContactSeen(contactUuid: String, seen: Boolean): Boolean
|
||||||
|
external fun changeContactName(contactUuid: String, newName: String): Boolean
|
||||||
|
external fun storeMsg(contactUuid: String, outgoing: Boolean, data: ByteArray): Boolean
|
||||||
|
external fun storeFile(contactUuid: String?, data: ByteArray): ByteArray?
|
||||||
|
external fun loadMsgs(uuid: String, offset: Int, count: Int): ArrayList<ChatItem>?
|
||||||
|
external fun loadFile(rawUuid: ByteArray): ByteArray?
|
||||||
|
external fun deleteConversation(contactUuid: String): Boolean
|
||||||
|
external fun clearTemporaryFiles(): Int
|
||||||
|
external fun getIdentityPublicKey(): ByteArray
|
||||||
|
external fun getIdentityFingerprint(): String
|
||||||
|
external fun changeName(newName: String): Boolean
|
||||||
|
external fun changePassword(databaseFolder: String, oldPassword: ByteArray?, newPassword: ByteArray?): Boolean
|
||||||
|
}
|
345
app/src/main/java/sushi/hardcore/aira/ChatActivity.kt
Normal file
@ -0,0 +1,345 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.*
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import android.view.Menu
|
||||||
|
import android.view.MenuItem
|
||||||
|
import android.view.View
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.constraintlayout.widget.ConstraintLayout
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import sushi.hardcore.aira.adapters.ChatAdapter
|
||||||
|
import sushi.hardcore.aira.background_service.AIRAService
|
||||||
|
import sushi.hardcore.aira.background_service.Protocol
|
||||||
|
import sushi.hardcore.aira.background_service.ReceiveFileTransfer
|
||||||
|
import sushi.hardcore.aira.databinding.ActivityChatBinding
|
||||||
|
import sushi.hardcore.aira.utils.FileUtils
|
||||||
|
import sushi.hardcore.aira.utils.StringUtils
|
||||||
|
import java.util.*
|
||||||
|
|
||||||
|
class ChatActivity : AppCompatActivity() {
|
||||||
|
private external fun generateFingerprint(publicKey: ByteArray): String
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityChatBinding
|
||||||
|
private var sessionId = -1
|
||||||
|
private lateinit var sessionName: String
|
||||||
|
private lateinit var airaService: AIRAService
|
||||||
|
private lateinit var chatAdapter: ChatAdapter
|
||||||
|
private var lastLoadedMessageOffset = 0
|
||||||
|
private var isActivityInForeground = false
|
||||||
|
private val filePicker = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
contentResolver.query(uri, null, null, null, null)?.let { cursor ->
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
contentResolver.openInputStream(uri)?.let { inputStream ->
|
||||||
|
val fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
|
||||||
|
val fileSize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE))
|
||||||
|
airaService.sendFileTo(sessionId, fileName, fileSize, inputStream)?.let { msg ->
|
||||||
|
chatAdapter.newMessage(ChatItem(true, msg))
|
||||||
|
}
|
||||||
|
if (airaService.contacts.contains(sessionId)) {
|
||||||
|
lastLoadedMessageOffset += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityChatBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
||||||
|
|
||||||
|
sessionId = intent.getIntExtra("sessionId", -1)
|
||||||
|
if (sessionId != -1) {
|
||||||
|
intent.getStringExtra("sessionName")?.let { name ->
|
||||||
|
sessionName = name
|
||||||
|
title = name
|
||||||
|
|
||||||
|
chatAdapter = ChatAdapter(this@ChatActivity, ::onClickSaveFile)
|
||||||
|
binding.recyclerChat.apply {
|
||||||
|
adapter = chatAdapter
|
||||||
|
layoutManager = LinearLayoutManager(this@ChatActivity, LinearLayoutManager.VERTICAL, false)
|
||||||
|
addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
|
fun loadMsgsIfNeeded(recyclerView: RecyclerView) {
|
||||||
|
if (!recyclerView.canScrollVertically(-1) && ::airaService.isInitialized) {
|
||||||
|
airaService.contacts[sessionId]?.let { contact ->
|
||||||
|
loadMsgs(contact.uuid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||||
|
loadMsgsIfNeeded(recyclerView)
|
||||||
|
}
|
||||||
|
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
|
||||||
|
loadMsgsIfNeeded(recyclerView)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Intent(this, AIRAService::class.java).also { serviceIntent ->
|
||||||
|
bindService(serviceIntent, object : ServiceConnection {
|
||||||
|
override fun onServiceConnected(name: ComponentName?, service: IBinder) {
|
||||||
|
val binder = service as AIRAService.AIRABinder
|
||||||
|
airaService = binder.getService()
|
||||||
|
|
||||||
|
airaService.contacts[sessionId]?.let { contact ->
|
||||||
|
displayIconTrustLevel(true, contact.verified)
|
||||||
|
loadMsgs(contact.uuid)
|
||||||
|
}
|
||||||
|
airaService.receiveFileTransfers[sessionId]?.let {
|
||||||
|
if (it.shouldAsk) {
|
||||||
|
it.ask(this@ChatActivity, sessionName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
airaService.savedMsgs[sessionId]?.let {
|
||||||
|
for (chatItem in it.asReversed()) {
|
||||||
|
chatAdapter.newLoadedMessage(chatItem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount)
|
||||||
|
val onConnected = {
|
||||||
|
findViewById<ConstraintLayout>(R.id.bottom_panel).visibility = View.VISIBLE
|
||||||
|
binding.buttonSend.setOnClickListener {
|
||||||
|
val msg = binding.editMessage.text.toString()
|
||||||
|
airaService.sendTo(sessionId, Protocol.newMessage(msg))
|
||||||
|
binding.editMessage.text.clear()
|
||||||
|
chatAdapter.newMessage(ChatItem(true, Protocol.newMessage(msg)))
|
||||||
|
if (airaService.contacts.contains(sessionId)) {
|
||||||
|
lastLoadedMessageOffset += 1
|
||||||
|
}
|
||||||
|
binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount)
|
||||||
|
}
|
||||||
|
binding.buttonAttach.setOnClickListener {
|
||||||
|
filePicker.launch("*/*")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
airaService.uiCallbacks = object : AIRAService.UiCallbacks {
|
||||||
|
override fun onNewSession(sessionId: Int, ip: String) {
|
||||||
|
if (this@ChatActivity.sessionId == sessionId) {
|
||||||
|
runOnUiThread {
|
||||||
|
onConnected()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onSessionDisconnect(sessionId: Int) {
|
||||||
|
if (this@ChatActivity.sessionId == sessionId) {
|
||||||
|
runOnUiThread {
|
||||||
|
findViewById<ConstraintLayout>(R.id.bottom_panel).visibility = View.GONE
|
||||||
|
binding.buttonSend.setOnClickListener(null)
|
||||||
|
binding.buttonAttach.setOnClickListener(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onNameTold(sessionId: Int, name: String) {
|
||||||
|
if (this@ChatActivity.sessionId == sessionId) {
|
||||||
|
runOnUiThread {
|
||||||
|
sessionName = name
|
||||||
|
title = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onNewMessage(sessionId: Int, data: ByteArray): Boolean {
|
||||||
|
return if (this@ChatActivity.sessionId == sessionId) {
|
||||||
|
runOnUiThread {
|
||||||
|
chatAdapter.newMessage(ChatItem(false, data))
|
||||||
|
binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount)
|
||||||
|
}
|
||||||
|
if (airaService.contacts.contains(sessionId)) {
|
||||||
|
lastLoadedMessageOffset += 1
|
||||||
|
}
|
||||||
|
isActivityInForeground
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean {
|
||||||
|
return if (this@ChatActivity.sessionId == sessionId) {
|
||||||
|
runOnUiThread {
|
||||||
|
receiveFileTransfer.ask(this@ChatActivity, name)
|
||||||
|
}
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
airaService.isAppInBackground = false
|
||||||
|
if (airaService.isOnline(sessionId)) {
|
||||||
|
onConnected()
|
||||||
|
}
|
||||||
|
airaService.setSeen(sessionId, true)
|
||||||
|
}
|
||||||
|
override fun onServiceDisconnected(name: ComponentName?) {}
|
||||||
|
}, Context.BIND_AUTO_CREATE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun displayIconTrustLevel(isContact: Boolean, isVerified: Boolean) {
|
||||||
|
when {
|
||||||
|
isVerified -> {
|
||||||
|
binding.imageTrustLevel.setImageResource(R.drawable.ic_verified)
|
||||||
|
}
|
||||||
|
isContact -> {
|
||||||
|
binding.imageTrustLevel.setImageDrawable(null)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
binding.imageTrustLevel.setImageResource(R.drawable.ic_warning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadMsgs(contactUuid: String) {
|
||||||
|
AIRADatabase.loadMsgs(contactUuid, lastLoadedMessageOffset, Constants.MSG_LOADING_COUNT)?.let {
|
||||||
|
for (chatItem in it.asReversed()) {
|
||||||
|
chatAdapter.newLoadedMessage(chatItem)
|
||||||
|
}
|
||||||
|
lastLoadedMessageOffset += it.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateOptionsMenu(menu: Menu): Boolean {
|
||||||
|
menuInflater.inflate(R.menu.chat_activity, menu)
|
||||||
|
val contact = airaService.contacts[sessionId]
|
||||||
|
if (contact == null){
|
||||||
|
menu.findItem(R.id.delete_conversation).isVisible = false
|
||||||
|
menu.findItem(R.id.set_as_contact).isVisible = true
|
||||||
|
menu.findItem(R.id.remove_contact).isVisible = false
|
||||||
|
menu.findItem(R.id.verify).isVisible = false
|
||||||
|
} else {
|
||||||
|
menu.findItem(R.id.delete_conversation).isVisible = true
|
||||||
|
menu.findItem(R.id.set_as_contact).isVisible = false
|
||||||
|
menu.findItem(R.id.remove_contact).isVisible = true
|
||||||
|
menu.findItem(R.id.verify).isVisible = !contact.verified
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||||
|
return when (item.itemId) {
|
||||||
|
android.R.id.home -> {
|
||||||
|
finish()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.session_info -> {
|
||||||
|
val contact = airaService.contacts[sessionId]
|
||||||
|
val session = airaService.sessions[sessionId]
|
||||||
|
val publicKey = contact?.publicKey ?: session?.peerPublicKey
|
||||||
|
val dialogView = layoutInflater.inflate(R.layout.dialog_info, null)
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_fingerprint).text = StringUtils.beautifyFingerprint(generateFingerprint(publicKey!!))
|
||||||
|
if (session == null) {
|
||||||
|
dialogView.findViewById<LinearLayout>(R.id.online_fields).visibility = View.GONE
|
||||||
|
} else {
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_ip).text = session.ip
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_outgoing).text = getString(if (session.outgoing) {
|
||||||
|
R.string.outgoing
|
||||||
|
} else {
|
||||||
|
R.string.incoming
|
||||||
|
})
|
||||||
|
}
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(sessionName)
|
||||||
|
.setView(dialogView)
|
||||||
|
.setPositiveButton(R.string.ok, null)
|
||||||
|
.show()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.set_as_contact -> {
|
||||||
|
if (airaService.setAsContact(sessionId, sessionName)) {
|
||||||
|
invalidateOptionsMenu()
|
||||||
|
displayIconTrustLevel(true, false)
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.remove_contact -> {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.warning)
|
||||||
|
.setMessage(R.string.ask_remove_contact)
|
||||||
|
.setPositiveButton(R.string.delete) { _, _ ->
|
||||||
|
if (airaService.removeContact(sessionId)) {
|
||||||
|
invalidateOptionsMenu()
|
||||||
|
displayIconTrustLevel(false, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.verify -> {
|
||||||
|
airaService.contacts[sessionId]?.let { contact ->
|
||||||
|
val localFingerprint = StringUtils.beautifyFingerprint(AIRADatabase.getIdentityFingerprint())
|
||||||
|
val peerFingerprint = StringUtils.beautifyFingerprint(generateFingerprint(contact.publicKey))
|
||||||
|
val dialogView = layoutInflater.inflate(R.layout.dialog_fingerprints, null)
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_local_fingerprint).text = localFingerprint
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_peer_fingerprint).text = peerFingerprint
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.verifying_contact)
|
||||||
|
.setView(dialogView)
|
||||||
|
.setPositiveButton(R.string.they_match) { _, _ ->
|
||||||
|
if (airaService.setVerified(sessionId)) {
|
||||||
|
invalidateOptionsMenu()
|
||||||
|
displayIconTrustLevel(true, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.delete_conversation -> {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.warning)
|
||||||
|
.setMessage(R.string.ask_delete_conversation)
|
||||||
|
.setPositiveButton(R.string.delete) { _, _ ->
|
||||||
|
if (airaService.deleteConversation(sessionId)) {
|
||||||
|
chatAdapter.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> super.onOptionsItemSelected(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
isActivityInForeground = true
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
airaService.setSeen(sessionId, true)
|
||||||
|
airaService.isAppInBackground = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
isActivityInForeground = false
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
airaService.isAppInBackground = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onClickSaveFile(fileName: String, rawUuid: ByteArray) {
|
||||||
|
FileUtils.openFileForDownload(this, fileName)?.apply {
|
||||||
|
AIRADatabase.loadFile(rawUuid)?.let {
|
||||||
|
write(it)
|
||||||
|
Toast.makeText(this@ChatActivity, R.string.file_saved, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
11
app/src/main/java/sushi/hardcore/aira/ChatItem.kt
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import sushi.hardcore.aira.background_service.Protocol
|
||||||
|
|
||||||
|
class ChatItem(val outgoing: Boolean, val data: ByteArray) {
|
||||||
|
companion object {
|
||||||
|
const val MESSAGE = 0
|
||||||
|
const val FILE = 1
|
||||||
|
}
|
||||||
|
val itemType = if (data[0] == Protocol.MESSAGE) { MESSAGE } else { FILE }
|
||||||
|
}
|
22
app/src/main/java/sushi/hardcore/aira/Constants.kt
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object Constants {
|
||||||
|
const val port = 7530
|
||||||
|
const val mDNSServiceName = "AIRA Node"
|
||||||
|
const val mDNSServiceType = "_aira._tcp"
|
||||||
|
const val fileSizeLimit = 32760000
|
||||||
|
const val MSG_LOADING_COUNT = 20
|
||||||
|
const val FILE_CHUNK_SIZE = 1023996
|
||||||
|
private const val databaseName = "AIRA.db"
|
||||||
|
|
||||||
|
fun getDatabaseFolder(context: Context): String {
|
||||||
|
return getDatabasePath(context).parent!!
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getDatabasePath(context: Context): File {
|
||||||
|
return context.getDatabasePath(databaseName)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.Toast
|
||||||
|
import sushi.hardcore.aira.databinding.FragmentCreateIdentityBinding
|
||||||
|
|
||||||
|
class CreateIdentityFragment : Fragment() {
|
||||||
|
private external fun createNewIdentity(databaseFolder: String, name: String, password: ByteArray?): Boolean
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun newInstance(): CreateIdentityFragment {
|
||||||
|
return CreateIdentityFragment()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: FragmentCreateIdentityBinding
|
||||||
|
|
||||||
|
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
|
||||||
|
binding = FragmentCreateIdentityBinding.inflate(inflater, container, false)
|
||||||
|
return binding.root
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
binding.checkboxEnablePassword.setOnCheckedChangeListener { _, isChecked ->
|
||||||
|
if (isChecked) {
|
||||||
|
binding.editPassword.visibility = View.VISIBLE
|
||||||
|
binding.editPasswordConfirm.visibility = View.VISIBLE
|
||||||
|
} else {
|
||||||
|
binding.editPassword.visibility = View.GONE
|
||||||
|
binding.editPasswordConfirm.visibility = View.GONE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.buttonCreate.setOnClickListener {
|
||||||
|
val identityName = binding.editName.text.toString()
|
||||||
|
val password = binding.editPassword.text.toString().toByteArray()
|
||||||
|
if (password.isEmpty()) {
|
||||||
|
createIdentity(identityName, null)
|
||||||
|
} else {
|
||||||
|
val passwordConfirm = binding.editPasswordConfirm.text.toString().toByteArray()
|
||||||
|
if (password.contentEquals(passwordConfirm)) {
|
||||||
|
createIdentity(identityName, password)
|
||||||
|
} else {
|
||||||
|
Toast.makeText(activity, R.string.password_mismatch, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
passwordConfirm.fill(0)
|
||||||
|
password.fill(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createIdentity(identityName: String, password: ByteArray?) {
|
||||||
|
val databaseFolder = Constants.getDatabaseFolder(requireContext())
|
||||||
|
if (createNewIdentity(
|
||||||
|
databaseFolder,
|
||||||
|
identityName,
|
||||||
|
password
|
||||||
|
)) {
|
||||||
|
val intent = Intent(activity, MainActivity::class.java)
|
||||||
|
intent.putExtra("identityName", identityName)
|
||||||
|
startActivity(intent)
|
||||||
|
activity?.finish()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(activity, R.string.identity_create_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
60
app/src/main/java/sushi/hardcore/aira/LoginActivity.kt
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import sushi.hardcore.aira.background_service.AIRAService
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
class LoginActivity : AppCompatActivity() {
|
||||||
|
private external fun getIdentityName(databaseFolder: String): String?
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
init {
|
||||||
|
System.loadLibrary("aira")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(R.layout.activity_login)
|
||||||
|
val databaseFolder = Constants.getDatabaseFolder(this)
|
||||||
|
val dbFile = File(databaseFolder)
|
||||||
|
if (!dbFile.isDirectory) {
|
||||||
|
if (!dbFile.mkdir()) {
|
||||||
|
Toast.makeText(this, R.string.db_mkdir_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val isProtected = AIRADatabase.isIdentityProtected(databaseFolder)
|
||||||
|
val name = getIdentityName(databaseFolder)
|
||||||
|
if (AIRAService.isServiceRunning) {
|
||||||
|
startActivity(Intent(this, MainActivity::class.java))
|
||||||
|
finish()
|
||||||
|
} else if (name != null && !isProtected) {
|
||||||
|
if (AIRADatabase.loadIdentity(databaseFolder, null)) {
|
||||||
|
AIRADatabase.clearTemporaryFiles()
|
||||||
|
startMainActivity(name)
|
||||||
|
} else {
|
||||||
|
Toast.makeText(this, R.string.identity_load_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
supportFragmentManager.beginTransaction()
|
||||||
|
.add(
|
||||||
|
R.id.fragment_container, if (name == null) {
|
||||||
|
CreateIdentityFragment.newInstance()
|
||||||
|
} else {
|
||||||
|
LoginFragment.newInstance(name)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.commit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startMainActivity(identityName: String?) {
|
||||||
|
val intent = Intent(this, MainActivity::class.java)
|
||||||
|
intent.putExtra("identityName", identityName)
|
||||||
|
startActivity(intent)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
50
app/src/main/java/sushi/hardcore/aira/LoginFragment.kt
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import sushi.hardcore.aira.databinding.FragmentLoginBinding
|
||||||
|
import sushi.hardcore.aira.widgets.TextAvatar
|
||||||
|
|
||||||
|
class LoginFragment : Fragment() {
|
||||||
|
companion object {
|
||||||
|
private const val NAME_ARG = "identityName"
|
||||||
|
fun newInstance(name: String): LoginFragment {
|
||||||
|
return LoginFragment().apply {
|
||||||
|
arguments = Bundle().apply { putString(NAME_ARG, name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: FragmentLoginBinding
|
||||||
|
|
||||||
|
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
|
||||||
|
binding = FragmentLoginBinding.inflate(inflater, container, false)
|
||||||
|
return binding.root
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
arguments?.let { bundle ->
|
||||||
|
bundle.getString(NAME_ARG)?.let { name ->
|
||||||
|
view.findViewById<TextAvatar>(R.id.text_avatar).setLetterFrom(name)
|
||||||
|
view.findViewById<TextView>(R.id.text_identity_name).text = name
|
||||||
|
binding.buttonLogin.setOnClickListener {
|
||||||
|
if (AIRADatabase.loadIdentity(Constants.getDatabaseFolder(requireContext()), binding.editPassword.text.toString().toByteArray())) {
|
||||||
|
AIRADatabase.clearTemporaryFiles()
|
||||||
|
val intent = Intent(activity, MainActivity::class.java)
|
||||||
|
intent.putExtra("identityName", name)
|
||||||
|
startActivity(intent)
|
||||||
|
activity?.finish()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(activity, R.string.identity_load_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
250
app/src/main/java/sushi/hardcore/aira/MainActivity.kt
Normal file
@ -0,0 +1,250 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.ServiceConnection
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import android.view.Menu
|
||||||
|
import android.view.MenuItem
|
||||||
|
import android.widget.AdapterView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import sushi.hardcore.aira.adapters.Session
|
||||||
|
import sushi.hardcore.aira.adapters.SessionAdapter
|
||||||
|
import sushi.hardcore.aira.background_service.AIRAService
|
||||||
|
import sushi.hardcore.aira.background_service.ReceiveFileTransfer
|
||||||
|
import sushi.hardcore.aira.databinding.ActivityMainBinding
|
||||||
|
import sushi.hardcore.aira.utils.FileUtils
|
||||||
|
|
||||||
|
class MainActivity : AppCompatActivity() {
|
||||||
|
private lateinit var binding: ActivityMainBinding
|
||||||
|
private lateinit var airaService: AIRAService
|
||||||
|
private lateinit var onlineSessionAdapter: SessionAdapter
|
||||||
|
private lateinit var offlineSessionAdapter: SessionAdapter
|
||||||
|
private val uiCallbacks = object : AIRAService.UiCallbacks {
|
||||||
|
override fun onNewSession(sessionId: Int, ip: String) {
|
||||||
|
runOnUiThread {
|
||||||
|
handleNewSession(sessionId, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onSessionDisconnect(sessionId: Int) {
|
||||||
|
runOnUiThread {
|
||||||
|
onlineSessionAdapter.remove(sessionId)?.let { session ->
|
||||||
|
if (session.isContact) {
|
||||||
|
offlineSessionAdapter.add(session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onNameTold(sessionId: Int, name: String) {
|
||||||
|
runOnUiThread {
|
||||||
|
onlineSessionAdapter.setName(sessionId, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onNewMessage(sessionId: Int, data: ByteArray): Boolean {
|
||||||
|
runOnUiThread {
|
||||||
|
onlineSessionAdapter.setSeen(sessionId, false)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean {
|
||||||
|
runOnUiThread {
|
||||||
|
receiveFileTransfer.ask(this@MainActivity, name)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityMainBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
|
||||||
|
val identityName = intent.getStringExtra("identityName")
|
||||||
|
identityName?.let { title = it }
|
||||||
|
|
||||||
|
val openedToShareFile = intent.action == Intent.ACTION_SEND
|
||||||
|
|
||||||
|
onlineSessionAdapter = SessionAdapter(this)
|
||||||
|
binding.onlineSessions.apply {
|
||||||
|
adapter = onlineSessionAdapter
|
||||||
|
onItemClickListener = if (openedToShareFile) {
|
||||||
|
AdapterView.OnItemClickListener { _, _, position, _ ->
|
||||||
|
askShareFileTo(onlineSessionAdapter.getItem(position))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AdapterView.OnItemClickListener { _, _, position, _ ->
|
||||||
|
launchChatActivity(onlineSessionAdapter.getItem(position))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offlineSessionAdapter = SessionAdapter(this)
|
||||||
|
binding.offlineSessions.apply {
|
||||||
|
adapter = offlineSessionAdapter
|
||||||
|
onItemClickListener = if (openedToShareFile) {
|
||||||
|
AdapterView.OnItemClickListener { _, _, position, _ ->
|
||||||
|
askShareFileTo(offlineSessionAdapter.getItem(position))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AdapterView.OnItemClickListener { _, _, position, _ ->
|
||||||
|
launchChatActivity(offlineSessionAdapter.getItem(position))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Intent(this, AIRAService::class.java).also { serviceIntent ->
|
||||||
|
bindService(serviceIntent, object : ServiceConnection {
|
||||||
|
override fun onServiceConnected(name: ComponentName?, service: IBinder) {
|
||||||
|
val binder = service as AIRAService.AIRABinder
|
||||||
|
airaService = binder.getService()
|
||||||
|
airaService.uiCallbacks = uiCallbacks
|
||||||
|
airaService.isAppInBackground = false
|
||||||
|
loadContacts()
|
||||||
|
if (AIRAService.isServiceRunning) {
|
||||||
|
title = airaService.identityName
|
||||||
|
loadSessions()
|
||||||
|
} else {
|
||||||
|
airaService.identityName = identityName
|
||||||
|
startService(serviceIntent)
|
||||||
|
}
|
||||||
|
binding.refresher.setOnRefreshListener {
|
||||||
|
airaService.restartDiscovery()
|
||||||
|
binding.refresher.isRefreshing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onServiceDisconnected(name: ComponentName?) {}
|
||||||
|
}, Context.BIND_AUTO_CREATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.editPeerIp.setOnEditorActionListener { _, _, _ ->
|
||||||
|
if (::airaService.isInitialized){
|
||||||
|
airaService.connectTo(binding.editPeerIp.text.toString())
|
||||||
|
}
|
||||||
|
binding.editPeerIp.text.clear()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
|
||||||
|
menuInflater.inflate(R.menu.main_activity, menu)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||||
|
return when (item.itemId) {
|
||||||
|
R.id.settings -> {
|
||||||
|
startActivity(Intent(this, SettingsActivity::class.java))
|
||||||
|
true
|
||||||
|
}
|
||||||
|
R.id.close -> {
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.warning)
|
||||||
|
.setMessage(R.string.ask_log_out)
|
||||||
|
.setPositiveButton(R.string.yes) { _, _ ->
|
||||||
|
airaService.logOut()
|
||||||
|
if (AIRADatabase.isIdentityProtected(Constants.getDatabaseFolder(this))) {
|
||||||
|
startActivity(Intent(this, LoginActivity::class.java))
|
||||||
|
}
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> super.onOptionsItemSelected(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
airaService.isAppInBackground = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
if (::airaService.isInitialized) {
|
||||||
|
if (AIRAService.isServiceRunning) {
|
||||||
|
airaService.isAppInBackground = false
|
||||||
|
airaService.uiCallbacks = uiCallbacks //restoring callbacks
|
||||||
|
onlineSessionAdapter.reset()
|
||||||
|
offlineSessionAdapter.reset()
|
||||||
|
loadContacts()
|
||||||
|
loadSessions()
|
||||||
|
title = airaService.identityName
|
||||||
|
} else {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadContacts() {
|
||||||
|
for ((sessionId, contact) in airaService.contacts) {
|
||||||
|
offlineSessionAdapter.add(Session(sessionId, true, contact.verified, contact.seen, null, contact.name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadSessions() {
|
||||||
|
for ((sessionId, session) in airaService.sessions) {
|
||||||
|
handleNewSession(sessionId, session.ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleNewSession(sessionId: Int, ip: String) {
|
||||||
|
val seen = !airaService.notSeen.contains(sessionId)
|
||||||
|
val contact = airaService.contacts[sessionId]
|
||||||
|
if (contact == null) {
|
||||||
|
onlineSessionAdapter.add(Session(sessionId, false, false, seen, ip, airaService.savedNames[sessionId]))
|
||||||
|
} else {
|
||||||
|
onlineSessionAdapter.add(Session(sessionId, true, contact.verified, seen, ip, contact.name))
|
||||||
|
offlineSessionAdapter.remove(sessionId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchChatActivity(session: Session) {
|
||||||
|
startActivity(Intent(this, ChatActivity::class.java).apply {
|
||||||
|
putExtra("sessionId", session.sessionId)
|
||||||
|
putExtra("sessionName", session.name)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun askShareFileTo(session: Session) {
|
||||||
|
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
|
||||||
|
if (uri == null) {
|
||||||
|
Toast.makeText(this, R.string.share_uri_null, Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
val cursor = contentResolver.query(uri, null, null, null, null)
|
||||||
|
if (cursor == null) {
|
||||||
|
Toast.makeText(this, R.string.file_open_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
val fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
|
||||||
|
val fileSize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE))
|
||||||
|
val inputStream = contentResolver.openInputStream(uri)
|
||||||
|
if (inputStream == null) {
|
||||||
|
Toast.makeText(this, R.string.file_open_failed, Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.warning)
|
||||||
|
.setMessage(getString(R.string.ask_send_file, fileName, FileUtils.formatSize(fileSize), session.name ?: session.ip))
|
||||||
|
.setPositiveButton(R.string.yes) { _, _ ->
|
||||||
|
airaService.sendFileTo(session.sessionId, fileName, fileSize, inputStream)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
139
app/src/main/java/sushi/hardcore/aira/SettingsActivity.kt
Normal file
@ -0,0 +1,139 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.ServiceConnection
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.view.MenuItem
|
||||||
|
import android.view.View
|
||||||
|
import android.widget.EditText
|
||||||
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.preference.EditTextPreference
|
||||||
|
import androidx.preference.Preference
|
||||||
|
import androidx.preference.PreferenceFragmentCompat
|
||||||
|
import sushi.hardcore.aira.background_service.AIRAService
|
||||||
|
import sushi.hardcore.aira.databinding.ActivityMainBinding
|
||||||
|
import sushi.hardcore.aira.databinding.ActivitySettingsBinding
|
||||||
|
import sushi.hardcore.aira.utils.StringUtils
|
||||||
|
|
||||||
|
class SettingsActivity: AppCompatActivity() {
|
||||||
|
class MySettingsFragment : PreferenceFragmentCompat() {
|
||||||
|
private lateinit var airaService: AIRAService
|
||||||
|
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
|
||||||
|
setPreferencesFromResource(R.xml.preferences, rootKey)
|
||||||
|
val identityName = findPreference<EditTextPreference>("identityName")
|
||||||
|
Intent(activity, AIRAService::class.java).also { serviceIntent ->
|
||||||
|
activity?.bindService(serviceIntent, object : ServiceConnection {
|
||||||
|
override fun onServiceConnected(name: ComponentName?, service: IBinder) {
|
||||||
|
val binder = service as AIRAService.AIRABinder
|
||||||
|
airaService = binder.getService()
|
||||||
|
identityName?.text = airaService.identityName
|
||||||
|
}
|
||||||
|
override fun onServiceDisconnected(name: ComponentName?) {}
|
||||||
|
}, Context.BIND_AUTO_CREATE)
|
||||||
|
}
|
||||||
|
identityName?.setOnPreferenceChangeListener { _, newValue ->
|
||||||
|
if (airaService.changeName(newValue as String)) {
|
||||||
|
identityName.text = newValue
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
findPreference<Preference>("deleteIdentity")?.setOnPreferenceClickListener {
|
||||||
|
activity?.let { activity ->
|
||||||
|
AlertDialog.Builder(activity)
|
||||||
|
.setMessage(R.string.confirm_delete)
|
||||||
|
.setTitle(R.string.warning)
|
||||||
|
.setPositiveButton(R.string.ok) { _, _ ->
|
||||||
|
if (Constants.getDatabasePath(activity).delete()) {
|
||||||
|
airaService.logOut()
|
||||||
|
startActivity(Intent(activity, LoginActivity::class.java))
|
||||||
|
activity.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
findPreference<Preference>("identityPassword")?.setOnPreferenceClickListener {
|
||||||
|
activity?.let { activity ->
|
||||||
|
val dialogView = layoutInflater.inflate(R.layout.dialog_password, null)
|
||||||
|
val oldPasswordEditText = dialogView.findViewById<EditText>(R.id.old_password)
|
||||||
|
val isIdentityProtected = AIRADatabase.isIdentityProtected(Constants.getDatabaseFolder(activity))
|
||||||
|
if (!isIdentityProtected) {
|
||||||
|
oldPasswordEditText.visibility = View.GONE
|
||||||
|
}
|
||||||
|
val newPasswordEditText = dialogView.findViewById<EditText>(R.id.new_password)
|
||||||
|
val newPasswordConfirmEditText = dialogView.findViewById<EditText>(R.id.new_password_confirm)
|
||||||
|
AlertDialog.Builder(activity)
|
||||||
|
.setView(dialogView)
|
||||||
|
.setTitle(R.string.change_password)
|
||||||
|
.setPositiveButton(R.string.ok) { _, _ ->
|
||||||
|
val newPassword = newPasswordEditText.text.toString().toByteArray()
|
||||||
|
if (newPassword.isEmpty()) {
|
||||||
|
if (isIdentityProtected) { //don't change password if identity is not protected and new password is blank
|
||||||
|
changePassword(activity, isIdentityProtected, oldPasswordEditText, null)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val newPasswordConfirm = newPasswordConfirmEditText.text.toString().toByteArray()
|
||||||
|
if (newPassword.contentEquals(newPasswordConfirm)) {
|
||||||
|
changePassword(activity, isIdentityProtected, oldPasswordEditText, newPassword)
|
||||||
|
} else {
|
||||||
|
AlertDialog.Builder(activity)
|
||||||
|
.setMessage(R.string.password_mismatch)
|
||||||
|
.setTitle(R.string.error)
|
||||||
|
.setPositiveButton(R.string.ok, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
newPassword.fill(0)
|
||||||
|
newPasswordConfirm.fill(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changePassword(context: Context, isIdentityProtected: Boolean, oldPasswordEditText: EditText, newPassword: ByteArray?) {
|
||||||
|
val oldPassword = if (isIdentityProtected) {
|
||||||
|
oldPasswordEditText.text.toString().toByteArray()
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (!AIRADatabase.changePassword(Constants.getDatabaseFolder(context), oldPassword, newPassword)) {
|
||||||
|
AlertDialog.Builder(context)
|
||||||
|
.setMessage(R.string.change_password_failed)
|
||||||
|
.setTitle(R.string.error)
|
||||||
|
.setPositiveButton(R.string.ok, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
oldPassword?.fill(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||||
|
return if (item.itemId == android.R.id.home) {
|
||||||
|
finish()
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
super.onOptionsItemSelected(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
val binding = ActivitySettingsBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
supportFragmentManager
|
||||||
|
.beginTransaction()
|
||||||
|
.replace(R.id.settings_container, MySettingsFragment())
|
||||||
|
.commit()
|
||||||
|
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
||||||
|
binding.textFingerprint.text = StringUtils.beautifyFingerprint(AIRADatabase.getIdentityFingerprint())
|
||||||
|
}
|
||||||
|
}
|
135
app/src/main/java/sushi/hardcore/aira/adapters/ChatAdapter.kt
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
package sushi.hardcore.aira.adapters
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.PorterDuff
|
||||||
|
import android.graphics.PorterDuffColorFilter
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.ImageButton
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import sushi.hardcore.aira.ChatItem
|
||||||
|
import sushi.hardcore.aira.R
|
||||||
|
|
||||||
|
class ChatAdapter(
|
||||||
|
private val context: Context,
|
||||||
|
private val onSavingFile: (filename: String, rawUuid: ByteArray) -> Unit
|
||||||
|
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val BUBBLE_MARGIN = 70
|
||||||
|
}
|
||||||
|
|
||||||
|
private val inflater: LayoutInflater = LayoutInflater.from(context)
|
||||||
|
private val chatItems = mutableListOf<ChatItem>()
|
||||||
|
|
||||||
|
fun newMessage(chatItem: ChatItem) {
|
||||||
|
chatItems.add(chatItem)
|
||||||
|
notifyItemInserted(chatItems.size-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun newLoadedMessage(chatItem: ChatItem) {
|
||||||
|
chatItems.add(0, chatItem)
|
||||||
|
notifyItemInserted(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
chatItems.clear()
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal open class BubbleViewHolder(private val context: Context, itemView: View): RecyclerView.ViewHolder(itemView) {
|
||||||
|
fun handleItemView(position: Int) {
|
||||||
|
if (position == 0) {
|
||||||
|
itemView.setPadding(itemView.paddingLeft, 50, itemView.paddingRight, itemView.paddingBottom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun setBubbleColor(bubble: View, outgoing: Boolean) {
|
||||||
|
if (outgoing) {
|
||||||
|
bubble.background.clearColorFilter()
|
||||||
|
} else {
|
||||||
|
bubble.background.colorFilter = PorterDuffColorFilter(ContextCompat.getColor(context, R.color.incomingBubbleBackground), PorterDuff.Mode.SRC)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class MessageViewHolder(context: Context, itemView: View): BubbleViewHolder(context, itemView) {
|
||||||
|
fun bind(chatItem: ChatItem, position: Int) {
|
||||||
|
itemView.findViewById<TextView>(R.id.text_message).apply {
|
||||||
|
text = chatItem.data.sliceArray(1 until chatItem.data.size).decodeToString()
|
||||||
|
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
|
||||||
|
if (chatItem.outgoing) {
|
||||||
|
gravity = Gravity.END
|
||||||
|
marginStart = BUBBLE_MARGIN
|
||||||
|
} else {
|
||||||
|
gravity = Gravity.START
|
||||||
|
marginEnd = BUBBLE_MARGIN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setBubbleColor(this, chatItem.outgoing)
|
||||||
|
}
|
||||||
|
handleItemView(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class FileViewHolder(context: Context, itemView: View): BubbleViewHolder(context, itemView) {
|
||||||
|
fun bind(chatItem: ChatItem, position: Int, onSavingFile: (filename: String, rawUuid: ByteArray) -> Unit) {
|
||||||
|
val filename = chatItem.data.sliceArray(17 until chatItem.data.size).decodeToString()
|
||||||
|
itemView.findViewById<TextView>(R.id.text_filename).text = filename
|
||||||
|
itemView.findViewById<ImageButton>(R.id.button_save).setOnClickListener {
|
||||||
|
onSavingFile(filename, chatItem.data.sliceArray(1 until 17))
|
||||||
|
}
|
||||||
|
itemView.findViewById<LinearLayout>(R.id.bubble_content).apply {
|
||||||
|
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
|
||||||
|
if (chatItem.outgoing) {
|
||||||
|
gravity = Gravity.END
|
||||||
|
marginStart = BUBBLE_MARGIN
|
||||||
|
} else {
|
||||||
|
gravity = Gravity.START
|
||||||
|
marginEnd = BUBBLE_MARGIN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setBubbleColor(this, chatItem.outgoing)
|
||||||
|
}
|
||||||
|
handleItemView(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
|
||||||
|
return when (viewType) {
|
||||||
|
ChatItem.MESSAGE -> {
|
||||||
|
val view = inflater.inflate(R.layout.adapter_chat_message, parent, false)
|
||||||
|
MessageViewHolder(context, view)
|
||||||
|
}
|
||||||
|
ChatItem.FILE -> {
|
||||||
|
val view = inflater.inflate(R.layout.adapter_chat_file, parent, false)
|
||||||
|
FileViewHolder(context, view)
|
||||||
|
}
|
||||||
|
else -> throw RuntimeException("Invalid chat item type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
|
||||||
|
val chatItem = chatItems[position]
|
||||||
|
when (chatItem.itemType) {
|
||||||
|
ChatItem.MESSAGE -> {
|
||||||
|
(holder as MessageViewHolder).bind(chatItem, position)
|
||||||
|
}
|
||||||
|
ChatItem.FILE -> {
|
||||||
|
(holder as FileViewHolder).bind(chatItem, position, onSavingFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getItemCount(): Int {
|
||||||
|
return chatItems.size
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getItemViewType(position: Int): Int {
|
||||||
|
return chatItems[position].itemType
|
||||||
|
}
|
||||||
|
}
|
10
app/src/main/java/sushi/hardcore/aira/adapters/Session.kt
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package sushi.hardcore.aira.adapters
|
||||||
|
|
||||||
|
class Session(
|
||||||
|
val sessionId: Int,
|
||||||
|
val isContact: Boolean,
|
||||||
|
val isVerified: Boolean,
|
||||||
|
var seen: Boolean,
|
||||||
|
val ip: String?,
|
||||||
|
var name: String?
|
||||||
|
)
|
101
app/src/main/java/sushi/hardcore/aira/adapters/SessionAdapter.kt
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
package sushi.hardcore.aira.adapters
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.BaseAdapter
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.TextView
|
||||||
|
import sushi.hardcore.aira.R
|
||||||
|
import sushi.hardcore.aira.widgets.TextAvatar
|
||||||
|
|
||||||
|
class SessionAdapter(context: Context): BaseAdapter() {
|
||||||
|
private val sessions = mutableListOf<Session>()
|
||||||
|
private val inflater: LayoutInflater = LayoutInflater.from(context)
|
||||||
|
|
||||||
|
override fun getCount(): Int {
|
||||||
|
return sessions.size
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getItem(position: Int): Session {
|
||||||
|
return sessions[position]
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getItemId(position: Int): Long {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
|
||||||
|
val view: View = convertView ?: inflater.inflate(R.layout.adapter_session, parent, false)
|
||||||
|
val currentSession = getItem(position)
|
||||||
|
view.findViewById<TextView>(R.id.text_name).apply {
|
||||||
|
if (currentSession.name == null) {
|
||||||
|
text = currentSession.ip
|
||||||
|
setTextColor(Color.RED)
|
||||||
|
} else {
|
||||||
|
text = currentSession.name
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
}
|
||||||
|
view.findViewById<TextAvatar>(R.id.text_avatar).setLetterFrom(text.toString())
|
||||||
|
}
|
||||||
|
view.findViewById<ImageView>(R.id.image_trust_level).apply {
|
||||||
|
if (currentSession.isVerified) {
|
||||||
|
setImageResource(R.drawable.ic_verified)
|
||||||
|
} else if (!currentSession.isContact) {
|
||||||
|
setImageResource(R.drawable.ic_warning)
|
||||||
|
} else {
|
||||||
|
setImageDrawable(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
view.findViewById<ImageView>(R.id.image_seen).visibility = if (currentSession.seen) {
|
||||||
|
View.GONE
|
||||||
|
} else {
|
||||||
|
View.VISIBLE
|
||||||
|
}
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
fun add(session: Session) {
|
||||||
|
sessions.add(session)
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getSessionById(sessionId: Int): Session? {
|
||||||
|
for (session in sessions){
|
||||||
|
if (session.sessionId == sessionId) {
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(sessionId: Int): Session? {
|
||||||
|
getSessionById(sessionId)?.let {
|
||||||
|
sessions.remove(it)
|
||||||
|
notifyDataSetChanged()
|
||||||
|
return it
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setName(sessionId: Int, name: String) {
|
||||||
|
getSessionById(sessionId)?.let {
|
||||||
|
it.name = name
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSeen(sessionId: Int, seen: Boolean) {
|
||||||
|
getSessionById(sessionId)?.let {
|
||||||
|
it.seen = seen
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun reset() {
|
||||||
|
sessions.clear()
|
||||||
|
notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,810 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import android.app.*
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.nsd.NsdManager
|
||||||
|
import android.net.nsd.NsdServiceInfo
|
||||||
|
import android.os.*
|
||||||
|
import android.os.Process.THREAD_PRIORITY_BACKGROUND
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.annotation.RequiresApi
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import androidx.core.app.RemoteInput
|
||||||
|
import sushi.hardcore.aira.*
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.net.*
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.channels.*
|
||||||
|
|
||||||
|
class AIRAService : Service() {
|
||||||
|
private external fun releaseIdentity()
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val SERVICE_NOTIFICATION_CHANNEL_ID = "AIRAService"
|
||||||
|
const val MESSAGES_NOTIFICATION_CHANNEL_ID = "Messages"
|
||||||
|
const val ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID = "AskFile"
|
||||||
|
const val FILE_TRANSFER_NOTIFICATION_CHANNEL_ID = "FileTransfer"
|
||||||
|
const val MESSAGE_CONNECT_TO = 0
|
||||||
|
const val MESSAGE_SEND_TO = 1
|
||||||
|
const val MESSAGE_LOGOUT = 2
|
||||||
|
const val MESSAGE_TELL_NAME = 3
|
||||||
|
const val MESSAGE_CANCEL_FILE_TRANSFER = 4
|
||||||
|
|
||||||
|
var isServiceRunning = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private val binder = AIRABinder()
|
||||||
|
val sessions = mutableMapOf<Int, Session>()
|
||||||
|
private var sessionCounter = 0
|
||||||
|
private var server: ServerSocketChannel? = null
|
||||||
|
private lateinit var selector: Selector
|
||||||
|
private val sessionIdByKey = mutableMapOf<SelectionKey, Int>()
|
||||||
|
private val notificationIdManager = NotificationIdManager()
|
||||||
|
private val sendFileTransfers = mutableMapOf<Int, SendFileTransfer>()
|
||||||
|
val receiveFileTransfers = mutableMapOf<Int, ReceiveFileTransfer>()
|
||||||
|
lateinit var contacts: HashMap<Int, Contact>
|
||||||
|
private lateinit var serviceHandler: Handler
|
||||||
|
private lateinit var notificationManager: NotificationManagerCompat
|
||||||
|
private lateinit var nsdManager: NsdManager
|
||||||
|
private val nsdRegistrationListener = object : NsdManager.RegistrationListener {
|
||||||
|
override fun onRegistrationFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {
|
||||||
|
Log.w("mDNS","DNS-SD registration failed: $errorCode")
|
||||||
|
}
|
||||||
|
override fun onUnregistrationFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {}
|
||||||
|
override fun onServiceRegistered(serviceInfo: NsdServiceInfo?) {}
|
||||||
|
override fun onServiceUnregistered(serviceInfo: NsdServiceInfo?) {}
|
||||||
|
}
|
||||||
|
private var shouldRestartDiscovery = false
|
||||||
|
private val nsdDiscoveryListener = object : NsdManager.DiscoveryListener {
|
||||||
|
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
|
||||||
|
Log.w("mDNS", "Failed to start discovery: $errorCode")
|
||||||
|
}
|
||||||
|
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {}
|
||||||
|
override fun onDiscoveryStarted(serviceType: String?) {}
|
||||||
|
override fun onDiscoveryStopped(serviceType: String?) {
|
||||||
|
if (shouldRestartDiscovery) {
|
||||||
|
startDiscovery()
|
||||||
|
shouldRestartDiscovery = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||||
|
nsdManager.resolveService(serviceInfo, object : NsdManager.ResolveListener {
|
||||||
|
override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {}
|
||||||
|
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||||
|
if (isServiceRunning) {
|
||||||
|
connectTo(serviceInfo.host.hostAddress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
override fun onServiceLost(serviceInfo: NsdServiceInfo?) {}
|
||||||
|
}
|
||||||
|
val savedMsgs = mutableMapOf<Int, MutableList<ChatItem>>()
|
||||||
|
val savedNames = mutableMapOf<Int, String>()
|
||||||
|
val notSeen = mutableListOf<Int>()
|
||||||
|
var uiCallbacks: UiCallbacks? = null
|
||||||
|
var isAppInBackground = true
|
||||||
|
var identityName: String? = null
|
||||||
|
|
||||||
|
inner class AIRABinder : Binder() {
|
||||||
|
fun getService(): AIRAService = this@AIRAService
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder {
|
||||||
|
return binder
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UiCallbacks {
|
||||||
|
fun onNewSession(sessionId: Int, ip: String)
|
||||||
|
fun onSessionDisconnect(sessionId: Int)
|
||||||
|
fun onNameTold(sessionId: Int, name: String)
|
||||||
|
fun onNewMessage(sessionId: Int, data: ByteArray): Boolean
|
||||||
|
fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connectTo(ip: String) {
|
||||||
|
serviceHandler.obtainMessage().apply {
|
||||||
|
what = MESSAGE_CONNECT_TO
|
||||||
|
data = Bundle().apply { putString("ip", ip) }
|
||||||
|
serviceHandler.sendMessage(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendTo(sessionId: Int, buffer: ByteArray) {
|
||||||
|
serviceHandler.obtainMessage().apply {
|
||||||
|
what = MESSAGE_SEND_TO
|
||||||
|
data = Bundle().apply {
|
||||||
|
putInt("sessionId", sessionId)
|
||||||
|
putByteArray("buff", buffer)
|
||||||
|
}
|
||||||
|
serviceHandler.sendMessage(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancelFileTransfer(sessionId: Int) {
|
||||||
|
serviceHandler.obtainMessage().apply {
|
||||||
|
what = MESSAGE_CANCEL_FILE_TRANSFER
|
||||||
|
data = Bundle().apply { putInt("sessionId", sessionId) }
|
||||||
|
serviceHandler.sendMessage(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendFileTo(sessionId: Int, fileName: String, fileSize: Long, inputStream: InputStream): ByteArray? {
|
||||||
|
if (fileSize <= Constants.fileSizeLimit) {
|
||||||
|
val buffer = inputStream.readBytes()
|
||||||
|
inputStream.close()
|
||||||
|
sendTo(sessionId, Protocol.newFile(fileName, buffer))
|
||||||
|
AIRADatabase.storeFile(contacts[sessionId]?.uuid, buffer)?.let { rawFileUuid ->
|
||||||
|
val msg = byteArrayOf(Protocol.FILE)+rawFileUuid+fileName.toByteArray()
|
||||||
|
saveMsg(sessionId, msg)
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val fileTransfer = SendFileTransfer(fileName, fileSize, inputStream)
|
||||||
|
sendFileTransfers[sessionId] = fileTransfer
|
||||||
|
createFileTransferNotification(sessionId, fileTransfer)
|
||||||
|
sendTo(sessionId, Protocol.askLargeFile(fileSize, fileName))
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logOut() {
|
||||||
|
serviceHandler.sendEmptyMessage(MESSAGE_LOGOUT)
|
||||||
|
isServiceRunning = false
|
||||||
|
releaseIdentity()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isOnline(sessionId: Int): Boolean {
|
||||||
|
return sessions.contains(sessionId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getNameOf(sessionId: Int): String {
|
||||||
|
return contacts[sessionId]?.name ?: savedNames[sessionId] ?: sessions[sessionId]!!.ip
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isContact(sessionId: Int): Boolean {
|
||||||
|
return contacts.contains(sessionId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setAsContact(sessionId: Int, name: String): Boolean {
|
||||||
|
sessions[sessionId]?.peerPublicKey?.let {
|
||||||
|
AIRADatabase.addContact(name, it)?.let { contact ->
|
||||||
|
contacts[sessionId] = contact
|
||||||
|
savedMsgs.remove(sessionId)?.let { msgs ->
|
||||||
|
for (msg in msgs) {
|
||||||
|
AIRADatabase.storeMsg(contact.uuid, msg.outgoing, msg.data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
savedNames.remove(sessionId)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setVerified(sessionId: Int): Boolean {
|
||||||
|
contacts[sessionId]?.let {
|
||||||
|
if (AIRADatabase.setVerified(it.uuid)) {
|
||||||
|
it.verified = true
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSeen(sessionId: Int, seen: Boolean) {
|
||||||
|
if (seen) {
|
||||||
|
notSeen.remove(sessionId)
|
||||||
|
notificationManager.cancel(notificationIdManager.getMessageNotificationId(sessionId))
|
||||||
|
} else if (!notSeen.contains(sessionId)) {
|
||||||
|
notSeen.add(sessionId)
|
||||||
|
}
|
||||||
|
contacts[sessionId]?.let { contact ->
|
||||||
|
if (contact.seen != seen) {
|
||||||
|
if (AIRADatabase.setContactSeen(contact.uuid, seen)) {
|
||||||
|
contact.seen = seen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeContact(sessionId: Int): Boolean {
|
||||||
|
contacts.remove(sessionId)?.let {
|
||||||
|
return if (AIRADatabase.removeContact(it.uuid)) {
|
||||||
|
savedMsgs[sessionId] = mutableListOf()
|
||||||
|
savedNames[sessionId] = it.name
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteConversation(sessionId: Int): Boolean {
|
||||||
|
contacts[sessionId]?.let {
|
||||||
|
return if (AIRADatabase.deleteConversation(it.uuid)) {
|
||||||
|
savedMsgs[sessionId] = mutableListOf()
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun changeName(newName: String): Boolean {
|
||||||
|
return if (AIRADatabase.changeName(newName)) {
|
||||||
|
identityName = newName
|
||||||
|
serviceHandler.sendEmptyMessage(MESSAGE_TELL_NAME)
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleNewSocket(socket: SocketChannel, outgoing: Boolean) {
|
||||||
|
Thread {
|
||||||
|
try {
|
||||||
|
val session = Session(socket, outgoing)
|
||||||
|
if (session.doHandshake()) {
|
||||||
|
var isActuallyNewSession = true
|
||||||
|
for (s in sessions.values) {
|
||||||
|
if (s.peerPublicKey.contentEquals(session.peerPublicKey)) {
|
||||||
|
isActuallyNewSession = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isActuallyNewSession && !session.peerPublicKey.contentEquals(AIRADatabase.getIdentityPublicKey())) {
|
||||||
|
var sessionId: Int? = null
|
||||||
|
for ((i, contact) in contacts) {
|
||||||
|
if (contact.publicKey.contentEquals(session.peerPublicKey)){
|
||||||
|
sessions[i] = session
|
||||||
|
sessionId = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sessionId == null) {
|
||||||
|
sessions[sessionCounter] = session
|
||||||
|
savedMsgs[sessionCounter] = mutableListOf()
|
||||||
|
sessionId = sessionCounter
|
||||||
|
sessionCounter++
|
||||||
|
}
|
||||||
|
session.configureBlocking(false)
|
||||||
|
val key = session.register(selector, SelectionKey.OP_READ)
|
||||||
|
sessionIdByKey[key] = sessionId
|
||||||
|
uiCallbacks?.onNewSession(sessionId, session.ip)
|
||||||
|
if (!isContact(sessionId)) {
|
||||||
|
session.encryptAndSend(Protocol.askName())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
session.close()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
session.close()
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendNotification(sessionId: Int, msgContent: ByteArray) {
|
||||||
|
val name = getNameOf(sessionId)
|
||||||
|
val notificationBuilder = NotificationCompat.Builder(this, MESSAGES_NOTIFICATION_CHANNEL_ID)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
|
||||||
|
.setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
.setContentTitle(name)
|
||||||
|
.setContentText(
|
||||||
|
if (msgContent[0] == Protocol.MESSAGE) {
|
||||||
|
msgContent.decodeToString(1)
|
||||||
|
} else { //file
|
||||||
|
msgContent.decodeToString(17)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setContentIntent(
|
||||||
|
PendingIntent.getActivity(this, 0, Intent(this, ChatActivity::class.java).apply {
|
||||||
|
putExtra("sessionId", sessionId)
|
||||||
|
putExtra("sessionName", name)
|
||||||
|
}, 0)
|
||||||
|
)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.setDefaults(Notification.DEFAULT_ALL)
|
||||||
|
.apply {
|
||||||
|
priority = NotificationCompat.PRIORITY_HIGH
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
|
||||||
|
val markReadIntent = PendingIntent.getBroadcast(this, 0,
|
||||||
|
Intent(this, NotificationBroadcastReceiver::class.java).apply {
|
||||||
|
val bundle = Bundle()
|
||||||
|
bundle.putBinder("binder", AIRABinder())
|
||||||
|
bundle.putInt("sessionId", sessionId)
|
||||||
|
putExtra("bundle", bundle)
|
||||||
|
action = NotificationBroadcastReceiver.ACTION_MARK_READ
|
||||||
|
}, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
notificationBuilder.addAction(
|
||||||
|
NotificationCompat.Action(
|
||||||
|
R.drawable.ic_launcher,
|
||||||
|
getString(R.string.mark_read),
|
||||||
|
markReadIntent
|
||||||
|
)
|
||||||
|
)
|
||||||
|
val replyPendingIntent: PendingIntent =
|
||||||
|
PendingIntent.getBroadcast(this, 0,
|
||||||
|
Intent(this, NotificationBroadcastReceiver::class.java).apply {
|
||||||
|
val bundle = Bundle()
|
||||||
|
bundle.putBinder("binder", AIRABinder())
|
||||||
|
bundle.putInt("sessionId", sessionId)
|
||||||
|
putExtra("bundle", bundle)
|
||||||
|
action = NotificationBroadcastReceiver.ACTION_REPLY
|
||||||
|
}, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
notificationBuilder.addAction(
|
||||||
|
NotificationCompat.Action.Builder(R.drawable.ic_launcher, getString(R.string.reply), replyPendingIntent)
|
||||||
|
.addRemoteInput(
|
||||||
|
RemoteInput.Builder(NotificationBroadcastReceiver.KEY_TEXT_REPLY)
|
||||||
|
.setLabel(getString(R.string.reply))
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
notificationManager.notify(notificationIdManager.getMessageNotificationId(sessionId), notificationBuilder.build())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createFileTransferNotification(sessionId: Int, fileTransfer: FileTransfer) {
|
||||||
|
fileTransfer.notificationBuilder = NotificationCompat.Builder(this, FILE_TRANSFER_NOTIFICATION_CHANNEL_ID)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
|
||||||
|
.setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
.setContentTitle(getNameOf(sessionId))
|
||||||
|
.setContentText(fileTransfer.fileName)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setProgress(fileTransfer.fileSize.toInt(), fileTransfer.transferred, true)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
|
||||||
|
val cancelIntent = PendingIntent.getBroadcast(this, 0,
|
||||||
|
Intent(this, NotificationBroadcastReceiver::class.java).apply {
|
||||||
|
val bundle = Bundle()
|
||||||
|
bundle.putBinder("binder", AIRABinder())
|
||||||
|
bundle.putInt("sessionId", sessionId)
|
||||||
|
putExtra("bundle", bundle)
|
||||||
|
action = NotificationBroadcastReceiver.ACTION_CANCEL_FILE_TRANSFER
|
||||||
|
}, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
fileTransfer.notificationBuilder.addAction(
|
||||||
|
NotificationCompat.Action(
|
||||||
|
R.drawable.ic_launcher,
|
||||||
|
getString(R.string.cancel),
|
||||||
|
cancelIntent
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fileTransfer.notificationId = notificationIdManager.getFileTransferNotificationId(sessionId)
|
||||||
|
notificationManager.notify(fileTransfer.notificationId, fileTransfer.notificationBuilder.build())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveMsg(sessionId: Int, msg: ByteArray) {
|
||||||
|
var msgSaved = false
|
||||||
|
contacts[sessionId]?.uuid?.let { uuid ->
|
||||||
|
msgSaved = AIRADatabase.storeMsg(uuid, true, msg)
|
||||||
|
}
|
||||||
|
if (!msgSaved) {
|
||||||
|
savedMsgs[sessionId]?.add(ChatItem(true, msg))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendAndSave(sessionId: Int, msg: ByteArray) {
|
||||||
|
sessions[sessionId]?.encryptAndSend(msg)
|
||||||
|
if (msg[0] == Protocol.MESSAGE) {
|
||||||
|
saveMsg(sessionId, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
HandlerThread("", THREAD_PRIORITY_BACKGROUND).apply {
|
||||||
|
start()
|
||||||
|
serviceHandler = object : Handler(looper){
|
||||||
|
override fun handleMessage(msg: Message) {
|
||||||
|
try {
|
||||||
|
when (msg.what) {
|
||||||
|
MESSAGE_SEND_TO -> {
|
||||||
|
val sessionId = msg.data.getInt("sessionId")
|
||||||
|
msg.data.getByteArray("buff")?.let {
|
||||||
|
val fileTransfer = sendFileTransfers[sessionId]
|
||||||
|
if (fileTransfer?.nextChunk == null) {
|
||||||
|
sendAndSave(sessionId, it)
|
||||||
|
} else {
|
||||||
|
fileTransfer.msgQueue.add(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MESSAGE_CONNECT_TO -> {
|
||||||
|
msg.data.getString("ip")?.let { ip ->
|
||||||
|
try {
|
||||||
|
val socket = SocketChannel.open()
|
||||||
|
if (socket.connect(InetSocketAddress(ip, Constants.port))) {
|
||||||
|
handleNewSocket(socket, true)
|
||||||
|
}
|
||||||
|
} catch (e: ConnectException) {
|
||||||
|
Log.w("Connect failed", e.message.toString())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MESSAGE_CANCEL_FILE_TRANSFER -> {
|
||||||
|
val sessionId = msg.data.getInt("sessionId")
|
||||||
|
sessions[sessionId]?.let { session ->
|
||||||
|
cancelFileTransfer(sessionId, session, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MESSAGE_TELL_NAME -> {
|
||||||
|
identityName?.let {
|
||||||
|
for (session in sessions.values) {
|
||||||
|
try {
|
||||||
|
session.encryptAndSend(Protocol.tellName(it))
|
||||||
|
} catch (e: SocketException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MESSAGE_LOGOUT -> {
|
||||||
|
nsdManager.unregisterService(nsdRegistrationListener)
|
||||||
|
stopDiscovery()
|
||||||
|
quit()
|
||||||
|
stopSelf()
|
||||||
|
uiCallbacks = null
|
||||||
|
for (session in sessions.values) {
|
||||||
|
session.close()
|
||||||
|
}
|
||||||
|
server?.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val contactList = AIRADatabase.loadContacts()
|
||||||
|
if (contactList == null) {
|
||||||
|
contacts = HashMap(0)
|
||||||
|
} else {
|
||||||
|
contacts = HashMap(contactList.size)
|
||||||
|
for (contact in contactList) {
|
||||||
|
contacts[sessionCounter] = contact
|
||||||
|
if (!contact.seen) {
|
||||||
|
notSeen.add(sessionCounter)
|
||||||
|
}
|
||||||
|
sessionCounter++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encryptNextChunk(session: Session, fileTransfer: SendFileTransfer) {
|
||||||
|
val nextChunk = ByteArray(Constants.FILE_CHUNK_SIZE)
|
||||||
|
nextChunk[0] = Protocol.LARGE_FILE_CHUNK
|
||||||
|
val read = fileTransfer.inputStream.read(nextChunk, 1, Constants.FILE_CHUNK_SIZE-1)
|
||||||
|
fileTransfer.nextChunk = if (read > 0) {
|
||||||
|
session.encrypt(nextChunk)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun flushSendFileTransfer(sessionId: Int, session: Session, fileTransfer: SendFileTransfer) {
|
||||||
|
fileTransfer.nextChunk?.let {
|
||||||
|
session.writeAll(it)
|
||||||
|
while (fileTransfer.msgQueue.size > 0) {
|
||||||
|
val msg = fileTransfer.msgQueue.removeAt(0)
|
||||||
|
sendAndSave(sessionId, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelFileTransfer(sessionId: Int, session: Session, outgoing: Boolean) {
|
||||||
|
sendFileTransfers[sessionId]?.let {
|
||||||
|
it.inputStream.close()
|
||||||
|
it.onAborted(this, notificationManager, getNameOf(sessionId))
|
||||||
|
flushSendFileTransfer(sessionId, session, it)
|
||||||
|
sendFileTransfers.remove(sessionId)
|
||||||
|
}
|
||||||
|
receiveFileTransfers[sessionId]?.let {
|
||||||
|
it.outputStream?.close()
|
||||||
|
it.onAborted(this, notificationManager, getNameOf(sessionId))
|
||||||
|
receiveFileTransfers.remove(sessionId)
|
||||||
|
}
|
||||||
|
if (outgoing) {
|
||||||
|
session.encryptAndSend(Protocol.abortFileTransfer())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startListening() {
|
||||||
|
server = try {
|
||||||
|
ServerSocketChannel.open().apply {
|
||||||
|
configureBlocking(false)
|
||||||
|
socket().bind(InetSocketAddress(Constants.port))
|
||||||
|
}
|
||||||
|
} catch (e: SocketException) {
|
||||||
|
Log.w("Bind failed", e.message.toString())
|
||||||
|
null
|
||||||
|
}
|
||||||
|
selector = Selector.open()
|
||||||
|
server?.register(selector, SelectionKey.OP_ACCEPT)
|
||||||
|
Thread {
|
||||||
|
while (isServiceRunning) {
|
||||||
|
selector.select(100) //timeout to stop this thread if we log out
|
||||||
|
val keys = selector.selectedKeys()
|
||||||
|
for (key in keys) {
|
||||||
|
if (key.isValid) {
|
||||||
|
if (key.isReadable) {
|
||||||
|
sessionIdByKey[key]?.let { sessionId ->
|
||||||
|
sessions[sessionId]?.let { session ->
|
||||||
|
var shouldCloseSession = false
|
||||||
|
try {
|
||||||
|
val buffer = session.receiveAndDecrypt()
|
||||||
|
if (buffer == null) {
|
||||||
|
shouldCloseSession = true
|
||||||
|
} else {
|
||||||
|
when (buffer[0]) {
|
||||||
|
Protocol.ASK_NAME -> {
|
||||||
|
identityName?.let { name ->
|
||||||
|
session.encryptAndSend(Protocol.tellName(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Protocol.TELL_NAME -> {
|
||||||
|
val name = buffer.sliceArray(1 until buffer.size).decodeToString()
|
||||||
|
uiCallbacks?.onNameTold(sessionId, name)
|
||||||
|
val contact = contacts[sessionId]
|
||||||
|
if (contact == null) {
|
||||||
|
savedNames[sessionId] = name
|
||||||
|
} else {
|
||||||
|
contact.name = name
|
||||||
|
AIRADatabase.changeContactName(contact.uuid, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Protocol.LARGE_FILE_CHUNK -> {
|
||||||
|
receiveFileTransfers[sessionId]?.let { fileTransfer ->
|
||||||
|
fileTransfer.outputStream?.let { outputStream ->
|
||||||
|
val chunk = buffer.sliceArray(1 until buffer.size)
|
||||||
|
try {
|
||||||
|
outputStream.write(chunk)
|
||||||
|
session.encryptAndSend(Protocol.ackChunk())
|
||||||
|
fileTransfer.transferred += chunk.size
|
||||||
|
if (fileTransfer.transferred >= fileTransfer.fileSize) {
|
||||||
|
outputStream.close()
|
||||||
|
receiveFileTransfers.remove(sessionId)
|
||||||
|
fileTransfer.onCompleted(this, notificationManager, getNameOf(sessionId))
|
||||||
|
} else {
|
||||||
|
fileTransfer.updateNotificationProgress(notificationManager)
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
cancelFileTransfer(sessionId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Protocol.ACK_CHUNK -> {
|
||||||
|
sendFileTransfers[sessionId]?.let { fileTransfer ->
|
||||||
|
flushSendFileTransfer(sessionId, session, fileTransfer)
|
||||||
|
fileTransfer.transferred += fileTransfer.nextChunk?.size ?: 0
|
||||||
|
if (fileTransfer.transferred >= fileTransfer.fileSize) {
|
||||||
|
fileTransfer.inputStream.close()
|
||||||
|
sendFileTransfers.remove(sessionId)
|
||||||
|
fileTransfer.onCompleted(this, notificationManager, getNameOf(sessionId))
|
||||||
|
} else {
|
||||||
|
encryptNextChunk(session, fileTransfer)
|
||||||
|
fileTransfer.updateNotificationProgress(notificationManager)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Protocol.ABORT_FILE_TRANSFER -> cancelFileTransfer(sessionId, session, false)
|
||||||
|
Protocol.ACCEPT_LARGE_FILE -> {
|
||||||
|
sendFileTransfers[sessionId]?.let { fileTransfer ->
|
||||||
|
encryptNextChunk(session, fileTransfer)
|
||||||
|
fileTransfer.nextChunk?.let {
|
||||||
|
session.writeAll(it)
|
||||||
|
fileTransfer.transferred += fileTransfer.nextChunk?.size ?: 0
|
||||||
|
encryptNextChunk(session, fileTransfer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Protocol.ASK_LARGE_FILE -> {
|
||||||
|
if (receiveFileTransfers[sessionId] == null) {
|
||||||
|
val fileSize = ByteBuffer.wrap(buffer.sliceArray(1..8)).long
|
||||||
|
val fileName = buffer.sliceArray(9 until buffer.size).decodeToString()
|
||||||
|
val fileTransfer = ReceiveFileTransfer(fileName, fileSize, { fileTransfer ->
|
||||||
|
createFileTransferNotification(sessionId, fileTransfer)
|
||||||
|
sendTo(sessionId, Protocol.acceptLargeFile())
|
||||||
|
}, {
|
||||||
|
receiveFileTransfers.remove(sessionId)
|
||||||
|
sendTo(sessionId, Protocol.abortFileTransfer())
|
||||||
|
notificationManager.cancel(notificationIdManager.getFileTransferNotificationId(sessionId))
|
||||||
|
})
|
||||||
|
receiveFileTransfers[sessionId] = fileTransfer
|
||||||
|
val name = getNameOf(sessionId)
|
||||||
|
var shouldSendNotification = true
|
||||||
|
if (!isAppInBackground) {
|
||||||
|
if (uiCallbacks?.onAskLargeFile(sessionId, name, fileTransfer) == true) {
|
||||||
|
shouldSendNotification = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shouldSendNotification) {
|
||||||
|
val notificationBuilder = NotificationCompat.Builder(this, ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
||||||
|
.setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
.setContentTitle(getString(R.string.download_file_request))
|
||||||
|
.setContentText(getString(R.string.want_to_send_a_file, name, ": $fileName"))
|
||||||
|
.setOngoing(true) //not cancelable
|
||||||
|
.setContentIntent(
|
||||||
|
PendingIntent.getActivity(this, 0, Intent(this, ChatActivity::class.java).apply {
|
||||||
|
putExtra("sessionId", sessionId)
|
||||||
|
putExtra("sessionName", name)
|
||||||
|
}, 0)
|
||||||
|
)
|
||||||
|
.setDefaults(Notification.DEFAULT_ALL)
|
||||||
|
.apply {
|
||||||
|
priority = NotificationCompat.PRIORITY_HIGH
|
||||||
|
}
|
||||||
|
notificationManager.notify(notificationIdManager.getFileTransferNotificationId(sessionId), notificationBuilder.build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
when (buffer[0]){
|
||||||
|
Protocol.MESSAGE -> buffer
|
||||||
|
Protocol.FILE -> {
|
||||||
|
val filenameLen = ByteBuffer.wrap(ByteArray(2) +buffer.sliceArray(1..2)).int
|
||||||
|
val filename = buffer.sliceArray(3 until 3+filenameLen)
|
||||||
|
val rawFileUuid = AIRADatabase.storeFile(contacts[sessionId]?.uuid, buffer.sliceArray(3+filenameLen until buffer.size))
|
||||||
|
if (rawFileUuid == null) {
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
byteArrayOf(Protocol.FILE)+rawFileUuid+filename
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
Log.i("Unknown message type", String.format("%02X", buffer[0]))
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}?.let { handledMsg ->
|
||||||
|
var seen = false
|
||||||
|
uiCallbacks?.let { uiCallbacks ->
|
||||||
|
seen = uiCallbacks.onNewMessage(sessionId, handledMsg)
|
||||||
|
}
|
||||||
|
setSeen(sessionId, seen)
|
||||||
|
var msgSaved = false
|
||||||
|
contacts[sessionId]?.let { contact ->
|
||||||
|
msgSaved = AIRADatabase.storeMsg(contact.uuid, false, handledMsg)
|
||||||
|
}
|
||||||
|
if (!msgSaved){
|
||||||
|
savedMsgs[sessionId]?.add(ChatItem(false, handledMsg))
|
||||||
|
}
|
||||||
|
if (isAppInBackground) {
|
||||||
|
sendNotification(sessionId, handledMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
shouldCloseSession = true
|
||||||
|
}
|
||||||
|
if (shouldCloseSession) {
|
||||||
|
session.close()
|
||||||
|
key.cancel()
|
||||||
|
uiCallbacks?.onSessionDisconnect(sessionId)
|
||||||
|
sessions.remove(sessionId)
|
||||||
|
savedMsgs.remove(sessionId)
|
||||||
|
savedNames.remove(sessionId)
|
||||||
|
sendFileTransfers.remove(sessionId)?.notificationId?.let {
|
||||||
|
if (it != -1) {
|
||||||
|
notificationManager.cancel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
receiveFileTransfers.remove(sessionId)?.notificationId?.let {
|
||||||
|
if (it != -1) {
|
||||||
|
notificationManager.cancel(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (key.isAcceptable) {
|
||||||
|
server?.accept()?.let {
|
||||||
|
handleNewSocket(it, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun restartDiscovery() {
|
||||||
|
shouldRestartDiscovery = true
|
||||||
|
stopDiscovery()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopDiscovery() {
|
||||||
|
nsdManager.stopServiceDiscovery(nsdDiscoveryListener)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startDiscovery() {
|
||||||
|
nsdManager.discoverServices(Constants.mDNSServiceType, NsdManager.PROTOCOL_DNS_SD, nsdDiscoveryListener)
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequiresApi(Build.VERSION_CODES.O)
|
||||||
|
private fun createNotificationChannels() {
|
||||||
|
notificationManager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
SERVICE_NOTIFICATION_CHANNEL_ID,
|
||||||
|
getString(R.string.service_name),
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
)
|
||||||
|
)
|
||||||
|
notificationManager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
MESSAGES_NOTIFICATION_CHANNEL_ID,
|
||||||
|
getString(R.string.msg_notification_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_HIGH
|
||||||
|
)
|
||||||
|
)
|
||||||
|
notificationManager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID,
|
||||||
|
getString(R.string.ask_file_notification_channel),
|
||||||
|
NotificationManager.IMPORTANCE_HIGH
|
||||||
|
)
|
||||||
|
)
|
||||||
|
notificationManager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
FILE_TRANSFER_NOTIFICATION_CHANNEL_ID,
|
||||||
|
getString(R.string.file_transfers),
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
notificationManager = NotificationManagerCompat.from(this)
|
||||||
|
val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
createNotificationChannels()
|
||||||
|
Notification.Builder(this, SERVICE_NOTIFICATION_CHANNEL_ID)
|
||||||
|
} else {
|
||||||
|
@Suppress("Deprecation")
|
||||||
|
Notification.Builder(this)
|
||||||
|
}
|
||||||
|
val notification: Notification = notificationBuilder
|
||||||
|
.setContentTitle(getString(R.string.background_service))
|
||||||
|
.setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
.setContentIntent(
|
||||||
|
PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), 0)
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
startForeground(1, notification)
|
||||||
|
|
||||||
|
val serviceInfo = NsdServiceInfo().apply {
|
||||||
|
serviceName = Constants.mDNSServiceName
|
||||||
|
serviceType = Constants.mDNSServiceType
|
||||||
|
port = Constants.port
|
||||||
|
}
|
||||||
|
nsdManager = getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||||
|
try {
|
||||||
|
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, nsdRegistrationListener)
|
||||||
|
startDiscovery()
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
//can happen if service is restarted too quickly
|
||||||
|
}
|
||||||
|
|
||||||
|
startListening()
|
||||||
|
|
||||||
|
isServiceRunning = true
|
||||||
|
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
isServiceRunning = false
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
class ApplicationKeys(
|
||||||
|
val localKey: ByteArray,
|
||||||
|
val localIv: ByteArray,
|
||||||
|
val peerKey: ByteArray,
|
||||||
|
val peerIv: ByteArray,
|
||||||
|
)
|
@ -0,0 +1,3 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
class Contact(val uuid: String, val publicKey: ByteArray, var name: String, var verified: Boolean, var seen: Boolean)
|
@ -0,0 +1,39 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import sushi.hardcore.aira.R
|
||||||
|
|
||||||
|
open class FileTransfer(val fileName: String, val fileSize: Long) {
|
||||||
|
var transferred = 0
|
||||||
|
lateinit var notificationBuilder: NotificationCompat.Builder
|
||||||
|
var notificationId = -1
|
||||||
|
|
||||||
|
fun updateNotificationProgress(notificationManager: NotificationManagerCompat) {
|
||||||
|
notificationBuilder.setProgress(fileSize.toInt(), transferred, false)
|
||||||
|
notificationManager.notify(notificationId, notificationBuilder.build())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun endNotification(context: Context, notificationManager: NotificationManagerCompat, sessionName: String, string: Int) {
|
||||||
|
notificationManager.notify(
|
||||||
|
notificationId,
|
||||||
|
NotificationCompat.Builder(context, AIRAService.FILE_TRANSFER_NOTIFICATION_CHANNEL_ID)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
||||||
|
.setSmallIcon(R.drawable.ic_launcher)
|
||||||
|
.setContentTitle(sessionName)
|
||||||
|
.setContentText(context.getString(string))
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onAborted(context: Context, notificationManager: NotificationManagerCompat, sessionName: String) {
|
||||||
|
if (::notificationBuilder.isInitialized) {
|
||||||
|
endNotification(context, notificationManager, sessionName, R.string.transfer_aborted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onCompleted(context: Context, notificationManager: NotificationManagerCompat, sessionName: String) {
|
||||||
|
endNotification(context, notificationManager, sessionName, R.string.transfer_completed)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
class HandshakeKeys(
|
||||||
|
val localKey: ByteArray,
|
||||||
|
val localIv: ByteArray,
|
||||||
|
val localHandshakeTrafficSecret: ByteArray,
|
||||||
|
val peerKey: ByteArray,
|
||||||
|
val peerIv: ByteArray,
|
||||||
|
val peerHandshakeTrafficSecret: ByteArray,
|
||||||
|
val handshakeSecret: ByteArray
|
||||||
|
)
|
@ -0,0 +1,33 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import androidx.core.app.RemoteInput
|
||||||
|
|
||||||
|
class NotificationBroadcastReceiver: BroadcastReceiver() {
|
||||||
|
companion object {
|
||||||
|
const val ACTION_MARK_READ = "mark_read"
|
||||||
|
const val ACTION_CANCEL_FILE_TRANSFER = "cancel"
|
||||||
|
const val ACTION_REPLY = "reply"
|
||||||
|
const val KEY_TEXT_REPLY = "key_text_reply"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReceive(context: Context?, intent: Intent) {
|
||||||
|
intent.getBundleExtra("bundle")?.let { bundle ->
|
||||||
|
(bundle.getBinder("binder") as AIRAService.AIRABinder?)?.let { binder ->
|
||||||
|
val sessionId = bundle.getInt("sessionId")
|
||||||
|
val airaService = binder.getService()
|
||||||
|
when (intent.action) {
|
||||||
|
ACTION_MARK_READ -> airaService.setSeen(sessionId, true)
|
||||||
|
ACTION_CANCEL_FILE_TRANSFER -> airaService.cancelFileTransfer(sessionId)
|
||||||
|
ACTION_REPLY -> RemoteInput.getResultsFromIntent(intent)?.getString(KEY_TEXT_REPLY)?.let { reply ->
|
||||||
|
airaService.sendTo(sessionId, Protocol.newMessage(reply))
|
||||||
|
airaService.setSeen(sessionId, true)
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
class NotificationIdManager {
|
||||||
|
|
||||||
|
private enum class NotificationType {
|
||||||
|
MESSAGE,
|
||||||
|
FILE_TRANSFER
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class Notification(
|
||||||
|
val sessionId: Int,
|
||||||
|
val type: NotificationType
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
private val notificationIds = mutableMapOf<Int, Notification>()
|
||||||
|
private var lastNotificationId = 1 //got some bugs when starting before 1
|
||||||
|
|
||||||
|
private fun registerNewId(sessionId: Int, type: NotificationType): Int {
|
||||||
|
lastNotificationId++
|
||||||
|
notificationIds[lastNotificationId] = Notification(sessionId, type)
|
||||||
|
return lastNotificationId
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getMessageNotificationId(sessionId: Int): Int {
|
||||||
|
for ((id, notification) in notificationIds) {
|
||||||
|
if (notification.sessionId == sessionId) {
|
||||||
|
if (notification.type == NotificationType.MESSAGE) {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return registerNewId(sessionId, NotificationType.MESSAGE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getFileTransferNotificationId(sessionId: Int): Int {
|
||||||
|
for ((id, notification) in notificationIds) {
|
||||||
|
if (notification.sessionId == sessionId) {
|
||||||
|
if (notification.type == NotificationType.FILE_TRANSFER) {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return registerNewId(sessionId, NotificationType.FILE_TRANSFER)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
|
||||||
|
class Protocol {
|
||||||
|
companion object {
|
||||||
|
const val MESSAGE: Byte = 0x00
|
||||||
|
const val ASK_NAME: Byte = 0x01
|
||||||
|
const val TELL_NAME: Byte = 0x02
|
||||||
|
const val FILE: Byte = 0x03
|
||||||
|
const val ASK_LARGE_FILE: Byte = 0x04
|
||||||
|
const val ACCEPT_LARGE_FILE: Byte = 0x05
|
||||||
|
const val LARGE_FILE_CHUNK: Byte = 0x06
|
||||||
|
const val ACK_CHUNK: Byte = 0x07
|
||||||
|
const val ABORT_FILE_TRANSFER: Byte = 0x08
|
||||||
|
|
||||||
|
fun askName(): ByteArray {
|
||||||
|
return byteArrayOf(ASK_NAME)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun tellName(name: String): ByteArray {
|
||||||
|
return byteArrayOf(TELL_NAME)+name.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun newMessage(msg: String): ByteArray {
|
||||||
|
return byteArrayOf(MESSAGE)+msg.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun newFile(fileName: String, buffer: ByteArray): ByteArray {
|
||||||
|
return byteArrayOf(FILE)+ByteBuffer.allocate(2).putShort(fileName.length.toShort()).array()+fileName.toByteArray()+buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
fun askLargeFile(fileSize: Long, fileName: String): ByteArray {
|
||||||
|
return byteArrayOf(ASK_LARGE_FILE)+ByteBuffer.allocate(8).putLong(fileSize).array()+fileName.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun acceptLargeFile(): ByteArray {
|
||||||
|
return byteArrayOf(ACCEPT_LARGE_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun abortFileTransfer(): ByteArray {
|
||||||
|
return byteArrayOf(ABORT_FILE_TRANSFER)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ackChunk(): ByteArray {
|
||||||
|
return byteArrayOf(ACK_CHUNK)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import sushi.hardcore.aira.R
|
||||||
|
import sushi.hardcore.aira.utils.FileUtils
|
||||||
|
import java.io.OutputStream
|
||||||
|
|
||||||
|
class ReceiveFileTransfer(
|
||||||
|
fileName: String,
|
||||||
|
fileSize: Long,
|
||||||
|
private val onAccepted: (fileTransfer: ReceiveFileTransfer) -> Unit,
|
||||||
|
private val onAborted: () -> Unit,
|
||||||
|
): FileTransfer(fileName, fileSize) {
|
||||||
|
var shouldAsk = true
|
||||||
|
var outputStream: OutputStream? = null
|
||||||
|
|
||||||
|
@SuppressLint("SetTextI18n")
|
||||||
|
fun ask(activity: AppCompatActivity, senderName: String) {
|
||||||
|
val dialogView = activity.layoutInflater.inflate(R.layout.dialog_ask_file, null)
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_title).text = activity.getString(R.string.want_to_send_a_file, senderName, ":")
|
||||||
|
dialogView.findViewById<TextView>(R.id.text_file_info).text = fileName+" ("+FileUtils.formatSize(fileSize)+")"
|
||||||
|
AlertDialog.Builder(activity)
|
||||||
|
.setTitle(R.string.download_file_request)
|
||||||
|
.setView(dialogView)
|
||||||
|
.setCancelable(false)
|
||||||
|
.setPositiveButton(R.string.download) { _, _ ->
|
||||||
|
outputStream = FileUtils.openFileForDownload(activity, fileName)
|
||||||
|
if (outputStream == null) {
|
||||||
|
onAborted()
|
||||||
|
} else {
|
||||||
|
onAccepted(this)
|
||||||
|
}
|
||||||
|
shouldAsk = false
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.refuse) { _, _ ->
|
||||||
|
onAborted()
|
||||||
|
shouldAsk = false
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
class SendFileTransfer(
|
||||||
|
fileName: String,
|
||||||
|
fileSize: Long,
|
||||||
|
val inputStream: InputStream
|
||||||
|
): FileTransfer(fileName, fileSize) {
|
||||||
|
var nextChunk: ByteArray? = null
|
||||||
|
val msgQueue = mutableListOf<ByteArray>()
|
||||||
|
}
|
@ -0,0 +1,275 @@
|
|||||||
|
package sushi.hardcore.aira.background_service
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import net.i2p.crypto.eddsa.EdDSAEngine
|
||||||
|
import net.i2p.crypto.eddsa.EdDSAPublicKey
|
||||||
|
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable
|
||||||
|
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
|
||||||
|
import org.whispersystems.curve25519.Curve25519
|
||||||
|
import sushi.hardcore.aira.AIRADatabase
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.channels.*
|
||||||
|
import java.nio.channels.spi.SelectorProvider
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.security.SecureRandom
|
||||||
|
import javax.crypto.AEADBadTagException
|
||||||
|
import javax.crypto.BadPaddingException
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
import javax.crypto.spec.SecretKeySpec
|
||||||
|
import kotlin.experimental.xor
|
||||||
|
|
||||||
|
class Session(private val socket: SocketChannel, val outgoing: Boolean): SelectableChannel() {
|
||||||
|
private external fun deriveHandshakeKeys(sharedSecret: ByteArray, handshakeHash: ByteArray, iAmBob: Boolean): HandshakeKeys
|
||||||
|
private external fun sign(input: ByteArray): ByteArray
|
||||||
|
private external fun computeHandshakeFinished(localHandshakeTrafficSecret: ByteArray, handshakeHash: ByteArray): ByteArray
|
||||||
|
private external fun verifyHandshakeFinished(peerHandshakeFinished: ByteArray, peerHandshakeTrafficSecret: ByteArray, handshakeHash: ByteArray): Boolean
|
||||||
|
private external fun deriveApplicationKeys(handshakeSecret: ByteArray, handshakeHash: ByteArray, iAmBob: Boolean): ApplicationKeys
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val RANDOM_LEN = 64
|
||||||
|
private const val PUBLIC_KEY_LEN = 32
|
||||||
|
private const val SIGNATURE_LEN = 64
|
||||||
|
private const val AES_TAG_LEN = 16
|
||||||
|
private const val IV_LEN = 12
|
||||||
|
private const val HASH_OUTPUT_LEN = 48
|
||||||
|
private const val handshakeBufferLen = (2*(RANDOM_LEN+PUBLIC_KEY_LEN))+SIGNATURE_LEN+AES_TAG_LEN
|
||||||
|
private const val CIPHER_TYPE = "AES/GCM/NoPadding"
|
||||||
|
private const val MESSAGE_LEN_LEN = 4
|
||||||
|
private const val PADDED_MAX_SIZE = 32768000
|
||||||
|
private const val MAX_RECV_SIZE = MESSAGE_LEN_LEN + PADDED_MAX_SIZE + AES_TAG_LEN
|
||||||
|
}
|
||||||
|
|
||||||
|
private val prng = SecureRandom()
|
||||||
|
private val handshakeSentBuff = ByteArrayOutputStream(handshakeBufferLen)
|
||||||
|
private val handshakeRecvBuff = ByteArrayOutputStream(handshakeBufferLen)
|
||||||
|
private val peerCipher = Cipher.getInstance(CIPHER_TYPE)
|
||||||
|
private val localCipher = Cipher.getInstance(CIPHER_TYPE)
|
||||||
|
private var peerCounter = 0L
|
||||||
|
private var localCounter = 0L
|
||||||
|
private lateinit var applicationKeys: ApplicationKeys
|
||||||
|
lateinit var peerPublicKey: ByteArray
|
||||||
|
val ip: String = socket.socket().inetAddress.hostAddress
|
||||||
|
|
||||||
|
private fun handshakeWrite(buffer: ByteArray) {
|
||||||
|
writeAll(buffer)
|
||||||
|
handshakeSentBuff.write(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handshakeRead(buffer: ByteBuffer): Boolean {
|
||||||
|
return if (socket.read(buffer) == buffer.position()) {
|
||||||
|
handshakeRecvBuff.write(buffer.array())
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private fun handshakeRead(buffer: ByteArray): Boolean {
|
||||||
|
return handshakeRead(ByteBuffer.wrap(buffer))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hashHandshake(iAmBob: Boolean): ByteArray {
|
||||||
|
MessageDigest.getInstance("SHA-384").apply {
|
||||||
|
if (iAmBob) {
|
||||||
|
update(handshakeSentBuff.toByteArray())
|
||||||
|
update(handshakeRecvBuff.toByteArray())
|
||||||
|
} else {
|
||||||
|
update(handshakeRecvBuff.toByteArray())
|
||||||
|
update(handshakeSentBuff.toByteArray())
|
||||||
|
}
|
||||||
|
return digest()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun amIBob(): Boolean {
|
||||||
|
val s = handshakeSentBuff.toByteArray()
|
||||||
|
val r = handshakeRecvBuff.toByteArray()
|
||||||
|
for (i in s.indices) {
|
||||||
|
if (s[i] != r[i]) {
|
||||||
|
return s[i].toInt() and 0xff < r[i].toInt() and 0xff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw SecurityException("Handshake buffers are identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ivToNonce(iv: ByteArray, counter: Long): ByteArray {
|
||||||
|
val nonce = ByteArray(IV_LEN-Long.SIZE_BYTES)+ByteBuffer.allocate(Long.SIZE_BYTES).putLong(counter).array()
|
||||||
|
for (i in nonce.indices) {
|
||||||
|
nonce[i] = nonce[i] xor iv[i]
|
||||||
|
}
|
||||||
|
return nonce
|
||||||
|
}
|
||||||
|
|
||||||
|
fun doHandshake(): Boolean {
|
||||||
|
val randomBuffer = ByteArray(RANDOM_LEN)
|
||||||
|
prng.nextBytes(randomBuffer)
|
||||||
|
val curve25519Cipher = Curve25519.getInstance(Curve25519.BEST)
|
||||||
|
val keypair = curve25519Cipher.generateKeyPair()
|
||||||
|
handshakeWrite(randomBuffer+keypair.publicKey)
|
||||||
|
|
||||||
|
var recvBuffer = ByteBuffer.allocate(RANDOM_LEN+PUBLIC_KEY_LEN)
|
||||||
|
if (handshakeRead(recvBuffer)) {
|
||||||
|
val peerEphemeralPublicKey = recvBuffer.array().sliceArray(RANDOM_LEN until recvBuffer.capacity())
|
||||||
|
val sharedSecret = curve25519Cipher.calculateAgreement(peerEphemeralPublicKey, keypair.privateKey)
|
||||||
|
val iAmBob = amIBob() //mutual consensus for keys attribution
|
||||||
|
var handshakeHash = hashHandshake(iAmBob)
|
||||||
|
val handshakeKeys = deriveHandshakeKeys(sharedSecret, handshakeHash, iAmBob)
|
||||||
|
|
||||||
|
prng.nextBytes(randomBuffer)
|
||||||
|
handshakeWrite(randomBuffer)
|
||||||
|
if (handshakeRead(randomBuffer)) {
|
||||||
|
val localCipher = Cipher.getInstance(CIPHER_TYPE)
|
||||||
|
localCipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(handshakeKeys.localKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, ivToNonce(handshakeKeys.localIv, 0)))
|
||||||
|
handshakeWrite(localCipher.doFinal(AIRADatabase.getIdentityPublicKey()+sign(keypair.publicKey)))
|
||||||
|
|
||||||
|
recvBuffer = ByteBuffer.allocate(PUBLIC_KEY_LEN+SIGNATURE_LEN+AES_TAG_LEN)
|
||||||
|
if (handshakeRead(recvBuffer)) {
|
||||||
|
val peerCipher = Cipher.getInstance(CIPHER_TYPE)
|
||||||
|
peerCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(handshakeKeys.peerKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, ivToNonce(handshakeKeys.peerIv, 0)))
|
||||||
|
val plainText: ByteArray
|
||||||
|
try {
|
||||||
|
plainText = peerCipher.doFinal(recvBuffer.array())
|
||||||
|
} catch (e: BadPaddingException) {
|
||||||
|
Log.w("BadPaddingException", ip)
|
||||||
|
return false
|
||||||
|
} catch (e: AEADBadTagException) {
|
||||||
|
Log.w("AEADBadTagException", ip)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
peerPublicKey = plainText.sliceArray(0 until PUBLIC_KEY_LEN)
|
||||||
|
val signature = plainText.sliceArray(PUBLIC_KEY_LEN until plainText.size)
|
||||||
|
|
||||||
|
val edDSAEngine = EdDSAEngine().apply {
|
||||||
|
initVerify(EdDSAPublicKey(EdDSAPublicKeySpec(peerPublicKey, EdDSANamedCurveTable.ED_25519_CURVE_SPEC)))
|
||||||
|
}
|
||||||
|
if (edDSAEngine.verifyOneShot(peerEphemeralPublicKey, signature)) {
|
||||||
|
handshakeHash = hashHandshake(iAmBob)
|
||||||
|
val handshakeFinished = computeHandshakeFinished(handshakeKeys.localHandshakeTrafficSecret, handshakeHash)
|
||||||
|
writeAll(handshakeFinished)
|
||||||
|
val peerHandshakeFinished = ByteBuffer.allocate(HASH_OUTPUT_LEN)
|
||||||
|
socket.read(peerHandshakeFinished)
|
||||||
|
if (verifyHandshakeFinished(peerHandshakeFinished.array(), handshakeKeys.peerHandshakeTrafficSecret, handshakeHash)){
|
||||||
|
applicationKeys = deriveApplicationKeys(handshakeKeys.handshakeSecret, handshakeHash, iAmBob)
|
||||||
|
handshakeSentBuff.reset()
|
||||||
|
handshakeRecvBuff.reset()
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
Log.w("Handshake", "Final verification failed")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Log.w("Handshake", "Signature verification failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun randomPad(input: ByteArray): ByteArray {
|
||||||
|
val encodedLen = ByteBuffer.allocate(MESSAGE_LEN_LEN).putInt(input.size).array()
|
||||||
|
val msgLen = input.size + MESSAGE_LEN_LEN
|
||||||
|
var len = 1000
|
||||||
|
while (len < msgLen) {
|
||||||
|
len *= 2
|
||||||
|
}
|
||||||
|
val padding = ByteArray(len-msgLen)
|
||||||
|
prng.nextBytes(padding)
|
||||||
|
return encodedLen + input + padding
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unpad(input: ByteArray): ByteArray {
|
||||||
|
val messageLen = ByteBuffer.wrap(input.sliceArray(0..MESSAGE_LEN_LEN)).int
|
||||||
|
return input.sliceArray(MESSAGE_LEN_LEN until MESSAGE_LEN_LEN+messageLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun writeAll(buffer: ByteArray) {
|
||||||
|
val byteBuffer = ByteBuffer.wrap(buffer)
|
||||||
|
while (byteBuffer.remaining() > 0) {
|
||||||
|
socket.write(byteBuffer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encrypt(plainText: ByteArray): ByteArray {
|
||||||
|
val padded = randomPad(plainText)
|
||||||
|
val rawMsgLen = ByteBuffer.allocate(MESSAGE_LEN_LEN).putInt(padded.size).array()
|
||||||
|
val nonce = ivToNonce(applicationKeys.localIv, localCounter)
|
||||||
|
localCounter++
|
||||||
|
localCipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(applicationKeys.localKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, nonce))
|
||||||
|
localCipher.updateAAD(rawMsgLen)
|
||||||
|
return rawMsgLen+localCipher.doFinal(padded)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encryptAndSend(plainText: ByteArray) {
|
||||||
|
writeAll(encrypt(plainText))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
|
private fun readAll(buffer: ByteBuffer): Boolean {
|
||||||
|
while (buffer.position() != buffer.capacity()) {
|
||||||
|
try {
|
||||||
|
if (socket.read(buffer) < 0) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
} catch (e: ClosedChannelException) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun receiveAndDecrypt(): ByteArray? {
|
||||||
|
val rawMessageLen = ByteBuffer.allocate(MESSAGE_LEN_LEN)
|
||||||
|
if (readAll(rawMessageLen)) {
|
||||||
|
rawMessageLen.position(0)
|
||||||
|
val messageLen = rawMessageLen.int + AES_TAG_LEN
|
||||||
|
if (messageLen in 1..MAX_RECV_SIZE) {
|
||||||
|
val cipherText = ByteBuffer.allocate(messageLen)
|
||||||
|
if (readAll(cipherText)) {
|
||||||
|
val nonce = ivToNonce(applicationKeys.peerIv, peerCounter)
|
||||||
|
peerCounter++
|
||||||
|
peerCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(applicationKeys.peerKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, nonce))
|
||||||
|
rawMessageLen.position(0)
|
||||||
|
peerCipher.updateAAD(rawMessageLen)
|
||||||
|
try {
|
||||||
|
return unpad(peerCipher.doFinal(cipherText.array()))
|
||||||
|
} catch (e: AEADBadTagException) {
|
||||||
|
Log.w("AEADBadTagException", ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Log.w("Message too large", "$messageLen from $ip")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun implCloseChannel() {
|
||||||
|
socket.close()
|
||||||
|
}
|
||||||
|
override fun provider(): SelectorProvider {
|
||||||
|
return socket.provider()
|
||||||
|
}
|
||||||
|
override fun validOps(): Int {
|
||||||
|
return socket.validOps()
|
||||||
|
}
|
||||||
|
override fun isRegistered(): Boolean {
|
||||||
|
return socket.isRegistered
|
||||||
|
}
|
||||||
|
override fun keyFor(sel: Selector?): SelectionKey {
|
||||||
|
return socket.keyFor(sel)
|
||||||
|
}
|
||||||
|
override fun register(sel: Selector?, ops: Int, att: Any?): SelectionKey {
|
||||||
|
return socket.register(sel, ops, att)
|
||||||
|
}
|
||||||
|
override fun configureBlocking(block: Boolean): SelectableChannel {
|
||||||
|
return socket.configureBlocking(block)
|
||||||
|
}
|
||||||
|
override fun isBlocking(): Boolean {
|
||||||
|
return socket.isBlocking
|
||||||
|
}
|
||||||
|
override fun blockingLock(): Any {
|
||||||
|
return socket.blockingLock()
|
||||||
|
}
|
||||||
|
}
|
52
app/src/main/java/sushi/hardcore/aira/utils/FileUtils.kt
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package sushi.hardcore.aira.utils
|
||||||
|
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import android.webkit.MimeTypeMap
|
||||||
|
import java.io.File
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.text.DecimalFormat
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.*
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.log10
|
||||||
|
|
||||||
|
object FileUtils {
|
||||||
|
private val units = arrayOf("B", "kB", "MB", "GB", "TB")
|
||||||
|
fun formatSize(size: Long): String {
|
||||||
|
if (size <= 0) {
|
||||||
|
return "0 B"
|
||||||
|
}
|
||||||
|
val digitGroups = (log10(size.toDouble()) / log10(1000.0)).toInt()
|
||||||
|
return DecimalFormat("#,##0.#").format(size / 1000.0.pow(digitGroups.toDouble())
|
||||||
|
) + " " + units[digitGroups]
|
||||||
|
}
|
||||||
|
|
||||||
|
fun openFileForDownload(context: Context, fileName: String): OutputStream? {
|
||||||
|
val fileExtension = fileName.substringAfterLast(".")
|
||||||
|
val dateExtension = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date())
|
||||||
|
val datedFilename = if (fileName.contains(".")) {
|
||||||
|
val basename = fileName.substringBeforeLast(".")
|
||||||
|
"""${basename}_$dateExtension.$fileExtension"""
|
||||||
|
} else {
|
||||||
|
fileName + "_" + dateExtension
|
||||||
|
}
|
||||||
|
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
|
||||||
|
context.contentResolver.insert(
|
||||||
|
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(MediaStore.Images.Media.TITLE, datedFilename)
|
||||||
|
put(MediaStore.Images.Media.DISPLAY_NAME, datedFilename)
|
||||||
|
put(MediaStore.Images.Media.MIME_TYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension))
|
||||||
|
}
|
||||||
|
)?.let {
|
||||||
|
context.contentResolver.openOutputStream(it)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
@Suppress("Deprecation")
|
||||||
|
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), datedFilename).outputStream()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
12
app/src/main/java/sushi/hardcore/aira/utils/StringUtils.kt
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package sushi.hardcore.aira.utils
|
||||||
|
|
||||||
|
object StringUtils {
|
||||||
|
fun beautifyFingerprint(fingerprint: String): String {
|
||||||
|
val newFingerprint = StringBuilder(fingerprint.length+7)
|
||||||
|
for (i in 0..fingerprint.length-8 step 4) {
|
||||||
|
newFingerprint.append(fingerprint.slice(i until i+4)+" ")
|
||||||
|
}
|
||||||
|
newFingerprint.append(fingerprint.slice(fingerprint.length-4 until fingerprint.length))
|
||||||
|
return newFingerprint.toString()
|
||||||
|
}
|
||||||
|
}
|
38
app/src/main/java/sushi/hardcore/aira/widgets/TextAvatar.kt
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package sushi.hardcore.aira.widgets
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.widget.RelativeLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import sushi.hardcore.aira.R
|
||||||
|
|
||||||
|
class TextAvatar @JvmOverloads constructor(
|
||||||
|
context: Context,
|
||||||
|
attrs: AttributeSet? = null,
|
||||||
|
defStyle: Int = 0
|
||||||
|
) : RelativeLayout(context, attrs, defStyle) {
|
||||||
|
|
||||||
|
private val view = LayoutInflater.from(context).inflate(R.layout.text_avatar, this, true)
|
||||||
|
|
||||||
|
init {
|
||||||
|
attrs?.let {
|
||||||
|
val typedArray = context.obtainStyledAttributes(it, R.styleable.TextAvatar)
|
||||||
|
for (i in 0..typedArray.indexCount) {
|
||||||
|
val attr = typedArray.getIndex(i)
|
||||||
|
if (attr == R.styleable.TextAvatar_textSize) {
|
||||||
|
val textSize = typedArray.getDimension(attr, -1F)
|
||||||
|
if (textSize != -1F) {
|
||||||
|
view.findViewById<TextView>(R.id.text_letter).textSize = textSize
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
typedArray.recycle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setLetterFrom(name: String) {
|
||||||
|
view.findViewById<TextView>(R.id.text_letter).text = name[0].toUpperCase().toString()
|
||||||
|
}
|
||||||
|
}
|
2
app/src/main/native/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
Cargo.lock
|
||||||
|
target
|
31
app/src/main/native/Cargo.toml
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
[package]
|
||||||
|
name = "aira"
|
||||||
|
version = "0.0.1"
|
||||||
|
authors = ["Hardcore Sushi <hardcore.sushi@disroot.org>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
[target.'cfg(target_os="android")'.dependencies]
|
||||||
|
jni = { version = "0.19", default-features = false }
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
crate-type = ["dylib"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
rand-8 = {package = "rand", version = "0.8.3"}
|
||||||
|
rand-7 = {package = "rand", version = "0.7.3"}
|
||||||
|
lazy_static = "1.4.0"
|
||||||
|
rusqlite = {version = "0.25.1", features = ["bundled"]}
|
||||||
|
ed25519-dalek = "1" #for singing
|
||||||
|
x25519-dalek = "1.1" #for shared secret
|
||||||
|
sha2 = "0.9.3"
|
||||||
|
hkdf = "0.11.0"
|
||||||
|
aes-gcm = "0.9.0" #PSEC
|
||||||
|
aes-gcm-siv = "0.10.0" #Database
|
||||||
|
hmac = "0.11.0"
|
||||||
|
hex = "0.4.3"
|
||||||
|
strum_macros = "0.20.1" #display enums
|
||||||
|
uuid = {version = "0.8", features = ["v4"]}
|
||||||
|
scrypt = "0.7.0"
|
||||||
|
zeroize = "1.2.0"
|
||||||
|
log = "0.4.14"
|
||||||
|
android_log = "0.1.3"
|
13
app/src/main/native/build.sh
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
if [ -z ${ANDROID_NDK_HOME+x} ]; then
|
||||||
|
echo "Error: \$ANDROID_NDK_HOME is not defined."
|
||||||
|
else
|
||||||
|
export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/:$PATH
|
||||||
|
declare -a androidABIs=("arm64-v8a" "armeabi-v7a")
|
||||||
|
declare -a targets=("aarch64-linux-android" "armv7-linux-androideabi")
|
||||||
|
for (( i=0; i < ${#targets[@]}; i++ )) do
|
||||||
|
cargo build --target ${targets[i]} --release
|
||||||
|
cp target/${targets[i]}/release/libaira.so ../jniLibs/${androidABIs[i]}/
|
||||||
|
done
|
||||||
|
fi
|
8
app/src/main/native/check.sh
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
if [ -z ${ANDROID_NDK_HOME+x} ]; then
|
||||||
|
echo "Error: \$ANDROID_NDK_HOME is not defined."
|
||||||
|
else
|
||||||
|
export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/:$PATH
|
||||||
|
cargo check --target aarch64-linux-android
|
||||||
|
fi
|
226
app/src/main/native/src/crypto.rs
Normal file
@ -0,0 +1,226 @@
|
|||||||
|
use std::convert::TryInto;
|
||||||
|
use hkdf::Hkdf;
|
||||||
|
use sha2::Sha384;
|
||||||
|
use hmac::{Hmac, Mac, NewMac};
|
||||||
|
use scrypt::{scrypt, Params};
|
||||||
|
use rand_8::{RngCore, rngs::OsRng};
|
||||||
|
use aes_gcm::{aead::Aead, NewAead, Nonce};
|
||||||
|
use aes_gcm_siv::Aes256GcmSiv;
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
use strum_macros::Display;
|
||||||
|
use crate::utils::*;
|
||||||
|
|
||||||
|
pub const HASH_OUTPUT_LEN: usize = 48; //SHA384
|
||||||
|
const KEY_LEN: usize = 16;
|
||||||
|
pub const IV_LEN: usize = 12;
|
||||||
|
pub const AES_TAG_LEN: usize = 16;
|
||||||
|
pub const SALT_LEN: usize = 32;
|
||||||
|
const PASSWORD_HASH_LEN: usize = 32;
|
||||||
|
pub const MASTER_KEY_LEN: usize = 32;
|
||||||
|
|
||||||
|
fn hkdf_expand_label(key: &[u8], label: &str, context: Option<&[u8]>, okm: &mut [u8]) {
|
||||||
|
let hkdf = Hkdf::<Sha384>::from_prk(key).unwrap();
|
||||||
|
//can't set info conditionnally because of different array size
|
||||||
|
match context {
|
||||||
|
Some(context) => {
|
||||||
|
let info = [&(label.len() as u32).to_be_bytes(), label.as_bytes(), &(context.len() as u32).to_be_bytes(), context];
|
||||||
|
hkdf.expand_multi_info(&info, okm).unwrap();
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let info = [&(label.len() as u32).to_be_bytes(), label.as_bytes()];
|
||||||
|
hkdf.expand_multi_info(&info, okm).unwrap();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HandshakeKeys {
|
||||||
|
pub local_key: [u8; KEY_LEN],
|
||||||
|
pub local_iv: [u8; IV_LEN],
|
||||||
|
pub local_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN],
|
||||||
|
pub peer_key: [u8; KEY_LEN],
|
||||||
|
pub peer_iv: [u8; IV_LEN],
|
||||||
|
pub peer_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN],
|
||||||
|
pub handshake_secret: [u8; HASH_OUTPUT_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HandshakeKeys {
|
||||||
|
pub fn derive_keys(shared_secret: [u8; 32], handshake_hash: [u8; HASH_OUTPUT_LEN], i_am_bob: bool) -> HandshakeKeys {
|
||||||
|
let (handshake_secret, _) = Hkdf::<Sha384>::extract(None, &shared_secret);
|
||||||
|
|
||||||
|
let local_label = "handshake".to_owned() + if i_am_bob {"i_am_bob"} else {"i_am_alice"};
|
||||||
|
let mut local_handshake_traffic_secret = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(handshake_secret.as_slice(), &local_label, Some(&handshake_hash), &mut local_handshake_traffic_secret);
|
||||||
|
|
||||||
|
let peer_label = "handshake".to_owned() + if i_am_bob {"i_am_alice"} else {"i_am_bob"};
|
||||||
|
let mut peer_handshake_traffic_secret = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(handshake_secret.as_slice(), &peer_label, Some(&handshake_hash), &mut peer_handshake_traffic_secret);
|
||||||
|
|
||||||
|
let mut local_handshake_key = [0; KEY_LEN];
|
||||||
|
hkdf_expand_label(&local_handshake_traffic_secret, "key", None, &mut local_handshake_key);
|
||||||
|
let mut local_handshake_iv = [0; IV_LEN];
|
||||||
|
hkdf_expand_label(&local_handshake_traffic_secret, "iv", None, &mut local_handshake_iv);
|
||||||
|
|
||||||
|
let mut peer_handshake_key = [0; KEY_LEN];
|
||||||
|
hkdf_expand_label(&peer_handshake_traffic_secret, "key", None, &mut peer_handshake_key);
|
||||||
|
let mut peer_handshake_iv = [0; IV_LEN];
|
||||||
|
hkdf_expand_label(&peer_handshake_traffic_secret,"iv", None, &mut peer_handshake_iv);
|
||||||
|
|
||||||
|
HandshakeKeys {
|
||||||
|
local_key: local_handshake_key,
|
||||||
|
local_iv: local_handshake_iv,
|
||||||
|
local_handshake_traffic_secret: local_handshake_traffic_secret,
|
||||||
|
peer_key: peer_handshake_key,
|
||||||
|
peer_iv: peer_handshake_iv,
|
||||||
|
peer_handshake_traffic_secret: peer_handshake_traffic_secret,
|
||||||
|
handshake_secret: to_array_48(handshake_secret.as_slice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ApplicationKeys {
|
||||||
|
pub local_key: [u8; KEY_LEN],
|
||||||
|
pub local_iv: [u8; IV_LEN],
|
||||||
|
pub peer_key: [u8; KEY_LEN],
|
||||||
|
pub peer_iv: [u8; IV_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationKeys {
|
||||||
|
pub fn derive_keys(handshake_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN], i_am_bob: bool) -> ApplicationKeys {
|
||||||
|
let mut derived_secret = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(&handshake_secret, "derived", None, &mut derived_secret);
|
||||||
|
let (master_secret, _) = Hkdf::<Sha384>::extract(Some(&derived_secret), b"");
|
||||||
|
|
||||||
|
let local_label = "application".to_owned() + if i_am_bob {"i_am_bob"} else {"i_am_alice"};
|
||||||
|
let mut local_application_traffic_secret = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(&master_secret, &local_label, Some(&handshake_hash), &mut local_application_traffic_secret);
|
||||||
|
|
||||||
|
let peer_label = "application".to_owned() + if i_am_bob {"i_am_alice"} else {"i_am_bob"};
|
||||||
|
let mut peer_application_traffic_secret = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(&master_secret, &peer_label, Some(&handshake_hash), &mut peer_application_traffic_secret);
|
||||||
|
|
||||||
|
let mut local_application_key = [0; KEY_LEN];
|
||||||
|
hkdf_expand_label(&local_application_traffic_secret, "key", None, &mut local_application_key);
|
||||||
|
let mut local_application_iv = [0; IV_LEN];
|
||||||
|
hkdf_expand_label(&local_application_traffic_secret, "iv", None, &mut local_application_iv);
|
||||||
|
|
||||||
|
let mut peer_application_key = [0; KEY_LEN];
|
||||||
|
hkdf_expand_label(&peer_application_traffic_secret, "key", None, &mut peer_application_key);
|
||||||
|
let mut peer_application_iv = [0; IV_LEN];
|
||||||
|
hkdf_expand_label(&peer_application_traffic_secret,"iv", None, &mut peer_application_iv);
|
||||||
|
|
||||||
|
ApplicationKeys {
|
||||||
|
local_key: local_application_key,
|
||||||
|
local_iv: local_application_iv,
|
||||||
|
peer_key: peer_application_key,
|
||||||
|
peer_iv: peer_application_iv,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn compute_handshake_finished(local_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN]) -> [u8; HASH_OUTPUT_LEN] {
|
||||||
|
let mut finished_key = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(&local_handshake_traffic_secret, "finished", None, &mut finished_key);
|
||||||
|
let mut hmac = Hmac::<Sha384>::new_from_slice(&finished_key).unwrap();
|
||||||
|
hmac.update(&handshake_hash);
|
||||||
|
hmac.finalize().into_bytes().as_slice().try_into().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify_handshake_finished(peer_handshake_finished: [u8; HASH_OUTPUT_LEN], peer_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN]) -> bool {
|
||||||
|
let mut peer_finished_key = [0; HASH_OUTPUT_LEN];
|
||||||
|
hkdf_expand_label(&peer_handshake_traffic_secret, "finished", None, &mut peer_finished_key);
|
||||||
|
let mut hmac = Hmac::<Sha384>::new_from_slice(&peer_finished_key).unwrap();
|
||||||
|
hmac.update(&handshake_hash);
|
||||||
|
hmac.verify(&peer_handshake_finished).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
pub fn generate_fingerprint(public_key: &[u8]) -> String {
|
||||||
|
let mut raw_fingerprint = [0; 16];
|
||||||
|
Hkdf::<Sha384>::new(None, public_key).expand(&[], &mut raw_fingerprint).unwrap();
|
||||||
|
hex::encode(raw_fingerprint).to_uppercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
pub fn generate_master_key() -> [u8; MASTER_KEY_LEN] {
|
||||||
|
let mut master_key = [0; MASTER_KEY_LEN];
|
||||||
|
OsRng.fill_bytes(&mut master_key);
|
||||||
|
master_key
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt_data(data: &[u8], master_key: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
if master_key.len() != MASTER_KEY_LEN {
|
||||||
|
return Err(CryptoError::InvalidLength);
|
||||||
|
}
|
||||||
|
let cipher = Aes256GcmSiv::new_from_slice(master_key).unwrap();
|
||||||
|
let mut iv = [0; IV_LEN];
|
||||||
|
OsRng.fill_bytes(&mut iv); //use it for IV for now
|
||||||
|
let mut cipher_text = iv.to_vec();
|
||||||
|
cipher_text.extend(cipher.encrypt(Nonce::from_slice(&iv), data).unwrap());
|
||||||
|
Ok(cipher_text)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Display, Debug, PartialEq, Eq)]
|
||||||
|
pub enum CryptoError {
|
||||||
|
DecryptionFailed,
|
||||||
|
InvalidLength
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt_data(data: &[u8], master_key: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
if data.len() <= IV_LEN || master_key.len() != MASTER_KEY_LEN {
|
||||||
|
return Err(CryptoError::InvalidLength);
|
||||||
|
}
|
||||||
|
let cipher = Aes256GcmSiv::new_from_slice(master_key).unwrap();
|
||||||
|
match cipher.decrypt(Nonce::from_slice(&data[..IV_LEN]), &data[IV_LEN..]) {
|
||||||
|
Ok(data) => {
|
||||||
|
Ok(data)
|
||||||
|
},
|
||||||
|
Err(_) => Err(CryptoError::DecryptionFailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scrypt_params() -> Params {
|
||||||
|
Params::new(16, 8, 1).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt_master_key(mut master_key: [u8; MASTER_KEY_LEN], password: &[u8]) -> (
|
||||||
|
[u8; SALT_LEN], //salt
|
||||||
|
[u8; IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN] //encrypted masterkey with IV
|
||||||
|
) {
|
||||||
|
let mut salt = [0; SALT_LEN];
|
||||||
|
OsRng.fill_bytes(&mut salt);
|
||||||
|
let mut password_hash = [0; PASSWORD_HASH_LEN];
|
||||||
|
scrypt(password, &salt, &scrypt_params(), &mut password_hash).unwrap();
|
||||||
|
let mut output = [0; IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN];
|
||||||
|
OsRng.fill_bytes(&mut output); //use it for IV for now
|
||||||
|
let cipher = Aes256GcmSiv::new_from_slice(&password_hash).unwrap();
|
||||||
|
let encrypted_master_key = cipher.encrypt(Nonce::from_slice(&output[..IV_LEN]), master_key.as_ref()).unwrap();
|
||||||
|
master_key.zeroize();
|
||||||
|
password_hash.zeroize();
|
||||||
|
encrypted_master_key.into_iter().enumerate().for_each(|i|{
|
||||||
|
output[IV_LEN+i.0] = i.1; //append encrypted master key to IV
|
||||||
|
});
|
||||||
|
(salt, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt_master_key(encrypted_master_key: &[u8], password: &[u8], salt: &[u8]) -> Result<[u8; MASTER_KEY_LEN], CryptoError> {
|
||||||
|
if encrypted_master_key.len() != IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN || salt.len() != SALT_LEN {
|
||||||
|
return Err(CryptoError::InvalidLength);
|
||||||
|
}
|
||||||
|
let mut password_hash = [0; PASSWORD_HASH_LEN];
|
||||||
|
scrypt(password, salt, &scrypt_params(), &mut password_hash).unwrap();
|
||||||
|
let cipher = Aes256GcmSiv::new_from_slice(&password_hash).unwrap();
|
||||||
|
let result = match cipher.decrypt(Nonce::from_slice(&encrypted_master_key[..IV_LEN]), &encrypted_master_key[IV_LEN..]) {
|
||||||
|
Ok(master_key) => {
|
||||||
|
if master_key.len() == MASTER_KEY_LEN {
|
||||||
|
Ok(master_key.try_into().unwrap())
|
||||||
|
} else {
|
||||||
|
return Err(CryptoError::InvalidLength)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => Err(CryptoError::DecryptionFailed)
|
||||||
|
};
|
||||||
|
password_hash.zeroize();
|
||||||
|
result
|
||||||
|
}
|
469
app/src/main/native/src/identity.rs
Normal file
@ -0,0 +1,469 @@
|
|||||||
|
use std::{convert::TryInto, path::Path};
|
||||||
|
use crypto::CryptoError;
|
||||||
|
use ed25519_dalek::{Keypair, Signer, SIGNATURE_LENGTH, PUBLIC_KEY_LENGTH};
|
||||||
|
use rusqlite::{Connection, params};
|
||||||
|
use utils::to_uuid_bytes;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
use crate::{crypto, key_value_table::KeyValueTable, print_error, utils};
|
||||||
|
|
||||||
|
const DB_NAME: &str = "AIRA.db";
|
||||||
|
const MAIN_TABLE: &str = "main";
|
||||||
|
const CONTACTS_TABLE: &str = "contacts";
|
||||||
|
const FILES_TABLE: &str = "files";
|
||||||
|
|
||||||
|
const DATABASE_CORRUPED_ERROR: &str = "Database corrupted";
|
||||||
|
|
||||||
|
struct DBKeys;
|
||||||
|
impl<'a> DBKeys {
|
||||||
|
pub const NAME: &'a str = "name";
|
||||||
|
pub const KEYPAIR: &'a str = "keypair";
|
||||||
|
pub const SALT: &'a str = "salt";
|
||||||
|
pub const MASTER_KEY: &'a str = "master_key";
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bool_to_byte(b: bool) -> u8 {
|
||||||
|
if b { 75 } else { 30 } //completely arbitrary values
|
||||||
|
}
|
||||||
|
|
||||||
|
fn byte_to_bool(b: u8) -> Result<bool, ()> {
|
||||||
|
if b == 75 {
|
||||||
|
Ok(true)
|
||||||
|
} else if b == 30 {
|
||||||
|
Ok(false)
|
||||||
|
} else {
|
||||||
|
Err(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_database_path(database_folder: &str) -> String {
|
||||||
|
Path::new(database_folder).join(DB_NAME).to_str().unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EncryptedIdentity {
|
||||||
|
name: String,
|
||||||
|
encrypted_keypair: Vec<u8>,
|
||||||
|
salt: Vec<u8>,
|
||||||
|
encrypted_master_key: Vec<u8>
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Contact {
|
||||||
|
pub uuid: Uuid,
|
||||||
|
pub public_key: [u8; PUBLIC_KEY_LENGTH],
|
||||||
|
pub name: String,
|
||||||
|
pub verified: bool,
|
||||||
|
pub seen: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Identity {
|
||||||
|
pub name: String,
|
||||||
|
keypair: Keypair,
|
||||||
|
pub master_key: [u8; crypto::MASTER_KEY_LEN],
|
||||||
|
database_folder: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Identity {
|
||||||
|
|
||||||
|
pub fn sign(&self, input: &[u8]) -> [u8; SIGNATURE_LENGTH] {
|
||||||
|
self.keypair.sign(input).to_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_public_key(&self) -> [u8; PUBLIC_KEY_LENGTH] {
|
||||||
|
self.keypair.public.to_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_database_path(&self) -> String {
|
||||||
|
get_database_path(&self.database_folder)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_contact(&self, name: String, public_key: [u8; PUBLIC_KEY_LENGTH]) -> Result<Contact, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
db.execute(&("CREATE TABLE IF NOT EXISTS ".to_owned()+CONTACTS_TABLE+"(uuid BLOB PRIMARY KEY, name BLOB, key BLOB, verified BLOB, seen BLOB)"), [])?;
|
||||||
|
let contact_uuid = Uuid::new_v4();
|
||||||
|
let encrypted_name = crypto::encrypt_data(name.as_bytes(), &self.master_key).unwrap();
|
||||||
|
let encrypted_public_key = crypto::encrypt_data(&public_key, &self.master_key).unwrap();
|
||||||
|
let encrypted_verified = crypto::encrypt_data(&[bool_to_byte(false)], &self.master_key).unwrap();
|
||||||
|
let encrypted_seen = crypto::encrypt_data(&[bool_to_byte(true)], &self.master_key).unwrap();
|
||||||
|
db.execute(&("INSERT INTO ".to_owned()+CONTACTS_TABLE+" (uuid, name, key, verified, seen) VALUES (?1, ?2, ?3, ?4, ?5)"), params![&contact_uuid.as_bytes()[..], encrypted_name, encrypted_public_key, encrypted_verified, encrypted_seen])?;
|
||||||
|
Ok(Contact {
|
||||||
|
uuid: contact_uuid,
|
||||||
|
public_key: public_key,
|
||||||
|
name: name,
|
||||||
|
verified: false,
|
||||||
|
seen: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_contact(&self, uuid: &Uuid) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
self.delete_conversation(uuid)?;
|
||||||
|
db.execute(&("DELETE FROM ".to_owned()+CONTACTS_TABLE+" WHERE uuid=?"), [&uuid.as_bytes()[..]])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_verified(&self, uuid: &Uuid) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
let encrypted_verified = crypto::encrypt_data(&[bool_to_byte(true)], &self.master_key).unwrap();
|
||||||
|
db.execute(&format!("UPDATE {} SET verified=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_verified.as_slice(), &uuid.as_bytes()[..]])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn change_contact_name(&self, uuid: &Uuid, new_name: &str) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
let encrypted_name = crypto::encrypt_data(new_name.as_bytes(), &self.master_key).unwrap();
|
||||||
|
db.execute(&format!("UPDATE {} SET name=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_name.as_slice(), uuid.as_bytes()])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_contact_seen(&self, uuid: &Uuid, seen: bool) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
let encrypted_seen = crypto::encrypt_data(&[bool_to_byte(seen)], &self.master_key).unwrap();
|
||||||
|
db.execute(&format!("UPDATE {} SET seen=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_seen.as_slice(), uuid.as_bytes()])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_contacts(&self) -> Option<Vec<Contact>> {
|
||||||
|
match Connection::open(self.get_database_path()) {
|
||||||
|
Ok(db) => {
|
||||||
|
match db.prepare(&("SELECT uuid, name, key, verified, seen FROM ".to_owned()+CONTACTS_TABLE)) {
|
||||||
|
Ok(mut stmt) => {
|
||||||
|
let mut rows = stmt.query([]).unwrap();
|
||||||
|
let mut contacts = Vec::new();
|
||||||
|
while let Some(row) = rows.next().unwrap() {
|
||||||
|
let encrypted_public_key: Vec<u8> = row.get(2).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_public_key.as_slice(), &self.master_key) {
|
||||||
|
Ok(public_key) => {
|
||||||
|
if public_key.len() == PUBLIC_KEY_LENGTH {
|
||||||
|
let encrypted_name: Vec<u8> = row.get(1).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_name.as_slice(), &self.master_key) {
|
||||||
|
Ok(name) => {
|
||||||
|
let encrypted_verified: Vec<u8> = row.get(3).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_verified.as_slice(), &self.master_key) {
|
||||||
|
Ok(verified) => {
|
||||||
|
let encrypted_seen: Vec<u8> = row.get(4).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_seen.as_slice(), &self.master_key) {
|
||||||
|
Ok(seen) => {
|
||||||
|
let uuid: Vec<u8> = row.get(0).unwrap();
|
||||||
|
match to_uuid_bytes(&uuid) {
|
||||||
|
Some(uuid_bytes) => {
|
||||||
|
contacts.push(Contact {
|
||||||
|
uuid: Uuid::from_bytes(uuid_bytes),
|
||||||
|
public_key: public_key.try_into().unwrap(),
|
||||||
|
name: std::str::from_utf8(name.as_slice()).unwrap().to_owned(),
|
||||||
|
verified: byte_to_bool(verified[0]).unwrap(),
|
||||||
|
seen: byte_to_bool(seen[0]).unwrap(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
print_error!("Invalid public key length: database corrupted");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(contacts)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_temporary_files(&self) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
db.execute(&format!("DELETE FROM {} WHERE contact_uuid IS NULL", FILES_TABLE), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_file(&self, uuid: Uuid) -> Option<Vec<u8>> {
|
||||||
|
match Connection::open(self.get_database_path()) {
|
||||||
|
Ok(db) => {
|
||||||
|
match db.prepare(&format!("SELECT uuid, data FROM \"{}\"", FILES_TABLE)) {
|
||||||
|
Ok(mut stmt) => {
|
||||||
|
let mut rows = stmt.query([]).unwrap();
|
||||||
|
while let Some(row) = rows.next().unwrap() {
|
||||||
|
let encrypted_uuid: Vec<u8> = row.get(0).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_uuid.as_slice(), &self.master_key){
|
||||||
|
Ok(test_uuid) => {
|
||||||
|
if test_uuid == uuid.as_bytes() {
|
||||||
|
let encrypted_data: Vec<u8> = row.get(1).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_data.as_slice(), &self.master_key) {
|
||||||
|
Ok(data) => return Some(data),
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store_file(&self, contact_uuid: Option<Uuid>, data: &[u8]) -> Result<Uuid, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
db.execute(&format!("CREATE TABLE IF NOT EXISTS \"{}\" (contact_uuid BLOB, uuid BLOB, data BLOB)", FILES_TABLE), [])?;
|
||||||
|
let file_uuid = Uuid::new_v4();
|
||||||
|
let encrypted_uuid = crypto::encrypt_data(file_uuid.as_bytes(), &self.master_key).unwrap();
|
||||||
|
let encrypted_data = crypto::encrypt_data(data, &self.master_key).unwrap();
|
||||||
|
let query = format!("INSERT INTO \"{}\" (contact_uuid, uuid, data) VALUES (?1, ?2, ?3)", FILES_TABLE);
|
||||||
|
match contact_uuid {
|
||||||
|
Some(uuid) => db.execute(&query, params![&uuid.as_bytes()[..], &encrypted_uuid, &encrypted_data])?,
|
||||||
|
None => db.execute(&query, params![None as Option<Vec<u8>>, &encrypted_uuid, &encrypted_data])?
|
||||||
|
};
|
||||||
|
Ok(file_uuid)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store_msg(&self, contact_uuid: &Uuid, outgoing: bool, data: &[u8]) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
db.execute(&format!("CREATE TABLE IF NOT EXISTS \"{}\" (outgoing BLOB, data BLOB)", contact_uuid), [])?;
|
||||||
|
let outgoing_byte: u8 = bool_to_byte(outgoing);
|
||||||
|
let encrypted_outgoing = crypto::encrypt_data(&[outgoing_byte], &self.master_key).unwrap();
|
||||||
|
let encrypted_data = crypto::encrypt_data(data, &self.master_key).unwrap();
|
||||||
|
db.execute(&format!("INSERT INTO \"{}\" (outgoing, data) VALUES (?1, ?2)", contact_uuid), params![encrypted_outgoing, encrypted_data])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_msgs(&self, contact_uuid: &Uuid, offset: usize, mut count: usize) -> Option<Vec<(bool, Vec<u8>)>> {
|
||||||
|
match Connection::open(self.get_database_path()) {
|
||||||
|
Ok(db) => {
|
||||||
|
match db.prepare(&format!("SELECT count(*) FROM \"{}\"", contact_uuid)) {
|
||||||
|
Ok(mut stmt) => {
|
||||||
|
let mut rows = stmt.query([]).unwrap();
|
||||||
|
let row = rows.next().unwrap();
|
||||||
|
if row.is_some() {
|
||||||
|
let total: usize = row.unwrap().get(0).unwrap();
|
||||||
|
if offset >= total {
|
||||||
|
print_error!("Offset larger than total numbers of rows");
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
if offset+count >= total {
|
||||||
|
count = total-offset;
|
||||||
|
}
|
||||||
|
match db.prepare(&format!("SELECT outgoing, data FROM \"{}\" LIMIT {} OFFSET {}", contact_uuid, count, total-offset-count)) {
|
||||||
|
Ok(mut stmt) => {
|
||||||
|
let mut rows = stmt.query([]).unwrap();
|
||||||
|
let mut msgs = Vec::new();
|
||||||
|
while let Some(row) = rows.next().unwrap() {
|
||||||
|
let encrypted_outgoing: Vec<u8> = row.get(0).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_outgoing.as_slice(), &self.master_key){
|
||||||
|
Ok(outgoing) => {
|
||||||
|
match byte_to_bool(outgoing[0]) {
|
||||||
|
Ok(outgoing) => {
|
||||||
|
let encrypted_data: Vec<u8> = row.get(1).unwrap();
|
||||||
|
match crypto::decrypt_data(encrypted_data.as_slice(), &self.master_key) {
|
||||||
|
Ok(data) => {
|
||||||
|
msgs.push(
|
||||||
|
(
|
||||||
|
outgoing,
|
||||||
|
data
|
||||||
|
)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
Err(e) => print_error!(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(msgs)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_must_use)]
|
||||||
|
pub fn delete_conversation(&self, contact_uuid: &Uuid) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = Connection::open(self.get_database_path())?;
|
||||||
|
db.execute(&format!("DELETE FROM {} WHERE contact_uuid=?", FILES_TABLE), &[&contact_uuid.as_bytes()[..]]);
|
||||||
|
db.execute(&format!("DROP TABLE IF EXISTS \"{}\"", contact_uuid), [])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn change_name(&mut self, new_name: String) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = KeyValueTable::new(&self.get_database_path(), MAIN_TABLE)?;
|
||||||
|
let result = db.update(DBKeys::NAME, new_name.as_bytes());
|
||||||
|
if result.is_ok() {
|
||||||
|
self.name = new_name;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn zeroize(&mut self){
|
||||||
|
self.master_key.zeroize();
|
||||||
|
self.keypair.secret.zeroize();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_encrypted_identity(database_folder: &str) -> Result<EncryptedIdentity, rusqlite::Error> {
|
||||||
|
let db = KeyValueTable::new(&get_database_path(database_folder), MAIN_TABLE)?;
|
||||||
|
let name = db.get(DBKeys::NAME)?;
|
||||||
|
let encrypted_keypair = db.get(DBKeys::KEYPAIR)?;
|
||||||
|
let salt = db.get(DBKeys::SALT)?;
|
||||||
|
let encrypted_master_key = db.get(DBKeys::MASTER_KEY)?;
|
||||||
|
Ok(EncryptedIdentity {
|
||||||
|
name: std::str::from_utf8(&name).unwrap().to_owned(),
|
||||||
|
encrypted_keypair,
|
||||||
|
salt,
|
||||||
|
encrypted_master_key,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_identity(database_folder: String, password: Option<&[u8]>) -> Result<Identity, String> {
|
||||||
|
match Identity::load_encrypted_identity(&database_folder) {
|
||||||
|
Ok(encrypted_identity) => {
|
||||||
|
let master_key: [u8; crypto::MASTER_KEY_LEN] = if password.is_none() {
|
||||||
|
if encrypted_identity.encrypted_master_key.len() == crypto::MASTER_KEY_LEN {
|
||||||
|
encrypted_identity.encrypted_master_key.try_into().unwrap()
|
||||||
|
} else {
|
||||||
|
return Err(String::from(DATABASE_CORRUPED_ERROR))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match crypto::decrypt_master_key(&encrypted_identity.encrypted_master_key, password.unwrap(), &encrypted_identity.salt) {
|
||||||
|
Ok(master_key) => master_key,
|
||||||
|
Err(e) => return Err(
|
||||||
|
match e {
|
||||||
|
CryptoError::DecryptionFailed => "Bad password".to_owned(),
|
||||||
|
CryptoError::InvalidLength => String::from(DATABASE_CORRUPED_ERROR)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match crypto::decrypt_data(&encrypted_identity.encrypted_keypair, &master_key) {
|
||||||
|
Ok(keypair) => {
|
||||||
|
Ok(Identity{
|
||||||
|
name: encrypted_identity.name,
|
||||||
|
keypair: Keypair::from_bytes(&keypair[..]).unwrap(),
|
||||||
|
master_key: master_key,
|
||||||
|
database_folder: database_folder,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
Err(String::from(DATABASE_CORRUPED_ERROR))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_identity_name(database_folder: &str) -> Result<String, rusqlite::Error> {
|
||||||
|
let db = KeyValueTable::new(&get_database_path(database_folder), MAIN_TABLE)?;
|
||||||
|
Ok(std::str::from_utf8(&db.get(DBKeys::NAME)?).unwrap().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_protected(database_folder: String) -> Result<bool, rusqlite::Error> {
|
||||||
|
let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?;
|
||||||
|
Ok(db.get(DBKeys::MASTER_KEY)?.len() != crypto::MASTER_KEY_LEN)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_identidy(database_folder: String, name: &str, password: Option<&[u8]>) -> Result<Identity, rusqlite::Error> {
|
||||||
|
let keypair = Keypair::generate(&mut rand_7::rngs::OsRng);
|
||||||
|
let master_key = crypto::generate_master_key();
|
||||||
|
let encrypted_keypair = crypto::encrypt_data(&keypair.to_bytes(), &master_key).unwrap();
|
||||||
|
let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?;
|
||||||
|
db.set(DBKeys::NAME, name.as_bytes())?;
|
||||||
|
db.set(DBKeys::KEYPAIR, &encrypted_keypair)?;
|
||||||
|
let salt = if password.is_none() { //no password
|
||||||
|
db.set(DBKeys::MASTER_KEY, &master_key)?; //storing master_key in plaintext
|
||||||
|
[0; crypto::SALT_LEN]
|
||||||
|
} else {
|
||||||
|
let (salt, encrypted_master_key) = crypto::encrypt_master_key(master_key, password.unwrap());
|
||||||
|
db.set(DBKeys::MASTER_KEY, &encrypted_master_key)?;
|
||||||
|
salt
|
||||||
|
};
|
||||||
|
db.set(DBKeys::SALT, &salt)?;
|
||||||
|
|
||||||
|
Ok(Identity {
|
||||||
|
name: name.to_owned(),
|
||||||
|
keypair,
|
||||||
|
master_key,
|
||||||
|
database_folder
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_master_key(database_folder: String, master_key: [u8; crypto::MASTER_KEY_LEN], new_password: Option<&[u8]>) -> Result<usize, rusqlite::Error> {
|
||||||
|
let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?;
|
||||||
|
let salt = if new_password.is_none() { //no password
|
||||||
|
db.update(DBKeys::MASTER_KEY, &master_key)?;
|
||||||
|
[0; crypto::SALT_LEN]
|
||||||
|
} else {
|
||||||
|
let (salt, encrypted_master_key) = crypto::encrypt_master_key(master_key, new_password.unwrap());
|
||||||
|
db.update(DBKeys::MASTER_KEY, &encrypted_master_key)?;
|
||||||
|
salt
|
||||||
|
};
|
||||||
|
db.update(DBKeys::SALT, &salt)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn change_password(database_folder: String, old_password: Option<&[u8]>, new_password: Option<&[u8]>) -> Result<bool, String> {
|
||||||
|
match Identity::load_encrypted_identity(&database_folder) {
|
||||||
|
Ok(encrypted_identity) => {
|
||||||
|
let master_key: [u8; crypto::MASTER_KEY_LEN] = if old_password.is_none() {
|
||||||
|
if encrypted_identity.encrypted_master_key.len() == crypto::MASTER_KEY_LEN {
|
||||||
|
encrypted_identity.encrypted_master_key.try_into().unwrap()
|
||||||
|
} else {
|
||||||
|
return Err(String::from(DATABASE_CORRUPED_ERROR))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match crypto::decrypt_master_key(&encrypted_identity.encrypted_master_key, old_password.unwrap(), &encrypted_identity.salt) {
|
||||||
|
Ok(master_key) => master_key,
|
||||||
|
Err(e) => return match e {
|
||||||
|
CryptoError::DecryptionFailed => Ok(false),
|
||||||
|
CryptoError::InvalidLength => Err(String::from(DATABASE_CORRUPED_ERROR))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match Identity::update_master_key(database_folder, master_key, new_password) {
|
||||||
|
Ok(_) => Ok(true),
|
||||||
|
Err(e) => Err(e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
31
app/src/main/native/src/key_value_table.rs
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
use rusqlite::{Connection, Error, params};
|
||||||
|
|
||||||
|
pub struct KeyValueTable<'a> {
|
||||||
|
db: Connection,
|
||||||
|
table_name: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> KeyValueTable<'a> {
|
||||||
|
pub fn new(db_path: &str, table_name: &'a str) -> Result<KeyValueTable<'a>, Error> {
|
||||||
|
let db = Connection::open(db_path)?;
|
||||||
|
db.execute(&format!("CREATE TABLE IF NOT EXISTS {} (key TEXT PRIMARY KEY, value BLOB)", table_name), [])?;
|
||||||
|
Ok(KeyValueTable {db, table_name})
|
||||||
|
}
|
||||||
|
pub fn set(&self, key: &str, value: &[u8]) -> Result<usize, Error> {
|
||||||
|
Ok(self.db.execute(&format!("INSERT INTO {} (key, value) VALUES (?1, ?2)", self.table_name), params![key, value])?)
|
||||||
|
}
|
||||||
|
pub fn get(&self, key: &str) -> Result<Vec<u8>, Error> {
|
||||||
|
let mut stmt = self.db.prepare(&format!("SELECT value FROM {} WHERE key=\"{}\"", self.table_name, key))?;
|
||||||
|
let mut rows = stmt.query([])?;
|
||||||
|
match rows.next()? {
|
||||||
|
Some(row) => Ok(row.get(0)?),
|
||||||
|
None => Err(rusqlite::Error::QueryReturnedNoRows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/*pub fn del(&self, key: &str) -> Result<usize, Error> {
|
||||||
|
self.db.execute(&format!("DELETE FROM {} WHERE key=\"{}\"", self.table_name, key), NO_PARAMS)
|
||||||
|
}*/
|
||||||
|
pub fn update(&self, key: &str, value: &[u8]) -> Result<usize, Error> {
|
||||||
|
self.db.execute(&format!("UPDATE {} SET value=? WHERE key=\"{}\"", self.table_name, key), params![value])
|
||||||
|
}
|
||||||
|
}
|
357
app/src/main/native/src/lib.rs
Normal file
@ -0,0 +1,357 @@
|
|||||||
|
mod key_value_table;
|
||||||
|
mod identity;
|
||||||
|
mod crypto;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
|
use std::{convert::TryInto, str::FromStr, fmt::Display, sync::{Mutex}};
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use log::*;
|
||||||
|
use android_log;
|
||||||
|
use identity::{Identity, Contact};
|
||||||
|
use crate::crypto::{HandshakeKeys, ApplicationKeys};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref loaded_identity: Mutex<Option<Identity>> = Mutex::new(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
use jni::JNIEnv;
|
||||||
|
use jni::objects::{JClass, JObject, JString, JList, JValue};
|
||||||
|
use jni::sys::{jboolean, jint, jbyteArray, jobject};
|
||||||
|
|
||||||
|
fn jstring_to_string(env: JNIEnv, input: JString) -> String {
|
||||||
|
String::from(env.get_string(input).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jboolean_to_bool(input: jboolean) -> bool {
|
||||||
|
input == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bool_to_jboolean(input: bool) -> u8 {
|
||||||
|
if input { 1 } else { 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slice_to_jvalue<'a>(env: JNIEnv, input: &'a [u8]) -> JValue<'a> {
|
||||||
|
JValue::Object(env.byte_array_from_slice(input).unwrap().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_must_use)]
|
||||||
|
fn log_error<T: Display>(e: T) {
|
||||||
|
android_log::init("AIRA Native");
|
||||||
|
error!("Error: {}", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn Java_sushi_hardcore_aira_CreateIdentityFragment_createNewIdentity(env: JNIEnv, _: JClass, database_folder: JString, name: JString, password: jbyteArray) -> jboolean {
|
||||||
|
let database_folder = jstring_to_string(env, database_folder);
|
||||||
|
let name = jstring_to_string(env, name);
|
||||||
|
match Identity::create_identidy(database_folder, &name, env.convert_byte_array(password).ok().as_deref()) {
|
||||||
|
Ok(identity) => {
|
||||||
|
*loaded_identity.lock().unwrap() = Some(identity);
|
||||||
|
1
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn Java_sushi_hardcore_aira_LoginActivity_getIdentityName(env: JNIEnv, _: JClass, database_folder: JString) -> jobject {
|
||||||
|
*match Identity::get_identity_name(&jstring_to_string(env, database_folder)) {
|
||||||
|
Ok(name) => *env.new_string(name).unwrap(),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn Java_sushi_hardcore_aira_AIRADatabase_isIdentityProtected(env: JNIEnv, _: JClass, database_folder: JString) -> jboolean {
|
||||||
|
match Identity::is_protected(jstring_to_string(env, database_folder)) {
|
||||||
|
Ok(is_protected) => bool_to_jboolean(is_protected),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn Java_sushi_hardcore_aira_AIRADatabase_loadIdentity(env: JNIEnv, _: JClass, database_folder: JString, password: jbyteArray) -> jboolean {
|
||||||
|
let database_folder = jstring_to_string(env, database_folder);
|
||||||
|
match Identity::load_identity(database_folder, env.convert_byte_array(password).ok().as_deref()) {
|
||||||
|
Ok(identity) => {
|
||||||
|
*loaded_identity.lock().unwrap() = Some(identity);
|
||||||
|
1
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_changePassword(env: JNIEnv, _: JClass, database_folder: JString, old_password: jbyteArray, new_password: jbyteArray) -> jboolean {
|
||||||
|
let database_folder = jstring_to_string(env, database_folder);
|
||||||
|
match Identity::change_password(database_folder, env.convert_byte_array(old_password).ok().as_deref(), env.convert_byte_array(new_password).ok().as_deref()) {
|
||||||
|
Ok(success) => bool_to_jboolean(success),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_getIdentityPublicKey(env: JNIEnv, _: JClass) -> jbyteArray {
|
||||||
|
env.byte_array_from_slice(&loaded_identity.lock().unwrap().as_ref().unwrap().get_public_key()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_Session_sign(env: JNIEnv, _: JClass, input: jbyteArray) -> jbyteArray {
|
||||||
|
env.byte_array_from_slice(&loaded_identity.lock().unwrap().as_ref().unwrap().sign(&env.convert_byte_array(input).unwrap())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_Session_deriveHandshakeKeys(env: JNIEnv, _: JClass, shared_secret: jbyteArray, handshake_hash: jbyteArray, i_am_bob: jboolean) -> jobject {
|
||||||
|
let shared_secret = env.convert_byte_array(shared_secret).unwrap();
|
||||||
|
let handshake_hash = env.convert_byte_array(handshake_hash).unwrap();
|
||||||
|
let handshake_keys = HandshakeKeys::derive_keys(shared_secret.as_slice().try_into().unwrap(), handshake_hash.as_slice().try_into().unwrap(), jboolean_to_bool(i_am_bob));
|
||||||
|
|
||||||
|
let args: Vec<JValue<'_>> = [&handshake_keys.local_key[..], &handshake_keys.local_iv, &handshake_keys.local_handshake_traffic_secret, &handshake_keys.peer_key, &handshake_keys.peer_iv, &handshake_keys.peer_handshake_traffic_secret, &handshake_keys.handshake_secret].iter().map(|field|{
|
||||||
|
slice_to_jvalue(env, field)
|
||||||
|
}).collect();
|
||||||
|
let handshake_keys_class = env.find_class("sushi/hardcore/aira/background_service/HandshakeKeys").unwrap();
|
||||||
|
*env.new_object(handshake_keys_class, "([B[B[B[B[B[B[B)V", &args).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_Session_computeHandshakeFinished(env: JNIEnv, _: JClass, local_handshake_traffic_secret: jbyteArray, handshake_hash: jbyteArray) -> jbyteArray {
|
||||||
|
env.byte_array_from_slice(&crypto::compute_handshake_finished(env.convert_byte_array(local_handshake_traffic_secret).unwrap()[..].try_into().unwrap(), env.convert_byte_array(handshake_hash).unwrap()[..].try_into().unwrap())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_Session_verifyHandshakeFinished(env: JNIEnv, _: JClass, peer_handshake_finished: jbyteArray, peer_handshake_traffic_secret: jbyteArray, handshake_hash: jbyteArray) -> jboolean {
|
||||||
|
bool_to_jboolean(crypto::verify_handshake_finished(env.convert_byte_array(peer_handshake_finished).unwrap()[..].try_into().unwrap(), env.convert_byte_array(peer_handshake_traffic_secret).unwrap()[..].try_into().unwrap(), env.convert_byte_array(handshake_hash).unwrap()[..].try_into().unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_Session_deriveApplicationKeys(env: JNIEnv, _: JClass, handshake_secret: jbyteArray, handshake_hash: jbyteArray, i_am_bob: jboolean) -> jobject {
|
||||||
|
let handshake_secret = env.convert_byte_array(handshake_secret).unwrap();
|
||||||
|
let handshake_hash = env.convert_byte_array(handshake_hash).unwrap();
|
||||||
|
let application_keys = ApplicationKeys::derive_keys(handshake_secret.as_slice().try_into().unwrap(), handshake_hash.as_slice().try_into().unwrap(), jboolean_to_bool(i_am_bob));
|
||||||
|
|
||||||
|
let args: Vec<JValue<'_>> = [&application_keys.local_key[..], &application_keys.local_iv, &application_keys.peer_key, &application_keys.peer_iv].iter().map(|field|{
|
||||||
|
slice_to_jvalue(env, field)
|
||||||
|
}).collect();
|
||||||
|
let application_keys_class = env.find_class("sushi/hardcore/aira/background_service/ApplicationKeys").unwrap();
|
||||||
|
*env.new_object(application_keys_class, "([B[B[B[B)V", &args).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_background_1service_AIRAService_releaseIdentity(_: JNIEnv, _: JClass) {
|
||||||
|
let mut identity = loaded_identity.lock().unwrap();
|
||||||
|
identity.as_mut().unwrap().zeroize();
|
||||||
|
*identity = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_contact(env: JNIEnv, contact: Contact) -> JObject {
|
||||||
|
let contact_class = env.find_class("sushi/hardcore/aira/background_service/Contact").unwrap();
|
||||||
|
env.new_object(contact_class, "(Ljava/lang/String;[BLjava/lang/String;ZZ)V", &[JValue::Object(*env.new_string(contact.uuid.to_string()).unwrap()), slice_to_jvalue(env, &contact.public_key), JValue::Object(*env.new_string(contact.name).unwrap()), JValue::Bool(bool_to_jboolean(contact.verified)), JValue::Bool(bool_to_jboolean(contact.seen))]).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_addContact(env: JNIEnv, _: JClass, name: JString, public_key: jbyteArray) -> jobject {
|
||||||
|
*match loaded_identity.lock().unwrap().as_ref().unwrap().add_contact(jstring_to_string(env, name), env.convert_byte_array(public_key).unwrap().try_into().unwrap()) {
|
||||||
|
Ok(contact) => new_contact(env, contact),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_removeContact(env: JNIEnv, _: JClass, uuid: JString) -> jboolean {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().remove_contact(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap()) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_loadContacts(env: JNIEnv, _: JClass) -> jobject {
|
||||||
|
*match loaded_identity.lock().unwrap().as_ref().unwrap().load_contacts() {
|
||||||
|
Some(contacts) => {
|
||||||
|
let array_list_class = env.find_class("java/util/ArrayList").unwrap();
|
||||||
|
let array_list = env.new_object(array_list_class, "(I)V", &[JValue::Int(contacts.len().try_into().unwrap())]).unwrap();
|
||||||
|
let array_list = JList::from_env(&env, array_list).unwrap();
|
||||||
|
for contact in contacts {
|
||||||
|
array_list.add(new_contact(env, contact)).unwrap();
|
||||||
|
}
|
||||||
|
*array_list
|
||||||
|
}
|
||||||
|
None => JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_setVerified(env: JNIEnv, _: JClass, uuid: JString) -> jboolean {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().set_verified(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap()) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_changeContactName(env: JNIEnv, _: JClass, contactUuid: JString, newName: JString) -> jboolean {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().change_contact_name(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), &jstring_to_string(env, newName)) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_setContactSeen(env: JNIEnv, _: JClass, contactUuid: JString, seen: jboolean) -> jboolean {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().set_contact_seen(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), jboolean_to_bool(seen)) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_storeMsg(env: JNIEnv, _: JClass, contactUuid: JString, outgoing: jboolean, data: jbyteArray) -> jboolean {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().store_msg(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), jboolean_to_bool(outgoing), &env.convert_byte_array(data).unwrap()) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_loadMsgs(env: JNIEnv, _: JClass, uuid: JString, offset: jint, count: jint) -> jobject {
|
||||||
|
*match loaded_identity.lock().unwrap().as_ref().unwrap().load_msgs(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap(), offset as usize, count as usize) {
|
||||||
|
Some(msgs) => {
|
||||||
|
let array_list_class = env.find_class("java/util/ArrayList").unwrap();
|
||||||
|
let array_list = env.new_object(array_list_class, "(I)V", &[JValue::Int(msgs.len().try_into().unwrap())]).unwrap();
|
||||||
|
let array_list = JList::from_env(&env, array_list).unwrap();
|
||||||
|
let chat_item_class = env.find_class("sushi/hardcore/aira/ChatItem").unwrap();
|
||||||
|
for msg in msgs {
|
||||||
|
let chat_item_object = env.new_object(chat_item_class, "(Z[B)V", &[JValue::Bool(bool_to_jboolean(msg.0)), slice_to_jvalue(env, &msg.1)]).unwrap();
|
||||||
|
array_list.add(chat_item_object).unwrap();
|
||||||
|
}
|
||||||
|
*array_list
|
||||||
|
}
|
||||||
|
None => JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_storeFile(env: JNIEnv, _: JClass, contactUuid: JString, data: jbyteArray) -> jbyteArray {
|
||||||
|
let contact_uuid = match env.get_string(contactUuid) {
|
||||||
|
Ok(uuid) => Some(Uuid::from_str(&String::from(uuid)).unwrap()),
|
||||||
|
Err(_) => None
|
||||||
|
};
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().store_file(contact_uuid, &env.convert_byte_array(data).unwrap()) {
|
||||||
|
Ok(uuid) => env.byte_array_from_slice(uuid.as_bytes()).unwrap(),
|
||||||
|
Err(_) => *JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_loadFile(env: JNIEnv, _: JClass, rawUuid: jbyteArray) -> jbyteArray {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().load_file(Uuid::from_bytes(env.convert_byte_array(rawUuid).unwrap().try_into().unwrap())) {
|
||||||
|
Some(buffer) => env.byte_array_from_slice(&buffer).unwrap(),
|
||||||
|
None => *JObject::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_deleteConversation(env: JNIEnv, _: JClass, contactUuid: JString) -> jboolean {
|
||||||
|
let contact_uuid = Uuid::from_str(&String::from(env.get_string(contactUuid).unwrap())).unwrap();
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().delete_conversation(&contact_uuid) {
|
||||||
|
Ok(_) => 1,
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_clearTemporaryFiles(_: JNIEnv, _: JClass) -> jint {
|
||||||
|
match loaded_identity.lock().unwrap().as_ref().unwrap().clear_temporary_files() {
|
||||||
|
Ok(r) => r.try_into().unwrap(),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_changeName(env: JNIEnv, _: JClass, new_name: JString) -> jboolean {
|
||||||
|
let new_name = jstring_to_string(env, new_name);
|
||||||
|
match loaded_identity.lock().unwrap().as_mut().unwrap().change_name(new_name) {
|
||||||
|
Ok(u) => bool_to_jboolean(u == 1),
|
||||||
|
Err(e) => {
|
||||||
|
log_error(e);
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_AIRADatabase_getIdentityFingerprint(env: JNIEnv, _: JClass) -> jobject {
|
||||||
|
**env.new_string(crypto::generate_fingerprint(&loaded_identity.lock().unwrap().as_ref().unwrap().get_public_key())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn Java_sushi_hardcore_aira_ChatActivity_generateFingerprint(env: JNIEnv, _: JClass, publicKey: jbyteArray) -> jobject {
|
||||||
|
**env.new_string(crypto::generate_fingerprint(&env.convert_byte_array(publicKey).unwrap())).unwrap()
|
||||||
|
}
|
27
app/src/main/native/src/utils.rs
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
use std::convert::TryInto;
|
||||||
|
use uuid::Bytes;
|
||||||
|
use crate::print_error;
|
||||||
|
|
||||||
|
pub fn to_array_48(s: &[u8]) -> [u8; 48] {
|
||||||
|
s.try_into().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_uuid_bytes(bytes: &[u8]) -> Option<Bytes> {
|
||||||
|
match bytes.try_into() {
|
||||||
|
Ok(uuid) => Some(uuid),
|
||||||
|
Err(e) => {
|
||||||
|
print_error!(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! print_error {
|
||||||
|
($arg:tt) => ({
|
||||||
|
println!("[{}:{}] {}", file!(), line!(), $arg);
|
||||||
|
});
|
||||||
|
($($arg:tt)*) => ({
|
||||||
|
println!("[{}:{}] {}", file!(), line!(), format_args!($($arg)*));
|
||||||
|
})
|
||||||
|
}
|
30
app/src/main/res/drawable-v24/ic_launcher_foreground.xml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
<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:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:endX="85.84757"
|
||||||
|
android:endY="92.4963"
|
||||||
|
android:startX="42.9492"
|
||||||
|
android:startY="49.59793"
|
||||||
|
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="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||||
|
android:strokeWidth="1"
|
||||||
|
android:strokeColor="#00000000" />
|
||||||
|
</vector>
|
9
app/src/main/res/drawable/background_adapter_bubble.xml
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
<solid android:color="@color/bubbleBackground"/>
|
||||||
|
<corners android:radius="20dp"/>
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</selector>
|
8
app/src/main/res/drawable/background_session.xml
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
<solid android:color="@color/sessionBackground"/>
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</selector>
|
5
app/src/main/res/drawable/ic_add.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_attach_file.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M16.5,6v11.5c0,2.21 -1.79,4 -4,4s-4,-1.79 -4,-4V5c0,-1.38 1.12,-2.5 2.5,-2.5s2.5,1.12 2.5,2.5v10.5c0,0.55 -0.45,1 -1,1s-1,-0.45 -1,-1V6H10v9.5c0,1.38 1.12,2.5 2.5,2.5s2.5,-1.12 2.5,-2.5V5c0,-2.21 -1.79,-4 -4,-4S7,2.79 7,5v12.5c0,3.04 2.46,5.5 5.5,5.5s5.5,-2.46 5.5,-5.5V6h-1.5z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_close.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_delete_conversation.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M15,16h4v2h-4zM15,8h7v2h-7zM15,12h6v2h-6zM3,18c0,1.1 0.9,2 2,2h6c1.1,0 2,-0.9 2,-2L13,8L3,8v10zM14,5h-3l-1,-1L6,4L5,5L2,5v2h12z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_delete_forever.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2L18,7L6,7v12zM8.46,11.88l1.41,-1.41L12,12.59l2.12,-2.12 1.41,1.41L13.41,14l2.12,2.12 -1.41,1.41L12,15.41l-2.12,2.12 -1.41,-1.41L10.59,14l-2.13,-2.12zM15.5,4l-1,-1h-5l-1,1L5,4v2h14L19,4z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_info.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z"/>
|
||||||
|
</vector>
|
BIN
app/src/main/res/drawable/ic_launcher.png
Normal file
After Width: | Height: | Size: 10 KiB |
170
app/src/main/res/drawable/ic_launcher_background.xml
Normal 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="#3DDC84"
|
||||||
|
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>
|
5
app/src/main/res/drawable/ic_lock.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M18,8h-1L17,6c0,-2.76 -2.24,-5 -5,-5S7,3.24 7,6v2L6,8c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L20,10c0,-1.1 -0.9,-2 -2,-2zM12,17c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2zM15.1,8L8.9,8L8.9,6c0,-1.71 1.39,-3.1 3.1,-3.1 1.71,0 3.1,1.39 3.1,3.1v2z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_person.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_person_add.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" 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>
|
5
app/src/main/res/drawable/ic_person_remove.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M14,8c0,-2.21 -1.79,-4 -4,-4S6,5.79 6,8s1.79,4 4,4S14,10.21 14,8zM17,10v2h6v-2H17zM2,18v2h16v-2c0,-2.66 -5.33,-4 -8,-4S2,15.34 2,18z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_save.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M19,12v7L5,19v-7L3,12v7c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2v-7h-2zM13,12.67l2.59,-2.58L17,11.5l-5,5 -5,-5 1.41,-1.41L11,12.67L11,3h2z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_send.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:autoMirrored="true" android:height="24dp"
|
||||||
|
android:tint="#FFFFFF" android:viewportHeight="24"
|
||||||
|
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_settings.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M19.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94c0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 -0.12,-0.61L19.14,12.94zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6s3.6,1.62 3.6,3.6S13.98,15.6 12,15.6z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_verified.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M12,1L3,5v6c0,5.55 3.84,10.74 9,12 5.16,-1.26 9,-6.45 9,-12L21,5l-9,-4zM10,17l-4,-4 1.41,-1.41L10,14.17l6.59,-6.59L18,9l-8,8z"/>
|
||||||
|
</vector>
|
5
app/src/main/res/drawable/ic_warning.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<vector android:height="24dp" android:tint="#FFFFFF"
|
||||||
|
android:viewportHeight="24" android:viewportWidth="24"
|
||||||
|
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<path android:fillColor="@android:color/white" android:pathData="M1,21h22L12,2 1,21zM13,18h-2v-2h2v2zM13,14h-2v-4h2v4z"/>
|
||||||
|
</vector>
|
8
app/src/main/res/drawable/round_background.xml
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="oval">
|
||||||
|
<solid android:color="@color/secondary"/>
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</selector>
|
59
app/src/main/res/layout/activity_chat.xml
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
tools:context=".ChatActivity">
|
||||||
|
|
||||||
|
<androidx.recyclerview.widget.RecyclerView
|
||||||
|
android:id="@+id/recycler_chat"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="0dp"
|
||||||
|
android:layout_marginHorizontal="20dp"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toTopOf="@id/bottom_panel"/>
|
||||||
|
|
||||||
|
<androidx.constraintlayout.widget.ConstraintLayout
|
||||||
|
android:id="@+id/bottom_panel"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
android:visibility="gone">
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/button_attach"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:src="@drawable/ic_attach_file"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintEnd_toStartOf="@id/image_trust_level" />
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/image_trust_level"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:src="@drawable/ic_warning"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintEnd_toStartOf="@id/edit_message"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_message"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintEnd_toStartOf="@+id/button_send"
|
||||||
|
app:layout_constraintStart_toStartOf="@id/button_attach"/>
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/button_send"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:src="@drawable/ic_send"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintEnd_toEndOf="parent" />
|
||||||
|
|
||||||
|
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||||
|
|
||||||
|
</androidx.constraintlayout.widget.ConstraintLayout>
|
13
app/src/main/res/layout/activity_login.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
tools:context=".LoginActivity">
|
||||||
|
|
||||||
|
<androidx.fragment.app.FragmentContainerView
|
||||||
|
android:id="@+id/fragment_container"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"/>
|
||||||
|
|
||||||
|
</RelativeLayout>
|
54
app/src/main/res/layout/activity_main.xml
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:id="@+id/refresher"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
tools:context=".MainActivity">
|
||||||
|
|
||||||
|
<androidx.constraintlayout.widget.ConstraintLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_online_sessions"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/online_peers"
|
||||||
|
style="@style/Label"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"/>
|
||||||
|
|
||||||
|
<ListView
|
||||||
|
android:id="@+id/online_sessions"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
app:layout_constraintTop_toBottomOf="@id/text_online_sessions"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_offline_sessions"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/offline_contacts"
|
||||||
|
style="@style/Label"
|
||||||
|
app:layout_constraintTop_toBottomOf="@id/online_sessions"/>
|
||||||
|
|
||||||
|
<ListView
|
||||||
|
android:id="@+id/offline_sessions"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
app:layout_constraintTop_toBottomOf="@id/text_offline_sessions"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_peer_ip"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="text"
|
||||||
|
android:maxLines="1"
|
||||||
|
android:imeOptions="actionGo"
|
||||||
|
android:hint="@string/add_peer_ip"
|
||||||
|
android:layout_margin="30dp"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"/>
|
||||||
|
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||||
|
|
||||||
|
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
|
32
app/src/main/res/layout/activity_settings.xml
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
<?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">
|
||||||
|
|
||||||
|
<FrameLayout
|
||||||
|
android:id="@+id/settings_container"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"/>
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:layout_marginTop="20dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/identity_fingerprint_label"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_fingerprint"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</LinearLayout>
|
33
app/src/main/res/layout/adapter_chat_file.xml
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
<?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:paddingVertical="1dp">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:id="@+id/bubble_content"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center"
|
||||||
|
style="@style/Bubble"
|
||||||
|
android:paddingTop="5dp"
|
||||||
|
android:paddingBottom="5dp">
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/button_save"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginEnd="5dp"
|
||||||
|
android:src="@drawable/ic_save"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_filename"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textIsSelectable="true"
|
||||||
|
android:textColor="@color/messageTextColor"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</LinearLayout>
|
17
app/src/main/res/layout/adapter_chat_message.xml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?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:paddingVertical="1dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_message"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textIsSelectable="true"
|
||||||
|
android:autoLink="all"
|
||||||
|
android:textColorLink="@color/textLink"
|
||||||
|
android:textColor="@color/messageTextColor"
|
||||||
|
style="@style/Bubble"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
46
app/src/main/res/layout/adapter_session.xml
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:padding="10dp"
|
||||||
|
android:background="@drawable/background_session">
|
||||||
|
|
||||||
|
<sushi.hardcore.aira.widgets.TextAvatar
|
||||||
|
android:id="@+id/text_avatar"
|
||||||
|
android:layout_width="40dp"
|
||||||
|
android:layout_height="40dp"
|
||||||
|
app:textSize="8sp"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintStart_toStartOf="parent"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_name"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginHorizontal="5dp"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintStart_toEndOf="@id/text_avatar"/>
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/image_trust_level"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintStart_toEndOf="@id/text_name"/>
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/image_seen"
|
||||||
|
android:layout_width="10dp"
|
||||||
|
android:layout_height="10dp"
|
||||||
|
android:layout_marginEnd="10dp"
|
||||||
|
android:src="@drawable/round_background"
|
||||||
|
app:layout_constraintTop_toTopOf="parent"
|
||||||
|
app:layout_constraintBottom_toBottomOf="parent"
|
||||||
|
app:layout_constraintEnd_toEndOf="parent"/>
|
||||||
|
|
||||||
|
</androidx.constraintlayout.widget.ConstraintLayout>
|
19
app/src/main/res/layout/dialog_ask_file.xml
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout
|
||||||
|
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_title"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
style="@style/Label"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_file_info"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
style="@style/Label"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
39
app/src/main/res/layout/dialog_fingerprints.xml
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
<?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"
|
||||||
|
android:paddingHorizontal="20dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/fingerprints_instructions"
|
||||||
|
style="@style/Label"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/local_fingerprint"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_local_fingerprint"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/peer_fingerprint"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_peer_fingerprint"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
54
app/src/main/res/layout/dialog_info.xml
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?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"
|
||||||
|
android:paddingHorizontal="20dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/fingerprint"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_fingerprint"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:id="@+id/online_fields"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/ip"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_ip"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/connection"
|
||||||
|
style="@style/Label"
|
||||||
|
android:textStyle="bold"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_outgoing"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</LinearLayout>
|
28
app/src/main/res/layout/dialog_password.xml
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
<?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"
|
||||||
|
android:paddingHorizontal="30dp">
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/old_password"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/current_password"
|
||||||
|
android:inputType="textPassword"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/new_password"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/new_password"
|
||||||
|
android:inputType="textPassword"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/new_password_confirm"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/new_password_confirm"
|
||||||
|
android:inputType="textPassword"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
60
app/src/main/res/layout/fragment_create_identity.xml
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
tools:context=".CreateIdentityFragment">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:layout_marginHorizontal="50dp"
|
||||||
|
android:layout_centerInParent="true">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/create_identity_test"
|
||||||
|
style="@style/Label"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_name"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/identity_name"
|
||||||
|
android:inputType="text"/>
|
||||||
|
|
||||||
|
<androidx.appcompat.widget.SwitchCompat
|
||||||
|
android:id="@+id/checkbox_enable_password"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="center_horizontal"
|
||||||
|
android:text="@string/enable_password"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_password"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/password_hint"
|
||||||
|
android:inputType="textPassword"
|
||||||
|
android:visibility="gone"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_password_confirm"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/password_confirm_hint"
|
||||||
|
android:inputType="textPassword"
|
||||||
|
android:visibility="gone"/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/button_create"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="center"
|
||||||
|
android:text="@string/create"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</RelativeLayout>
|
54
app/src/main/res/layout/fragment_login.xml
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
tools:context=".LoginFragment">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:layout_marginHorizontal="50dp"
|
||||||
|
android:layout_centerInParent="true">
|
||||||
|
|
||||||
|
<sushi.hardcore.aira.widgets.TextAvatar
|
||||||
|
android:id="@+id/text_avatar"
|
||||||
|
android:layout_height="90dp"
|
||||||
|
android:layout_width="90dp"
|
||||||
|
app:textSize="20sp"
|
||||||
|
android:layout_gravity="center"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_identity_name"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textAlignment="center"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:textSize="25sp"
|
||||||
|
android:layout_marginTop="10dp"/>
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/enter_password"
|
||||||
|
style="@style/Label"/>
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/edit_password"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="textPassword"
|
||||||
|
android:hint="@string/password_hint"/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/button_login"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="center"
|
||||||
|
android:text="@string/login"/>
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</RelativeLayout>
|
13
app/src/main/res/layout/text_avatar.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?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"
|
||||||
|
android:background="@drawable/round_background">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/text_letter"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_centerInParent="true"/>
|
||||||
|
|
||||||
|
</RelativeLayout>
|
35
app/src/main/res/menu/chat_activity.xml
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<menu xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto">
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/delete_conversation"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_delete_conversation"
|
||||||
|
android:title="@string/delete_conversation" />
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/verify"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_verified"
|
||||||
|
android:title="@string/verify"/>
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/set_as_contact"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_person_add"
|
||||||
|
android:title="@string/add_contact"/>
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/remove_contact"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_person_remove"
|
||||||
|
android:title="@string/remove_contact"/>
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/session_info"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_info"
|
||||||
|
android:title="@string/details"/>
|
||||||
|
|
||||||
|
</menu>
|
15
app/src/main/res/menu/main_activity.xml
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<menu xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto">
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/settings"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_settings"/>
|
||||||
|
|
||||||
|
<item
|
||||||
|
android:id="@+id/close"
|
||||||
|
app:showAsAction="ifRoom"
|
||||||
|
android:icon="@drawable/ic_close"/>
|
||||||
|
|
||||||
|
</menu>
|
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal 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>
|
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal 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>
|
BIN
app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_round.png
Normal file
After Width: | Height: | Size: 5.2 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
After Width: | Height: | Size: 2.6 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_round.png
Normal file
After Width: | Height: | Size: 3.3 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
Normal file
After Width: | Height: | Size: 7.3 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
After Width: | Height: | Size: 7.7 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
After Width: | Height: | Size: 10 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
Normal file
After Width: | Height: | Size: 16 KiB |
6
app/src/main/res/values/attrs.xml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<declare-styleable name="TextAvatar">
|
||||||
|
<attr name="textSize" format="dimension"/>
|
||||||
|
</declare-styleable>
|
||||||
|
</resources>
|
12
app/src/main/res/values/colors.xml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<color name="primary">#262626</color>
|
||||||
|
<color name="secondary">#FF3C00</color>
|
||||||
|
<color name="white">#FFFFFF</color>
|
||||||
|
<color name="backgroundColor">#111111</color>
|
||||||
|
<color name="sessionBackground">#1F1F1F</color>
|
||||||
|
<color name="bubbleBackground">@color/sessionBackground</color>
|
||||||
|
<color name="incomingBubbleBackground">@color/secondary</color>
|
||||||
|
<color name="textLink">#3845A3</color>
|
||||||
|
<color name="messageTextColor">#ffffff</color>
|
||||||
|
</resources>
|
73
app/src/main/res/values/strings.xml
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">AIRA</string>
|
||||||
|
<string name="create_identity_test">Create a new identity:</string>
|
||||||
|
<string name="identity_name">Identity Name</string>
|
||||||
|
<string name="password_hint">Password</string>
|
||||||
|
<string name="password_confirm_hint">Password (confirm)</string>
|
||||||
|
<string name="create">Create</string>
|
||||||
|
<string name="password_mismatch">Passwords don\'t match !</string>
|
||||||
|
<string name="online_peers">Online peers:</string>
|
||||||
|
<string name="offline_contacts">Offline contacts:</string>
|
||||||
|
<string name="identity_create_failed">Failed to create identity</string>
|
||||||
|
<string name="identity_load_failed">Failed to load identity. Please check your password</string>
|
||||||
|
<string name="service_name">AIRA Background Service</string>
|
||||||
|
<string name="login">Login</string>
|
||||||
|
<string name="add_peer_ip">Add peer by IP</string>
|
||||||
|
<string name="unknown">Unknown</string>
|
||||||
|
<string name="file_saved">File saved !</string>
|
||||||
|
<string name="enter_password">Enter your password:</string>
|
||||||
|
<string name="yes">Yes</string>
|
||||||
|
<string name="warning">Warning !</string>
|
||||||
|
<string name="ask_log_out">Do you really want to log out ? (You will no longer receive messages until you login again)</string>
|
||||||
|
<string name="cancel">Cancel</string>
|
||||||
|
<string name="background_service">Background service</string>
|
||||||
|
<string name="verifying_contact">Verifying contact</string>
|
||||||
|
<string name="fingerprints_instructions">Compare the following fingerprints by a trusted way of communication (such as real life) and be sure they match..</string>
|
||||||
|
<string name="local_fingerprint">Local fingerprint:</string>
|
||||||
|
<string name="peer_fingerprint">Peer fingerprint:</string>
|
||||||
|
<string name="summary_name">The name of your identity. Shown to all active sessions.</string>
|
||||||
|
<string name="delete_identity">Delete Identity</string>
|
||||||
|
<string name="summary_delete_identity">Delete all your data. You won\'t be able to be recognized by your contacts anymore.</string>
|
||||||
|
<string name="preference_password">Identity Password</string>
|
||||||
|
<string name="summary_password">You can\'t access your data or be recognized by your contacts without this password.</string>
|
||||||
|
<string name="change_password">Change password:</string>
|
||||||
|
<string name="ok">OK</string>
|
||||||
|
<string name="change_password_failed">Operation failed. Please check your old password.</string>
|
||||||
|
<string name="error">Error</string>
|
||||||
|
<string name="current_password">Current password</string>
|
||||||
|
<string name="new_password">New password (empty for no password)</string>
|
||||||
|
<string name="new_password_confirm">New password (confirm)</string>
|
||||||
|
<string name="confirm_delete">Are you sure you want to delete all your conversations (messages and files), all your contacts, and your private key ?</string>
|
||||||
|
<string name="they_match">They match</string>
|
||||||
|
<string name="ask_delete_conversation">Deleting a conversation only affects you. Your contact will still have a copy of this conversation if she/he doesn\'t delete it too. Do you really want to delete all this conversation (messages and files) ?</string>
|
||||||
|
<string name="delete">Delete</string>
|
||||||
|
<string name="ask_remove_contact">Deleting contact will remove her/his identity key and your conversation (messages and files). You won\'t be able to recognize her/him anymore. This action only affects you. Do you really want to remove this contact ?</string>
|
||||||
|
<string name="enable_password">Encrypt with a password</string>
|
||||||
|
<string name="msg_notification_channel_name">New Messages</string>
|
||||||
|
<string name="mark_read">Mark read</string>
|
||||||
|
<string name="ask_file_notification_channel">Download file requests</string>
|
||||||
|
<string name="db_mkdir_failed">Databases directory creation failed</string>
|
||||||
|
<string name="want_to_send_a_file">%s wants to send you a file%s</string>
|
||||||
|
<string name="download_file_request">Download file request</string>
|
||||||
|
<string name="download">Download</string>
|
||||||
|
<string name="refuse">Refuse</string>
|
||||||
|
<string name="file_transfers">File transfers</string>
|
||||||
|
<string name="transfer_aborted">Transfer aborted</string>
|
||||||
|
<string name="transfer_completed">Transfer completed</string>
|
||||||
|
<string name="reply">Reply</string>
|
||||||
|
<string name="share_uri_null">Failed to retrieve URI</string>
|
||||||
|
<string name="ask_send_file">Send %s (%s) to %s ?</string>
|
||||||
|
<string name="file_open_failed">Failed to open file</string>
|
||||||
|
<string name="share_label">Send with AIRA</string>
|
||||||
|
<string name="identity_fingerprint_label">Your identity\'s fingerprint:</string>
|
||||||
|
<string name="fingerprint">Fingerprint:</string>
|
||||||
|
<string name="ip">IP:</string>
|
||||||
|
<string name="connection">Connection:</string>
|
||||||
|
<string name="outgoing">Outgoing</string>
|
||||||
|
<string name="incoming">Incoming</string>
|
||||||
|
<string name="delete_conversation">Delete conversation</string>
|
||||||
|
<string name="verify">Verify</string>
|
||||||
|
<string name="add_contact">Add contact</string>
|
||||||
|
<string name="remove_contact">Remove contact</string>
|
||||||
|
<string name="details">Details</string>
|
||||||
|
</resources>
|
20
app/src/main/res/values/styles.xml
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<style name="Label" parent="Widget.MaterialComponents.TextView">
|
||||||
|
<item name="android:textAlignment">center</item>
|
||||||
|
<item name="android:textSize">15sp</item>
|
||||||
|
<item name="android:paddingTop">8dp</item>
|
||||||
|
<item name="android:paddingBottom">8dp</item>
|
||||||
|
</style>
|
||||||
|
<style name="Bubble">
|
||||||
|
<item name="android:background">@drawable/background_adapter_bubble</item>
|
||||||
|
<item name="android:paddingTop">10dp</item>
|
||||||
|
<item name="android:paddingBottom">10dp</item>
|
||||||
|
<item name="android:paddingStart">15dp</item>
|
||||||
|
<item name="android:paddingEnd">15dp</item>
|
||||||
|
</style>
|
||||||
|
<style name="Theme.AIRA.NoActionBar">
|
||||||
|
<item name="windowActionBar">false</item>
|
||||||
|
<item name="windowNoTitle">true</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
18
app/src/main/res/values/themes.xml
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
<!-- Base application theme. -->
|
||||||
|
<style name="Theme.AIRA" parent="Theme.AppCompat">
|
||||||
|
<!-- Primary brand color. -->
|
||||||
|
<item name="colorPrimary">@color/primary</item>
|
||||||
|
<item name="colorPrimaryVariant">@color/primary</item>
|
||||||
|
<!-- Secondary brand color. -->
|
||||||
|
<item name="colorSecondary">@color/secondary</item>
|
||||||
|
<item name="colorSecondaryVariant">@color/secondary</item>
|
||||||
|
|
||||||
|
<item name="colorAccent">@color/secondary</item>
|
||||||
|
|
||||||
|
<!-- Status bar color. -->
|
||||||
|
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
|
||||||
|
|
||||||
|
<item name="android:windowBackground">@color/backgroundColor</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
22
app/src/main/res/xml/preferences.xml
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<EditTextPreference
|
||||||
|
android:key="identityName"
|
||||||
|
android:title="@string/identity_name"
|
||||||
|
android:summary="@string/summary_name"
|
||||||
|
android:icon="@drawable/ic_person"/>
|
||||||
|
|
||||||
|
<Preference
|
||||||
|
android:key="identityPassword"
|
||||||
|
android:title="@string/preference_password"
|
||||||
|
android:summary="@string/summary_password"
|
||||||
|
android:icon="@drawable/ic_lock"/>
|
||||||
|
|
||||||
|
<Preference
|
||||||
|
android:key="deleteIdentity"
|
||||||
|
android:title="@string/delete_identity"
|
||||||
|
android:summary="@string/summary_delete_identity"
|
||||||
|
android:icon="@drawable/ic_delete_forever"/>
|
||||||
|
|
||||||
|
</PreferenceScreen>
|
17
app/src/test/java/sushi/hardcore/aira/ExampleUnitTest.kt
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package sushi.hardcore.aira
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
import org.junit.Assert.*
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example local unit test, which will execute on the development machine (host).
|
||||||
|
*
|
||||||
|
* See [testing documentation](http://d.android.com/tools/testing).
|
||||||
|
*/
|
||||||
|
class ExampleUnitTest {
|
||||||
|
@Test
|
||||||
|
fun addition_isCorrect() {
|
||||||
|
assertEquals(4, 2 + 2)
|
||||||
|
}
|
||||||
|
}
|
26
build.gradle
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
|
buildscript {
|
||||||
|
ext.kotlin_version = "1.4.21"
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
jcenter()
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
classpath 'com.android.tools.build:gradle:4.1.3'
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
task clean(type: Delete) {
|
||||||
|
delete rootProject.buildDir
|
||||||
|
}
|