Repo created

This commit is contained in:
Fr4nz D13trich 2025-11-23 08:52:50 +01:00
parent 7c106522d5
commit de8996c1cc
544 changed files with 17766 additions and 2 deletions

14
.gitignore vendored Normal file
View file

@ -0,0 +1,14 @@
*.iml
.gradle
/local.properties
/.idea/
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
/app/build/
/app/release/
/app/libs/
/.kotlin

674
LICENSE Normal file
View file

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

View file

@ -1,3 +1,68 @@
# c2c-passwords
# Nextcloud Passwords
Nextcloud Passwords Android App
[![Android CI](https://github.com/hegocre/NextcloudPasswords/actions/workflows/android.yml/badge.svg?branch=main)](https://github.com/hegocre/NextcloudPasswords/actions/workflows/android.yml)
[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://github.com/hegocre/NextcloudPasswords/blob/main/LICENSE)
[![Crowdin](https://badges.crowdin.net/e/da2d6d8cb4ace3704592ebcf73969dc9/localized.svg)](https://hegocre.crowdin.com/nextcloud-passwords)
[![F-Droid Download](https://img.shields.io/f-droid/v/com.hegocre.nextcloudpasswords.svg?logo=F-Droid)](https://f-droid.org/packages/com.hegocre.nextcloudpasswords/)
[![GitHub Release](https://img.shields.io/github/release/hegocre/NextcloudPasswords.svg?logo=github)](https://github.com/hegocre/NextcloudPasswords/releases/)
[![Google Play Download](https://PlayBadges.pavi2410.me/badge/downloads?id=com.hegocre.nextcloudpasswords&pretty)](https://play.google.com/store/apps/details?id=com.hegocre.nextcloudpasswords)
This app connects to a Nextcloud server with Passwords App installed, and allows to view and edit its content on a user-friendly UI. It also acts as an AutoFill service, making logging in on Android devices easier.
## Features
- Display user passwords and folders on a Material Design UI
- Edit and create passwords, including custom fields
- Edit and create folders
- Show site icons, with cache to minimize data usage (optional)
- Supports self-signed certificates
- App lock screen with both passcode and biometric authentication
- Autofill service (Android 8.0 or higher)
- Uses the latest technologies like Kotlin and Jetpack Compose
- Privacy friendly: The only server this app connects is your own Nextcloud Server
- Free and Open Source
## Screenshots
| ![Light app lock view](/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png) | ![Light password list view](/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png) | ![Light password detail view](/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png) | ![Light password edit view](/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png) |
|----------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| ![Dark app lock view](/fastlane/metadata/android/en-US/images/phoneScreenshots/5.png) | ![Dark password list view](/fastlane/metadata/android/en-US/images/phoneScreenshots/6.png) | ![Dark password detail view](/fastlane/metadata/android/en-US/images/phoneScreenshots/7.png) | ![Dark password edit view](/fastlane/metadata/android/en-US/images/phoneScreenshots/8.png) |
## Download
You can download the app from multiple sources. Keep in mind that each repository version is signed with a different key, which means it is not possible to switch between providers without uninstalling the previous APK first.
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Download it on F-Droid" height="75">](https://f-droid.org/packages/com.hegocre.nextcloudpasswords/)
[<img src="https://user-images.githubusercontent.com/663460/26973090-f8fdc986-4d14-11e7-995a-e7c5e79ed925.png" alt="Download APK from GitHub" height="75">](https://github.com/hegocre/NextcloudPasswords/releases)
[<img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png" alt="Get it on Google Play" height="75">](https://play.google.com/store/apps/details?id=com.hegocre.nextcloudpasswords)
## Contribute
There are many ways you can contribute, including:
- Spread the word! Share the application to help the community grow. A review on Google Play is highly appreciated ⭐
- Help [translate the app](https://translations.hegocre.com/nextcloud-passwords)!. Make the app multilingual. The more languages, the more people it reaches! 🌏
- Contribute with the developement. Hop to the [Issues](https://github.com/hegocre/NextcloudPasswords/issues) page, and if you feel like working on something, be my guest! 🧑🏽‍💻
- [Make a donation](https://paypal.me/hegocre). Your generosity is the only source of income, and any small tip will be invested in coffee in order to survive those long coding nights 😴
## Contact
- Bugs and feature requests: [Issues](https://github.com/hegocre/NextcloudPasswords/issues)
- Email: nextcloudpasswords@hegocre.com
## License
Copyright (C) 2023 Hèctor Godoy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

1
app/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

132
app/build.gradle Normal file
View file

@ -0,0 +1,132 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.devtools.ksp' version "$kotlin_version-$ksp_version"
id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version"
id 'org.jetbrains.kotlin.plugin.compose' version "$kotlin_version"
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
android {
namespace 'com.hegocre.nextcloudpasswords'
compileSdk 35
defaultConfig {
applicationId "com.hegocre.nextcloudpasswords"
minSdk 24
targetSdk 35
versionCode 36
versionName "1.0.11"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
applicationVariants.configureEach { variant ->
variant.resValue "string", "version_name", variant.versionName
variant.resValue "string", "version_code", variant.versionCode.toString()
}
}
androidResources {
generateLocaleConfig = true
}
ksp {
arg("room.schemaLocation", "$projectDir/schemas".toString())
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
applicationIdSuffix ".debug"
versionNameSuffix "-DEBUG"
}
}
splits {
abi {
enable true
universalApk true
}
}
buildFeatures {
compose true
buildConfig true
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
jniLibs {
keepDebugSymbols += ['**/*.so']
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.16.0'
implementation 'androidx.security:security-crypto:1.0.0'
implementation 'androidx.datastore:datastore-preferences:1.1.4'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.goterl:lazysodium-android:5.1.0@aar'
implementation 'net.java.dev.jna:jna:5.17.0@aar'
implementation 'org.commonmark:commonmark:0.24.0'
implementation 'io.coil-kt:coil-compose:2.7.0'
//Compose dependencies
implementation platform('androidx.compose:compose-bom:2025.04.00')
implementation 'androidx.compose.ui:ui'
implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material:material-icons-extended'
implementation 'androidx.compose.runtime:runtime-livedata'
implementation 'androidx.compose.foundation:foundation'
implementation 'androidx.navigation:navigation-compose:2.8.9'
implementation 'androidx.activity:activity-compose:1.10.1'
implementation 'androidx.biometric:biometric:1.1.0'
implementation 'androidx.autofill:autofill:1.1.0'
implementation 'androidx.work:work-runtime-ktx:2.10.0'
//Room dependencies
implementation "androidx.room:room-ktx:$room_version"
ksp "androidx.room:room-compiler:$room_version"
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1'
implementation 'com.materialkolor:material-kolor:2.1.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.arch.core:core-testing:2.2.0'
androidTestImplementation platform('androidx.compose:compose-bom:2025.04.00')
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
}
// Compiler flag to use experimental Compose APIs
tasks.withType(KotlinCompile).configureEach {
compilerOptions {
freeCompilerArgs.addAll("-opt-in=kotlin.RequiresOptIn", "-Xjvm-default=all-compatibility")
}
}

35
app/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1,35 @@
# 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
# Rules for JNA (sodium)
-dontwarn java.awt.*
-keep class com.sun.jna.* { *; }
-keepclassmembers class * extends com.sun.jna.* { public *; }
# OkHttp platform used only on JVM and when Conscrypt and other security providers are available.
-dontwarn okhttp3.internal.platform.**
-dontwarn org.conscrypt.**
-dontwarn org.bouncycastle.**
-dontwarn org.openjsse.**
# This is generated automatically by the Android Gradle plugin.
-dontwarn com.google.errorprone.annotations.Immutable

View file

@ -0,0 +1,212 @@
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "807d8eef8f1631eb109d2349af8e318a",
"entities": [
{
"tableName": "favicons",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `data` BLOB NOT NULL, PRIMARY KEY(`url`))",
"fields": [
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "data",
"columnName": "data",
"affinity": "BLOB",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"url"
]
},
"indices": [
{
"name": "index_favicons_url",
"unique": true,
"columnNames": [
"url"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favicons_url` ON `${TABLE_NAME}` (`url`)"
}
],
"foreignKeys": []
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `parent` TEXT NOT NULL, `revision` TEXT NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parent",
"columnName": "parent",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
},
{
"tableName": "passwords",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `url` TEXT NOT NULL, `revision` TEXT NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, `favorite` INTEGER NOT NULL, `folder` TEXT NOT NULL, `status` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "password",
"columnName": "password",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "folder",
"columnName": "folder",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_passwords_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_passwords_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '807d8eef8f1631eb109d2349af8e318a')"
]
}
}

View file

@ -0,0 +1,332 @@
{
"formatVersion": 1,
"database": {
"version": 2,
"identityHash": "ceb1b4aae289d6612d8fc78484b48c1b",
"entities": [
{
"tableName": "favicons",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `data` BLOB NOT NULL, PRIMARY KEY(`url`))",
"fields": [
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "data",
"columnName": "data",
"affinity": "BLOB",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"url"
]
},
"indices": [
{
"name": "index_favicons_url",
"unique": true,
"columnNames": [
"url"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favicons_url` ON `${TABLE_NAME}` (`url`)"
}
],
"foreignKeys": []
},
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `parent` TEXT NOT NULL, `revision` TEXT NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, `client` TEXT NOT NULL, `hidden` INTEGER NOT NULL, `trashed` INTEGER NOT NULL, `favorite` INTEGER NOT NULL, `created` INTEGER NOT NULL, `updated` INTEGER NOT NULL, `edited` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parent",
"columnName": "parent",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "client",
"columnName": "client",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hidden",
"columnName": "hidden",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trashed",
"columnName": "trashed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "created",
"columnName": "created",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updated",
"columnName": "updated",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "edited",
"columnName": "edited",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
},
{
"tableName": "passwords",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `url` TEXT NOT NULL, `notes` TEXT NOT NULL, `customFields` TEXT NOT NULL, `status` INTEGER NOT NULL, `statusCode` TEXT NOT NULL, `hash` TEXT NOT NULL, `folder` TEXT NOT NULL, `revision` TEXT NOT NULL, `share` TEXT, `shared` INTEGER NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, `client` TEXT NOT NULL, `hidden` INTEGER NOT NULL, `trashed` INTEGER NOT NULL, `favorite` INTEGER NOT NULL, `editable` INTEGER NOT NULL, `edited` INTEGER NOT NULL, `created` INTEGER NOT NULL, `updated` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "password",
"columnName": "password",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notes",
"columnName": "notes",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "customFields",
"columnName": "customFields",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "statusCode",
"columnName": "statusCode",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hash",
"columnName": "hash",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folder",
"columnName": "folder",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "share",
"columnName": "share",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "shared",
"columnName": "shared",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "client",
"columnName": "client",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hidden",
"columnName": "hidden",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trashed",
"columnName": "trashed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "editable",
"columnName": "editable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "edited",
"columnName": "edited",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "created",
"columnName": "created",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updated",
"columnName": "updated",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_passwords_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_passwords_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ceb1b4aae289d6612d8fc78484b48c1b')"
]
}
}

View file

@ -0,0 +1,296 @@
{
"formatVersion": 1,
"database": {
"version": 3,
"identityHash": "93e9a73ac790c295e6009993d8ff5c56",
"entities": [
{
"tableName": "folders",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `parent` TEXT NOT NULL, `revision` TEXT NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, `client` TEXT NOT NULL, `hidden` INTEGER NOT NULL, `trashed` INTEGER NOT NULL, `favorite` INTEGER NOT NULL, `created` INTEGER NOT NULL, `updated` INTEGER NOT NULL, `edited` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parent",
"columnName": "parent",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "client",
"columnName": "client",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hidden",
"columnName": "hidden",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trashed",
"columnName": "trashed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "created",
"columnName": "created",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updated",
"columnName": "updated",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "edited",
"columnName": "edited",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_folders_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
},
{
"tableName": "passwords",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `label` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `url` TEXT NOT NULL, `notes` TEXT NOT NULL, `customFields` TEXT NOT NULL, `status` INTEGER NOT NULL, `statusCode` TEXT NOT NULL, `hash` TEXT NOT NULL, `folder` TEXT NOT NULL, `revision` TEXT NOT NULL, `share` TEXT, `shared` INTEGER NOT NULL, `cseType` TEXT NOT NULL, `cseKey` TEXT NOT NULL, `sseType` TEXT NOT NULL, `client` TEXT NOT NULL, `hidden` INTEGER NOT NULL, `trashed` INTEGER NOT NULL, `favorite` INTEGER NOT NULL, `editable` INTEGER NOT NULL, `edited` INTEGER NOT NULL, `created` INTEGER NOT NULL, `updated` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "password",
"columnName": "password",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notes",
"columnName": "notes",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "customFields",
"columnName": "customFields",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "statusCode",
"columnName": "statusCode",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hash",
"columnName": "hash",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "folder",
"columnName": "folder",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "revision",
"columnName": "revision",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "share",
"columnName": "share",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "shared",
"columnName": "shared",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "cseType",
"columnName": "cseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "cseKey",
"columnName": "cseKey",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sseType",
"columnName": "sseType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "client",
"columnName": "client",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hidden",
"columnName": "hidden",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trashed",
"columnName": "trashed",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "favorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "editable",
"columnName": "editable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "edited",
"columnName": "edited",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "created",
"columnName": "created",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "updated",
"columnName": "updated",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_passwords_id",
"unique": true,
"columnNames": [
"id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_passwords_id` ON `${TABLE_NAME}` (`id`)"
}
],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '93e9a73ac790c295e6009993d8ff5c56')"
]
}
}

View file

@ -0,0 +1,33 @@
package com.hegocre.nextcloudpasswords
import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class ApiControllerTest {
private lateinit var context: Context
@Before
fun setup() {
context = InstrumentationRegistry.getInstrumentation().targetContext
with(PreferencesManager.getInstance(context)) {
setLoggedInServer("")
setLoggedInUser("")
setLoggedInPassword("")
}
}
@Test
fun ignoreCertificateErrorsTest() {
PreferencesManager.getInstance(context).setSkipCertificateValidation(true)
ApiController.getInstance(context)
val okHttpRequest = OkHttpRequest.getInstance()
Assert.assertEquals(okHttpRequest.allowInsecureRequests, true)
}
}

View file

@ -0,0 +1,79 @@
package com.hegocre.nextcloudpasswords
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.platform.app.InstrumentationRegistry
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.databases.AppDatabase
import com.hegocre.nextcloudpasswords.databases.passworddatabase.PasswordDatabaseDao
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import java.io.IOException
class PasswordDatabaseTest {
@get:Rule
val instantExecutorRUle: TestRule = InstantTaskExecutorRule()
private lateinit var passwordDatabaseDao: PasswordDatabaseDao
private lateinit var database: AppDatabase
@Before
fun createDb() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
database = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.allowMainThreadQueries()
.build()
passwordDatabaseDao = database.passwordDao
}
@After
@Throws(IOException::class)
fun closeDb() {
database.close()
}
@Test
@Throws(Exception::class)
fun insertAndGet() = runTest {
val password = Password(
id = "",
label = "Nextcloud",
username = "john_doe",
password = "secret_value",
url = "https://nextcloud.com/",
notes = "",
customFields = "",
status = 0,
statusCode = "GOOD",
hash = "",
folder = "",
revision = "",
share = null,
shared = false,
cseType = "",
cseKey = "",
sseType = "",
client = "",
hidden = false,
trashed = false,
favorite = true,
editable = true,
edited = 0,
created = 0,
updated = 0
)
passwordDatabaseDao.insertPassword(password)
passwordDatabaseDao.fetchAllPasswords().value?.let {
assertEquals(it, listOf(password))
}
}
}

View file

@ -0,0 +1,77 @@
package com.hegocre.nextcloudpasswords
import com.goterl.lazysodium.LazySodiumAndroid
import com.goterl.lazysodium.SodiumAndroid
import com.goterl.lazysodium.interfaces.AEAD
import com.goterl.lazysodium.interfaces.Box
import com.goterl.lazysodium.interfaces.GenericHash
import com.goterl.lazysodium.interfaces.PwHash
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.utils.LazySodiumUtils
import com.hegocre.nextcloudpasswords.utils.decryptValue
import com.hegocre.nextcloudpasswords.utils.encryptValue
import org.junit.Assert
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Locale
class SodiumTest {
@Test
fun testSodiumSolve() {
val salts = Array(3) { "" }
salts[0] = ""
salts[1] = ""
salts[2] = ""
val password = ""
val sodium = LazySodiumAndroid(SodiumAndroid())
val passwordSalt = sodium.sodiumHex2Bin(salts[0])
val genericHashKey = sodium.sodiumHex2Bin(salts[1])
val passwordHashSalt = sodium.sodiumHex2Bin(salts[2])
val input = sodium.bytes(password) + passwordSalt
val genericHash = ByteArray(GenericHash.BYTES_MAX)
!sodium.cryptoGenericHash(
genericHash,
genericHash.size,
input,
input.size.toLong(),
genericHashKey,
genericHashKey.size
)
val passwordHash = ByteArray(Box.SEEDBYTES)
!sodium.cryptoPwHash(
passwordHash,
passwordHash.size,
genericHash,
genericHash.size,
passwordHashSalt,
PwHash.OPSLIMIT_INTERACTIVE,
PwHash.MEMLIMIT_INTERACTIVE,
PwHash.Alg.PWHASH_ALG_ARGON2ID13
)
val secret = sodium.sodiumBin2Hex(passwordHash)
assertTrue(secret.lowercase(Locale.getDefault()) == "")
}
@Test
fun decryption_isCorrect() {
val sodium = LazySodiumUtils.getSodium()
val key = sodium.keygen(AEAD.Method.AES256GCM)
val csEv1Keychain = CSEv1Keychain(
mapOf("test_key" to key.asHexString),
"test_key"
)
val testString = "abcdefg_12345678"
val encryptedString = testString.encryptValue("test_key", csEv1Keychain)
val decryptedString = encryptedString.decryptValue("test_key", csEv1Keychain)
Assert.assertEquals(testString, decryptedString)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View file

@ -0,0 +1,31 @@
<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">
<group
android:scaleX="0.08035714"
android:scaleY="0.08035714">
<path
android:fillType="evenOdd"
android:pathData="M0,0h1344v1344h-1344z"
android:strokeLineJoin="round">
<aapt:attr name="android:fillColor">
<gradient
android:endX="1343.9999"
android:endY="1.2959057E-4"
android:startX="163.34073"
android:startY="1344.0002"
android:type="linear">
<item
android:color="#F6A110"
android:offset="0" />
<item
android:color="#F1BA5B"
android:offset="1" />
</gradient>
</aapt:attr>
</path>
</group>
</vector>

View file

@ -0,0 +1,16 @@
<!-- drawable/ic_launcher_foreground.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<group
android:scaleX="1.98"
android:scaleY="1.98"
android:translateX="30.24"
android:translateY="30.24">
<path
android:fillColor="#fff"
android:pathData="M17,7H22V17H17V19A1,1 0 0,0 18,20H20V22H17.5C16.95,22 16,21.55 16,21C16,21.55 15.05,22 14.5,22H12V20H14A1,1 0 0,0 15,19V5A1,1 0 0,0 14,4H12V2H14.5C15.05,2 16,2.45 16,3C16,2.45 16.95,2 17.5,2H20V4H18A1,1 0 0,0 17,5V7M2,7H13V9H4V15H13V17H2V7M20,15V9H17V15H20M8.5,12A1.5,1.5 0 0,0 7,10.5A1.5,1.5 0 0,0 5.5,12A1.5,1.5 0 0,0 7,13.5A1.5,1.5 0 0,0 8.5,12M13,10.89C12.39,10.33 11.44,10.38 10.88,11C10.32,11.6 10.37,12.55 11,13.11C11.55,13.63 12.43,13.63 13,13.11V10.89Z" />
</group>
</vector>

View file

@ -0,0 +1,6 @@
<?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" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">NextCloud Passwords Debug</string>
</resources>

View file

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission"
tools:targetApi="s" />
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:dataExtractionRules="@xml/data_extraction_rules"
android:supportsRtl="true"
android:fullBackupContent="@xml/full_backup_content"
android:networkSecurityConfig="@xml/network_security_config"
android:theme="@style/Theme.NextcloudPasswords"
android:enableOnBackInvokedCallback="true"
tools:ignore="UnusedAttribute">
<activity
android:name=".ui.activities.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.hegocre.nextcloudpasswords.action.main" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.WebLoginActivity"
android:exported="false">
<intent-filter>
<action android:name="com.hegocre.nextcloudpasswords.action.weblogin" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.LoginActivity"
android:exported="false">
<intent-filter>
<action android:name="com.hegocre.nextcloudpasswords.action.login" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.SettingsActivity"
android:exported="false">
<intent-filter>
<action android:name="com.hegocre.nextcloudpasswords.action.settings" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.AboutActivity"
android:exported="false">
<intent-filter>
<action android:name="com.hegocre.nextcloudpasswords.action.about" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".services.autofill.NCPAutofillService"
android:exported="true"
android:label="@string/app_name"
android:permission="android.permission.BIND_AUTOFILL_SERVICE">
<intent-filter>
<action android:name="android.service.autofill.AutofillService" />
</intent-filter>
<meta-data
android:name="android.autofill"
android:resource="@xml/service_configuration" />
</service>
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View file

@ -0,0 +1,383 @@
package com.hegocre.nextcloudpasswords.api
import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.work.WorkManager
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyInvalidException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyNeededException
import com.hegocre.nextcloudpasswords.data.folder.DeletedFolder
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.folder.NewFolder
import com.hegocre.nextcloudpasswords.data.folder.UpdatedFolder
import com.hegocre.nextcloudpasswords.data.password.DeletedPassword
import com.hegocre.nextcloudpasswords.data.password.NewPassword
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.data.password.UpdatedPassword
import com.hegocre.nextcloudpasswords.data.user.UserController
import com.hegocre.nextcloudpasswords.services.keepalive.KeepAliveWorker
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Class with methods used to interact with [the API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api)
* classes. This is a Singleton class and will have only one instance.
*
* @param context Context of the application.
*/
class ApiController private constructor(context: Context) {
private val server = UserController.getInstance(context).getServer()
private val preferencesManager = PreferencesManager.getInstance(context)
private val passwordsApi = PasswordsApi.getInstance(server)
private val foldersApi = FoldersApi.getInstance(server)
private val sessionApi = SessionApi.getInstance(server)
private val serviceApi = ServiceApi.getInstance(server)
private val settingsApi = SettingsApi.getInstance(server)
private var sessionCode: String? = null
val csEv1Keychain = MutableLiveData<CSEv1Keychain?>(null)
val serverSettings = MutableLiveData(
preferencesManager.getServerSettings()
)
private val _sessionOpen = MutableStateFlow(false)
val sessionOpen: StateFlow<Boolean>
get() = _sessionOpen.asStateFlow()
private val workManager = WorkManager.getInstance(context)
init {
decryptCSEv1Keychain(
preferencesManager.getCSEv1Keychain(),
preferencesManager.getMasterPassword()
)?.let {
csEv1Keychain.postValue(it)
}
CoroutineScope(Dispatchers.IO).launch {
var result = settingsApi.get()
while (result !is Result.Success) {
Log.e("ServerSettings", "Error getting server settings")
delay(5000L)
result = settingsApi.get()
}
Log.i("ServerSettings", "Got server settings")
val settings = result.data
serverSettings.postValue(settings)
preferencesManager.setServerSettings(settings)
preferencesManager.setInstanceColor(settings.themeColorPrimary)
}
OkHttpRequest.getInstance().allowInsecureRequests =
preferencesManager.getSkipCertificateValidation()
}
private fun decryptCSEv1Keychain(
encryptedData: String?,
masterPassword: String?
): CSEv1Keychain? = try {
encryptedData?.let { encryptedCSEv1Keychain ->
masterPassword?.let { masterPassword ->
val decryptedCsEv1KeychainJson = CSEv1Keychain.decryptJson(
encryptedCSEv1Keychain,
masterPassword
)
CSEv1Keychain.fromJson(decryptedCsEv1KeychainJson)
}
}
} catch (e: Exception) {
null
}
/**
* Requests and opens a session via the [SessionApi] class.
*
* @param masterPassword Master password to request the session, if provided, and not needed
* if no CSE used.
* @return A boolean indicating if the session was successfully opened.
* @throws PWDv1ChallengeMasterKeyNeededException If there is no master key provided, but one is
* needed.
* @throws PWDv1ChallengeMasterKeyInvalidException If a master key was provided, but is not valid.
*/
@Throws(
PWDv1ChallengeMasterKeyNeededException::class,
PWDv1ChallengeMasterKeyInvalidException::class
)
suspend fun openSession(masterPassword: String?): Boolean = withContext(Dispatchers.Default) {
decryptCSEv1Keychain(
preferencesManager.getCSEv1Keychain(),
masterPassword
)?.let {
csEv1Keychain.postValue(it)
}
val requestResult = sessionApi.requestSession()
val secretResult = if (requestResult is Result.Success) {
requestResult.data.solve(masterPassword)
} else {
// Error opening session
if (requestResult is Result.Error) {
// Could not open session, try to use cached keychain
preferencesManager.getCSEv1Keychain()?.let { cachedKeychain ->
if (masterPassword == null) {
throw PWDv1ChallengeMasterKeyNeededException()
} else {
decryptCSEv1Keychain(cachedKeychain, masterPassword)?.let {
csEv1Keychain.postValue(it)
} ?: throw PWDv1ChallengeMasterKeyInvalidException() // Could not decrypt
}
}
// If we get here, keychain was decrypted from cache, but session is still not open
when (requestResult.code) {
Error.API_TIMEOUT -> Log.e(
"API Controller",
"Timeout requesting session, user ${server.username}"
)
Error.API_BAD_RESPONSE -> Log.e(
"API Controller",
"Bad response on session request, user ${server.username}"
)
}
}
return@withContext false
}
val secret = if (secretResult is Result.Success) {
secretResult.data
} else {
return@withContext if (secretResult is Result.Error && secretResult.code == Error.API_NO_CSE) {
// No encryption, we need no session
// Clear old keychain, if CSE was disabled
preferencesManager.setCSEv1Keychain(null)
_sessionOpen.emit(true)
true
} else {
// Error opening session
false
}
}
val openedSessionRequest = sessionApi.openSession(secret)
val (newSessionCode, encryptedKeychainJson) = if (openedSessionRequest is Result.Success) {
openedSessionRequest.data
} else {
if (openedSessionRequest is Result.Error) {
when (openedSessionRequest.code) {
Error.API_TIMEOUT -> Log.e(
"API Controller",
"Timeout opening session, user ${server.username}"
)
Error.API_BAD_RESPONSE -> Log.e(
"API Controller",
"Bad response on session open, user ${server.username}"
)
}
}
return@withContext false
}
preferencesManager.setCSEv1Keychain(encryptedKeychainJson)
encryptedKeychainJson.let {
masterPassword?.let { masterPassword ->
val keysJson = CSEv1Keychain.decryptJson(encryptedKeychainJson, masterPassword)
csEv1Keychain.postValue(CSEv1Keychain.fromJson(keysJson))
}
}
sessionCode = newSessionCode
serverSettings.value?.let { settings ->
val keepAliveDelay = (settings.sessionLifetime * 3 / 4 * 1000).toLong()
workManager.cancelAllWorkByTag(KeepAliveWorker.TAG)
workManager.enqueue(KeepAliveWorker.getRequest(keepAliveDelay, newSessionCode))
}
_sessionOpen.emit(true)
return@withContext true
}
/**
* Closes the current session and deletes the saved keychain from the app storage.
*
* @return A boolean indicating if the session was successfully closed.
*/
suspend fun closeSession(): Boolean {
return if (sessionCode == null || sessionCode?.let { code -> sessionApi.closeSession(code) } == true) {
_sessionOpen.emit(false)
preferencesManager.setCSEv1Keychain(null)
true
} else {
// Session was not closed, some error happened
false
}
}
suspend fun clearSession() {
_sessionOpen.emit(false)
sessionCode = null
}
/**
* Gets a list of the user passwords via the [PasswordsApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @return A result with the list of passwords if success, or an error code otherwise.
*/
suspend fun listPasswords(): Result<List<Password>> {
if (!sessionOpen.value) return Result.Error(Error.API_NO_SESSION)
return passwordsApi.list(sessionCode)
}
/**
* Gets a list of the user folders via the [FoldersApi] class. This can only be called when a session
* is open, otherwise an error is thrown.
*
* @return A result with the list of folders if success, or an error code otherwise.
*/
suspend fun listFolders(): Result<List<Folder>> {
if (!sessionOpen.value) return Result.Error(Error.API_NO_SESSION)
return foldersApi.list(sessionCode)
}
/**
* Creates a new password via the [PasswordsApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param newPassword [NewPassword] object to be created.
* @return A boolean stating whether the password was successfully created.
*/
suspend fun createPassword(newPassword: NewPassword): Boolean {
if (!sessionOpen.value) return false
val result = passwordsApi.create(newPassword, sessionCode)
return result is Result.Success
}
/**
* Updates an existing password via the [PasswordsApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param updatedPassword [UpdatedPassword] object to be updated.
* @return A boolean stating whether the password was successfully updated.
*/
suspend fun updatePassword(updatedPassword: UpdatedPassword): Boolean {
if (!sessionOpen.value) return false
val result = passwordsApi.update(updatedPassword, sessionCode)
return result is Result.Success
}
/**
* Deletes an existing password via the [PasswordsApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param deletedPassword [DeletedPassword] object to be deleted.
* @return A boolean stating whether the password was successfully deleted.
*/
suspend fun deletePassword(deletedPassword: DeletedPassword): Boolean {
if (!sessionOpen.value) return false
val result = passwordsApi.delete(deletedPassword, sessionCode)
return result is Result.Success
}
/**
* Generates a random password using user's settings. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @return A string with the generated password, or null if there was an error.
*/
suspend fun generatePassword(
strength: Int,
includeDigits: Boolean,
includeSymbols: Boolean
): String? {
if (!sessionOpen.value) return null
val result = serviceApi.password(strength, includeDigits, includeSymbols, sessionCode)
return if (result is Result.Success) result.data else null
}
/**
* Creates a new folder via the [FoldersApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param newFolder [NewFolder] object to be created.
* @return A boolean stating whether the folder was successfully created.
*/
suspend fun createFolder(newFolder: NewFolder): Boolean {
if (!sessionOpen.value) return false
val result = foldersApi.create(newFolder, sessionCode)
return result is Result.Success
}
/**
* Updates an existing folder via the [FoldersApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param updatedFolder [UpdatedFolder] object to be updated.
* @return A boolean stating whether the folder was successfully updated.
*/
suspend fun updateFolder(updatedFolder: UpdatedFolder): Boolean {
if (!sessionOpen.value) return false
val result = foldersApi.update(updatedFolder, sessionCode)
return result is Result.Success
}
/**
* Deletes an existing folder via the [FoldersApi] class. This can only be called when a
* session is open, otherwise an error is thrown.
*
* @param deletedFolder [DeletedFolder] object to be deleted.
* @return A boolean stating whether the folder was successfully deleted.
*/
suspend fun deleteFolder(deletedFolder: DeletedFolder): Boolean {
if (!sessionOpen.value) return false
val result = foldersApi.delete(deletedFolder, sessionCode)
return result is Result.Success
}
fun getFaviconServiceRequest(url: String): Pair<String, Server> =
Pair(serviceApi.getFaviconUrl(url), server)
fun getAvatarServiceRequest(): Pair<String, Server> =
Pair(serviceApi.getAvatarUrl(), server)
companion object {
private var instance: ApiController? = null
/**
* Get the instance of the [ApiController], and create it if null.
*
* @param context Context of the application.
* @return The instance of the controller.
*/
fun getInstance(context: Context): ApiController {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = ApiController(context)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,260 @@
package com.hegocre.nextcloudpasswords.api
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.data.folder.DeletedFolder
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.folder.NewFolder
import com.hegocre.nextcloudpasswords.data.folder.UpdatedFolder
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
/**
* Class with methods used to interact with the
* [Folder API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Folder-Api).
* This is a Singleton class and will have only one instance.
*
* @property server The [Server] where the requests will be made.
*/
class FoldersApi private constructor(private var server: Server) {
/**
* Sends a request to the api to list all the user passwords. If the user uses CSE, a
* session code needs to be provided in order for the request to succeed.
*
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result with a list of folders if success, or with an error code otherwise
*/
suspend fun list(
sessionCode: String? = null
): Result<List<Folder>> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = server.url + LIST_URL,
sessionCode = sessionCode,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200 || body == null) return Result.Error(Error.API_BAD_RESPONSE)
withContext(Dispatchers.Default) {
Result.Success(Json.decodeFromString(body))
}
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to create a new folder. If the user uses CSE, the
* folder needs to be encrypted.
*
* @param newFolder The [NewFolder] object of the created folder.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun create(
newFolder: NewFolder,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().post(
sUrl = server.url + CREATE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(newFolder),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 201) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to update a folder. If the user uses CSE, the
* folder needs to be encrypted.
*
* @param updatedFolder The [UpdatedFolder] object of the edited folder.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun update(
updatedFolder: UpdatedFolder,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().patch(
sUrl = server.url + UPDATE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(updatedFolder),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to delete a folder.
*
* @param deletedFolder The [DeletedFolder] object of the folder to be deleted.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun delete(
deletedFolder: DeletedFolder,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().delete(
sUrl = server.url + DELETE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(deletedFolder),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
companion object {
private const val LIST_URL = "/index.php/apps/passwords/api/1.0/folder/list"
private const val CREATE_URL = "/index.php/apps/passwords/api/1.0/folder/create"
private const val UPDATE_URL = "/index.php/apps/passwords/api/1.0/folder/update"
private const val DELETE_URL = "/index.php/apps/passwords/api/1.0/folder/delete"
const val DEFAULT_FOLDER_UUID = "00000000-0000-0000-0000-000000000000"
private var instance: FoldersApi? = null
/**
* Get the instance of the [FoldersApi], and create it if null.
*
* @param server The [Server] where the requests will be made.
* @return The instance of the api.
*/
fun getInstance(server: Server): FoldersApi {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = FoldersApi(server)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,260 @@
package com.hegocre.nextcloudpasswords.api
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.data.password.DeletedPassword
import com.hegocre.nextcloudpasswords.data.password.NewPassword
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.data.password.UpdatedPassword
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
/**
* Class with methods used to interact with the
* [Password API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api).
* This is a Singleton class and will have only one instance.
*
* @param server The [Server] where the requests will be made.
*/
class PasswordsApi private constructor(private var server: Server) {
/**
* Sends a request to the api to list all the user passwords. If the user uses CSE, a
* session code needs to be provided in order for the request to succeed.
*
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result with a list of passwords if success, or with an error code otherwise
*/
suspend fun list(
sessionCode: String? = null,
): Result<List<Password>> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = server.url + LIST_URL,
sessionCode = sessionCode,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200 || body == null) {
return Result.Error(Error.API_BAD_RESPONSE)
}
withContext(Dispatchers.Default) {
Result.Success(Json.decodeFromString(body))
}
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to create a new password. If the user uses CSE, the
* password needs to be encrypted.
*
* @param newPassword The [NewPassword] object of the created password.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun create(
newPassword: NewPassword,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().post(
sUrl = server.url + CREATE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(newPassword),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 201) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to update a password. If the user uses CSE, the
* password needs to be encrypted.
*
* @param updatedPassword The [UpdatedPassword] object of the edited password.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun update(
updatedPassword: UpdatedPassword,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().patch(
sUrl = server.url + UPDATE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(updatedPassword),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to delete a password.
*
* @param deletedPassword The [DeletedPassword] object of the password to be deleted.
* @param sessionCode Code of the current session, only needed if CSE enabled.
* @return A result if success, or an error code otherwise
*/
suspend fun delete(
deletedPassword: DeletedPassword,
sessionCode: String? = null
): Result<Unit> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().delete(
sUrl = server.url + DELETE_URL,
sessionCode = sessionCode,
body = Json.encodeToString(deletedPassword),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200) {
return Result.Error(Error.API_BAD_RESPONSE)
}
Result.Success(Unit)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
companion object {
private const val LIST_URL = "/index.php/apps/passwords/api/1.0/password/list"
private const val CREATE_URL = "/index.php/apps/passwords/api/1.0/password/create"
private const val UPDATE_URL = "/index.php/apps/passwords/api/1.0/password/update"
private const val DELETE_URL = "/index.php/apps/passwords/api/1.0/password/delete"
private var instance: PasswordsApi? = null
/**
* Get the instance of the [PasswordsApi], and create it if null.
*
* @param server The [Server] where the requests will be made.
* @return The instance of the api.
*/
fun getInstance(server: Server): PasswordsApi {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = PasswordsApi(server)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,16 @@
package com.hegocre.nextcloudpasswords.api
/**
* A data class representing an authenticated server where requests can be made. The credentials
* can be obtained using the
* [Nextcloud login flow](https://docs.nextcloud.com/server/latest/developer_manual/client_apis/LoginFlow/index.html).
*
* @property url The url of the server, without a trailing `/`.
* @property username The username used to authenticate on the server.
* @property password The password used to authenticate on the server. This is usually an app password.
*/
data class Server(
val url: String,
val username: String,
val password: String
)

View file

@ -0,0 +1,129 @@
package com.hegocre.nextcloudpasswords.api
import android.util.Log
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.data.password.GeneratedPassword
import com.hegocre.nextcloudpasswords.data.password.RequestedPassword
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.SocketTimeoutException
import java.net.URLEncoder
import java.util.Locale
import javax.net.ssl.SSLHandshakeException
/**
* Class with methods used to interact with the
* [Service API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Service-Api).
* This is a Singleton class and will have only one instance.
*
* @param server The [Server] where the requests will be made.
*/
class ServiceApi private constructor(private val server: Server) {
/**
* Sends a request to the api to obtain a generated password using user settings.
*
* @return A result with the password as aString if success, and an error code otherwise.
*/
suspend fun password(
strength: Int,
includeDigits: Boolean,
includeSymbols: Boolean,
sessionCode: String?
): Result<String> {
return try {
val requestBody = Json.encodeToString(
RequestedPassword(strength, includeDigits, includeSymbols)
)
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().post(
sUrl = server.url + PASSWORD_URL,
sessionCode = sessionCode,
username = server.username,
password = server.password,
body = requestBody,
mediaType = OkHttpRequest.JSON
)
}
val code = apiResponse.code
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code != 200 || body == null) {
Log.d("SERVICE API", "Code response $code")
return Result.Error(Error.API_BAD_RESPONSE)
}
withContext(Dispatchers.Default) {
Result.Success(Json.decodeFromString<GeneratedPassword>(body).password)
}
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
fun getFaviconUrl(url: String): String =
server.url + String.format(
Locale.getDefault(),
FAVICON_URL,
URLEncoder.encode(url, "utf-8"),
256
)
fun getAvatarUrl(): String =
server.url + String.format(
Locale.getDefault(),
AVATAR_URL,
URLEncoder.encode(server.username, "utf-8"),
256
)
companion object {
private const val FAVICON_URL = "/index.php/apps/passwords/api/1.0/service/favicon/%s/%d"
private const val PASSWORD_URL = "/index.php/apps/passwords/api/1.0/service/password"
private const val AVATAR_URL = "/index.php/apps/passwords/api/1.0/service/avatar/%s/%d"
private var instance: ServiceApi? = null
/**
* Get the instance of the [ServiceApi], and create it if null.
*
* @param server The [Server] where the requests will be made.
* @return The instance of the api.
*/
fun getInstance(server: Server): ServiceApi {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = ServiceApi(server)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,231 @@
package com.hegocre.nextcloudpasswords.api
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.api.encryption.PWDv1Challenge
import com.hegocre.nextcloudpasswords.api.exceptions.ClientDeauthorizedException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyInvalidException
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
/**
* Class with methods used to interact with the
* [Session API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Session-Api).
* This is a Singleton class and will have only one instance.
*
* @param server The [Server] where the requests will be made.
*/
class SessionApi private constructor(private var server: Server) {
/**
* Sends a request to the api to open a session. If the user uses client-side encryption,
* it returns a challenge with 3 salts. If no CSE used, the challenge is empty.
*
* @return Result with the [PWDv1Challenge] if success, or with an error code otherwise.
*/
suspend fun requestSession(): Result<PWDv1Challenge> {
return try {
val apiResponse = try {
withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = server.url + REQUEST_URL,
username = server.username,
password = server.password
)
}
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
return Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
return Result.Error(0)
}
val code = apiResponse.code
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code == 403 || code == 401)
throw ClientDeauthorizedException()
if (code == 200) {
Result.Success(PWDv1Challenge.fromJson(body ?: "{}"))
} else Result.Error(Error.API_BAD_RESPONSE)
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
}
}
/**
* Sends a request to the Session API to open a session. This only needs to be called if the user
* uses CSE encryption.
*
* @param solvedChallenge The solved PWDv1Challenge via [libsodium](https://doc.libsodium.org/)
* using the master password.
* @return Result with a pair with the session code and the encrypted keychain JSON if success,
* or an error code otherwise.
* @throws PWDv1ChallengeMasterKeyInvalidException If a master key was provided, but is not valid.
* @throws ClientDeauthorizedException If too many incorrect attempts were made and
* the client has been deauthorized.
*/
suspend fun openSession(solvedChallenge: String): Result<Pair<String, String>> {
val jsonChallenge = JSONObject()
.put("challenge", solvedChallenge)
.toString()
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().post(
sUrl = server.url + OPEN_URL,
body = jsonChallenge,
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password
)
}
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
val code = apiResponse.code
val xSessionCode = apiResponse.header("x-api-session", null)
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code == 401)
throw PWDv1ChallengeMasterKeyInvalidException()
if (code == 403)
throw ClientDeauthorizedException()
if (xSessionCode == null || body == null || code != 200)
return Result.Error(Error.API_BAD_RESPONSE)
Result.Success(Pair(xSessionCode, body))
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
/**
* Sends a request to the api to keep the session alive. For this to be called, a session
* needs to be open.
*
* @param sessionCode The session code of the current session.
* @return A boolean indicating if the request was successful.
*/
suspend fun keepAlive(sessionCode: String): Boolean {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = server.url + KEEPALIVE_URL,
sessionCode = sessionCode,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
code == 200
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
false
}
}
/**
* Sends a request to the api to close the current session. For this to be called, a session
* needs to be open.
*
* @param sessionCode The session code of the current session.
* @return A boolean indicating if the request was successful.
*/
suspend fun closeSession(sessionCode: String): Boolean {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().get(
sUrl = server.url + CLOSE_URL,
sessionCode = sessionCode,
username = server.username,
password = server.password
)
}
val code = apiResponse.code
withContext(Dispatchers.IO) {
apiResponse.close()
}
code == 200
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
false
}
}
companion object {
private const val REQUEST_URL = "/index.php/apps/passwords/api/1.0/session/request"
private const val OPEN_URL = "/index.php/apps/passwords/api/1.0/session/open"
private const val CLOSE_URL = "/index.php/apps/passwords/api/1.0/session/close"
private const val KEEPALIVE_URL = "/index.php/apps/passwords/api/1.0/session/keepalive"
private var instance: SessionApi? = null
/**
* Get the instance of the [SessionApi], and create it if null.
*
* @param server The [Server] where the requests will be made.
* @return The instance of the api.
*/
fun getInstance(server: Server): SessionApi {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = SessionApi(server)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,89 @@
package com.hegocre.nextcloudpasswords.api
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.data.serversettings.ServerSettings
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
class SettingsApi private constructor(private val server: Server) {
/**
* Sends a request to the api to obtain required user settings. No session is required to send this request.
*
* @return A result with the [ServerSettings] object if success, and an error code otherwise.
*/
suspend fun get(): Result<ServerSettings> {
return try {
val apiResponse = withContext(Dispatchers.IO) {
OkHttpRequest.getInstance().post(
sUrl = server.url + GET_URL,
body = ServerSettings.getRequestBody(),
mediaType = OkHttpRequest.JSON,
username = server.username,
password = server.password,
)
}
val code = apiResponse.code
val body = withContext(Dispatchers.IO) { apiResponse.body?.string() }
withContext(Dispatchers.IO) {
apiResponse.close()
}
if (code == 200 && body != null) {
Result.Success(Json.decodeFromString(body))
} else {
Result.Error(Error.API_BAD_RESPONSE)
}
} catch (e: SocketTimeoutException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.API_TIMEOUT)
} catch (e: SSLHandshakeException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.SSL_HANDSHAKE_EXCEPTION)
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
Result.Error(Error.UNKNOWN)
}
}
companion object {
private const val GET_URL = "/index.php/apps/passwords/api/1.0/settings/get"
private var instance: SettingsApi? = null
/**
* Get the instance of the [ServiceApi], and create it if null.
*
* @param server The [Server] where the requests will be made.
* @return The instance of the api.
*/
fun getInstance(server: Server): SettingsApi {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = SettingsApi(server)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,121 @@
package com.hegocre.nextcloudpasswords.api.encryption
import com.goterl.lazysodium.interfaces.Box
import com.goterl.lazysodium.interfaces.PwHash
import com.goterl.lazysodium.interfaces.SecretBox
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.api.exceptions.SodiumDecryptionException
import com.hegocre.nextcloudpasswords.utils.LazySodiumUtils
import okio.internal.commonToUtf8String
import org.json.JSONException
import org.json.JSONObject
/**
* Object containing all the keys in the user keychain, used to decrypt data. See the
* [API reference](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Encryption/CSEv1Keychain).
*
* @property keys Encoded keys, each one identified by an id.
* @property current Id of the current key used to encrypt new data.
*/
data class CSEv1Keychain(
val keys: Map<String, String>,
val current: String
) {
companion object {
/**
* Return a JSON string from an encrypted API response. The string must be decrypted
* using the same password as the one used to open the session.
*
* @param data The encrypted data from the response.
* @param password Master password used to decrypt the response.
* @return A JSON object with the actual keychain.
*/
fun decryptJson(data: String, password: String): String {
val obj = JSONObject(data)
val encryptedJson = try {
val keysObj = obj.getJSONObject("keys")
keysObj.getString("CSEv1r1")
} catch (e: JSONException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
return ""
}
val sodium = LazySodiumUtils.getSodium()
val p = sodium.bytes(password)
val key = sodium.sodiumHex2Bin(encryptedJson)
val keySalt = key.sliceArray(0 until PwHash.SALTBYTES)
val keyPayload = key.sliceArray(PwHash.SALTBYTES until key.size)
val decryptionKey = ByteArray(Box.SEEDBYTES)
if (!sodium.cryptoPwHash(
decryptionKey,
decryptionKey.size,
p,
p.size,
keySalt,
PwHash.OPSLIMIT_INTERACTIVE,
PwHash.MEMLIMIT_INTERACTIVE,
PwHash.Alg.PWHASH_ALG_ARGON2ID13
)
) throw SodiumDecryptionException("Could not create decryption key")
val nonce = keyPayload.sliceArray(0 until Box.NONCEBYTES)
val cipher = keyPayload.sliceArray(Box.NONCEBYTES until keyPayload.size)
val message = ByteArray(cipher.size - SecretBox.MACBYTES)
if (!sodium.cryptoSecretBoxOpenEasy(
message,
cipher,
cipher.size.toLong(),
nonce,
decryptionKey
)
) throw SodiumDecryptionException("Could not open box")
return message.commonToUtf8String()
}
/**
* Creates a [CSEv1Keychain] from a JSON object.
*
* @param data The keychain as a JSON object.
* @return The keychain created from the JSON.
*/
fun fromJson(data: String): CSEv1Keychain {
val obj = JSONObject(data)
val keyObject = try {
obj.getJSONObject("keys")
} catch (e: JSONException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
JSONObject()
}
val keys = HashMap<String, String>()
val jsonKeys = keyObject.keys()
while (jsonKeys.hasNext()) {
val uuid = jsonKeys.next()
val value = keyObject.getString(uuid)
keys[uuid] = value
}
val current = try {
obj.getString("current")
} catch (e: JSONException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
""
}
return CSEv1Keychain(keys, current)
}
}
}

View file

@ -0,0 +1,123 @@
package com.hegocre.nextcloudpasswords.api.encryption
import com.goterl.lazysodium.interfaces.Box
import com.goterl.lazysodium.interfaces.GenericHash
import com.goterl.lazysodium.interfaces.PwHash
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyNeededException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengePasswordException
import com.hegocre.nextcloudpasswords.api.exceptions.SodiumDecryptionException
import com.hegocre.nextcloudpasswords.utils.Error
import com.hegocre.nextcloudpasswords.utils.LazySodiumUtils
import com.hegocre.nextcloudpasswords.utils.Result
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
/**
* A PWDv1Challenge object. See the
* [API reference](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Encryption/PWDv1Challenge).
*
* @property salts An array with the salts to compute the secret.
* @property secret An encoded string with the secret, only present when creating a challenge.
*/
data class PWDv1Challenge(
val salts: Array<String>,
val secret: String? = null
) {
/**
* Solve the PWDv1 challenge according to the API reference.
*
* @param password The password used to solve the challenge.
* @return A result with the solved challenge if success, and an error code otherwise.
*/
fun solve(password: String?): Result<String> {
// Challenge is empty
if (salts.size != 3) return Result.Error(Error.API_NO_CSE)
// Master key needed but not provided
if (password == null) throw PWDv1ChallengeMasterKeyNeededException()
// TODO: Warn the user
if (password.length < 12) throw PWDv1ChallengePasswordException("Password should have no less than 12 characters")
if (password.length > 128) throw PWDv1ChallengePasswordException("Password should have no more than 128 characters")
val sodium = LazySodiumUtils.getSodium()
val passwordSalt = sodium.sodiumHex2Bin(salts[0])
val genericHashKey = sodium.sodiumHex2Bin(salts[1])
val passwordHashSalt = sodium.sodiumHex2Bin(salts[2])
val input = sodium.bytes(password) + passwordSalt
val genericHash = ByteArray(GenericHash.BYTES_MAX)
if (!sodium.cryptoGenericHash(
genericHash,
genericHash.size,
input,
input.size.toLong(),
genericHashKey,
genericHashKey.size
)
) throw SodiumDecryptionException("Could not create generic hash")
val passwordHash = ByteArray(Box.SEEDBYTES)
if (!sodium.cryptoPwHash(
passwordHash,
passwordHash.size,
genericHash,
genericHash.size,
passwordHashSalt,
PwHash.OPSLIMIT_INTERACTIVE,
PwHash.MEMLIMIT_INTERACTIVE,
PwHash.Alg.PWHASH_ALG_ARGON2ID13
)
) throw SodiumDecryptionException("Could not create password hash")
return Result.Success(sodium.sodiumBin2Hex(passwordHash).lowercase())
}
/* Generated by Android Studio */
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PWDv1Challenge
return salts.contentEquals(other.salts)
}
/* Generated by Android Studio */
override fun hashCode(): Int {
return salts.contentHashCode()
}
companion object {
/**
* Creates a [PWDv1Challenge] from a JSON object.
*
* @param data The data as a JSON object.
* @return The challenge created from the JSON.
*/
fun fromJson(data: String): PWDv1Challenge {
val obj = JSONObject(data)
val saltsArray = try {
val challengeObj = obj.getJSONObject("challenge")
challengeObj.getJSONArray("salts")
} catch (e: JSONException) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
JSONArray()
}
val salts = Array(saltsArray.length()) { "" }
for (i in 0 until saltsArray.length()) {
salts[i] = saltsArray.getString(i)
}
return PWDv1Challenge(salts)
}
}
}

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.api.exceptions
class ClientDeauthorizedException : Exception()

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.api.exceptions
class PWDv1ChallengeMasterKeyInvalidException : Exception()

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.api.exceptions
class PWDv1ChallengeMasterKeyNeededException : Exception()

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.api.exceptions
class PWDv1ChallengePasswordException(message: String) : Exception(message)

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.api.exceptions
class SodiumDecryptionException(message: String) : Exception(message)

View file

@ -0,0 +1,15 @@
package com.hegocre.nextcloudpasswords.data.folder
import kotlinx.serialization.Serializable
/**
* Data class representing a Deleted Folder and containing all its required information.
*
* @property id The UUID of the folder.
* @property revision UUID of the current revision.
*/
@Serializable
data class DeletedFolder(
val id: String,
val revision: String
)

View file

@ -0,0 +1,73 @@
package com.hegocre.nextcloudpasswords.data.folder
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.utils.decryptValue
import kotlinx.serialization.Serializable
/**
* Data class representing a
* [Folder Object](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Folder-Api#the-folder-object)
* and containing all its information.
*
* @property id The UUID of the folder.
* @property label User defined label of the folder.
* @property parent UUID of the parent folder.
* @property revision UUID of the current revision.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property sseType Type of the used server side encryption.
* @property client Name of the client which created this revision.
* @property hidden Hides the folder in list / find actions.
* @property trashed True if the folder is in the trash.
* @property favorite True if the user has marked the folder as favorite.
* @property created Unix timestamp when the folder was created.
* @property updated Unix timestamp when the folder was updated.
* @property edited Unix timestamp when the user last changed the folder name.
*/
@Serializable
@Entity(tableName = "folders", indices = [Index(value = ["id"], unique = true)])
data class Folder(
@PrimaryKey
val id: String,
val label: String,
val parent: String = FoldersApi.DEFAULT_FOLDER_UUID,
val revision: String,
val cseType: String,
val cseKey: String,
val sseType: String,
val client: String,
val hidden: Boolean,
val trashed: Boolean,
val favorite: Boolean,
val created: Int,
val updated: Int,
val edited: Int
) {
/**
* Returns a copy of this object with the encrypted fields decrypted using the keychain.
*
* @param csEv1Keychain The keychain used to decrypt the values.
* @return The object with the decrypted values.
*/
fun decrypt(csEv1Keychain: CSEv1Keychain? = null): Folder? {
//Not encrypted
if (cseType == "none") return this
//Encrypted but no keychain provided
if (csEv1Keychain == null) return null
//We don't have they key to decrypt
if (!csEv1Keychain.keys.containsKey(cseKey)) return null
//We can decrypt
val label = label.decryptValue(cseKey, csEv1Keychain)
return copy(
label = label
)
}
}

View file

@ -0,0 +1,69 @@
package com.hegocre.nextcloudpasswords.data.folder
import android.content.Context
import androidx.lifecycle.LiveData
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.databases.AppDatabase
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Class used to manage the folders cache and make requests to the [ApiController] folder methods.
* This is a Singleton class and will have only one instance.
*
* @param context Context of the application
*/
class FolderController private constructor(context: Context) {
private val folderDatabase = AppDatabase.getInstance(context)
private val apiController = ApiController.getInstance(context)
/**
* Sync the folders obtained from the [ApiController] with the cached ones.
*
*/
suspend fun syncFolders() {
withContext(Dispatchers.IO) {
val result = apiController.listFolders()
if (result is Result.Success) {
val savedFoldersSet = folderDatabase.folderDao.fetchAllFoldersId().toHashSet()
for (folder in result.data) {
val oldRevision = folderDatabase.folderDao.getFolderRevision(folder.id)
if (oldRevision == null || oldRevision != folder.revision) {
folderDatabase.folderDao.insertFolder(folder)
}
savedFoldersSet.remove(folder.id)
}
for (id in savedFoldersSet) {
folderDatabase.folderDao.deleteFolder(id)
}
}
}
}
fun getFolders(): LiveData<List<Folder>> =
folderDatabase.folderDao.fetchAllFolders()
companion object {
private var instance: FolderController? = null
/**
* Get the instance of the [FolderController], and create it if null.
*
* @param context Context of the application.
* @return The instance of the controller.
*/
fun getInstance(context: Context): FolderController {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = FolderController(context)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,25 @@
package com.hegocre.nextcloudpasswords.data.folder
import kotlinx.serialization.Serializable
/**
* Data class representing a New Folder and containing all its required information.
*
* @property label User defined label of the folder.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property parent UUID of the current parent of the folder.
* @property edited Unix timestamp when the user last changed the folder.
* @property hidden Hides the folder in list / find actions.
* @property favorite True if the user has marked the folder as favorite.
*/
@Serializable
data class NewFolder(
val label: String,
val parent: String,
val cseType: String,
val cseKey: String,
val edited: Int,
val hidden: Boolean,
val favorite: Boolean,
)

View file

@ -0,0 +1,29 @@
package com.hegocre.nextcloudpasswords.data.folder
import kotlinx.serialization.Serializable
/**
* Data class representing an Updated Folder and containing all its required information.
*
* @property id The UUID of the folder.
* @property revision UUID of the current revision.
* @property label User defined label of the folder.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property parent UUID of the current parent of the folder.
* @property edited Unix timestamp when the user last changed the folder.
* @property hidden Hides the folder in list / find actions.
* @property favorite True if the user has marked the folder as favorite.
*/
@Serializable
data class UpdatedFolder(
val id: String,
val revision: String,
val label: String,
val cseType: String,
val cseKey: String,
val parent: String,
val edited: Int,
val hidden: Boolean,
val favorite: Boolean,
)

View file

@ -0,0 +1,26 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
/**
* Data class representing a custom field of a [Password].
*
* @property label The name of the field.
* @property type The [field type](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#field-types).
* @property value The value for the field.
*/
@Serializable
data class CustomField(
val label: String,
val type: String,
val value: String
) {
companion object {
const val TYPE_TEXT = "text"
const val TYPE_SECRET = "secret"
const val TYPE_EMAIL = "email"
const val TYPE_URL = "url"
const val TYPE_FILE = "file"
const val TYPE_DATA = "data"
}
}

View file

@ -0,0 +1,15 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
/**
* Data class representing a Deleted Password and containing all its required information.
*
* @property id The UUID of the password.
* @property revision UUID of the current revision.
*/
@Serializable
data class DeletedPassword(
val id: String,
val revision: String
)

View file

@ -0,0 +1,22 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
/**
* Data class representing a random generated password by the
* [Service API](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Service-Api#the-password-endpoint).
*
* @property password The generated password.
* @property words The words used in the password.
* @property strength The strength setting used.
* @property numbers Whether or not numbers were used in the password.
* @property special Whether or not special characters were used in the password.
*/
@Serializable
data class GeneratedPassword(
val password: String,
val words: List<String>,
val strength: Int,
val numbers: Boolean,
val special: Boolean
)

View file

@ -0,0 +1,38 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
/**
* Data class representing a New Password and containing all its required information.
*
* @property password The actual password.
* @property label User defined label of the password.
* @property username Username associated with the password.
* @property url Url of the website.
* @property notes Notes for the password. Can be formatted with Markdown.
* @property customFields Custom fields created by the user. (See
* [custom fields](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#custom-fields)).
* @property hash SHA1 hash of the password.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property folder UUID of the current folder of the password.
* @property edited Unix timestamp when the user last changed the password.
* @property hidden Hides the password in list / find actions.
* @property favorite True if the user has marked the password as favorite.
*/
@Serializable
data class NewPassword(
val password: String,
val label: String,
val username: String,
val url: String,
val notes: String,
val customFields: String,
val hash: String,
val cseType: String,
val cseKey: String,
val folder: String,
val edited: Int,
val hidden: Boolean,
val favorite: Boolean,
)

View file

@ -0,0 +1,133 @@
package com.hegocre.nextcloudpasswords.data.password
import android.net.Uri
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.utils.decryptValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import okhttp3.internal.publicsuffix.PublicSuffixDatabase
/**
* Data class representing a
* [Password Object](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#the-password-object)
* and containing all its information.
*
* @property id The UUID of the password.
* @property label User defined label of the password.
* @property username Username associated with the password.
* @property password The actual password.
* @property url Url of the website.
* @property notes Notes for the password. Can be formatted with Markdown.
* @property customFields Custom fields created by the user. (See
* [custom fields](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#custom-fields)).
* @property status Security status level of the password. (See
* [Security Status](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#security-status)).
* @property statusCode Specific code for the current security status. (See
* [Security Status](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#security-status)).
* @property hash SHA1 hash of the password.
* @property folder UUID of the current folder of the password.
* @property revision UUID of the current revision.
* @property share UUID of the share if the password was shared by someone else with the user.
* @property shared True if the password is shared with other users.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property sseType Type of the used server side encryption.
* @property client Name of the client which created this revision.
* @property hidden Hides the password in list / find actions.
* @property trashed True if the password is in the trash.
* @property favorite True if the user has marked the password as favorite.
* @property editable Specifies if the encrypted properties can be changed. Might be false for shared passwords.
* @property edited Unix timestamp when the user last changed the password.
* @property created Unix timestamp when the password was created.
* @property updated Unix timestamp when the password was updated.
*/
@Serializable
@Entity(tableName = "passwords", indices = [Index(value = ["id"], unique = true)])
data class Password(
@PrimaryKey
val id: String,
val label: String,
val username: String,
val password: String,
val url: String,
val notes: String,
val customFields: String,
val status: Int,
val statusCode: String,
val hash: String,
val folder: String,
val revision: String,
val share: String?,
val shared: Boolean,
val cseType: String,
val cseKey: String,
val sseType: String,
val client: String,
val hidden: Boolean,
val trashed: Boolean,
val favorite: Boolean,
val editable: Boolean,
val edited: Int,
val created: Int,
val updated: Int
) {
/**
* Returns a copy of this object with the encrypted fields decrypted using the keychain.
*
* @param csEv1Keychain The keychain used to decrypt the values.
* @return The object with the decrypted values.
*/
suspend fun decrypt(csEv1Keychain: CSEv1Keychain? = null): Password? {
//Not encrypted
if (cseType == "none") return this
//Encrypted but no keychain provided
if (csEv1Keychain == null) return null
//We don't have they key to decrypt
if (!csEv1Keychain.keys.containsKey(cseKey)) return null
//We can decrypt
val decryptedPassword = withContext(Dispatchers.IO) {
val url = url.decryptValue(cseKey, csEv1Keychain)
val label = label.decryptValue(cseKey, csEv1Keychain)
val password = password.decryptValue(cseKey, csEv1Keychain)
val username = username.decryptValue(cseKey, csEv1Keychain)
val notes = notes.decryptValue(cseKey, csEv1Keychain)
val customFields = customFields.decryptValue(cseKey, csEv1Keychain)
copy(
label = label,
password = password,
username = username,
url = url,
notes = notes,
customFields = customFields
)
}
return decryptedPassword
}
fun matches(query: String, strictUrlMatching: Boolean = true): Boolean {
if (label.lowercase().contains(query.lowercase())) {
return true
}
try {
val queryDomain = (Uri.parse(query).host ?: Uri.parse("https://$query").host)?.let {
if (strictUrlMatching) it else PublicSuffixDatabase.get().getEffectiveTldPlusOne(it)
} ?: return false
val passwordDomain = (Uri.parse(url).host ?: Uri.parse("https://$url").host)?.let {
if (strictUrlMatching) it else PublicSuffixDatabase.get().getEffectiveTldPlusOne(it)
} ?: return false
return queryDomain == passwordDomain
} catch (e: Exception) {
return false
}
}
}

View file

@ -0,0 +1,70 @@
package com.hegocre.nextcloudpasswords.data.password
import android.content.Context
import androidx.lifecycle.LiveData
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.databases.AppDatabase
import com.hegocre.nextcloudpasswords.utils.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Class used to manage the passwords cache and make requests to the [ApiController] password methods.
* This is a Singleton class and will have only one instance.
*
* @param context Context of the application
*/
class PasswordController private constructor(context: Context) {
private val passwordDatabase = AppDatabase.getInstance(context)
private val apiController = ApiController.getInstance(context)
/**
* Sync the passwords obtained from the [ApiController] with the cached ones.
*
*/
suspend fun syncPasswords() {
withContext(Dispatchers.IO) {
val result = apiController.listPasswords()
if (result is Result.Success) {
val savedPasswordsSet =
passwordDatabase.passwordDao.fetchAllPasswordsId().toHashSet()
for (password in result.data) {
val oldRevision = passwordDatabase.passwordDao.getPasswordRevision(password.id)
if (oldRevision == null || oldRevision != password.revision) {
passwordDatabase.passwordDao.insertPassword(password)
}
savedPasswordsSet.remove(password.id)
}
for (id in savedPasswordsSet) {
passwordDatabase.passwordDao.deletePassword(id)
}
}
}
}
fun getPasswords(): LiveData<List<Password>> =
passwordDatabase.passwordDao.fetchAllPasswords()
companion object {
private var instance: PasswordController? = null
/**
* Get the instance of the [PasswordController], and create it if null.
*
* @param context Context of the application.
* @return The instance of the controller.
*/
fun getInstance(context: Context): PasswordController {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = PasswordController(context)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,18 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
@Serializable
data class RequestedPassword(
val strength: Int,
val numbers: Boolean,
val special: Boolean
) {
companion object {
const val STRENGTH_ULTRA = 4
const val STRENGTH_HIGH = 3
const val STRENGTH_MEDIUM = 2
const val STRENGTH_STANDARD = 1
const val STRENGTH_LOW = 0
}
}

View file

@ -0,0 +1,42 @@
package com.hegocre.nextcloudpasswords.data.password
import kotlinx.serialization.Serializable
/**
* Data class representing an Updated Password and containing all its required information.
*
* @property id The UUID of the password.
* @property revision UUID of the current revision.
* @property password The actual password.
* @property label User defined label of the password.
* @property username Username associated with the password.
* @property url Url of the website.
* @property notes Notes for the password. Can be formatted with Markdown.
* @property customFields Custom fields created by the user. (See
* [custom fields](https://git.mdns.eu/nextcloud/passwords/-/wikis/Developers/Api/Password-Api#custom-fields)).
* @property hash SHA1 hash of the password.
* @property cseType Type of the used server side encryption.
* @property cseKey UUID of the key used for client side encryption.
* @property folder UUID of the current folder of the password.
* @property edited Unix timestamp when the user last changed the password.
* @property hidden Hides the password in list / find actions.
* @property favorite True if the user has marked the password as favorite.
*/
@Serializable
data class UpdatedPassword(
val id: String,
val revision: String,
val password: String,
val label: String,
val username: String,
val url: String,
val notes: String,
val customFields: String,
val hash: String,
val cseType: String,
val cseKey: String,
val folder: String,
val edited: Int,
val hidden: Boolean,
val favorite: Boolean,
)

View file

@ -0,0 +1,29 @@
package com.hegocre.nextcloudpasswords.data.serversettings
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.elementNames
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
@Serializable
data class ServerSettings(
@SerialName(value = "user.password.security.hash")
val passwordSecurityHash: Int = 40,
@SerialName(value = "user.encryption.cse")
val encryptionCse: Int = 0,
@SerialName(value = "user.session.lifetime")
val sessionLifetime: Int = 600,
@SerialName(value = "server.theme.color.primary")
val themeColorPrimary: String = "#745bca"
) {
companion object {
@OptIn(ExperimentalSerializationApi::class)
fun getRequestBody(): String {
val names = serializer<ServerSettings>().descriptor.elementNames.toList()
return Json.encodeToString(names)
}
}
}

View file

@ -0,0 +1,90 @@
package com.hegocre.nextcloudpasswords.data.user
import android.content.Context
import com.hegocre.nextcloudpasswords.api.Server
import com.hegocre.nextcloudpasswords.databases.AppDatabase
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Class used to manage to log in and log out, as well as providing the current server to the API
* Controller. This is a Singleton class and will have only one instance.
*
* @param context Context of the application.
*/
class UserController private constructor(context: Context) {
private val _preferencesManager = PreferencesManager.getInstance(context)
private val passwordDatabase = AppDatabase.getInstance(context)
private val folderDatabase = AppDatabase.getInstance(context)
val isLoggedIn: Boolean
get() = _preferencesManager.getLoggedInServer() != null
/**
* Method to store the server URl and credentials on the storage.
*
* @param server The URL of the server to log in
* @param username The username used to authenticate on the server.
* @param password The password used to authenticate on the server.
*/
fun logIn(server: String, username: String, password: String) {
with(_preferencesManager) {
setLoggedInServer(server)
setLoggedInUser(username)
setLoggedInPassword(password)
}
}
/**
* Method to delete the server credentials from the storage, as well as clearing the saved master
* password and keychain if present.
*
*/
suspend fun logOut() {
withContext(Dispatchers.IO) {
passwordDatabase.passwordDao.deleteDatabase()
folderDatabase.folderDao.deleteDatabase()
}
_preferencesManager.clear()
}
/**
* Returns the current logged in server stored on the device.
*
* @return The [Server] with the current URL and credentials.
* @throws UserException If there are no credentials stored.
*/
@Throws(UserException::class)
fun getServer(): Server {
return with(_preferencesManager) {
val url = getLoggedInServer() ?: throw UserException("Not logged in")
val username = getLoggedInUser() ?: throw UserException("Not logged in")
val password = getLoggedInPassword() ?: throw UserException("Not logged in")
Server(url, username, password)
}
}
companion object {
private var instance: UserController? = null
/**
* Get the instance of the [UserController], and create it if null.
*
* @param context Context of the application.
* @return The instance of the controller.
*/
fun getInstance(context: Context): UserController {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = UserController(context)
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,3 @@
package com.hegocre.nextcloudpasswords.data.user
class UserException(message: String) : Exception(message)

View file

@ -0,0 +1,52 @@
package com.hegocre.nextcloudpasswords.databases
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.DeleteTable
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.AutoMigrationSpec
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.databases.folderdatabase.FolderDatabaseDao
import com.hegocre.nextcloudpasswords.databases.passworddatabase.PasswordDatabaseDao
@Database(
entities = [Folder::class, Password::class],
version = 3,
autoMigrations = [
AutoMigration(from = 2, to = 3, spec = AppDatabase.DeleteFaviconsMigration::class)
]
)
abstract class AppDatabase : RoomDatabase() {
abstract val passwordDao: PasswordDatabaseDao
abstract val folderDao: FolderDatabaseDao
@DeleteTable(tableName = "favicons")
class DeleteFaviconsMigration : AutoMigrationSpec
companion object {
@Volatile
private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"password.db"
)
.fallbackToDestructiveMigration()
.build()
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,32 @@
package com.hegocre.nextcloudpasswords.databases.folderdatabase
import androidx.lifecycle.LiveData
import androidx.room.*
import com.hegocre.nextcloudpasswords.data.folder.Folder
@Dao
interface FolderDatabaseDao {
@Query("SELECT * FROM folders")
fun fetchAllFolders(): LiveData<List<Folder>>
@Query("SELECT id FROM folders")
suspend fun fetchAllFoldersId(): List<String>
@Query("SELECT revision FROM folders WHERE id = :id")
suspend fun getFolderRevision(id: String): String?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFolder(folder: Folder)
@Update
suspend fun updateFolder(folder: Folder)
@Delete
suspend fun deleteFolder(folder: Folder)
@Query("DELETE FROM folders WHERE id = :id")
suspend fun deleteFolder(id: String)
@Query("DELETE FROM folders")
suspend fun deleteDatabase()
}

View file

@ -0,0 +1,32 @@
package com.hegocre.nextcloudpasswords.databases.passworddatabase
import androidx.lifecycle.LiveData
import androidx.room.*
import com.hegocre.nextcloudpasswords.data.password.Password
@Dao
interface PasswordDatabaseDao {
@Query("SELECT * FROM passwords")
fun fetchAllPasswords(): LiveData<List<Password>>
@Query("SELECT id FROM passwords")
suspend fun fetchAllPasswordsId(): List<String>
@Query("SELECT revision FROM passwords WHERE id = :id")
suspend fun getPasswordRevision(id: String): String?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPassword(password: Password)
@Update
suspend fun updatePassword(password: Password)
@Delete
suspend fun deletePassword(password: Password)
@Query("DELETE FROM passwords WHERE id = :id")
suspend fun deletePassword(id: String)
@Query("DELETE FROM passwords")
suspend fun deleteDatabase()
}

View file

@ -0,0 +1,197 @@
package com.hegocre.nextcloudpasswords.services.autofill
import android.app.assist.AssistStructure
import android.os.Build
import android.text.InputType
import android.util.Log
import android.view.View
import android.view.autofill.AutofillId
import android.view.inputmethod.EditorInfo
import androidx.annotation.RequiresApi
import com.hegocre.nextcloudpasswords.BuildConfig
/**
* Parser used to get the needed information from an assist structure to reply to an Autofill request.
*
* @param assistStructure The assist structure provided by the Autofill Request, containing all autofill
* fields information
*/
@RequiresApi(Build.VERSION_CODES.O)
class AssistStructureParser(assistStructure: AssistStructure) {
val usernameAutofillIds = mutableListOf<AutofillId>()
val passwordAutofillIds = mutableListOf<AutofillId>()
private var lastTextAutofillId: AutofillId? = null
private var candidateTextAutofillId: AutofillId? = null
private val webDomains = HashMap<String, Int>()
val packageName = assistStructure.activityComponent.flattenToShortString().substringBefore("/")
// Get the most repeated domain on the fields (there may be more than one)
val webDomain: String?
get() = webDomains.toList().filter { it.first != "localhost" }
.maxByOrNull { (_, value) -> value }?.first
init {
for (i in 0 until assistStructure.windowNodeCount) {
val windowNode = assistStructure.getWindowNodeAt(i)
windowNode.rootViewNode?.let { parseNode(it) }
}
if (usernameAutofillIds.isEmpty())
candidateTextAutofillId?.let {
usernameAutofillIds.add(it)
}
}
/**
* Parse the provided node and its child and classify them by type (username or password).
*
* @param node The node to parse.
*/
private fun parseNode(node: AssistStructure.ViewNode) {
node.autofillId?.let { autofillId ->
val fieldType = getFieldType(node)
if (fieldType != null) {
when (fieldType) {
FIELD_TYPE_USERNAME -> {
usernameAutofillIds.add(autofillId)
}
FIELD_TYPE_PASSWORD -> {
passwordAutofillIds.add(autofillId)
// We save the autofillId of the field above the password field,
// in case we don't find any explicit username field
candidateTextAutofillId = lastTextAutofillId
}
FIELD_TYPE_TEXT -> {
lastTextAutofillId = autofillId
}
}
}
}
node.webDomain?.let { webDomain ->
webDomains[webDomain] = webDomains.getOrDefault(webDomain, 0) + 1
}
// Parse child
for (i in 0 until node.childCount) {
val windowNode = node.getChildAt(i)
parseNode(windowNode)
}
}
/**
* Try to determine the type of the node. First, getting a provided autofill hint is tried. If not present,
* html attributes are checked. If also not provided, the text type flag is checked.
*
* @param node The node that has to be classified.
* @return The determined field type.
*/
private fun getFieldType(node: AssistStructure.ViewNode): Int? {
if (node.autofillType == View.AUTOFILL_TYPE_TEXT) {
if (BuildConfig.DEBUG) {
Log.d(packageName, "Autofill node -> ${node.hint}")
Log.d(
packageName,
"-- Hints: ${node.autofillHints?.joinToString(", ")}"
)
Log.d(
packageName,
"-- HTML Attributes: ${node.htmlInfo?.attributes?.joinToString(", ")}"
)
Log.d(packageName, "-- Field type: ${node.inputType}")
}
// Get by autofill hint
node.autofillHints?.forEach { hint ->
if (hint == View.AUTOFILL_HINT_USERNAME || hint == View.AUTOFILL_HINT_EMAIL_ADDRESS) {
return FIELD_TYPE_USERNAME
} else if (hint == View.AUTOFILL_HINT_PASSWORD) {
return FIELD_TYPE_PASSWORD
}
}
// Get by HTML attributes
if (node.hasAttribute("type", "email") ||
node.hasAttribute("type", "tel") ||
node.hasAttribute("type", "text") ||
node.hasAttribute("name", "email") ||
node.hasAttribute("name", "mail") ||
node.hasAttribute("name", "user") ||
node.hasAttribute("name", "username")
) {
return FIELD_TYPE_USERNAME
}
if (node.hasAttribute("type", "password")) {
return FIELD_TYPE_PASSWORD
}
if (node.hint?.lowercase()?.contains("user") == true ||
node.hint?.lowercase()?.contains("mail") == true
) {
return FIELD_TYPE_USERNAME
}
// Get by field type
if (node.inputType.isPasswordType()) {
return FIELD_TYPE_PASSWORD
}
if (node.inputType.isTextType()) {
return FIELD_TYPE_TEXT
}
}
return null
}
/**
* Check if the view node contains a specific HTML attribute value.
*
* @param attr The attribute to check.
* @param value The value to compare.
* @return Whether the value of the provided attribute matches the provided value.
*/
private fun AssistStructure.ViewNode?.hasAttribute(attr: String, value: String): Boolean =
this?.htmlInfo?.attributes?.firstOrNull { it.first == attr && it.second == value } != null
/**
* Check if a text field matches the [InputType.TYPE_CLASS_TEXT] input type.
*
* @return Whether the field matches the input type.
*/
private fun Int?.isTextType() = this != null && (this and InputType.TYPE_CLASS_TEXT != 0)
/**
* Check if a text field is any type of password field.
*
* @return Whether the field matches a password type.
*/
private fun Int?.isPasswordType() = this != null &&
(isPasswordInputType(this) || isVisiblePasswordInputType(this))
//Methods extracted from android source, used since API 33 to heuristically provide
// the AUTOFILL_HINT_PASSWORD_AUTO hint
// https://android.googlesource.com/platform/frameworks/base/+/1f5c147eb5959a7e4fd03b751679cb5e00984c9c%5E%21/#F0
private fun isPasswordInputType(inputType: Int): Boolean {
val variation = inputType and (EditorInfo.TYPE_MASK_CLASS or EditorInfo.TYPE_MASK_VARIATION)
return variation == EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
|| variation == EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD
|| variation == EditorInfo.TYPE_CLASS_NUMBER or EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
|| variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD
|| variation == EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD
}
private fun isVisiblePasswordInputType(inputType: Int): Boolean {
val variation = inputType and (EditorInfo.TYPE_MASK_CLASS or EditorInfo.TYPE_MASK_VARIATION)
return variation == EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|| variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
}
companion object {
private const val FIELD_TYPE_USERNAME = 0
private const val FIELD_TYPE_PASSWORD = 1
private const val FIELD_TYPE_TEXT = 2
}
}

View file

@ -0,0 +1,217 @@
package com.hegocre.nextcloudpasswords.services.autofill
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.assist.AssistStructure
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.graphics.BlendMode
import android.graphics.drawable.Icon
import android.os.Build
import android.service.autofill.Dataset
import android.service.autofill.Field
import android.service.autofill.InlinePresentation
import android.service.autofill.Presentations
import android.view.autofill.AutofillId
import android.view.autofill.AutofillValue
import android.widget.RemoteViews
import android.widget.inline.InlinePresentationSpec
import androidx.annotation.RequiresApi
import androidx.autofill.inline.v1.InlineSuggestionUi
import com.hegocre.nextcloudpasswords.R
object AutofillHelper {
@RequiresApi(Build.VERSION_CODES.O)
fun buildDataset(
context: Context,
password: Triple<String, String, String>?,
assistStructure: AssistStructure,
inlinePresentationSpec: InlinePresentationSpec?,
authenticationIntent: IntentSender? = null
): Dataset {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (inlinePresentationSpec != null) {
buildInlineDataset(
context,
password,
assistStructure,
inlinePresentationSpec,
authenticationIntent
)
} else {
buildPresentationDataset(context, password, assistStructure, authenticationIntent)
}
} else {
buildPresentationDataset(context, password, assistStructure, authenticationIntent)
}
}
@RequiresApi(Build.VERSION_CODES.R)
private fun buildInlineDataset(
context: Context,
password: Triple<String, String, String>?,
assistStructure: AssistStructure,
inlinePresentationSpec: InlinePresentationSpec,
authenticationIntent: IntentSender? = null
): Dataset {
val helper = AssistStructureParser(assistStructure)
return Dataset.Builder()
.apply {
helper.usernameAutofillIds.forEach { autofillId ->
addInlineAutofillValue(
context,
autofillId,
password?.first,
password?.second,
inlinePresentationSpec
)
}
helper.passwordAutofillIds.forEach { autofillId ->
addInlineAutofillValue(
context,
autofillId,
password?.first,
password?.third,
inlinePresentationSpec
)
}
if (authenticationIntent != null) {
setAuthentication(authenticationIntent)
}
}.build()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun buildPresentationDataset(
context: Context,
password: Triple<String, String, String>?,
assistStructure: AssistStructure,
authenticationIntent: IntentSender? = null
): Dataset {
val helper = AssistStructureParser(assistStructure)
return Dataset.Builder().apply {
helper.usernameAutofillIds.forEach { autofillId ->
addAutofillValue(context, autofillId, password?.first, password?.second)
}
helper.passwordAutofillIds.forEach { autofillId ->
addAutofillValue(context, autofillId, password?.first, password?.third)
}
if (authenticationIntent != null) {
setAuthentication(authenticationIntent)
}
}.build()
}
@SuppressLint("RestrictedApi")
@RequiresApi(Build.VERSION_CODES.O)
private fun Dataset.Builder.addAutofillValue(
context: Context,
autofillId: AutofillId,
label: String?,
value: String?,
) {
val autofillLabel = label ?: context.getString(R.string.app_name)
val presentation = if (label == null) {
RemoteViews(context.packageName, R.layout.password_list_item).apply {
setTextViewText(R.id.text, autofillLabel)
}
} else {
RemoteViews(context.packageName, android.R.layout.simple_list_item_1).apply {
setTextViewText(android.R.id.text1, autofillLabel)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val fieldBuilder = Field.Builder()
value?.let {
fieldBuilder.setValue(AutofillValue.forText(it))
}
val dialogPresentation = Presentations.Builder().apply {
setMenuPresentation(presentation)
}.build()
fieldBuilder.setPresentations(dialogPresentation)
setField(autofillId, fieldBuilder.build())
} else {
@Suppress("DEPRECATION")
setValue(
autofillId,
value?.let { AutofillValue.forText(it) },
presentation
)
}
}
@SuppressLint("RestrictedApi")
@RequiresApi(Build.VERSION_CODES.R)
private fun Dataset.Builder.addInlineAutofillValue(
context: Context,
autofillId: AutofillId,
label: String?,
value: String?,
inlinePresentationSpec: InlinePresentationSpec,
) {
val autofillLabel = label ?: context.getString(R.string.app_name)
val authIntent = Intent().apply {
setPackage(context.packageName)
identifier = AUTOFILL_INTENT_ID
}
val intentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
val pendingIntent = PendingIntent.getActivity(
context,
1001,
authIntent,
intentFlags
)
val inlinePresentation = InlinePresentation(
InlineSuggestionUi.newContentBuilder(pendingIntent).apply {
setTitle(autofillLabel)
setStartIcon(
Icon.createWithResource(context, R.mipmap.ic_launcher)
.setTintBlendMode(BlendMode.DST)
)
}.build().slice, inlinePresentationSpec, false
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val fieldBuilder = Field.Builder()
value?.let {
fieldBuilder.setValue(AutofillValue.forText(it))
}
val dialogPresentation = Presentations.Builder().apply {
setInlinePresentation(inlinePresentation)
}.build()
fieldBuilder.setPresentations(dialogPresentation)
setField(autofillId, fieldBuilder.build())
} else {
val presentation = if (label == null) {
RemoteViews(context.packageName, R.layout.password_list_item).apply {
setTextViewText(R.id.text, autofillLabel)
}
} else {
RemoteViews(context.packageName, android.R.layout.simple_list_item_1).apply {
setTextViewText(android.R.id.text1, autofillLabel)
}
}
@Suppress("DEPRECATION")
setValue(
autofillId,
value?.let { AutofillValue.forText(it) },
presentation,
inlinePresentation
)
}
}
private const val AUTOFILL_INTENT_ID = "com.hegocre.nextcloudpasswords.intents.autofill"
}

View file

@ -0,0 +1,143 @@
package com.hegocre.nextcloudpasswords.services.autofill
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.CancellationSignal
import android.service.autofill.AutofillService
import android.service.autofill.FillCallback
import android.service.autofill.FillRequest
import android.service.autofill.FillResponse
import android.service.autofill.SaveCallback
import android.service.autofill.SaveRequest
import androidx.annotation.RequiresApi
import com.hegocre.nextcloudpasswords.data.user.UserController
import com.hegocre.nextcloudpasswords.data.user.UserException
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
@RequiresApi(Build.VERSION_CODES.O)
class NCPAutofillService : AutofillService() {
@SuppressLint("RestrictedApi")
override fun onFillRequest(
request: FillRequest,
cancellationSignal: CancellationSignal,
callback: FillCallback
) {
val context = request.fillContexts
val structure = context.last().structure
val helper = AssistStructureParser(structure)
// Do not autofill this application
if (helper.packageName == packageName) {
callback.onSuccess(null)
return
}
try {
UserController.getInstance(applicationContext).getServer()
} catch (e: UserException) {
// User not logged in, cannot fill request
callback.onSuccess(null)
return
}
val useInline = PreferencesManager.getInstance(applicationContext).getUseInlineAutofill()
val inlineSuggestionsRequest =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && useInline) {
request.inlineSuggestionsRequest
} else null
val searchHint: String? = when {
// If the structure contains a domain, use that (probably a web browser)
helper.webDomain != null -> {
helper.webDomain
}
else -> with(packageManager) {
//Get the name of the package (QUERY_ALL_PACKAGES permission needed)
try {
val app = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
getApplicationInfo(
helper.packageName,
PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong())
)
else
getApplicationInfo(
helper.packageName,
PackageManager.GET_META_DATA
)
getApplicationLabel(app).toString()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
null
}
}
}
// Intent to open MainActivity and provide a response to the request
val authIntent = Intent("com.hegocre.nextcloudpasswords.action.main").apply {
setPackage(packageName)
putExtra(AUTOFILL_REQUEST, true)
searchHint?.let {
putExtra(AUTOFILL_SEARCH_HINT, it)
}
}
val intentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
val intentSender = PendingIntent.getActivity(
this,
1001,
authIntent,
intentFlags
).intentSender
if (helper.passwordAutofillIds.isNotEmpty()) {
val fillResponse = FillResponse.Builder().apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
addDataset(
AutofillHelper.buildDataset(
applicationContext,
null,
structure,
inlineSuggestionsRequest?.inlinePresentationSpecs?.first(),
intentSender
)
)
} else {
addDataset(
AutofillHelper.buildDataset(
applicationContext,
null,
structure,
null,
intentSender
)
)
}
}.build()
callback.onSuccess(fillResponse)
} else {
// Do not return a response if there are no autofill fields.
callback.onSuccess(null)
}
}
override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {
callback.onFailure("Not implemented")
}
companion object {
const val AUTOFILL_REQUEST = "autofill_request"
const val AUTOFILL_SEARCH_HINT = "autofill_query"
}
}

View file

@ -0,0 +1,76 @@
package com.hegocre.nextcloudpasswords.services.keepalive
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.WorkerParameters
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.api.SessionApi
import com.hegocre.nextcloudpasswords.data.user.UserController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
class KeepAliveWorker(context: Context, private val params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val apiController = ApiController.getInstance(applicationContext)
if (!apiController.sessionOpen.value) {
return Result.success()
}
val server = UserController.getInstance(applicationContext).getServer()
val sessionApi = SessionApi.getInstance(server)
val sessionCode = params.inputData.getString(SESSION_CODE_KEY) ?: return Result.failure()
val keepAliveDelay = params.inputData.getLong(KEEPALIVE_DELAY_KEY, -1L)
if (keepAliveDelay == -1L) return Result.failure()
val resultSuccess = withContext(Dispatchers.IO) {
sessionApi.keepAlive(sessionCode)
}
if (resultSuccess) {
WorkManager.getInstance(applicationContext)
.enqueue(getRequest(keepAliveDelay, sessionCode))
return Result.success()
} else {
if (params.runAttemptCount > 2) {
ApiController.getInstance(applicationContext).clearSession()
return Result.failure()
} else {
return Result.retry()
}
}
}
companion object {
private const val SESSION_CODE_KEY = "com.hegocre.nextcloudpasswords.sessionCode"
private const val KEEPALIVE_DELAY_KEY = "com.hegocre.nextcloudpasswords.keepAliveDelay"
const val TAG = "com.hegocre.nextcloudpasswords.keepaliveworker"
fun getRequest(delay: Long, sessionCode: String): WorkRequest {
val data = Data.Builder()
.putString(SESSION_CODE_KEY, sessionCode)
.putLong(KEEPALIVE_DELAY_KEY, delay)
.build()
return OneTimeWorkRequestBuilder<KeepAliveWorker>()
.setInitialDelay(delay, TimeUnit.MILLISECONDS)
.setInputData(data)
.setBackoffCriteria(BackoffPolicy.LINEAR, 10L, TimeUnit.SECONDS)
.addTag(TAG)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
}
}
}

View file

@ -0,0 +1,61 @@
package com.hegocre.nextcloudpasswords.ui
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.VpnKey
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.VpnKey
import androidx.compose.ui.graphics.vector.ImageVector
import com.hegocre.nextcloudpasswords.R
enum class NCPScreen(
@StringRes val title: Int,
val selectedIcon: ImageVector,
val unselectedIcon: ImageVector,
val hidden: Boolean = false
) {
Passwords(
title = R.string.passwords,
selectedIcon = Icons.Filled.VpnKey,
unselectedIcon = Icons.Outlined.VpnKey
),
Favorites(
title = R.string.favorites,
selectedIcon = Icons.Filled.Favorite,
unselectedIcon = Icons.Outlined.FavoriteBorder
),
Folders(
title = R.string.folders,
selectedIcon = Icons.Filled.Folder,
unselectedIcon = Icons.Outlined.Folder
),
PasswordEdit(
title = R.string.action_edit_password,
selectedIcon = Icons.Default.Edit,
unselectedIcon = Icons.Default.Edit,
hidden = true
),
FolderEdit(
title = R.string.edit_folder,
selectedIcon = Icons.Default.Edit,
unselectedIcon = Icons.Default.Edit,
hidden = true
);
companion object {
fun fromRoute(route: String?): NCPScreen =
when (route?.substringBefore("/")) {
Passwords.name -> Passwords
Favorites.name -> Favorites
Folders.name -> Folders
PasswordEdit.name -> PasswordEdit
FolderEdit.name -> FolderEdit
null -> Passwords
else -> throw IllegalArgumentException("Route $route is not recognized.")
}
}
}

View file

@ -0,0 +1,33 @@
package com.hegocre.nextcloudpasswords.ui.activities
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.ui.components.NCPAboutScreen
import com.hegocre.nextcloudpasswords.ui.components.NCPAppLockWrapper
import com.hegocre.nextcloudpasswords.utils.LogHelper
import com.hegocre.nextcloudpasswords.utils.copyToClipboard
class AboutActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
NCPAppLockWrapper {
NCPAboutScreen(
onBackPressed = this::finish,
onLogoLongPressed = {
if (BuildConfig.DEBUG) {
copyToClipboard(LogHelper.getInstance().appLog)
Toast.makeText(this, "Log copied!", Toast.LENGTH_LONG).show()
}
}
)
}
}
}
}

View file

@ -0,0 +1,39 @@
package com.hegocre.nextcloudpasswords.ui.activities
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.components.NCPLoginScreen
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
class LoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
val loginIntent = Intent(this, WebLoginActivity::class.java)
setContent {
NCPLoginScreen(
loginIntent = loginIntent,
onLoginSuccess = {
val intent = Intent("com.hegocre.nextcloudpasswords.action.main")
.setPackage(packageName)
startActivity(intent)
finish()
},
onLoginFailed = {
PreferencesManager.getInstance(this).setSkipCertificateValidation(false)
Toast.makeText(this, getString(R.string.error_logging_in), Toast.LENGTH_LONG)
.show()
}
)
}
}
}

View file

@ -0,0 +1,156 @@
package com.hegocre.nextcloudpasswords.ui.activities
import android.app.Activity
import android.app.assist.AssistStructure
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.autofill.AutofillManager
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.view.WindowCompat
import androidx.fragment.app.FragmentActivity
import coil.Coil
import coil.ImageLoader
import coil.disk.DiskCache
import com.hegocre.nextcloudpasswords.BuildConfig
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.data.user.UserController
import com.hegocre.nextcloudpasswords.services.autofill.AutofillHelper
import com.hegocre.nextcloudpasswords.services.autofill.NCPAutofillService
import com.hegocre.nextcloudpasswords.ui.components.NCPAppLockWrapper
import com.hegocre.nextcloudpasswords.ui.components.NextcloudPasswordsApp
import com.hegocre.nextcloudpasswords.ui.viewmodels.PasswordsViewModel
import com.hegocre.nextcloudpasswords.utils.LogHelper
import com.hegocre.nextcloudpasswords.utils.OkHttpRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
if (BuildConfig.DEBUG) LogHelper.getInstance()
super.onCreate(savedInstanceState)
if (!UserController.getInstance(this).isLoggedIn) {
login()
return
}
val passwordsViewModel by viewModels<PasswordsViewModel>()
val autofillRequested = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.getBooleanExtra(NCPAutofillService.AUTOFILL_REQUEST, false)
} else {
false
}
val autofillSearchQuery =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && autofillRequested) {
intent.getStringExtra(NCPAutofillService.AUTOFILL_SEARCH_HINT) ?: ""
} else {
""
}
val replyAutofill: ((String, String, String) -> Unit)? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& autofillRequested
) {
{ label, username, password ->
val structure = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
intent.getParcelableExtra(
AutofillManager.EXTRA_ASSIST_STRUCTURE,
AssistStructure::class.java
)
else
@Suppress("DEPRECATION") intent.getParcelableExtra(AutofillManager.EXTRA_ASSIST_STRUCTURE)
if (structure == null) {
setResult(Activity.RESULT_CANCELED)
finish()
} else {
autofillReply(Triple(label, username, password), structure)
}
}
} else null
passwordsViewModel.clientDeauthorized.observe(this) { deauthorized ->
if (deauthorized) {
Toast.makeText(this, R.string.client_deauthorized_toast, Toast.LENGTH_LONG).show()
logOut()
}
}
Coil.setImageLoader {
ImageLoader.Builder(this)
.okHttpClient { OkHttpRequest.getInstance().client }
.diskCache {
DiskCache.Builder()
.directory(this.cacheDir.resolve("image_cache"))
.build()
}.build()
}
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
NCPAppLockWrapper {
NextcloudPasswordsApp(
passwordsViewModel = passwordsViewModel,
onLogOut = { logOut() },
replyAutofill = replyAutofill,
isAutofillRequest = autofillRequested,
defaultSearchQuery = autofillSearchQuery
)
}
}
}
private fun logOut() {
val logOutJob = SupervisorJob()
val logOutScope = CoroutineScope(Dispatchers.IO + logOutJob)
logOutScope.launch {
ApiController.getInstance(this@MainActivity).closeSession()
UserController.getInstance(this@MainActivity).logOut()
triggerRebirth()
}
}
private fun triggerRebirth() {
val intent = packageManager.getLaunchIntentForPackage(packageName)
val componentName = intent?.component
val mainIntent = Intent.makeRestartActivityTask(componentName)
startActivity(mainIntent)
Runtime.getRuntime().exit(0)
}
private fun login() {
val intent = Intent("com.hegocre.nextcloudpasswords.action.login")
.setPackage(packageName)
startActivity(intent)
finish()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun autofillReply(
password: Triple<String, String, String>,
structure: AssistStructure
) {
val dataset = AutofillHelper.buildDataset(this, password, structure, null)
val replyIntent = Intent().apply {
putExtra(AutofillManager.EXTRA_AUTHENTICATION_RESULT, dataset)
}
setResult(Activity.RESULT_OK, replyIntent)
finish()
}
}

View file

@ -0,0 +1,25 @@
package com.hegocre.nextcloudpasswords.ui.activities
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import androidx.fragment.app.FragmentActivity
import com.hegocre.nextcloudpasswords.ui.components.NCPAppLockWrapper
import com.hegocre.nextcloudpasswords.ui.components.NCPSettingsScreen
class SettingsActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
NCPAppLockWrapper {
NCPSettingsScreen(
onNavigationUp = { finish() }
)
}
}
}
}

View file

@ -0,0 +1,84 @@
package com.hegocre.nextcloudpasswords.ui.activities
import android.content.Intent
import android.os.Bundle
import android.webkit.CookieManager
import android.webkit.WebStorage
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import com.hegocre.nextcloudpasswords.data.user.UserController
import com.hegocre.nextcloudpasswords.ui.components.NCPWebLoginScreen
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
class WebLoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
val loginUrl = intent.getStringExtra("login_url")?.let {
var url = it
if (it.last() != '/') url += '/'
"${url}index.php/login/flow"
} ?: ""
setContent {
NCPWebLoginScreen(
onLoginUrl = { url -> processCredentials(url) },
url = loginUrl
)
}
}
private fun processCredentials(url: String) {
val uri = URLDecoder.decode(url, StandardCharsets.UTF_8.toString())
val match = CRED_REGEX_1.matchEntire(uri)?.groups
val (user, password, server) = if (match != null) {
listOf(match[2]?.value, match[3]?.value, match[1]?.value)
} else {
val match2 = CRED_REGEX_2.matchEntire(uri)?.groups
listOf(match2?.get(1)?.value, match2?.get(2)?.value, match2?.get(3)?.value)
}
val intent = Intent()
if (user != null && password != null && server != null) {
UserController.getInstance(this).logIn(
server,
user,
password
)
intent.putExtra("loggedIn", true)
setResult(RESULT_OK, intent)
} else {
intent.putExtra("loggedIn", false)
setResult(RESULT_CANCELED, intent)
}
finish()
}
override fun onDestroy() {
WebStorage.getInstance().deleteAllData()
// Clear all the cookies
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
val webView = WebView(this)
webView.clearCache(true)
webView.clearFormData()
webView.clearHistory()
webView.clearSslPreferences()
super.onDestroy()
}
companion object {
private val CRED_REGEX_1 = "nc:.*server:(.*)&user:(.*)&password:(.*)".toRegex()
private val CRED_REGEX_2 = "nc:.*user:(.*)&password:(.*)&server:(.*)".toRegex()
}
}

View file

@ -0,0 +1,137 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.InterceptPlatformTextInput
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import kotlinx.coroutines.awaitCancellation
@Composable
fun OutlinedTextFieldWithCaption(
text: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
label: String = "",
captionText: String = "",
errorText: String = "",
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardType: KeyboardType = KeyboardType.Text,
trailingIcon: @Composable (() -> Unit)? = null,
onDone: () -> Unit = {}
) {
val isError by remember { derivedStateOf { errorText.isNotBlank() } }
val keyboardController = LocalSoftwareKeyboardController.current
Column(modifier = modifier) {
OutlinedTextField(
modifier = Modifier.align(Alignment.CenterHorizontally),
value = text,
maxLines = 1,
singleLine = true,
onValueChange = onValueChange,
label = { Text(text = label) },
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done,
keyboardType = keyboardType
),
keyboardActions = KeyboardActions(onDone = {
onDone()
keyboardController?.hide()
}),
isError = isError,
visualTransformation = visualTransformation,
trailingIcon = trailingIcon
)
if (captionText.isNotBlank() || isError) {
Text(
text = if (!isError)
captionText
else
errorText,
style = if (!isError)
MaterialTheme.typography.labelSmall
else
MaterialTheme.typography.labelSmall.copy(
color = MaterialTheme.colorScheme.error
),
modifier = Modifier.padding(start = 4.dp, top = 4.dp)
)
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun OutlinedClickableTextField(
value: String,
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val interactionSource = remember { MutableInteractionSource() }
Box {
InterceptPlatformTextInput(interceptor = { _, _ ->
awaitCancellation()
}) {
OutlinedTextField(
value = value,
onValueChange = { },
label = { Text(text = label) },
singleLine = true,
maxLines = 1,
modifier = modifier,
readOnly = true,
colors = OutlinedTextFieldDefaults.colors(cursorColor = Color.Transparent)
)
}
Box(
modifier = Modifier
.matchParentSize()
.clickable(
onClick = onClick,
interactionSource = interactionSource,
indication = null
),
)
}
}
@Preview
@Composable
fun OutlinedTextFieldPreview() {
NextcloudPasswordsTheme {
OutlinedTextFieldWithCaption(
text = "Hello World",
onValueChange = {},
captionText = "Caption here"
)
}
}

View file

@ -0,0 +1,890 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.AutofillType
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.password.CustomField
import com.hegocre.nextcloudpasswords.data.password.RequestedPassword
import com.hegocre.nextcloudpasswords.ui.theme.ContentAlpha
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.hegocre.nextcloudpasswords.utils.autofill
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MasterPasswordDialog(
masterPassword: String,
setMasterPassword: (String) -> Unit,
savePassword: Boolean,
setSavePassword: (Boolean) -> Unit,
onOkClick: () -> Unit,
errorText: String = "",
onDismissRequest: (() -> Unit)? = null
) {
val requester = remember { FocusRequester() }
var showPassword by rememberSaveable { mutableStateOf(false) }
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp
) {
Column(modifier = Modifier.padding(24.dp)) {
LaunchedEffect(key1 = Unit) {
coroutineContext.job.invokeOnCompletion {
if (it?.cause == null) {
requester.requestFocus()
}
}
}
OutlinedTextFieldWithCaption(
text = masterPassword,
onValueChange = setMasterPassword,
visualTransformation = if (showPassword)
VisualTransformation.None else PasswordVisualTransformation(),
keyboardType = KeyboardType.Password,
label = stringResource(R.string.dialog_master_password_title),
trailingIcon = {
IconButton(onClick = { showPassword = !showPassword }) {
Icon(
imageVector = if (showPassword)
Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = stringResource(R.string.text_input_show_password_toggle)
)
}
},
errorText = errorText,
modifier = Modifier
.focusRequester(requester)
.autofill(
autofillTypes = listOf(AutofillType.Password),
onFill = setMasterPassword
)
)
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = ContentAlpha.medium)
) {
Row {
Checkbox(
checked = savePassword,
onCheckedChange = setSavePassword,
modifier = Modifier.align(Alignment.CenterVertically)
)
Text(
text = "Save password",
modifier = Modifier
.align(Alignment.CenterVertically)
.pointerInput(Unit) {
detectTapGestures {
setSavePassword(!savePassword)
}
},
style = MaterialTheme.typography.bodySmall
)
}
}
TextButton(
onClick = onOkClick,
modifier = Modifier.align(Alignment.End)
) {
Text(text = stringResource(android.R.string.ok))
}
}
}
}
}
@Composable
fun LogOutDialog(
onDismissRequest: (() -> Unit)? = null,
onConfirmButton: () -> Unit
) {
AlertDialog(
onDismissRequest = { onDismissRequest?.invoke() },
title = { Text(text = stringResource(R.string.action_log_out)) },
text = { Text(text = stringResource(R.string.dialog_log_out_text)) },
confirmButton = {
TextButton(
onClick = {
onConfirmButton()
onDismissRequest?.invoke()
}
) {
Text(text = stringResource(R.string.action_log_out))
}
},
dismissButton = {
TextButton(onClick = { onDismissRequest?.invoke() }) {
Text(text = stringResource(id = android.R.string.cancel))
}
}
)
}
@Composable
fun DeleteElementDialog(
onDismissRequest: (() -> Unit)? = null,
onConfirmButton: () -> Unit
) {
AlertDialog(
onDismissRequest = { onDismissRequest?.invoke() },
title = { Text(text = stringResource(R.string.action_delete)) },
text = { Text(text = stringResource(R.string.dialog_delete_element_text)) },
confirmButton = {
TextButton(
onClick = {
onConfirmButton()
onDismissRequest?.invoke()
}
) {
Text(text = stringResource(R.string.action_delete))
}
},
dismissButton = {
TextButton(onClick = { onDismissRequest?.invoke() }) {
Text(text = stringResource(id = android.R.string.cancel))
}
}
)
}
@Composable
fun DiscardChangesDialog(
onDismissRequest: (() -> Unit)? = null,
onConfirmButton: () -> Unit
) {
AlertDialog(
onDismissRequest = { onDismissRequest?.invoke() },
title = { Text(text = stringResource(R.string.action_discard)) },
text = { Text(text = stringResource(R.string.dialog_discard_changes_text)) },
confirmButton = {
TextButton(
onClick = {
onConfirmButton()
onDismissRequest?.invoke()
}
) {
Text(text = stringResource(R.string.action_discard))
}
},
dismissButton = {
TextButton(onClick = { onDismissRequest?.invoke() }) {
Text(text = stringResource(id = android.R.string.cancel))
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddCustomFieldDialog(
onAddClick: (String, String) -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
val types = mapOf(
CustomField.TYPE_TEXT to stringResource(id = R.string.custom_field_type_text),
CustomField.TYPE_EMAIL to stringResource(id = R.string.custom_field_type_email),
CustomField.TYPE_URL to stringResource(id = R.string.custom_field_type_url),
CustomField.TYPE_SECRET to stringResource(id = R.string.custom_field_type_secret)
)
val (type, setType) = remember { mutableStateOf(CustomField.TYPE_TEXT) }
val (label, setLabel) = remember { mutableStateOf("") }
var typeMenuExpanded by remember { mutableStateOf(false) }
var showEmptyError by rememberSaveable {
mutableStateOf(false)
}
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(all = 24.dp)) {
Text(
text = stringResource(id = R.string.action_add_custom_field),
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier.padding(bottom = 16.dp)
)
Column(
modifier = Modifier
.weight(1f, fill = false)
.verticalScroll(
rememberScrollState()
)
) {
ExposedDropdownMenuBox(
expanded = typeMenuExpanded,
onExpandedChange = { typeMenuExpanded = !typeMenuExpanded }
) {
OutlinedTextField(
modifier = Modifier.menuAnchor(MenuAnchorType.PrimaryNotEditable),
value = types[type] ?: "",
onValueChange = {},
readOnly = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = typeMenuExpanded) },
label = { Text(text = stringResource(id = R.string.custom_field_type)) },
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors()
)
ExposedDropdownMenu(
expanded = typeMenuExpanded,
onDismissRequest = { typeMenuExpanded = false }
) {
types.forEach { type ->
DropdownMenuItem(
text = { Text(text = type.value) },
onClick = {
setType(type.key)
typeMenuExpanded = false
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding
)
}
}
}
OutlinedTextField(
modifier = Modifier.padding(bottom = 16.dp, top = 8.dp),
value = label,
onValueChange = setLabel,
singleLine = true,
maxLines = 1,
label = { Text(text = stringResource(id = R.string.custom_field_label)) },
isError = showEmptyError && label.isBlank(),
supportingText = if (showEmptyError && label.isBlank()) {
{
Text(text = stringResource(id = R.string.error_field_cannot_be_empty))
}
} else null
)
}
TextButton(
onClick = {
if (label.isBlank()) {
showEmptyError = true
} else {
onAddClick(type, label)
}
},
modifier = Modifier
.align(Alignment.End)
.padding(horizontal = 0.dp)
) {
Text(text = stringResource(android.R.string.ok))
}
}
}
}
}
@Composable
fun SelectFolderDialog(
folders: List<Folder>,
currentFolder: String,
onSelectClick: (String) -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
val (selectedFolderId, setSelectedFolderId) = remember { mutableStateOf(currentFolder) }
val filteredFolders = remember(folders, selectedFolderId) {
folders.filter {
it.parent == selectedFolderId
}
}
val selectedFolder = remember(folders, selectedFolderId) {
folders.firstOrNull { it.id == selectedFolderId }
}
val parentFolder = remember(selectedFolder) {
folders.firstOrNull { it.id == selectedFolder?.parent }
}
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(vertical = 24.dp)) {
Text(
text = if (selectedFolderId == FoldersApi.DEFAULT_FOLDER_UUID) {
stringResource(id = R.string.top_level_folder_name)
} else {
selectedFolder?.label ?: stringResource(id = R.string.top_level_folder_name)
},
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 24.dp)
)
Column(
modifier = Modifier
.weight(1f, fill = false)
) {
LazyColumn(
modifier = Modifier.fillMaxWidth(),
) {
if (selectedFolderId != FoldersApi.DEFAULT_FOLDER_UUID) {
item(key = "parent_${parentFolder?.id ?: FoldersApi.DEFAULT_FOLDER_UUID}") {
ListItem(
leadingContent = {
Image(
imageVector = Icons.Filled.Folder,
contentDescription = stringResource(R.string.content_description_folder_icon),
colorFilter = ColorFilter.tint(
MaterialTheme.colorScheme.onSurface.copy(
alpha = ContentAlpha.medium
)
),
modifier = Modifier
.size(45.dp)
.padding(8.dp)
)
},
headlineContent = {
Text(text = "..")
},
modifier = Modifier.clickable {
setSelectedFolderId(
parentFolder?.id ?: FoldersApi.DEFAULT_FOLDER_UUID
)
}
)
}
}
items(items = filteredFolders, key = { folder -> folder.id }) { folder ->
FolderRow(
folder = folder,
onFolderClick = {
setSelectedFolderId(folder.id)
},
modifier = Modifier
)
}
}
}
TextButton(
onClick = {
onSelectClick(selectedFolderId)
},
modifier = Modifier
.align(Alignment.End)
.padding(horizontal = 24.dp)
) {
Text(text = stringResource(R.string.action_select))
}
}
}
}
}
@Composable
fun AddElementDialog(
onPasswordAdd: () -> Unit,
onFolderAdd: () -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(vertical = 24.dp)) {
Text(
text = stringResource(id = R.string.action_create_element),
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 24.dp)
)
ListItem(
headlineContent = {
Text(text = stringResource(id = R.string.password))
},
modifier = Modifier
.clickable(onClick = onPasswordAdd)
.padding(horizontal = 8.dp)
)
ListItem(
headlineContent = {
Text(text = stringResource(id = R.string.folder))
},
modifier = Modifier
.clickable(onClick = onFolderAdd)
.padding(horizontal = 8.dp)
)
}
}
}
}
@Composable
fun InputPasscodeDialog(
title: String,
onInputPasscode: (String) -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
val requester = remember { FocusRequester() }
var showPasscode by rememberSaveable { mutableStateOf(false) }
val (passcode, setPasscode) = remember { mutableStateOf("") }
var showEmptyError by rememberSaveable {
mutableStateOf(false)
}
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(all = 24.dp)) {
Text(
text = title,
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier.padding(bottom = 16.dp)
)
LaunchedEffect(key1 = Unit) {
coroutineContext.job.invokeOnCompletion {
if (it?.cause == null) {
requester.requestFocus()
}
}
}
OutlinedTextField(
modifier = Modifier
.padding(bottom = 16.dp, top = 8.dp)
.focusRequester(requester),
value = passcode,
onValueChange = { newPasscode ->
if (newPasscode.length <= 16 &&
(newPasscode.toIntOrNull() != null || newPasscode.isEmpty())
) {
setPasscode(newPasscode)
}
},
singleLine = true,
maxLines = 1,
label = { Text(text = stringResource(id = R.string.passcode)) },
isError = showEmptyError && passcode.isBlank(),
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
trailingIcon = {
IconButton(onClick = { showPasscode = !showPasscode }) {
Icon(
imageVector = if (showPasscode)
Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = stringResource(R.string.text_input_show_password_toggle)
)
}
},
visualTransformation = if (showPasscode)
VisualTransformation.None else PasswordVisualTransformation(),
)
TextButton(
onClick = {
if (passcode.length < 4 || passcode.toIntOrNull() == null) {
showEmptyError = true
} else {
onInputPasscode(passcode)
}
},
modifier = Modifier
.align(Alignment.End)
.padding(horizontal = 0.dp)
) {
Text(text = stringResource(android.R.string.ok))
}
}
}
}
}
@Composable
fun ListPreferenceDialog(
title: (@Composable () -> Unit),
options: Map<String, String>,
selectedOption: String,
onSelectOption: (String) -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(vertical = 24.dp)) {
Box(
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 24.dp)
) {
CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.headlineSmall
) {
title()
}
}
LazyColumn(
modifier = Modifier
.weight(1f, fill = false)
.fillMaxWidth()
) {
items(items = options.keys.toList(), key = { it }) { option ->
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable {
onSelectOption(option)
}
.padding(vertical = 4.dp, horizontal = 12.dp)
) {
RadioButton(
selected = option == selectedOption,
onClick = { onSelectOption(option) }
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = options.getOrDefault(option, ""))
}
}
}
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PasswordGenerationDialog(
onGenerate: (Int, Boolean, Boolean) -> Unit,
onDismissRequest: (() -> Unit)? = null
) {
val strengthValues = mapOf(
RequestedPassword.STRENGTH_ULTRA to stringResource(id = R.string.password_strength_ultra),
RequestedPassword.STRENGTH_HIGH to stringResource(id = R.string.password_strength_high),
RequestedPassword.STRENGTH_MEDIUM to stringResource(id = R.string.password_strength_medium),
RequestedPassword.STRENGTH_STANDARD to stringResource(id = R.string.password_strength_standard),
RequestedPassword.STRENGTH_LOW to stringResource(id = R.string.password_strength_low)
)
val (strength, setStrength) = remember { mutableIntStateOf(RequestedPassword.STRENGTH_STANDARD) }
val (includeDigits, setIncludeDigits) = remember { mutableStateOf(true) }
val (includeSymbols, setIncludeSymbols) = remember { mutableStateOf(true) }
val context = LocalContext.current
LaunchedEffect(Unit) {
val lastValues = PreferencesManager.getInstance(context)
.getPasswordGenerationOptions()?.split(";") ?: listOf()
setStrength(lastValues.getOrNull(0)?.toIntOrNull() ?: strength)
setIncludeDigits(lastValues.getOrNull(1)?.toBooleanStrictOrNull() ?: includeDigits)
setIncludeSymbols(lastValues.getOrNull(2)?.toBooleanStrictOrNull() ?: includeSymbols)
}
var typeMenuExpanded by remember { mutableStateOf(false) }
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
) {
Column(modifier = Modifier.padding(vertical = 24.dp)) {
Box(
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 24.dp)
) {
Text(
text = stringResource(id = R.string.action_generate_password),
style = MaterialTheme.typography.headlineSmall
)
}
Column(
modifier = Modifier
.weight(1f, fill = false)
.fillMaxWidth()
) {
ExposedDropdownMenuBox(
expanded = typeMenuExpanded,
onExpandedChange = { typeMenuExpanded = !typeMenuExpanded },
modifier = Modifier
.padding(horizontal = 24.dp)
.padding(bottom = 8.dp)
) {
OutlinedTextField(
modifier = Modifier.menuAnchor(MenuAnchorType.PrimaryNotEditable),
value = strengthValues[strength] ?: "",
onValueChange = {},
readOnly = true,
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = typeMenuExpanded) },
label = { Text(text = stringResource(id = R.string.password_generation_strength)) },
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors()
)
ExposedDropdownMenu(
expanded = typeMenuExpanded,
onDismissRequest = { typeMenuExpanded = false }
) {
strengthValues.forEach { strengthValue ->
DropdownMenuItem(
text = { Text(text = strengthValue.value) },
onClick = {
setStrength(strengthValue.key)
typeMenuExpanded = false
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding
)
}
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable {
setIncludeDigits(!includeDigits)
}
.padding(vertical = 4.dp, horizontal = 12.dp)
) {
Checkbox(
checked = includeDigits,
onCheckedChange = setIncludeDigits
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = stringResource(id = R.string.password_generation_include_numbers))
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable {
setIncludeSymbols(!includeSymbols)
}
.padding(vertical = 4.dp, horizontal = 12.dp)
) {
Checkbox(
checked = includeSymbols,
onCheckedChange = setIncludeSymbols
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = stringResource(id = R.string.password_generation_include_special_characters))
}
}
val coroutineScope = rememberCoroutineScope()
TextButton(
onClick = {
onGenerate(strength, includeDigits, includeSymbols)
coroutineScope.launch(Dispatchers.IO) {
PreferencesManager.getInstance(context).setPasswordGenerationOptions(
"$strength;$includeDigits;$includeSymbols"
)
}
},
modifier = Modifier
.align(Alignment.End)
.padding(horizontal = 24.dp)
) {
Text(text = stringResource(android.R.string.ok))
}
}
}
}
}
@Preview
@Composable
fun MasterPasswordDialogPreview() {
NextcloudPasswordsTheme {
MasterPasswordDialog(
masterPassword = "",
setMasterPassword = {},
savePassword = false,
setSavePassword = {},
onOkClick = {}
)
}
}
@Preview
@Composable
fun LogOutDialogPreview() {
NextcloudPasswordsTheme {
LogOutDialog {
}
}
}
@Preview
@Composable
fun DeleteDialogPreview() {
NextcloudPasswordsTheme {
DeleteElementDialog {
}
}
}
@Preview
@Composable
fun AddFieldDialogPreview() {
NextcloudPasswordsTheme {
AddCustomFieldDialog(onAddClick = { _, _ -> })
}
}
@Preview
@Composable
fun AddElementDialogPreview() {
NextcloudPasswordsTheme {
AddElementDialog({}, {})
}
}
@Preview
@Composable
fun InputPasscodePreview() {
NextcloudPasswordsTheme {
InputPasscodeDialog(title = "Input passcode", onInputPasscode = {})
}
}
@Preview
@Composable
fun ListPreferenceDialogPreview() {
NextcloudPasswordsTheme {
ListPreferenceDialog(
title = { Text("Language") },
options = mapOf(
"ES" to "Spanish",
"EN" to "English",
"CA" to "Catalan"
),
selectedOption = "CA",
onSelectOption = {}
)
}
}
@Preview
@Composable
fun GeneratePasswordDialogPreview() {
NextcloudPasswordsTheme {
PasswordGenerationDialog(onGenerate = { _, _, _ -> })
}
}

View file

@ -0,0 +1,294 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.ui.theme.ContentAlpha
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.ui.theme.favoriteColor
import kotlinx.coroutines.android.awaitFrame
import kotlinx.coroutines.launch
class EditableFolderState(originalFolder: Folder?) {
var label by mutableStateOf(originalFolder?.label ?: "")
var parent by mutableStateOf(originalFolder?.parent ?: FoldersApi.DEFAULT_FOLDER_UUID)
var favorite by mutableStateOf(originalFolder?.favorite ?: false)
fun isValid(): Boolean {
return label.isNotBlank()
}
companion object {
val Saver: Saver<EditableFolderState, *> = listSaver(
save = {
listOf(
it.label, it.parent, it.favorite.toString()
)
},
restore = {
EditableFolderState(null).apply {
label = it[0]
parent = it[1]
favorite = it[2].toBooleanStrictOrNull() ?: false
}
}
)
}
}
@Composable
fun rememberEditableFolderState(folder: Folder? = null): EditableFolderState =
rememberSaveable(folder, saver = EditableFolderState.Saver) {
EditableFolderState(folder)
}
@Composable
fun EditableFolderView(
editableFolderState: EditableFolderState,
folders: List<Folder>,
isUpdating: Boolean,
onSaveFolder: () -> Unit,
onDeleteFolder: (() -> Unit)? = null
) {
val coroutineScope = rememberCoroutineScope()
val onBackPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
var showDeleteDialog by rememberSaveable {
mutableStateOf(false)
}
var showFolderDialog by rememberSaveable {
mutableStateOf(false)
}
var showFieldErrors by rememberSaveable {
mutableStateOf(false)
}
var showDiscardDialog by rememberSaveable {
mutableStateOf(false)
}
var confirmedDiscard by rememberSaveable {
mutableStateOf(false)
}
BackHandler (enabled = !confirmedDiscard) {
showDiscardDialog = true
}
if (showDiscardDialog) {
DiscardChangesDialog(
onConfirmButton = {
confirmedDiscard = true
showDiscardDialog = false
coroutineScope.launch {
awaitFrame()
onBackPressedDispatcher?.onBackPressed()
confirmedDiscard = false
}
},
onDismissRequest = {
showDiscardDialog = false
}
)
}
LazyColumn {
item(key = "top_spacer") { Spacer(modifier = Modifier.width(16.dp)) }
item(key = "favorite_button") {
Button(
onClick = { editableFolderState.favorite = !editableFolderState.favorite },
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
colors = if (editableFolderState.favorite) ButtonDefaults.filledTonalButtonColors(
contentColor = MaterialTheme.colorScheme.onSurface,
containerColor = MaterialTheme.colorScheme.favoriteColor.copy(alpha = 0.3f)
)
else ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.80f),
containerColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f)
),
) {
Icon(
imageVector = Icons.Default.Star,
contentDescription = stringResource(id = R.string.password_attr_favorite)
)
Text(
text = stringResource(id = R.string.password_attr_favorite),
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
item(key = "folder_label") {
OutlinedTextField(
value = editableFolderState.label,
onValueChange = { newText -> editableFolderState.label = newText },
label = { Text(text = stringResource(id = R.string.password_folder_attr_label)) },
singleLine = true,
maxLines = 1,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
isError = showFieldErrors && editableFolderState.label.isBlank(),
supportingText = if (showFieldErrors && editableFolderState.label.isBlank()) {
{
Text(text = stringResource(id = R.string.error_field_cannot_be_empty))
}
} else null
)
}
item(key = "folder_parent") {
OutlinedClickableTextField(
value = if (editableFolderState.parent == FoldersApi.DEFAULT_FOLDER_UUID) {
stringResource(id = R.string.top_level_folder_name)
} else {
folders.firstOrNull { it.id == editableFolderState.parent }?.label
?: stringResource(id = R.string.top_level_folder_name)
},
label = stringResource(id = R.string.folder_attr_parent_folder),
onClick = { showFolderDialog = true },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp)
)
}
item(key = "folder_save") {
Button(
onClick = {
if (!editableFolderState.isValid()) {
showFieldErrors = true
} else {
onSaveFolder()
}
},
content = {
if (isUpdating) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.primary,
strokeWidth = 2.dp,
modifier = Modifier.size(16.dp)
)
} else {
Text(text = stringResource(id = R.string.action_save))
}
},
enabled = !isUpdating,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
if (onDeleteFolder != null) {
item(key = "folder_delete") {
if (!isUpdating) {
Button(
onClick = { showDeleteDialog = true },
colors = ButtonDefaults.outlinedButtonColors(
contentColor = MaterialTheme.colorScheme.error,
disabledContentColor = MaterialTheme.colorScheme.error.copy(alpha = ContentAlpha.medium)
),
content = {
Text(text = stringResource(id = R.string.action_delete_folder))
},
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
.padding(horizontal = 16.dp)
)
}
}
}
item(key = "bottom_spacer") {
Spacer(
modifier = Modifier
.windowInsetsBottomHeight(WindowInsets.ime.add(WindowInsets.navigationBars))
.padding(bottom = 16.dp)
)
}
}
if (showDeleteDialog) {
DeleteElementDialog(
onConfirmButton = {
showDeleteDialog = false
onDeleteFolder?.invoke()
},
onDismissRequest = {
showDeleteDialog = false
}
)
}
if (showFolderDialog) {
SelectFolderDialog(
folders = folders,
currentFolder = editableFolderState.parent,
onSelectClick = { folder ->
editableFolderState.parent = folder
showFolderDialog = false
},
onDismissRequest = {
showFolderDialog = false
}
)
}
}
@Preview
@Composable
fun FolderEditPreview() {
NextcloudPasswordsTheme {
Surface {
EditableFolderView(
editableFolderState = rememberEditableFolderState(),
folders = listOf(),
isUpdating = false,
onSaveFolder = { },
onDeleteFolder = { },
)
}
}
}

View file

@ -0,0 +1,407 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.twotone.Security
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.ui.theme.statusBreached
import com.hegocre.nextcloudpasswords.ui.theme.statusGood
import com.hegocre.nextcloudpasswords.ui.theme.statusWeak
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import kotlinx.coroutines.Dispatchers
data class ListDecryptionState<T>(
val decryptedList: List<T>? = null,
val isLoading: Boolean = false
)
@Composable
fun MixedLazyColumn(
passwords: List<Password>? = null,
folders: List<Folder>? = null,
onPasswordClick: ((Password) -> Unit)? = null,
onPasswordLongClick: ((Password) -> Unit)? = null,
onFolderClick: ((Folder) -> Unit)? = null,
onFolderLongClick: ((Folder) -> Unit)? = null,
getPainterForUrl: (@Composable (String) -> Painter)? = null
) {
val context = LocalContext.current
val shouldShowIcon by PreferencesManager.getInstance(context).getShowIcons()
.collectAsState(initial = false, context = Dispatchers.IO)
val listState = rememberLazyListState()
val knobRatio by remember {
derivedStateOf { (10f / ((passwords?.size ?: 0) + (folders?.size ?: 0))).coerceIn(0f, 1f) }
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.then(
if (knobRatio == 1f) Modifier else Modifier.scrollbar(
state = listState,
horizontal = false,
visibleAlpha = 0.5f,
fixedKnobRatio = knobRatio,
knobCornerRadius = 0.dp
)
),
state = listState
) {
folders?.let {
items(items = it, key = { folder -> folder.id }) { folder ->
FolderRow(
folder = folder,
onFolderClick = onFolderClick,
onFolderLongClick = onFolderLongClick
)
}
}
passwords?.let {
items(items = it, key = { password -> password.id }) { folder ->
PasswordRow(
password = folder,
shouldShowIcon = shouldShowIcon,
onPasswordClick = onPasswordClick,
onPasswordLongClick = onPasswordLongClick,
getPainterForUrl = getPainterForUrl
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PasswordRow(
password: Password,
modifier: Modifier = Modifier,
shouldShowIcon: Boolean = false,
onPasswordClick: ((Password) -> Unit)? = null,
onPasswordLongClick: ((Password) -> Unit)? = null,
getPainterForUrl: (@Composable (String) -> Painter)? = null
) {
ListItem(
modifier = modifier
.combinedClickable(
onClick = {
onPasswordClick?.invoke(password)
},
onLongClick = {
onPasswordLongClick?.invoke(password)
}
),
headlineContent = {
Text(
text = password.label,
)
},
supportingContent = if (password.username.isNotBlank()) {
{
Text(
text = password.username,
)
}
} else null,
trailingContent = if (password.status != 3) {
{
Icon(
imageVector = Icons.TwoTone.Security,
contentDescription = stringResource(id = R.string.password_attr_security_status),
modifier = Modifier
.size(40.dp)
.padding(all = 8.dp),
tint = (when (password.status) {
0 -> MaterialTheme.colorScheme.statusGood
1 -> MaterialTheme.colorScheme.statusWeak
2 -> MaterialTheme.colorScheme.statusBreached
else -> Color.Unspecified
})
)
}
} else null,
leadingContent = if (shouldShowIcon) {
{
getPainterForUrl?.let {
Image(
painter = getPainterForUrl(password.url.ifBlank { password.label }),
modifier = Modifier
.size(45.dp)
.padding(all = 8.dp)
.clip(RoundedCornerShape(4.dp)),
contentDescription = stringResource(R.string.content_description_site_favicon)
)
}
}
} else null,
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FolderRow(
folder: Folder,
modifier: Modifier = Modifier,
onFolderClick: ((Folder) -> Unit)? = null,
onFolderLongClick: ((Folder) -> Unit)? = null,
) {
ListItem(
leadingContent = {
Image(
imageVector = Icons.Filled.Folder,
contentDescription = stringResource(R.string.content_description_folder_icon),
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary),
modifier = Modifier
.size(45.dp)
.padding(8.dp)
)
},
headlineContent = {
Text(text = folder.label)
},
modifier = modifier
.combinedClickable(
onClick = {
onFolderClick?.invoke(folder)
},
onLongClick = {
onFolderLongClick?.invoke(folder)
}
)
)
}
// Scrollbars added from https://stackoverflow.com/questions/66341823/jetpack-compose-scrollbars/71932181#71932181
@Composable
fun Modifier.scrollbar(
state: LazyListState,
horizontal: Boolean,
alignEnd: Boolean = true,
thickness: Dp = 4.dp,
fixedKnobRatio: Float? = null,
knobCornerRadius: Dp = 4.dp,
trackCornerRadius: Dp = 2.dp,
knobColor: Color = MaterialTheme.colorScheme.onSurface,
padding: Dp = 0.dp,
visibleAlpha: Float = 1f,
hiddenAlpha: Float = 0f,
fadeInAnimationDurationMs: Int = 150,
fadeOutAnimationDurationMs: Int = 500,
fadeOutAnimationDelayMs: Int = 1000,
): Modifier {
check(thickness > 0.dp) { "Thickness must be a positive integer." }
check(fixedKnobRatio == null || fixedKnobRatio < 1f) {
"A fixed knob ratio must be smaller than 1."
}
check(knobCornerRadius >= 0.dp) { "Knob corner radius must be greater than or equal to 0." }
check(trackCornerRadius >= 0.dp) { "Track corner radius must be greater than or equal to 0." }
check(hiddenAlpha <= visibleAlpha) { "Hidden alpha cannot be greater than visible alpha." }
check(fadeInAnimationDurationMs >= 0) {
"Fade in animation duration must be greater than or equal to 0."
}
check(fadeOutAnimationDurationMs >= 0) {
"Fade out animation duration must be greater than or equal to 0."
}
check(fadeOutAnimationDelayMs >= 0) {
"Fade out animation delay must be greater than or equal to 0."
}
val targetAlpha =
if (state.isScrollInProgress) {
visibleAlpha
} else {
hiddenAlpha
}
val animationDurationMs =
if (state.isScrollInProgress) {
fadeInAnimationDurationMs
} else {
fadeOutAnimationDurationMs
}
val animationDelayMs =
if (state.isScrollInProgress) {
0
} else {
fadeOutAnimationDelayMs
}
val alpha by
animateFloatAsState(
targetValue = targetAlpha,
animationSpec =
tween(delayMillis = animationDelayMs, durationMillis = animationDurationMs),
label = "alpha"
)
return drawWithContent {
drawContent()
state.layoutInfo.visibleItemsInfo.firstOrNull()?.let { firstVisibleItem ->
if (state.isScrollInProgress || alpha > 0f) {
// Size of the viewport, the entire size of the scrollable composable we are decorating with
// this scrollbar.
val viewportSize =
if (horizontal) {
size.width
} else {
size.height
} - padding.toPx() * 2
// The size of the first visible item. We use this to estimate how many items can fit in the
// viewport. Of course, this works perfectly when all items have the same size. When they
// don't, the scrollbar knob size will grow and shrink as we scroll.
val firstItemSize = firstVisibleItem.size
// The *estimated* size of the entire scrollable composable, as if it's all on screen at
// once. It is estimated because it's possible that the size of the first visible item does
// not represent the size of other items. This will cause the scrollbar knob size to grow
// and shrink as we scroll, if the item sizes are not uniform.
val estimatedFullListSize = firstItemSize * state.layoutInfo.totalItemsCount
// The difference in position between the first pixels visible in our viewport as we scroll
// and the top of the fully-populated scrollable composable, if it were to show all the
// items at once. At first, the value is 0 since we start all the way to the top (or start
// edge). As we scroll down (or towards the end), this number will grow.
val viewportOffsetInFullListSpace =
state.firstVisibleItemIndex * firstItemSize + state.firstVisibleItemScrollOffset
// Where we should render the knob in our composable.
val knobPosition =
(viewportSize / estimatedFullListSize) * viewportOffsetInFullListSpace + padding.toPx()
// How large should the knob be.
val knobSize =
fixedKnobRatio?.let { it * viewportSize }
?: ((viewportSize * viewportSize) / estimatedFullListSize)
// Draw the knob
drawRoundRect(
color = knobColor,
topLeft =
when {
// When the scrollbar is horizontal and aligned to the bottom:
horizontal && alignEnd -> Offset(
knobPosition,
size.height - thickness.toPx()
)
// When the scrollbar is horizontal and aligned to the top:
horizontal && !alignEnd -> Offset(knobPosition, 0f)
// When the scrollbar is vertical and aligned to the end:
alignEnd -> Offset(size.width - thickness.toPx(), knobPosition)
// When the scrollbar is vertical and aligned to the start:
else -> Offset(0f, knobPosition)
},
size =
if (horizontal) {
Size(knobSize, thickness.toPx())
} else {
Size(thickness.toPx(), knobSize)
},
alpha = alpha,
cornerRadius = CornerRadius(
x = knobCornerRadius.toPx(),
y = knobCornerRadius.toPx()
),
)
}
}
}
}
@Preview
@Composable
fun PasswordRowPreview() {
NextcloudPasswordsTheme {
PasswordRow(
password = Password(
id = "",
label = "Nextcloud",
username = "john_doe",
password = "secret_value",
url = "https://nextcloud.com/",
notes = "",
customFields = "",
status = 0,
statusCode = "GOOD",
hash = "",
folder = "",
revision = "",
share = null,
shared = false,
cseType = "",
cseKey = "",
sseType = "",
client = "",
hidden = false,
trashed = false,
favorite = true,
editable = true,
edited = 0,
created = 0,
updated = 0
),
shouldShowIcon = true
)
}
}
@Preview
@Composable
fun FolderRowPreview() {
NextcloudPasswordsTheme {
FolderRow(
folder = Folder(
id = "",
label = "Management",
parent = "00000000-0000-0000-0000-000000000000",
revision = "",
cseType = "",
cseKey = "",
sseType = "",
client = "",
hidden = false,
trashed = false,
favorite = false,
created = 0,
updated = 0,
edited = 0
)
)
}
}

View file

@ -0,0 +1,384 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.http.SslError
import android.view.View
import android.view.ViewGroup
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
@Composable
fun NCPLoginScreen(
loginIntent: Intent,
onLoginSuccess: () -> Unit,
onLoginFailed: () -> Unit
) {
NextcloudPasswordsTheme {
Scaffold(
topBar = {
Spacer(
modifier = Modifier
.statusBarsPadding()
.fillMaxWidth()
)
},
bottomBar = {
Spacer(
modifier = Modifier
.statusBarsPadding()
.fillMaxWidth()
)
}
) { innerPadding ->
LoginView(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
loginIntent = loginIntent,
onLoginSuccess = onLoginSuccess,
onLoginFailed = onLoginFailed
)
}
}
}
@Composable
fun LoginView(
modifier: Modifier = Modifier,
loginIntent: Intent,
onLoginSuccess: () -> Unit,
onLoginFailed: () -> Unit
) {
val launchLoginWebView =
rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
if (result.data?.getBooleanExtra("loggedIn", false) == true) {
onLoginSuccess()
}
} else if (result.resultCode == Activity.RESULT_CANCELED) {
if (result.data?.getBooleanExtra("loggedIn", false) == false) {
onLoginFailed()
}
}
}
val (urlText, setUrlText) = remember { mutableStateOf("") }
var errorText by remember { mutableStateOf("") }
val errorMessages = listOf(
stringResource(R.string.error_url_cannot_be_empty),
stringResource(R.string.error_url_must_start_https)
)
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.verticalScroll(rememberScrollState())
) {
LoginCard(
text = urlText,
onTextChange = setUrlText,
errorText = errorText,
onLoginButtonClick = {
when {
urlText.isBlank() -> {
errorText = errorMessages[0]
}
urlText.startsWith("http://") -> {
errorText = errorMessages[1]
}
else -> {
errorText = ""
if (!urlText.startsWith("https://"))
setUrlText(String.format("https://%s", urlText))
loginIntent.putExtra(
"login_url",
if (urlText.startsWith("https://")) urlText else "https://$urlText"
)
launchLoginWebView.launch(loginIntent)
}
}
}
)
Text(
text = "v${stringResource(id = R.string.version_name)} (${stringResource(id = R.string.version_code)})",
fontSize = 12.sp,
color = LocalContentColor.current.copy(alpha = 0.7f),
modifier = Modifier.padding(top = 4.dp)
)
}
}
}
@Composable
fun LoginCard(
text: String,
onTextChange: (String) -> Unit,
errorText: String,
onLoginButtonClick: () -> Unit
) {
Card {
Column(
modifier = Modifier
.padding(all = 20.dp)
) {
Image(
modifier = Modifier
.height(70.dp)
.width(70.dp)
.clip(CircleShape)
.align(Alignment.CenterHorizontally),
painter = painterResource(id = R.drawable.app_icon),
contentDescription = stringResource(id = R.string.app_name)
)
OutlinedTextFieldWithCaption(
text = text,
onValueChange = onTextChange,
modifier = Modifier
.padding(vertical = 8.dp),
label = stringResource(id = R.string.login_server_url),
captionText = "${stringResource(R.string.example)}: https://cloud.example.com/",
errorText = errorText,
onDone = onLoginButtonClick
)
Button(
modifier = Modifier.align(Alignment.End),
onClick = onLoginButtonClick
) {
Text(text = stringResource(R.string.action_login))
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun NCPWebLoginScreen(
onLoginUrl: (String) -> Unit,
modifier: Modifier = Modifier,
url: String = ""
) {
NextcloudPasswordsTheme {
val context = LocalContext.current
var showTlsDialog by rememberSaveable { mutableStateOf(false) }
var skipTlsValidation by rememberSaveable { mutableStateOf(false) }
val (title, setTitle) = rememberSaveable {
mutableStateOf(url)
}
BackHandler(enabled = skipTlsValidation) {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
val componentName = intent?.component
val mainIntent = Intent.makeRestartActivityTask(componentName)
context.startActivity(mainIntent)
Runtime.getRuntime().exit(0)
}
val webViewClient = remember(skipTlsValidation) {
object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.url.toString().let { url ->
setTitle(url)
if (url.startsWith("nc://")) {
//Login credentials captured, clear all login data
view?.clearCache(true)
view?.clearFormData()
view?.clearHistory()
view?.visibility = View.GONE
if (skipTlsValidation) {
PreferencesManager.getInstance(context)
.setSkipCertificateValidation(true)
}
onLoginUrl(url)
} else view?.loadUrl(url, mapOf("OCS-APIREQUEST" to "true"))
}
return false
}
@SuppressLint("WebViewClientOnReceivedSslError")
override fun onReceivedSslError(
view: WebView?,
handler: SslErrorHandler?,
error: SslError?
) {
if (skipTlsValidation) {
handler?.proceed()
} else {
showTlsDialog = true
super.onReceivedSslError(view, handler, error)
}
}
}
}
val (loadingProgress, setLoadingProgress) = remember { mutableIntStateOf(0) }
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
title = {
Text(
text = title,
maxLines = 1,
fontSize = 14.sp,
overflow = TextOverflow.Clip
)
},
windowInsets = WindowInsets.statusBars
)
},
bottomBar = {
Spacer(modifier = Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
},
) { paddingValues ->
Box(modifier = Modifier.padding(paddingValues)) {
AndroidView(
factory = {
WebView(it).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
val webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
setLoadingProgress(newProgress)
super.onProgressChanged(view, newProgress)
}
}
this.webChromeClient = webChromeClient
this.webViewClient = webViewClient
settings.domStorageEnabled = true
settings.javaScriptEnabled = true
settings.userAgentString = it.getString(R.string.app_name)
loadUrl(url, mapOf("OCS-APIREQUEST" to "true"))
}
},
update = {
it.webViewClient = webViewClient
it.loadUrl(url, mapOf("OCS-APIREQUEST" to "true"))
},
)
if (loadingProgress < 100) {
LinearProgressIndicator(
progress = { (loadingProgress.toFloat() / 100) },
modifier = Modifier.fillMaxWidth(),
)
}
}
if (showTlsDialog) {
AlertDialog(
onDismissRequest = { showTlsDialog = false },
confirmButton = {
TextButton(
onClick = {
skipTlsValidation = true
showTlsDialog = false
}
) {
Text(text = stringResource(id = android.R.string.ok))
}
},
dismissButton = {
TextButton(
onClick = {
showTlsDialog = false
}
) {
Text(text = stringResource(id = android.R.string.cancel))
}
},
title = { Text(stringResource(id = R.string.dialog_invalid_certificate_title)) },
text = { Text(text = stringResource(id = R.string.dialog_invalid_certificate_text)) }
)
}
}
}
}
@Preview(name = "Login card")
@Composable
fun PreviewCard() {
NextcloudPasswordsTheme {
LoginCard("", {}, "") {}
}
}

View file

@ -0,0 +1,439 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.outlined.Campaign
import androidx.compose.material.icons.outlined.Code
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.Handshake
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.Policy
import androidx.compose.material.icons.outlined.Web
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
data class LicenseNotice(
val name: String,
val copyright: String,
val licenseName: String,
val licenseUrl: String
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NCPAboutScreen(
onBackPressed: () -> Unit,
onLogoLongPressed: (() -> Unit)? = null
) {
val uriHandler = LocalUriHandler.current
var showLicensesDialog by rememberSaveable { mutableStateOf(false) }
NextcloudPasswordsTheme {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = stringResource(id = R.string.screen_about))
},
navigationIcon = {
IconButton(onClick = onBackPressed) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.navigation_back)
)
}
},
windowInsets = WindowInsets.statusBars
)
},
contentWindowInsets = WindowInsets.systemBars
) { paddingValues ->
Column(
modifier = Modifier.padding(paddingValues),
horizontalAlignment = Alignment.CenterHorizontally
) {
LazyColumn(modifier = Modifier.weight(1f)) {
item {
OutlinedCard(
border = CardDefaults.outlinedCardBorder(enabled = false),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(modifier = Modifier.padding(bottom = 8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
modifier = Modifier
.padding(20.dp)
.height(50.dp)
.width(50.dp)
.clip(CircleShape),
painter = painterResource(id = R.drawable.app_icon),
contentDescription = stringResource(id = R.string.app_name)
)
Text(
text = stringResource(id = R.string.app_name),
style = MaterialTheme.typography.headlineMedium
)
}
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Info,
contentDescription = stringResource(id = R.string.version)
)
},
primaryText = { Text(text = stringResource(id = R.string.version)) },
secondaryText = {
Text(
text = "v${stringResource(id = R.string.version_name)} " +
"(${stringResource(id = R.string.version_code)})"
)
},
onLongClick = {
onLogoLongPressed?.invoke()
}
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Code,
contentDescription = stringResource(id = R.string.source_code)
)
},
primaryText = { Text(text = stringResource(id = R.string.source_code)) },
onClick = { uriHandler.openUri(repoUrl) }
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.History,
contentDescription = stringResource(id = R.string.changelog)
)
},
primaryText = { Text(text = stringResource(id = R.string.changelog)) },
onClick = { uriHandler.openUri(changelogUrl) }
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Campaign,
contentDescription = stringResource(id = R.string.help_suggestions)
)
},
primaryText = { Text(text = stringResource(id = R.string.help_suggestions)) },
onClick = { uriHandler.openUri("$repoUrl/issues") }
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Handshake,
contentDescription = stringResource(id = R.string.contribute)
)
},
primaryText = { Text(text = stringResource(id = R.string.contribute)) },
onClick = { uriHandler.openUri(contributeUrl) }
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Description,
contentDescription = stringResource(id = R.string.licenses)
)
},
primaryText = { Text(text = stringResource(id = R.string.licenses)) },
onClick = { showLicensesDialog = true }
)
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Policy,
contentDescription = stringResource(id = R.string.privacy_policy)
)
},
primaryText = { Text(text = stringResource(id = R.string.privacy_policy)) },
onClick = { uriHandler.openUri(policyUrl) }
)
}
}
}
//Authors card
item {
OutlinedCard(
border = CardDefaults.outlinedCardBorder(enabled = false),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(modifier = Modifier.padding(vertical = 8.dp)) {
Text(
text = stringResource(id = R.string.author),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 12.dp, horizontal = 16.dp),
)
for (author in authors) {
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Person,
contentDescription = stringResource(id = R.string.author)
)
},
primaryText = { Text(text = author.key) },
onClick = { uriHandler.openUri(author.value) }
)
}
AboutTextField(
icon = {
Icon(
imageVector = Icons.Outlined.Web,
contentDescription = stringResource(id = R.string.website)
)
},
primaryText = { Text(text = stringResource(id = R.string.website)) },
onClick = { uriHandler.openUri(websiteUrl) }
)
}
}
}
}
}
if (showLicensesDialog) {
LicensesDialog(
licenses = licenses,
onDismissRequest = { showLicensesDialog = false }
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AboutTextField(
modifier: Modifier = Modifier,
icon: (@Composable () -> Unit)? = null,
primaryText: (@Composable () -> Unit)? = null,
secondaryText: (@Composable () -> Unit)? = null,
onClick: () -> Unit = {},
onLongClick: () -> Unit = {}
) {
Row(
modifier = modifier
.fillMaxWidth()
.combinedClickable(onClick = onClick, onLongClick = onLongClick)
.padding(vertical = 12.dp, horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = 0.7f),
) {
icon?.invoke()
}
Column(modifier = Modifier.padding(start = if (icon == null) 0.dp else 24.dp)) {
primaryText?.let { content ->
CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.bodyLarge
) {
content()
}
}
secondaryText?.let { content ->
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = 0.7f),
LocalTextStyle provides MaterialTheme.typography.bodyMedium
) {
content()
}
}
}
}
}
@Composable
fun LicensesDialog(
licenses: List<LicenseNotice>,
onDismissRequest: (() -> Unit)? = null
) {
Dialog(
onDismissRequest = { onDismissRequest?.invoke() },
) {
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colorScheme.surface),
shape = MaterialTheme.shapes.extraLarge,
) {
Column(modifier = Modifier.padding(vertical = 24.dp)) {
Text(
text = stringResource(id = R.string.licenses),
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 24.dp)
)
val uriHandler = LocalUriHandler.current
LazyColumn(modifier = Modifier.weight(1f, fill = false)) {
items(items = licenses, key = { it.name }) { license ->
ListItem(
headlineContent = {
Text(text = license.name)
},
overlineContent = if (license.copyright.isNotBlank()) {
{
Text(text = license.copyright)
}
} else null,
supportingContent = {
Text(text = license.licenseName)
},
modifier = Modifier
.clickable {
uriHandler.openUri(license.licenseUrl)
}
.padding(horizontal = 10.dp)
)
}
}
TextButton(
onClick = { onDismissRequest?.invoke() },
modifier = Modifier
.align(Alignment.End)
.padding(horizontal = 24.dp)
) {
Text(text = stringResource(android.R.string.ok))
}
}
}
}
}
const val policyUrl = "https://hegocre.com/nextcloudpasswords/privacy.html"
const val repoUrl = "https://github.com/hegocre/NextcloudPasswords"
const val websiteUrl = "https://hegocre.com/"
const val changelogUrl = "https://github.com/hegocre/NextcloudPasswords/releases/latest"
const val contributeUrl = "https://github.com/hegocre/NextcloudPasswords#contribute"
val authors = mapOf(
"Hector Godoy" to "https://github.com/hegocre",
)
val licenses = listOf(
LicenseNotice(
name = "Kotlin Programming Language",
copyright = "Copyright (C) 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.",
licenseName = "Apache License 2.0",
licenseUrl = "https://github.com/JetBrains/kotlin/blob/master/license/LICENSE.txt"
),
LicenseNotice(
name = "Android Jetpack",
copyright = "Copyright (C) 2023 The Android Open Source Project",
licenseName = "Apache License 2.0",
licenseUrl = "https://github.com/androidx/androidx/blob/androidx-main/LICENSE.txt"
),
LicenseNotice(
name = "OkHttp",
copyright = "Copyright (C) 2019 Square, Inc.",
licenseName = "Apache License 2.0",
licenseUrl = "https://github.com/square/okhttp/blob/master/LICENSE.txt"
),
LicenseNotice(
name = "Java Native Access",
copyright = "",
licenseName = "Apache License 2.0",
licenseUrl = "https://github.com/java-native-access/jna/blob/master/AL2.0"
),
LicenseNotice(
name = "Lazysodium Android",
copyright = "Copyright (C) 2022 Terl Tech Ltd • goterl.com",
licenseName = "Mozilla Public License 2.0",
licenseUrl = "https://github.com/terl/lazysodium-android/blob/master/LICENSE.md"
),
LicenseNotice(
name = "Markdown Composer",
copyright = "Copyright (C) 2021 Erik Hellman",
licenseName = "MIT License",
licenseUrl = "https://github.com/ErikHellman/MarkdownComposer/blob/master/LICENSE.txt"
),
LicenseNotice(
name = "MaterialKolor",
copyright = "Copyright (c) 2023 Jordon de Hoog",
licenseName = "MIT License",
licenseUrl = "https://github.com/jordond/MaterialKolor/blob/main/LICENSE"
),
)
@Preview
@Composable
fun NCPAboutPreview() {
NCPAboutScreen({})
}
@Preview
@Composable
fun LicensesDialogPreview() {
NextcloudPasswordsTheme {
LicensesDialog(licenses = licenses)
}
}

View file

@ -0,0 +1,314 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.ui.NCPScreen
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.ui.viewmodels.PasswordsViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NextcloudPasswordsApp(
passwordsViewModel: PasswordsViewModel,
onLogOut: () -> Unit,
isAutofillRequest: Boolean = false,
defaultSearchQuery: String = "",
replyAutofill: ((String, String, String) -> Unit)? = null
) {
val coroutineScope = rememberCoroutineScope()
val navController = rememberNavController()
val backstackEntry = navController.currentBackStackEntryAsState()
val currentScreen = NCPScreen.fromRoute(
backstackEntry.value?.destination?.route
)
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val modalSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val needsMasterPassword by passwordsViewModel.needsMasterPassword.collectAsState()
val masterPasswordInvalid by passwordsViewModel.masterPasswordInvalid.collectAsState()
val sessionOpen by passwordsViewModel.sessionOpen.collectAsState()
val showSessionOpenError by passwordsViewModel.showSessionOpenError.collectAsState()
val isRefreshing by passwordsViewModel.isRefreshing.collectAsState()
var showLogOutDialog by rememberSaveable { mutableStateOf(false) }
var showAddElementDialog by rememberSaveable { mutableStateOf(false) }
val keyboardController = LocalSoftwareKeyboardController.current
var searchExpanded by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(Unit) {
if (isAutofillRequest) searchExpanded = true
}
val (searchQuery, setSearchQuery) = rememberSaveable { mutableStateOf(defaultSearchQuery) }
val server = remember {
passwordsViewModel.server
}
NextcloudPasswordsTheme {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
Scaffold(
modifier = Modifier
.nestedScroll(scrollBehavior.nestedScrollConnection)
.imePadding(),
topBar = {
if (currentScreen != NCPScreen.PasswordEdit && currentScreen != NCPScreen.FolderEdit) {
NCPSearchTopBar(
username = server.username,
serverAddress = server.url,
title = when (currentScreen) {
NCPScreen.Passwords, NCPScreen.Favorites -> stringResource(currentScreen.title)
NCPScreen.Folders -> {
passwordsViewModel.visibleFolder.value?.let {
if (it.id == FoldersApi.DEFAULT_FOLDER_UUID)
stringResource(currentScreen.title)
else
it.label
} ?: stringResource(currentScreen.title)
}
else -> ""
},
userAvatar = { size ->
Image(
painter = passwordsViewModel.getPainterForAvatar(),
contentDescription = "",
modifier = Modifier
.clip(CircleShape)
.size(size)
)
},
searchQuery = searchQuery,
setSearchQuery = setSearchQuery,
isAutofill = isAutofillRequest,
searchExpanded = searchExpanded,
onSearchClick = { searchExpanded = true },
onSearchCloseClick = {
searchExpanded = false
setSearchQuery("")
},
onLogoutClick = { showLogOutDialog = true },
scrollBehavior = scrollBehavior
)
} else {
TopAppBar(
title = { Text(text = stringResource(id = currentScreen.title)) },
navigationIcon = {
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.navigation_back)
)
}
}
)
}
},
bottomBar = {
Column {
AnimatedVisibility(visible = !sessionOpen && showSessionOpenError && !isRefreshing) {
Surface(
color = MaterialTheme.colorScheme.errorContainer,
modifier = Modifier.clickable { (passwordsViewModel.sync()) }
) {
Text(
text = stringResource(id = R.string.error_cannot_connect_to_server),
style = MaterialTheme.typography.bodySmall,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
}
val navigationHeight =
WindowInsets.navigationBars.getBottom(LocalDensity.current)
AnimatedVisibility(
visible = currentScreen != NCPScreen.PasswordEdit
&& currentScreen != NCPScreen.FolderEdit,
enter = slideInVertically(initialOffsetY = { (it + navigationHeight) }),
exit = slideOutVertically(targetOffsetY = { (it + navigationHeight) })
) {
NCPBottomNavigation(
allScreens = NCPScreen.entries.filter { !it.hidden },
currentScreen = currentScreen,
onScreenSelected = { screen ->
navController.navigate(screen.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
},
)
}
}
},
floatingActionButton = {
AnimatedVisibility(
visible = currentScreen != NCPScreen.PasswordEdit &&
currentScreen != NCPScreen.FolderEdit && sessionOpen,
enter = scaleIn(),
exit = scaleOut(),
) {
FloatingActionButton(
onClick = { showAddElementDialog = true },
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = stringResource(id = R.string.action_create_element)
)
}
}
}
) { innerPadding ->
NCPNavHost(
modifier = Modifier.padding(innerPadding),
navController = navController,
passwordsViewModel = passwordsViewModel,
searchQuery = searchQuery,
isAutofillRequest = isAutofillRequest,
modalSheetState = modalSheetState,
openPasswordDetails = { password, folderPath ->
passwordsViewModel.setVisiblePassword(password, folderPath)
keyboardController?.hide()
openBottomSheet = true
},
replyAutofill = replyAutofill,
searchVisibility = searchExpanded,
closeSearch = {
searchExpanded = false
setSearchQuery("")
},
)
if (showLogOutDialog) {
LogOutDialog(
onDismissRequest = { showLogOutDialog = false },
onConfirmButton = onLogOut
)
}
if (showAddElementDialog) {
AddElementDialog(
onPasswordAdd = {
navController.navigate("${NCPScreen.PasswordEdit.name}/none")
showAddElementDialog = false
},
onFolderAdd = {
navController.navigate("${NCPScreen.FolderEdit.name}/none")
showAddElementDialog = false
},
onDismissRequest = {
showAddElementDialog = false
}
)
}
if (needsMasterPassword) {
val (masterPassword, setMasterPassword) = rememberSaveable {
mutableStateOf("")
}
val (savePassword, setSavePassword) = rememberSaveable {
mutableStateOf(false)
}
MasterPasswordDialog(
masterPassword = masterPassword,
setMasterPassword = setMasterPassword,
savePassword = savePassword,
setSavePassword = setSavePassword,
onOkClick = {
passwordsViewModel.setMasterPassword(masterPassword, savePassword)
setMasterPassword("")
},
errorText = if (masterPasswordInvalid) stringResource(R.string.error_invalid_password) else "",
onDismissRequest = { }
)
}
if (openBottomSheet) {
ModalBottomSheet(
onDismissRequest = { openBottomSheet = false },
contentWindowInsets = { WindowInsets.navigationBars },
sheetState = modalSheetState
) {
PasswordItem(
passwordInfo = passwordsViewModel.visiblePassword.value,
onEditPassword = if (sessionOpen) {
{
coroutineScope.launch {
modalSheetState.hide()
}.invokeOnCompletion {
if (!modalSheetState.isVisible) {
openBottomSheet = false
}
}
navController.navigate("${NCPScreen.PasswordEdit.name}/${passwordsViewModel.visiblePassword.value?.first?.id ?: "none"}")
}
} else null,
modifier = Modifier.padding(bottom = 16.dp)
)
}
}
}
}
}

View file

@ -0,0 +1,509 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.content.res.Configuration
import androidx.biometric.BiometricManager
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Backspace
import androidx.compose.material.icons.outlined.Fingerprint
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.utils.AppLockHelper
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.hegocre.nextcloudpasswords.utils.showBiometricPrompt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.job
import kotlin.math.roundToInt
@Composable
fun NCPAppLockWrapper(
content: @Composable () -> Unit,
) {
val context = LocalContext.current
val appLockHelper = remember { AppLockHelper.getInstance(context) }
val hasAppLock by PreferencesManager.getInstance(context).getHasAppLock()
.collectAsState(null)
val isLocked by appLockHelper.isLocked.collectAsState()
hasAppLock?.let {
Crossfade(targetState = it && isLocked, label = "locked") { locked ->
if (locked) {
NextcloudPasswordsAppLock(
onCheckPasscode = appLockHelper::checkPasscode,
onCorrectPasscode = appLockHelper::disableLock
)
} else {
if (hasAppLock == false) {
// Avoid asking for passcode just after setting it
appLockHelper.disableLock()
}
content()
}
}
}
}
@Composable
fun NextcloudPasswordsAppLock(
onCheckPasscode: (String) -> Deferred<Boolean>,
onCorrectPasscode: () -> Unit
) {
val isPreview = LocalInspectionMode.current
val (inputPassword, setInputPassword) = rememberSaveable {
mutableStateOf("")
}
var isError by remember { mutableStateOf(false) }
val context = LocalContext.current
val hasBiometricAppLock by if (isPreview) remember { mutableStateOf(true) }
else PreferencesManager.getInstance(context).getHasBiometricAppLock().collectAsState(
initial = false
)
val canAuthenticateBiometric = if (isPreview) remember { true }
else remember {
BiometricManager.from(context)
.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
}
LaunchedEffect(key1 = inputPassword) {
if (onCheckPasscode(inputPassword).await()) {
onCorrectPasscode()
}
}
LaunchedEffect(key1 = isError) {
if (isError) {
delay(1500L)
isError = false
}
}
LaunchedEffect(key1 = hasBiometricAppLock) {
if (hasBiometricAppLock && canAuthenticateBiometric) {
showBiometricPrompt(
context = context,
title = context.getString(R.string.biometric_prompt_title),
description = context.getString(R.string.biometric_prompt_description),
onBiometricUnlock = onCorrectPasscode
)
}
}
val requester = remember { FocusRequester() }
NextcloudPasswordsTheme {
Scaffold(
modifier = Modifier
.onKeyEvent { keyEvent ->
if (keyEvent.type == KeyEventType.KeyDown) {
when (keyEvent.key) {
Key.Zero, Key.NumPad0 -> setInputPassword(inputPassword + "0")
Key.One, Key.NumPad1 -> setInputPassword(inputPassword + "1")
Key.Two, Key.NumPad2 -> setInputPassword(inputPassword + "2")
Key.Three, Key.NumPad3 -> setInputPassword(inputPassword + "3")
Key.Four, Key.NumPad4 -> setInputPassword(inputPassword + "4")
Key.Five, Key.NumPad5 -> setInputPassword(inputPassword + "5")
Key.Six, Key.NumPad6 -> setInputPassword(inputPassword + "6")
Key.Seven, Key.NumPad7 -> setInputPassword(inputPassword + "7")
Key.Eight, Key.NumPad8 -> setInputPassword(inputPassword + "8")
Key.Nine, Key.NumPad9 -> setInputPassword(inputPassword + "9")
Key.Backspace -> setInputPassword(inputPassword.dropLast(1))
}
}
return@onKeyEvent true
}
.focusRequester(requester)
) { paddingValues ->
LaunchedEffect(key1 = Unit) {
coroutineContext.job.invokeOnCompletion {
if (it?.cause == null) {
requester.requestFocus()
}
}
}
Box(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
if (LocalConfiguration.current.orientation != Configuration.ORIENTATION_LANDSCAPE) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
PasscodeIndicator(
inputPassword = inputPassword,
isError = isError
)
val spacerPadding = minOf((screenHeight() * 0.04).roundToInt(), 170)
Spacer(modifier = Modifier.height(spacerPadding.dp))
KeyPad(
inputPassword = inputPassword,
setInputPassword = { setInputPassword(inputPassword + it) },
showBiometricIndicator = hasBiometricAppLock && canAuthenticateBiometric,
onBiometricClick = {
showBiometricPrompt(
context = context,
title = context.getString(R.string.biometric_prompt_title),
description = context.getString(R.string.biometric_prompt_description),
onBiometricUnlock = onCorrectPasscode
)
},
showBackspaceIndicator = inputPassword.isNotBlank(),
onBackspaceClick = { setInputPassword(inputPassword.dropLast(1)) },
onBackspaceLongClick = { setInputPassword("") }
)
}
} else {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.Center
) {
PasscodeIndicator(
inputPassword = inputPassword,
isError = isError
)
}
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.Center
) {
KeyPad(
inputPassword = inputPassword,
setInputPassword = { setInputPassword(inputPassword + it) },
showBiometricIndicator = hasBiometricAppLock && canAuthenticateBiometric,
onBiometricClick = {
showBiometricPrompt(
context = context,
title = context.getString(R.string.biometric_prompt_title),
description = context.getString(R.string.biometric_prompt_description),
onBiometricUnlock = onCorrectPasscode
)
},
showBackspaceIndicator = inputPassword.isNotBlank(),
onBackspaceClick = { setInputPassword(inputPassword.dropLast(1)) },
onBackspaceLongClick = { setInputPassword("") }
)
}
}
}
}
}
}
}
@Composable
fun PasscodeIndicator(
inputPassword: String,
isError: Boolean,
) {
Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = if (!isError)
stringResource(id = R.string.app_lock_input_passcode)
else
stringResource(id = R.string.error_app_lock_incorrect_code),
)
val spacerPadding = minOf((screenHeight() * 0.1).roundToInt(), 170)
Spacer(modifier = Modifier.height(spacerPadding.dp))
if (inputPassword.isEmpty()) {
Spacer(modifier = Modifier.height(10.dp))
} else {
LazyRow(modifier = Modifier.padding(horizontal = 16.dp)) {
items(count = inputPassword.length, key = { it }) {
KeyboardDigitIndicator(
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.animateItem()
)
}
}
}
}
}
@Composable
fun KeyPad(
inputPassword: String,
setInputPassword: (String) -> Unit,
showBiometricIndicator: Boolean,
onBiometricClick: () -> Unit,
showBackspaceIndicator: Boolean,
onBackspaceClick: () -> Unit,
onBackspaceLongClick: () -> Unit,
modifier: Modifier = Modifier
) {
val isPreview = LocalInspectionMode.current
Column(modifier = modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Row {
KeyboardNumber(
number = "1",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "2",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "3",
onPressNumber = setInputPassword
)
}
Row {
KeyboardNumber(
number = "4",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "5",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "6",
onPressNumber = setInputPassword
)
}
Row {
KeyboardNumber(
number = "7",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "8",
onPressNumber = setInputPassword
)
KeyboardNumber(
number = "9",
onPressNumber = setInputPassword
)
}
Row {
if (showBiometricIndicator) {
FilledTonalIconButton(
onClick = onBiometricClick,
modifier = Modifier
.padding(buttonPadding().dp)
.height(buttonSize().dp)
.width(buttonSize().dp)
) {
Icon(
imageVector = Icons.Outlined.Fingerprint,
contentDescription = stringResource(id = R.string.biometric_unlock_preference_title),
modifier = Modifier.size(35.dp)
)
}
} else {
Spacer(
modifier = Modifier
.padding(buttonPadding().dp)
.height(buttonSize().dp)
.width(buttonSize().dp)
)
}
KeyboardNumber(
number = "0",
onPressNumber = setInputPassword
)
if (isPreview || showBackspaceIndicator) {
val interactionSource = remember { MutableInteractionSource() }
val viewConfiguration = LocalViewConfiguration.current
LaunchedEffect(interactionSource, inputPassword) {
var isLongClick = false
interactionSource.interactions.collectLatest { interaction ->
when (interaction) {
is PressInteraction.Press -> {
isLongClick = false
delay(viewConfiguration.longPressTimeoutMillis)
isLongClick = true
onBackspaceLongClick()
}
is PressInteraction.Release -> {
if (isLongClick.not()) {
onBackspaceClick()
}
}
}
}
}
FilledTonalIconButton(
onClick = {},
interactionSource = interactionSource,
modifier = Modifier
.padding(buttonPadding().dp)
.height(buttonSize().dp)
.width(buttonSize().dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Outlined.Backspace,
contentDescription = stringResource(id = R.string.action_delete),
modifier = Modifier.size(25.dp)
)
}
} else {
Spacer(
modifier = Modifier
.padding(buttonPadding().dp)
.height(buttonSize().dp)
.width(buttonSize().dp)
)
}
}
}
}
@Composable
fun KeyboardNumber(
number: String,
onPressNumber: (String) -> Unit
) {
FilledTonalButton(
onClick = {
onPressNumber(number)
},
modifier = Modifier
.padding(buttonPadding().dp)
.height(buttonSize().dp)
.width(buttonSize().dp)
) {
Text(text = number, fontSize = 25.sp)
}
}
@Composable
fun KeyboardDigitIndicator(
color: Color,
modifier: Modifier = Modifier
) {
var visible by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
visible = true
}
val scale by animateFloatAsState(targetValue = if (visible) 1f else 0f, label = "opacity")
Spacer(
modifier = modifier
.padding(horizontal = 8.dp)
.height(10.dp)
.width(10.dp)
.scale(scale)
.clip(CircleShape)
.background(color)
)
}
@Composable
fun screenHeight(): Float =
LocalConfiguration.current.screenHeightDp.toFloat()
@Composable
fun screenWidth(): Float =
LocalConfiguration.current.screenWidthDp.toFloat()
@Composable
fun buttonSize(): Int {
val screenHeight = screenHeight().times(
if (LocalConfiguration.current.orientation != Configuration.ORIENTATION_LANDSCAPE) 0.8f else 1f
)
return minOf((screenHeight * 0.20).roundToInt(), (screenWidth() * 0.25).roundToInt(), 90)
}
@Composable
fun buttonPadding(): Int {
val screenHeight = screenHeight().times(
if (LocalConfiguration.current.orientation != Configuration.ORIENTATION_LANDSCAPE) 0.8f else 1f
)
return minOf((screenHeight * 0.04).roundToInt(), (screenWidth() * 0.06).roundToInt(), 8)
}
@Preview
@Composable
fun AppLockPreview() {
NextcloudPasswordsTheme {
NextcloudPasswordsAppLock(onCheckPasscode = {
return@NextcloudPasswordsAppLock CoroutineScope(Dispatchers.Default).async {
true
}
}, {})
}
}

View file

@ -0,0 +1,54 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.hegocre.nextcloudpasswords.ui.NCPScreen
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
@Composable
fun NCPBottomNavigation(
allScreens: List<NCPScreen>,
currentScreen: NCPScreen,
onScreenSelected: (NCPScreen) -> Unit,
modifier: Modifier = Modifier
) {
NavigationBar(
modifier = modifier,
windowInsets = WindowInsets.navigationBars
) {
allScreens.forEach { screen ->
NavigationBarItem(
icon = {
Icon(
imageVector = if (currentScreen == screen) screen.selectedIcon else screen.unselectedIcon,
contentDescription = screen.name
)
},
label = { Text(text = stringResource(screen.title)) },
selected = currentScreen == screen,
onClick = { onScreenSelected(screen) },
alwaysShowLabel = false,
)
}
}
}
@Preview(name = "Bottom Navigation preview")
@Composable
fun NCPBottomNavigationPreview() {
NextcloudPasswordsTheme {
NCPBottomNavigation(
allScreens = NCPScreen.entries.filter { !it.hidden },
currentScreen = NCPScreen.Passwords,
onScreenSelected = {}
)
}
}

View file

@ -0,0 +1,828 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SheetState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.data.folder.DeletedFolder
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.folder.NewFolder
import com.hegocre.nextcloudpasswords.data.folder.UpdatedFolder
import com.hegocre.nextcloudpasswords.data.password.DeletedPassword
import com.hegocre.nextcloudpasswords.data.password.NewPassword
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.data.password.UpdatedPassword
import com.hegocre.nextcloudpasswords.data.serversettings.ServerSettings
import com.hegocre.nextcloudpasswords.ui.NCPScreen
import com.hegocre.nextcloudpasswords.ui.viewmodels.PasswordsViewModel
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.hegocre.nextcloudpasswords.utils.decryptFolders
import com.hegocre.nextcloudpasswords.utils.decryptPasswords
import com.hegocre.nextcloudpasswords.utils.encryptValue
import com.hegocre.nextcloudpasswords.utils.sha1Hash
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
@ExperimentalMaterial3Api
@Composable
fun NCPNavHost(
navController: NavHostController,
passwordsViewModel: PasswordsViewModel,
modifier: Modifier = Modifier,
searchQuery: String = "",
isAutofillRequest: Boolean,
openPasswordDetails: (Password, List<String>) -> Unit,
replyAutofill: ((String, String, String) -> Unit)? = null,
modalSheetState: SheetState? = null,
searchVisibility: Boolean? = null,
closeSearch: (() -> Unit)? = null,
) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val passwords by passwordsViewModel.passwords.observeAsState()
val folders by passwordsViewModel.folders.observeAsState()
val keychain by passwordsViewModel.csEv1Keychain.observeAsState()
val isRefreshing by passwordsViewModel.isRefreshing.collectAsState()
val isUpdating by passwordsViewModel.isUpdating.collectAsState()
val serverSettings by passwordsViewModel.serverSettings.observeAsState(initial = ServerSettings())
val sessionOpen by passwordsViewModel.sessionOpen.collectAsState()
val passwordsDecryptionState by produceState(
initialValue = ListDecryptionState(isLoading = true),
key1 = passwords, key2 = keychain
) {
value = ListDecryptionState(decryptedList = passwords?.let { passwordList ->
passwordList.decryptPasswords(keychain).sortedBy { it.label.lowercase() }
} ?: emptyList())
}
val foldersDecryptionState by produceState(
initialValue = ListDecryptionState(isLoading = true),
key1 = folders, key2 = keychain
) {
value = ListDecryptionState(decryptedList = folders?.let { folderList ->
folderList.decryptFolders(keychain).sortedBy { it.label.lowercase() }
} ?: emptyList())
}
val baseFolderName = stringResource(R.string.top_level_folder_name)
val onPasswordClick: (Password) -> Unit = { password ->
if (isAutofillRequest && replyAutofill != null) {
replyAutofill(password.label, password.username, password.password)
} else {
val folderPath = mutableListOf<String>()
var nextFolderUuid = password.folder
while (nextFolderUuid != FoldersApi.DEFAULT_FOLDER_UUID) {
val nextFolder =
foldersDecryptionState.decryptedList?.find { it.id == nextFolderUuid }
nextFolder?.label?.let {
folderPath.add(it)
}
nextFolderUuid = nextFolder?.parent ?: FoldersApi.DEFAULT_FOLDER_UUID
}
folderPath.add(baseFolderName)
openPasswordDetails(password, folderPath.toList())
}
}
val onFolderClick: (Folder) -> Unit = { folder ->
navController.navigate("${NCPScreen.Folders.name}/${folder.id}")
}
val userStartDestination by PreferencesManager.getInstance(context).getStartScreen()
.collectAsState(NCPScreen.Passwords.name, context = Dispatchers.IO)
val startDestination = remember(isAutofillRequest, userStartDestination) {
if (isAutofillRequest) NCPScreen.Passwords.name else userStartDestination
}
val searchByUsername by PreferencesManager.getInstance(context).getSearchByUsername()
.collectAsState(true, context = Dispatchers.IO)
val strictUrlMatching by PreferencesManager.getInstance(context).getUseStrictUrlMatching()
.collectAsState(true, context = Dispatchers.IO)
val filteredPasswordList = remember(passwordsDecryptionState.decryptedList, searchQuery) {
passwordsDecryptionState.decryptedList?.filter {
!it.hidden && !it.trashed && (it.matches(searchQuery, strictUrlMatching)
|| (searchByUsername && it.username.contains(searchQuery)))
}
}
val filteredFolderList = remember(foldersDecryptionState.decryptedList, searchQuery) {
foldersDecryptionState.decryptedList?.filter {
!it.hidden && !it.trashed && it.label.lowercase().contains(searchQuery.lowercase())
}
}
NavHost(
navController = navController,
startDestination = startDestination,
modifier = modifier,
enterTransition = { fadeIn(animationSpec = tween(300)) },
exitTransition = { fadeOut(animationSpec = tween(300)) },
) {
composable(NCPScreen.Passwords.name) {
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
when {
passwordsDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
passwordsDecryptionState.decryptedList != null -> {
PullToRefreshBody(
isRefreshing = isRefreshing,
onRefresh = { passwordsViewModel.sync() },
) {
if (filteredPasswordList?.isEmpty() == true) {
if (searchQuery.isBlank()) NoContentText() else NoResultsText()
} else {
MixedLazyColumn(
passwords = filteredPasswordList,
onPasswordClick = onPasswordClick,
onPasswordLongClick = {
if (sessionOpen && !isAutofillRequest && it.editable)
navController.navigate("${NCPScreen.PasswordEdit.name}/${it.id}")
},
getPainterForUrl = { passwordsViewModel.getPainterForUrl(url = it) }
)
}
}
}
}
}
}
composable(NCPScreen.Favorites.name) {
val filteredFavoritePasswords = remember(filteredPasswordList) {
filteredPasswordList?.filter { it.favorite }
}
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
when {
passwordsDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
passwordsDecryptionState.decryptedList != null -> {
PullToRefreshBody(
isRefreshing = isRefreshing,
onRefresh = { passwordsViewModel.sync() },
) {
if (filteredFavoritePasswords?.isEmpty() == true) {
if (searchQuery.isBlank())
NoContentText()
else
NoResultsText { navController.navigate(NCPScreen.Passwords.name) }
} else {
MixedLazyColumn(
passwords = filteredFavoritePasswords,
onPasswordClick = onPasswordClick,
onPasswordLongClick = {
if (sessionOpen && !isAutofillRequest && it.editable)
navController.navigate("${NCPScreen.PasswordEdit.name}/${it.id}")
},
getPainterForUrl = { passwordsViewModel.getPainterForUrl(url = it) }
)
}
}
}
}
}
}
composable(NCPScreen.Folders.name) {
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
val filteredPasswordsParentFolder = remember(filteredPasswordList) {
filteredPasswordList?.filter {
it.folder == FoldersApi.DEFAULT_FOLDER_UUID
}
}
val filteredFoldersParentFolder = remember(filteredFolderList) {
filteredFolderList?.filter {
it.parent == FoldersApi.DEFAULT_FOLDER_UUID
}
}
when {
foldersDecryptionState.isLoading || passwordsDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
foldersDecryptionState.decryptedList != null
&& passwordsDecryptionState.decryptedList != null -> {
LaunchedEffect(Unit) {
passwordsViewModel.setVisibleFolder(null)
}
PullToRefreshBody(
isRefreshing = isRefreshing,
onRefresh = { passwordsViewModel.sync() },
) {
if (filteredFoldersParentFolder?.isEmpty() == true
&& filteredPasswordsParentFolder?.isEmpty() == true
) {
if (searchQuery.isBlank())
NoContentText()
else
NoResultsText { navController.navigate(NCPScreen.Passwords.name) }
} else {
MixedLazyColumn(
passwords = filteredPasswordsParentFolder,
folders = filteredFoldersParentFolder,
onPasswordClick = onPasswordClick,
onPasswordLongClick = {
if (sessionOpen && !isAutofillRequest && it.editable)
navController.navigate("${NCPScreen.PasswordEdit.name}/${it.id}")
},
onFolderClick = onFolderClick,
onFolderLongClick = {
if (sessionOpen && !isAutofillRequest)
navController.navigate("${NCPScreen.FolderEdit.name}/${it.id}")
},
getPainterForUrl = { passwordsViewModel.getPainterForUrl(url = it) }
)
}
}
}
}
}
}
composable(
route = "${NCPScreen.Folders.name}/{folder_uuid}",
arguments = listOf(
navArgument("folder_uuid") {
type = NavType.StringType
}
)
) { entry ->
val folderUuid =
entry.arguments?.getString("folder_uuid") ?: FoldersApi.DEFAULT_FOLDER_UUID
val filteredPasswordsSelectedFolder = remember(filteredPasswordList) {
filteredPasswordList?.filter {
it.folder == folderUuid
}
}
val filteredFoldersSelectedFolder = remember(filteredFolderList) {
filteredFolderList?.filter {
it.parent == folderUuid
}
}
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
when {
passwordsDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
passwordsDecryptionState.decryptedList != null -> {
DisposableEffect(folderUuid) {
if (foldersDecryptionState.decryptedList?.isEmpty() == false) {
passwordsViewModel.setVisibleFolder(foldersDecryptionState.decryptedList
?.firstOrNull { it.id == folderUuid })
}
onDispose {
if (passwordsViewModel.visibleFolder.value?.id == folderUuid) {
passwordsViewModel.setVisibleFolder(null)
}
}
}
PullToRefreshBody(
isRefreshing = isRefreshing,
onRefresh = { passwordsViewModel.sync() },
) {
if (filteredFoldersSelectedFolder?.isEmpty() == true
&& filteredPasswordsSelectedFolder?.isEmpty() == true
) {
if (searchQuery.isBlank())
NoContentText()
else
NoResultsText { navController.navigate(NCPScreen.Passwords.name) }
} else {
MixedLazyColumn(
passwords = filteredPasswordsSelectedFolder,
folders = filteredFoldersSelectedFolder,
onPasswordClick = onPasswordClick,
onPasswordLongClick = {
if (sessionOpen && !isAutofillRequest && it.editable)
navController.navigate("${NCPScreen.PasswordEdit.name}/${it.id}")
},
onFolderClick = onFolderClick,
onFolderLongClick = {
if (sessionOpen && !isAutofillRequest)
navController.navigate("${NCPScreen.FolderEdit.name}/${it.id}")
},
getPainterForUrl = { passwordsViewModel.getPainterForUrl(url = it) }
)
}
}
}
}
}
}
composable(
route = "${NCPScreen.PasswordEdit.name}/{password_uuid}",
arguments = listOf(
navArgument("password_uuid") {
type = NavType.StringType
}
)
) { entry ->
BackHandler(enabled = isUpdating) {
// Block back gesture when updating to avoid data loss
return@BackHandler
}
val passwordUuid = entry.arguments?.getString("password_uuid")
val selectedPassword = remember(passwordsDecryptionState.decryptedList, passwordUuid) {
if (passwordUuid == "none") {
null
} else {
passwordsDecryptionState.decryptedList?.firstOrNull {
it.id == passwordUuid
}
}
}
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
when {
passwordsDecryptionState.isLoading || foldersDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
passwordsDecryptionState.decryptedList != null && foldersDecryptionState.decryptedList != null -> {
val editablePasswordState =
rememberEditablePasswordState(selectedPassword).apply {
if (selectedPassword == null) {
folder = passwordsViewModel.visibleFolder.value?.id ?: folder
}
}
EditablePasswordView(
editablePasswordState = editablePasswordState,
folders = foldersDecryptionState.decryptedList ?: listOf(),
onSavePassword = {
val currentKeychain = keychain
val customFields =
Json.encodeToString(editablePasswordState.customFields.toList())
if (selectedPassword == null) {
// New password
val newPassword =
if (currentKeychain != null && serverSettings.encryptionCse != 0) {
NewPassword(
password = editablePasswordState.password.encryptValue(
currentKeychain.current,
currentKeychain
),
label = editablePasswordState.label.encryptValue(
currentKeychain.current,
currentKeychain
),
username = editablePasswordState.username.encryptValue(
currentKeychain.current,
currentKeychain
),
url = editablePasswordState.url.encryptValue(
currentKeychain.current,
currentKeychain
),
notes = editablePasswordState.notes.encryptValue(
currentKeychain.current,
currentKeychain
),
customFields = customFields.encryptValue(
currentKeychain.current,
currentKeychain
),
hash = editablePasswordState.password.sha1Hash()
.take(serverSettings.passwordSecurityHash),
cseType = "CSEv1r1",
cseKey = currentKeychain.current,
folder = editablePasswordState.folder,
edited = 0,
hidden = false,
favorite = editablePasswordState.favorite
)
} else {
NewPassword(
password = editablePasswordState.password,
label = editablePasswordState.label,
username = editablePasswordState.username,
url = editablePasswordState.url,
notes = editablePasswordState.notes,
customFields = customFields,
hash = editablePasswordState.password.sha1Hash()
.take(serverSettings.passwordSecurityHash),
cseType = "none",
cseKey = "",
folder = editablePasswordState.folder,
edited = 0,
hidden = false,
favorite = editablePasswordState.favorite
)
}
coroutineScope.launch {
if (passwordsViewModel.createPassword(newPassword)
.await()
) {
if (editablePasswordState.replyAutofill && replyAutofill != null) {
replyAutofill(
editablePasswordState.label,
editablePasswordState.username,
editablePasswordState.password
)
} else {
navController.navigateUp()
}
} else {
Toast.makeText(
context,
R.string.error_password_saving_failed,
Toast.LENGTH_LONG
).show()
}
}
} else {
val updatedPassword =
if (currentKeychain != null && selectedPassword.cseType == "CSEv1r1") {
UpdatedPassword(
id = selectedPassword.id,
revision = selectedPassword.revision,
password = editablePasswordState.password.encryptValue(
currentKeychain.current,
currentKeychain
),
label = editablePasswordState.label.encryptValue(
currentKeychain.current,
currentKeychain
),
username = editablePasswordState.username.encryptValue(
currentKeychain.current,
currentKeychain
),
url = editablePasswordState.url.encryptValue(
currentKeychain.current,
currentKeychain
),
notes = editablePasswordState.notes.encryptValue(
currentKeychain.current,
currentKeychain
),
customFields = customFields.encryptValue(
currentKeychain.current,
currentKeychain
),
hash = editablePasswordState.password.sha1Hash()
.take(serverSettings.passwordSecurityHash),
cseType = "CSEv1r1",
cseKey = currentKeychain.current,
folder = editablePasswordState.folder,
edited = if (editablePasswordState.password == selectedPassword.password) selectedPassword.edited else 0,
hidden = selectedPassword.hidden,
favorite = editablePasswordState.favorite
)
} else {
UpdatedPassword(
id = selectedPassword.id,
revision = selectedPassword.revision,
password = editablePasswordState.password,
label = editablePasswordState.label,
username = editablePasswordState.username,
url = editablePasswordState.url,
notes = editablePasswordState.notes,
customFields = customFields,
hash = editablePasswordState.password.sha1Hash()
.take(serverSettings.passwordSecurityHash),
cseType = "none",
cseKey = "",
folder = editablePasswordState.folder,
edited = if (editablePasswordState.password == selectedPassword.password) selectedPassword.edited else 0,
hidden = selectedPassword.hidden,
favorite = editablePasswordState.favorite
)
}
coroutineScope.launch {
if (passwordsViewModel.updatePassword(updatedPassword)
.await()
) {
if (editablePasswordState.replyAutofill && replyAutofill != null) {
replyAutofill(
editablePasswordState.label,
editablePasswordState.username,
editablePasswordState.password
)
} else {
navController.navigateUp()
}
} else {
Toast.makeText(
context,
R.string.error_password_saving_failed,
Toast.LENGTH_LONG
).show()
}
}
}
},
onDeletePassword = if (selectedPassword == null) null
else {
{
val deletedPassword = DeletedPassword(
id = selectedPassword.id,
revision = selectedPassword.revision
)
coroutineScope.launch {
if (passwordsViewModel.deletePassword(deletedPassword)
.await()
) {
navController.navigateUp()
} else {
Toast.makeText(
context,
R.string.error_password_deleting_failed,
Toast.LENGTH_LONG
).show()
}
}
}
},
isUpdating = isUpdating,
isAutofillRequest = isAutofillRequest,
onGeneratePassword = passwordsViewModel::generatePassword
)
}
}
}
}
composable(
route = "${NCPScreen.FolderEdit.name}/{folder_uuid}",
arguments = listOf(
navArgument("folder_uuid") {
type = NavType.StringType
}
)
) { entry ->
BackHandler(enabled = isUpdating) {
// Block back gesture when updating to avoid data loss
return@BackHandler
}
val folderUuid = entry.arguments?.getString("folder_uuid")
val selectedFolder = remember(foldersDecryptionState.decryptedList, folderUuid) {
if (folderUuid == "none") {
null
} else {
foldersDecryptionState.decryptedList?.firstOrNull {
it.id == folderUuid
}
}
}
NCPNavHostComposable(
modalSheetState = modalSheetState,
searchVisibility = searchVisibility,
closeSearch = closeSearch
) {
when {
foldersDecryptionState.isLoading -> {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
foldersDecryptionState.decryptedList != null -> {
val editableFolderState =
rememberEditableFolderState(selectedFolder).apply {
if (selectedFolder == null) {
parent = passwordsViewModel.visibleFolder.value?.id ?: parent
}
}
EditableFolderView(
editableFolderState = editableFolderState,
folders = foldersDecryptionState.decryptedList ?: listOf(),
onSaveFolder = {
if (selectedFolder == null) {
val newFolder = keychain?.let {
NewFolder(
label = editableFolderState.label.encryptValue(
it.current,
it
),
cseType = "CSEv1r1",
cseKey = it.current,
parent = editableFolderState.parent,
edited = 0,
hidden = false,
favorite = editableFolderState.favorite
)
} ?: NewFolder(
label = editableFolderState.label,
cseType = "none",
cseKey = "",
parent = editableFolderState.parent,
edited = 0,
hidden = false,
favorite = editableFolderState.favorite
)
coroutineScope.launch {
if (passwordsViewModel.createFolder(newFolder)
.await()
) {
navController.navigateUp()
} else {
Toast.makeText(
context,
R.string.error_folder_saving_failed,
Toast.LENGTH_LONG
).show()
}
}
} else {
val updatedFolder = keychain?.let {
UpdatedFolder(
id = selectedFolder.id,
revision = selectedFolder.revision,
label = editableFolderState.label.encryptValue(
it.current,
it
),
cseType = "CSEv1r1",
cseKey = it.current,
parent = editableFolderState.parent,
edited = if (editableFolderState.label == selectedFolder.label) selectedFolder.edited else 0,
hidden = selectedFolder.hidden,
favorite = editableFolderState.favorite
)
} ?: UpdatedFolder(
id = selectedFolder.id,
revision = selectedFolder.revision,
label = editableFolderState.label,
cseType = "none",
cseKey = "",
parent = editableFolderState.parent,
edited = if (editableFolderState.label == selectedFolder.label) selectedFolder.edited else 0,
hidden = selectedFolder.hidden,
favorite = editableFolderState.favorite
)
coroutineScope.launch {
if (passwordsViewModel.updateFolder(updatedFolder)
.await()
) {
navController.navigateUp()
} else {
Toast.makeText(
context,
R.string.error_folder_saving_failed,
Toast.LENGTH_LONG
).show()
}
}
}
},
onDeleteFolder = if (selectedFolder == null) null
else {
{
val deletedFolder = DeletedFolder(
id = selectedFolder.id,
revision = selectedFolder.revision
)
coroutineScope.launch {
if (passwordsViewModel.deleteFolder(deletedFolder)
.await()
) {
navController.navigateUp()
} else {
Toast.makeText(
context,
R.string.error_folder_deleting_failed,
Toast.LENGTH_LONG
).show()
}
}
}
},
isUpdating = isUpdating,
)
}
}
}
}
}
}
@Composable
fun NoContentText() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp), contentAlignment = Alignment.Center
) {
Text(text = stringResource(id = R.string.empty_list_no_content_here))
}
}
@Composable
fun NoResultsText(
onButtonPress: (() -> Unit)? = null
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp), contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = stringResource(id = R.string.empty_list_no_results_found))
if (onButtonPress != null) {
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = onButtonPress) {
Text(text = stringResource(id = R.string.action_search_everywhere))
}
}
}
}
}
@ExperimentalMaterial3Api
@Composable
fun NCPNavHostComposable(
modifier: Modifier = Modifier,
modalSheetState: SheetState? = null,
searchVisibility: Boolean? = null,
closeSearch: (() -> Unit)? = null,
content: @Composable () -> Unit = { }
) {
BackHandler(enabled = searchVisibility == true) {
closeSearch?.invoke()
}
val scope = rememberCoroutineScope()
BackHandler(enabled = modalSheetState?.isVisible ?: false) {
scope.launch {
modalSheetState?.hide()
}
}
Box(modifier = modifier) {
content()
}
}

View file

@ -0,0 +1,412 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.view.autofill.AutofillManager
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.NCPScreen
import com.hegocre.nextcloudpasswords.ui.theme.NCPTheme
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.hegocre.nextcloudpasswords.utils.showBiometricPrompt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.core.net.toUri
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NCPSettingsScreen(
onNavigationUp: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val preferencesManager = remember {
PreferencesManager.getInstance(context)
}
NextcloudPasswordsTheme {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(stringResource(R.string.screen_settings))
},
navigationIcon = {
IconButton(onClick = onNavigationUp) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.navigation_back)
)
}
},
windowInsets = WindowInsets.statusBars
)
},
bottomBar = {
Spacer(
modifier = Modifier
.navigationBarsPadding()
.fillMaxWidth()
)
}
)
{ innerPadding ->
Column(
Modifier
.padding(innerPadding)
.verticalScroll(rememberScrollState())
) {
PreferencesCategory(title = { Text(stringResource(R.string.preferences_category_general)) }) {
val selectedScreen by preferencesManager.getStartScreen()
.collectAsState(
initial = NCPScreen.Passwords.name,
context = Dispatchers.IO
)
val startViews = mapOf(
NCPScreen.Passwords.name to stringResource(NCPScreen.Passwords.title),
NCPScreen.Favorites.name to stringResource(NCPScreen.Favorites.title),
NCPScreen.Folders.name to stringResource(NCPScreen.Folders.title)
)
ListPreference(
items = startViews,
onItemSelected = {
scope.launch {
preferencesManager.setStartScreen(it)
}
},
title = { Text(text = stringResource(id = R.string.start_view_preference_title)) },
selectedItem = selectedScreen
)
val showIcons by preferencesManager.getShowIcons()
.collectAsState(initial = false, context = Dispatchers.IO)
SwitchPreference(
checked = showIcons,
onCheckedChange = { show ->
scope.launch(Dispatchers.IO) {
preferencesManager.setShowIcons(show)
}
},
title = { Text(stringResource(R.string.show_icons_preference_title)) },
subtitle = { Text(stringResource(R.string.show_icons_preference_subtitle)) }
)
}
PreferencesCategory(title = { Text(stringResource(R.string.preferences_category_search)) }) {
val useStringUrlMatching by preferencesManager.getUseStrictUrlMatching()
.collectAsState(initial = true, context = Dispatchers.IO)
SwitchPreference(
checked = useStringUrlMatching,
onCheckedChange = { useStrict ->
scope.launch(Dispatchers.IO) {
preferencesManager.setUseStrictUrlMatching(useStrict)
}
},
title = { Text(stringResource(R.string.use_strict_domain_matching_preference_title)) },
subtitle = { Text(stringResource(R.string.use_strict_domain_matching_preference_subtitle)) }
)
val searchByUsername by preferencesManager.getSearchByUsername()
.collectAsState(initial = true, context = Dispatchers.IO)
SwitchPreference(
checked = searchByUsername,
onCheckedChange = { search ->
scope.launch(Dispatchers.IO) {
preferencesManager.setSearchByUsername(search)
}
},
title = { Text(stringResource(R.string.search_by_username_preference_title)) },
subtitle = { Text(stringResource(R.string.search_by_username_preference_subtitle)) }
)
}
PreferencesCategory(title = { Text(text = stringResource(id = R.string.preferences_category_appearance)) }) {
val appTheme by preferencesManager.getAppTheme()
.collectAsState(initial = NCPTheme.SYSTEM)
val useNextcloudInstanceColor by preferencesManager.getUseInstanceColor()
.collectAsState(initial = false)
val useSystemDynamicColor by preferencesManager.getUseSystemDynamicColor()
.collectAsState(initial = false)
val themes = mapOf(
NCPTheme.SYSTEM to stringResource(id = R.string.app_theme_system),
NCPTheme.LIGHT to stringResource(id = R.string.app_theme_light),
NCPTheme.DARK to stringResource(id = R.string.app_theme_dark),
NCPTheme.AMOLED to stringResource(id = R.string.app_theme_black)
)
ListPreference(
items = themes,
selectedItem = appTheme,
onItemSelected = { theme ->
scope.launch(Dispatchers.IO) {
preferencesManager.setAppTheme(theme)
}
},
title = { Text(text = stringResource(id = R.string.app_theme_preference_title)) })
SwitchPreference(
checked = useNextcloudInstanceColor,
onCheckedChange = { use ->
scope.launch(Dispatchers.IO) {
preferencesManager.setUseInstanceColor(use)
}
},
title = { Text(text = stringResource(id = R.string.use_nextcloud_color_preference_title)) },
subtitle = { Text(text = stringResource(id = R.string.use_nextcloud_color_preference_subtitle)) },
enabled = !useSystemDynamicColor
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
SwitchPreference(
checked = useSystemDynamicColor,
onCheckedChange = { use ->
scope.launch(Dispatchers.IO) {
preferencesManager.setUseSystemDynamicColor(use)
}
},
title = { Text(text = stringResource(id = R.string.use_dynamic_colors_preference_title)) },
subtitle = { Text(text = stringResource(id = R.string.use_dynamic_colors_preference_subtitle)) },
enabled = !useNextcloudInstanceColor
)
}
}
PreferencesCategory(title = { Text(text = stringResource(id = R.string.preferences_category_security)) }) {
val hasAppLock by preferencesManager.getHasAppLock()
.collectAsState(false)
val hasBiometricAppLock by preferencesManager
.getHasBiometricAppLock().collectAsState(false)
val canUseBiometrics = remember {
BiometricManager.from(context)
.canAuthenticate(BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
}
var showCreatePasscodeDialog by rememberSaveable {
mutableStateOf(false)
}
var showConfirmPasscodeDialog by rememberSaveable {
mutableStateOf(false)
}
var showDeletePasscodeDialog by rememberSaveable {
mutableStateOf(false)
}
var firstPasscode by rememberSaveable {
mutableStateOf("")
}
var isEnablingBiometric by rememberSaveable {
mutableStateOf(false)
}
SwitchPreference(
checked = hasAppLock,
onCheckedChange = { enabled ->
if (enabled) {
showCreatePasscodeDialog = true
} else {
showDeletePasscodeDialog = true
}
},
title = { Text(text = stringResource(id = R.string.app_lock_preference_title)) },
subtitle = { Text(text = stringResource(id = R.string.app_lock_preference_subtitle)) }
)
if (canUseBiometrics) {
SwitchPreference(
checked = hasBiometricAppLock,
onCheckedChange = { enabled ->
if (enabled && !hasAppLock) {
showCreatePasscodeDialog = true
isEnablingBiometric = true
} else {
showBiometricPrompt(
context = context,
title = context.getString(R.string.biometric_prompt_title),
description = context.getString(R.string.biometric_prompt_description),
onBiometricUnlock = {
scope.launch {
preferencesManager.setHasBiometricAppLock(enabled)
}
}
)
}
},
title = { Text(text = stringResource(id = R.string.biometric_unlock_preference_title)) },
subtitle = { Text(text = stringResource(id = R.string.biometric_unlock_preference_subtitle)) },
)
}
if (showCreatePasscodeDialog) {
InputPasscodeDialog(
title = stringResource(id = R.string.app_lock_input_passcode),
onInputPasscode = {
firstPasscode = it
showCreatePasscodeDialog = false
showConfirmPasscodeDialog = true
},
onDismissRequest = {
showCreatePasscodeDialog = false
isEnablingBiometric = false
}
)
}
if (showConfirmPasscodeDialog) {
InputPasscodeDialog(
title = stringResource(id = R.string.app_lock_confirm_passcode),
onInputPasscode = { secondPasscode ->
if (firstPasscode != secondPasscode) {
Toast.makeText(
context,
R.string.error_passcodes_dont_match,
Toast.LENGTH_LONG
).show()
} else {
scope.launch {
with(preferencesManager) {
setAppLockPasscode(secondPasscode)
setHasAppLock(true)
}
}
}
showConfirmPasscodeDialog = false
if (isEnablingBiometric) {
isEnablingBiometric = false
showBiometricPrompt(
context = context,
title = context.getString(R.string.biometric_prompt_title),
description = context.getString(R.string.biometric_prompt_description),
onBiometricUnlock = {
scope.launch {
preferencesManager.setHasBiometricAppLock(true)
}
}
)
}
},
onDismissRequest = {
showConfirmPasscodeDialog = false
isEnablingBiometric = false
firstPasscode = ""
}
)
}
if (showDeletePasscodeDialog) {
InputPasscodeDialog(
title = stringResource(id = R.string.app_lock_input_passcode),
onInputPasscode = { passcode ->
scope.launch {
with(preferencesManager) {
val currentPasscode = getAppLockPasscode()
if (currentPasscode == passcode) {
setHasAppLock(false)
setAppLockPasscode(null)
setHasBiometricAppLock(false)
} else {
Toast.makeText(
context,
R.string.error_app_lock_incorrect_code,
Toast.LENGTH_LONG
).show()
}
}
}
showDeletePasscodeDialog = false
},
onDismissRequest = {
showDeletePasscodeDialog = false
}
)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val autofillManager = context.getSystemService(AutofillManager::class.java)
var autofillEnabled by remember { mutableStateOf(autofillManager.hasEnabledAutofillServices()) }
val launchAutofillRequest = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
autofillEnabled = true
}
}
PreferencesCategory(title = { Text(text = stringResource(R.string.preferences_category_autofill_service)) }) {
SwitchPreference(
checked = autofillEnabled,
onCheckedChange = { enable ->
if (enable) {
val intent =
Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE).apply {
data = "package:${context.packageName}".toUri()
}
launchAutofillRequest.launch(intent)
}
},
title = { Text(stringResource(R.string.autofill_preference_title)) },
subtitle = { Text(stringResource(R.string.autofill_preference_subtitle)) },
enabled = !autofillEnabled
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
var useInlineAutofill by remember { mutableStateOf(preferencesManager.getUseInlineAutofill()) }
SwitchPreference(
checked = useInlineAutofill,
onCheckedChange = { enabled ->
scope.launch(Dispatchers.IO) {
if (preferencesManager.setUseInlineAutofill(enabled)) {
useInlineAutofill = enabled
}
}
},
title = { Text(text = stringResource(id = R.string.inline_autofill_preference_title)) },
subtitle = { Text(text = stringResource(id = R.string.inline_autofill_preference_subtitle)) },
enabled = autofillEnabled
)
}
}
}
}
}
}
}

View file

@ -0,0 +1,480 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.content.Intent
import android.content.res.Configuration
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.outlined.Logout
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.outlined.AccountCircle
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.ui.theme.ContentAlpha
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import kotlinx.coroutines.job
object AppBarDefaults {
val TopAppBarElevation = 4.dp
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NCPSearchTopBar(
username: String,
serverAddress: String,
modifier: Modifier = Modifier,
title: String = stringResource(R.string.app_name),
scrollBehavior: TopAppBarScrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(
rememberTopAppBarState()
),
userAvatar: @Composable (Dp) -> Unit = { size ->
Image(
imageVector = Icons.Outlined.AccountCircle,
contentDescription = username,
modifier = Modifier.size(size)
)
},
searchQuery: String = "",
setSearchQuery: (String) -> Unit = {},
isAutofill: Boolean = false,
onLogoutClick: () -> Unit = {},
searchExpanded: Boolean = false,
onSearchClick: () -> Unit = {},
onSearchCloseClick: () -> Unit = {}
) {
Surface(
modifier = modifier,
) {
Crossfade(targetState = searchExpanded, label = "expanded") { expanded ->
if (expanded) {
SearchAppBar(
searchQuery = searchQuery,
setSearchQuery = setSearchQuery,
onBackPressed = onSearchCloseClick
)
} else {
TitleAppBar(
username = username,
serverAddress = serverAddress,
title = title,
onSearchClick = onSearchClick,
onLogoutClick = onLogoutClick,
scrollBehavior = scrollBehavior,
showMenu = !isAutofill,
userAvatar = userAvatar
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TitleAppBar(
username: String,
serverAddress: String,
title: String,
onSearchClick: () -> Unit,
onLogoutClick: () -> Unit,
scrollBehavior: TopAppBarScrollBehavior,
showMenu: Boolean,
userAvatar: @Composable (Dp) -> Unit
) {
var menuExpanded by rememberSaveable { mutableStateOf(false) }
LargeTopAppBar(
title = { Text(text = title) },
scrollBehavior = scrollBehavior,
windowInsets = WindowInsets.statusBars,
actions = {
IconButton(onClick = onSearchClick) {
Icon(
imageVector = Icons.Outlined.Search,
contentDescription = stringResource(id = R.string.action_search)
)
}
if (showMenu) {
Box {
IconButton(
onClick = { menuExpanded = true },
modifier = Modifier.padding(end = 8.dp)
) {
userAvatar(26.dp)
}
PopupAppMenu(
username = username,
serverAddress = serverAddress,
menuExpanded = menuExpanded,
userAvatar = userAvatar,
onDismissRequest = { menuExpanded = false },
onLogoutClick = onLogoutClick
)
}
}
},
)
}
@Composable
fun SearchAppBar(
searchQuery: String,
setSearchQuery: (String) -> Unit,
onBackPressed: () -> Unit
) {
val keyboardController = LocalSoftwareKeyboardController.current
val requester = remember { FocusRequester() }
Column(
Modifier.background(MaterialTheme.colorScheme.surfaceColorAtElevation(AppBarDefaults.TopAppBarElevation))
) {
Spacer(modifier = Modifier.statusBarsPadding())
Row(
modifier = Modifier.height(64.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = onBackPressed
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.navigation_back)
)
}
LaunchedEffect(key1 = Unit) {
coroutineContext.job.invokeOnCompletion {
if (it?.cause == null) {
requester.requestFocus()
}
}
}
TextField(
modifier = Modifier
.weight(1f)
.focusRequester(requester),
value = searchQuery,
onValueChange = setSearchQuery,
maxLines = 1,
singleLine = true,
placeholder = { Text(text = stringResource(R.string.action_search)) },
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
disabledContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent,
),
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(onSearch = {
keyboardController?.hide()
})
)
IconButton(
onClick = { setSearchQuery("") }
) {
Icon(
imageVector = Icons.Default.Clear,
contentDescription = stringResource(id = R.string.action_clear_search_query)
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PopupAppMenu(
username: String,
serverAddress: String,
menuExpanded: Boolean,
userAvatar: @Composable (Dp) -> Unit,
onDismissRequest: () -> Unit,
onLogoutClick: () -> Unit
) {
val context = LocalContext.current
val dismissSheet = Modifier
.pointerInput(Unit) {
detectTapGestures {
onDismissRequest()
}
}
val orientation = LocalConfiguration.current.orientation
val screenHeight = LocalConfiguration.current.screenHeightDp.dp
if (menuExpanded) {
BasicAlertDialog(
onDismissRequest = onDismissRequest,
modifier = Modifier.fillMaxWidth(),
properties = DialogProperties(
usePlatformDefaultWidth = false
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
horizontalAlignment = Alignment.CenterHorizontally
) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
Spacer(
modifier = Modifier
.height(72.dp)
.fillMaxWidth()
.then(dismissSheet)
)
}
Surface(
modifier = Modifier
.padding(horizontal = 16.dp)
.then(
if (orientation == Configuration.ORIENTATION_PORTRAIT)
Modifier.fillMaxWidth()
else
Modifier.width(screenHeight)
),
color = MaterialTheme.colorScheme.surface,
shape = MaterialTheme.shapes.large
) {
Column(
modifier = Modifier
.padding(vertical = 8.dp)
.verticalScroll(rememberScrollState()),
) {
Row(
modifier = Modifier
.padding(vertical = 12.dp)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.padding(all = 8.dp)
.padding(end = 12.dp)
) {
userAvatar(40.dp)
}
Column {
Text(
text = username,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Start
)
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = ContentAlpha.medium)
) {
Text(
text = serverAddress,
style = MaterialTheme.typography.bodyMedium,
fontSize = 14.sp
)
}
}
}
HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
DropdownMenuItem(
onClick = {
val intent =
Intent("com.hegocre.nextcloudpasswords.action.settings")
.setPackage(context.packageName)
context.startActivity(intent)
onDismissRequest()
},
text = {
Text(
text = stringResource(id = R.string.screen_settings),
modifier = Modifier.padding(end = 16.dp)
)
},
leadingIcon = {
Icon(
imageVector = Icons.Outlined.Settings,
contentDescription = stringResource(id = R.string.screen_settings),
modifier = Modifier
.padding(end = 8.dp)
.padding(start = 16.dp)
)
}
)
DropdownMenuItem(
onClick = {
val intent = Intent("com.hegocre.nextcloudpasswords.action.about")
.setPackage(context.packageName)
context.startActivity(intent)
onDismissRequest()
},
text = {
Text(
text = stringResource(id = R.string.screen_about),
modifier = Modifier.padding(end = 16.dp)
)
},
leadingIcon = {
Icon(
imageVector = Icons.Outlined.Info,
contentDescription = stringResource(id = R.string.screen_about),
modifier = Modifier
.padding(end = 8.dp)
.padding(start = 16.dp)
)
}
)
DropdownMenuItem(
onClick = {
onLogoutClick()
onDismissRequest()
},
text = {
Text(
text = stringResource(R.string.action_log_out),
modifier = Modifier.padding(end = 16.dp)
)
},
leadingIcon = {
Icon(
imageVector = Icons.AutoMirrored.Outlined.Logout,
contentDescription = stringResource(id = R.string.action_log_out),
modifier = Modifier
.padding(end = 8.dp)
.padding(start = 16.dp)
)
}
)
HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = ContentAlpha.medium)
) {
Text(
text = "${stringResource(id = R.string.app_name)} v${
stringResource(
id = R.string.version_name
)
}(${
stringResource(
id = R.string.version_code
)
})",
style = MaterialTheme.typography.labelSmall,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
)
}
}
}
Spacer(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.then(dismissSheet)
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview(name = "Top bar")
@Composable
fun TopBarPreview() {
NextcloudPasswordsTheme {
NCPSearchTopBar("", "")
}
}
@Preview
@Composable
fun SearchBarPreview() {
NextcloudPasswordsTheme {
SearchAppBar(
searchQuery = "Query",
setSearchQuery = {},
onBackPressed = {}
)
}
}

View file

@ -0,0 +1,683 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Casino
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.FoldersApi
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.password.CustomField
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.ui.theme.ContentAlpha
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.ui.theme.favoriteColor
import com.hegocre.nextcloudpasswords.utils.isValidEmail
import com.hegocre.nextcloudpasswords.utils.isValidURL
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.android.awaitFrame
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlin.reflect.KFunction3
class EditablePasswordState(originalPassword: Password?) {
var password by mutableStateOf(originalPassword?.password ?: "")
var label by mutableStateOf(originalPassword?.label ?: "")
var username by mutableStateOf(originalPassword?.username ?: "")
var url by mutableStateOf(originalPassword?.url ?: "")
var notes by mutableStateOf(originalPassword?.notes ?: "")
var folder by mutableStateOf(originalPassword?.folder ?: FoldersApi.DEFAULT_FOLDER_UUID)
var customFields =
if (originalPassword?.customFields?.isBlank() == true) mutableStateListOf() else
Json.decodeFromString<List<CustomField>>(originalPassword?.customFields ?: "[]")
.toMutableStateList()
var favorite by mutableStateOf(originalPassword?.favorite ?: false)
var replyAutofill = false
fun isValid(): Boolean {
if (label.isBlank())
return false
if (password.isBlank())
return false
if (!url.isValidURL())
return false
for (customField in customFields) {
when (customField.type) {
CustomField.TYPE_URL -> {
if (!customField.value.isValidURL())
return false
}
CustomField.TYPE_EMAIL -> {
if (!customField.value.isValidEmail())
return false
}
}
}
return true
}
companion object {
val Saver: Saver<EditablePasswordState, *> = listSaver(
save = {
listOf(
it.password, it.label, it.username, it.url, it.notes,
it.folder, Json.encodeToString(it.customFields.toList()),
it.favorite.toString(), it.replyAutofill.toString()
)
},
restore = {
EditablePasswordState(null).apply {
password = it[0]
label = it[1]
username = it[2]
url = it[3]
notes = it[4]
folder = it[5]
customFields =
Json.decodeFromString<List<CustomField>>(it[6]).toMutableStateList()
favorite = it[7].toBooleanStrictOrNull() ?: false
replyAutofill = it[8].toBooleanStrictOrNull() ?: false
}
}
)
}
}
@Composable
fun rememberEditablePasswordState(password: Password? = null): EditablePasswordState =
rememberSaveable(password, saver = EditablePasswordState.Saver) {
EditablePasswordState(password)
}
@Composable
fun EditablePasswordView(
editablePasswordState: EditablePasswordState,
folders: List<Folder>,
isUpdating: Boolean,
isAutofillRequest: Boolean,
onGeneratePassword: KFunction3<Int, Boolean, Boolean, Deferred<String?>>?,
onSavePassword: () -> Unit,
onDeletePassword: (() -> Unit)? = null
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
val onBackPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
var showDeleteDialog by rememberSaveable {
mutableStateOf(false)
}
var showAddCustomFieldDialog by rememberSaveable {
mutableStateOf(false)
}
var showFolderDialog by rememberSaveable {
mutableStateOf(false)
}
var showFieldErrors by rememberSaveable {
mutableStateOf(false)
}
var showDiscardDialog by rememberSaveable {
mutableStateOf(false)
}
var confirmedDiscard by rememberSaveable {
mutableStateOf(false)
}
BackHandler (enabled = !confirmedDiscard) {
showDiscardDialog = true
}
if (showDiscardDialog) {
DiscardChangesDialog(
onConfirmButton = {
confirmedDiscard = true
showDiscardDialog = false
coroutineScope.launch {
awaitFrame()
onBackPressedDispatcher?.onBackPressed()
confirmedDiscard = false
}
},
onDismissRequest = {
showDiscardDialog = false
}
)
}
LazyColumn {
item(key = "top_spacer") { Spacer(modifier = Modifier.width(16.dp)) }
item(key = "favorite_button") {
val contentColor by animateColorAsState(
targetValue = if (editablePasswordState.favorite)
MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurface.copy(
alpha = 0.80f
),
label = "favoriteContentColor"
)
val containerColor by animateColorAsState(
targetValue = if (editablePasswordState.favorite)
MaterialTheme.colorScheme.favoriteColor.copy(alpha = 0.3f) else MaterialTheme.colorScheme.onSurface.copy(
alpha = 0.12f
),
label = "favoriteContentColor"
)
Button(
onClick = { editablePasswordState.favorite = !editablePasswordState.favorite },
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
colors = ButtonDefaults.filledTonalButtonColors(
contentColor = contentColor,
containerColor = containerColor
),
) {
Icon(
imageVector = Icons.Default.Star,
contentDescription = stringResource(id = R.string.password_attr_favorite)
)
Text(
text = stringResource(id = R.string.password_attr_favorite),
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
item(key = "password_label") {
OutlinedTextField(
value = editablePasswordState.label,
onValueChange = { newText -> editablePasswordState.label = newText },
label = { Text(text = stringResource(id = R.string.password_folder_attr_label)) },
singleLine = true,
maxLines = 1,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
isError = showFieldErrors && editablePasswordState.label.isBlank(),
supportingText = if (showFieldErrors && editablePasswordState.label.isBlank()) {
{
Text(text = stringResource(id = R.string.error_field_cannot_be_empty))
}
} else null
)
}
item(key = "password_username") {
OutlinedTextField(
value = editablePasswordState.username,
onValueChange = { newText -> editablePasswordState.username = newText },
label = { Text(text = stringResource(id = R.string.password_attr_username)) },
singleLine = true,
maxLines = 1,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp)
)
}
item(key = "password_password") {
var showPassword by rememberSaveable {
mutableStateOf(false)
}
var showGenerateDialog by remember {
mutableStateOf(false)
}
var isGenerating by rememberSaveable {
mutableStateOf(false)
}
OutlinedTextField(
value = editablePasswordState.password,
onValueChange = { newText -> editablePasswordState.password = newText },
textStyle = LocalTextStyle.current.copy(fontFamily = FontFamily(Font(R.font.dejavu_sans_mono))),
label = { Text(text = stringResource(id = R.string.password_attr_password)) },
singleLine = true,
maxLines = 1,
trailingIcon = {
Row(verticalAlignment = Alignment.CenterVertically) {
if (isGenerating) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.onSurfaceVariant,
strokeWidth = 2.dp,
modifier = Modifier.size(20.dp)
)
}
IconButton(onClick = { showPassword = !showPassword }) {
Icon(
imageVector = if (showPassword)
Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = stringResource(R.string.text_input_show_password_toggle)
)
}
if (onGeneratePassword != null) {
IconButton(onClick = {
showGenerateDialog = true
}) {
Icon(
imageVector = Icons.Default.Casino,
contentDescription = stringResource(id = R.string.action_generate_password)
)
}
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Password),
visualTransformation = if (showPassword)
VisualTransformation.None else PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
isError = showFieldErrors && editablePasswordState.password.isBlank(),
supportingText = if (showFieldErrors && editablePasswordState.password.isBlank()) {
{
Text(text = stringResource(id = R.string.error_field_cannot_be_empty))
}
} else null
)
if (showGenerateDialog) {
PasswordGenerationDialog(
onGenerate = { strength, includeDigits, includeSymbols ->
if (onGeneratePassword != null) {
coroutineScope.launch {
isGenerating = true
val generatedPassword = onGeneratePassword(
strength, includeDigits, includeSymbols
).await()
if (generatedPassword == null) {
Toast.makeText(
context,
R.string.error_could_not_generate_password,
Toast.LENGTH_LONG
).show()
} else {
editablePasswordState.password = generatedPassword
}
isGenerating = false
}
showGenerateDialog = false
}
},
onDismissRequest = {
showGenerateDialog = false
}
)
}
}
item(key = "password_url") {
OutlinedTextField(
value = editablePasswordState.url,
onValueChange = { newText -> editablePasswordState.url = newText },
label = { Text(text = stringResource(id = R.string.password_attr_url)) },
singleLine = true,
maxLines = 1,
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Uri),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
isError = showFieldErrors && !editablePasswordState.url.isValidURL(),
supportingText = if (showFieldErrors && !editablePasswordState.url.isValidURL()) {
{
Text(text = stringResource(id = R.string.error_enter_valid_url))
}
} else null
)
}
item(key = "password_folder") {
OutlinedClickableTextField(
value = if (editablePasswordState.folder == FoldersApi.DEFAULT_FOLDER_UUID) {
stringResource(id = R.string.top_level_folder_name)
} else {
folders.firstOrNull { it.id == editablePasswordState.folder }?.label
?: stringResource(id = R.string.top_level_folder_name)
},
label = stringResource(id = R.string.folder),
onClick = {
showFolderDialog = true
},
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp)
)
}
itemsIndexed(
items = editablePasswordState.customFields,
key = { index, field -> "${index}_password_custom_${field.label}" }) { index, customField ->
var showValue by rememberSaveable {
mutableStateOf(customField.type != CustomField.TYPE_SECRET)
}
OutlinedTextField(
value = customField.value,
onValueChange = { newText ->
val newElement = editablePasswordState.customFields[index].copy(value = newText)
editablePasswordState.customFields.removeAt(index)
editablePasswordState.customFields.add(index, newElement)
},
textStyle = if (customField.type == CustomField.TYPE_SECRET)
LocalTextStyle.current.copy(fontFamily = FontFamily(Font(R.font.dejavu_sans_mono)))
else
LocalTextStyle.current,
label = { Text(text = customField.label) },
singleLine = true,
maxLines = 1,
trailingIcon = {
Row {
if (customField.type == CustomField.TYPE_SECRET) {
IconButton(onClick = { showValue = !showValue }) {
Icon(
imageVector = if (showValue)
Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = stringResource(R.string.text_input_show_password_toggle)
)
}
}
IconButton(onClick = { editablePasswordState.customFields.removeAt(index) }) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = stringResource(R.string.action_delete)
)
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = when (customField.type) {
CustomField.TYPE_SECRET -> KeyboardType.Password
CustomField.TYPE_EMAIL -> KeyboardType.Email
CustomField.TYPE_URL -> KeyboardType.Uri
else -> KeyboardType.Text
}
),
visualTransformation = if (showValue)
VisualTransformation.None else PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp),
isError = when (customField.type) {
CustomField.TYPE_URL -> showFieldErrors && !customField.value.isValidURL()
CustomField.TYPE_EMAIL -> showFieldErrors && !customField.value.isValidEmail()
else -> false
},
supportingText = when (customField.type) {
CustomField.TYPE_URL -> {
if (showFieldErrors && !customField.value.isValidURL()) {
{
Text(text = stringResource(id = R.string.error_enter_valid_url))
}
} else null
}
CustomField.TYPE_EMAIL -> {
if (showFieldErrors && !customField.value.isValidEmail()) {
{
Text(text = stringResource(id = R.string.error_enter_valid_email))
}
} else null
}
else -> null
},
)
}
item(key = "password_notes") {
OutlinedTextField(
value = editablePasswordState.notes,
onValueChange = { newText -> editablePasswordState.notes = newText },
label = { Text(text = stringResource(id = R.string.password_attr_notes)) },
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 24.dp)
.padding(horizontal = 16.dp)
)
}
item(key = "custom_field_add") {
Button(
onClick = { showAddCustomFieldDialog = true },
content = {
Text(text = stringResource(id = R.string.action_add_custom_field))
},
colors = ButtonDefaults.filledTonalButtonColors(),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
.padding(horizontal = 16.dp)
)
}
item(key = "password_save") {
Button(
onClick = {
if (!editablePasswordState.isValid()) {
showFieldErrors = true
} else {
onSavePassword()
}
},
content = {
if (isUpdating) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.primary,
strokeWidth = 2.dp,
modifier = Modifier.size(16.dp)
)
} else {
Text(text = stringResource(id = R.string.action_save))
}
},
enabled = !isUpdating,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
if (isAutofillRequest) {
item(key = "password_save_autofill") {
Button(
onClick = {
if (!editablePasswordState.isValid()) {
showFieldErrors = true
} else {
editablePasswordState.replyAutofill = true
onSavePassword()
}
},
content = {
if (isUpdating) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.primary,
strokeWidth = 2.dp,
modifier = Modifier.size(16.dp)
)
} else {
Text(text = stringResource(id = R.string.action_save_autofill))
}
},
enabled = !isUpdating,
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
.padding(horizontal = 16.dp)
)
}
}
if (onDeletePassword != null) {
item(key = "password_delete") {
if (!isUpdating) {
Button(
onClick = { showDeleteDialog = true },
colors = ButtonDefaults.outlinedButtonColors(
contentColor = MaterialTheme.colorScheme.error,
disabledContentColor = MaterialTheme.colorScheme.error.copy(alpha = ContentAlpha.medium)
),
content = {
Text(text = stringResource(id = R.string.action_delete_password))
},
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
.padding(horizontal = 16.dp)
)
}
}
}
item(key = "bottom_spacer") {
Spacer(
modifier = Modifier
.windowInsetsBottomHeight(WindowInsets.ime.add(WindowInsets.navigationBars))
.padding(bottom = 16.dp)
)
}
}
if (showDeleteDialog) {
DeleteElementDialog(
onConfirmButton = {
showDeleteDialog = false
onDeletePassword?.invoke()
},
onDismissRequest = {
showDeleteDialog = false
}
)
}
if (showAddCustomFieldDialog) {
AddCustomFieldDialog(
onAddClick = { type, label ->
editablePasswordState.customFields.add(
CustomField(
type = type, label = label, value = ""
)
)
showAddCustomFieldDialog = false
},
onDismissRequest = {
showAddCustomFieldDialog = false
}
)
}
if (showFolderDialog) {
SelectFolderDialog(
folders = folders,
currentFolder = editablePasswordState.folder,
onSelectClick = { folder ->
editablePasswordState.folder = folder
showFolderDialog = false
},
onDismissRequest = {
showFolderDialog = false
}
)
}
}
@Preview
@Composable
fun PasswordEditPreview() {
NextcloudPasswordsTheme {
Surface {
EditablePasswordView(
editablePasswordState = rememberEditablePasswordState().apply {
customFields.add(
CustomField(
type = CustomField.TYPE_TEXT,
label = "Custom field 1",
value = ""
)
)
customFields.add(
CustomField(
type = CustomField.TYPE_SECRET,
label = "Custom field 2",
value = ""
)
)
},
folders = listOf(),
isUpdating = false,
isAutofillRequest = true,
onSavePassword = { },
onDeletePassword = { },
onGeneratePassword = null
)
}
}
}

View file

@ -0,0 +1,578 @@
package com.hegocre.nextcloudpasswords.ui.components
import android.content.ActivityNotFoundException
import android.webkit.URLUtil
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.twotone.AccountCircle
import androidx.compose.material.icons.twotone.AlternateEmail
import androidx.compose.material.icons.twotone.ContentCopy
import androidx.compose.material.icons.twotone.Info
import androidx.compose.material.icons.twotone.Link
import androidx.compose.material.icons.twotone.Password
import androidx.compose.material.icons.twotone.Shield
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.data.password.CustomField
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.ui.components.markdown.MDDocument
import com.hegocre.nextcloudpasswords.ui.theme.ContentAlpha
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
import com.hegocre.nextcloudpasswords.ui.theme.favoriteColor
import com.hegocre.nextcloudpasswords.utils.copyToClipboard
import kotlinx.serialization.json.Json
import org.commonmark.node.Document
import org.commonmark.parser.Parser
@Composable
fun PasswordItem(
passwordInfo: Pair<Password, List<String>>?,
modifier: Modifier = Modifier,
onEditPassword: (() -> Unit)? = null,
) {
passwordInfo?.let { pass ->
PasswordItemContent(
passwordInfo = pass,
onEditPassword = onEditPassword,
modifier = modifier
)
} ?: Text(
text = stringResource(R.string.password),
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(bottom = 8.dp)
)
}
@Composable
fun PasswordItemContent(
passwordInfo: Pair<Password, List<String>>,
onEditPassword: (() -> Unit)?,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val copiedText = stringResource(R.string.copied)
val uriHandler = LocalUriHandler.current
val password = passwordInfo.first
val folderPath = remember {
buildAnnotatedString {
appendInlineContent("folder")
append(" ")
passwordInfo.second.reversed().forEachIndexed { index, folderName ->
if (index != 0) append(" /")
append(" $folderName")
}
}
}
val customFields by remember {
derivedStateOf {
if (password.customFields.isNotBlank()) {
Json.decodeFromString<List<CustomField>>(password.customFields)
} else {
listOf()
}
}
}
Column(modifier = modifier) {
Row(
modifier = Modifier
.padding(bottom = 4.dp)
.padding(horizontal = 16.dp),
verticalAlignment = CenterVertically
) {
val favoriteInlineContent = mapOf(
Pair(
"favorite",
InlineTextContent(
placeholder = Placeholder(
width = LocalTextStyle.current.fontSize,
height = LocalTextStyle.current.fontSize,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
Icon(
imageVector = Icons.Default.Star,
contentDescription = stringResource(
id = R.string.password_attr_favorite
),
tint = MaterialTheme.colorScheme.favoriteColor
)
}
)
)
Text(
text = buildAnnotatedString {
append(password.label)
if (password.favorite) {
append(" ")
appendInlineContent("favorite")
}
},
inlineContent = favoriteInlineContent,
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier
.padding(bottom = 2.dp)
.weight(1f)
)
if (password.editable) {
onEditPassword?.let {
IconButton(onClick = it) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = stringResource(id = R.string.action_edit_password),
)
}
}
}
}
LazyColumn {
item(key = "${password.id}_path") {
val folderInlineContent = mapOf(
Pair(
"folder",
InlineTextContent(
placeholder = Placeholder(
width = LocalTextStyle.current.fontSize,
height = LocalTextStyle.current.fontSize,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
Icon(
imageVector = Icons.Default.Folder,
contentDescription = stringResource(
id = R.string.folder
),
tint = MaterialTheme.colorScheme.onSurface
.copy(alpha = ContentAlpha.medium)
)
}
)
)
Text(
text = folderPath,
inlineContent = folderInlineContent,
modifier = Modifier
.padding(bottom = 16.dp)
.padding(horizontal = 16.dp)
)
}
if (password.username.isNotBlank()) {
item(key = "${password.id}_username") {
val usernameLabel = stringResource(id = R.string.password_attr_username)
PasswordTextField(
text = password.username,
label = usernameLabel,
icon = {
Icon(
imageVector = Icons.TwoTone.AccountCircle,
contentDescription = stringResource(id = R.string.password_attr_username)
)
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(password.username)
Toast.makeText(
context,
String.format(copiedText, usernameLabel),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
}
)
}
}
item(key = "${password.id}_password") {
var showPassword by rememberSaveable { mutableStateOf(false) }
val passwordLabel = stringResource(id = R.string.password_attr_password)
PasswordTextField(
text = if (showPassword) password.password else "".repeat(password.password.length),
label = passwordLabel,
icon = {
Icon(
imageVector = Icons.TwoTone.Password,
contentDescription = stringResource(id = R.string.password_attr_password)
)
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(password.password, isSensitive = true)
Toast.makeText(
context,
String.format(copiedText, passwordLabel),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
},
onClickText = { showPassword = !showPassword },
fontFamily = FontFamily(Font(R.font.dejavu_sans_mono))
)
}
if (password.url.isNotBlank()) {
item(key = "${password.id}_url") {
val urlLabel = stringResource(id = R.string.password_attr_url)
PasswordTextField(
text = password.url,
label = urlLabel,
icon = {
Icon(
imageVector = Icons.TwoTone.Link,
contentDescription = stringResource(id = R.string.password_attr_url)
)
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(password.url)
Toast.makeText(
context,
String.format(copiedText, urlLabel),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
},
onClickText = if (URLUtil.isValidUrl(password.url)) {
{
try {
uriHandler.openUri(password.url)
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
context,
R.string.error_could_not_open_url,
Toast.LENGTH_LONG
).show()
}
}
} else if (URLUtil.isValidUrl("https://${password.url}")) {
{
try {
uriHandler.openUri("https://${password.url}")
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
context,
R.string.error_could_not_open_url,
Toast.LENGTH_LONG
).show()
}
}
} else null
)
}
}
if (customFields.isNotEmpty()) {
itemsIndexed(
items = customFields,
key = { index, field -> "${index}_${password.id}_${field.label}" }) {_, customField ->
when (customField.type) {
CustomField.TYPE_TEXT, CustomField.TYPE_EMAIL -> {
PasswordTextField(
text = customField.value,
label = customField.label,
icon = {
if (customField.type == CustomField.TYPE_TEXT) {
Icon(
imageVector = Icons.TwoTone.Info,
contentDescription = stringResource(id = R.string.custom_field_type_text)
)
} else {
Icon(
imageVector = Icons.TwoTone.AlternateEmail,
contentDescription = stringResource(id = R.string.custom_field_type_email)
)
}
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(customField.value)
Toast.makeText(
context,
String.format(copiedText, customField.label),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
}
)
}
CustomField.TYPE_SECRET -> {
var showSecret by rememberSaveable { mutableStateOf(false) }
PasswordTextField(
text = if (showSecret) customField.value else
"".repeat(customField.value.length),
label = customField.label,
icon = {
Icon(
imageVector = Icons.TwoTone.Shield,
contentDescription = stringResource(id = R.string.custom_field_type_secret)
)
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(customField.value)
Toast.makeText(
context,
String.format(copiedText, customField.label),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
},
onClickText = { showSecret = !showSecret },
fontFamily = FontFamily(Font(R.font.dejavu_sans_mono))
)
}
CustomField.TYPE_URL -> {
PasswordTextField(
text = customField.value,
label = customField.label,
icon = {
Icon(
imageVector = Icons.TwoTone.Link,
contentDescription = stringResource(id = R.string.password_attr_url)
)
},
trailingIcon = {
IconButton(onClick = {
context.copyToClipboard(customField.value)
Toast.makeText(
context,
String.format(copiedText, customField.label),
Toast.LENGTH_SHORT
).show()
}) {
Icon(
imageVector = Icons.TwoTone.ContentCopy,
contentDescription = stringResource(id = R.string.action_copy_value)
)
}
},
onClickText = if (URLUtil.isValidUrl(customField.value)) {
{
try {
uriHandler.openUri(customField.value)
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
context,
R.string.error_could_not_open_url,
Toast.LENGTH_LONG
).show()
}
}
} else if (URLUtil.isValidUrl("https://${customField.value}")) {
{
try {
uriHandler.openUri("https://${customField.value}")
} catch (ex: ActivityNotFoundException) {
Toast.makeText(
context,
R.string.error_could_not_open_url,
Toast.LENGTH_LONG
).show()
}
}
} else null
)
}
}
}
}
if (password.notes.isNotBlank()) {
item(key = "${password.id}_notes") {
val notesLabel = stringResource(id = R.string.password_attr_notes)
PasswordMarkdownField(
markdown = password.notes.replace("\n", "\n\n"),
modifier = Modifier
.padding(top = 8.dp)
.padding(horizontal = 4.dp),
label = notesLabel
)
}
}
}
}
}
@Composable
fun PasswordTextField(
text: String,
label: String,
modifier: Modifier = Modifier,
icon: @Composable () -> Unit = {},
trailingIcon: @Composable () -> Unit = {},
onClickText: (() -> Unit)? = null,
maxLines: Int? = null,
fontFamily: FontFamily? = null,
) {
ListItem(
headlineContent = {
Text(
text = text,
maxLines = maxLines ?: Int.MAX_VALUE,
overflow = TextOverflow.Ellipsis,
fontFamily = fontFamily,
modifier = Modifier
.clickable(
enabled = onClickText != null,
onClick = onClickText ?: {}
),
)
},
overlineContent = {
Text(
text = label.uppercase(),
maxLines = 1
)
},
leadingContent = icon,
trailingContent = trailingIcon,
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = modifier
)
}
@Composable
fun PasswordMarkdownField(
markdown: String,
modifier: Modifier = Modifier,
label: String = "",
) {
val root = remember(markdown) {
Parser.builder().build().parse(markdown) as Document
}
Column(modifier = modifier.padding(horizontal = 16.dp)) {
if (label.isNotBlank()) {
Text(
text = label.uppercase(),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
SelectionContainer {
Column {
MDDocument(root)
}
}
}
}
@Preview
@Composable
fun PasswordItemPreview() {
NextcloudPasswordsTheme {
Surface {
PasswordItem(
passwordInfo = Pair(
Password(
id = "",
label = "Nextcloud with a really long label",
username = "john_doe",
password = "secret_value",
url = "https://nextcloud.com/",
notes = "# This is a note\n\nIt is very important that this is read by all __means__\n\n" +
"## Subsection \n\n This is also important.\n\n" +
"## Another subsection\n\n### Even deeper\n\n Some text\nSome more text",
customFields = "",
status = 0,
statusCode = "GOOD",
hash = "",
folder = "",
revision = "",
share = null,
shared = false,
cseType = "",
cseKey = "",
sseType = "",
client = "",
hidden = false,
trashed = false,
favorite = true,
editable = true,
edited = 0,
created = 0,
updated = 0
), listOf("Second", "Home")
),
onEditPassword = {},
modifier = Modifier.padding(bottom = 16.dp)
)
}
}
}

View file

@ -0,0 +1,25 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PullToRefreshBody(
isRefreshing: Boolean,
onRefresh: () -> Unit = {},
content: @Composable () -> Unit = {}
) {
val pullRefreshState = rememberPullToRefreshState()
PullToRefreshBox(
state = pullRefreshState,
onRefresh = onRefresh,
isRefreshing = isRefreshing,
content = { content() }
//contentColor = MaterialTheme.colorScheme.primary,
//containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp)
)
}

View file

@ -0,0 +1,181 @@
package com.hegocre.nextcloudpasswords.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hegocre.nextcloudpasswords.ui.theme.NextcloudPasswordsTheme
@Composable
fun PreferencesCategory(
title: @Composable () -> Unit,
content: @Composable () -> Unit
) {
Column {
Column(
modifier = Modifier.padding(bottom = 18.dp)
) {
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colorScheme.primary,
LocalTextStyle provides MaterialTheme.typography.labelSmall.copy(fontSize = 14.sp)
) {
Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
title()
}
}
content()
}
}
}
@Composable
fun SwitchPreference(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
subtitle: (@Composable () -> Unit)? = null,
enabled: Boolean = true
) {
Row(
modifier = modifier
.fillMaxWidth()
.clickable { if (enabled) onCheckedChange(!checked) }
.padding(vertical = 12.dp, horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(
Modifier
.weight(1f)
.padding(end = 12.dp)) {
title()
CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.bodySmall.copy(fontSize = 13.sp)
) {
subtitle?.let {
it()
}
}
}
Switch(
checked = checked,
onCheckedChange = { if (enabled) onCheckedChange(it) },
enabled = enabled,
)
}
}
@Composable
fun ListPreference(
items: Map<String, String>,
selectedItem: String,
onItemSelected: (String) -> Unit,
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
) {
var dialogVisible by remember { mutableStateOf(false) }
Row(
modifier = modifier
.fillMaxWidth()
.clickable { dialogVisible = true }
.padding(vertical = 12.dp, horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(Modifier.weight(1f)) {
title()
CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.bodySmall.copy(fontSize = 13.sp)
) {
Text(items.getOrDefault(selectedItem, ""))
}
}
if (dialogVisible) {
ListPreferenceDialog(
title = title,
options = items,
selectedOption = selectedItem,
onSelectOption = {
onItemSelected(it)
dialogVisible = false
},
onDismissRequest = { dialogVisible = false }
)
}
}
}
@Preview
@Composable
fun PreferencesPreview() {
NextcloudPasswordsTheme {
Surface {
Column {
PreferencesCategory(title = { Text("General") }) {
ListPreference(
items = mapOf("passwords" to "Passwords"),
onItemSelected = {},
title = { Text(text = "Initial view") },
selectedItem = "passwords"
)
SwitchPreference(
checked = true,
onCheckedChange = {},
title = { Text(text = "Show icons") },
subtitle = { Text(text = "Show website icons") }
)
}
PreferencesCategory(title = { Text("Security") }) {
SwitchPreference(
checked = true,
onCheckedChange = {},
title = { Text(text = "App lock") },
subtitle = { Text(text = "Lock access to the application with a code") }
)
SwitchPreference(
checked = true,
onCheckedChange = {},
title = { Text(text = "Biometric unlock") },
subtitle = { Text(text = "Unlock the app with biometric credentials such as fingerprint or face") }
)
}
PreferencesCategory(title = { Text("Security") }) {
SwitchPreference(
checked = true,
onCheckedChange = {},
title = { Text(text = "Autofill") },
subtitle = { Text(text = "Enable autofill service") },
enabled = false
)
}
}
}
}
}

View file

@ -0,0 +1,306 @@
package com.hegocre.nextcloudpasswords.ui.components.markdown
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import org.commonmark.node.BlockQuote
import org.commonmark.node.BulletList
import org.commonmark.node.Code
import org.commonmark.node.Document
import org.commonmark.node.Emphasis
import org.commonmark.node.FencedCodeBlock
import org.commonmark.node.HardLineBreak
import org.commonmark.node.Heading
import org.commonmark.node.Image
import org.commonmark.node.Link
import org.commonmark.node.ListBlock
import org.commonmark.node.Node
import org.commonmark.node.OrderedList
import org.commonmark.node.Paragraph
import org.commonmark.node.StrongEmphasis
import org.commonmark.node.Text
private const val TAG_URL = "url"
private const val TAG_IMAGE_URL = "imageUrl"
@Composable
fun MDDocument(document: Document) {
MDBlockChildren(document)
}
@Composable
fun MDHeading(heading: Heading, modifier: Modifier = Modifier) {
val style = when (heading.level) {
1 -> MaterialTheme.typography.headlineSmall
2 -> MaterialTheme.typography.headlineSmall.copy(fontSize = 20.sp)
3 -> MaterialTheme.typography.headlineSmall.copy(fontSize = 18.sp)
4 -> MaterialTheme.typography.headlineSmall.copy(fontSize = 16.sp)
5 -> MaterialTheme.typography.headlineSmall.copy(fontSize = 14.sp)
6 -> MaterialTheme.typography.headlineSmall.copy(fontSize = 14.sp)
else -> {
// Invalid header...
MDBlockChildren(heading)
return
}
}
val padding = if (heading.parent is Document) 8.dp else 0.dp
Box(modifier = modifier.padding(bottom = padding)) {
val text = buildAnnotatedString {
appendMarkdownChildren(heading, MaterialTheme.colorScheme)
}
MarkdownText(text, style)
}
}
@Composable
fun MDParagraph(paragraph: Paragraph, modifier: Modifier = Modifier) {
val padding = if (paragraph.parent is Document) 10.dp else 0.dp
Box(modifier = modifier.padding(bottom = padding)) {
val styledText = buildAnnotatedString {
pushStyle(MaterialTheme.typography.bodyMedium.toSpanStyle())
appendMarkdownChildren(paragraph, MaterialTheme.colorScheme)
pop()
}
MarkdownText(styledText, MaterialTheme.typography.bodyMedium)
}
}
@Composable
fun MDImage(image: Image, modifier: Modifier = Modifier) {
Box(modifier = modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Image(
painter = rememberAsyncImagePainter(
ImageRequest.Builder(LocalContext.current).data(data = image.destination)
.apply(block = fun ImageRequest.Builder.() {
size(Size.ORIGINAL)
}).build()
),
contentDescription = null,
)
}
}
@Composable
fun MDBulletList(bulletList: BulletList, modifier: Modifier = Modifier) {
val marker = bulletList.marker
MDListItems(bulletList, modifier = modifier) {
val text = buildAnnotatedString {
pushStyle(MaterialTheme.typography.bodyMedium.toSpanStyle())
append("$marker ")
appendMarkdownChildren(it, MaterialTheme.colorScheme)
pop()
}
MarkdownText(text, MaterialTheme.typography.bodyMedium, modifier)
}
}
@Composable
fun MDOrderedList(orderedList: OrderedList, modifier: Modifier = Modifier) {
var number = orderedList.markerStartNumber
val delimiter = orderedList.markerDelimiter
MDListItems(orderedList, modifier) {
val text = buildAnnotatedString {
pushStyle(MaterialTheme.typography.bodyMedium.toSpanStyle())
append("${number++}$delimiter ")
appendMarkdownChildren(it, MaterialTheme.colorScheme)
pop()
}
MarkdownText(text, MaterialTheme.typography.bodyMedium, modifier)
}
}
@Composable
fun MDListItems(
listBlock: ListBlock,
modifier: Modifier = Modifier,
item: @Composable (node: Node) -> Unit
) {
val bottom = if (listBlock.parent is Document) 8.dp else 0.dp
val start = if (listBlock.parent is Document) 0.dp else 8.dp
Column(modifier = modifier.padding(start = start, bottom = bottom)) {
var listItem = listBlock.firstChild
while (listItem != null) {
var child = listItem.firstChild
while (child != null) {
when (child) {
is BulletList -> MDBulletList(child, modifier)
is OrderedList -> MDOrderedList(child, modifier)
else -> item(child)
}
child = child.next
}
listItem = listItem.next
}
}
}
@Composable
fun MDBlockQuote(blockQuote: BlockQuote, modifier: Modifier = Modifier) {
val color = MaterialTheme.colorScheme.onBackground
Box(modifier = modifier
.drawBehind {
drawLine(
color = color,
strokeWidth = 2f,
start = Offset(12.dp.value, 0f),
end = Offset(12.dp.value, size.height)
)
}
.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)) {
val text = buildAnnotatedString {
pushStyle(
MaterialTheme.typography.bodyMedium.toSpanStyle()
.plus(SpanStyle(fontStyle = FontStyle.Italic))
)
appendMarkdownChildren(blockQuote, MaterialTheme.colorScheme)
pop()
}
Text(text, modifier)
}
}
@Composable
fun MDFencedCodeBlock(fencedCodeBlock: FencedCodeBlock, modifier: Modifier = Modifier) {
val padding = if (fencedCodeBlock.parent is Document) 8.dp else 0.dp
Box(modifier = modifier.padding(start = 8.dp, bottom = padding)) {
Text(
text = fencedCodeBlock.literal,
style = TextStyle(fontFamily = FontFamily.Monospace),
modifier = modifier
)
}
}
@Composable
fun MDBlockChildren(parent: Node) {
var child = parent.firstChild
while (child != null) {
when (child) {
is BlockQuote -> MDBlockQuote(child)
is Heading -> MDHeading(child)
is Paragraph -> MDParagraph(child)
is FencedCodeBlock -> MDFencedCodeBlock(child)
is Image -> MDImage(child)
is BulletList -> MDBulletList(child)
is OrderedList -> MDOrderedList(child)
}
child = child.next
}
}
fun AnnotatedString.Builder.appendMarkdownChildren(
parent: Node, colors: ColorScheme
) {
var child = parent.firstChild
while (child != null) {
when (child) {
is Paragraph -> appendMarkdownChildren(child, colors)
is Text -> append(child.literal)
is Image -> appendInlineContent(TAG_IMAGE_URL, child.destination)
is Emphasis -> {
pushStyle(SpanStyle(fontStyle = FontStyle.Italic))
appendMarkdownChildren(child, colors)
pop()
}
is StrongEmphasis -> {
pushStyle(SpanStyle(fontWeight = FontWeight.Bold))
appendMarkdownChildren(child, colors)
pop()
}
is Code -> {
pushStyle(TextStyle(fontFamily = FontFamily.Monospace).toSpanStyle())
append(child.literal)
pop()
}
is HardLineBreak -> {
append("\n")
}
is Link -> {
val underline = SpanStyle(colors.primary, textDecoration = TextDecoration.Underline)
pushStyle(underline)
pushStringAnnotation(TAG_URL, child.destination)
appendMarkdownChildren(child, colors)
pop()
pop()
}
}
child = child.next
}
}
@Composable
fun MarkdownText(text: AnnotatedString, style: TextStyle, modifier: Modifier = Modifier) {
val uriHandler = LocalUriHandler.current
val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
Text(text = text,
modifier.pointerInput(Unit) {
detectTapGestures { offset ->
layoutResult.value?.let { layoutResult ->
val position = layoutResult.getOffsetForPosition(offset)
text.getStringAnnotations(position, position)
.firstOrNull()
?.let { sa ->
if (sa.tag == TAG_URL) {
uriHandler.openUri(sa.item)
}
}
}
}
},
style = style,
inlineContent = mapOf(
TAG_IMAGE_URL to InlineTextContent(
Placeholder(style.fontSize, style.fontSize, PlaceholderVerticalAlign.Bottom)
) {
Image(
painter = rememberAsyncImagePainter(model = it),
contentDescription = null,
modifier = modifier,
alignment = Alignment.Center
)
}
),
onTextLayout = { layoutResult.value = it }
)
}

View file

@ -0,0 +1,72 @@
package com.hegocre.nextcloudpasswords.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF0061A4)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFD1E4FF)
val md_theme_light_onPrimaryContainer = Color(0xFF001D36)
val md_theme_light_secondary = Color(0xFF535F70)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFD7E3F7)
val md_theme_light_onSecondaryContainer = Color(0xFF101C2B)
val md_theme_light_tertiary = Color(0xFF006398)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFCDE5FF)
val md_theme_light_onTertiaryContainer = Color(0xFF001D32)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFDFCFF)
val md_theme_light_onBackground = Color(0xFF1A1C1E)
val md_theme_light_surface = Color(0xFFFDFCFF)
val md_theme_light_onSurface = Color(0xFF1A1C1E)
val md_theme_light_surfaceVariant = Color(0xFFDFE2EB)
val md_theme_light_onSurfaceVariant = Color(0xFF43474E)
val md_theme_light_outline = Color(0xFF73777F)
val md_theme_light_inverseOnSurface = Color(0xFFF1F0F4)
val md_theme_light_inverseSurface = Color(0xFF2F3033)
val md_theme_light_inversePrimary = Color(0xFF9ECAFF)
val md_theme_light_surfaceTint = Color(0xFF0061A4)
val md_theme_light_outlineVariant = Color(0xFFC3C7CF)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF9ECAFF)
val md_theme_dark_onPrimary = Color(0xFF003258)
val md_theme_dark_primaryContainer = Color(0xFF00497D)
val md_theme_dark_onPrimaryContainer = Color(0xFFD1E4FF)
val md_theme_dark_secondary = Color(0xFFBBC7DB)
val md_theme_dark_onSecondary = Color(0xFF253140)
val md_theme_dark_secondaryContainer = Color(0xFF3B4858)
val md_theme_dark_onSecondaryContainer = Color(0xFFD7E3F7)
val md_theme_dark_tertiary = Color(0xFF94CCFF)
val md_theme_dark_onTertiary = Color(0xFF003352)
val md_theme_dark_tertiaryContainer = Color(0xFF004B74)
val md_theme_dark_onTertiaryContainer = Color(0xFFCDE5FF)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1A1C1E)
val md_theme_dark_onBackground = Color(0xFFE2E2E6)
val md_theme_dark_surface = Color(0xFF1A1C1E)
val md_theme_dark_onSurface = Color(0xFFE2E2E6)
val md_theme_dark_surfaceVariant = Color(0xFF43474E)
val md_theme_dark_onSurfaceVariant = Color(0xFFC3C7CF)
val md_theme_dark_outline = Color(0xFF8D9199)
val md_theme_dark_inverseOnSurface = Color(0xFF1A1C1E)
val md_theme_dark_inverseSurface = Color(0xFFE2E2E6)
val md_theme_dark_inversePrimary = Color(0xFF0061A4)
val md_theme_dark_surfaceTint = Color(0xFF9ECAFF)
val md_theme_dark_outlineVariant = Color(0xFF43474E)
val md_theme_dark_scrim = Color(0xFF000000)
val Amber500 = Color(0xFFFFC107)
val Amber200 = Color(0xFFFFE082)
val Green500 = Color(0xFF4CAF50)
val Green200 = Color(0xFFA5D6A7)
val Red500 = Color(0xFFF44336)
val Red200 = Color(0xFFEF9A9A)

View file

@ -0,0 +1,7 @@
package com.hegocre.nextcloudpasswords.ui.theme
object ContentAlpha {
// Enable if needed // const val high = 0.87f
const val medium = 0.60f
// Enable if needed // const val disabled = 0.38f
}

View file

@ -0,0 +1,213 @@
package com.hegocre.nextcloudpasswords.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.LocalView
import androidx.core.graphics.toColorInt
import androidx.core.view.WindowCompat
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import com.materialkolor.dynamicColorScheme
private val defaultLightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val defaultDarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun NextcloudPasswordsTheme(
content: @Composable () -> Unit
) {
val isPreview = LocalInspectionMode.current
if (isPreview) {
MaterialTheme(
colorScheme = if (isSystemInDarkTheme()) defaultDarkColorScheme else defaultLightColorScheme,
typography = Typography,
content = content
)
} else {
val context = LocalContext.current
val preferencesManager = PreferencesManager.getInstance(context)
val appTheme by preferencesManager.getAppTheme().collectAsState(initial = NCPTheme.SYSTEM)
val useNextcloudInstanceColor by preferencesManager.getUseInstanceColor()
.collectAsState(initial = false)
val instanceColorString by preferencesManager.getInstanceColor()
.collectAsState(initial = "#745bca")
val instanceColor by remember {
derivedStateOf {
try {
Color(instanceColorString.toColorInt())
} catch (e: IllegalArgumentException) {
Color(0xFF745BCA)
}
}
}
val useSystemDynamicColor by preferencesManager.getUseSystemDynamicColor()
.collectAsState(initial = false)
val colorScheme = when {
useSystemDynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
when {
appTheme == NCPTheme.LIGHT -> dynamicLightColorScheme(context)
appTheme == NCPTheme.DARK -> dynamicDarkColorScheme(context)
appTheme == NCPTheme.AMOLED -> dynamicDarkColorScheme(context).copy(
background = Color.Black,
surface = Color.Black
)
isSystemInDarkTheme() -> dynamicDarkColorScheme(context)
else -> dynamicLightColorScheme(context)
}
}
useNextcloudInstanceColor -> {
when (appTheme) {
NCPTheme.LIGHT -> dynamicColorScheme(
instanceColor,
isDark = false,
isAmoled = false
)
NCPTheme.DARK -> dynamicColorScheme(instanceColor, isDark = true, isAmoled = false)
NCPTheme.AMOLED -> dynamicColorScheme(instanceColor, isDark = true, isAmoled = true)
else -> dynamicColorScheme(instanceColor, isSystemInDarkTheme(), false)
}
}
appTheme == NCPTheme.LIGHT -> defaultLightColorScheme
appTheme == NCPTheme.DARK -> defaultDarkColorScheme
appTheme == NCPTheme.AMOLED -> defaultDarkColorScheme.copy(
background = Color.Black,
surface = Color.Black
)
isSystemInDarkTheme() -> defaultDarkColorScheme
else -> defaultLightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
val insetsController = WindowCompat.getInsetsController(window, view)
insetsController.isAppearanceLightStatusBars = colorScheme.isLight()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
insetsController.isAppearanceLightNavigationBars = colorScheme.isLight()
}
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
}
fun ColorScheme.isLight() = this.background.luminance() > 0.5
val ColorScheme.favoriteColor: Color
get() {
return if (isLight()) Amber500 else Amber200
}
val ColorScheme.statusGood: Color
get() {
return if (isLight()) Green500 else Green200
}
val ColorScheme.statusWeak: Color
get() {
return if (isLight()) Amber500 else Amber200
}
val ColorScheme.statusBreached: Color
get() {
return if (isLight()) Red500 else Red200
}
object NCPTheme {
const val SYSTEM = "system_theme"
const val LIGHT = "light_theme"
const val DARK = "dark_theme"
const val AMOLED = "amoled_theme"
}

View file

@ -0,0 +1,28 @@
package com.hegocre.nextcloudpasswords.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)

View file

@ -0,0 +1,345 @@
package com.hegocre.nextcloudpasswords.ui.viewmodels
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.ColorStateList
import android.os.Build
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.hegocre.nextcloudpasswords.R
import com.hegocre.nextcloudpasswords.api.ApiController
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.api.exceptions.ClientDeauthorizedException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyInvalidException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengeMasterKeyNeededException
import com.hegocre.nextcloudpasswords.api.exceptions.PWDv1ChallengePasswordException
import com.hegocre.nextcloudpasswords.data.folder.DeletedFolder
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.folder.FolderController
import com.hegocre.nextcloudpasswords.data.folder.NewFolder
import com.hegocre.nextcloudpasswords.data.folder.UpdatedFolder
import com.hegocre.nextcloudpasswords.data.password.DeletedPassword
import com.hegocre.nextcloudpasswords.data.password.NewPassword
import com.hegocre.nextcloudpasswords.data.password.Password
import com.hegocre.nextcloudpasswords.data.password.PasswordController
import com.hegocre.nextcloudpasswords.data.password.UpdatedPassword
import com.hegocre.nextcloudpasswords.data.serversettings.ServerSettings
import com.hegocre.nextcloudpasswords.data.user.UserController
import com.hegocre.nextcloudpasswords.utils.AppLockHelper
import com.hegocre.nextcloudpasswords.utils.PreferencesManager
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.Credentials
import java.net.MalformedURLException
import java.net.URL
class PasswordsViewModel(application: Application) : AndroidViewModel(application) {
private val preferencesManager = PreferencesManager.getInstance(application)
private var masterPassword: MutableLiveData<String?> = MutableLiveData<String?>(null).also {
it.value = preferencesManager.getMasterPassword()
}
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing: StateFlow<Boolean>
get() = _isRefreshing.asStateFlow()
private val _isUpdating = MutableStateFlow(false)
val isUpdating: StateFlow<Boolean>
get() = _isUpdating.asStateFlow()
private val _needsMasterPassword = MutableStateFlow(false)
val needsMasterPassword: StateFlow<Boolean>
get() = _needsMasterPassword.asStateFlow()
private val _masterPasswordInvalid = MutableStateFlow(false)
val masterPasswordInvalid: StateFlow<Boolean>
get() = _masterPasswordInvalid.asStateFlow()
private val _clientDeauthorized = MutableLiveData(false)
val clientDeauthorized: LiveData<Boolean>
get() = _clientDeauthorized
private val apiController = ApiController.getInstance(application)
val sessionOpen
get() = apiController.sessionOpen
private val _showSessionOpenError = MutableStateFlow(false)
val showSessionOpenError: StateFlow<Boolean>
get() = _showSessionOpenError.asStateFlow()
val csEv1Keychain: LiveData<CSEv1Keychain?>
get() = apiController.csEv1Keychain
val serverSettings: LiveData<ServerSettings>
get() = apiController.serverSettings
val server
get() = UserController.getInstance(getApplication()).getServer()
val passwords: LiveData<List<Password>>
get() = PasswordController.getInstance(getApplication()).getPasswords()
val folders: LiveData<List<Folder>>
get() = FolderController.getInstance(getApplication()).getFolders()
var visiblePassword = mutableStateOf<Pair<Password, List<String>>?>(null)
private set
var visibleFolder = mutableStateOf<Folder?>(null)
private set
init {
val screenLockFilter = IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_OFF)
}
val screenOffReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent != null) {
val action = intent.action
if (screenLockFilter.matchAction(action)) {
AppLockHelper.getInstance(context).enableLock()
}
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
application.registerReceiver(
screenOffReceiver,
screenLockFilter,
Context.RECEIVER_EXPORTED
)
} else {
application.registerReceiver(screenOffReceiver, screenLockFilter)
}
if (!sessionOpen.value)
openSession(masterPassword.value)
}
private fun openSession(password: String?) {
viewModelScope.launch {
_isRefreshing.emit(true)
try {
if (apiController.openSession(password)) {
sync()
_showSessionOpenError.emit(true)
return@launch
}
_showSessionOpenError.emit(true)
} catch (ex: PWDv1ChallengeMasterKeyNeededException) {
_needsMasterPassword.emit(true)
} catch (ex: ClientDeauthorizedException) {
_clientDeauthorized.postValue(true)
} catch (ex: Exception) {
when (ex) {
is PWDv1ChallengeMasterKeyInvalidException, is PWDv1ChallengePasswordException -> {
_needsMasterPassword.emit(true)
_masterPasswordInvalid.emit(true)
masterPassword.postValue(null)
preferencesManager.setMasterPassword(null)
}
else -> {
_showSessionOpenError.emit(true)
ex.printStackTrace()
}
}
}
_isRefreshing.emit(false)
}
}
fun setMasterPassword(password: String, save: Boolean = false) {
openSession(password)
masterPassword.postValue(password)
viewModelScope.launch {
_needsMasterPassword.emit(false)
_masterPasswordInvalid.emit(false)
}
if (save)
preferencesManager.setMasterPassword(password)
}
fun sync() {
if (sessionOpen.value) {
viewModelScope.launch {
_isRefreshing.emit(true)
PasswordController.getInstance(getApplication()).syncPasswords()
FolderController.getInstance(getApplication()).syncFolders()
_isRefreshing.emit(false)
}
} else {
openSession(masterPassword.value)
}
}
fun setVisiblePassword(password: Password, folderPath: List<String>) {
visiblePassword.value = Pair(password, folderPath)
}
fun setVisibleFolder(folder: Folder?) {
visibleFolder.value = folder
}
fun createPassword(newPassword: NewPassword): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.createPassword(newPassword)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
fun updatePassword(updatedPassword: UpdatedPassword): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.updatePassword(updatedPassword)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
fun deletePassword(deletedPassword: DeletedPassword): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.deletePassword(deletedPassword)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
fun generatePassword(
strength: Int, includeDigits: Boolean, includeSymbols: Boolean
): Deferred<String?> {
return viewModelScope.async {
return@async apiController.generatePassword(strength, includeDigits, includeSymbols)
}
}
fun createFolder(newFolder: NewFolder): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.createFolder(newFolder)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
fun updateFolder(updatedFolder: UpdatedFolder): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.updateFolder(updatedFolder)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
fun deleteFolder(deletedFolder: DeletedFolder): Deferred<Boolean> {
return viewModelScope.async {
_isUpdating.value = true
if (!apiController.deleteFolder(deletedFolder)) {
_isUpdating.value = false
return@async false
}
sync()
_isUpdating.value = false
true
}
}
@Composable
fun getPainterForUrl(url: String): Painter {
val context = LocalContext.current
val domain = try {
URL(url).host
} catch (e: MalformedURLException) {
url
}
val (requestUrl, server) = apiController.getFaviconServiceRequest(domain)
return rememberAsyncImagePainter(
ImageRequest.Builder(context).apply {
data(requestUrl)
addHeader("OCS-APIRequest", "true")
addHeader("Authorization", Credentials.basic(server.username, server.password))
crossfade(true)
val lockDrawable = context.getDrawable(R.drawable.ic_lock)?.apply {
setTintList(
ColorStateList.valueOf(
MaterialTheme.colorScheme.primary.toArgb()
)
)
}
placeholder(lockDrawable)
fallback(lockDrawable)
error(lockDrawable)
}.build()
)
}
@Composable
fun getPainterForAvatar(): Painter {
val context = LocalContext.current
val (requestUrl, server) = apiController.getAvatarServiceRequest()
return rememberAsyncImagePainter(
model = ImageRequest.Builder(context).apply {
data(requestUrl)
addHeader("OCS-APIRequest", "true")
addHeader("Authorization", Credentials.basic(server.username, server.password))
crossfade(true)
val accountDrawable = context.getDrawable(R.drawable.ic_account_circle)?.apply {
setTintList(
ColorStateList.valueOf(
MaterialTheme.colorScheme.primary.toArgb()
)
)
}
placeholder(accountDrawable)
fallback(accountDrawable)
error(accountDrawable)
}.build()
)
}
override fun onCleared() {
apiController
super.onCleared()
}
}

View file

@ -0,0 +1,53 @@
package com.hegocre.nextcloudpasswords.utils
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class AppLockHelper private constructor(context: Context) {
private val preferencesManager = PreferencesManager.getInstance(context)
private var _isLocked = MutableStateFlow(true)
val isLocked: StateFlow<Boolean>
get() = _isLocked.asStateFlow()
fun checkPasscode(passcode: String): Deferred<Boolean> {
return CoroutineScope(Dispatchers.Default).async {
val correctPasscode = preferencesManager.getAppLockPasscode() ?: "0000"
passcode == correctPasscode
}
}
fun disableLock() {
CoroutineScope(Dispatchers.Default).launch {
_isLocked.emit(false)
}
}
fun enableLock() {
CoroutineScope(Dispatchers.Default).launch {
_isLocked.emit(true)
}
}
companion object {
private var instance: AppLockHelper? = null
fun getInstance(context: Context): AppLockHelper {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = AppLockHelper(context)
}
instance = tempInstance
return tempInstance
}
}
}
}

View file

@ -0,0 +1,61 @@
package com.hegocre.nextcloudpasswords.utils
import android.content.Context
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
// 1
private val biometricsIgnoredErrors = listOf(
BiometricPrompt.ERROR_NEGATIVE_BUTTON,
BiometricPrompt.ERROR_CANCELED,
BiometricPrompt.ERROR_USER_CANCELED,
BiometricPrompt.ERROR_NO_BIOMETRICS
)
fun showBiometricPrompt(
context: Context,
title: String,
description: String,
onBiometricUnlock: () -> Unit,
onBiometricFailed: (() -> Unit)? = null,
onBiometricError: (() -> Unit)? = null
) {
// 2
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.setDescription(description)
.setAllowedAuthenticators(BIOMETRIC_STRONG)
.setNegativeButtonText(context.getString(android.R.string.cancel))
.build()
// 3
val biometricPrompt = BiometricPrompt(
context as FragmentActivity,
object : BiometricPrompt.AuthenticationCallback() {
// 4
override fun onAuthenticationError(
errorCode: Int,
errString: CharSequence
) {
if (errorCode !in biometricsIgnoredErrors) {
onBiometricError?.invoke()
}
}
// 5
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult
) {
onBiometricUnlock()
}
// 6
override fun onAuthenticationFailed() {
onBiometricFailed?.invoke()
}
}
)
// 7
biometricPrompt.authenticate(promptInfo)
}

View file

@ -0,0 +1,19 @@
package com.hegocre.nextcloudpasswords.utils
import android.content.ClipData
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.PersistableBundle
fun Context.copyToClipboard(value: String, isSensitive: Boolean = false) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("text/plain", value)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val extras = PersistableBundle()
extras.putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, isSensitive)
clip.description.extras = extras
}
clipboard.setPrimaryClip(clip)
}

View file

@ -0,0 +1,91 @@
package com.hegocre.nextcloudpasswords.utils
import com.goterl.lazysodium.interfaces.SecretBox
import com.goterl.lazysodium.utils.Key
import com.hegocre.nextcloudpasswords.api.encryption.CSEv1Keychain
import com.hegocre.nextcloudpasswords.api.exceptions.SodiumDecryptionException
import com.hegocre.nextcloudpasswords.data.folder.Folder
import com.hegocre.nextcloudpasswords.data.password.Password
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.security.MessageDigest
suspend fun List<Password>.decryptPasswords(csEv1Keychain: CSEv1Keychain? = null): List<Password> =
withContext(Dispatchers.Default) {
val decryptedList: MutableList<Password> = mutableListOf()
forEach { password ->
//Decrypt password
val decryptedPassword = password.decrypt(csEv1Keychain)
if (decryptedPassword != null)
decryptedList.add(decryptedPassword)
}
decryptedList.toList()
}
suspend fun List<Folder>.decryptFolders(csEv1Keychain: CSEv1Keychain? = null): List<Folder> =
withContext(Dispatchers.Default) {
val decryptedList: MutableList<Folder> = mutableListOf()
forEach { folder ->
//Decrypt password
val decryptedFolder = folder.decrypt(csEv1Keychain)
if (decryptedFolder != null)
decryptedList.add(decryptedFolder)
}
decryptedList.toList()
}
/**
* Decrypt and encrypted value using the provided key id from the keychain.
*
* @param cseKey The id of the key used to encrypt and decrypt the value.
* @param csEv1Keychain The keychain containing the key.
* @return The decrypted value.
*/
fun String.decryptValue(cseKey: String, csEv1Keychain: CSEv1Keychain): String {
if (this.isEmpty() || cseKey.isEmpty()) return this
val sodium = LazySodiumUtils.getSodium()
val value = sodium.sodiumHex2Bin(this)
val nonce = value.sliceArray(0 until SecretBox.NONCEBYTES)
val cipher = value.sliceArray(SecretBox.NONCEBYTES until value.size)
val decryptionKey = sodium.sodiumHex2Bin(csEv1Keychain.keys[cseKey]!!)
val message = ByteArray(cipher.size - SecretBox.MACBYTES)
if (!sodium.cryptoSecretBoxOpenEasy(
message,
cipher,
cipher.size.toLong(),
nonce,
decryptionKey
)
) throw SodiumDecryptionException("Could not decrypt value")
return message.toString(Charsets.UTF_8)
}
fun String.encryptValue(cseKey: String, csEv1Keychain: CSEv1Keychain): String {
if (this.isEmpty() || cseKey.isEmpty()) return this
val sodium = LazySodiumUtils.getSodium()
val nonce = sodium.randomBytesBuf(SecretBox.NONCEBYTES)
val encryptionKey = Key.fromHexString(csEv1Keychain.keys[cseKey]!!)
val encryptedContent = sodium.cryptoSecretBoxEasy(this, nonce, encryptionKey)
return sodium.sodiumBin2Hex(nonce) + encryptedContent
}
fun String.sha1Hash(): String {
val digest = MessageDigest.getInstance("SHA-1")
val result = digest.digest(this.toByteArray())
val sb = StringBuilder()
for (b in result) {
sb.append(String.format("%02x", b))
}
return sb.toString()
}

View file

@ -0,0 +1,12 @@
package com.hegocre.nextcloudpasswords.utils
object Error {
const val API_TIMEOUT = 10000
const val API_NO_CSE = 10001
const val API_BAD_RESPONSE = 10002
const val API_NO_SESSION = 10003
const val SSL_HANDSHAKE_EXCEPTION = 20000
const val UNKNOWN = -1
}

View file

@ -0,0 +1,33 @@
package com.hegocre.nextcloudpasswords.utils
import com.goterl.lazysodium.LazySodiumAndroid
import com.goterl.lazysodium.SodiumAndroid
/**
* Singleton class used to provide the [LazySodiumAndroid] instance. This is used to avoid creating new instances
* and potentially crashing the application.
*
*/
class LazySodiumUtils private constructor() {
companion object {
var instance: LazySodiumAndroid? = null
/**
* Get the [LazySodiumAndroid] instance, and create one if not present.
*
* @return A LazySodium instance
*/
fun getSodium(): LazySodiumAndroid {
synchronized(this) {
var tempInstance = instance
if (tempInstance == null) {
tempInstance = LazySodiumAndroid(SodiumAndroid())
instance = tempInstance
}
return tempInstance
}
}
}
}

View file

@ -0,0 +1,42 @@
package com.hegocre.nextcloudpasswords.utils
import com.hegocre.nextcloudpasswords.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
class LogHelper private constructor() {
private val _appLog = StringBuilder("")
val appLog: String
get() = _appLog.toString()
init {
if (BuildConfig.DEBUG) {
CoroutineScope(Dispatchers.IO).launch {
Runtime.getRuntime().exec("logcat -c")
Runtime.getRuntime().exec("logcat")
.inputStream
.bufferedReader()
.useLines { lines ->
lines.forEach { line ->
ensureActive()
_appLog.append("$line\n")
}
}
}
}
}
companion object {
private var instance: LogHelper? = null
fun getInstance(): LogHelper {
synchronized(this) {
if (instance == null) instance = LogHelper()
return instance as LogHelper
}
}
}
}

View file

@ -0,0 +1,201 @@
package com.hegocre.nextcloudpasswords.utils
import android.annotation.SuppressLint
import okhttp3.Credentials
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
/**
* Class to manage the [OkHttpRequest] requests, and make them using always the same client, as suggested
* [here](https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/#okhttpclients-should-be-shared).
*
*/
class OkHttpRequest private constructor() {
var allowInsecureRequests = false
private val secureClient = OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
private val insecureClient: OkHttpClient
val client: OkHttpClient
get() = if (allowInsecureRequests) insecureClient else secureClient
init {
val insecureTrustManager = @SuppressLint("CustomX509TrustManager")
object : X509TrustManager {
@SuppressLint("TrustAllX509TrustManager")
override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {
}
@SuppressLint("TrustAllX509TrustManager")
override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, arrayOf(insecureTrustManager), java.security.SecureRandom())
insecureClient = OkHttpClient.Builder()
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.sslSocketFactory(sslContext.socketFactory, insecureTrustManager)
.hostnameVerifier { _, _ -> true }
.build()
}
@Throws(
MalformedURLException::class,
IllegalArgumentException::class,
IOException::class,
IllegalStateException::class
)
fun get(
sUrl: String, sessionCode: String? = null,
username: String? = null, password: String? = null
): Response {
val url = URL(sUrl)
val requestBuilder = Request.Builder()
.url(url)
.header("OCS-APIRequest", "true")
if (username != null && password != null) {
requestBuilder.addHeader("Authorization", Credentials.basic(username, password))
}
if (sessionCode != null) {
requestBuilder.addHeader("x-api-session", sessionCode)
}
val request = requestBuilder.build()
return client.newCall(request).execute()
}
@Throws(
MalformedURLException::class,
IllegalArgumentException::class,
IOException::class,
IllegalStateException::class
)
fun post(
sUrl: String, sessionCode: String? = null,
body: String, mediaType: MediaType?,
username: String? = null, password: String? = null
): Response {
val formBody = body.toRequestBody(mediaType)
val url = URL(sUrl)
val requestBuilder = Request.Builder()
.url(url)
.header("OCS-APIRequest", "true")
.post(formBody)
if (username != null && password != null) {
requestBuilder.addHeader("Authorization", Credentials.basic(username, password))
}
if (sessionCode != null) {
requestBuilder.addHeader("x-api-session", sessionCode)
}
val request = requestBuilder.build()
return client.newCall(request).execute()
}
@Throws(
MalformedURLException::class,
IllegalArgumentException::class,
IOException::class,
IllegalStateException::class
)
fun patch(
sUrl: String, sessionCode: String? = null,
body: String, mediaType: MediaType?,
username: String? = null, password: String? = null
): Response {
val formBody = body.toRequestBody(mediaType)
val url = URL(sUrl)
val requestBuilder = Request.Builder()
.url(url)
.header("OCS-APIRequest", "true")
.patch(formBody)
if (username != null && password != null) {
requestBuilder.addHeader("Authorization", Credentials.basic(username, password))
}
if (sessionCode != null) {
requestBuilder.addHeader("x-api-session", sessionCode)
}
val request = requestBuilder.build()
return client.newCall(request).execute()
}
@Throws(
MalformedURLException::class,
IllegalArgumentException::class,
IOException::class,
IllegalStateException::class
)
fun delete(
sUrl: String, sessionCode: String? = null,
body: String, mediaType: MediaType?,
username: String? = null, password: String? = null
): Response {
val formBody = body.toRequestBody(mediaType)
val url = URL(sUrl)
val requestBuilder = Request.Builder()
.url(url)
.header("OCS-APIRequest", "true")
.delete(formBody)
if (username != null && password != null) {
requestBuilder.addHeader("Authorization", Credentials.basic(username, password))
}
if (sessionCode != null) {
requestBuilder.addHeader("x-api-session", sessionCode)
}
val request = requestBuilder.build()
return client.newCall(request).execute()
}
companion object {
private var instance: OkHttpRequest? = null
val JSON = "application/json; charset=utf-8".toMediaTypeOrNull()
fun getInstance(): OkHttpRequest {
synchronized(this) {
if (instance == null) instance = OkHttpRequest()
return instance as OkHttpRequest
}
}
}
}

View file

@ -0,0 +1,193 @@
package com.hegocre.nextcloudpasswords.utils
import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.hegocre.nextcloudpasswords.data.password.RequestedPassword
import com.hegocre.nextcloudpasswords.data.serversettings.ServerSettings
import com.hegocre.nextcloudpasswords.ui.NCPScreen
import com.hegocre.nextcloudpasswords.ui.theme.NCPTheme
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.IOException
class PreferencesManager private constructor(context: Context) {
private val Context._sharedPreferences by preferencesDataStore(name = "preferences")
private val sharedPreferences = context._sharedPreferences
private val _encryptedSharedPrefs = context.let {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
EncryptedSharedPreferences.create(
"${it.packageName}_encrypted_preferences",
masterKeyAlias,
it,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
suspend fun clear(): Boolean {
sharedPreferences.edit {
it.clear()
}
return _encryptedSharedPrefs.edit().clear().commit()
}
fun getHasAppLock(): Flow<Boolean> = getPreference(PreferenceKeys.HAS_APP_LOCK, false)
suspend fun setHasAppLock(value: Boolean) = setPreference(PreferenceKeys.HAS_APP_LOCK, value)
fun getHasBiometricAppLock(): Flow<Boolean> =
getPreference(PreferenceKeys.HAS_BIOMETRIC_APP_LOCK, false)
suspend fun setHasBiometricAppLock(value: Boolean) =
setPreference(PreferenceKeys.HAS_BIOMETRIC_APP_LOCK, value)
fun getAppLockPasscode(): String? = _encryptedSharedPrefs.getString("APP_LOCK_PASSCODE", null)
fun setAppLockPasscode(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("APP_LOCK_PASSCODE", value).commit()
fun getLoggedInServer(): String? = _encryptedSharedPrefs.getString("LOGGED_IN_SERVER", null)
fun setLoggedInServer(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("LOGGED_IN_SERVER", value).commit()
fun getLoggedInUser(): String? = _encryptedSharedPrefs.getString("LOGGED_IN_USER", null)
fun setLoggedInUser(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("LOGGED_IN_USER", value).commit()
fun getLoggedInPassword(): String? = _encryptedSharedPrefs.getString("LOGGED_IN_PASSWORD", null)
fun setLoggedInPassword(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("LOGGED_IN_PASSWORD", value).commit()
fun getMasterPassword(): String? = _encryptedSharedPrefs.getString("MASTER_KEY", null)
fun setMasterPassword(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("MASTER_KEY", value).commit()
fun getCSEv1Keychain(): String? = _encryptedSharedPrefs.getString("CSE_V1_KEYCHAIN", null)
fun setCSEv1Keychain(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("CSE_V1_KEYCHAIN", value).commit()
fun getServerSettings(): ServerSettings = try {
_encryptedSharedPrefs.getString("SERVER_SETTINGS", null)?.let {
Json.decodeFromString(it)
} ?: ServerSettings()
} catch (e: Exception) {
ServerSettings()
}
fun setServerSettings(value: ServerSettings?): Boolean =
_encryptedSharedPrefs.edit().putString("SERVER_SETTINGS", value?.let {
Json.encodeToString(it)
}).commit()
fun getSkipCertificateValidation(): Boolean =
_encryptedSharedPrefs.getBoolean("SKIP_CERTIFICATE_VALIDATION", false)
fun setSkipCertificateValidation(value: Boolean): Boolean =
_encryptedSharedPrefs.edit().putBoolean("SKIP_CERTIFICATE_VALIDATION", value).commit()
fun getUseInlineAutofill(): Boolean =
_encryptedSharedPrefs.getBoolean("USE_INLINE_AUTOFILL", false)
fun setUseInlineAutofill(value: Boolean): Boolean =
_encryptedSharedPrefs.edit().putBoolean("USE_INLINE_AUTOFILL", value).commit()
fun getPasswordGenerationOptions(): String? =
_encryptedSharedPrefs.getString(
"PASSWORD_GENERATION_OPTIONS",
"${RequestedPassword.STRENGTH_STANDARD};true;true"
)
fun setPasswordGenerationOptions(value: String?): Boolean =
_encryptedSharedPrefs.edit().putString("PASSWORD_GENERATION_OPTIONS", value).commit()
fun getShowIcons(): Flow<Boolean> = getPreference(PreferenceKeys.SHOW_ICONS, false)
suspend fun setShowIcons(value: Boolean) = setPreference(PreferenceKeys.SHOW_ICONS, value)
fun getStartScreen(): Flow<String> =
getPreference(PreferenceKeys.START_SCREEN, NCPScreen.Passwords.name)
suspend fun setStartScreen(value: String) = setPreference(PreferenceKeys.START_SCREEN, value)
fun getAppTheme(): Flow<String> = getPreference(PreferenceKeys.APP_THEME, NCPTheme.SYSTEM)
suspend fun setAppTheme(value: String) = setPreference(PreferenceKeys.APP_THEME, value)
fun getInstanceColor(): Flow<String> = getPreference(PreferenceKeys.INSTANCE_COLOR, "#745bca")
suspend fun setInstanceColor(value: String) =
setPreference(PreferenceKeys.INSTANCE_COLOR, value)
fun getUseInstanceColor(): Flow<Boolean> =
getPreference(PreferenceKeys.USE_NEXTCLOUD_INSTANCE_COLOR, false)
suspend fun setUseInstanceColor(value: Boolean) =
setPreference(PreferenceKeys.USE_NEXTCLOUD_INSTANCE_COLOR, value)
fun getUseSystemDynamicColor(): Flow<Boolean> =
getPreference(PreferenceKeys.USE_SYSTEM_DYNAMIC_COLOR, false)
suspend fun setUseSystemDynamicColor(value: Boolean) =
setPreference(PreferenceKeys.USE_SYSTEM_DYNAMIC_COLOR, value)
fun getSearchByUsername(): Flow<Boolean> =
getPreference(PreferenceKeys.SEARCH_BY_USERNAME, true)
suspend fun setSearchByUsername(value: Boolean) =
setPreference(PreferenceKeys.SEARCH_BY_USERNAME, value)
fun getUseStrictUrlMatching(): Flow<Boolean> =
getPreference(PreferenceKeys.USE_STRICT_URL_MATCHING, true)
suspend fun setUseStrictUrlMatching(value: Boolean) =
setPreference(PreferenceKeys.USE_STRICT_URL_MATCHING, value)
private fun <T> getPreference(key: Preferences.Key<T>, defaultValue: T): Flow<T> =
sharedPreferences.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
preferences[key] ?: defaultValue
}
private suspend fun <T> setPreference(key: Preferences.Key<T>, value: T) {
sharedPreferences.edit { preferences ->
preferences[key] = value
}
}
companion object {
private var instance: PreferencesManager? = null
fun getInstance(context: Context): PreferencesManager {
synchronized(this) {
if (instance == null) instance = PreferencesManager(context)
return instance as PreferencesManager
}
}
private object PreferenceKeys {
val SHOW_ICONS = booleanPreferencesKey("SHOW_ICONS")
val START_SCREEN = stringPreferencesKey("START_SCREEN")
val HAS_APP_LOCK = booleanPreferencesKey("HAS_APP_LOCK")
val HAS_BIOMETRIC_APP_LOCK = booleanPreferencesKey("HAS_BIOMETRIC_APP_LOCK")
val APP_THEME = stringPreferencesKey("APP_THEME")
val USE_NEXTCLOUD_INSTANCE_COLOR = booleanPreferencesKey("USE_NEXTCLOUD_INSTANCE_COLOR")
val USE_SYSTEM_DYNAMIC_COLOR = booleanPreferencesKey("USE_SYSTEM_DYNAMIC_COLOR")
val INSTANCE_COLOR = stringPreferencesKey("INSTANCE_COLOR")
val SEARCH_BY_USERNAME = booleanPreferencesKey("SEARCH_BY_USERNAME")
val USE_STRICT_URL_MATCHING = booleanPreferencesKey("USE_STRICT_URL_MATCHING")
}
}
}

View file

@ -0,0 +1,6 @@
package com.hegocre.nextcloudpasswords.utils
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val code: Int) : Result<Nothing>()
}

View file

@ -0,0 +1,55 @@
package com.hegocre.nextcloudpasswords.utils
import android.webkit.URLUtil
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.AutofillNode
import androidx.compose.ui.autofill.AutofillType
import androidx.compose.ui.composed
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalAutofill
import androidx.compose.ui.platform.LocalAutofillTree
fun String.isValidEmail(): Boolean {
return if (this.isBlank()) {
true
} else {
android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
}
fun String.isValidURL(): Boolean {
return if (this.isBlank()) {
true
} else {
URLUtil.isValidUrl(this) || URLUtil.isValidUrl("http://${this}")
}
}
@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.autofill(
onFill: (String) -> Unit,
autofillTypes: List<AutofillType>
) = composed {
val autofill = LocalAutofill.current
val autofillNode = AutofillNode(
onFill = onFill, autofillTypes = autofillTypes
)
LocalAutofillTree.current += autofillNode
this
.onGloballyPositioned {
autofillNode.boundingBox = it.boundsInWindow()
}
.onFocusChanged { focusState ->
autofill?.run {
if (focusState.isFocused) {
requestAutofillForNode(autofillNode)
} else {
cancelAutofillForNode(autofillNode)
}
}
}
}

Some files were not shown because too many files have changed in this diff Show more